|
| 1 | +# Tencent is pleased to support the open source community by making tRPC-Agent-Python available. |
| 2 | +# |
| 3 | +# Copyright (C) 2026 Tencent. All rights reserved. |
| 4 | +# |
| 5 | +# tRPC-Agent-Python is licensed under Apache-2.0. |
| 6 | +"""Live agent bridge for the eval_optimize_loop example. |
| 7 | +
|
| 8 | +The optimizer contract is intentionally small: ``call_agent`` is an async |
| 9 | +function that accepts one user query and returns the final response text. This |
| 10 | +module re-reads the prompt file on every invocation so prompt candidates written |
| 11 | +by AgentOptimizer take effect immediately. |
| 12 | +
|
| 13 | +The public bridge in this file mirrors the SDK docs: |
| 14 | +
|
| 15 | +* ``create_agent`` builds a fresh ``LlmAgent`` from the current prompt file. |
| 16 | +* ``run_agent`` drives that agent through ``Runner`` and ``InMemorySessionService``. |
| 17 | +* ``make_call_agent`` returns the exact async callable required by |
| 18 | + ``AgentOptimizer.optimize`` when a ``TargetPrompt`` is registered. |
| 19 | +""" |
| 20 | + |
| 21 | +from __future__ import annotations |
| 22 | + |
| 23 | +import asyncio |
| 24 | +import logging |
| 25 | +import os |
| 26 | +import random |
| 27 | +import uuid |
| 28 | +from pathlib import Path |
| 29 | +from typing import Any |
| 30 | +from typing import Awaitable |
| 31 | +from typing import Callable |
| 32 | + |
| 33 | +from trpc_agent_sdk.agents import LlmAgent |
| 34 | +from trpc_agent_sdk.models import OpenAIModel |
| 35 | +from trpc_agent_sdk.runners import Runner |
| 36 | +from trpc_agent_sdk.sessions import InMemorySessionService |
| 37 | +from trpc_agent_sdk.tools import FunctionTool |
| 38 | +from trpc_agent_sdk.types import Content |
| 39 | +from trpc_agent_sdk.types import Part |
| 40 | + |
| 41 | + |
| 42 | +APP_NAME = "eval_optimize_loop" |
| 43 | +LOGGER = logging.getLogger("eval_optimize_loop.agent") |
| 44 | + |
| 45 | +# Live-call resilience knobs. A single flaky network call must not abort the |
| 46 | +# whole pipeline after real money was already spent on earlier evaluations. |
| 47 | +CALL_TIMEOUT_SECONDS = float(os.getenv("EVAL_OPT_CALL_TIMEOUT", "120")) |
| 48 | +CALL_MAX_ATTEMPTS = int(os.getenv("EVAL_OPT_CALL_ATTEMPTS", "3")) |
| 49 | +CALL_BACKOFF_BASE_SECONDS = float(os.getenv("EVAL_OPT_CALL_BACKOFF", "1.0")) |
| 50 | + |
| 51 | + |
| 52 | +def is_retryable(exc: BaseException) -> bool: |
| 53 | + """Decide whether a failed live call is worth retrying. |
| 54 | +
|
| 55 | + Connection problems and timeouts are always retryable. Provider SDK |
| 56 | + exception classes are not imported here (the example must stay usable |
| 57 | + without them), so rate-limit style errors are matched by type name. |
| 58 | + """ |
| 59 | + if isinstance(exc, (asyncio.TimeoutError, ConnectionError, OSError)): |
| 60 | + return True |
| 61 | + name = type(exc).__name__.lower() |
| 62 | + return "ratelimit" in name or "timeout" in name or "connection" in name |
| 63 | + |
| 64 | + |
| 65 | +def lookup_order(order_id: str) -> str: |
| 66 | + """FunctionTool body used by the live ``LlmAgent`` example.""" |
| 67 | + data = { |
| 68 | + "A100": "Order A100 is in transit and arrives on Friday.", |
| 69 | + "A200": "Order A200 is delivered.", |
| 70 | + } |
| 71 | + return data.get(order_id, f"No order record found for {order_id}.") |
| 72 | + |
| 73 | + |
| 74 | +def search_policy(topic: str) -> str: |
| 75 | + """FunctionTool body for policy and warranty lookup examples.""" |
| 76 | + topic_lower = topic.lower() |
| 77 | + if "damaged" in topic_lower or "refund" in topic_lower: |
| 78 | + return "Damaged items are eligible for a full refund within 30 days." |
| 79 | + if "model z" in topic_lower or "warranty" in topic_lower: |
| 80 | + return "Model Z has a 24-month warranty." |
| 81 | + return "No matching policy snippet was found." |
| 82 | + |
| 83 | + |
| 84 | +def get_model_config() -> tuple[str, str, str]: |
| 85 | + """Read live model credentials consumed by ``OpenAIModel``.""" |
| 86 | + api_key = os.getenv("TRPC_AGENT_API_KEY", "") |
| 87 | + base_url = os.getenv("TRPC_AGENT_BASE_URL", "") |
| 88 | + model_name = os.getenv("TRPC_AGENT_MODEL_NAME", "") |
| 89 | + if not api_key or not base_url or not model_name: |
| 90 | + raise ValueError( |
| 91 | + "Live mode requires TRPC_AGENT_API_KEY, TRPC_AGENT_BASE_URL, and " |
| 92 | + "TRPC_AGENT_MODEL_NAME. Use --mode fake for the no-key path." |
| 93 | + ) |
| 94 | + return api_key, base_url, model_name |
| 95 | + |
| 96 | + |
| 97 | +def create_agent(prompt_path: Path) -> LlmAgent: |
| 98 | + """Create a fresh ``LlmAgent`` from the current prompt file. |
| 99 | +
|
| 100 | + Re-reading here is the critical TargetPrompt contract: when |
| 101 | + ``AgentOptimizer`` writes a candidate prompt, the next call immediately uses |
| 102 | + that candidate without restarting the process. |
| 103 | + """ |
| 104 | + api_key, base_url, model_name = get_model_config() |
| 105 | + instruction = Path(prompt_path).read_text(encoding="utf-8").strip() |
| 106 | + return LlmAgent( |
| 107 | + name="support_assistant", |
| 108 | + description="A support assistant whose system prompt is under optimization.", |
| 109 | + model=OpenAIModel(model_name=model_name, api_key=api_key, base_url=base_url), |
| 110 | + instruction=instruction, |
| 111 | + tools=[FunctionTool(lookup_order), FunctionTool(search_policy)], |
| 112 | + ) |
| 113 | + |
| 114 | + |
| 115 | +async def run_agent_once(query: str, prompt_path: Path) -> dict[str, Any]: |
| 116 | + """Run the live agent once and collect text, tool calls, and token usage. |
| 117 | +
|
| 118 | + ``AgentOptimizer.optimize`` only needs final response text, but the outer |
| 119 | + issue-level report also wants key trajectory information and per-call token |
| 120 | + counts for the cost audit. This richer helper supports all of them. |
| 121 | + """ |
| 122 | + agent = create_agent(prompt_path) |
| 123 | + session_service = InMemorySessionService() |
| 124 | + runner = Runner(app_name=APP_NAME, agent=agent, session_service=session_service) |
| 125 | + session_id = str(uuid.uuid4()) |
| 126 | + user_id = "optimizer" |
| 127 | + await session_service.create_session( |
| 128 | + app_name=APP_NAME, |
| 129 | + user_id=user_id, |
| 130 | + session_id=session_id, |
| 131 | + state={}, |
| 132 | + ) |
| 133 | + message = Content(role="user", parts=[Part.from_text(text=query)]) |
| 134 | + final_text = "" |
| 135 | + tools: list[dict[str, Any]] = [] |
| 136 | + tokens = 0 |
| 137 | + async for event in runner.run_async( |
| 138 | + user_id=user_id, |
| 139 | + session_id=session_id, |
| 140 | + new_message=message, |
| 141 | + ): |
| 142 | + usage = getattr(event, "usage_metadata", None) |
| 143 | + if usage is not None: |
| 144 | + tokens += getattr(usage, "total_token_count", None) or 0 |
| 145 | + if not event.content or not event.content.parts: |
| 146 | + continue |
| 147 | + for part in event.content.parts: |
| 148 | + function_call = getattr(part, "function_call", None) |
| 149 | + if function_call is not None: |
| 150 | + tools.append( |
| 151 | + { |
| 152 | + "name": getattr(function_call, "name", None), |
| 153 | + "args": dict(getattr(function_call, "args", {}) or {}), |
| 154 | + } |
| 155 | + ) |
| 156 | + if event.is_final_response(): |
| 157 | + for part in event.content.parts: |
| 158 | + if getattr(part, "text", None) and not getattr(part, "thought", False): |
| 159 | + final_text += part.text |
| 160 | + return {"text": final_text.strip(), "tools": tools, "tokens": tokens} |
| 161 | + |
| 162 | + |
| 163 | +async def run_agent(query: str, prompt_path: Path) -> dict[str, Any]: |
| 164 | + """Run the live agent with timeout plus exponential-backoff retry. |
| 165 | +
|
| 166 | + Each attempt builds a fresh agent and session, so retrying is idempotent. |
| 167 | + Non-retryable errors (see ``is_retryable``) propagate immediately. |
| 168 | + """ |
| 169 | + for attempt in range(1, CALL_MAX_ATTEMPTS + 1): |
| 170 | + try: |
| 171 | + return await asyncio.wait_for( |
| 172 | + run_agent_once(query=query, prompt_path=prompt_path), |
| 173 | + timeout=CALL_TIMEOUT_SECONDS, |
| 174 | + ) |
| 175 | + except Exception as exc: |
| 176 | + if attempt == CALL_MAX_ATTEMPTS or not is_retryable(exc): |
| 177 | + raise |
| 178 | + delay = CALL_BACKOFF_BASE_SECONDS * 2 ** (attempt - 1) + random.uniform(0, 0.5) |
| 179 | + LOGGER.warning( |
| 180 | + "live agent call failed (%s: %s), retry %d/%d in %.1fs", |
| 181 | + type(exc).__name__, |
| 182 | + str(exc)[:200], |
| 183 | + attempt, |
| 184 | + CALL_MAX_ATTEMPTS - 1, |
| 185 | + delay, |
| 186 | + ) |
| 187 | + await asyncio.sleep(delay) |
| 188 | + raise RuntimeError("unreachable: retry loop exited without returning or raising") |
| 189 | + |
| 190 | + |
| 191 | +def make_call_agent(prompt_path: Path) -> Callable[[str], Awaitable[str]]: |
| 192 | + """Return the fixed async ``(query: str) -> str`` bridge required by GEPA.""" |
| 193 | + |
| 194 | + async def call_agent(query: str) -> str: |
| 195 | + return (await run_agent(query=query, prompt_path=prompt_path))["text"] |
| 196 | + |
| 197 | + return call_agent |
0 commit comments