Coverage for app / agents / base.py: 94%

531 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2Base WorkerAgent — foundation for all agents in the execution graph. 

3""" 

4 

5from __future__ import annotations 

6import time 

7 

8from abc import ABC, abstractmethod 

9from contextlib import contextmanager 

10from dataclasses import dataclass, field 

11from typing import Any, Callable, ClassVar, Iterator, TYPE_CHECKING 

12 

13from langchain_core.language_models import BaseLanguageModel 

14from langchain_core.messages import ( 

15 AIMessage, 

16 BaseMessage, 

17 HumanMessage, 

18 SystemMessage, 

19 ToolMessage, 

20) 

21from langchain_core.runnables import RunnableConfig 

22from langchain_core.tools import StructuredTool 

23 

24from opentelemetry import trace as _otel_trace 

25 

26from app.services import metering, reply_formats 

27from app.util import safe_json 

28from app.util.logger import get_logger 

29from app.util.observability import LLMSpan, LangChainOtelHandler 

30from app.agents.enums import AgentRole 

31from app.agents import written_calls 

32from app.tools import limits as tool_limits 

33from app.tools.clarify import ASK_USER, ClarificationRequested, may_ask 

34from app import prompts 

35 

36if TYPE_CHECKING: 

37 from app.models.spec import AgentConfig 

38 

39logger = get_logger(__name__) 

40 

41_tracer = _otel_trace.get_tracer(__name__) 

42 

43 

44# --------------------------------------------------------------------------- 

45# Shared helpers 

46# --------------------------------------------------------------------------- 

47 

48 

49def _is_truncated(response: Any) -> bool: 

50 """True when the provider stopped the completion at the token cap. 

51 

52 Three spellings, because the answer decides whether 

53 ``_complete_if_truncated`` runs — and a missed truncation is silent, the 

54 user simply receives a response that stops mid-sentence: 

55 

56 * Chat Completions (OpenAI, Groq) — ``finish_reason == "length"`` 

57 * Anthropic Messages — ``stop_reason == "max_tokens"`` 

58 * OpenAI Responses — neither. It reports ``status == "incomplete"`` 

59 with ``incomplete_details.reason == "max_output_tokens"``, so 

60 reasoning models, which this service now routes through that API, 

61 read as complete on the two checks above. 

62 * Bedrock Converse — ``stopReason == "max_tokens"``, whichever vendor's 

63 model it served. 

64 """ 

65 meta = getattr(response, "response_metadata", None) or {} 

66 reason = ( 

67 meta.get("finish_reason") 

68 or meta.get("stop_reason") 

69 or meta.get("stopReason") 

70 or "" 

71 ) 

72 if reason in ("length", "max_tokens"): 

73 return True 

74 

75 if meta.get("status") == "incomplete": 

76 details = meta.get("incomplete_details") or {} 

77 return details.get("reason") == "max_output_tokens" 

78 return False 

79 

80 

81def _warn_if_truncated(agent_name: str, response: Any) -> None: 

82 """Log loudly when the provider truncated the completion at the token cap. 

83 

84 A capped response reaches the user cut off mid-sentence. Agent output 

85 must never be truncated — when this fires, the model config's max_tokens 

86 is too small for the response being generated. Callers should follow 

87 up with ``WorkerAgent._complete_if_truncated`` so the cut-off text is 

88 resumed rather than passed downstream. 

89 """ 

90 if _is_truncated(response): 

91 meta = getattr(response, "response_metadata", None) or {} 

92 usage = getattr(response, "usage_metadata", None) or {} 

93 logger.warning( 

94 "[%s] completion TRUNCATED at the max_tokens cap " 

95 "(finish_reason=%r, output_tokens=%s) — resuming from the cut-off point; " 

96 "raise max_tokens in the model config to avoid the extra call", 

97 agent_name, 

98 meta.get("finish_reason") or meta.get("stop_reason"), 

99 usage.get("output_tokens", "?"), 

100 ) 

101 

102 

103def _message_text(result: Any) -> str: 

104 """Text form of a worker result for AIMessage content (JSON for dicts).""" 

105 if isinstance(result, str): 

106 return result 

107 if hasattr(result, "model_dump_json"): 

108 return result.model_dump_json() 

109 if isinstance(result, (dict, list)): 

110 from app.util import safe_json 

111 

112 return safe_json.dumps(result, ensure_ascii=False) 

113 return str(result) 

114 

115 

116def reply_text(llm: Any, response: Any, agent: str = "") -> str: 

117 """The answer in a model's reply, read through the format of the model 

118 that wrote it (``reply_formats``): never its reasoning or preamble. For 

119 code that calls a model itself rather than through 

120 :meth:`WorkerAgent.process_with_history`.""" 

121 reader = reply_formats.of_client(llm) 

122 found = reader.reply(response) 

123 reply_formats.log_reply(agent or "agent", reader, found) 

124 return found.answer 

125 

126 

127def _replayed( 

128 messages: list[BaseMessage], reader: reply_formats.Reader 

129) -> list[BaseMessage]: 

130 """Earlier turns as this model is sent them: each earlier answer as its 

131 format replays one (``ReplyFormat.wrap_history``) — in the envelope for a 

132 model told to answer in one, so the conversation shows it answering that 

133 way. Deterministic, so the replayed history still reads from cache.""" 

134 out: list[BaseMessage] = [] 

135 for message in messages: 

136 if ( 

137 isinstance(message, AIMessage) 

138 and not message.tool_calls 

139 and isinstance(message.content, str) 

140 and message.content 

141 ): 

142 wrapped = reader.wrap_history(message.content) 

143 if wrapped != message.content: 

144 message = message.model_copy(update={"content": wrapped}) 

145 out.append(message) 

146 return out 

147 

148 

149def _reply_attributes(span: Any, found: reply_formats.Reply) -> None: 

150 """How the delivered answer was read, on the agent's span.""" 

151 if span is not None and span.is_recording(): 

152 span.set_attribute("reply.path", found.path) 

153 span.set_attribute("reply.removed_chars", found.removed) 

154 

155 

156def _merge_continuations(fragments: list[AIMessage], name: str) -> AIMessage: 

157 """Fold a truncated response and its continuation(s) into one AIMessage. 

158 

159 Text is joined with no separator — the continuation prompt instructs the 

160 model to resume exactly where the cut-off happened, mid-word if needed. 

161 Fragments that answered with tool calls instead of text carry no 

162 continuation text and are skipped. Each fragment's text is its reply 

163 text (``reply_formats.text_of``: no reasoning blocks); what is answer in 

164 the joined text is read once, by the caller, so an envelope a fragment 

165 opened and its continuation closed reads as one. 

166 

167 Usage is folded into one message's figures: each continuation re-sends 

168 the full context, so ``input_tokens`` is the largest single-call value 

169 while ``output_tokens`` sums every fragment. What was billed is counted 

170 per call by the meter (``services/metering.py``) and, in a stream's 

171 trace, per call by ``graph_based._stream_graph`` — not from this fold. 

172 """ 

173 content = "".join( 

174 reply_formats.text_of(f.content) 

175 for f in fragments 

176 if not getattr(f, "tool_calls", None) 

177 ) 

178 input_tokens = 0 

179 output_tokens = 0 

180 has_usage = False 

181 for f in fragments: 

182 usage = getattr(f, "usage_metadata", None) or {} 

183 if usage: 

184 has_usage = True 

