Coverage for app / inference / engines / agent.py: 88%
69 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""
2AgentEngine — single agent with optional tools and knowledge bases.
4Handles ExecuteRequest(type="agent"). Builds a single-node LangGraph
5(GATE → WORKER → SYNTHESIS) and delegates batch/streaming to GraphBasedEngine.
6"""
8from __future__ import annotations
10from typing import Any
12from app.inference.context import InferenceContext
13from app.inference.engines.graph_based import GraphBasedEngine
14from app import prompts
15from app.models.spec import AgentConfig
16from app.tools.web.search import DEFAULT_MAX_CALLS, DEFAULT_MAX_RESULTS
18_WEB_DEFAULTS = {"max_results": DEFAULT_MAX_RESULTS, "max_calls": DEFAULT_MAX_CALLS}
21class AgentEngine(GraphBasedEngine):
22 """
23 Executes a single agent through the unified GATE → WORKER → SYNTHESIS graph.
24 Supports both batch (infer) and full streaming (infer_stream) paths.
25 """
27 # The single-node graph built in _build_builder always names its node "agent".
28 _default_end_node = "agent"
30 def _build_builder(
31 self, ctx: InferenceContext
32 ) -> tuple[Any, list[dict], dict[str, Any]]:
33 from app.agents import effort as effort_registry
34 from app.agents.factory import AgentFactory, SimpleWorkerAgent
35 from app.agents.fixtures import apply_to_tools as apply_fixtures
36 from app.agents.graph import OUTPUT_FORMAT_KEY, AgentGraphBuilder
37 from app.inference.output_shape import AnswerShape
38 from app.services.llm import build_format_instruction, build_langchain_llm
39 from app.tools.registry import (
40 BUILTIN_TOOLS,
41 general_tools,
42 make_webhook_tool,
43 resolve_tool,
44 run_tool_config,
45 )
47 config: AgentConfig = ctx.request.spec # type: ignore[assignment]
49 # A configured web_search passes its domain policy to every tool that
50 # fetches — url_fetch, a document's images — so an operator allowlist
51 # cannot be bypassed another way (``run_tool_config``).
52 web_cfg = {**_WEB_DEFAULTS}
53 for tc in config.tools:
54 if tc.type == "builtin" and tc.name == "web_search":
55 web_cfg = {**_WEB_DEFAULTS, **tc.config}
56 break
58 # The general set is bound unless the caller asked for exactly its own
59 # tools. Keyed by name so an explicit ToolConfig overrides the default
60 # instance of the same tool rather than binding it twice — a duplicate
61 # name is a provider error, not a second tool.
62 tool_map: dict[str, Any] = (
63 {t.name: t for t in general_tools({"web_search": web_cfg})}
64 if config.tools_enabled
65 else {}
66 )
67 for tc in config.tools:
68 if tc.type == "builtin" and tc.name in BUILTIN_TOOLS:
69 tool_cfg = (
70 {**_WEB_DEFAULTS, **tc.config}
71 if tc.name == "web_search"
72 else run_tool_config(tc.name, web_cfg, tc.config)
73 )
74 tool_map[tc.name] = resolve_tool(tc.name, tool_cfg)
75 elif tc.type == "webhook":
76 url = tc.config.get("url", "")
77 if url:
78 tool_map[tc.name] = make_webhook_tool(
79 tc.name,
80 url,
81 tc.description or tc.config.get("description", ""),
82 )
83 # Scripted tools replace a bound tool of the same name, or join the set
84 # (``app/agents/fixtures.py``, which a skill graph's nodes share).
85 tool_map = apply_fixtures(tool_map, config.tool_fixtures)
86 tools = list(tool_map.values())
88 base_system = config.model.system_prompt or "You are a helpful AI assistant."
89 system_prompt = "\n\n".join(
90 filter(
91 None,
92 [
93 prompts.build_metadata_context(),
94 prompts.build_identity_context(config.name),
95 base_system,
96 ],
97 )
98 )
100 cls = AgentFactory.ROLE_CLASS_MAP.get(config.role, SimpleWorkerAgent)
101 worker = cls(name="agent", system_prompt=system_prompt, tools=tools or None)
102 worker.llm = build_langchain_llm(config.model)
103 # MCP server tools are loaded lazily on first execution (connections
104 # are async) and merged into the worker's toolset by
105 # WorkerAgent.process_with_history — builtin tools keep precedence.
106 worker.mcp_servers = [s.model_dump() for s in config.mcp_servers]
108 builder = AgentGraphBuilder(
109 db=self.db,
110 clarify_scope=config.clarify_scope,
111 cost_profile=config.cost_profile.value,
112 lighter_model=config.lighter_model,
113 structured_model=config.structured_model,
114 )
115 builder.add_agent("agent", worker, start=True, end=True)
116 # The platform's web sources, for the built-in agent only: svc-core
117 # sends none for any other (``tools/web/platform_sources.py``).
118 builder.platform_sources = frozenset(config.platform_sources)
119 # Asked for as JSON, the answer is held to it once the run ends, on
120 # the agent's own model (``output_shape``).
121 builder.answer_shape = AnswerShape.of(
122 config.model.output_format, config.model.output_schema, config.model
123 )
125 knowledge_bases = [kb.model_dump() for kb in config.knowledge_bases]
126 extra_context: dict[str, Any] = {
127 "web_search_config": web_cfg,
128 "retrieval_config": config.retrieval.model_dump(),
129 # Agent identity — threaded into GraphState so the gate, synthesis,
130 # and skill nodes can respond in the agent's configured persona.
131 "agent_name": config.name,
132 "agent_system_prompt": base_system,
133 # How much pipeline work the turn does (app/agents/effort.py).
134 effort_registry.CONTEXT_KEY: config.cost_profile.value,
135 }
136 # The format the request asks the answer in, as the model path states
137 # it — a chat's chosen output format, or the schema a dashboard tile
138 # reads its reply against. It used to reach the agent's model config
139 # and go no further. One request's, so it rides in the request
140 # context, never the system prompt (``graph.OUTPUT_FORMAT_KEY``).
141 output_format = build_format_instruction(
142 config.model.output_format, config.model.output_schema
143 )
144 if output_format:
145 extra_context[OUTPUT_FORMAT_KEY] = output_format
147 # Thread conversation history as LangChain messages into GraphState
148 from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
150 lc_messages = []
151 for m in ctx.request.messages or []:
152 role = m.get("role", "")
153 content = m.get("content", "")
154 if role == "user":
155 lc_messages.append(HumanMessage(content=content))
156 elif role == "assistant":
157 lc_messages.append(AIMessage(content=content))
158 elif role == "system":
159 lc_messages.append(SystemMessage(content=content))
161 # Attach history directly on builder so _extra_state_kwargs picks it up
162 builder._initial_lc_messages = lc_messages # type: ignore[attr-defined]
164 return builder, knowledge_bases, extra_context
166 # ── GraphBasedEngine hooks ───────────────────────────────────────────────
167 #
168 # Agent executions thread conversation history in as real LangChain
169 # ``messages`` (so the worker's LLM sees proper message turns) rather than
170 # the raw ``conversation_history`` list the base context carries — hence
171 # the context override below also drops that key to avoid injecting the
172 # same history twice. ``agent_id`` is specific to standalone agent runs.
174 def _extra_state_kwargs(self, builder: Any) -> dict[str, Any]:
175 return {"messages": getattr(builder, "_initial_lc_messages", [])}
177 def _base_state_context(self, ctx: InferenceContext) -> dict[str, Any]:
178 return {
179 "user_id": ctx.request.user_id,
180 "agent_id": str(ctx.request.external_agent_id)
181 if ctx.request.external_agent_id
182 else "",
183 "conversation_id": ctx.request.conversation_id,
184 }
186 def _record_usage(self, usage: dict[str, Any]) -> None:
187 self.monitor.add_usage_dict(usage)