185 input_tokens = max(input_tokens, int(usage.get("input_tokens", 0) or 0)) 

186 output_tokens += int(usage.get("output_tokens", 0) or 0) 

187 metadata = dict(getattr(fragments[-1], "response_metadata", None) or {}) 

188 metadata["continuations"] = len(fragments) - 1 

189 return AIMessage( 

190 content=content, 

191 name=name, 

192 response_metadata=metadata, 

193 usage_metadata=( 

194 { 

195 "input_tokens": input_tokens, 

196 "output_tokens": output_tokens, 

197 "total_tokens": input_tokens + output_tokens, 

198 } 

199 if has_usage 

200 else None 

201 ), 

202 ) 

203 

204 

205@dataclass 

206class AgentCapability: 

207 """Describes a named capability this agent declares.""" 

208 

209 name: str 

210 description: str 

211 required: bool = False 

212 

213 

214@dataclass 

215class AgentState: 

216 """ 

217 Per-agent runtime state tracked across one setup→execute→teardown cycle. 

218 

219 ``messages`` holds proper LangChain message objects, making the history 

220 directly reusable for multi-turn LLM calls. 

221 """ 

222 

223 step_count: int = 0 

224 messages: list[BaseMessage] = field(default_factory=list) 

225 context: dict[str, Any] = field(default_factory=dict) 

226 errors: list[str] = field(default_factory=list) 

227 

228 def add_message(self, message: BaseMessage) -> None: 

229 self.messages.append(message) 

230 

231 def add_error(self, error: str) -> None: 

232 self.errors.append(error) 

233 

234 

235class WorkerAgent(ABC): 

236 """ 

237 Base class for all agents in the execution graph. 

238 

239 Subclasses SHOULD override as class-level constants: 

240 DEFAULT_ROLE — the AgentRole that represents this agent type 

241 DEFAULT_SYSTEM_PROMPT — instructions injected into every LLM call 

242 DEFAULT_MAX_ITERATIONS — iteration cap passed to the agent loop 

243 

244 Subclasses MUST implement: 

245 execute(input_data) — the core logic for this agent role 

246 

247 LLM resolution order (first wins): 

248 1. Explicitly passed ``llm=`` argument to __init__ 

249 2. Built via ``WorkerAgent.from_config(AgentConfig)`` 

250 3. The deployment's default model, built lazily by ``resolve_llm()`` 

251 

252 Message construction: 

253 Use ``self.build_messages(user_content)`` in ``execute()`` to produce 

254 a model-agnostic ``[SystemMessage, HumanMessage]`` sequence that can be 

255 passed directly to any LangChain LLM. 

256 

257 Graph execution: 

258 The graph calls ``process_with_history(task_content, prior_messages)`` 

259 rather than ``process``. This threads the full conversation history 

260 from prior nodes into each agent's LLM call, so every agent in the 

261 graph sees all preceding work as proper conversation context. 

262 """ 

263 

264 # --- class-level defaults (override per role) --- 

265 DEFAULT_ROLE: ClassVar[AgentRole] = AgentRole.WORKER 

266 DEFAULT_SYSTEM_PROMPT: ClassVar[str] = "" 

267 DEFAULT_MAX_ITERATIONS: ClassVar[int] = 10 

268 # How many times a completion that stopped at the max_tokens cap is 

269 # resumed before the (still partial) text is accepted. Each resume is a 

270 # full extra LLM call, so the budget is deliberately small. 

271 DEFAULT_MAX_CONTINUATIONS: ClassVar[int] = 2 

272 

273 def __init__( 

274 self, 

275 name: str, 

276 role: AgentRole | None = None, 

277 llm: BaseLanguageModel | None = None, 

278 system_prompt: str | None = None, 

279 tools: list[StructuredTool] | None = None, 

280 max_iterations: int | None = None, 

281 mcp_servers: list[dict] | None = None, 

282 max_continuations: int | None = None, 

283 input_schema: list[dict] | None = None, 

284 output_schema: list[dict] | None = None, 

285 ) -> None: 

286 from app.agents.interfaces import normalise_schema 

287 

288 self.name = name 

289 self.role = role if role is not None else self.DEFAULT_ROLE 

290 self.llm: BaseLanguageModel | None = llm 

291 # A model this agent answers with for one call instead of ``llm`` 

292 # (``answering_with``): an Economy profile's lighter model, for a 

293 # request triage called simple. 

294 self._answer_override: BaseLanguageModel | None = None 

295 self.system_prompt = ( 

296 system_prompt if system_prompt is not None else self.DEFAULT_SYSTEM_PROMPT 

297 ) 

298 self.tools: list[StructuredTool] = list(tools or []) 

299 # Tools this agent is not given, whoever offers them (its own list, 

300 # a plan's guidance): its workflow's own step holds them — a skill 

301 # whose last step makes the document (``DOCUMENT_TOOL``). 

302 self.withheld_tools: frozenset[str] = frozenset() 

303 self.max_iterations = ( 

304 max_iterations 

305 if max_iterations is not None 

306 else self.DEFAULT_MAX_ITERATIONS 

307 ) 

308 self.max_continuations = ( 

309 max_continuations 

310 if max_continuations is not None 

311 else self.DEFAULT_MAX_CONTINUATIONS 

312 ) 

313 # Earlier turns its last answer could not carry (``token_budget``): 

314 # read by the graph node that called it, for the turn's record. 

315 self.history_turns_omitted = 0 

316 # A cap of the run's cost profile's own on the history it replays, 

317 # in tokens (``app/agents/effort.py``), set by the graph node that 

318 # calls it. None: the model's window and price tier alone. 

319 self.history_token_cap: int | None = None 

320 # MCP server descriptors — their tools are loaded lazily on first 

321 # execution (connections are async) and cached for the agent's life. 

322 self.mcp_servers: list[dict] = list(mcp_servers or []) 

323 self._mcp_tools: list[StructuredTool] | None = None 

324 # Typed interface (see app.agents.interfaces). ``input_schema`` 

325 # describes the values a graph node binds into this worker; 

326 # ``output_schema`` — when non-empty — makes the worker return a 

327 # schema-validated dict instead of free text. 

328 self.input_schema = normalise_schema(input_schema) 

329 self.output_schema = normalise_schema(output_schema) 

330 self.state = AgentState() 

331 self._capabilities: dict[str, AgentCapability] = {} 

332 

333 # ------------------------------------------------------------------ 

334 # Interface helpers 

335 # ------------------------------------------------------------------ 

336 

337 @property 

338 def is_structured(self) -> bool: 

339 """True when this worker returns a dict matching ``output_schema``.""" 

340 return bool(self.output_schema) 

341 

342 def set_interface( 

343 self, 

344 input_schema: Any = None, 

345 output_schema: Any = None, 

346 ) -> None: 

347 """Replace the typed interface (used by per-node overrides).""" 

348 from app.agents.interfaces import normalise_schema 

349 

350 if input_schema is not None: 

351 self.input_schema = normalise_schema(input_schema) 

352 if output_schema is not None: 

353 self.output_schema = normalise_schema(output_schema) 

354 

355 async def _structure_output( 

356 self, 

357 output: Any, 

358 messages: list[BaseMessage], 

359 config: RunnableConfig | None = None, 

360 ) -> Any: 

361 """Coerce a worker answer to its ``output_schema``. 

362 

363 1. Read the answer exactly: the whole text, or the one fenced block it 

364 is (``interfaces.parse_structured_output``). 

365 2. On failure, ask the model once more through ``structured_call`` 

366 (a cheap repair call with the answer already in context, decoded 

367 natively where the route can). 

368 3. As a last resort return the schema defaults plus ``_raw`` / 

369 ``_error`` so the graph keeps flowing and the problem is visible 

370 in the trace rather than crashing the whole skill. 

371 """ 

372 from app.agents.interfaces import ( 

373 build_output_model, 

374 default_output, 

375 output_values, 

376 parse_structured_output, 

377 ) 

378 

379 parsed, error = parse_structured_output(output, self.output_schema) 

380 if parsed is not None: 

381 return parsed 

382 

383 logger.warning( 

384 "[agent:%s] output did not match output_schema (%s) — attempting repair", 

385 self.name, 

386 error, 

387 ) 

388 try: 

389 from app.services.structured_output import structured_call 

390 

391 llm = self.resolve_llm() 

392 model_cls = build_output_model(self.output_schema, f"{self.name}_output") 

393 repair_thread: list[BaseMessage] = [ 

394 *messages, 

395 AIMessage( 

396 content=reply_formats.text_of(output) 

397 if not isinstance(output, str) 

398 else output 

399 ), 

400 HumanMessage( 

401 content=( 

402 "Convert your answer above into the required JSON object. " 

403 "Preserve every fact; do not add commentary." 

404 ) 

405 ), 

406 ] 

407 # structured_call picks the method: an output schema with an 

408 # ``object`` field cannot be decoded strictly, and ChatOpenAI's 

409 # default (strict json_schema) refused it — so this repair failed 

410 # on OpenAI for every such schema. 

411 repaired = await structured_call( 

412 llm, 

413 model_cls, 

414 repair_thread, 

415 purpose=f"{self.name}.output_repair", 

416 config=config, 

417 ) 

418 if repaired.value is not None: 

419 return output_values(repaired.value, self.output_schema) 

420 error = f"{error}; repair failed: {repaired.failure}" 

421 except Exception as exc: # noqa: BLE001 — degrade, never crash the graph 

422 from app.services import model_errors 

423 

424 model_errors.raise_if_fatal(exc) 

425 logger.warning( 

426 "[agent:%s] structured repair failed: %s", 

427 self.name, 

428 model_errors.describe(exc), 

429 ) 

430 error = f"{error}; repair failed: {model_errors.describe(exc)}" 

431 

432 fallback = default_output(self.output_schema) 

433 fallback["_raw"] = ( 

434 output if isinstance(output, str) else reply_formats.text_of(output) 

435 ) 

436 fallback["_error"] = error 

437 return fallback 

438 

439 async def _typed_reply( 

440 self, messages: list[BaseMessage], config: RunnableConfig | None 

441 ) -> tuple[dict[str, Any], list[BaseMessage]]: 

442 """A worker without tools held to its ``output_schema``: one 

443 structured call (``structured_call``, decoded natively where the 

444 route can), not a free-text answer parsed afterwards. What it could 

445 not fill is the schema's defaults with ``_error``, as when a repair 

446 fails. Its calls are tagged as structured, so their JSON never 

447 streams to the person. The node's own work, so its own model makes 

448 the call: a run's native sibling never stands in for it.""" 

449 from app.agents.interfaces import ( 

450 build_output_model, 

451 default_output, 

452 output_values, 

453 ) 

454 from app.services.structured_output import structured_call 

455 

456 model_cls = build_output_model(self.output_schema, f"{self.name}_output") 

457 result = await structured_call( 

458 self.resolve_llm(), 

459 model_cls, 

460 messages, 

461 purpose=f"{self.name}.output", 

462 config=config, 

463 stand_in=False, 

464 ) 

465 if result.value is not None: 

466 values = output_values(result.value, self.output_schema) 

467 else: 

468 logger.warning( 

469 "[agent:%s] typed output failed: %s", self.name, result.failure 

470 ) 

471 values = default_output(self.output_schema) 

472 values["_error"] = result.failure 

473 return values, [AIMessage(content=safe_json.dumps(values, ensure_ascii=False))] 

474 

475 # ------------------------------------------------------------------ 

476 # Construction helpers 

477 # ------------------------------------------------------------------ 

478 

479 @classmethod 

480 def from_config(cls, config: AgentConfig, name: str = "") -> WorkerAgent: 

481 """ 

482 Construct this agent from an API-layer AgentConfig. 

483 

484 Builds a LangChain LLM from config.model and forwards the system 

485 prompt if one is set. Resolves any builtin ToolConfigs into 

486 LangChain StructuredTools and binds them to the agent. 

487 Subclasses may override to handle additional role-specific config keys. 

488 """ 

489 from app.services.llm import build_langchain_llm 

490 from app.tools.registry import general_tools, resolve_tool, run_tool_config 

491 

492 llm = build_langchain_llm(config.model) 

493 

494 # General tools are always present; explicit config tools override by 

495 # name. A configured web_search also passes its domain policy to 

496 # every tool that fetches (``run_tool_config``). 

497 web_cfg = next( 

498 ( 

499 tc.config 

500 for tc in config.tools 

501 if tc.type == "builtin" and tc.name == "web_search" 

502 ), 

503 None, 

504 ) 

505 tool_map: dict[str, StructuredTool] = { 

506 t.name: t 

507 for t in general_tools({"web_search": web_cfg} if web_cfg else None) 

508 } 

509 for tc in config.tools: 

510 if tc.type == "builtin": 

511 try: 

512 tool_map[tc.name] = resolve_tool( 

513 tc.name, run_tool_config(tc.name, web_cfg, tc.config) 

514 ) 

515 except ValueError: 

516 logger.warning( 

517 "Could not resolve tool %r for agent %r; skipping", 

518 tc.name, 

519 name, 

520 ) 

521 

522 return cls( 

523 name=name or f"{cls.DEFAULT_ROLE.value}_agent", 

524 llm=llm, 

525 system_prompt=config.model.system_prompt or None, 

526 tools=list(tool_map.values()), 

527 ) 

528 

529 # ------------------------------------------------------------------ 

530 # LLM resolution 

531 # ------------------------------------------------------------------ 

532 

533 @contextmanager 

534 def answering_with(self, llm: BaseLanguageModel | None) -> Iterator[None]: 

535 """Answer with ``llm`` for the calls made inside the block — the 

536 tool loop, history fitting and caching included, since each asks 

537 :meth:`resolve_llm`. None changes nothing.""" 

538 previous = getattr(self, "_answer_override", None) 

539 self._answer_override = llm if llm is not None else previous 

540 try: 

541 yield 

542 finally: 

543 self._answer_override = previous 

544 

545 def resolve_llm(self) -> BaseLanguageModel: 

546 """ 

547 Return self.llm, building the deployment's default model if none was 

548 assigned — or the model this call answers with instead 

549 (:meth:`answering_with`). 

550 

551 Every model is built through ``build_langchain_llm``, so it takes this 

552 backend's route, its spending ceiling and its meter; a model named 

553 here once (GPT-4o mini, through OpenAI's API) bypassed all three and 

554 could not run on Bedrock at all. 

555 """ 

556 override = getattr(self, "_answer_override", None) 

557 if override is not None: 

558 return override 

559 if self.llm is not None: 

560 return self.llm 

561 from app.services.llm import build_langchain_llm, deployment_default_model 

562 

563 self.llm = build_langchain_llm(deployment_default_model()) 

564 return self.llm 

565 

566 # ------------------------------------------------------------------ 

567 # Message construction 

568 # ------------------------------------------------------------------ 

569 

570 def build_messages(self, user_content: str) -> list[BaseMessage]: 

571 """ 

572 Build a model-agnostic message sequence for a single LLM turn. 

573 

574 Returns ``[SystemMessage, HumanMessage]`` when a system prompt is set, 

575 or just ``[HumanMessage]`` otherwise. Pass the result directly to 

576 ``llm.ainvoke(messages)``. 

577 

578 Example:: 

579 

580 messages = self.build_messages(f"Analyse:\\n{input_data}") 

581 response: AIMessage = await llm.ainvoke(messages) 

582 content = response.content 

583 """ 

584 messages: list[BaseMessage] = [] 

585 if self.system_prompt: 

586 messages.append(SystemMessage(content=self.system_prompt)) 

587 messages.append(HumanMessage(content=user_content)) 

588 return messages 

589 

590 # ------------------------------------------------------------------ 

591 # Capability registry 

592 # ------------------------------------------------------------------ 

593 

594 def add_capability(self, capability: AgentCapability) -> None: 

595 """Register a capability this agent supports.""" 

596 self._capabilities[capability.name] = capability 

597 

598 def get_capabilities(self) -> list[AgentCapability]: 

599 return list(self._capabilities.values()) 

600 

601 # ------------------------------------------------------------------ 

602 # Tool management 

603 # ------------------------------------------------------------------ 

604 

605 def add_tool(self, tool: StructuredTool) -> None: 

606 self.tools.append(tool) 

607 

608 def get_tools(self) -> list[StructuredTool]: 

609 return list(self.tools) 

610 

611 async def _load_mcp_tools(self) -> list[StructuredTool]: 

612 """Load tools from the configured MCP servers, once per agent instance. 

613 

614 A failed or empty load caches [] — MCP problems degrade the agent to 

615 its builtin toolset rather than failing execution. 

616 """ 

617 if self._mcp_tools is None: 

618 if self.mcp_servers: 

619 from app.mcp.loader import load_mcp_tools 

620 

621 self._mcp_tools = list(await load_mcp_tools(self.mcp_servers)) 

622 else: 

623 self._mcp_tools = [] 

624 return self._mcp_tools 

625 

626 # ------------------------------------------------------------------ 

627 # Execution lifecycle 

628 # ------------------------------------------------------------------ 

629 

630 async def setup(self) -> None: 

631 """Pre-execution hook. Override for custom initialisation.""" 

632 

633 async def teardown(self) -> None: 

634 """Post-execution hook. Override for custom cleanup.""" 

635 

636 @abstractmethod 

637 async def execute(self, input_data: Any) -> Any: 

638 """ 

639 Execute this agent's primary task. 

640 

641 Use ``self.build_messages(user_content)`` to construct the LLM input 

642 and pass the list directly to ``llm.ainvoke()``. 

643 

644 Returns: 

645 Agent output — type is defined by the concrete subclass. 

646 """ 

647 

648 async def process(self, input_data: Any) -> Any: 

649 """ 

650 Full lifecycle: setup → execute → teardown. 

651 

652 Appends an AIMessage to state.messages on success so the full 

653 conversation history is available for inspection or multi-turn use. 

654 """ 

655 try: 

656 self.state.step_count += 1 

657 await self.setup() 

658 result = await self.execute(input_data) 

659 await self.teardown() 

660 self.state.add_message(AIMessage(content=str(result), name=self.name)) 

661 return result 

662 except Exception as exc: 

663 self.state.add_error(str(exc)) 

664 raise 

665 

666 async def process_state(self, state: Any) -> Any: 

667 """ 

668 Execute with access to the full graph state. 

669 

670 Called by the graph runner instead of ``process``. The default 

671 implementation extracts ``state.input`` so simple agents continue 

672 to work unchanged. Override in context-aware agents that need to 

673 inspect ``state.results``, ``state.context``, etc. 

674 """ 

675 input_text = getattr(state, "input", str(state)) 

676 return await self.process(input_text) 

677 

678 async def process_with_history( 

679 self, 

680 task_content: str, 

681 prior_messages: list[BaseMessage], 

682 extra_tools: list[StructuredTool] | None = None, 

683 extra_system_context: str = "", 

684 on_tool_call: Callable | None = None, 

685 config: RunnableConfig | None = None, 

686 request_context: str = "", 

687 answer_format_requested: bool = False, 

688 ) -> tuple[Any, list[BaseMessage]]: 

689 """Execute within a graph, threading full conversation history — see 

690 :meth:`_respond_with_history`. Every call it makes is labelled as this 

691 worker responding (``metering.Step.respond``), unless something 

692 inside labels its own: a continuation, an output repair. 

693 

694 ``answer_format_requested``: the request chose the answer's format 

695 (JSON, say), so a reply shaped like a tool's arguments may be the 

696 answer, and is never sent back as a call written out as text.""" 

697 with metering.step(metering.Step.respond): 

698 return await self._respond_with_history( 

699 task_content, 

700 prior_messages, 

701 extra_tools, 

702 extra_system_context, 

703 on_tool_call, 

704 config, 

705 request_context, 

706 answer_format_requested, 

707 ) 

708 

709 async def _respond_with_history( 

710 self, 

711 task_content: str, 

712 prior_messages: list[BaseMessage], 

713 extra_tools: list[StructuredTool] | None = None, 

714 extra_system_context: str = "", 

715 on_tool_call: Callable | None = None, 

716 config: RunnableConfig | None = None, 

717 request_context: str = "", 

718 answer_format_requested: bool = False, 

719 ) -> tuple[Any, list[BaseMessage]]: 

720 """ 

721 Execute within a graph, threading full conversation history. 

722 

723 This is the method the graph node function calls. Unlike 

724 ``process``, it builds the LLM's input as a proper conversation 

725 thread — ``[SystemMessage, *prior_messages, HumanMessage(task)]`` — 

726 so each agent naturally sees every prior node's output and tool calls 

727 as conversation context rather than receiving a flat text blob. 

728 

729 Returns: 

730 ``(result, new_messages)`` where ``new_messages`` are only the 

731 messages generated in this call (suitable for appending to 

732 ``GraphState.messages`` via the ``add_messages`` reducer). 

733 

734 Fallback: 

735 Agents without a configured LLM and no tools (e.g. pure-logic 

736 or test agents) fall back to ``process(task_content)`` so they 

737 continue to work correctly without an LLM dependency. 

738 """ 

739 await self.setup() 

740 try: 

741 # Agents with neither LLM nor tools use their execute() directly. 

742 # This keeps test agents (EchoAgent etc.) and pure-logic agents working. 

743 if self.llm is None and not self.tools: 

744 result = await self.execute(task_content) 

745 if self.output_schema and not isinstance(result, dict): 

746 from app.agents.interfaces import parse_structured_output 

747 

748 parsed, _ = parse_structured_output(result, self.output_schema) 

749 if parsed is not None: 

750 result = parsed 

751 new_messages: list[BaseMessage] = [ 

752 AIMessage(content=_message_text(result), name=self.name) 

753 ] 

754 self.state.step_count += 1 

755 self.state.add_message(new_messages[0]) 

756 return result, new_messages 

757 

758 # Merge self.tools + MCP tools + extra_tools, deduplicating by name. 

759 # extra_tools (injected from graph state) win over self.tools so that 

760 # state-chained replacements (e.g. a query_knowledge_graph with valid 

761 # KB IDs pre-listed) always override generic agent-definition defaults. 

762 # MCP tools never shadow builtin/graph tools of the same name. 

763 merged: dict[str, StructuredTool] = {t.name: t for t in self.tools} 

764 for t in await self._load_mcp_tools(): 

765 merged.setdefault(t.name, t) 

766 for t in extra_tools or []: 

767 merged[t.name] = t 

768 for name in self.withheld_tools: 

769 merged.pop(name, None) 

770 effective_tools = list(merged.values()) 

771 

772 # Build the full conversation context: 

773 # [SystemMessage] + prior_messages + [HumanMessage(task)] 

774 effective_prompt = self.system_prompt or "" 

775 if extra_system_context: 

776 effective_prompt = effective_prompt + "\n\n" + extra_system_context 

777 # The rendering hint instructs the model to CALL the render tools. 

778 # For agents without them (retrieval workers, tool-less system 

779 # nodes) it provokes hand-written, unvalidated fences — so it is 

780 # only injected when a render tool is actually bound. 

781 from app.tools.registry import DOCUMENT_TOOL, RENDER_TOOL_NAMES 

782 

783 if any(t.name in RENDER_TOOL_NAMES for t in effective_tools): 

784 if DOCUMENT_TOOL in self.withheld_tools: 

785 # Told about a tool it does not hold, the step called it. 

786 effective_prompt += ( 

787 "\n\n" 

788 + prompts.RENDERING_HINT_WITHOUT_DOCUMENT 

789 + "\n" 

790 + prompts.DOCUMENT_STEP_NOTE 

791 ) 

792 else: 

793 effective_prompt += "\n\n" + prompts.RENDERING_HINT 

794 reader = reply_formats.of_client(self.resolve_llm()) 

795 if effective_tools: 

796 effective_prompt = ( 

797 effective_prompt 

798 + "\n\n" 

799 + prompts.tool_turn_hint(reader.keeps_tool_turn_text) 

800 ) 

801 # Where the reply goes, for a model whose reasoning can arrive as 

802 # text (``reply_formats.GptOss``): the answer is then what it puts 

803 # in the envelope. Not for typed output, which is JSON. 

804 if reader.contract() and not self.output_schema: 

805 effective_prompt = effective_prompt + "\n\n" + reader.contract() 

806 # Typed output contract — placed last so it is the final 

807 # instruction the model reads before answering. Only where the 

808 # answer is read from text (a tool loop's final message): without 

809 # tools the worker is held to the schema itself (``_typed_reply``). 

810 if self.output_schema and effective_tools: 

811 from app.agents.interfaces import output_schema_instruction 

812 

813 effective_prompt = ( 

814 effective_prompt 

815 + "\n\n" 

816 + output_schema_instruction(self.output_schema) 

817 ) 

818 

819 # The system message is the same on every call of this agent, so 

820 # a provider can serve it (and the tools before it) from cache. 

821 # What changes per request (``request_context``) travels with the 

822 # task, after the history. 

823 from app.services import prompt_cache 

824 

825 messages: list[BaseMessage] = [] 

826 if effective_prompt: 

827 messages.append( 

828 prompt_cache.system_message(self.resolve_llm(), effective_prompt) 

829 ) 

830 # The history fitted to this model: inside its window and below 

831 # its long-context price tier (``token_budget``). The model is 

832 # told what it cannot see, and the node reports it. 

833 from app.services import token_budget 

834 

835 fitted = token_budget.fit_for_call( 

836 self.resolve_llm(), 

837 _replayed(list(prior_messages), reader), 

838 system_text=effective_prompt, 

839 task_text=f"{request_context}\n\n{task_content}", 

840 tools=effective_tools, 

841 profile_cap=self.history_token_cap, 

842 ) 

843 self.history_turns_omitted = fitted.omitted_turns 

844 note = token_budget.omitted_note(fitted) 

845 if note: 

846 request_context = ( 

847 f"{request_context}\n{note}" if request_context else note 

848 ) 

849 # A breakpoint after the history: the next turn begins with the 

850 # same conversation, so it reads it from cache (``mark_last``). 

851 messages.extend(prompt_cache.mark_last(self.resolve_llm(), fitted.messages)) 

852 messages.append( 

853 HumanMessage( 

854 content=f"{request_context}\n\n{task_content}" 

855 if request_context 

856 else task_content 

857 ) 

858 ) 

859 

860 if effective_tools: 

861 output, new_messages = await self.run_with_tools( 

862 messages, 

863 tools=effective_tools, 

864 on_tool_call=on_tool_call, 

865 config=config, 

866 structured=bool(self.output_schema), 

867 answer_format_requested=answer_format_requested, 

868 ) 

869 elif self.output_schema: 

870 output, new_messages = await self._typed_reply(messages, config) 

871 else: 

872 llm = self.resolve_llm() 

873 t0 = time.monotonic() 

874 response = await llm.ainvoke( 

875 messages, 

876 config=config, 

877 **prompt_cache.request_options(llm, effective_prompt, []), 

878 ) 

879 _warn_if_truncated(self.name, response) 

880 text, response = await self._complete_if_truncated( 

881 llm, messages, response, config 

882 ) 

883 found = reader.answer(text) 

884 if not found.answer and not text.strip(): 

885 found = reader.reply(response) 

886 reply_formats.log_reply(self.name, reader, found) 

887 output = found.answer 

888 latency_ms = int((time.monotonic() - t0) * 1000) 

889 usage = getattr(response, "usage_metadata", None) or {} 

890 _prompt_t = usage.get("input_tokens", 0) 

891 _compl_t = usage.get("output_tokens", 0) 

892 _cost_usd: float | None = None 

893 try: 

894 import litellm as _litellm 

895 

896 _model_name = getattr(llm, "model_name", getattr(llm, "model", "")) 

897 if _model_name: 

898 _p, _c = _litellm.cost_per_token( 

899 model=_model_name, 

900 prompt_tokens=_prompt_t, 

901 completion_tokens=_compl_t, 

902 ) 

903 _cost_usd = _p + _c 

904 except Exception: 

905 pass 

906 LLMSpan( 

907 agent=self.name, 

908 model=getattr(llm, "model_name", getattr(llm, "model", "")), 

909 latency_ms=latency_ms, 

910 prompt_tokens=_prompt_t, 

911 completion_tokens=_compl_t, 

912 cost_usd=_cost_usd, 

913 ).log(logger) 

914 new_messages = [reader.trace(response)] 

915 

916 result: Any = output 

917 # A tool loop's answer is text, read and repaired here; a typed 

918 # reply (``_typed_reply``) already is the schema, or says why not. 

919 if self.output_schema and effective_tools: 

920 result = await self._structure_output(output, messages, config) 

921 

922 self.state.step_count += 1 

923 self.state.add_message( 

924 AIMessage(content=_message_text(result), name=self.name) 

925 ) 

926 return result, new_messages 

927 

928 except ClarificationRequested: 

929 # A question for the person, not a failure. 

930 raise 

931 except Exception as exc: 

932 self.state.add_error(str(exc)) 

933 raise 

934 finally: 

935 await self.teardown() 

936 

937 # ------------------------------------------------------------------ 

938 # Truncation recovery 

939 # ------------------------------------------------------------------ 

940 

941 async def _complete_if_truncated( 

942 self, 

943 llm: Any, 

944 context: list[BaseMessage], 

945 response: AIMessage, 

946 config: RunnableConfig | None = None, 

947 ) -> tuple[str, AIMessage]: 

948 """Resume ``response`` when the provider cut it off at the token cap. 

949 

950 ``context`` is the message list that produced ``response`` (without 

951 the response itself). While the latest fragment reports a cap hit 

952 and the continuation budget allows, the model is asked to carry on 

953 from exactly where it stopped; the fragments are then folded into a 

954 single AIMessage so downstream consumers (state messages, usage 

955 accounting, context injection) see one clean response. 

956 

957 Returns ``(text, message)``: the reply text of every fragment joined 

958 (``reply_formats.text_of``), for the caller to read the answer in 

959 once. When the response was not truncated it is returned untouched, 

960 so callers can use this unconditionally. 

961 """ 

962 if not _is_truncated(response) or self.max_continuations <= 0: 

963 return reply_formats.text_of(response.content), response 

964 

965 fragments: list[AIMessage] = [response] 

966 thread: list[BaseMessage] = list(context) + [response] 

967 for attempt in range(1, self.max_continuations + 1): 

968 thread.append(HumanMessage(content=prompts.CONTINUATION_PROMPT)) 

969 with metering.step(metering.Step.continuation): 

970 nxt: AIMessage = await llm.ainvoke(list(thread), config=config) 

971 fragments.append(nxt) 

972 thread.append(nxt) 

973 usage = getattr(nxt, "usage_metadata", None) or {} 

974 logger.info( 

975 "[agent:%s] continuation %d/%d output_tokens=%s truncated=%s", 

976 self.name, 

977 attempt, 

978 self.max_continuations, 

979 usage.get("output_tokens", "?"), 

980 _is_truncated(nxt), 

981 ) 

982 if getattr(nxt, "tool_calls", None): 

983 # The model answered with a tool call rather than prose — 

984 # there is no text to splice on; keep what we have. 

985 break 

986 if not _is_truncated(nxt): 

987 break 

988 else: 

989 logger.warning( 

990 "[agent:%s] response still truncated after %d continuation(s) " 

991 "— raise max_tokens in the model config", 

992 self.name, 

993 self.max_continuations, 

994 ) 

995 

996 merged = _merge_continuations(fragments, self.name) 

997 return reply_formats.text_of(merged.content), merged 

998 

999 # ------------------------------------------------------------------ 

1000 # Tool-calling loop 

1001 # ------------------------------------------------------------------ 

1002 

1003 async def run_with_tools( 

1004 self, 

1005 messages: list[BaseMessage], 

1006 tools: list[StructuredTool] | None = None, 

1007 on_tool_call: Callable | None = None, 

1008 config: RunnableConfig | None = None, 

1009 structured: bool = False, 

1010 answer_format_requested: bool = False, 

1011 ) -> tuple[str, list[BaseMessage]]: 

1012 """ 

1013 Run an agentic tool-calling loop via LangGraph's ``ToolNode``. 

1014 

1015 ``structured``: the final answer is a typed worker's JSON, read from 

1016 the final message alone — no continuation spliced into it, no earlier 

1017 turn's text joined to it — and passed whole when it parses whole. 

1018 

1019 A final reply that is a bound tool's call written out as text (its 

1020 arguments as JSON, ``written_calls``) is sent back once, so the model 

1021 makes the call or answers in prose; never for a typed worker, nor when 

1022 the request chose the answer's format (``answer_format_requested``). 

1023 

1024 ``ToolNode`` executes all pending tool calls in parallel and wraps 

1025 exceptions as ``ToolMessage(status="error")`` rather than raising, 

1026 giving each agent automatic error resilience without boilerplate. 

1027 

1028 Returns: 

1029 ``(final_content, new_messages)`` — same contract as before. 

1030 ``new_messages`` contains every message produced after the initial 

1031 ``messages`` param so the full tool trace is preserved in 

1032 ``GraphState.messages`` for streaming, usage accounting, and 

1033 downstream context injection. 

1034 """ 

1035 import json as _json 

1036 from langgraph.prebuilt import ToolNode 

1037 

1038 effective_tools = tools if tools is not None else self.tools 

1039 if effective_tools and not may_ask(): 

1040 # The person cannot be asked here (once a turn, never on a 

1041 # revision, never outside a graph step): the tool is not offered. 

1042 effective_tools = [t for t in effective_tools if t.name != ASK_USER] 

1043 llm = self.resolve_llm() 

1044 reader = reply_formats.of_client(llm) 

1045 # No with_retry() here: the provider client already retries transient 

1046 # failures (``llm.MODEL_CALL_RETRIES``). A wrapper retried every 

1047 # exception, a 400 included, and multiplied the client's attempts — 

1048 # nine metered calls for one failing request. 

1049 from app.services import prompt_cache 

1050 

1051 system_text = ( 

1052 prompt_cache.text_of(messages[0].content) 

1053 if messages and isinstance(messages[0], SystemMessage) 

1054 else "" 

1055 ) 

1056 from app.tools import wire 

1057 

1058 def _bind(specs: list[Any]) -> Any: 

1059 return llm.bind_tools( 

1060 specs, 

1061 **prompt_cache.request_options( 

1062 llm, system_text, [t.name for t in effective_tools] 

1063 ), 

1064 # Each round caches up to its last block, and the next round — 

1065 # the same messages plus a reply and its tool results — reads it. 

1066 **prompt_cache.tail_options(llm), 

1067 ) 

1068 

1069 # What the model is shown: the platform's tools as strict specs on a 

1070 # route that holds arguments to their schema (``wire``); the tools 

1071 # themselves still run below, through ``ToolNode``. 

1072 # What the model is offered: never a tool already past its call limit 

1073 # (an earlier pass of the same run spent it), and a tool that reaches 

1074 # it is withdrawn for the rest of the loop (``tools/limits``); once 

1075 # the route refused strict specs the tools are bound as they are. 

1076 offered = [t for t in effective_tools if not tool_limits.is_spent(t)] 

1077 strict = True 

1078 bound_tools = wire.for_binding(offered, llm) 

1079 # Unbound only when every tool it was given is spent. 

1080 llm_with_tools = _bind(bound_tools) if offered or not effective_tools else llm 

1081 # handle_tool_errors wraps exceptions as error ToolMessages instead of raising. 

1082 tool_node = ToolNode(effective_tools, handle_tool_errors=True) 

1083 

1084 current_messages: list[BaseMessage] = list(messages) 

1085 new_messages: list[BaseMessage] = [] 

1086 # Text the model writes in turns that ALSO call tools. Claude writes 

1087 # the answer incrementally — a section, a render call, the next 

1088 # section, a search, … — so its final tool-free message holds only 

1089 # the tail; other models write what they are about to do. Which it 

1090 # is decides the answer (``reply_formats.Reader.tool_loop_answer``). 

1091 # ``current_messages`` goes back to the model as it wrote it; 

1092 # ``new_messages`` is the trace, and holds only answer 

1093 # (``Reader.trace``). 

1094 prose_parts: list[str] = [] 

1095 # A call written out as text is sent back once (``written_calls``). 

1096 checks_written_calls = not structured and not answer_format_requested 

1097 sent_back = False 

1098 

1099 # Merge the parent LangGraph streaming config with our local requirements: 

1100 # - OTEL handler for per-tool child spans under the current graph-node span. 

1101 # - LGRuntime in configurable if not already present (ToolNode requires it). 

1102 # Using merge_configs (append) rather than a fresh RunnableConfig (replace) 

1103 # preserves the astream_events callbacks so on_tool_start/on_tool_end events 

1104 # stay visible to the graph's streaming consumer. 

1105 from langchain_core.runnables.config import merge_configs 

1106 from langgraph.runtime import Runtime as _LGRuntime 

1107 from langgraph._internal._constants import CONFIG_KEY_RUNTIME as _CKR 

1108 

1109 _otel_handler = LangChainOtelHandler() 

1110 _parent_config: dict = config if isinstance(config, dict) else {} 

1111 _parent_configurable: dict = _parent_config.get("configurable") or {} 

1112 _extra_configurable = ( 

1113 {} if _CKR in _parent_configurable else {_CKR: _LGRuntime()} 

1114 ) 

1115 _effective_config = merge_configs( 

1116 _parent_config, 

1117 {"callbacks": [_otel_handler], "configurable": _extra_configurable}, 

1118 ) 

1119 

1120 logger.info( 

1121 "[agent:%s] run_with_tools tools=%s max_iter=%d", 

1122 self.name, 

1123 [t.name for t in effective_tools], 

1124 self.max_iterations, 

1125 ) 

1126 

1127 with _tracer.start_as_current_span( 

1128 f"agent.run_with_tools.{self.name}" 

1129 ) as _span: 

1130 if _span.is_recording(): 

1131 _span.set_attribute("agent.name", self.name) 

1132 _span.set_attribute( 

1133 "agent.tools", ", ".join(t.name for t in effective_tools) 

1134 ) 

1135 _span.set_attribute("agent.max_iterations", self.max_iterations) 

1136 # Capture the system prompt and last user message so the Trace Explorer 

1137 # can show the full prompt context for each agent span. 

1138 for _m in current_messages: 

1139 if isinstance(_m, SystemMessage): 

1140 _span.set_attribute( 

1141 "llm.system_prompt", prompt_cache.text_of(_m.content)[:2000] 

1142 ) 

1143 break 

1144 for _m in reversed(current_messages): 

1145 if isinstance(_m, HumanMessage): 

1146 _span.set_attribute("llm.user_message", str(_m.content)[:1000]) 

1147 break 

1148 

1149 for iteration in range(self.max_iterations): 

1150 t_llm = time.monotonic() 

1151 try: 

1152 response: AIMessage = await llm_with_tools.ainvoke( 

1153 current_messages, config=_effective_config 

1154 ) 

1155 except Exception as exc: 

1156 # A route that refuses strict tools is asked again with 

1157 # them as they are, and is never sent them again. 

1158 if not wire.refused(llm, bound_tools, exc): 

1159 raise 

1160 strict = False 

1161 bound_tools = list(offered) 

1162 llm_with_tools = _bind(bound_tools) 

1163 response = await llm_with_tools.ainvoke( 

1164 current_messages, config=_effective_config 

1165 ) 

1166 llm_ms = int((time.monotonic() - t_llm) * 1000) 

1167 _warn_if_truncated(self.name, response) 

1168 # A call whose arguments did not parse never goes back to the 

1169 # provider (``written_calls.without_invalid_calls``). 

1170 response, malformed = written_calls.without_invalid_calls(response) 

1171 if malformed: 

1172 logger.warning( 

1173 "[agent:%s] tool call(s) with unreadable arguments left " 

1174 "out: %s", 

1175 self.name, 

1176 malformed, 

1177 ) 

1178 current_messages.append(response) 

1179 new_messages.append(response) 

1180 if malformed and not response.tool_calls and not sent_back: 

1181 # Nothing else to run: asked once to call it again, or 

1182 # to answer. 

1183 sent_back = True 

1184 note = HumanMessage(content=written_calls.malformed_note(malformed)) 

1185 current_messages.append(note) 

1186 new_messages.append(note) 

1187 continue 

1188 

1189 usage = getattr(response, "usage_metadata", None) or {} 

1190 _prompt_t = usage.get("input_tokens", 0) 

1191 _compl_t = usage.get("output_tokens", 0) 

1192 _cost_usd: float | None = None 

1193 try: 

1194 import litellm as _litellm 

1195 

1196 _model_name = getattr(llm, "model_name", getattr(llm, "model", "")) 

1197 if _model_name: 

1198 _p, _c = _litellm.cost_per_token( 

1199 model=_model_name, 

1200 prompt_tokens=_prompt_t, 

1201 completion_tokens=_compl_t, 

1202 ) 

1203 _cost_usd = _p + _c 

1204 except Exception: 

1205 pass 

1206 span = LLMSpan( 

1207 agent=self.name, 

1208 model=getattr(llm, "model_name", getattr(llm, "model", "")), 

1209 iteration=iteration + 1, 

1210 latency_ms=llm_ms, 

1211 prompt_tokens=_prompt_t, 

1212 completion_tokens=_compl_t, 

1213 tool_calls=[c["name"] for c in (response.tool_calls or [])], 

1214 cost_usd=_cost_usd, 

1215 ) 

1216 span.log(logger) 

1217 

1218 if not response.tool_calls: 

1219 if structured: 

1220 text = reply_formats.text_of(response.content) 

1221 final_msg = response 

1222 else: 

1223 text, final_msg = await self._complete_if_truncated( 

1224 llm_with_tools, 

1225 current_messages[:-1], 

1226 response, 

1227 _effective_config, 

1228 ) 

1229 if final_msg is not response: 

1230 current_messages[-1] = final_msg 

1231 found = ( 

1232 reply_formats.whole_json(text) 

1233 or reader.tool_loop_answer(text, []) 

1234 if structured 

1235 else reader.tool_loop_answer(text, prose_parts) 

1236 ) 

1237 if not found.answer and not text.strip(): 

1238 found = reader.reply(final_msg) 

1239 reply_formats.log_reply(self.name, reader, found) 

1240 content = found.answer 

1241 new_messages[-1] = reader.trace(final_msg) 

1242 written = ( 

1243 written_calls.written_tool_call(content, effective_tools) 

1244 if checks_written_calls and not sent_back 

1245 else None 

1246 ) 

1247 if ( 

1248 not written 

1249 and not sent_back 

1250 and checks_written_calls 

1251 and written_calls.holds_no_answer(content) 

1252 ): 

1253 # No words at all: sent back once, the tools still 

1254 # bound. 

1255 sent_back = True 

1256 logger.warning( 

1257 "[agent:%s] a reply with no answer in it; sent back", 

1258 self.name, 

1259 ) 

1260 note = HumanMessage(content=written_calls.NO_ANSWER) 

1261 current_messages.append(note) 

1262 new_messages.append(note) 

1263 continue 

1264 if written: 

1265 # Not an answer: the call it meant to make. Sent back 

1266 # once, with the tools still bound (or, past the last 

1267 # round, to the closing call below). 

1268 sent_back = True 

1269 logger.warning( 

1270 "[agent:%s] a %s call written as text; sent back", 

1271 self.name, 

1272 written, 

1273 ) 

1274 note = HumanMessage( 

1275 content=written_calls.SEND_BACK.format(tool=written) 

1276 ) 

1277 current_messages.append(note) 

1278 new_messages.append(note) 

1279 continue 

1280 _reply_attributes(_span, found) 

1281 if _span.is_recording(): 

1282 _span.set_attribute("llm.response", str(content)[:2000]) 

1283 return content, new_messages 

1284 

1285 interim = reader.text_of(response.content).strip() 

1286 if interim: 

1287 prose_parts.append(interim) 

1288 new_messages[-1] = reader.trace(response) 

1289 logger.info( 

1290 "[agent:%s] iteration=%d tool_calls=%s interim_prose=%d chars", 

1291 self.name, 

1292 iteration + 1, 

1293 [c["name"] for c in response.tool_calls], 

1294 len(interim), 

1295 ) 

1296 

1297 # ToolNode executes all pending tool calls (parallel when multiple) 

1298 # and wraps any exception as a ToolMessage with status="error". 

1299 t0 = time.monotonic() 

1300 try: 

1301 tool_result = await tool_node.ainvoke( 

1302 {"messages": current_messages}, config=_effective_config 

1303 ) 

1304 except ClarificationRequested as asked: 

1305 # ask_user: the step ends here, and the graph asks the 

1306 # person (``__clarify__``). What it did so far goes with 

1307 # it, so the step that resumes sees its earlier calls. 

1308 asked.messages = list(new_messages) 

1309 raise 

1310 latency_ms = int((time.monotonic() - t0) * 1000) 

1311 tool_messages: list[ToolMessage] = tool_result["messages"] 

1312 

1313 if on_tool_call is not None: 

1314 from app.db.postgres.enums import ToolInvocationEnum 

1315 

1316 call_map = {c["id"]: c for c in response.tool_calls} 

1317 for tm in tool_messages: 

1318 call = call_map.get(tm.tool_call_id, {}) 

1319 tool_name = call.get("name", "") 

1320 args = call.get("args") or {} 

1321 if isinstance(args, str): 

1322 try: 

1323 args = _json.loads(args) 

1324 except Exception: 

1325 args = {} 

1326 is_error = getattr(tm, "status", None) == "error" 

1327 on_tool_call( 

1328 tool_name, 

1329 args, 

1330 tm.content, 

1331 latency_ms, 

1332 ToolInvocationEnum.Status.error 

1333 if is_error 

1334 else ToolInvocationEnum.Status.success, 

1335 tm.content if is_error else None, 

1336 # What the tool kept beside its text (a web 

1337 # search's report), which no model is sent. 

1338 artifact=getattr(tm, "artifact", None), 

1339 ) 

1340 

1341 current_messages.extend(tool_messages) 

1342 new_messages.extend(tool_messages) 

1343 if malformed: 

1344 # The calls that could not run, after the ones that did. 

1345 note = HumanMessage(content=written_calls.malformed_note(malformed)) 

1346 current_messages.append(note) 

1347 new_messages.append(note) 

1348 # A tool that says it is past its call limit is offered no 

1349 # more: every further call was another round of the whole 

1350 # prompt for the same note. 

1351 withdrawn = ( 

1352 tool_limits.spent(tm.content for tm in tool_messages) 

1353 | {t.name for t in offered if tool_limits.is_spent(t)} 

1354 ) & {t.name for t in offered} 

1355 if withdrawn: 

1356 offered = [t for t in offered if t.name not in withdrawn] 

1357 logger.info( 

1358 "[agent:%s] withdrawn at their call limit: %s", 

1359 self.name, 

1360 sorted(withdrawn), 

1361 ) 

1362 bound_tools = ( 

1363 wire.for_binding(offered, llm) if strict else list(offered) 

1364 ) 

1365 llm_with_tools = _bind(bound_tools) if offered else llm 

1366 note = HumanMessage(content=tool_limits.withdrawn_note(withdrawn)) 

1367 current_messages.append(note) 

1368 new_messages.append(note) 

1369 

1370 logger.warning( 

1371 "[agent:%s] max_iterations=%d reached; synthesising final response", 

1372 self.name, 

1373 self.max_iterations, 

1374 ) 

1375 # Tools unbound: say so, and ask for prose — a model shown its 

1376 # earlier calls as text (langchain-aws does, with no tools bound) 

1377 # otherwise writes the next one out as its answer. 

1378 synthesis_messages = current_messages + [ 

1379 HumanMessage(content=written_calls.TOOLS_SPENT) 

1380 ] 

1381 synthesis: AIMessage = await llm.ainvoke( 

1382 synthesis_messages, config=_effective_config 

1383 ) 

1384 _warn_if_truncated(self.name, synthesis) 

1385 text, _ = await self._complete_if_truncated( 

1386 llm, synthesis_messages, synthesis, _effective_config 

1387 ) 

1388 found = reader.tool_loop_answer(text, prose_parts) 

1389 reply_formats.log_reply(self.name, reader, found) 

1390 content = found.answer 

1391 written = ( 

1392 written_calls.written_tool_call(content, effective_tools) 

1393 if checks_written_calls 

1394 else None 

1395 ) 

1396 empty = ( 

1397 not written 

1398 and checks_written_calls 

1399 and written_calls.holds_no_answer(content) 

1400 ) 

1401 if written or empty: 

1402 logger.warning( 

1403 "[agent:%s] %s after the last round; asked once more for prose", 

1404 self.name, 

1405 f"a {written} call written as text" if written else "no answer", 

1406 ) 

1407 retry_messages = synthesis_messages + [ 

1408 AIMessage(content=text), 

1409 HumanMessage( 

1410 content=written_calls.TOOLS_GONE.format(tool=written) 

1411 if written 

1412 else written_calls.NO_ANSWER 

1413 ), 

1414 ] 

1415 again: AIMessage = await llm.ainvoke( 

1416 retry_messages, config=_effective_config 

1417 ) 

1418 again_text, _ = await self._complete_if_truncated( 

1419 llm, retry_messages, again, _effective_config 

1420 ) 

1421 retried = reader.tool_loop_answer(again_text, prose_parts) 

1422 if ( 

1423 retried.answer.strip() 

1424 and not written_calls.written_tool_call( 

1425 retried.answer, effective_tools 

1426 ) 

1427 and not written_calls.holds_no_answer(retried.answer) 

1428 ): 

1429 found, content = retried, retried.answer 

1430 else: 

1431 # Shipped as written; the quality check reads it. 

1432 logger.warning( 

1433 "[agent:%s] still %s", 

1434 self.name, 

1435 f"a {written} call written as text" if written else "no answer", 

1436 ) 

1437 _reply_attributes(_span, found) 

1438 if _span.is_recording(): 

1439 _span.set_attribute("llm.response", str(content)[:2000]) 

1440 final = AIMessage(content=content, name=self.name) 

1441 new_messages.append(final) 

1442 return final.content, new_messages 

1443 

1444 # ------------------------------------------------------------------ 

1445 # State management 

1446 # ------------------------------------------------------------------ 

1447 

1448 def get_state(self) -> AgentState: 

1449 return self.state 

1450 

1451 def reset_state(self) -> None: 

1452 self.state = AgentState() 

1453 

1454 def __repr__(self) -> str: 

1455 return ( 

1456 f"{type(self).__name__}(" 

1457 f"name={self.name!r}, role={self.role.value!r}, " 

1458 f"tools={len(self.tools)}, capabilities={len(self._capabilities)})" 

1459 )