Coverage for app / agents / graph.py: 90%
3044 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"""
2Dynamic agent graph builder using LangGraph.
3"""
5from __future__ import annotations
7import asyncio
8import functools
9import operator
10import re
11from collections.abc import Sequence
12from dataclasses import dataclass, field
13from datetime import date
14from functools import wraps
15from typing import Annotated, Any, Callable, Generic, Literal, Optional, TypeVar
17from langchain_core.language_models import BaseLanguageModel
18from langchain_core.messages import (
19 AIMessage,
20 BaseMessage,
21 HumanMessage,
22 SystemMessage,
23 ToolMessage,
24)
25from langchain_core.runnables import RunnableConfig
26from langchain_core.runnables import chain as lc_chain
27from langgraph.errors import GraphBubbleUp
28from langgraph.graph import END, StateGraph
29from langgraph.graph.message import add_messages
30from langgraph.types import Send
31from langgraph.types import interrupt as lg_interrupt
32from pydantic import BaseModel, Field, OnErrorOmit, create_model, field_validator
34from app import prompts
35from app.knowledge import categories as knowledge_categories_registry
36from app.knowledge import mix as knowledge_mix
37from app.knowledge import turn_report
38from app.util.knowledge_categories import KnowledgeCategory
39from app.agents import effort as effort_registry
40from app.agents import source_ledger
41from app.agents import answer_artifacts, answer_sources
42from app.agents.base import WorkerAgent, reply_text
43from app.common import web_policy
44from app.services import reply_formats
45from app.memory import render as memory_render
46from app.memory.render import RecalledMemory
47from app.tools import clarify
48from app.tools import registry as tool_registry
49from app.tools.web import platform_sources
50from app.tools.clarify import ClarifyQuestion
51from app.services import (
52 inference_routes,
53 metering,
54 model_capabilities,
55 model_errors,
56)
57from app.services.structured_output import ModelOutput, structured_call
58from app.util import attachments as attachment_util
59from app.util import safe_json, source_registry, vocab, web_search_report
60from app.util.logger import get_logger
62logger = get_logger(__name__)
64# OpenTelemetry tracer — resolves to a no-op when OTEL is not configured so
65# graph execution is unaffected in environments without Tempo.
66from opentelemetry import trace as _otel_trace # noqa: E402
68_tracer = _otel_trace.get_tracer(__name__)
71def _span_node(node_id: str, fn: Callable) -> Callable:
72 """Wrap a LangGraph async node function in an OTEL span.
74 Each node execution becomes a child span of whatever span is current in
75 the async context (typically the root execute-request span set by executor.py).
76 LiteLLM's OTEL callback then nests its own spans inside each node span,
77 giving the full invocation chain in the Tempo trace viewer.
79 Attributes set per span:
80 node.id, node.step, node.route, node.retrieval_type, node.kb_count
81 node.input — the user's query from graph state
82 node.output — node-type-specific output (plan goal, route, retrieved context, answer)
83 """
85 @wraps(fn)
86 async def _wrapped(state: Any) -> Any:
87 with _tracer.start_as_current_span(f"graph.node.{node_id}") as span:
88 if span.is_recording():
89 span.set_attribute("node.id", node_id)
90 step = getattr(state, "step_count", None)
91 if step is not None:
92 span.set_attribute("node.step", step)
93 route = getattr(state, "route", None)
94 if route:
95 span.set_attribute("node.route", route)
96 retrieval_type = getattr(state, "retrieval_type", None)
97 if retrieval_type:
98 span.set_attribute("node.retrieval_type", retrieval_type)
99 kb_count = len(getattr(state, "knowledge_bases", None) or [])
100 span.set_attribute("node.kb_count", kb_count)
101 user_input = getattr(state, "input", None)
102 if user_input:
103 span.set_attribute("node.input", str(user_input)[:2000])
104 # Every model call the node makes is marked with the pass it is
105 # on (0 first, one more per revision after the quality check),
106 # so a turn's spend can say what its revisions cost.
107 with metering.graph_pass(getattr(state, "eval_retry_count", None)):
108 result = await fn(state)
109 if span.is_recording() and isinstance(result, dict):
110 output = _extract_node_output(node_id, result)
111 if output:
112 span.set_attribute("node.output", str(output)[:2000])
113 return result
115 return _wrapped
118def _abort_on_error(node_id: str, fn: Callable) -> Callable:
119 """Wrap a node function to no-op when the pipeline has a critical error.
121 Nodes reached through unconditional edges after a failure would otherwise
122 keep burning LLM calls on poisoned state. The conditional routers
123 (_after_triage, _planning_router, _synthesis_router, _evaluator_router)
124 route to END at the next junction; this guard covers the nodes in between.
125 """
127 @wraps(fn)
128 async def _guarded(state: Any, *args: Any, **kwargs: Any) -> Any:
129 if _has_critical_error(state):
130 errors = getattr(state, "errors", None) or []
131 logger.error(
132 "[graph] ⛔ node=%s skipped — critical error in state: %s",
133 node_id,
134 errors[-1] if errors else "status=error",
135 )
136 return {}
137 return await fn(state, *args, **kwargs)
139 return _guarded
142def _name_node_messages(node_id: str, fn: Callable) -> Callable:
143 """Stamp every message a node writes with the node's id.
145 ``_history_entries`` tells the caller's conversation from this run's own
146 messages by ``name``. The node-status messages were always named, but a
147 worker's tool loop returns the model's replies unnamed — so a retrieval
148 node's summary used to read as an earlier turn of the conversation.
149 ToolMessages keep their tool name.
150 """
152 @wraps(fn)
153 async def _named(state: Any, *args: Any, **kwargs: Any) -> Any:
154 result = await fn(state, *args, **kwargs)
155 if isinstance(result, dict):
156 for message in result.get("messages") or []:
157 if isinstance(message, ToolMessage):
158 continue
159 if isinstance(message, BaseMessage) and not message.name:
160 message.name = node_id
161 return result
163 return _named
166# ---------------------------------------------------------------------------
167# Infrastructure node IDs
168# ---------------------------------------------------------------------------
170#: What __planning__ says when a single-node graph needs no plan.
171SINGLE_NODE_PLAN_NOTE = "No plan needed — one agent answers."
173GATE_NODE_ID = "__gate__"
174PLANNING_NODE_ID = "__planning__"
175RETRIEVAL_NODE_ID = "__retrieval__" # kept for backward-compat with stored traces
176#: The knowledge retrieval stage's name before it ran as lanes (October
177#: 2026). No node runs under it: it stays for stored traces and for the
178#: model-facing text that names the stage — the planner's description of
179#: it, ``ExecutionPlan.retrieval_focus`` and the agentic pass's prompt.
180INTERNAL_RETRIEVAL_NODE_ID = "__internal_retrieval__"
181EXTERNAL_RETRIEVAL_NODE_ID = "__external_retrieval__"
182TOOL_RETRIEVAL_NODE_ID = "__tool_retrieval__"
183#: Plans a turn's knowledge search once, for every lane: the query set, the
184#: documents the request names, and which kinds run (the turn's mix).
185KNOWLEDGE_PLAN_NODE_ID = "__knowledge_plan__"
186#: One retrieval node per kind of knowledge, a **lane** of the turn's mix
187#: (``knowledge.mix``): each searches and judges its own knowledge bases,
188#: side by side with the others, the web and the tools.
189LANE_NODE_IDS: dict[KnowledgeCategory, str] = {
190 category: f"__{category.value}_retrieval__" for category in KnowledgeCategory
191}
192DOMAIN_RETRIEVAL_NODE_ID = LANE_NODE_IDS[KnowledgeCategory.domain]
193TEMPORAL_RETRIEVAL_NODE_ID = LANE_NODE_IDS[KnowledgeCategory.temporal]
194REASONING_RETRIEVAL_NODE_ID = LANE_NODE_IDS[KnowledgeCategory.reasoning]
195#: Where every retrieval branch meets, once, before the answer: the lanes
196#: packed into one evidence block, then the web's section and the tools'.
197RETRIEVAL_JOIN_NODE_ID = "__retrieval_join__"
198#: Each lane's result in ``GraphState`` (one field per lane: they run in
199#: one superstep), until the join packs and clears them.
200LANE_FIELDS: dict[KnowledgeCategory, str] = {
201 category: f"{category.value}_lane" for category in KnowledgeCategory
202}
203#: The retrieval nodes a ``retrieval_type`` target runs beside the lanes.
204_RETRIEVAL_NODE_FOR: dict[str, str] = {
205 "external": EXTERNAL_RETRIEVAL_NODE_ID,
206 "tools": TOOL_RETRIEVAL_NODE_ID,
207}
208SYNTHESIS_NODE_ID = "__synthesis__"
209HITL_NODE_ID = "__hitl__"
210CLARIFY_NODE_ID = "__clarify__"
211MEMORY_READ_NODE_ID = "__memory_read__"
212MEMORY_WRITE_NODE_ID = "__memory_write__"
213EVALUATOR_NODE_ID = "__evaluator__"
215# All infrastructure node IDs. Derived constant — kept out of GraphState so it
216# cannot drift per-execution; consumers that previously read
217# ``state.system_node_ids`` should import this instead.
218SYSTEM_NODE_IDS: frozenset[str] = frozenset(
219 {
220 GATE_NODE_ID,
221 PLANNING_NODE_ID,
222 RETRIEVAL_NODE_ID,
223 INTERNAL_RETRIEVAL_NODE_ID,
224 EXTERNAL_RETRIEVAL_NODE_ID,
225 TOOL_RETRIEVAL_NODE_ID,
226 KNOWLEDGE_PLAN_NODE_ID,
227 *LANE_NODE_IDS.values(),
228 RETRIEVAL_JOIN_NODE_ID,
229 SYNTHESIS_NODE_ID,
230 EVALUATOR_NODE_ID,
231 HITL_NODE_ID,
232 CLARIFY_NODE_ID,
233 MEMORY_READ_NODE_ID,
234 MEMORY_WRITE_NODE_ID,
235 }
236)
238# Maximum number of times the evaluator may send a failed draft back to the
239# agent to revise before the agent's latest answer ships as it stands (an
240# outcome of ``failed``). Simple tasks (per triage) get a reduced budget —
241# see _eval_retry_budget. A run's own budget is its cost profile's
242# (``app/agents/effort.py``); this is the thorough profile's, the default.
243_MAX_EVAL_RETRIES = effort_registry.THOROUGH.max_eval_retries
245#: Supersteps a run may take beyond one per node per pass (see
246#: ``AgentGraphBuilder.recursion_limit``).
247_RECURSION_MARGIN = 10
249# How much of the agent's instructions the evaluator is shown.
250_EVALUATOR_INSTRUCTIONS_CHARS = 6000
251#: The earlier turns the quality check reads, and how much of each: enough
252#: to read a follow-up the way the agent did, bounded because the check runs
253#: on every substantive turn — the latest answer up to 1,200 characters,
254#: every other message 400 (at most ~2,400 characters in all).
255_EVALUATOR_HISTORY_TURNS = 2
256_EVALUATOR_TURN_CHARS = 1_200
257_EVALUATOR_EARLIER_TURN_CHARS = 400
259# Completion-token budget for the system LLM driving infrastructure nodes.
260# The system LLM defaults to the start agent's LLM, which carries the agent's
261# user-configured max_tokens (4096 by default) — sized for a chat reply, not
262# for the answer-producing nodes. __synthesis__ is told to preserve every
263# finding from the retrieved knowledge with full citations, and __evaluator__
264# must reproduce the whole revised response inside a structured tool call;
265# both routinely exceed 4096 tokens on knowledge-heavy tasks. A cap hit
266# leaves the draft cut off mid-sentence, the evaluator then fails it, and
267# its own revision is capped the same way.
268#
269# The floor is therefore raised towards _TARGET_SYSTEM_LLM_MAX_TOKENS,
270# clamped to the model's real output ceiling (LiteLLM model metadata) since
271# requesting more than the model allows is a hard API error. When the
272# ceiling is unknown (mocks, custom deployments) the conservative
273# _MIN_SYSTEM_LLM_MAX_TOKENS applies — every current provider model supports
274# at least that much output.
275_MIN_SYSTEM_LLM_MAX_TOKENS = 4096
276_TARGET_SYSTEM_LLM_MAX_TOKENS = 16384
278# LangChain chat-model class → LiteLLM provider prefix used for metadata
279# lookup. OpenAI models resolve by bare name.
280_LLM_CLASS_PROVIDER_PREFIX: dict[str, str] = {
281 "ChatAnthropic": "anthropic/",
282 "ChatGroq": "groq/",
283 "AzureChatOpenAI": "azure/",
284 "ChatBedrockConverse": "bedrock/",
285}
288def _model_output_ceiling(llm: Any) -> int | None:
289 """Return the model's maximum output tokens, if known: LiteLLM's figure,
290 held to the catalogue's for a seeded Bedrock route, whichever is lower.
291 LiteLLM's map is not the route's (gpt-oss-120b: 16,384 against the
292 16,000 it is seeded with), and a step asking a route for more than it
293 writes is refused."""
294 name = getattr(llm, "model_name", None)
295 if not isinstance(name, str) or not name:
296 name = getattr(llm, "model", None)
297 if not isinstance(name, str) or not name:
298 # ChatBedrockConverse names its model ``model_id``.
299 name = getattr(llm, "model_id", None)
300 if not isinstance(name, str) or not name:
301 return None
302 prefix = _LLM_CLASS_PROVIDER_PREFIX.get(type(llm).__name__, "")
303 candidates = [name] if not prefix else [f"{prefix}{name}", name]
304 seeded = (
305 inference_routes.seeded_output_ceiling(name)
306 if prefix == _LLM_CLASS_PROVIDER_PREFIX["ChatBedrockConverse"]
307 else None
308 )
309 try:
310 import litellm as _litellm
311 except ImportError: # pragma: no cover - litellm is a hard dependency
312 return seeded
313 for candidate in candidates:
314 try:
315 ceiling = _litellm.get_model_info(candidate).get("max_output_tokens")
316 except Exception:
317 continue
318 if isinstance(ceiling, int) and ceiling > 0:
319 return min(ceiling, seeded) if seeded else ceiling
320 return seeded
323def _system_token_floor(llm: Any) -> int:
324 """Completion budget infrastructure nodes should run with for ``llm``."""
325 ceiling = _model_output_ceiling(llm)
326 if ceiling is None:
327 return _MIN_SYSTEM_LLM_MAX_TOKENS
328 return min(_TARGET_SYSTEM_LLM_MAX_TOKENS, ceiling)
331def _declares_max_tokens(llm: Any) -> bool:
332 """Whether ``llm`` holds its own ``max_tokens``, so a copy with another
333 value changes what it sends.
335 A wrapper does not: ``with_fallbacks`` forwards the attribute from the
336 model it wraps (a ``RunnableBinding`` from the bound one), so the value
337 reads as the model's, but a copy sets it on the wrapper alone — and the
338 model it wraps sends its own.
339 """
340 return "max_tokens" in getattr(type(llm), "model_fields", {})
343def _ensure_system_token_budget(llm: Any) -> Any:
344 """Return ``llm`` with ``max_tokens`` raised to the system-node floor.
346 Returns the original object when the budget is already sufficient, the
347 attribute is absent (mocks, custom models) or not the model's own
348 (``_declares_max_tokens``: a ``with_fallbacks`` wrapper, which this
349 logged as raised while every call kept the wrapped model's cap), or the
350 model cannot be copied.
351 """
352 if llm is None or not _declares_max_tokens(llm):
353 return llm
354 current = getattr(llm, "max_tokens", None)
355 if not isinstance(current, int):
356 return llm
357 floor = _system_token_floor(llm)
358 if current >= floor:
359 return llm
360 try:
361 raised = llm.model_copy(update={"max_tokens": floor})
362 logger.info(
363 "[graph] system LLM max_tokens raised %d → %d for infrastructure nodes",
364 current,
365 floor,
366 )
367 return raised
368 except Exception as exc:
369 logger.warning("[graph] could not raise system LLM max_tokens (%s)", exc)
370 return llm
373def _deterministic(llm: Any) -> Any:
374 """Return ``llm`` at temperature 0, for the pipeline's own decisions.
376 The system LLM is the agent's model at the agent's temperature (0.7 by
377 default), so triage and the quality check varied from one run of
378 the same request to the next: a route, a scope check or a verdict is a
379 judgement to repeat, not a reply to vary. Left alone when the model takes
380 no temperature (it was dropped, and stays dropped) or cannot be copied.
381 """
382 if llm is None:
383 return llm
384 current = getattr(llm, "temperature", None)
385 if not isinstance(current, (int, float)) or isinstance(current, bool):
386 return llm
387 if current == 0:
388 return llm
389 try:
390 return llm.model_copy(update={"temperature": 0.0})
391 except Exception as exc: # noqa: BLE001 — a model we cannot copy keeps its own
392 logger.warning("[graph] could not pin system LLM temperature (%s)", exc)
393 return llm
396# Output caps for the small structured steps: retrieval's two and triage.
397# The system LLM is raised towards 16,384 tokens (``_ensure_system_token_budget``)
398# because synthesis and the quality check write whole answers; a query plan
399# or a list of relevance scores is a few hundred tokens. A reasoning model
400# that kept thinking ran each step to the raised cap — about 38 s and 17k
401# output tokens, twice in one turn. The judge gets more room than the
402# planner: a cut-off judge leaves the turn's passages unjudged, a cut-off
403# planner only loses the alternative queries.
404_QUERY_PLANNER_MAX_TOKENS = 4096
405_RERANKER_MAX_TOKENS = 8192
406#: The same for triage: a route and the task's shape, a profile of a few
407#: hundred tokens. On the raised cap a gpt-oss triage that kept reasoning ran
408#: to 16,384 tokens and 42 s, and was then discarded (the climbing-knots
409#: turn); a healthy one used about 1,850, its reasoning included.
410_CLASSIFICATION_MAX_TOKENS = 4096
411#: A model that answers without reasoning first gets less: Qwen3 235B
412#: Instruct's healthy profiles ran 120–990 tokens, and on 6 of 31 scenario
413#: turns it ran on to 4,096 tokens and 30–39 s before the reply was
414#: discarded — whitespace after its last field (``cut_replies``), which is
415#: now closed and read. 1,536 (run 5) left a scope check of four questions,
416#: 1,381 tokens, little room.
417_CLASSIFICATION_PLAIN_MAX_TOKENS = 2048
418#: The quality check's verdict is a few hundred tokens: it names problems
419#: and never writes the answer. On the answer-sized cap a revision check ran
420#: on in whitespace to 16,384 tokens and 128 s (run 5's illusions PDF).
421_CHECK_MAX_TOKENS = 4096
422_CHECK_PLAIN_MAX_TOKENS = 2048
425def _check_cap(llm: Any) -> int:
426 """The quality check's output cap for ``llm`` (``_classification_cap``'s
427 rule)."""
428 caps = model_capabilities.of_client(llm)
429 return (
430 _CHECK_MAX_TOKENS if caps.reasons_before_answering else _CHECK_PLAIN_MAX_TOKENS
431 )
434def _classification_cap(llm: Any) -> int:
435 """Triage's output cap for ``llm``: room for a model's reasoning only
436 where its reasoning counts against the cap
437 (``ModelCapabilities.reasons_before_answering``)."""
438 caps = model_capabilities.of_client(llm)
439 return (
440 _CLASSIFICATION_MAX_TOKENS
441 if caps.reasons_before_answering
442 else _CLASSIFICATION_PLAIN_MAX_TOKENS
443 )
446def _capped_llm(llm: Any, cap: int) -> Any:
447 """Return ``llm`` with ``max_tokens`` lowered to ``cap``.
449 The inverse of ``_ensure_system_token_budget``, for a step whose output
450 is small. Only the cap changes: the model, temperature and callbacks are
451 the ones the step already ran on. Returns the original object when it is
452 None, its ``max_tokens`` is not an int (mocks, custom models) or already
453 within the cap, or the model cannot be copied. A wrapper that does not
454 declare ``max_tokens`` itself (``with_fallbacks``) is left alone too
455 (``_declares_max_tokens``): a copy would cap nothing.
456 """
457 if llm is None or not _declares_max_tokens(llm):
458 return llm
459 current = getattr(llm, "max_tokens", None)
460 if not isinstance(current, int) or isinstance(current, bool) or current <= cap:
461 return llm
462 try:
463 return llm.model_copy(update={"max_tokens": cap})
464 except Exception as exc: # noqa: BLE001 — a model we cannot copy keeps its own
465 logger.warning("[graph] could not cap a step's max_tokens (%s)", exc)
466 return llm
469#: A request that asks for a derivation — where the reasoning standards
470#: (no circular assumption, consistent approximations, complete solution
471#: sets) apply.
472_DERIVATION_RE = re.compile(
473 r"\b(prove|proof|derive|derivation|find\s+all|show\s+that|solve|theorem|"
474 r"lemma|equation|integral|inequalit(y|ies))\b",
475 re.IGNORECASE,
476)
479def _needs_reasoning_standards(state: "GraphState") -> bool:
480 """Whether the answering model is given the reasoning standards.
482 They are rules for proofs and derivations, written after hard maths
483 problems went wrong, and were sent with every request — a lookup, a
484 summary, a political or privacy question — as the last thing the model
485 read. Kept where they apply: a task triage called complex, or one that
486 asks for a derivation.
487 """
488 if (state.resource_strategy or {}).get("complexity") == "complex":
489 return True
490 return bool(_DERIVATION_RE.search(state.input or ""))
493def _configured_triage_llm() -> Any:
494 """The model ``TRIAGE_MODEL`` names, at temperature 0 with the system-node
495 token budget, or None when it names none (the agent's own model
496 triages)."""
497 from app.common.settings import get_settings
499 configured = (get_settings().TRIAGE_MODEL or "").strip()
500 if "/" not in configured:
501 return None
502 provider, model = (part.strip() for part in configured.split("/", 1))
503 return _triage_llm_for(provider, model)
506def _same_provider(triage_llm: Any, agent_llm: Any) -> bool:
507 """Whether the triage model is on the agent's own provider.
509 Triage reads the whole request. A model on another provider would send
510 every agent's prompts to a provider the agent — and any routing or
511 residency rule that chose its model — never named, so the setting
512 applies only within a provider. An agent whose provider is unknown
513 triages with its own model.
514 """
515 from app.services.structured_output import provider_model
517 ours = provider_model(agent_llm)[0].lower()
518 return bool(ours) and provider_model(triage_llm)[0].lower() == ours
521@functools.lru_cache(maxsize=4)
522def _triage_llm_for(provider: str, model: str) -> Any:
523 from app.models.spec import ModelConfig
524 from app.services.llm import build_langchain_llm
526 try:
527 llm = build_langchain_llm(
528 ModelConfig(provider=provider, model=model, temperature=0.0)
529 )
530 except Exception as exc: # noqa: BLE001 — a bad setting must not break every run
531 logger.warning(
532 "[graph] TRIAGE_MODEL %s/%s could not be built (%s) — the agent's "
533 "own model triages",
534 provider,
535 model,
536 model_errors.describe(exc),
537 )
538 return None
539 return _deterministic(_ensure_system_token_budget(llm))
542#: Where a run records that a model other than the agent's own wrote its
543#: answer (an Economy profile's lighter model): ``{"provider", "model",
544#: "reason"}``, on the run's context, ``ExecuteResponse.context`` and the
545#: stream's ``done`` frame.
546ANSWERED_BY_KEY = "answered_by"
549def _lighter_llm_for(config: Any) -> Any:
550 """The model svc-core chose for an Economy profile's lighter work
551 (``lighter_model``), or None when it names none or cannot be built — the
552 run then does that work on the agent's own model, as it would without
553 the profile."""
554 if config is None:
555 return None
556 from app.models.spec import ModelConfig
557 from app.services.llm import build_langchain_llm
559 try:
560 spec = config if isinstance(config, ModelConfig) else ModelConfig(**config)
561 return build_langchain_llm(spec)
562 except Exception as exc: # noqa: BLE001 — a bad choice must not break the run
563 logger.warning(
564 "[graph] lighter model %r could not be built (%s) — the agent's own "
565 "model does its work",
566 config,
567 model_errors.describe(exc),
568 )
569 return None
572def _answered_by(llm: Any, reason: str) -> dict[str, str]:
573 """``ANSWERED_BY_KEY``'s value for an answer ``llm`` wrote."""
574 from app.services.structured_output import provider_model
576 provider, model = provider_model(llm)
577 return {"provider": provider, "model": model, "reason": reason}
580def _extract_node_output(node_id: str, result: dict) -> str:
581 """Extract a displayable output string from a node's return dict for span annotation."""
582 if node_id == SYNTHESIS_NODE_ID:
583 return str(result.get("results", {}).get(SYNTHESIS_NODE_ID, ""))
584 if node_id == PLANNING_NODE_ID:
585 plan = result.get("execution_plan", {})
586 if isinstance(plan, dict):
587 return str(plan.get("overall_goal", "") or plan.get("task_summary", ""))
588 return str(plan)
589 if node_id in (
590 RETRIEVAL_NODE_ID,
591 INTERNAL_RETRIEVAL_NODE_ID,
592 RETRIEVAL_JOIN_NODE_ID,
593 ):
594 return str(result.get("retrieval_context", ""))
595 if node_id == EXTERNAL_RETRIEVAL_NODE_ID:
596 return str(result.get("web_context", ""))
597 if node_id == TOOL_RETRIEVAL_NODE_ID:
598 return str(result.get("tool_context", ""))
599 if node_id == KNOWLEDGE_PLAN_NODE_ID:
600 planned = result.get("knowledge_plan") or {}
601 return f"{planned.get('mode', '')}: {', '.join(planned.get('lanes') or [])}"
602 if node_id == GATE_NODE_ID:
603 trivial = result.get("results", {}).get(SYNTHESIS_NODE_ID, "")
604 return str(trivial) if trivial else result.get("route", "")
605 if node_id == MEMORY_READ_NODE_ID:
606 memories = result.get("memories", [])
607 return f"recalled {len(memories)} memor{'y' if len(memories) == 1 else 'ies'}"
608 if node_id == MEMORY_WRITE_NODE_ID:
609 return str(result.get("memory_write_result", ""))
610 if node_id == EVALUATOR_NODE_ID:
611 er = result.get("results", {}).get(EVALUATOR_NODE_ID, None)
612 if hasattr(er, "final_output"):
613 score = getattr(er, "score", None)
614 passed = getattr(er, "passed", True)
615 re_count = len(getattr(er, "reasoning_errors", []) or [])
616 re_note = f" reasoning_errors={re_count}" if re_count else ""
617 critique = str(getattr(er, "critique", "") or "")
618 return f"passed={passed} score={score}{re_note} {critique[:120].replace(chr(10), ' ')}"
619 return str(er)[:200] if er else ""
620 # Skill/worker node
621 node_result = result.get("results", {}).get(node_id, "")
622 return _result_text(node_result)
625def _result_text(result: Any) -> str:
626 """Canonical text form of a node result (JSON for structured results).
628 The one way a result becomes text — for the next node, the evaluator's
629 draft and the reply itself — and it cannot raise. A structured result
630 used to reach the user as a Python repr (``{'summary': ...}``) where a
631 caller fell back to ``str()``.
632 """
633 if result is None:
634 return ""
635 if isinstance(result, str):
636 return result
637 if hasattr(result, "model_dump_json"):
638 try:
639 return result.model_dump_json()
640 except Exception: # noqa: BLE001 — a field pydantic cannot render
641 pass
642 if isinstance(result, (int, float, bool)):
643 return str(result)
644 return safe_json.dumps(result, ensure_ascii=False)
647# ---------------------------------------------------------------------------
648# Input gate — heuristic classifier + trivial-response generator
649# ---------------------------------------------------------------------------
651# Patterns that reliably indicate a non-task input, matched against the whole
652# (stripped) input. Two kinds, because only one of them is safe mid-conversation:
653#
654# * social — greetings, thanks, farewells. Answered the same whatever was
655# said before, so the canned reply is always right.
656# * replies — "yes", "no", "ok", "great", "later". On their own they mean
657# nothing to act on; after the agent has asked "Shall I draft
658# it?" they are the whole answer. They short-circuit only when
659# there is no conversation — "yes" to a question used to get
660# "Hello! How can I help you today?".
661_GREETING = (
662 r"hi+|hello+|hey+|howdy|greetings|good\s+(morning|afternoon|evening|day)|sup|yo+"
663 r"|what'?s\s+up|how'?s\s+it\s+going|how\s+are\s+you"
664)
665_THANKS = (
666 r"thanks?(\s+(you|a\s+lot|so\s+much|very\s+much))?|thank\s+you(\s+so\s+much)?"
667 r"|ty|cheers|appreciate\s+(it|that)|much\s+appreciated"
668)
669_FAREWELL = r"bye+|goodbye|good\s+bye|see\s+you|cya|farewell|take\s+care|ttyl"
670_REPLY = (
671 r"ok(ay)?|sure|sounds\s+good|got\s+it|understood|alright|alrighty|noted"
672 r"|perfect|great|cool|awesome|nice|brilliant|excellent|wonderful|fantastic"
673 r"|yep|nope|yeah|nah|yes|no|later|no\s+problem"
674)
677def _whole(pattern: str) -> re.Pattern[str]:
678 return re.compile(rf"^({pattern})[!?.]*$", re.IGNORECASE)
681_SOCIAL_RE = _whole(f"{_GREETING}|{_THANKS}|{_FAREWELL}")
682_REPLY_RE = _whole(_REPLY)
684# Inputs shorter than this word count are subjected to the pattern check;
685# longer inputs are always treated as substantive regardless of content.
686_TRIVIAL_WORD_LIMIT = 6
689def _classify_input(
690 text: str, in_conversation: bool = False
691) -> Literal["trivial", "substantive"]:
692 """Classify user input as trivial (social/greeting) or substantive (task).
694 Uses only heuristics — no LLM call — so the gate costs nothing for
695 inputs that clearly need no agent pipeline. ``in_conversation`` is True
696 when earlier turns exist: a bare reply ("yes", "great") is then an
697 answer to the agent, and goes through the pipeline.
698 """
699 stripped = text.strip()
700 if not stripped:
701 return "trivial"
702 if len(stripped.split()) > _TRIVIAL_WORD_LIMIT:
703 return "substantive"
704 if _SOCIAL_RE.match(stripped):
705 return "trivial"
706 if _REPLY_RE.match(stripped) and not in_conversation:
707 return "trivial"
708 return "substantive"
711def _trivial_response(text: str, agent_name: str = "") -> str:
712 """Generate an appropriate canned reply for a trivial input.
714 When the agent has a configured name it is used in the greeting so the
715 response is in-persona rather than generic.
716 """
717 lower = text.strip().lower().rstrip("!?.")
718 intro = f"I'm {agent_name}. " if agent_name else ""
719 if re.search(rf"\b({_FAREWELL})\b", lower):
720 return "Goodbye! Feel free to come back whenever you need help."
721 if re.search(rf"\b({_THANKS})\b", lower) or "appreciated" in lower:
722 return "You're welcome! Let me know if there's anything else I can help with."
723 if _REPLY_RE.match(lower):
724 return "Got it! Let me know what you'd like to work on."
725 # Default: greeting
726 return f"Hello! {intro}How can I help you today?"
729# ---------------------------------------------------------------------------
730# Gate routing — structured classification + router helpers
731# ---------------------------------------------------------------------------
734class RequestProfile(ModelOutput):
735 """Triage's route: which data source this request requires.
737 Its subclasses add the task's shape (``TriageProfile``), asked in the
738 same answer.
739 """
741 route: prompts.GateRoute = Field(description=prompts.GATE_ROUTE_SUMMARY)
742 # Not "reasoning": Claude 5.x can refuse an output field by that name.
743 basis: str = Field(
744 default="",
745 description="One sentence on what the route rests on, logged for observability (not used downstream)",
746 )
747 standalone_query: str = Field(
748 default="",
749 description=(
750 "The request rewritten as a self-contained query with every reference "
751 "to earlier conversation turns resolved. Copy the request verbatim when "
752 "it is already self-contained."
753 ),
754 )
757async def _classify_request_route(
758 text: str,
759 has_kbs: bool,
760 llm: Optional["BaseLanguageModel"],
761 kb_metadata: str = "",
762 history: str = "",
763 task_structure: str = "",
764 triage_schema: type[RequestProfile] = RequestProfile,
765 always_retrieve: bool = True,
766 attachments: Sequence[str] = (),
767 has_attachments: bool = False,
768) -> tuple[str, str, str, RequestProfile | None, dict[str, Any] | None]:
769 """Classify a substantive request into a route + retrieval_type pair and
770 rewrite it as a standalone query.
772 With ``task_structure`` (the triage call) the same answer also classifies
773 how the task is shaped: ``triage_schema`` is then ``TriageProfile`` or
774 ``ScopedTriageProfile``, and the fourth value is the whole profile, from
775 which the gate node reads the task's shape (``_task_shape``). It is None
776 when the call failed or only a route was asked for.
778 Uses a lightweight structured-output LLM call (``structured_call``). When
779 that fails the route comes from ``_fallback_route``: internal retrieval
780 with knowledge attached (unless the agent's ``always_retrieve`` is off),
781 and external retrieval for a request that reads as time-sensitive —
782 never a silent ``direct`` that cannot see the web.
784 Returns (route, retrieval_type, standalone_query) where:
785 route — direct | retrieve
786 retrieval_type — internal | external | tools | both
787 (only meaningful when route is 'retrieve')
788 standalone_query — history-resolved rewrite of *text* ("" when no
789 history was supplied or the call failed; callers fall back to *text*)
790 profile — the parsed profile when ``task_structure`` was given
791 note — why the call failed, for the trace
792 (``StructuredResult.failure_record``: a cut-off reply's shape
793 included); on an answer read only by closing what a cut-off reply
794 left open, ``{"recovered": "closed"}``; else None
795 """
796 from langchain_core.messages import HumanMessage as _HM
797 from langchain_core.messages import SystemMessage as _SM
799 if llm is None:
800 return (
801 *_fallback_route(text, has_kbs, always_retrieve, has_attachments),
802 "",
803 None,
804 {"reason": "no model configured"},
805 )
807 # ── KB availability section — placed FIRST so it anchors routing decisions ─
809 if has_kbs and kb_metadata:
810 kb_section = (
811 "KNOWLEDGE BASE INVENTORY\n"
812 "Internal knowledge bases ARE attached to this agent. Their contents are listed below.\n"
813 "Read this carefully before choosing a route — it determines whether internal "
814 "retrieval is relevant to the request.\n\n"
815 f"{kb_metadata}\n"
816 "RETRIEVAL BIAS RULE: If the request touches ANY topic, entity, document, or domain "
817 "covered in the knowledge bases above — even partially — prefer a route ending in "
818 "'_internal' over 'direct'. Only choose 'direct' when you are confident the KBs "
819 "contain nothing relevant to this specific request. "
820 f"{prompts.GATE_KB_PURPOSE_RULE}"
821 )
822 elif has_kbs:
823 kb_section = (
824 "KNOWLEDGE BASE INVENTORY\n"
825 "Internal knowledge bases ARE attached to this agent (metadata unavailable at routing time).\n"
826 "RETRIEVAL BIAS RULE: When the request is about domain-specific, organisational, or "
827 "proprietary information, prefer a route ending in '_internal'. Only choose 'direct' "
828 "for requests that are clearly general-purpose (maths, coding, public knowledge) with "
829 "no plausible connection to an internal knowledge base."
830 )
831 else:
832 kb_section = (
833 "KNOWLEDGE BASE INVENTORY\n"
834 "No internal knowledge bases are attached. "
835 "Never choose a route ending in '_internal' or '_both'."
836 )
838 # The same for every turn of this agent, so it can be served from cache;
839 # the conversation a follow-up needs travels with the request instead.
840 system_prompt = prompts.build_gate_routing_prompt(kb_section, task_structure)
842 _gate_date = prompts.today()
844 result = None
845 try:
846 result = await structured_call(
847 llm,
848 triage_schema,
849 [
850 _SM(content=system_prompt),
851 # The date goes with the request so the gate can correctly
852 # identify queries about "today", "current prices", "latest news" etc.
853 # as needing retrieve_external rather than direct.
854 _HM(
855 content=prompts.build_gate_request(
856 _gate_date, text, history, attachments="\n".join(attachments)
857 )
858 ),
859 ],
860 purpose=GATE_NODE_ID,
861 cache_system=True,
862 )
863 profile = result.unwrap()
865 combined = profile.route # e.g. "retrieve_internal"
867 # Parse the single combined value into (base_route, retrieval_type).
868 # The task's shape is read from the same profile by the gate node.
869 if combined.startswith("retrieve_"):
870 route = "retrieve"
871 rtype = combined[len("retrieve_") :]
872 else:
873 route = "direct"
874 rtype = "internal" # irrelevant for direct; set safe default
876 # Hard-enforce KB constraint when no KBs are available.
877 # "tools" and "external" retrieval types are KB-independent and must not be overridden.
878 if not has_kbs and rtype in ("internal", "both"):
879 rtype = "external"
881 standalone = (profile.standalone_query or "").strip() if history else ""
882 logger.info(
883 "[gate] combined=%r route=%r retrieval_type=%r standalone=%s",
884 combined,
885 route,
886 rtype,
887 # Whether the request was rewritten, never its words (or the
888 # basis, which restates them): ``app/util/logger.py``.
889 bool(standalone),
890 )
891 # A reply read only by closing what it left open is on the record.
892 note = {"recovered": result.recovered} if result.recovered else None
893 return route, rtype, standalone, (profile if task_structure else None), note
895 except Exception as exc:
896 model_errors.raise_if_fatal(exc)
897 route, rtype = _fallback_route(text, has_kbs, always_retrieve, has_attachments)
898 logger.warning(
899 "[gate] classification failed (%s) — falling back to route=%r rtype=%r",
900 model_errors.describe(exc),
901 route,
902 rtype,
903 )
904 failure = (
905 result.failure_record()
906 if result is not None and not result.ok
907 else {"reason": model_errors.describe(exc)}
908 )
909 return route, rtype, "", None, failure
912#: Words that ask about now on their own: "What's new in UK AI regulation
913#: this month?" is about what is current whatever tools triage names.
914_ABOUT_NOW_RE = re.compile(
915 r"\b(today|tonight|tomorrow|yesterday|right\s+now|latest|recent|recently|"
916 r"this\s+(week|month|year)|news|headlines?|breaking|"
917 r"what(?:'|’)?s\s+new|what\s+is\s+new|anything\s+new)\b",
918 re.IGNORECASE,
919)
920#: Words that may: "the current DPIA guidance" or "update our policy" is not
921#: news, so these count only beside a web tool triage named.
922_MAYBE_NOW_RE = re.compile(
923 r"\b(currently|current|prices?|weather|forecast|stock|shares|"
924 r"exchange\s+rate|live|update[sd]?)\b",
925 re.IGNORECASE,
926)
927#: Words that make a request time-sensitive: answered from training data they
928#: are answered wrong. Read whole when the gate's model call failed
929#: (``_fallback_route``); triage's answer reads them apart
930#: (``_needs_live_data``).
931_LIVE_DATA_RE = re.compile(
932 f"{_ABOUT_NOW_RE.pattern}|{_MAYBE_NOW_RE.pattern}", re.IGNORECASE
933)
936def _fallback_route(
937 text: str, has_kbs: bool, always: bool = True, has_attachments: bool = False
938) -> tuple[str, str]:
939 """The route when the gate could not classify the request.
941 With knowledge attached, internal retrieval always runs (the
942 retrieve-then-judge default), joined by the web when the request reads as
943 time-sensitive. Without, a time-sensitive request goes to the web and
944 anything else is answered directly. The old fallback sent every request
945 on an agent without knowledge ``direct``, so a failed gate on "what's the
946 latest on X?" was answered from training data.
948 An agent whose ``RetrievalConfig.always_retrieve`` is off searches its
949 knowledge only when triage says the request bears on it, so a failed
950 triage is no such word: it is routed as an agent without knowledge.
951 CHAINR Bot is one — a failed triage on "render pdf of different climbing
952 knots" searched its user guide and kept the page on making PDFs.
954 A message that attached documents is answered from them, unless it reads
955 as time-sensitive: "review this report" is not a knowledge search.
956 """
957 live = bool(_LIVE_DATA_RE.search(text or ""))
958 if has_attachments and not live:
959 return "direct", "internal"
960 if has_kbs and always:
961 return "retrieve", "both" if live else "internal"
962 return ("retrieve", "external") if live else ("direct", "internal")
965def _name_key(name: object) -> str:
966 """A name as a mention matches it: lower case, separators as spaces."""
967 return re.sub(r"[\s_\-]+", " ", str(name or "").strip().lower())
970def _naming(text: str, kb: dict[str, Any]) -> str:
971 """How ``text`` names ``kb`` — "knowledge base 'X'", "repository 'Y'" —
972 or "" when it does not: a whole-word match of three characters or more,
973 of its own name or a repository's that holds it."""
974 norm = f" {_name_key(text)} "
975 name = str(kb.get("name") or "").strip()
976 key = _name_key(name)
977 if len(key) >= 3 and f" {key} " in norm:
978 return f"knowledge base '{name}'"
979 for repository in kb.get("repositories") or []:
980 key = _name_key(repository)
981 if len(key) >= 3 and f" {key} " in norm:
982 return f"repository '{str(repository).strip()}'"
983 return ""
986def _named_knowledge_bases(
987 text: str, knowledge_bases: list[dict[str, Any]]
988) -> list[str]:
989 """The ids of the knowledge bases ``text`` names (:func:`_naming`): a
990 framework a request names is searched whatever its shape, and a
991 repository named is its knowledge bases named."""
992 return [str(kb.get("id", "")) for kb in knowledge_bases if _naming(text or "", kb)]
995async def _knowledge_mention_reason(
996 text: str,
997 knowledge_bases: list[dict[str, Any]],
998 attached: Sequence[str] = (),
999 attached_mentions: Sequence[str] = (),
1000) -> str:
1001 """Deterministic check that the request refers to attached knowledge.
1003 Returns a short reason ("document 'X.pdf'", "knowledge base 'Policies'") or
1004 "" when nothing is referenced. Used by the gate to override an LLM routing
1005 decision: a request that names a stored file or a KB must always run
1006 internal retrieval, regardless of how general the wording looks.
1008 ``attached`` names the documents the conversation attached: a file they
1009 name is in the agent's hands, not a knowledge base's — "review
1010 report.pdf" with report.pdf attached forced a knowledge search that then
1011 reported the report missing (24 October 2026); and a file one of them
1012 mentions (``attached_mentions``) is what that document talks about, not
1013 a file missing from the knowledge.
1014 """
1015 if not text or not knowledge_bases:
1016 return ""
1017 from app.knowledge import documents as documents_service
1019 for kb in knowledge_bases:
1020 naming = _naming(text, kb)
1021 if naming:
1022 return naming
1024 for kb in knowledge_bases:
1025 if kb.get("source_type") == "graph":
1026 continue
1027 kb_id = str(kb.get("id") or "")
1028 try:
1029 docs = await documents_service.list_documents(
1030 kb_id, manifest=kb.get("documents")
1031 )
1032 except Exception as exc: # noqa: BLE001 — override is best-effort
1033 logger.debug("[gate] document listing failed for %s: %s", kb_id, exc)
1034 continue
1035 found, unresolved = documents_service.find_mentioned_documents(
1036 text,
1037 docs,
1038 exclude=documents_service.attached_refs(attached),
1039 elsewhere=attached_mentions,
1040 )
1041 if found:
1042 return f"document '{found[0].display_name}'"
1043 if unresolved:
1044 # The user asked about a file by name; retrieval must run so the
1045 # agent can report accurately that it does not exist.
1046 return f"file mention '{unresolved[0]}'"
1047 return ""
1050def _mention_text(
1051 request: str,
1052 standalone: str,
1053 turns: list[dict[str, str]],
1054 *,
1055 own_words_only: bool,
1056) -> str:
1057 """What the gate's knowledge-mention check reads: the request, its
1058 standalone form (triage's rewrite, which already carries what a
1059 follow-up such as "and section 3?" refers to) and the previous exchange.
1061 ``own_words_only``, for a web-only triage, keeps the person's own words:
1062 the previous exchange's user message, never the assistant's reply. The
1063 reply names the agent's own sources — CHAINR Bot's ends "[1] 03-agents.md
1064 (CHAIN-R User Guide)", as the response standards ask — so a platform
1065 answer followed by "whats in the news" read as a request naming the
1066 guide, and the guide was searched instead of the web.
1067 """
1068 recent = turns[-2:]
1069 if own_words_only:
1070 recent = [m for m in recent if m.get("role") == "user"]
1071 return " ".join([request, standalone, *(m["content"] for m in recent)])
1074def _apply_knowledge_override(route: str, rtype: str, reason: str) -> tuple[str, str]:
1075 """Force internal retrieval when the request references attached knowledge."""
1076 if not reason:
1077 return route, rtype
1078 if route != "retrieve":
1079 return "retrieve", "internal"
1080 if rtype == "external":
1081 return "retrieve", "both"
1082 if rtype == "tools":
1083 return "retrieve", "internal"
1084 return route, rtype
1087_RETRIEVAL_TARGET_KEYS: tuple[str, ...] = ("internal", "external", "tools")
1090def _retrieval_config(state: Any) -> Any:
1091 """The run's retrieval settings (``RetrievalConfig``), leniently: a
1092 malformed override reads as the defaults — it never blocks retrieval."""
1093 from app.models.spec import RetrievalConfig
1095 try:
1096 return RetrievalConfig(**(getattr(state, "retrieval_config", None) or {}))
1097 except Exception as exc: # noqa: BLE001
1098 logger.warning("[graph] invalid retrieval_config (%s) — using defaults", exc)
1099 return RetrievalConfig()
1102def _retrieval_targets(rtype: str | None) -> list[str]:
1103 """Expand a ``retrieval_type`` value into the retrieval nodes to run.
1105 Accepts the legacy singletons (``internal`` / ``external`` / ``tools``),
1106 ``both`` (= internal + external) and ``+``-joined combinations such as
1107 ``internal+tools``. Unknown or empty values default to ``["internal"]``.
1108 """
1109 raw = (rtype or "internal").strip().lower()
1110 if raw == "both":
1111 return ["internal", "external"]
1112 targets = [
1113 part
1114 for part in (x.strip() for x in raw.split("+"))
1115 if part in _RETRIEVAL_TARGET_KEYS
1116 ]
1117 # Preserve canonical order so parallel fan-outs are deterministic.
1118 ordered = [k for k in _RETRIEVAL_TARGET_KEYS if k in targets]
1119 return ordered or ["internal"]
1122def _join_retrieval_targets(targets: list[str]) -> str:
1123 ordered = [k for k in _RETRIEVAL_TARGET_KEYS if k in targets]
1124 if ordered == ["internal", "external"]:
1125 return "both"
1126 return "+".join(ordered) or "internal"
1129def _apply_kb_default(
1130 route: str,
1131 rtype: str,
1132 has_kbs: bool,
1133 always: bool,
1134 keep_web_only: bool = False,
1135) -> tuple[str, str]:
1136 """Retrieve-then-judge policy: with knowledge bases attached, internal
1137 retrieval is always part of the plan (CRAG / Self-RAG). The LLM router
1138 still decides whether external sources or deterministic tools are added.
1140 ``keep_web_only`` lets a web-only route (``retrieve`` / ``external``)
1141 stand (``RetrievalConfig.respect_triage_web_route``); the caller passes
1142 it only when :func:`_web_route_hold` found nothing against it. Every
1143 other route — ``direct``, ``tools``, ``internal``, ``both`` or a
1144 ``+``-joined combination — still gains internal retrieval.
1145 """
1146 if not (has_kbs and always):
1147 return route, rtype
1148 if keep_web_only and _web_only(route, rtype):
1149 return route, rtype
1150 if route != "retrieve":
1151 return "retrieve", "internal"
1152 targets = _retrieval_targets(rtype)
1153 if "internal" not in targets:
1154 targets.append("internal")
1155 return "retrieve", _join_retrieval_targets(targets)
1158def _web_only(route: str, rtype: str) -> bool:
1159 """Whether a route reads the web and nothing else."""
1160 return route == "retrieve" and _retrieval_targets(rtype) == ["external"]
1163def _needs_live_data(
1164 triage_route: dict[str, Any], strategy: dict[str, Any], text: str = ""
1165) -> bool:
1166 """Whether a request triage answered needs current information:
1167 - triage's own route (before the gate's rules change it) reads the web;
1168 - the person's words (``text``) ask about now (``_ABOUT_NOW_RE``, or a
1169 period named): "What's new in UK AI regulation this month?" had read
1170 as a lookup when triage named no web tool;
1171 - or words that may (``_MAYBE_NOW_RE``: current, prices, update…) sit
1172 beside a web tool triage named. A named web tool alone is research,
1173 not news: asked how to prioritise a backlog, triage named all sixteen
1174 of the agent's tools.
1176 Only a triage that answered: a failed one says nothing, and recall goes
1177 on as before."""
1178 if triage_route.get("source") != "triage":
1179 return False
1180 if triage_route.get("route") == "retrieve" and "external" in _retrieval_targets(
1181 triage_route.get("retrieval_type")
1182 ):
1183 return True
1184 words = text or ""
1185 if (
1186 _ABOUT_NOW_RE.search(words)
1187 or knowledge_categories_registry.named_window(words) is not None
1188 ):
1189 return True
1190 named_web = strategy.get("source") == "triage" and any(
1191 source_ledger.tool_kind(str(tool)) == "web"
1192 for tool in strategy.get("relevant_tools") or []
1193 )
1194 return named_web and bool(_MAYBE_NOW_RE.search(words))
1197def _attachment_route_hold(
1198 route: str, triaged: bool, has_attachments: bool, mention: str
1199) -> bool:
1200 """Whether triage's ``direct`` stands against the knowledge default
1201 (``always_retrieve``): the request is about documents its message
1202 attached, triage chose to answer from them, and it names no knowledge.
1203 Searching the knowledge for "review this report" found the user guide's
1204 page on documents, and the answer reviewed that."""
1205 return route == "direct" and triaged and has_attachments and not mention
1208def _web_route_hold(
1209 respect: bool, triaged: bool, inventory_complete: bool, mention: str
1210) -> str:
1211 """Why a web-only triage may not stand on an agent with knowledge, or ""
1212 when it may.
1214 Triage read the knowledge inventory and chose the web alone: that is
1215 respected only when the choice was its own (not the fallback's), made
1216 on an inventory read in full (one that could not be read may have hidden
1217 what bears on the request), and the request names no attached document
1218 or knowledge base. ``mention`` is read from the person's own words only
1219 (``_mention_text``).
1220 """
1221 if not respect:
1222 return "respect_triage_web_route is off"
1223 if not triaged:
1224 return "triage did not answer"
1225 if not inventory_complete:
1226 return "the knowledge inventory is incomplete"
1227 if mention:
1228 return f"the request names {mention}"
1229 return ""
1232def _direct_route_hold(
1233 respect: bool,
1234 triaged: bool,
1235 inventory_complete: bool,
1236 mention: str,
1237 period: bool = False,
1238) -> str:
1239 """Why triage's ``direct`` may not stand against the knowledge default
1240 (``always_retrieve``), or "" when it may.
1242 Triage read the knowledge inventory and judged that none of it bears on
1243 the request: a dinner recipe asked of a compliance agent, a backlog
1244 question asked of a law-only one. Forcing the search anyway judged 120
1245 passages and kept none, and filed the turn as a question the knowledge
1246 could not answer. The choice stands on the same terms as a web-only one
1247 (:func:`_web_route_hold`), and not when the request names a period an
1248 agent with dated knowledge holds (``period``).
1249 """
1250 if not respect:
1251 return "respect_triage_direct_route is off"
1252 if not triaged:
1253 return "triage did not answer"
1254 if not inventory_complete:
1255 return "the knowledge inventory is incomplete"
1256 if mention:
1257 return f"the request names {mention}"
1258 if period:
1259 return "the request names a period and the agent holds dated knowledge"
1260 return ""
1263def _route_label(route: str, rtype: str) -> str:
1264 """A route as the trace reads it: ``retrieve · both``, ``direct``."""
1265 return f"{route} · {rtype}" if route == "retrieve" else route
1268#: Memories recalled for a turn (preferences come on top) and the most
1269#: characters they take together: the block reaches every answering call, so
1270#: it is held to a fixed size. A run's own are its cost profile's
1271#: (``app/agents/effort.py``); these are the thorough profile's, the default.
1272MEMORY_RECALL_LIMIT = effort_registry.THOROUGH.memory_recall_limit
1273MEMORY_BLOCK_MAX_CHARS = effort_registry.THOROUGH.memory_block_max_chars
1274#: Longest single memory sent to a model.
1275MEMORY_ITEM_MAX_CHARS = 1_500
1278#: Earlier turns an answering node replays verbatim; older ones are dropped
1279#: (uncapped history is the main cause of silent truncation on long
1280#: sessions — Packer et al. 2023, "MemGPT"). A run's own number is its cost
1281#: profile's (``app/agents/effort.py``); this is the thorough profile's.
1282_HISTORY_TURNS = effort_registry.THOROUGH.history_turns
1285def _history_entries(state: "GraphState") -> list[dict[str, str]]:
1286 """Every earlier turn of the conversation, oldest first.
1288 ``{"role", "content"}`` with role ``user`` / ``assistant`` / ``system``.
1289 Skill executions carry history in ``context["conversation_history"]``;
1290 single-agent executions seed it as LangChain messages in
1291 ``state.messages``. Those are told apart from this run's own messages by
1292 ``name``: every message a node writes carries its node id
1293 (``_name_node_messages``), so an unnamed message is history.
1294 """
1295 entries: list[dict[str, str]] = []
1296 for m in state.context.get("conversation_history", []) or []:
1297 role = str(m.get("role", ""))
1298 if role in ("user", "assistant", "model", "system"):
1299 content = _text_of(m.get("content", ""))
1300 if role in ("assistant", "model"):
1301 content = _earlier_answer(content)
1302 entries.append(
1303 {"role": "assistant" if role == "model" else role, "content": content}
1304 )
1305 if entries:
1306 return entries
1307 for m in state.messages:
1308 if getattr(m, "name", None) or isinstance(m, ToolMessage):
1309 continue
1310 if isinstance(m, HumanMessage):
1311 entries.append({"role": "user", "content": _text_of(m.content)})
1312 elif isinstance(m, SystemMessage):
1313 entries.append({"role": "system", "content": _text_of(m.content)})
1314 elif isinstance(m, AIMessage) and not getattr(m, "tool_calls", None):
1315 entries.append(
1316 {
1317 "role": "assistant",
1318 "content": _earlier_answer(reply_formats.text_of(m.content)),
1319 }
1320 )
1321 return entries
1324def _earlier_answer(text: str) -> str:
1325 """An earlier answer as a later turn reads it: without its citation
1326 markers and Sources block (``answer_sources.plain``: their ids name
1327 sources this turn was never shown), and without the working an answer
1328 stored before its model's reply format was read could still hold —
1329 harmony markers, tagged reasoning, an envelope (``cleaning.answer``,
1330 which removes only what it can tell apart; the seam rule stays with the
1331 reply format that wrote the answer, so a Claude answer is never cut)."""
1332 from app.services.reply_formats import cleaning
1334 cleaned = cleaning.answer(text, use_envelope=True, use_seam=False).text
1335 # A document is a note (it runs to thousands of characters); a visual is
1336 # replayed as written, so the agent sees what it drew. A copy of it in a
1337 # later answer is made again by its tool (``answer_artifacts``). An
1338 # answer that copied the note format this replay once used is read as
1339 # the fence it stood for.
1340 return _ARTIFACT_FENCE_RE.sub(
1341 lambda m: (
1342 _document_note(m.group(0)) if m.group(1) == _DOCUMENT_TYPE else m.group(0)
1343 ),
1344 answer_artifacts.notes_to_fences(answer_sources.plain(cleaned)),
1345 )
1348def _conversation_tail(state: "GraphState", max_turns: int = 3) -> list[dict[str, str]]:
1349 """Most recent conversation turns as ``{"role", "content"}`` dicts.
1351 At most ``max_turns`` user/assistant pairs; system notes are left out. A
1352 user message names the documents it carried and never quotes them
1353 (``attachments.describe_turn``): every reader of this — triage, the
1354 planner, the quality check, memory — cut an earlier message to its first
1355 few hundred characters, which for one that pasted a document were the
1356 document's.
1357 """
1358 turns = [
1359 {**e, "content": attachment_util.describe_turn(e["content"])}
1360 if e["role"] == "user"
1361 else e
1362 for e in _history_entries(state)
1363 if e["role"] != "system"
1364 ]
1365 return turns[-(max_turns * 2) :]
1368def _windowed(
1369 entries: list[dict[str, str]], max_turns: int, block: int | None
1370) -> list[dict[str, str]]:
1371 """The newest ``max_turns`` turns of ``entries`` (two entries a turn).
1373 With ``block``, the window's start moves ``block`` turns at a time
1374 rather than one, anchored at the first turn: it keeps between
1375 ``max_turns`` and ``max_turns + block - 1`` turns, and starts at the
1376 same turn for ``block`` turns running, so a provider can serve the
1377 replayed history from cache.
1378 """
1379 keep = max(0, max_turns) * 2
1380 start = max(0, len(entries) - keep)
1381 if block and block > 1 and start:
1382 start -= start % (block * 2)
1383 return entries[start:]
1386def _history_messages(
1387 state: "GraphState", max_turns: int | None = None
1388) -> tuple[list[BaseMessage], list[str]]:
1389 """What an answering node replays of the conversation: ``(turns, notes)``.
1391 ``turns`` are the person's and the agent's earlier messages, oldest first
1392 and capped — and nothing else. This run's own messages never appear:
1393 system-node status lines, error text, retrieval summaries and earlier
1394 nodes' outputs were once replayed here as turns the agent had said, so a
1395 planner failure reached the answering model as its own previous reply.
1396 Node outputs travel in the task content (``_aggregate_prior_results``)
1397 and evidence in ``<knowledge>``.
1399 ``notes`` are system messages that arrived with the history. They go into
1400 the node's system context instead of their place in the thread: Anthropic
1401 refuses a system message after the first turn.
1402 """
1403 effort = effort_registry.of_state(state)
1404 if max_turns is None:
1405 max_turns = effort.history_turns
1406 entries = _history_entries(state)
1407 notes = [
1408 e["content"] for e in entries if e["role"] == "system" and e["content"].strip()
1409 ]
1410 turns = _windowed(
1411 [e for e in entries if e["role"] != "system"],
1412 max_turns,
1413 effort.history_block_turns,
1414 )
1415 messages: list[BaseMessage] = [
1416 HumanMessage(content=e["content"])
1417 if e["role"] == "user"
1418 else AIMessage(content=e["content"])
1419 for e in turns
1420 ]
1421 return messages, notes
1424#: The context key a node's ``history_turns_omitted`` travels under — read
1425#: by its ``node_end`` frame into the turn's decision record.
1426HISTORY_OMITTED_KEY = "history_turns_omitted"
1429def _history_figure(agent: Any) -> dict[str, int]:
1430 """The earlier turns ``agent``'s answer could not carry
1431 (``token_budget``), for the node's state update — nothing when none."""
1432 omitted = getattr(agent, "history_turns_omitted", 0)
1433 return (
1434 {HISTORY_OMITTED_KEY: omitted} if isinstance(omitted, int) and omitted else {}
1435 )
1438def _conversation_notes_block(notes: list[str]) -> str:
1439 """System notes from the history as one XML block (CDATA-wrapped)."""
1440 if not notes:
1441 return ""
1442 body = "\n\n".join(n.replace("]]>", "]]]]><![CDATA[>") for n in notes)
1443 return (
1444 '<conversation_notes note="System messages supplied with the '
1445 'conversation history.">\n<![CDATA[\n' + body + "\n]]>\n</conversation_notes>"
1446 )
1449def _text_of(content: Any) -> str:
1450 if isinstance(content, str):
1451 return content
1452 if isinstance(content, list):
1453 return " ".join(
1454 b.get("text", "") if isinstance(b, dict) else str(b) for b in content
1455 )
1456 return str(content)
1459def _history_text(turns: list[dict[str, str]], per_turn_chars: int = 500) -> str:
1460 lines = []
1461 for m in turns:
1462 label = "User" if m["role"] == "user" else "Assistant"
1463 lines.append(f"{label}: {m['content'][:per_turn_chars]}")
1464 return "\n".join(lines)
1467_ANAPHORA_RE = re.compile(
1468 r"(^\s*(and|also|then|now|ok(ay)?|what about|how about)\b)|"
1469 r"\b(it|its|that|this|these|those|they|them|same|above|previous|earlier|again|"
1470 r"more|also|what about|and for|how about|section|chapter|page|table|figure|part|"
1471 r"the (document|file|report|one|other|second|third|first|last))\b",
1472 re.IGNORECASE,
1473)
1476def _heuristic_standalone_query(text: str, turns: list[dict[str, str]]) -> str:
1477 """No-LLM fallback for conversational query reformulation.
1479 Short follow-ups that lean on references ("and section 3?") are
1480 prefixed with the previous user question so retrieval keeps the topic.
1481 """
1482 if not turns:
1483 return text
1484 words = text.split()
1485 if len(words) <= 12 and _ANAPHORA_RE.search(text):
1486 prev_user = next(
1487 (m["content"] for m in reversed(turns) if m["role"] == "user"), ""
1488 )
1489 if prev_user and prev_user.strip().lower() != text.strip().lower():
1490 return f"{prev_user.strip()[:300]} — follow-up: {text.strip()}"
1491 return text
1494#: The longest query internal retrieval plans, judges and reranks with.
1495_MAX_RETRIEVAL_QUERY_CHARS = 2_000
1498def _attachment_mentions(state: "GraphState") -> list[str]:
1499 """The file names the conversation's documents mention: a request about
1500 one is about what the document says of it, not a file of the knowledge
1501 to report missing — the report's ``manifest.json`` was reported missing
1502 beside the report itself (24 October 2026)."""
1503 from app.knowledge import documents as documents_service
1505 found: list[str] = []
1506 for a in state.attachments:
1507 if a.readable:
1508 for name in documents_service.filename_mentions(a.text):
1509 if name not in found:
1510 found.append(name)
1511 return found
1514def _attached_hint(state: "GraphState") -> str:
1515 """What a retrieval worker is told of the conversation's documents: their
1516 names and a preview — it searches for what the request needs beyond
1517 them, and the answering node reads them whole."""
1518 lines = attachment_util.manifest_lines(state.attachments)
1519 if not lines:
1520 return ""
1521 return (
1522 "\nThe person attached these documents (the answer is written from "
1523 "them; search only for what the request needs beyond them):\n"
1524 + "\n".join(lines)
1525 )
1528def _context_window(llm: Any) -> int | None:
1529 """``llm``'s context window, when the catalogue or LiteLLM knows it."""
1530 if llm is None:
1531 return None
1532 try:
1533 from app.services import token_budget
1535 return token_budget.limits_for(llm).context_window
1536 except Exception: # noqa: BLE001 — the default budget stands
1537 return None
1540def _attachment_tools(state: "GraphState", llm: Any) -> list[Any]:
1541 """``read_attachment`` and ``search_attachments`` over the conversation's
1542 documents, for an answering step on ``llm`` — whenever it has a document,
1543 so the tools an agent holds do not change once one is attached (their
1544 descriptions name none: ``app/tools/attachments.py``). None without."""
1545 if not state.attachments:
1546 return []
1547 from app.tools.attachments import make_attachment_tools
1549 return make_attachment_tools(state.attachments, _context_window(llm))
1552def _bundle_sufficient(bundle: Any) -> bool:
1553 """Whether the deterministic pipeline's evidence leaves the agentic
1554 gap-filling pass (hybrid mode) nothing to fill: it found something, no
1555 search failed, and every document the request names was found and is in
1556 the evidence.
1558 It used to count passages too (three), so a request one passage answered
1559 — most of them — paid for a tool loop that searched the same knowledge
1560 again. What the count stood for is what the pipeline can say it missed.
1561 """
1562 if bundle is None or bundle.is_empty:
1563 return False
1564 if bundle.errors or bundle.unresolved_mentions:
1565 return False
1566 return all(t.get("coverage") != "none" for t in bundle.targeted_documents)
1569def _retrieval_report(bundle: Any) -> dict[str, Any]:
1570 """What a pipeline run went without, for the trace (the join's
1571 ``system_node_result`` frame) and the answering node.
1573 ``planner_failure`` / ``judge_failure``: the query planner or relevance
1574 judge failed (one line each, empty when it ran). ``degraded``: search
1575 legs that could not run. ``judged_out``: passages the judge ruled out.
1576 Each was in the logs only: a turn whose judge failed answered from
1577 passages nobody had checked, and nothing said so.
1578 """
1579 report: dict[str, Any] = {
1580 "planner_failure": bundle.planner_failure,
1581 "judge_failure": bundle.judge_failure,
1582 "degraded": list(bundle.degraded),
1583 "judged_out": bundle.judged_out,
1584 }
1585 # How each lane of the turn's mix fared in packing (the join's frame
1586 # draws it): its budget, what it used, what it packed and took over.
1587 if bundle.lanes:
1588 report["lanes"] = bundle.lanes
1589 failed = [
1590 f"{stage} failed ({failure})"
1591 for stage, failure in (
1592 ("query planner", bundle.planner_failure),
1593 ("relevance judge", bundle.judge_failure),
1594 )
1595 if failure
1596 ] + list(bundle.degraded)
1597 if failed:
1598 logger.warning(
1599 "[graph] node=%s retrieval ran with less: %s",
1600 RETRIEVAL_JOIN_NODE_ID,
1601 "; ".join(failed),
1602 )
1603 return report
1606def _has_critical_error(state: "GraphState") -> bool:
1607 """True when execution has hit a non-recoverable failure.
1609 Critical means a skill node or synthesis raised (``status == "error"``).
1610 Retrieval failures are deliberately NOT critical — they degrade to an
1611 empty ``retrieval_context`` and the pipeline continues, which is the
1612 desired behaviour for a missing data source.
1613 """
1614 return state.status == "error"
1617#: Retrieval a plain agent does for itself. It holds web search and its own
1618#: tools — an evaluation case's scripted ones included — so a pre-step that
1619#: searched the web or called the general tools first did the same work with
1620#: the real tools, never the agent's, summarised what came back, and told the
1621#: agent to reuse it. It also ran when the caller had asked for no tools.
1622_AGENT_OWN_RETRIEVAL = frozenset({"external", "tools"})
1625def _plain_agent_route(route: str, rtype: str) -> tuple[str, str]:
1626 """A plain agent's route: knowledge-base retrieval only. With nothing
1627 left to pre-retrieve, the agent answers directly, with its tools."""
1628 if route != "retrieve":
1629 return route, rtype
1630 kept = [t for t in _retrieval_targets(rtype) if t not in _AGENT_OWN_RETRIEVAL]
1631 if not kept:
1632 return "direct", "internal"
1633 return "retrieve", "+".join(kept)
1636def _pinned_skill_route(route: str, rtype: str) -> tuple[str, str]:
1637 """A pinned skill's route when one of its steps searches the web itself:
1638 knowledge and tools pre-retrieved, never the web. A chat command runs
1639 every step in order, and Research brief's ``research`` step searched again
1640 after ``__external_retrieval__`` had: 18 web calls for one brief."""
1641 if route != "retrieve":
1642 return route, rtype
1643 kept = [t for t in _retrieval_targets(rtype) if t != "external"]
1644 if not kept:
1645 return "direct", "internal"
1646 return "retrieve", "+".join(kept)
1649#: How much of each tool result a retrieval step passes on, and of all of
1650#: them together. The evidence is what downstream nodes answer from, so a
1651#: result is kept whole where it fits; the caps bound what one search can add
1652#: to every later prompt.
1653_EVIDENCE_ITEM_CHARS = 4000
1654_EVIDENCE_TOTAL_CHARS = 16000
1657def _message_text(msg: Any) -> str:
1658 content = getattr(msg, "content", "")
1659 if isinstance(content, str):
1660 return content
1661 if isinstance(content, list):
1662 return "\n".join(
1663 str(b.get("text", "")) if isinstance(b, dict) else str(b) for b in content
1664 )
1665 return str(content or "")
1668def _pass_findings(messages: list[Any]) -> str:
1669 """The results of the join's agentic pass that found something, as
1670 evidence (``_retrieval_evidence`` with no notes): a search with results,
1671 a document read, a graph walked — never a listing of names, "No results"
1672 or "No document named …", and never the pass's own reply."""
1673 from app.tools import registry as tool_registry
1675 kept = []
1676 for msg in messages:
1677 if getattr(msg, "tool_call_id", None) is None:
1678 continue
1679 if getattr(msg, "status", "success") == "error":
1680 continue
1681 name = str(getattr(msg, "name", "") or "")
1682 text = _message_text(msg).strip()
1683 if name == tool_registry.SEARCH_KNOWLEDGE_TOOL:
1684 artifact = getattr(msg, "artifact", None) or []
1685 if not any(
1686 isinstance(entry, dict) and entry.get("found") for entry in artifact
1687 ):
1688 continue
1689 elif name == tool_registry.READ_DOCUMENT_TOOL:
1690 if not text.startswith("# "):
1691 continue
1692 elif name != tool_registry.EXPLORE_GRAPH_TOOL or not text:
1693 continue
1694 kept.append(msg)
1695 return _retrieval_evidence(kept, "")
1698def _unstreamed_config(config: RunnableConfig | None) -> RunnableConfig:
1699 """``config`` for a call whose text is the pipeline's, never the
1700 person's: the stream leaves it out (``UNSTREAMED_TAG``). A retrieval
1701 worker's write-up had streamed into the chat ahead of the answer."""
1702 from langchain_core.runnables.config import merge_configs
1704 from app.services.reply_formats import UNSTREAMED_TAG
1706 return merge_configs(config, {"tags": [UNSTREAMED_TAG]})
1709def _retrieval_evidence(messages: list[Any], notes: str) -> str:
1710 """What a web or tool retrieval step passes on: the tool results
1711 themselves, then the worker's summary as notes.
1713 It passed only the summary, so a downstream node could not quote a page,
1714 read a figure the summary dropped, or see that the summary had it wrong.
1715 Results are kept in the order they arrived, each up to
1716 ``_EVIDENCE_ITEM_CHARS`` and all up to ``_EVIDENCE_TOTAL_CHARS``.
1717 """
1718 parts: list[str] = []
1719 used = 0
1720 for msg in messages:
1721 if getattr(msg, "tool_call_id", None) is None:
1722 continue
1723 text = _message_text(msg).strip()
1724 if not text:
1725 continue
1726 excerpt = text[:_EVIDENCE_ITEM_CHARS]
1727 if len(text) > _EVIDENCE_ITEM_CHARS:
1728 excerpt += " …[truncated]"
1729 if used + len(excerpt) > _EVIDENCE_TOTAL_CHARS:
1730 break
1731 used += len(excerpt)
1732 name = str(getattr(msg, "name", "") or "tool")
1733 # Headed by tool, never numbered: a number reads as a citation
1734 # marker, and each result carries its own source ids (``Cite as:``).
1735 parts.append(f"### {name} result\n{excerpt}")
1736 notes = (notes or "").strip()
1737 if notes:
1738 parts.append(
1739 "### Retrieval notes (a summary of the results above; where they "
1740 f"differ, the results win)\n{notes}"
1741 )
1742 return "\n\n".join(parts)
1745def _gate_router(state: "GraphState") -> str:
1746 """Out of triage (``__gate__``): a trivial input is answered and ends the
1747 run; anything else goes where the task's shape sends it
1748 (:func:`_after_triage`). Retrieval itself is dispatched after planning,
1749 from ``route`` and ``retrieval_type``."""
1750 if state.route == "trivial":
1751 return "trivial"
1752 return _after_triage(state)
1755def _after_triage(state: "GraphState") -> str:
1756 """Where a classified request goes: the clarify node when triage's scope
1757 check has questions, else the skill-graph shortcut or planning.
1759 The ``use_skill_graph=False`` shortcut is only valid for ``direct`` routes.
1760 For any retrieve route the pipeline must run retrieval before synthesis
1761 can produce a meaningful answer — short-circuiting here would skip
1762 retrieval entirely and leave synthesis with no context.
1763 """
1764 if _has_critical_error(state):
1765 return "abort"
1766 # Triage found the request's scope ambiguous and proposed questions; the
1767 # clarify node asks them and comes back here once they are answered
1768 # (it clears ``pending_clarification``), so the destination below is
1769 # decided once, for both paths.
1770 if state.pending_clarification:
1771 return "clarify"
1772 strategy = state.resource_strategy
1773 if (
1774 strategy
1775 and not strategy.get("use_skill_graph", True)
1776 and state.route == "direct"
1777 ):
1778 return "direct_answer"
1779 return "to_planning"
1782def _skill_dispatch_router(state: "GraphState") -> str:
1783 """Post-planning/retrieval dispatch into the skill graph — or past it.
1785 The planner has full authority over skill-node execution: when
1786 ``active_node_ids`` is empty (a successful plan that selected no skill
1787 nodes), the skill graph is bypassed entirely and __synthesis__ produces
1788 the final answer directly from the retrieved context. This avoids a
1789 generic relay node re-summarising (and degrading) retrieval output.
1790 Planning failures never produce an empty list — the planning node's
1791 fallback explicitly dispatches every registered skill node.
1792 """
1793 if _has_critical_error(state):
1794 return "abort"
1795 return "to_skill" if state.active_node_ids else "to_synthesis"
1798def _planning_router(state: "GraphState") -> str | list[Send]:
1799 """Conditional-edge function for the planning node.
1801 ``direct`` routes skip retrieval and jump straight to the skill graph —
1802 or to __synthesis__ when the planner dispatched no skill nodes.
1803 ``retrieve`` routes proceed to retrieval as ``state.retrieval_type`` (set
1804 by the gate) says:
1806 * one that searches the agent's knowledge goes to ``__knowledge_plan__``,
1807 which plans the search and starts its lanes, the web and the tools
1808 side by side (``_knowledge_plan_router``);
1809 * one that does not runs the web and the tools in parallel via the Send
1810 API: independent sources, so running them in turn only adds latency.
1812 Every branch meets in ``__retrieval_join__``, which runs once after all
1813 of them and hands on one evidence block.
1814 """
1815 if _has_critical_error(state):
1816 return "abort"
1817 if state.route == "direct":
1818 return _skill_dispatch_router(state) # "to_skill" | "to_synthesis"
1819 targets = _retrieval_targets(state.retrieval_type)
1820 if "internal" in targets:
1821 return "knowledge"
1822 if len(targets) > 1:
1823 return [Send(_RETRIEVAL_NODE_FOR[t], state) for t in targets]
1824 return targets[0] # "external" | "tools"
1827def _knowledge_plan_router(state: "GraphState") -> str | list[Send]:
1828 """Out of ``__knowledge_plan__``: a Send to each lane it planned, and on
1829 a first pass to the web and the tools the route also asked for — every
1830 branch one node deep, so all of them run in one superstep and the join
1831 runs once after them. A corrective pass (``mode`` ``gap``) re-runs its
1832 evidence lanes only. With nothing to send (the agentic mode plans no
1833 lanes), straight to the join."""
1834 if _has_critical_error(state):
1835 return "abort"
1836 planned = state.knowledge_plan or {}
1837 sends: list[Send] = [
1838 Send(LANE_NODE_IDS[category], state)
1839 for category in KnowledgeCategory
1840 if category.value in (planned.get("lanes") or ())
1841 ]
1842 if planned.get("mode") != "gap":
1843 sends += [
1844 Send(_RETRIEVAL_NODE_FOR[target], state)
1845 for target in _retrieval_targets(state.retrieval_type)
1846 if target in _RETRIEVAL_NODE_FOR
1847 ]
1848 return sends or "join"
1851def _synthesis_router(state: "GraphState") -> str:
1852 """Conditional-edge function for terminal skill nodes.
1854 Synthesis runs when ``state.needs_synthesis`` is True — set by triage
1855 based on task complexity (Adaptive RAG, Jeong et al. 2024) and force-set
1856 by __planning__ when it dispatches multiple skill nodes. Routes to END
1857 when a critical error occurred in the skill graph.
1858 """
1859 # A step asked the person something (``ask_user``): nothing more runs
1860 # on a half-done answer until ``__clarify__`` has asked it.
1861 if state.pending_clarification:
1862 return "clarify"
1863 if _has_critical_error(state):
1864 return "abort"
1865 return "synthesise" if state.needs_synthesis else "skip"
1868def _clarify_router(state: "GraphState") -> str:
1869 """Out of ``__clarify__``: a question an agent asked mid-task goes back
1870 to the skill graph, which runs again with the answers; the up-front scope
1871 check goes on as triage would have."""
1872 from app.tools.clarify import SOURCE_TOOL
1874 last = state.clarifications[-1] if state.clarifications else {}
1875 if isinstance(last, dict) and last.get("source") == SOURCE_TOOL:
1876 return "resume"
1877 return _after_triage(state)
1880def _eval_retry_budget(state: "GraphState") -> int:
1881 """Retry budget scaled by task complexity (classified by triage).
1883 Simple tasks get a single retry: re-running the skill graph over a
1884 one-question lookup rarely changes the answer, and the evaluator's
1885 in-place revision is almost always sufficient. Both numbers are the
1886 run's cost profile's (``app/agents/effort.py``).
1887 """
1888 effort = effort_registry.of_state(state)
1889 complexity = (state.resource_strategy or {}).get("complexity", "moderate")
1890 return (
1891 effort.simple_eval_retries
1892 if complexity == "simple"
1893 else effort.max_eval_retries
1894 )
1897def _evaluator_router(state: "GraphState") -> str:
1898 """Conditional-edge function for the evaluator node.
1900 A failed draft goes back to the agent to revise while the
1901 complexity-scaled retry budget lasts; the verdict (gaps, reasoning
1902 errors, critique) reaches it as a revision note through
1903 ``_aggregate_prior_results``. Once the budget is spent the agent's latest
1904 answer ships as it stands. The evaluator never writes the answer: its
1905 rewrite used to ship on any "minor" failure, written without the agent's
1906 instructions, tools or the material the user supplied.
1907 """
1908 if _has_critical_error(state):
1909 return "abort"
1910 er = state.results.get(EVALUATOR_NODE_ID)
1911 if getattr(er, "passed", True):
1912 return "accept"
1913 if not _final_verdict(False, state.eval_retry_count, _eval_retry_budget(state)):
1914 if _knowledge_can_fill_gaps(state, er):
1915 return "retry_retrieval"
1916 # When the planner skipped the skill graph, the retry re-runs
1917 # __synthesis__ (the answer-producing node on that path) instead —
1918 # as it does when synthesis wrote the draft and its problems are the
1919 # summary's own (``_summary_can_fix``).
1920 if not state.active_node_ids or _summary_can_fix(state, er):
1921 return "retry_synthesis"
1922 return "retry"
1923 return "accept"
1926def _summary_can_fix(state: "GraphState", verdict: Any) -> bool:
1927 """Whether a failed check names only what synthesis can fix in its own
1928 summary of the skill graph's work: synthesis wrote the draft, and no gap
1929 is missing content (``missing``), which needs the steps run again.
1931 Research brief's summary failed twice on its claims about its own
1932 report, and each failure re-ran the whole skill — plan, research, write,
1933 publish: 43 tool calls, $0.15 after the check (scenario run 6). A gap
1934 whose kind went unrecorded counts as missing, so a verdict from before
1935 kinds re-runs the skill as it did."""
1936 if SYNTHESIS_NODE_ID not in state.results:
1937 return False
1938 gaps = list(getattr(verdict, "gaps", None) or [])
1939 kinds = list(getattr(verdict, "gap_kinds", None) or [])
1940 return len(kinds) >= len(gaps) and "missing" not in kinds[: len(gaps)]
1943def _knowledge_can_fill_gaps(state: "GraphState", verdict: Any) -> bool:
1944 """Whether corrective retrieval (CRAG) can help a failed draft: search
1945 the knowledge bases again for the gaps the evaluator named, before the
1946 agent revises — re-running the skill graph over the same evidence
1947 rarely helps.
1949 Only where the knowledge is where the answer came from:
1951 * not when the web answered (``source_ledger.web_answered``): the gaps
1952 in a web answer are the web's to fill, and the agent revises with its
1953 own tools. Searching the knowledge for today's headlines handed CHAINR
1954 Bot its user guide's page on the News repository as evidence;
1955 * only when this turn searched the knowledge and found something
1956 (``KNOWLEDGE_SEARCHED_KEY``) — a turn that never retrieved has no
1957 evidence for a gap to be missing from;
1958 * not when the judge found the knowledge holds nothing for this request
1959 (``KNOWLEDGE_NOT_RELEVANT_KEY``): searching it again finds the same
1960 (CRAG's "incorrect" action);
1961 * only when the turn searched evidence (``_evidence_lanes``): a gap is a
1962 missing fact, and a framework holds none;
1963 * not for a request about now that made no web search
1964 (``UNSEARCHED_LIVE_GAP``): the knowledge already answered it with
1965 what was indexed.
1966 """
1967 if source_ledger.web_answered(state.messages):
1968 return False
1969 # A request about now that searched no web: the web is where to look.
1970 if UNSEARCHED_LIVE_GAP in (getattr(verdict, "gaps", None) or []):
1971 return False
1972 return bool(
1973 state.knowledge_bases
1974 and getattr(verdict, "gaps", None)
1975 and not state.context.get(KNOWLEDGE_NOT_RELEVANT_KEY)
1976 and state.context.get(KNOWLEDGE_SEARCHED_KEY)
1977 and _evidence_lanes(_turn_mix(state))
1978 )
1981def _turn_mix(state: "GraphState") -> knowledge_mix.Mix:
1982 """The turn's mix (``knowledge.mix``), as the gate decided it — or, for
1983 a turn checkpointed before it had one, decided now from the turn."""
1984 return knowledge_mix.Mix.read(
1985 state.context.get(knowledge_mix.MIX_KEY)
1986 ) or knowledge_mix.decide(
1987 state.knowledge_bases,
1988 knowledge_categories_registry.RetrievalTurn.read(
1989 state.context.get(KNOWLEDGE_TURN_KEY)
1990 ),
1991 internal=True,
1992 cfg=_retrieval_config(state),
1993 effort=effort_registry.of_state(state),
1994 empty=state.empty_kb_ids,
1995 )
1998def _lane_query_counts(
1999 lanes: Sequence[knowledge_mix.Lane],
2000) -> dict[KnowledgeCategory, int]:
2001 """Each lane's kind and how many queries it runs, in the mix's order,
2002 for planning the lanes' own queries (``RetrievalPipeline.plan``)."""
2003 return {
2004 KnowledgeCategory(lane.category): lane.max_queries
2005 for lane in lanes
2006 if lane.kb_ids and lane.category in KnowledgeCategory._value2member_map_
2007 }
2010def _evidence_lanes(mix: knowledge_mix.Mix) -> list[knowledge_mix.Lane]:
2011 """The mix's lanes that search evidence (primary and supporting), never
2012 a method: what a corrective pass can search for a missing fact."""
2013 return [lane for lane in mix.lanes if lane.role in knowledge_mix.EVIDENCE_SHARES]
2016# ---------------------------------------------------------------------------
2017# Structured planning models
2018# ---------------------------------------------------------------------------
2021class NodePlan(ModelOutput):
2022 """Planned specification for one dispatched skill node."""
2024 node_id: str = Field(description="Node identifier this plan applies to")
2025 goal: str = Field(description="Specific objective this node must achieve")
2026 expected_output: str = Field(
2027 default="",
2028 description="Required format and content of this node's output",
2029 )
2030 success_criteria: str = Field(
2031 default="",
2032 description="Measurable criteria for evaluating whether this node succeeded",
2033 )
2036class ToolGuidance(ModelOutput):
2037 """The builtin tools recommended for one skill node."""
2039 node_id: str = Field(description="The skill node these tools are for")
2040 tools: list[str] = Field(
2041 default_factory=list, description="Builtin tool names, most useful first"
2042 )
2045class ExecutionPlan(ModelOutput):
2046 """Structured execution plan produced by __planning__ before the graph runs.
2048 Everything that is empty for a simple request has a default. The prompt
2049 tells the planner to leave ``active_nodes`` empty for a lookup and to plan
2050 only the nodes it dispatches, so the correct plan for a simple question
2051 has no ``node_plans`` — a field that was once required, and rejected
2052 exactly the plans it asked for.
2053 """
2055 task_summary: str = Field(description="One-sentence summary of the task")
2056 overall_goal: str = Field(
2057 description="What the complete execution must deliver to the user"
2058 )
2059 retrieval_focus: str = Field(
2060 default="",
2061 description=(
2062 "Entity types, entity names, or specific topics to prioritise during "
2063 "INTERNAL knowledge base retrieval. Used by __internal_retrieval__ to "
2064 "query KBs precisely. Leave empty when retrieval_type is 'external'."
2065 ),
2066 )
2067 external_retrieval_focus: str = Field(
2068 default="",
2069 description=(
2070 "Specific queries, keywords, or topics to search for in EXTERNAL sources "
2071 "(web search, live APIs). Used by __external_retrieval__. "
2072 "Leave empty when retrieval_type is 'internal'."
2073 ),
2074 )
2075 # OnErrorOmit: one malformed node plan is dropped, not the whole plan.
2076 node_plans: list[OnErrorOmit[NodePlan]] = Field(
2077 default_factory=list,
2078 description=(
2079 "One plan per skill node listed in active_nodes, in dispatch order. "
2080 "Empty when active_nodes is empty."
2081 ),
2082 )
2083 # A list of items, not a node_id → tools map: strict decoding cannot
2084 # express a map with free keys (Anthropic's schema transform empties it,
2085 # OpenAI's strict mode refuses it). ``guidance_map`` gives the map.
2086 tool_guidance: list[ToolGuidance] = Field(
2087 default_factory=list,
2088 description=(
2089 "Builtin tools the planner recommends, one entry per dispatched skill "
2090 "node. Surfaced in each node's execution plan so the worker knows which "
2091 "tools are most relevant to the current task."
2092 ),
2093 )
2094 active_nodes: list[str] = Field(
2095 default_factory=list,
2096 description=(
2097 "Skill node IDs that should actually execute for this task. "
2098 "List ONLY nodes whose specialised role adds genuine value beyond "
2099 "retrieval + synthesis — unlisted nodes are skipped entirely. "
2100 "Leave EMPTY to skip the skill graph: the pipeline then synthesises "
2101 "the final answer directly from the retrieved context, which is the "
2102 "right choice for lookups, factual questions, and summaries. "
2103 "Never include system node IDs here (__retrieval__, __synthesis__, etc.)."
2104 ),
2105 )
2107 @field_validator("tool_guidance", mode="before")
2108 @classmethod
2109 def _coerce_tool_guidance(cls, v: Any) -> Any:
2110 """Read the shapes models actually send, drop the rest.
2112 Guidance is advisory — a node keeps its own tools without it — so an
2113 unreadable entry is dropped rather than failing the plan. A
2114 ``{node_id: tools}`` map (the old shape, and what a model reaches for
2115 under function calling) is read as items; a bare string is one tool.
2116 """
2117 if isinstance(v, dict):
2118 v = [{"node_id": node_id, "tools": tools} for node_id, tools in v.items()]
2119 if not isinstance(v, list):
2120 return []
2121 items: list[dict[str, Any]] = []
2122 for item in v:
2123 if not isinstance(item, dict) or not item.get("node_id"):
2124 continue
2125 tools = item.get("tools")
2126 if isinstance(tools, str):
2127 tools = [tools]
2128 if isinstance(tools, list):
2129 items.append(
2130 {
2131 "node_id": str(item["node_id"]),
2132 "tools": [t for t in tools if isinstance(t, str)],
2133 }
2134 )
2135 return items
2137 def guidance_map(self) -> dict[str, list[str]]:
2138 """``tool_guidance`` as node_id → tools, the shape the plan is stored in."""
2139 merged: dict[str, list[str]] = {}
2140 for item in self.tool_guidance:
2141 merged.setdefault(item.node_id, []).extend(
2142 t for t in item.tools if t not in merged.get(item.node_id, [])
2143 )
2144 return merged
2146 @field_validator("active_nodes", mode="before")
2147 @classmethod
2148 def _coerce_active_nodes(cls, v: Any) -> Any:
2149 """A lone node id is a one-item dispatch; non-string entries are dropped."""
2150 if isinstance(v, str):
2151 return [v] if v.strip() else []
2152 if isinstance(v, list):
2153 return [n for n in v if isinstance(n, str)]
2154 return v
2157_SIMPLE, _MODERATE, _COMPLEX = vocab.members(
2158 prompts.TaskComplexity, ("simple", "moderate", "complex")
2159)
2162class ResourceStrategy(ModelOutput):
2163 """Complexity and synthesis strategy — the task's shape, which triage
2164 decides in the same answer as the route (``TriageProfile``).
2166 It is a pure task-complexity classification — it reads the
2167 task text and KB metadata already fetched by the gate, and decides how
2168 to configure downstream execution. It makes NO tool calls; data
2169 retrieval is handled exclusively by the dedicated retrieval nodes
2170 (Self-RAG, Asai et al. 2023; Adaptive RAG, Jeong et al. 2024).
2171 """
2173 complexity: prompts.TaskComplexity = Field(
2174 description=(
2175 "Complexity of the request:\n"
2176 + vocab.guide(prompts.TASK_COMPLEXITY, prompts.TaskComplexity)
2177 )
2178 )
2179 use_skill_graph: bool = Field(
2180 description=(
2181 "Whether to invoke the skill/agent graph for this request.\n"
2182 f"Only set False for '{vocab.member(prompts.GateRoute, 'direct')}' route "
2183 "requests where the task is simple enough\n"
2184 "that the model can answer from training knowledge alone without skill orchestration.\n"
2185 "Always True for any retrieve route — retrieval must complete before synthesis."
2186 )
2187 )
2188 needs_synthesis: bool = Field(
2189 description=(
2190 "Whether a final synthesis pass should consolidate skill-node outputs.\n"
2191 f"Set True when: complexity is '{_COMPLEX}', multiple skill nodes will "
2192 "produce complementary outputs that need merging, or the request has "
2193 "multiple sub-questions each needing a separate answer.\n"
2194 f"Set False when: complexity is '{_SIMPLE}' or '{_MODERATE}' and a single "
2195 "skill node can produce a self-contained answer."
2196 )
2197 )
2198 relevant_tools: list[str] = Field(
2199 default_factory=list,
2200 description=(
2201 "Names, from the tools the task can use, of those most useful for "
2202 "this specific task. Used to seed tool_guidance in the execution "
2203 "plan. Only include tools that would genuinely help."
2204 ),
2205 )
2206 resource_notes: str = Field(
2207 default="",
2208 description=(
2209 "Brief notes for the planner about task structure and recommended approach. "
2210 "Reference specific aspects of the task that need attention."
2211 ),
2212 )
2215#: At most this many scope questions — fewer than ``ask_user`` allows. A scope
2216#: check that needs more than a handful has found a request to discuss, not
2217#: one to disambiguate, and should let the agent start and ask in context.
2218MAX_SCOPE_QUESTIONS = 4
2219#: Guidance, not a limit: a scope question past this many options is a menu.
2220#: ``clarify.MAX_OPTIONS`` is the hard cap.
2221SCOPE_QUESTION_OPTIONS = 5
2222_SINGLE, _MULTI = vocab.members(clarify.QuestionKind, ("single", "multi"))
2225class ScopedResourceStrategy(ResourceStrategy):
2226 """``ResourceStrategy`` plus a scope check, for agents that clarify first.
2228 Asked in the same structured call as the complexity classification, so
2229 checking scope costs no extra model call. The questions are validated by
2230 ``tools.clarify.validate_questions`` — the same checks ``ask_user``
2231 applies — before anything is shown; a malformed set is dropped and the
2232 run carries on, because a scope check is an aid, never a gate.
2233 """
2235 scope_is_ambiguous: bool = Field(
2236 default=False,
2237 description=(
2238 "True only when the request can reasonably be read in materially "
2239 "different ways AND those readings would produce substantially "
2240 "different work or answers, AND neither the request nor the recent "
2241 "conversation settles it. False when a sensible default exists, "
2242 "when the detail is minor, or when the user already said."
2243 ),
2244 )
2245 ambiguity_reason: str = Field(
2246 default="",
2247 description="One sentence naming what is ambiguous, for the audit trail.",
2248 )
2249 # OnErrorOmit: a malformed question is dropped, not the whole strategy —
2250 # one bad option list used to lose the complexity classification too.
2251 clarifying_questions: list[OnErrorOmit[ClarifyQuestion]] = Field(
2252 default_factory=list,
2253 description=(
2254 f"When scope_is_ambiguous: 1–{MAX_SCOPE_QUESTIONS} questions that "
2255 f"settle it. Prefer '{_SINGLE}' options with the best default marked "
2256 "recommended. Empty when not ambiguous."
2257 ),
2258 )
2261def _field_guidance(model: type[BaseModel], *fields: str) -> str:
2262 """``fields`` of ``model``, each with its own description, for a prompt.
2264 The triage prompt states the same guidance its structured-output schema
2265 carries, so the two can never disagree — they once did, on when
2266 ``needs_synthesis`` is true.
2267 """
2268 blocks = []
2269 for name in fields:
2270 text = (model.model_fields[name].description or "").strip()
2271 body = "\n".join(f" {line}" for line in text.splitlines())
2272 blocks.append(f" {name}:\n{body}")
2273 return "\n\n".join(blocks)
2276#: What triage is told about each decision — its schema's own descriptions.
2277_TASK_SHAPE_GUIDANCE = _field_guidance(
2278 ResourceStrategy, "complexity", "use_skill_graph", "needs_synthesis"
2279)
2282_SCOPE_CHECK_GUIDANCE = """
2284SCOPE CHECK — you are also deciding whether {agent} should ask the user a few
2285clarifying questions BEFORE any work starts.
2287 Ask (scope_is_ambiguous=true) only when ALL of these hold:
2288 - the request can reasonably be read in materially different ways
2289 (which system, which period, which audience, how deep, which format,
2290 which of several named things), and
2291 - those readings would lead to substantially different work or answers, and
2292 - neither the request nor the recent conversation already settles it, and
2293 - no sensible default exists that the user would obviously accept.
2294 Do NOT ask for: small details the agent can assume and state, greetings or
2295 chit-chat, questions answerable from general knowledge, follow-ups whose
2296 scope the conversation already fixed, or a request the user has just
2297 clarified. Never ask:
2298 - what to name a file or title a document — the agent names it;
2299 - for something because the knowledge bases do not hold it — that is
2300 not ambiguity, and the agent can search the web;
2301 - which items to include when the request leaves the set open ("different
2302 climbing knots", "interesting illusions") — the agent chooses a
2303 representative set and says what it chose.
2305 When asking: 1–{max_questions} short questions, each settling one decision.
2306 Prefer '{single}' with {min_options}–{max_options} concrete options and mark the
2307 best default recommended=true; '{multi}' when several can apply, with
2308 every option the agent would include by default marked recommended — a
2309 request for several things keeps several; {inputs} fields only for values
2310 only the user knows (a budget, a deadline, a name).
2311 Keep allow_other=true. Give each a short snake_case id.
2313The agent's persona, for judging what is in scope:
2314{persona}
2315"""
2318def _scope_clarification(strategy: ScopedResourceStrategy) -> dict[str, Any] | None:
2319 """The clarification payload for an ambiguous scope, or None.
2321 Model output at a boundary: the questions pass the same checks as an
2322 ``ask_user`` call (``usable_questions``), capped lower. A question that
2323 fails is left out, not the set; with none left the run proceeds without
2324 asking rather than failing or showing the person a form that cannot be
2325 answered.
2326 """
2327 from app.tools.clarify import SOURCE_SCOPE, clarification_payload, usable_questions
2329 if not strategy.scope_is_ambiguous or not strategy.clarifying_questions:
2330 return None
2331 questions, problems = usable_questions(
2332 strategy.clarifying_questions, limit=MAX_SCOPE_QUESTIONS
2333 )
2334 if problems:
2335 logger.warning(
2336 "[graph] node=%s %d scope question(s) left out, %d kept",
2337 GATE_NODE_ID,
2338 len(problems),
2339 len(questions),
2340 )
2341 if not questions:
2342 return None
2343 return clarification_payload(
2344 questions,
2345 source=SOURCE_SCOPE,
2346 title="Before I start",
2347 intro=(strategy.ambiguity_reason or "").strip()
2348 or "A couple of details change how I approach this.",
2349 reason=(strategy.ambiguity_reason or "").strip() or None,
2350 )
2353def _task_structure_brief(
2354 skill_node_descriptors: list[dict[str, str]],
2355 state: "GraphState",
2356 clarify_scope: bool,
2357 tools: Sequence[str] = (),
2358) -> str:
2359 """What a model needs to classify how a task is shaped.
2361 Asked in triage's call, in the same answer as the route. The guidance is
2362 the schema's own field descriptions (``_TASK_SHAPE_GUIDANCE``). ``tools``
2363 are the tools the task can use (``AgentGraphBuilder._triage_tools``):
2364 shown the whole built-in registry, triage named tools the agent did not
2365 hold, and some that do not exist.
2366 """
2367 skill_summary = (
2368 "\n".join(
2369 f" - {d['node_id']} ({d['role']}): {d['description'][:120]}"
2370 for d in skill_node_descriptors
2371 )
2372 or " (no skill nodes configured)"
2373 )
2374 brief = (
2375 f"Configured skill nodes:\n{skill_summary}\n\n"
2376 f"Tools the task can use: {vocab.listing(sorted(tools), sep=', ') or '(none)'}\n\n"
2377 "GUIDANCE:\n" + _TASK_SHAPE_GUIDANCE
2378 )
2379 if clarify_scope:
2380 brief += _SCOPE_CHECK_GUIDANCE.format(
2381 agent=state.agent_name or "the agent",
2382 persona=(state.agent_system_prompt or "")[:600]
2383 or "(no persona configured)",
2384 max_questions=MAX_SCOPE_QUESTIONS,
2385 single=_SINGLE,
2386 multi=_MULTI,
2387 inputs=vocab.listing(clarify.INPUT_KINDS, sep=" / ", quote="'"),
2388 min_options=clarify.MIN_CHOICE_OPTIONS,
2389 max_options=SCOPE_QUESTION_OPTIONS,
2390 )
2391 return brief
2394class _MemoryCue(ModelOutput):
2395 """Whether the request gives the agent something to remember — the
2396 memory write policy's model-side signal (``app/memory/cues.py`` is the
2397 deterministic one). Asked in the triage call every substantive turn
2398 makes already, so it costs a field rather than a call."""
2400 worth_remembering: bool = Field(
2401 default=False,
2402 description=(
2403 "True only when the person's own words (not an attached document "
2404 "or text they quote) tell you something worth knowing in a later, "
2405 "different conversation: who they are or what they use, how they "
2406 "want to be answered from now on, or ongoing work, decisions or "
2407 "deadlines — or they correct such a thing, or ask you to remember "
2408 "or forget something. False for questions, requests and anything "
2409 "that matters only for this answer."
2410 ),
2411 )
2414#: Where the triage's memory cue travels in ``state.context``.
2415MEMORY_CUE_KEY = "memory_cue"
2417#: Set in ``state.context`` when triage judged that the request needs
2418#: current information (``_needs_live_data``). Recall then leaves out every
2419#: earlier exchange (``recall.Query.live``), and the answering node is told
2420#: that nothing remembered is current (``_LIVE_DATA_NOTE``). "whats in the
2421#: news" had recalled the last time it was asked, answered "the search found
2422#: nothing", and the agent repeated that answer without searching.
2423LIVE_DATA_KEY = "live_data"
2425#: Set in ``state.context`` by the memory-read node when it left kinds of
2426#: memory out, and why: the memory stage of the trace says so.
2427RECALL_LEFT_OUT_KEY = "recall_left_out"
2429#: What the answering node is told on a request for current information.
2430_LIVE_DATA_NOTE = (
2431 "This request asks for current information. Nothing remembered from "
2432 "earlier conversations is current: where a tool can provide it, use the "
2433 "tool now, and never repeat an earlier answer in its place."
2434)
2437def _live_data_note(tool_names: Sequence[str]) -> str:
2438 """``_LIVE_DATA_NOTE``, naming the agent's web tool when it holds one.
2440 On a plain agent the gate hands the web to the agent itself, and a live
2441 request that also had dated knowledge was searched there and nowhere
2442 else: told only "use the tool", the agent answered from an empty news
2443 feed that the NCSC had issued no warnings."""
2444 web = [n for n in tool_names if source_ledger.tool_kind(n) == "web"]
2445 if not web:
2446 return _LIVE_DATA_NOTE
2447 return (
2448 f"{_LIVE_DATA_NOTE} Search the web for it now ({', '.join(web)}): your "
2449 "knowledge bases hold only what was indexed, and may not have the latest."
2450 )
2453#: The gap code records when a request about what is current was answered
2454#: with no web search and no dated knowledge (``_unsearched_live_gap``).
2455UNSEARCHED_LIVE_GAP = (
2456 "The request asks what is current, and no web search was made this turn: "
2457 "the answer rests on reference material, which cannot say what is new. "
2458 "Search the web for it, then answer from what you find."
2459)
2462def _unsearched_live_gap(state: "GraphState", *, holds_web: bool) -> str | None:
2463 """:data:`UNSEARCHED_LIVE_GAP` when a request about now got nothing
2464 current: triage marked it live (``LIVE_DATA_KEY``), a step holds a web
2465 tool (``holds_web``), none ran (``source_ledger.web_searched``), and
2466 the evidence held no dated passages (``DATED_KNOWLEDGE_KEY``).
2468 Told in words to search the web, c-ai-rules ("What's new in UK AI
2469 regulation this month?") answered from the statute text that "no new
2470 regulations came into force in October 2026", and the check passed it
2471 at 92 (scenario run 7; run 6 had searched eight times). The gap is
2472 code's, so the revision searches whatever the check made of it."""
2473 if not holds_web or not state.context.get(LIVE_DATA_KEY):
2474 return None
2475 if state.context.get(DATED_KNOWLEDGE_KEY) or source_ledger.web_searched(
2476 state.messages
2477 ):
2478 return None
2479 return UNSEARCHED_LIVE_GAP
2482def _with_live_gap(result: "EvaluatorResult", gap: str | None) -> "EvaluatorResult":
2483 """``result`` holding :data:`UNSEARCHED_LIVE_GAP` exactly when ``gap``
2484 says it still applies: added as ``missing`` and failing the draft, or
2485 taken out of a revision's open items once the web was searched."""
2486 kept = [g for g in result.gaps if _issue(g) != UNSEARCHED_LIVE_GAP]
2487 if gap:
2488 return result.model_copy(
2489 update={"gaps": [*kept, Gap(issue=gap, kind="missing")], "passed": False}
2490 )
2491 if len(kept) == len(result.gaps):
2492 return result
2493 passed = not (any(_fails(g) for g in kept) or result.reasoning_errors)
2494 return result.model_copy(update={"gaps": kept, "passed": passed})
2497#: Set in ``state.context`` when internal retrieval searched the knowledge
2498#: and the relevance judge ruled out everything it found: the answering node
2499#: is told the knowledge holds nothing for this request.
2500KNOWLEDGE_NOT_RELEVANT_KEY = "knowledge_not_relevant"
2502#: Set in ``state.context`` when internal retrieval searched the knowledge
2503#: bases and handed on what it found. Only then can the evaluator's gaps be
2504#: searched for in the same knowledge (corrective retrieval):
2505#: ``state.retrieval_context`` holds the web and tool retrieval nodes'
2506#: sections too, so it does not say the knowledge was searched.
2507KNOWLEDGE_SEARCHED_KEY = "knowledge_searched"
2509#: Where the format a request asks the answer in travels in
2510#: ``state.context`` (``llm.build_format_instruction`` of the request's
2511#: ``output_format`` / ``output_schema``): one request's, so it closes the
2512#: answering node's ``<request_context>`` rather than joining the system
2513#: prompt, which stays the same on every call of the agent.
2514OUTPUT_FORMAT_KEY = "output_format_instruction"
2516#: The note on an answering node's ``<knowledge>`` block, and the one it
2517#: carries when the relevance judge failed and the passages went through
2518#: unchecked (each reads "relevance unjudged"): the passages stay, since a
2519#: judge's hiccup is no reason to answer without the knowledge, and the
2520#: agent is told what that means.
2521_KNOWLEDGE_NOTE = (
2522 "Retrieved for this request; use and cite only the passages that bear on it."
2523)
2524_UNJUDGED_KNOWLEDGE_NOTE = (
2525 "Retrieved for this request, but these passages were not checked for "
2526 "relevance; use and cite only those that bear on the request."
2527)
2529#: The note on a ``<frameworks>`` block: the methods internal retrieval found
2530#: in the agent's reasoning knowledge (``state.frameworks_context``).
2531_FRAMEWORKS_NOTE = (
2532 "Methods from your reasoning knowledge for this request: apply the one "
2533 "that fits and cite it by its id. They are not evidence for facts."
2534)
2535#: The same block as the quality check reads it. It had said "check that it
2536#: applied one", and the check failed sound answers for choosing another
2537#: method: a payroll plan for not using the spiral model, a systems answer
2538#: for leverage points rather than archetypes.
2539_EVALUATOR_FRAMEWORKS_NOTE = (
2540 "Methods the agent was offered. Which one it applies, if any, is its "
2541 "choice: judge only whether a method it uses is applied correctly and "
2542 "credited with what it says. They are not evidence for facts."
2543)
2546def _frameworks_block(frameworks: str, note: str, indent: str = " ") -> list[str]:
2547 """``frameworks`` as a ``<frameworks>`` element, CDATA-wrapped like the
2548 knowledge it comes before; nothing without any."""
2549 if not frameworks:
2550 return []
2551 return [
2552 f'{indent}<frameworks note="{note}">',
2553 f"{indent} <![CDATA[",
2554 attachment_util.cdata(frameworks),
2555 f"{indent} ]]>",
2556 f"{indent}</frameworks>",
2557 ]
2560# Bases are listed last-field-first: pydantic lays fields out from the last
2561# base, so ``route`` comes first and the defaulted cues last. With
2562# ``_MemoryCue`` last here, ``worth_remembering`` was the first field, and
2563# every triage runaway of scenario runs 5 and 6 stopped in it — Qwen3 235B
2564# writing whitespace to the cap before any of the profile
2565# (``cut_replies.closed`` reads a runaway at the end, never at the start).
2566class TriageProfile(_MemoryCue, ResourceStrategy, RequestProfile):
2567 """The gate's one call: where the data comes from (``RequestProfile``)
2568 and how the task is shaped (``ResourceStrategy``).
2570 These were two sequential calls on the same request — the gate's, then
2571 ``__recon__``'s — each waiting on the other; then recon read the strategy
2572 from here and asked again only when this call failed. Now this is the
2573 only call, and the gate node reads both halves (October 2026).
2574 """
2577class ScopedTriageProfile(_MemoryCue, ScopedResourceStrategy, RequestProfile):
2578 """``TriageProfile`` with the scope check, for agents that clarify first."""
2581class _RecencyCue(ModelOutput):
2582 """How recent a request wants dated knowledge to be: the window a
2583 temporal knowledge base's passages are kept to
2584 (``app/knowledge/categories.py``). Asked only of an agent that has
2585 temporal knowledge, in the triage call it makes already; every other
2586 agent's triage schema, and its cached prompt, are unchanged."""
2588 time_window: knowledge_categories_registry.TimeWindow = Field(
2589 default="any",
2590 description=(
2591 "How recent the information the request asks about must be, read "
2592 "from its own words ('this week', 'today', 'latest'):\n"
2593 + vocab.guide(
2594 knowledge_categories_registry.TIME_WINDOWS,
2595 knowledge_categories_registry.TimeWindow,
2596 )
2597 ),
2598 )
2601class DatedTriageProfile(_RecencyCue, TriageProfile):
2602 """``TriageProfile`` for an agent with temporal knowledge."""
2605class ScopedDatedTriageProfile(_RecencyCue, ScopedTriageProfile):
2606 """``ScopedTriageProfile`` for an agent with temporal knowledge."""
2609@functools.lru_cache(maxsize=256)
2610def _naming_only(
2611 schema: type[RequestProfile], tools: tuple[str, ...]
2612) -> type[RequestProfile]:
2613 """``schema`` with ``relevant_tools`` held to ``tools``: a ``Literal`` of
2614 the names, so constrained decoding can write no other (``relevant_tools``
2615 was any string, and triage named tools the agent did not hold). Built
2616 once per schema and tool set, under the schema's own name, so a request
2617 reads as before. A name it could still write wrongly (function calling)
2618 is dropped, not the profile (``OnErrorOmit``)."""
2619 if not tools or "relevant_tools" not in schema.model_fields:
2620 return schema
2621 names = Literal[tools] # type: ignore[valid-type]
2622 return create_model(
2623 schema.__name__,
2624 __base__=schema,
2625 __module__=schema.__module__,
2626 relevant_tools=(
2627 list[OnErrorOmit[names]],
2628 Field(
2629 default_factory=list,
2630 description=schema.model_fields["relevant_tools"].description,
2631 ),
2632 ),
2633 )
2636#: Where what triage said that decides how each kind of knowledge is searched
2637#: travels in ``state.context`` (``categories.RetrievalTurn.wire``), set by
2638#: the gate and read by the retrieval node.
2639KNOWLEDGE_TURN_KEY = knowledge_categories_registry.TURN_KEY
2641#: Set in ``state.context`` when the evidence handed on held dated passages
2642#: (temporal knowledge): the memory write keeps only the question, as it
2643#: does for an answer resting on a news search.
2644DATED_KNOWLEDGE_KEY = "dated_knowledge"
2647# The check failed the agent's own work three runs in a row — a payroll
2648# plan for its own dates, an offsite agenda for a venue's availability
2649# nobody asked about, a claim cited to a search result whose page would not
2650# load — though its prompt said none of that is a gap. It now labels each
2651# problem, and code decides: only ``prompts.FAILING_GAP_KINDS`` fail the
2652# draft (``_split_gaps``). The docstring is the model's to read.
2653class Gap(ModelOutput):
2654 """One problem the check found in the draft, and its kind."""
2656 issue: str = Field(description="The problem, as something the agent can fix.")
2657 kind: prompts.GapKind = Field(
2658 description="What kind of problem it is: " + vocab.one_of(prompts.GapKind) + "."
2659 )
2662def _as_gap(item: Any) -> Any:
2663 """A gap as models and older scripts write it: a bare string, or an item
2664 without a kind (or one outside the vocabulary), is ``missing``, which
2665 fails as every gap used to."""
2666 if isinstance(item, str):
2667 return {"issue": item, "kind": "missing"} if item.strip() else None
2668 if isinstance(item, dict) and item.get("kind") not in prompts.GAP_KIND_GUIDE:
2669 return {**item, "kind": "missing"}
2670 return item
2673def _kind(item: Any) -> str:
2674 """A gap's kind, whatever shape it arrived in; a bare string is
2675 ``missing``, as ``_as_gap`` reads it."""
2676 if isinstance(item, Gap):
2677 return item.kind
2678 if isinstance(item, dict) and item.get("kind") in prompts.GAP_KIND_GUIDE:
2679 return str(item["kind"])
2680 return "missing"
2683def _issue(item: Any) -> str:
2684 """A gap's words, whatever shape it arrived in."""
2685 if isinstance(item, Gap):
2686 return item.issue
2687 if isinstance(item, dict):
2688 return str(item.get("issue") or "")
2689 return str(item)
2692def _fails(item: Any) -> bool:
2693 """Whether a gap fails the draft: a string always does (a revision's
2694 open gaps, a verdict's), an item by its kind."""
2695 if isinstance(item, Gap):
2696 return item.kind in prompts.FAILING_GAP_KINDS
2697 if isinstance(item, dict):
2698 return item.get("kind") in prompts.FAILING_GAP_KINDS
2699 return bool(str(item).strip())
2702class EvaluatorResult(ModelOutput):
2703 """Structured output produced by the __evaluator__ quality-gate node.
2705 The evaluator checks two orthogonal dimensions:
2706 1. Coverage — does the response address every requirement?
2707 2. Reasoning — is every claim validly derived from stated premises?
2709 Both dimensions must pass for the overall result to pass. A response that
2710 gives the correct answer via a logically invalid path (e.g. assuming the
2711 form of the solution, inconsistently applying approximations) fails on
2712 reasoning even if it nominally covers all requirements.
2713 """
2715 gaps: list[OnErrorOmit[Gap]] = Field(
2716 default_factory=list,
2717 description=(
2718 "Each problem the check found in the draft's content, with its kind. "
2719 "Focused on content, not reasoning quality. Empty when there is "
2720 "nothing to fix."
2721 ),
2722 )
2723 reasoning_errors: list[str] = Field(
2724 default_factory=list,
2725 description=(
2726 "Logical flaws in the reasoning chain, independent of content coverage. "
2727 "Each entry is a specific error such as:\n"
2728 " - Circular assumption: concluding the answer by assuming its form\n"
2729 " - Inconsistent derivation: silently switching approximations mid-proof\n"
2730 " - Incomplete solution set: finding one solution without proving completeness\n"
2731 " - Strategy mismatch: applying a known protocol whose invariant does not "
2732 " hold for this problem's specific constraints\n"
2733 "Empty list when the reasoning chain is valid throughout."
2734 ),
2735 )
2736 # The verdict after the evidence for it: the check lists what it found,
2737 # then decides. With ``passed`` first, a boolean opened the reply, and the
2738 # one check runaway of scenario run 5 (16,384 tokens of whitespace) began
2739 # there, as every triage runaway began at its leading boolean.
2740 passed: bool = Field(
2741 description=(
2742 "True only when BOTH conditions hold: (a) every explicit requirement is "
2743 "addressed, AND (b) reasoning_errors is empty. False whenever either "
2744 "content gaps or logical flaws exist."
2745 )
2746 )
2747 score: int = Field(
2748 ge=0,
2749 le=100,
2750 description=(
2751 "Quality score 0–100 reflecting coverage, accuracy, completeness, AND "
2752 "reasoning validity. Deduct heavily for circular assumptions, inconsistent "
2753 "derivations, or incomplete solution sets. 90+ means fully correct and "
2754 "rigorously derived; below 50 means significant gaps or invalid reasoning."
2755 ),
2756 )
2758 @field_validator("gaps", "reasoning_errors", mode="before")
2759 @classmethod
2760 def _coerce_str_to_list(cls, v: Any) -> Any:
2761 # Function-calling models routinely emit "" (or a bare string) for an
2762 # empty list field. Without coercion that fails pydantic validation
2763 # for the WHOLE verdict, and the evaluator node degrades to the
2764 # pass-through fallback — silently shipping exactly the drafts that
2765 # were mid-way through being criticised.
2766 return _listed(v)
2768 @field_validator("gaps", mode="before")
2769 @classmethod
2770 def _gap_items(cls, v: Any) -> Any:
2771 return [g for g in (_as_gap(item) for item in _listed(v)) if g is not None]
2773 @field_validator("score", mode="before")
2774 @classmethod
2775 def _coerce_score(cls, v: Any) -> Any:
2776 return _score_of(v)
2778 # Optional with an empty default — not because it is unimportant, but
2779 # because models routinely omit long trailing fields, and a required one
2780 # failed the whole verdict into the pass-through fallback. The evaluator
2781 # node derives a summary when it is empty.
2782 critique: str = Field(
2783 default="",
2784 description=(
2785 "One-sentence evaluation summary covering both coverage and reasoning "
2786 "quality. Always provide this."
2787 ),
2788 )
2791def _listed(v: Any) -> Any:
2792 """A list field as models send it: ``null`` or ``""`` is empty, a bare
2793 string is one item."""
2794 if v is None:
2795 return []
2796 if isinstance(v, str):
2797 return [v] if v.strip() else []
2798 return v
2801def _score_of(v: Any) -> Any:
2802 """A score is an integer 0–100; read the near-misses models send.
2804 ``85.5`` and ``"85"`` are rounded; a fraction strictly between 0 and 1
2805 (``0.85``) is the same judgement on a 0–1 scale. Out-of-range values
2806 are clamped. Without this one fractional score failed the whole
2807 verdict and the answer went out unchecked.
2808 """
2809 if isinstance(v, str):
2810 try:
2811 v = float(v.strip().rstrip("%"))
2812 except ValueError:
2813 return v
2814 if isinstance(v, float):
2815 v = round(v * 100) if 0 < v < 1 else round(v)
2816 if isinstance(v, int) and not isinstance(v, bool):
2817 return min(100, max(0, v))
2818 return v
2821class RevisionCheck(ModelOutput):
2822 """The quality check of a revision: what it was asked to fix and did
2823 not, and what it got wrong that the draft before it did not.
2825 It used to be checked as a first answer is, and raised new gaps on every
2826 pass — advice, proposals, extras — though the prompt forbade it: one
2827 discharge answer failed three checks in a row, each on new objections.
2828 A revision can now fail only on a gap the last check named (by its
2829 number in ``<earlier_checks>``) or a factual error it introduced; code
2830 builds the verdict from them (``_revision_result``).
2831 """
2833 open_gaps: list[int] = Field(
2834 default_factory=list,
2835 description=(
2836 "The numbers of the gaps in <earlier_checks> that the draft still "
2837 "leaves unfixed. Empty when it fixed them all."
2838 ),
2839 )
2840 new_errors: list[str] = Field(
2841 default_factory=list,
2842 description=(
2843 "Factual errors the revision introduced: a claim that contradicts "
2844 "the evidence, or a specific figure, name, date or quotation that "
2845 "none of it supports. Never advice, analysis, a proposal, an "
2846 "interpretation or general knowledge. Empty when there are none."
2847 ),
2848 )
2849 score: int = Field(
2850 ge=0,
2851 le=100,
2852 description="Quality score 0–100 of the revised draft.",
2853 )
2854 critique: str = Field(
2855 default="",
2856 description="One sentence on whether the revision did what was asked.",
2857 )
2859 @field_validator("score", mode="before")
2860 @classmethod
2861 def _coerce_score(cls, v: Any) -> Any:
2862 return _score_of(v)
2864 @field_validator("open_gaps", mode="before")
2865 @classmethod
2866 def _numbers(cls, v: Any) -> Any:
2867 """Numbers as models write them: ``"1"``, ``1.0``; anything else
2868 goes."""
2869 if v is None:
2870 return []
2871 out = []
2872 for item in v if isinstance(v, list) else [v]:
2873 try:
2874 out.append(int(float(item)))
2875 except (TypeError, ValueError):
2876 continue
2877 return out
2879 @field_validator("new_errors", mode="before")
2880 @classmethod
2881 def _errors(cls, v: Any) -> Any:
2882 if v is None:
2883 return []
2884 if isinstance(v, str):
2885 return [v] if v.strip() else []
2886 return v
2889def _revision_result(
2890 check: RevisionCheck, checks: list[dict[str, Any]]
2891) -> EvaluatorResult:
2892 """A revision's check as the verdict the node reads: the numbered gaps
2893 still open (``_latest_items``), then what the revision got wrong. A
2894 number that names no gap is dropped."""
2895 entries = _latest_entries(checks)
2896 still_open = [
2897 entries[n - 1] for n in dict.fromkeys(check.open_gaps) if 1 <= n <= len(entries)
2898 ]
2899 # Each item keeps the kind its check gave it, so a summary's own
2900 # problems still go back to synthesis alone; what the revision got wrong
2901 # is a fact the evidence does not support.
2902 gaps = [
2903 *(
2904 Gap(issue=text, kind=kind)
2905 for text, kind in still_open
2906 if kind != _REASONING
2907 ),
2908 *(
2909 Gap(issue=str(e), kind="unsupported_fact")
2910 for e in check.new_errors
2911 if str(e).strip()
2912 ),
2913 ]
2914 reasoning = [text for text, kind in still_open if kind == _REASONING]
2915 return EvaluatorResult(
2916 passed=not (gaps or reasoning),
2917 score=check.score,
2918 gaps=gaps,
2919 reasoning_errors=reasoning,
2920 critique=check.critique,
2921 )
2924#: What became of an answer at the quality check. ``passed``: the check ran
2925#: and the first answer stood. ``revised``: it failed, the agent revised it,
2926#: and the revision passed. ``failed``: it failed, and no revision passed —
2927#: the agent's latest answer went out. ``unavailable``: no check ran — no
2928#: evaluator model, or it errored. svc-core's ``quality_check`` rule field
2929#: offers exactly these.
2930QualityOutcome = Literal["passed", "revised", "failed", "unavailable", "skipped"]
2932#: Why a ``skipped`` check did not run, as its critique says it.
2933SKIPPED_CRITIQUE = (
2934 "Not checked: this agent's cost profile answers a request triage calls "
2935 "simple without a quality check."
2936)
2939class AnswerSource(BaseModel):
2940 """One citation of a delivered answer: ``[marker]`` names ``citation_id``."""
2942 marker: int
2943 citation_id: str
2946class EvaluatorVerdict(EvaluatorResult):
2947 """The evaluator node's result, as everything after it reads it.
2949 Adds what the model is not asked to say, so none of it is on
2950 ``EvaluatorResult``, the structured-output schema the model fills: what
2951 became of the answer, a ``score`` that is None when no check ran, and the
2952 answer itself. A pass-through used to report a pass scored 80, which made
2953 an answer nobody checked indistinguishable from one that was checked and
2954 was good.
2956 ``final_output`` is always the agent's own answer. The evaluator used to
2957 write a replacement whenever a check failed, and that rewrite shipped: an
2958 answer written without the agent's instructions, its tools or the
2959 material the user supplied, which nothing then checked. It now only names
2960 what is wrong, and the agent revises (``_evaluator_router``).
2961 """
2963 score: Optional[int] = Field(default=None, ge=0, le=100) # type: ignore[assignment]
2964 #: What the agent must fix, in words: the failing gaps only.
2965 gaps: list[str] = Field(default_factory=list) # type: ignore[assignment]
2966 #: Each gap's kind (``prompts.GapKind``), in the order of ``gaps``: what
2967 #: the router reads to send a summary's own problems back to synthesis
2968 #: alone (``_evaluator_router``), and the trace shows for review.
2969 gap_kinds: list[str] = Field(default_factory=list)
2970 #: Problems the check named that do not fail a draft (the agent's own
2971 #: work, what was not asked, presentation), each with its kind. On the
2972 #: trace and the stored answer for whoever reviews the check; never sent
2973 #: back to the agent.
2974 set_aside: list[str] = Field(default_factory=list)
2975 outcome: QualityOutcome = "unavailable"
2976 final_output: str = ""
2977 #: Markers in the draft that name no source the run was given, in words
2978 #: (``answer_sources.check_markers``) — set by code, after a model check
2979 #: ran, and never read by corrective retrieval: the agent revises the
2980 #: markers with the ids it is shown, nothing is searched again.
2981 citation_problems: list[str] = Field(default_factory=list)
2982 #: What the delivered answer cites, in order: each marker and the id of
2983 #: the source it names (``answer_sources.finalise``).
2984 answer_sources: list[AnswerSource] = Field(default_factory=list)
2986 # Named as ``EvaluatorResult``'s, so it replaces it: a verdict's gaps
2987 # are words.
2988 @field_validator("gaps", mode="before")
2989 @classmethod
2990 def _gap_items(cls, v: Any) -> Any:
2991 return [w for w in (_issue(item) for item in _listed(v)) if w.strip()]
2994def _split_gaps(result: EvaluatorResult) -> tuple[EvaluatorResult, list[str]]:
2995 """A first check's verdict holding only the gaps that fail a draft, and
2996 the rest in words (``"own_work: …"``), set aside."""
2997 failing = [g for g in result.gaps if _fails(g)]
2998 set_aside = [f"{g.kind}: {g.issue}" for g in result.gaps if not _fails(g)]
2999 if not set_aside:
3000 return result, []
3001 return result.model_copy(update={"gaps": failing}), set_aside
3004#: What a reply's document is called in a gap.
3005_DOCUMENT_NOUN = (
3006 r"(?:pdf|document|report|brief|attachment|download(?:able)?"
3007 r"(?:\s+(?:file|link|pdf))?)"
3008)
3009#: A gap saying the reply's document is not there: "The draft does not
3010#: include the PDF attachment in the response; it only states that it has
3011#: been attached" (scenario run 7, pdf-brief, all three checks, though the
3012#: prompt said a document is never a gap). Narrow on purpose: the document
3013#: itself is the object — "does not include the costs from the report" and
3014#: "the attached document does not mention open questions" are content.
3015_ABSENT_DOCUMENT_RE = re.compile(
3016 r"(?:\bnot|n't|\bnever|\bwithout|\bfails?\s+to)\s+"
3017 r"(?:actually\s+|explicitly\s+|directly\s+)?"
3018 r"(?:include|includes|including|attach|attaches|attaching|provide|provides|"
3019 r"providing|embed|embeds|embedding|deliver|delivers|delivering|contain|"
3020 r"contains|containing|links?\s+to|offer|offers|share|shares|show|shows)\s+"
3021 r"(?:the|a|an|any)\s+(?:actual\s+|rendered\s+|generated\s+|downloadable\s+|"
3022 r"requested\s+|promised\s+|attached\s+|pdf\s+)?" + _DOCUMENT_NOUN + r"s?"
3023 r"(?:\s+(?:itself|file|attachment|link|document))?"
3024 r"(?=\s*(?:[.,;:)!]|$)|\s+(?:in|with|to|as|itself|anywhere|but|and|or|only)\b)"
3025 r"|\b(?:pdf|document|report|brief|attachment)s?\s+(?:itself\s+)?"
3026 r"(?:is|was|are|were|has|have)\s+(?:not|never)\s+(?:been\s+)?(?:actually\s+)?"
3027 r"(?:attached|included|provided|linked|present|delivered|shared|embedded)\b"
3028 r"|\bno\s+(?:actual\s+)?(?:pdf|download(?:able)?(?:\s+(?:file|link))?)\s+"
3029 r"(?:is\s+|was\s+)?(?:attached|included|provided|linked|given)\b",
3030 re.IGNORECASE,
3031)
3034def _set_aside_absent_documents(
3035 result: EvaluatorResult, *, attaches_document: bool
3036) -> tuple[EvaluatorResult, list[str]]:
3037 """``result`` without the gaps that say the reply's document is missing,
3038 when the reply attaches one, and those gaps in words, set aside.
3040 CHAIN-R attaches every document the run made, whatever the draft says,
3041 so the claim is never true of such a reply: a revision cannot fix it,
3042 and pdf-brief shipped failed at 50 for it."""
3043 if not attaches_document:
3044 return result, []
3045 absent = [
3046 g for g in result.gaps if _fails(g) and _ABSENT_DOCUMENT_RE.search(_issue(g))
3047 ]
3048 if not absent:
3049 return result, []
3050 kept = [g for g in result.gaps if not any(g is a for a in absent)]
3051 # A fail left naming nothing passes, as any other (``_material``).
3052 return result.model_copy(update={"gaps": kept}), [
3053 f"presentation: {_issue(g)}" for g in absent
3054 ]
3057def _material(result: EvaluatorResult) -> bool:
3058 """Whether a verdict names something the agent must fix. A fail that
3059 names neither a gap, a reasoning error nor a citation problem is the
3060 model objecting to presentation — the agent's own style to keep, not a
3061 failure."""
3062 return bool(
3063 any(_fails(g) for g in result.gaps)
3064 or result.reasoning_errors
3065 or getattr(result, "citation_problems", None)
3066 )
3069def _final_verdict(passed: bool, retry_count: int, budget: int) -> bool:
3070 """Whether the evaluator's verdict ends the turn: it passed, or the
3071 revisions it may ask for are spent. ``_evaluator_router`` routes on the
3072 same rule, so the answer is finalised exactly when it ships."""
3073 return passed or retry_count > budget
3076def _verdict(
3077 result: EvaluatorResult,
3078 draft: str,
3079 *,
3080 revision: bool,
3081 set_aside: Sequence[str] = (),
3082) -> EvaluatorVerdict:
3083 """What became of the answer, given a check that ran.
3085 The answer is always ``draft``, the agent's. ``revision`` says whether it
3086 is a revision the check asked for: one that passes is ``revised``. A fail
3087 is ``failed`` — retried by ``_evaluator_router`` while budget remains, so
3088 this is what it ships as when none remains.
3089 """
3090 passed = result.passed and not result.reasoning_errors
3091 if passed:
3092 outcome: QualityOutcome = "revised" if revision else "passed"
3093 else:
3094 outcome = "failed"
3095 return EvaluatorVerdict(
3096 **{**result.model_dump(), "passed": passed},
3097 gap_kinds=[_kind(gap) for gap in result.gaps],
3098 set_aside=list(set_aside),
3099 outcome=outcome,
3100 final_output=draft,
3101 )
3104#: The most of a failed check the next one is shown: its gaps and reasoning
3105#: errors are what a revision was asked to fix.
3106_EARLIER_CHECK_ITEMS = 8
3109def _check_record(verdict: Any) -> dict[str, Any]:
3110 """A failed check as the next one reads it (``GraphState.quality_checks``)."""
3111 gaps = [str(g) for g in (getattr(verdict, "gaps", None) or [])]
3112 kinds = list(getattr(verdict, "gap_kinds", None) or [])
3113 return {
3114 "score": getattr(verdict, "score", None),
3115 "gaps": gaps[:_EARLIER_CHECK_ITEMS],
3116 # Aligned with ``gaps``; a gap whose kind went unrecorded is missing.
3117 "gap_kinds": [
3118 kinds[i] if i < len(kinds) else "missing" for i in range(len(gaps))
3119 ][:_EARLIER_CHECK_ITEMS],
3120 "reasoning_errors": [
3121 str(e) for e in (getattr(verdict, "reasoning_errors", None) or [])
3122 ][:_EARLIER_CHECK_ITEMS],
3123 "citation_problems": [
3124 str(c) for c in (getattr(verdict, "citation_problems", None) or [])
3125 ][:_EARLIER_CHECK_ITEMS],
3126 }
3129#: The kind of a numbered item that was a reasoning error, not a gap.
3130_REASONING = "reasoning"
3133def _latest_entries(checks: list[dict[str, Any]]) -> list[tuple[str, str]]:
3134 """What the latest failed check asked the agent to fix, each with its
3135 kind, in the order it is numbered in ``<earlier_checks>``: its gaps,
3136 then its reasoning errors (``_REASONING``). A citation problem is
3137 checked again by code, so it is not numbered."""
3138 if not checks:
3139 return []
3140 latest = checks[-1]
3141 gaps = [str(item) for item in latest.get("gaps") or []]
3142 kinds = list(latest.get("gap_kinds") or [])
3143 return [
3144 *(
3145 (gap, kinds[i] if i < len(kinds) else "missing")
3146 for i, gap in enumerate(gaps)
3147 ),
3148 *((str(item), _REASONING) for item in latest.get("reasoning_errors") or []),
3149 ]
3152def _latest_items(checks: list[dict[str, Any]]) -> list[str]:
3153 """The latest failed check's numbered items, in words
3154 (``_latest_entries``)."""
3155 return [text for text, _ in _latest_entries(checks)]
3158def _earlier_checks_block(checks: list[dict[str, Any]]) -> list[str]:
3159 """``<earlier_checks>``: what each earlier check of this answer asked the
3160 agent to fix, oldest first, the latest's items numbered — a revision's
3161 check names the ones still open by number (``RevisionCheck``). Empty on
3162 the first check."""
3163 if not checks:
3164 return []
3165 lines = [" <earlier_checks>"]
3166 for number, check in enumerate(checks, start=1):
3167 latest = number == len(checks)
3168 lines.append(
3169 f' <check number="{number}"' + (' latest="true">' if latest else ">")
3170 )
3171 counted = 0
3172 for tag in ("gaps", "reasoning_errors", "citation_problems"):
3173 for item in check.get(tag) or []:
3174 singular = tag[:-1] if tag.endswith("s") else tag
3175 numbered = latest and tag != "citation_problems"
3176 if numbered:
3177 counted += 1
3178 lines.append(
3179 f" <{singular}"
3180 + (f' number="{counted}"' if numbered else "")
3181 + f"><![CDATA[{attachment_util.cdata(str(item))}]]></{singular}>"
3182 )
3183 lines.append(" </check>")
3184 lines.append(" </earlier_checks>")
3185 return lines
3188def _revision_note(verdict: Any) -> str:
3189 """The evaluator's verdict as the agent reads it on a revision: what to
3190 fix, in words — not the verdict's JSON."""
3191 lines = [
3192 "Your previous answer (above) did not pass the quality check. Revise "
3193 "it: keep what was right, fix what is listed below, and use your tools "
3194 "or the material you were given where they help. A claim the check "
3195 "found unsupported is fixed by taking it out or saying it is "
3196 "unconfirmed, never by stating it again; search again only for a fact "
3197 "the request needs. Answer the original task directly, and do not "
3198 "mention the check. The person cannot be asked during a revision: "
3199 "what cannot be had, leave out and say so."
3200 ]
3201 gaps = list(getattr(verdict, "gaps", None) or [])
3202 errors = list(getattr(verdict, "reasoning_errors", None) or [])
3203 if gaps:
3204 lines.append("Fix:\n" + "\n".join(f"- {g}" for g in gaps))
3205 if errors:
3206 lines.append("Reasoning errors:\n" + "\n".join(f"- {e}" for e in errors))
3207 citations = list(getattr(verdict, "citation_problems", None) or [])
3208 if citations:
3209 lines.append(
3210 "Citations — keep your answer as it is and change only these "
3211 "markers; there is no need to search again:\n"
3212 + "\n".join(f"- {c}" for c in citations)
3213 )
3214 critique = str(getattr(verdict, "critique", "") or "").strip()
3215 if critique:
3216 lines.append(f"Summary: {critique}")
3217 return "\n\n".join(lines)
3220# ---------------------------------------------------------------------------
3221# @chain prompt factories
3222# ---------------------------------------------------------------------------
3225def _make_node_prompt_chain(role: str, base_instructions: str) -> Any:
3226 """Return a ``@chain`` that renders a full XML system prompt for a system node.
3228 Injects the node's plan (goal, expected output, success criteria) from
3229 ``state.execution_plan`` into a structured XML template. Falls back to a
3230 minimal prompt when no plan is available.
3232 Input keys:
3233 node_id — this node's graph ID (used to look up its plan)
3234 task — original user task from ``state.input``
3235 execution_plan — dict from ``GraphState.execution_plan``
3236 """
3238 @lc_chain
3239 def format_prompt(inputs: dict) -> str:
3240 import html as _html
3242 node_id: str = inputs.get("node_id", "")
3243 plan: dict = inputs.get("execution_plan", {})
3245 if not plan:
3246 return f"You are a {role}.\n\n{base_instructions}"
3248 overall_goal: str = _html.escape(plan.get("overall_goal", ""))
3249 node_plans_list: list[dict] = plan.get("node_plans", [])
3250 node_plan: dict = next(
3251 (np for np in node_plans_list if np.get("node_id") == node_id), {}
3252 )
3254 # The planner plans only the skill nodes it dispatches, so a system
3255 # node has no assignment of its own: it works to the overall goal
3256 # rather than to a placeholder ("Perform your assigned role.").
3257 goal = _html.escape(node_plan.get("goal", ""))
3258 expected_output = _html.escape(node_plan.get("expected_output", ""))
3259 success_criteria = _html.escape(node_plan.get("success_criteria", ""))
3261 # Retrieval focus lines are node-specific: only rendered for the node
3262 # that will use them so the other nodes' prompts stay uncluttered.
3263 retrieval_focus: str = _html.escape(plan.get("retrieval_focus", ""))
3264 external_focus: str = _html.escape(plan.get("external_retrieval_focus", ""))
3265 if node_id == INTERNAL_RETRIEVAL_NODE_ID and retrieval_focus:
3266 focus_block = f"\n <retrieval_focus>{retrieval_focus}</retrieval_focus>"
3267 elif node_id == EXTERNAL_RETRIEVAL_NODE_ID and external_focus:
3268 focus_block = f"\n <retrieval_focus>{external_focus}</retrieval_focus>"
3269 else:
3270 focus_block = ""
3272 expected_block = (
3273 f"\n <expected_output>{expected_output}</expected_output>"
3274 if expected_output
3275 else ""
3276 )
3277 criteria_block = (
3278 f"\n <success_criteria>{success_criteria}</success_criteria>"
3279 if success_criteria
3280 else ""
3281 )
3283 assignment_block = (
3284 f"\n <your_assignment>\n"
3285 f" <goal>{goal}</goal>{expected_block}{criteria_block}\n"
3286 f" </your_assignment>"
3287 if goal
3288 else ""
3289 )
3291 # <task> is intentionally omitted — the task arrives as the HumanMessage
3292 # so stating it again here would duplicate content and dilute attention
3293 # on the instructions (Liu et al. 2023, "Lost in the Middle").
3294 return (
3295 f"<system>\n"
3296 f" <role>{role}</role>\n"
3297 f" <plan>\n"
3298 f" <overall_goal>{overall_goal}</overall_goal>{focus_block}{assignment_block}\n"
3299 f" </plan>\n"
3300 f" <instructions>\n{base_instructions}\n </instructions>\n"
3301 f"</system>"
3302 )
3304 return format_prompt
3307def _make_plan_injection_chain() -> Any:
3308 """Return a ``@chain`` that renders an XML ``<execution_plan>`` block for skill nodes.
3310 Unlike ``_make_node_prompt_chain``, this produces only the plan section so it
3311 can be appended to a skill node's existing configured system prompt without
3312 replacing it.
3314 Input keys: same as ``_make_node_prompt_chain``.
3315 Returns an empty string when no plan exists (no-op injection).
3316 """
3318 @lc_chain
3319 def inject_plan(inputs: dict) -> str:
3320 import html as _html
3322 node_id: str = inputs.get("node_id", "")
3323 plan: dict = inputs.get("execution_plan", {})
3325 if not plan:
3326 return ""
3328 overall_goal: str = _html.escape(plan.get("overall_goal", ""))
3329 node_plans_list: list[dict] = plan.get("node_plans", [])
3330 node_plan: dict = next(
3331 (np for np in node_plans_list if np.get("node_id") == node_id), {}
3332 )
3334 goal = _html.escape(node_plan.get("goal", ""))
3335 expected_output = _html.escape(node_plan.get("expected_output", ""))
3336 success_criteria = _html.escape(node_plan.get("success_criteria", ""))
3338 if not (goal or expected_output):
3339 return ""
3341 lines = ["<plan>"]
3342 if overall_goal:
3343 lines.append(f" <overall_goal>{overall_goal}</overall_goal>")
3344 lines.append(" <your_assignment>")
3345 if goal:
3346 lines.append(f" <goal>{goal}</goal>")
3347 if expected_output:
3348 lines.append(f" <expected_output>{expected_output}</expected_output>")
3349 if success_criteria:
3350 lines.append(f" <success_criteria>{success_criteria}</success_criteria>")
3351 lines.append(" </your_assignment>")
3352 lines.append("</plan>")
3353 return "\n".join(lines)
3355 return inject_plan
3358# Module-level singleton chains — created once at import, invoked per execution.
3359_RETRIEVAL_PROMPT_CHAIN = _make_node_prompt_chain(
3360 role="knowledge_retrieval_specialist",
3361 base_instructions=prompts.NODE_RETRIEVAL,
3362)
3363_EXTERNAL_RETRIEVAL_PROMPT_CHAIN = _make_node_prompt_chain(
3364 role="external_data_retrieval_specialist",
3365 base_instructions=prompts.NODE_EXTERNAL_RETRIEVAL,
3366)
3367_TOOL_RETRIEVAL_PROMPT_CHAIN = _make_node_prompt_chain(
3368 role="tool_based_information_retrieval_specialist",
3369 base_instructions=prompts.NODE_TOOL_RETRIEVAL,
3370)
3371_SYNTHESIS_PROMPT_CHAIN = _make_node_prompt_chain(
3372 role="synthesis_specialist",
3373 base_instructions=prompts.NODE_SYNTHESIS,
3374)
3375_PLAN_INJECTION_CHAIN = _make_plan_injection_chain()
3378StateType = TypeVar("StateType", bound=BaseModel)
3381class _SystemWorker(WorkerAgent):
3382 """Minimal concrete WorkerAgent for __retrieval__ and __synthesis__ nodes."""
3384 async def execute(self, input_data: Any) -> Any:
3385 messages = self.build_messages(str(input_data))
3386 if self.tools:
3387 output, _ = await self.run_with_tools(messages)
3388 return output
3389 llm = self.resolve_llm()
3390 response = await llm.ainvoke(messages)
3391 return reply_text(llm, response, self.name)
3394@dataclass
3395class GraphNode:
3396 """Represents a node in the execution graph."""
3398 id: str
3399 agent: WorkerAgent
3400 next_nodes: dict[str, str] = field(default_factory=dict)
3401 is_start: bool = False
3402 is_end: bool = False
3403 conditional_edges: Optional[Callable[[Any], str]] = None
3404 # Maps condition-function return values to target node IDs.
3405 # Passed directly to LangGraph as path_map.
3406 conditional_edge_map: dict[str, str] = field(default_factory=dict)
3407 # ── State bindings (skill graph schema v2) ────────────────────────────
3408 # output_key: state variable this node's output is written to
3409 # (state_vars[output_key] = result). Empty → no state write.
3410 # prompt_template: for agent nodes, replaces the default aggregated task
3411 # content; ``{key}`` placeholders render from state variables.
3412 # input_keys: state variables surfaced to an agent node as context even
3413 # without a prompt_template.
3414 output_key: str = ""
3415 prompt_template: str = ""
3416 input_keys: list[str] = field(default_factory=list)
3417 # ── Typed bindings (skill graph schema v3) ────────────────────────────
3418 # inputs: worker input field → binding. A binding is a literal or a
3419 # "{path}" reference into the graph variables (input, state
3420 # keys, node results). Bound values are validated against the
3421 # agent's input_schema and surfaced to the LLM as <inputs>.
3422 inputs: dict[str, Any] = field(default_factory=dict)
3423 # ── Human in the loop (per node) ──────────────────────────────────────
3424 # approval: pause *before* this node runs and show what the graph has
3425 # produced so far; ``{"message": str}``. Rejecting stops the
3426 # run (``RunRejected``); approving with feedback hands that
3427 # feedback to this node. Placed before the node's work so a
3428 # resume, which replays the node, repeats nothing that was paid.
3429 # ask_user: give this node the ``ask_user`` tool, so it can put
3430 # clarifying questions to the person and wait for answers.
3431 approval: dict[str, Any] | None = None
3432 ask_user: bool = False
3435class RunRejected(Exception):
3436 """A person declined an approval gate — the run stops there, by design.
3438 Not an error: the engines turn it into a response saying where the run
3439 stopped and why, rather than a failure.
3440 """
3442 def __init__(self, node_id: str, feedback: str = "") -> None:
3443 super().__init__(f"Rejected at {node_id}")
3444 self.node_id = node_id
3445 self.feedback = feedback
3447 def payload(self) -> dict[str, Any]:
3448 return {"node_id": self.node_id, "feedback": self.feedback}
3451#: Interrupt discriminator for an approval gate (the whole-run gate uses the
3452#: same one, so a client handles both with one control).
3453APPROVAL_INTERRUPT = "approval_request"
3454#: Characters of each completed node's output shown at a gate.
3455APPROVAL_PREVIEW_CHARS = 4000
3458# ---------------------------------------------------------------------------
3459# GraphState reducers
3460#
3461# Every field that more than one node can write in the same superstep needs a
3462# reducer, otherwise LangGraph raises InvalidUpdateError on parallel branches
3463# (Send fan-out for retrieval_type=="both", convergent skill graphs like
3464# [analyzer_a, analyzer_b] → validator).
3465# ---------------------------------------------------------------------------
3468def _merge_dicts(existing: dict, new: dict) -> dict:
3469 """Shallow-merge dict updates; later writes win per key."""
3470 return {**existing, **new}
3473def _merge_reports(existing: dict, new: dict) -> dict:
3474 """``_merge_dicts``, except that an empty value never replaces one an
3475 earlier write set: a corrective retrieval pass whose judge worked does
3476 not make the first pass's unjudged passages, still in the evidence,
3477 judged."""
3478 return {**existing, **{k: v for k, v in new.items() if v or not existing.get(k)}}
3481def _max_step(existing: int, new: int) -> int:
3482 """Parallel nodes report the same step number; keep the highest."""
3483 return max(existing, new)
3486def _sticky_error_status(existing: str, new: str) -> str:
3487 """Once any branch reports "error" the pipeline status stays "error"."""
3488 if "error" in (existing, new):
3489 return "error"
3490 return new or existing
3493def _merge_retrieval_context(existing: str, new: str) -> str:
3494 """Concatenate retrieval sections from independent retrieval nodes."""
3495 if not new:
3496 return existing
3497 if not existing:
3498 return new
3499 return f"{existing}\n\n---\n\n{new}"
3502def _merge_state_vars(existing: dict, new: dict) -> dict:
3503 """Merge user-visible skill state written by (possibly parallel) nodes.
3505 Per-key semantics mirror LangGraph state channels without requiring a
3506 custom schema class per skill:
3507 list + list → concatenate (parallel branches accumulate)
3508 dict + dict → shallow merge
3509 otherwise → new value wins (overwrite)
3510 """
3511 merged = dict(existing)
3512 for key, value in new.items():
3513 current = merged.get(key)
3514 if isinstance(current, list) and isinstance(value, list):
3515 merged[key] = current + value
3516 elif isinstance(current, dict) and isinstance(value, dict):
3517 merged[key] = {**current, **value}
3518 else:
3519 merged[key] = value
3520 return merged
3523# ---------------------------------------------------------------------------
3524# Render artifacts
3525#
3526# The render_* tools return pre-validated code fences (```map, ```chart, …)
3527# that the frontend displays and that must reach the user VERBATIM. A fence
3528# lives only in a ToolMessage unless the calling agent re-embeds it — and
3529# ToolMessages never reach a downstream node (``_history_messages`` replays
3530# only the conversation), so a rewrite pass (synthesis, evaluator revision)
3531# silently drops the visual. These helpers capture fences into
3532# GraphState.artifacts, the durable channel that lets synthesis/evaluator
3533# embed them and lets the evaluator restore any fence a rewrite dropped.
3534# ---------------------------------------------------------------------------
3536_ARTIFACT_FENCE_RE = re.compile(
3537 r"```("
3538 + "|".join(re.escape(language) for language in prompts.ARTIFACT_FENCE_LANGUAGES)
3539 + r")[ \t]*\n.*?\n```",
3540 re.DOTALL,
3541)
3543# Documents (render_document) are handled apart from the visual fences. A
3544# document can run to many pages, so a model is never asked to copy one: the
3545# rewrite passes see a one-line note in its place, and the artifact guard
3546# strips any document fence a model wrote and attaches the tool's own. What
3547# reaches the user is therefore exactly what the tool validated.
3548_DOCUMENT_TYPE = "document"
3549_DOCUMENT_FENCE_MARK = "```" + _DOCUMENT_TYPE
3552def _fence_type(fence: str) -> str | None:
3553 m = _ARTIFACT_FENCE_RE.match(fence)
3554 return m.group(1) if m else None
3557def _document_note(fence: str) -> str:
3558 from app.documents import parse_document_fences
3560 docs = parse_document_fences(fence)
3561 title = docs[0].title if docs else "Untitled document"
3562 return (
3563 f'<document title="{title.replace(chr(34), chr(39))}" note="Attached to '
3564 "the reply automatically as a downloadable document. Refer to it by "
3565 'title; do NOT reproduce its content or its fence." />'
3566 )
3569#: How much of an attached document's body the quality check reads. Every
3570#: other part is read whole: the spec bounds each.
3571_CHECK_DOCUMENT_CHARS = 8000
3572#: The most of a document's sources list the check reads.
3573_CHECK_DOCUMENT_SOURCES = 40
3574#: A visual fence inside a document's body, as the check reads it.
3575_BODY_VISUAL_RE = re.compile(
3576 r"```("
3577 + "|".join(re.escape(language) for language in prompts.VISUAL_FENCE_LANGUAGES)
3578 + r")[ \t]*\n(.*?)\n```",
3579 re.DOTALL,
3580)
3583def _visual_mention(match: re.Match[str]) -> str:
3584 """``[chart: Quarterly sales]`` for a visual fence: what it is and its
3585 title, never its data."""
3586 kind, body = match.group(1), match.group(2)
3587 try:
3588 title = safe_json.loads_exact(body).get("title")
3589 except (ValueError, AttributeError):
3590 title = None
3591 return (
3592 f"[{kind}: {title}]"
3593 if isinstance(title, str) and title.strip()
3594 else f"[{kind}]"
3595 )
3598def _document_for_check(
3599 fence: str, registry: source_registry.SourceRegistry | None = None
3600) -> str:
3601 """A document the reply attaches, as the quality check reads it: every
3602 part its PDF prints, in the PDF's order — subtitle, confidence, summary,
3603 key findings, body, open questions and the numbered sources, each with
3604 the id ``registry`` handed it out under.
3606 The check was shown its title alone (``_document_note``), so a reply
3607 describing its own report — "the brief covers North Yorkshire's
3608 savings" — read as unsupported (scenario run 6). Then it was shown the
3609 summary, findings and body alone, so a summary naming the brief's open
3610 questions read as contradicted and Research brief re-ran twice, and a
3611 body citing ``[1]`` read as citing a list that was not there (run 7).
3612 History still replays the note: a model is never asked to copy a
3613 document."""
3614 from app.documents import parse_document_fences
3616 docs = parse_document_fences(fence)
3617 if not docs:
3618 return _document_note(fence)
3619 doc = docs[0]
3620 body = _BODY_VISUAL_RE.sub(_visual_mention, doc.body).strip()
3621 if len(body) > _CHECK_DOCUMENT_CHARS:
3622 body = body[:_CHECK_DOCUMENT_CHARS].rstrip() + "…"
3623 parts: list[str] = []
3624 if doc.subtitle:
3625 parts.append(f"Subtitle: {doc.subtitle}")
3626 if doc.confidence:
3627 parts.append(f"Confidence: {doc.confidence}")
3628 if doc.summary:
3629 parts.append(f"Summary: {doc.summary}")
3630 if doc.key_findings:
3631 parts.append(
3632 "Key findings:\n" + "\n".join(f"- {line}" for line in doc.key_findings)
3633 )
3634 if body:
3635 parts.append(body)
3636 if doc.open_questions:
3637 parts.append(
3638 "Open questions:\n" + "\n".join(f"- {line}" for line in doc.open_questions)
3639 )
3640 if doc.sources:
3641 parts.append("Sources:\n" + _document_sources_for_check(doc.sources, registry))
3642 title = (doc.title or "Untitled document").replace('"', "'")
3643 return (
3644 f'<document title="{title}" note="Attached to the reply by CHAIN-R as a '
3645 'downloadable PDF, whatever the draft says."><![CDATA['
3646 + attachment_util.cdata("\n\n".join(parts))
3647 + "]]></document>"
3648 )
3651def _document_sources_for_check(
3652 lines: list[str], registry: source_registry.SourceRegistry | None
3653) -> str:
3654 """A document's sources list numbered as its PDF numbers it — the
3655 ``[n]`` its text cites — each with the id it has in ``<sources>`` when
3656 ``render_document`` built the line from one."""
3657 ids: dict[str, str] = {}
3658 if registry is not None:
3659 for sid, citation in registry.sources().items():
3660 ids.setdefault(answer_sources.document_line(citation), sid)
3661 shown = [
3662 f"[{n}] {line}" + (f" (id {ids[line]} in <sources>)" if line in ids else "")
3663 for n, line in enumerate(lines[:_CHECK_DOCUMENT_SOURCES], start=1)
3664 ]
3665 if len(lines) > _CHECK_DOCUMENT_SOURCES:
3666 shown.append(f"… and {len(lines) - _CHECK_DOCUMENT_SOURCES} more")
3667 return "\n".join(shown)
3670def _attach_documents(final_output: str, artifacts: list[str]) -> str:
3671 """Replace every ```document fence in ``final_output`` with the ones the
3672 tool produced. A model-written copy is never kept — it may be truncated
3673 or altered — and a document the model left out is still attached."""
3674 documents = [f for f in artifacts if _fence_type(f) == _DOCUMENT_TYPE]
3675 if not documents and "```" + _DOCUMENT_TYPE not in final_output:
3676 return final_output
3677 stripped = _ARTIFACT_FENCE_RE.sub(
3678 lambda m: "" if m.group(1) == _DOCUMENT_TYPE else m.group(0), final_output
3679 ).rstrip()
3680 if not documents:
3681 return stripped
3682 return stripped + "\n\n" + "\n\n".join(documents)
3685def _extract_artifact_fences(messages: list[BaseMessage]) -> list[str]:
3686 """Collect render-tool fences from the ToolMessages produced by one node."""
3687 fences: list[str] = []
3688 for msg in messages:
3689 if isinstance(msg, ToolMessage):
3690 content = msg.content if isinstance(msg.content, str) else str(msg.content)
3691 fences.extend(m.group(0) for m in _ARTIFACT_FENCE_RE.finditer(content))
3692 return fences
3695def _operation_artifacts(result: Any) -> list[str]:
3696 """Render fences in a tool node's output — a skill graph can call
3697 ``render_document`` (or a chart tool) deterministically, and its fence
3698 must reach the reply the same way an agent's tool call does."""
3699 if not isinstance(result, str):
3700 return []
3701 return [m.group(0) for m in _ARTIFACT_FENCE_RE.finditer(result)]
3704def _merge_artifacts(existing: list[str], new: list[str]) -> list[str]:
3705 """Order-preserving concatenation with exact-match dedupe.
3707 Evaluator retries re-run the skill graph, which re-renders identical
3708 fences; plain operator.add would accumulate duplicates.
3709 """
3710 merged = list(existing)
3711 for fence in new:
3712 if fence not in merged:
3713 merged.append(fence)
3714 return merged
3717#: Where a document came from. A skill's document step (a ``render_document``
3718#: tool node) renders its document deterministically from the skill's own
3719#: output; a model may also call ``render_document`` itself — the agent, a
3720#: worker, or synthesis.
3721_FROM_STEP = "step"
3722_FROM_MODEL = "model"
3725def _document_entries(
3726 fences: list[str], *, pass_index: int, source: str
3727) -> list[dict[str, Any]]:
3728 """The document fences among ``fences``, tagged with the pass (the
3729 evaluator's retry count when they were rendered) and their source."""
3730 return [
3731 {"fence": f, "pass": pass_index, "source": source}
3732 for f in fences
3733 if _fence_type(f) == _DOCUMENT_TYPE
3734 ]
3737def _visual_fences(fences: list[str]) -> list[str]:
3738 """The render fences that are not documents (maps, charts, …)."""
3739 return [f for f in fences if _fence_type(f) != _DOCUMENT_TYPE]
3742def _merge_documents(
3743 existing: list[dict[str, Any]], new: list[dict[str, Any]]
3744) -> list[dict[str, Any]]:
3745 merged = list(existing)
3746 for entry in new:
3747 if entry not in merged:
3748 merged.append(entry)
3749 return merged
3752def _document_title(fence: str) -> str:
3753 from app.documents import parse_document_fences
3755 docs = parse_document_fences(fence)
3756 return docs[0].title if docs else fence
3759def _reply_documents(documents: list[dict[str, Any]]) -> list[str]:
3760 """The documents a reply carries: those of the latest pass that rendered
3761 any, one per title, a skill's document step before a model's own call.
3763 Every document a run rendered used to be attached. A revision re-runs the
3764 skill graph and renders the document again with the revised content, and
3765 in one pass the agent, the skill's document step and synthesis may each
3766 render it, so a Research brief chat came back with five PDF cards. A
3767 revision's document supersedes the earlier pass's; within a pass the
3768 skill's step is what the skill was designed to deliver, and a later
3769 rendering of the same title supersedes an earlier one. A pass that
3770 rendered nothing (a revision that only fixed the text) leaves the
3771 previous documents in place.
3772 """
3773 if not documents:
3774 return []
3775 latest = max(int(d.get("pass", 0)) for d in documents)
3776 current = [d for d in documents if int(d.get("pass", 0)) == latest]
3777 if any(d.get("source") == _FROM_STEP for d in current):
3778 current = [d for d in current if d.get("source") == _FROM_STEP]
3779 by_title: dict[str, str] = {}
3780 for entry in current:
3781 by_title[_document_title(entry["fence"])] = entry["fence"]
3782 return list(by_title.values())
3785def _seen_by_the_run(state: "GraphState") -> list[str]:
3786 """Every text the run was given or found: the person's words, the earlier
3787 turns, what its tools returned and the evidence it was handed. An image
3788 an answer shows must come from one of them
3789 (``answer_artifacts.drop_unseen_images``)."""
3790 seen = [
3791 state.input,
3792 state.request_before_clarification,
3793 state.retrieval_context,
3794 state.frameworks_context,
3795 state.web_context,
3796 state.tool_context,
3797 *(str(entry.get("content") or "") for entry in _history_entries(state)),
3798 *(a.text for a in state.attachments or [] if getattr(a, "text", "")),
3799 ]
3800 for message in state.messages:
3801 if isinstance(message, (ToolMessage, HumanMessage)):
3802 seen.append(reply_formats.text_of(message.content))
3803 return seen
3806def _restore_missing_artifacts(
3807 final_output: str, artifacts: list[str], documents: Sequence[str] = ()
3808) -> str:
3809 """Append render fences that a rewrite pass dropped from the final output.
3811 Conservative: a fence is only restored when the final output contains NO
3812 fence of the same type — a surviving fence of that type means the model
3813 kept (or legitimately re-rendered) the visual, and appending another
3814 would duplicate it. When retries produced several fences of one type,
3815 the most recent wins. A visual a reply's document carries in its body
3816 (``documents``) is the document's, and is not restored into the reply.
3817 """
3818 if not artifacts:
3819 return final_output
3820 present_types = {m.group(1) for m in _ARTIFACT_FENCE_RE.finditer(final_output)}
3821 in_documents = answer_artifacts.visual_fences_in(documents) if documents else set()
3822 latest_by_type: dict[str, str] = {}
3823 for fence in artifacts:
3824 m = _ARTIFACT_FENCE_RE.match(fence)
3825 # Documents are attached whole by _attach_documents, not restored.
3826 if m and m.group(1) != _DOCUMENT_TYPE:
3827 if answer_artifacts._key(fence) in in_documents:
3828 continue
3829 latest_by_type[m.group(1)] = fence
3830 additions = [f for t, f in latest_by_type.items() if t not in present_types]
3831 if not additions:
3832 return final_output
3833 return final_output.rstrip() + "\n\n" + "\n\n".join(additions)
3836#: How much of a tool result a downstream model reads: the whole of it up to
3837#: ``_TOOL_RESULT_CHARS``; past that, its blank-line separated blocks share
3838#: that budget, each cut to no less than ``_TOOL_BLOCK_CHARS``. A tool that
3839#: returns several items writes one block each — web_search a Title / URL /
3840#: date / snippet block per result — so a cut per block keeps every item's
3841#: opening lines, where one cut of the whole message kept the first result or
3842#: two: the quality check could not see results 2–5 of a five-result search,
3843#: and failed an answer built on them.
3844_TOOL_BLOCK_CHARS = 400
3845_TOOL_RESULT_CHARS = 3000
3846#: A result carrying a render fence is kept whole up to this: a cut fence can
3847#: never be restored into the reply.
3848_TOOL_FENCE_CHARS = 8000
3849#: The whole ``<prior_tool_calls>`` ledger, which reaches the reviser and
3850#: every skill node: the newest calls whole, earlier ones to one line each.
3851#: Without a cap a tool-heavy graph (25 calls of 3,000 characters) would add
3852#: ~75,000 characters to every downstream call.
3853_TOOL_LEDGER_CHARS = 12_000
3854#: An abridged ledger entry: its result's first line, cut to this.
3855_TOOL_LEDGER_LINE_CHARS = 200
3858def _shared_block_limit(lengths: list[int], total_chars: int) -> int:
3859 """The longest cut that lets blocks of these ``lengths`` fit
3860 ``total_chars`` together, the blank lines between them and each cut
3861 block's ``…`` counted: a block shorter than an even share of what is
3862 left keeps its length, and the longer ones share the rest."""
3863 remaining = total_chars - 2 * (len(lengths) - 1)
3864 for i, size in enumerate(sorted(lengths)):
3865 share = remaining // (len(lengths) - i)
3866 if size > share:
3867 return share - 1
3868 remaining -= size
3869 return max(lengths, default=0)
3872#: A figure as an answer states it: digits with a decimal point or a
3873#: thousands comma, or three digits or more (``_draft_figures``).
3874_FIGURE = re.compile(r"(?<![\w.])\d{1,3}(?:,\d{3})+(?:\.\d+)?|(?<![\w.])\d+(?:\.\d+)?")
3875#: Figures read from one draft at most.
3876_MAX_FIGURES = 40
3879def _draft_figures(text: str) -> frozenset[str]:
3880 """The figures an answer states that a source would have to hold —
3881 amounts, percentages, decimals, ids — as written, commas and all. A
3882 bare year and a one- or two-digit number are left out: every page holds
3883 them. What the check marks "not in any of the tool results" is most
3884 often one of these, and where a long page held it the digest had cut it
3885 (``_tool_result_digest``'s ``keep``)."""
3886 found: list[str] = []
3887 for match in _FIGURE.finditer(text or ""):
3888 token = match.group(0)
3889 digits = token.replace(",", "")
3890 follows = (text[match.end() : match.end() + 1] or "").strip()
3891 if "." not in digits and len(digits) < 3 and follows != "%":
3892 continue
3893 if len(digits) == 4 and digits.isdigit() and 1900 <= int(digits) <= 2099:
3894 continue
3895 if token not in found:
3896 found.append(token)
3897 if len(found) >= _MAX_FIGURES:
3898 break
3899 return frozenset(found)
3902def _holds_figure(block: str, figures: frozenset[str]) -> bool:
3903 return any(
3904 re.search(rf"(?<![\d.]){re.escape(f)}(?!\d)", block)
3905 or (
3906 "," in f
3907 and re.search(rf"(?<![\d.]){re.escape(f.replace(',', ''))}(?!\d)", block)
3908 )
3909 for f in figures
3910 )
3913def _tool_result_digest(
3914 text: str,
3915 *,
3916 block_chars: int = _TOOL_BLOCK_CHARS,
3917 total_chars: int = _TOOL_RESULT_CHARS,
3918 keep: frozenset[str] = frozenset(),
3919) -> str:
3920 """``text`` whole when it fits ``total_chars``, else abridged block by
3921 block (see ``_TOOL_BLOCK_CHARS``).
3923 A result that fits is never cut: a one-block JSON reply or a five-result
3924 search under the total reaches the reader as the tool wrote it. One that
3925 does not is cut block by block — a block being the text between blank
3926 lines — each to one shared limit (marked ``…``): the largest that lets
3927 every block fit the total, short blocks kept whole and the rest of the
3928 budget split among the long ones, never below ``block_chars``. A lone
3929 block is cut to the total. Blocks are kept in order while they fit; the
3930 first is always kept, and those left out are counted, so a reader knows
3931 the result went on. Every tool's result is read the same way.
3933 ``keep`` (``_draft_figures``) puts first the blocks that hold a figure
3934 the answer states, whole where the total allows: the check had failed
3935 answers for an IBISWorld market size "not in any of the tool results"
3936 that sat further down the page than the first 3,000 characters. Blocks
3937 still appear in the order the tool wrote them.
3938 """
3939 text = text.strip()
3940 if len(text) <= total_chars:
3941 return text
3942 blocks = [b for b in re.split(r"\n\s*\n", text) if b.strip()]
3943 if len(blocks) == 1:
3944 return text[:total_chars].rstrip() + "…"
3945 limit = min(
3946 max(block_chars, _shared_block_limit([len(b) for b in blocks], total_chars)),
3947 total_chars,
3948 )
3949 held = {i for i, block in enumerate(blocks) if keep and _holds_figure(block, keep)}
3950 # The first block, then the blocks holding a figure, then the rest in
3951 # order — each while the total allows.
3952 order = [
3953 0,
3954 *sorted(held - {0}),
3955 *(i for i in range(len(blocks)) if i not in held and i),
3956 ]
3957 chosen: dict[int, str] = {}
3958 used = 0
3959 for i in order:
3960 block = blocks[i]
3961 room = total_chars - used - (2 if chosen else 0)
3962 width = min(len(block), room) if i in held else limit
3963 cut = block if len(block) <= width else block[:width].rstrip() + "…"
3964 cost = len(cut) + (2 if chosen else 0)
3965 if chosen and (used + cost > total_chars or room <= 0):
3966 if i in held:
3967 continue
3968 break
3969 chosen[i] = cut
3970 used += cost
3971 kept = [chosen[i] for i in sorted(chosen)]
3972 digest = "\n\n".join(kept)
3973 left_out = len(blocks) - len(kept)
3974 if left_out:
3975 digest += (
3976 f"\n\n[{left_out} more block{'s' if left_out != 1 else ''} of this "
3977 "result left out]"
3978 )
3979 return digest
3982def _tool_call_ledger(
3983 messages: list[BaseMessage],
3984 max_result_chars: int = _TOOL_RESULT_CHARS,
3985 max_calls: int = 25,
3986 max_chars: int = _TOOL_LEDGER_CHARS,
3987 keep: frozenset[str] = frozenset(),
3988) -> str:
3989 """Compact digest of every tool call made by earlier pipeline stages.
3991 Injected into skill-node context so downstream agents REUSE prior results
3992 instead of repeating identical calls — the raw ToolMessages themselves
3993 never reach a downstream node (``_history_messages`` replays only the
3994 conversation), which otherwise leaves re-calling as the only way to
3995 recover the information. A reviser re-checks its own answer against it,
3996 so each result is read whole where it fits and otherwise abridged block
3997 by block (``_tool_result_digest``), never cut to its first few hundred
3998 characters.
4000 The whole is bounded by ``max_chars``: the newest calls are kept whole,
4001 earlier ones are cut to their result's first line, and what still does
4002 not fit — the oldest, and any past ``max_calls`` — is left out. A note
4003 says how many were abridged or left out.
4004 """
4005 results_by_id: dict[str, ToolMessage] = {
4006 m.tool_call_id: m for m in messages if isinstance(m, ToolMessage)
4007 }
4008 # (call, full digest) per call, oldest first.
4009 entries: list[tuple[str, str]] = []
4010 for msg in messages:
4011 for tc in getattr(msg, "tool_calls", None) or []:
4012 if isinstance(tc, dict):
4013 name, args, tc_id = (
4014 tc.get("name", "?"),
4015 tc.get("args", {}),
4016 tc.get("id"),
4017 )
4018 else:
4019 name = getattr(tc, "name", "?")
4020 args = getattr(tc, "args", {})
4021 tc_id = getattr(tc, "id", None)
4022 tm = results_by_id.get(tc_id) if tc_id else None
4023 shown_args = str(args)[:200]
4024 if tm is None:
4025 digest = "(no result recorded)"
4026 else:
4027 raw = tm.content if isinstance(tm.content, str) else str(tm.content)
4028 if _DOCUMENT_FENCE_MARK in raw:
4029 # A document is attached already: its note, and what the
4030 # tool said about it (images it could not embed) — never
4031 # its arguments or its fence, which a reviser copied out
4032 # as its whole answer.
4033 raw = _ARTIFACT_FENCE_RE.sub(
4034 lambda m: (
4035 _document_note(m.group(0))
4036 if m.group(1) == _DOCUMENT_TYPE
4037 else m.group(0)
4038 ),
4039 raw,
4040 )
4041 title = args.get("title") if isinstance(args, dict) else None
4042 shown_args = f"title={str(title or '')[:120]!r}"
4043 held_by_none = source_ledger.not_held(raw)
4044 if held_by_none:
4045 digest = source_ledger.NOT_HELD_NOTE.format(tool=held_by_none)
4046 else:
4047 digest = _tool_result_digest(
4048 raw, total_chars=max_result_chars, keep=keep
4049 )
4050 if getattr(tm, "status", None) == "error":
4051 digest = f"ERROR: {digest}"
4052 entries.append((f"- {name}({shown_args})", digest))
4053 if not entries:
4054 return ""
4055 left_out = max(0, len(entries) - max_calls)
4056 entries = entries[left_out:]
4058 # Newest first: whole while they fit, then one line each, then nothing.
4059 lines: list[str] = []
4060 abridged = 0
4061 used = 0
4062 for i, (call, digest) in enumerate(reversed(entries)):
4063 line = f"{call} → {digest}"
4064 if i and (abridged or used + len(line) + 1 > max_chars):
4065 first = next((ln for ln in digest.splitlines() if ln.strip()), "")
4066 if len(first) > _TOOL_LEDGER_LINE_CHARS:
4067 first = first[:_TOOL_LEDGER_LINE_CHARS].rstrip() + "…"
4068 line = f"{call} → {first} [abridged]"
4069 if used + len(line) + 1 > max_chars:
4070 left_out += len(entries) - i
4071 break
4072 abridged += 1
4073 lines.append(line)
4074 used += len(line) + 1
4075 lines.reverse()
4076 notes = []
4077 if abridged:
4078 notes.append(
4079 f"{abridged} earlier call{'s' if abridged != 1 else ''} abridged to "
4080 "the first line of the result"
4081 )
4082 if left_out:
4083 notes.append(f"{left_out} earliest call{'s' if left_out != 1 else ''} left out")
4084 if notes:
4085 lines.insert(0, f"({'; '.join(notes)})")
4086 return "\n".join(lines)
4089class GraphState(BaseModel):
4090 """
4091 Shared state flowing through the agent graph.
4093 ``messages`` uses the LangGraph ``add_messages`` reducer — node functions
4094 return a list containing only the new message(s) and LangGraph appends
4095 them, rather than replacing the whole list. ``results``, ``context``,
4096 ``errors``, ``retrieval_context``, ``step_count`` and ``status`` carry
4097 reducers for the same reason: parallel branches (Send retrieval fan-out,
4098 convergent skill graphs) write them concurrently.
4100 Node functions must therefore return only their OWN delta for these
4101 fields (e.g. ``{"errors": ["node_x: boom"]}``), never a copy of the
4102 accumulated value.
4104 Full message trace
4105 ------------------
4106 Every message produced by any agent — including intermediate tool-call
4107 AIMessages and ToolMessages — is stored here. This gives complete
4108 traceability of the conversation and is used for:
4110 - Token-usage accounting across all nodes
4111 - Streaming events to the client
4112 - The evaluator's tool-call audit and the skill nodes' tool ledger
4114 It is a trace, not a conversation: the only part of it replayed to a
4115 model is the caller's history (``_history_messages`` — unnamed messages,
4116 since every node names what it writes).
4118 Extend for application-specific fields::
4120 class MyState(GraphState):
4121 quality_score: float = 0.0
4122 """
4124 input: str = Field(description="Original user input")
4125 step_count: Annotated[int, _max_step] = Field(
4126 default=0,
4127 description="Trace step counter; max-reduced so parallel branches count as one step",
4128 )
4129 # add_messages reducer: returning {"messages": [new_msgs...]} appends, not replaces.
4130 messages: Annotated[list[BaseMessage], add_messages] = Field(default_factory=list)
4131 context: Annotated[dict[str, Any], _merge_dicts] = Field(
4132 default_factory=dict, description="Shared context between agents"
4133 )
4134 results: Annotated[dict[str, Any], _merge_dicts] = Field(
4135 default_factory=dict, description="Structured output keyed by node ID"
4136 )
4137 errors: Annotated[list[str], operator.add] = Field(default_factory=list)
4138 status: Annotated[str, _sticky_error_status] = Field(default="running")
4139 route: str = Field(
4140 default="",
4141 description=(
4142 "Data-source route set by __gate__: trivial | direct | retrieve. "
4143 "Empty string falls back to 'retrieve' (full pipeline) in all routers. "
4144 "Complexity and synthesis decisions are in resource_strategy, from the same triage."
4145 ),
4146 )
4147 retrieval_type: str = Field(
4148 default="internal",
4149 description=(
4150 "Which data sources to query, set by __gate__: "
4151 "internal | external | tools | both. "
4152 "Only meaningful when route is 'retrieve'."
4153 ),
4154 )
4155 # Knowledge base descriptors injected at skill-execution time.
4156 # Each entry mirrors KnowledgeBaseSpec: id, name, description, source_type,
4157 # source_config, config. Stored as plain dicts to keep GraphState
4158 # JSON-serialisable without a cross-module import.
4159 knowledge_bases: list[dict[str, Any]] = Field(
4160 default_factory=list,
4161 description="KB descriptors available to every node in this graph",
4162 )
4163 # The documents the person attached to the conversation, apart from
4164 # their words in ``input`` (``app/util/attachments.py``): each readable
4165 # one a source with its ``[S#]``. Set once, at the boundary.
4166 attachments: list[attachment_util.Attachment] = Field(
4167 default_factory=list,
4168 description="Documents attached to the conversation, this message's first",
4169 )
4170 # How the answering agent is shown each document — whole, listed for the
4171 # attachment tools, or unavailable — as the gate planned it for the
4172 # agent's model (``Planned.summary``: never a document's text). For the
4173 # trace: the gate's frame carries it.
4174 attachment_plan: list[dict[str, Any]] = Field(
4175 default_factory=list,
4176 description="How each attached document is delivered to the answering agent",
4177 )
4178 # ResourceStrategy from triage — determines whether to invoke the skill
4179 # graph or short-circuit to synthesis, and seeds tool_guidance for planning.
4180 # STALE-READ RISK: this is triage's raw dump. Its "needs_synthesis" value
4181 # may be overridden by __planning__ (multi-node dispatch forces synthesis);
4182 # readers must use ``state.needs_synthesis``, never this dict's copy.
4183 resource_strategy: dict[str, Any] = Field(
4184 default_factory=dict,
4185 description="ResourceStrategy dict from triage: complexity, use_skill_graph, relevant_tools, resource_notes",
4186 )
4187 # Structured retrieval output produced by the retrieval nodes and consumed
4188 # by skill nodes as read-only context. Skill nodes cannot query KBs directly.
4189 # Reducer concatenates sections so parallel internal+external retrieval
4190 # (Send fan-out on retrieval_type=="both") merges instead of colliding.
4191 # Retrieval nodes return ONLY their own section, never the merged value.
4192 retrieval_context: Annotated[str, _merge_retrieval_context] = Field(
4193 default="",
4194 description="Pre-retrieved knowledge context from the retrieval node(s)",
4195 )
4196 #: The frameworks internal retrieval packed apart from the evidence
4197 #: (reasoning knowledge, ``RetrievalBundle.frameworks_markdown``): the
4198 #: answering node reads them as the approach to take, in ``<frameworks>``
4199 #: before ``<knowledge>``, never as evidence.
4200 frameworks_context: str = Field(
4201 default="",
4202 description="Frameworks to apply, from reasoning knowledge",
4203 )
4204 # ── Retrieval branches, staged for ``__retrieval_join__`` ──────────────
4205 # Each written by one node in one superstep and cleared by the join,
4206 # which alone writes ``retrieval_context`` and the rest of what the
4207 # answer reads: the knowledge first, then the web, then the tools,
4208 # whatever order the branches finished in.
4209 #: What ``__knowledge_plan__`` planned: ``{"mode": "pipeline" | "hybrid"
4210 #: | "agentic" | "gap" | "none", "query", "plan" (``KnowledgePlan.dump``),
4211 #: "lanes" [kinds], "on" (the day, ISO), "gaps", "error"}``.
4212 knowledge_plan: dict[str, Any] = Field(
4213 default_factory=dict,
4214 description="The turn's knowledge search as planned, for its lanes and the join",
4215 )
4216 #: One lane's search (``LaneResult.dump``), per kind of knowledge.
4217 domain_lane: dict[str, Any] = Field(
4218 default_factory=dict, description="The domain lane's search"
4219 )
4220 temporal_lane: dict[str, Any] = Field(
4221 default_factory=dict, description="The temporal lane's search"
4222 )
4223 reasoning_lane: dict[str, Any] = Field(
4224 default_factory=dict, description="The reasoning lane's search"
4225 )
4226 #: The web's section (``## External Sources``) and the tools'.
4227 web_context: str = Field(default="", description="What the web search found")
4228 tool_context: str = Field(default="", description="What the tools returned")
4229 # Render-tool fences (```map/```chart/```plot/```graph/```mermaid) captured
4230 # from ToolMessages by the node that made the call. Tool outputs live only
4231 # in ToolMessages, which every downstream context path strips — this field
4232 # is the durable channel that carries them to __synthesis__/__evaluator__
4233 # and lets the evaluator restore any fence a rewrite pass dropped.
4234 artifacts: Annotated[list[str], _merge_artifacts] = Field(
4235 default_factory=list,
4236 description="Render-tool output fences that must reach the user verbatim",
4237 )
4238 # Documents (```document fences) apart from the visuals, each tagged with
4239 # the pass that rendered it and its source, so the reply carries one set:
4240 # see _reply_documents.
4241 documents: Annotated[list[dict[str, Any]], _merge_documents] = Field(
4242 default_factory=list,
4243 description="render_document fences, with the pass and source of each",
4244 )
4245 # User-visible skill state (graph schema v2). Nodes with an ``output_key``
4246 # binding write their result here; operation nodes and prompt templates
4247 # read from it via ``{key}`` placeholders. Surfaced in the execution
4248 # response so users can inspect how state evolved across nodes.
4249 state_vars: Annotated[dict[str, Any], _merge_state_vars] = Field(
4250 default_factory=dict,
4251 description="User-defined skill state carried across graph nodes",
4252 )
4253 # Structured execution plan produced by __planning__ before anything else runs.
4254 # Stored as a plain dict (ExecutionPlan.model_dump()) to stay JSON-serialisable.
4255 # Each node reads its own NodePlan from node_plans keyed by node_id.
4256 execution_plan: dict[str, Any] = Field(
4257 default_factory=dict,
4258 description="Per-node execution plan from the __planning__ node",
4259 )
4260 # Memories recalled from the store before planning. Injected as context
4261 # into planning and skill nodes so agents benefit from past interactions.
4262 memories: list[RecalledMemory] = Field(
4263 default_factory=list,
4264 description="What the agent recalled of this person for this request (app/memory)",
4265 )
4266 # Populated by __memory_write__ for trace display only — not used downstream.
4267 memory_write_result: str = Field(
4268 default="",
4269 description="Summary of what was written to memory (trace display only)",
4270 )
4271 # Skill node IDs selected by the planner for this execution.
4272 # Populated by __planning__ from ExecutionPlan.active_nodes.
4273 # After planning, EMPTY means the planner deliberately skipped the skill
4274 # graph — routers send execution straight to __synthesis__, which answers
4275 # from the retrieved context. Planning failures populate this with every
4276 # registered skill node, so the safe fallback remains "run everything".
4277 active_node_ids: list[str] = Field(
4278 default_factory=list,
4279 description=(
4280 "Skill node IDs selected by the planner for this execution. "
4281 "Empty (after planning) means the skill graph is bypassed and "
4282 "synthesis answers directly from retrieved context."
4283 ),
4284 )
4285 # Compact metadata describing the contents of every attached KB (document
4286 # sources for vector KBs, entity/relationship schema for graph KBs).
4287 # Fetched once by the gate node and reused by planning and retrieval nodes
4288 # so they can reason about what data is available before making tool calls.
4289 kb_metadata: str = Field(
4290 default="",
4291 description="Pre-fetched KB content metadata for routing and planning decisions",
4292 )
4293 # Whether ``kb_metadata`` describes every knowledge base in full. False
4294 # when a count, a document listing or a schema could not be read, so the
4295 # inventory may understate what is there.
4296 #: The knowledge bases confirmed to hold nothing (``_confirmed_empty``),
4297 #: set by the gate: no lane, judge or knowledge tool searches them.
4298 empty_kb_ids: list[str] = Field(default_factory=list)
4299 kb_inventory_complete: bool = Field(
4300 default=False,
4301 description="Whether every knowledge base's contents were read for kb_metadata",
4302 )
4303 # The route triage itself chose, before the gate's own rules changed it,
4304 # and each change they made: ``{"route", "retrieval_type" ("" unless
4305 # route is "retrieve"), "source": "triage" | "fallback", "adjustments":
4306 # [one line each]}``. Set by __gate__ for the trace only; empty on a
4307 # trivial turn.
4308 triage_route: dict[str, Any] = Field(
4309 default_factory=dict,
4310 description="Triage's own route and the gate's adjustments to it (trace only)",
4311 )
4312 # What the internal retrieval pipeline ran without: ``{"planner_failure":
4313 # str, "judge_failure": str, "degraded": [str], "judged_out": int}``
4314 # (``_retrieval_report``), whenever it produced a bundle. A failure stays
4315 # for the turn (``_merge_reports``): with ``judge_failure`` set, the
4316 # answering node is told its knowledge was not checked for relevance.
4317 retrieval_report: Annotated[dict[str, Any], _merge_reports] = Field(
4318 default_factory=dict,
4319 description="What the retrieval pipeline ran without (failed stages)",
4320 )
4321 # Standalone, history-resolved form of the request ("and section 3?" →
4322 # "What does section 3 of the Annual Report 2024 say?"). Set by __gate__;
4323 # every retrieval node searches with this instead of the raw turn.
4324 retrieval_query: str = Field(
4325 default="",
4326 description="History-resolved standalone query used by retrieval nodes",
4327 )
4328 # RetrievalConfig (as a dict) governing the context-rich retrieval pipeline
4329 # run by __internal_retrieval__. Injected by the engine from the spec.
4330 retrieval_config: dict[str, Any] = Field(
4331 default_factory=dict,
4332 description="RetrievalConfig dict for the internal retrieval pipeline",
4333 )
4334 # Structured citations (document / page / chunk / KB provenance) produced by
4335 # the retrieval pipeline. Appended by reducer so parallel retrieval
4336 # branches never overwrite each other; surfaced in the execute response
4337 # and streamed as a ``citations`` frame.
4338 retrieval_citations: Annotated[list[dict[str, Any]], operator.add] = Field(
4339 default_factory=list,
4340 description="Structured citations from the retrieval pipeline",
4341 )
4342 # Set by triage based on task complexity, and force-set to True by
4343 # __planning__ whenever it dispatches more than one skill node (otherwise
4344 # the skip-synthesis path would surface only the last node's output).
4345 # This field is the single source of truth — resource_strategy carries a
4346 # potentially stale copy. When True, a __synthesis__ node consolidates
4347 # all skill-node outputs; when False, the terminal skill node's output
4348 # is used directly.
4349 needs_synthesis: bool = Field(
4350 default=False,
4351 description="Whether a synthesis pass is needed to consolidate skill-node outputs",
4352 )
4353 # Number of times the evaluator has rejected a draft and sent it back
4354 # through the skill graph. Bounded by _MAX_EVAL_RETRIES in
4355 # _evaluator_router; incremented by __evaluator__ on each failed pass.
4356 eval_retry_count: int = Field(
4357 default=0,
4358 description="Evaluator retry-loop counter (bounded by _MAX_EVAL_RETRIES)",
4359 )
4360 # Each failed check's verdict, in pass order (``_check_record``): the next
4361 # check reads them, so a revision is judged on what was asked of it.
4362 quality_checks: Annotated[list[dict[str, Any]], operator.add] = Field(
4363 default_factory=list,
4364 description="Failed quality checks of this answer, oldest first",
4365 )
4366 # User-configured agent identity. Injected by the engine at construction
4367 # time so every node — including the trivial gate bypass and synthesis —
4368 # can respond in the agent's configured persona rather than with generic text.
4369 agent_name: str = Field(
4370 default="",
4371 description="User-configured agent name (e.g. 'Aria')",
4372 )
4373 agent_system_prompt: str = Field(
4374 default="",
4375 description="User-configured agent system prompt defining persona and behaviour",
4376 )
4377 # Scope clarification (``AgentGraphBuilder.clarify_scope``). Triage
4378 # writes the validated clarification payload here when it finds the
4379 # request ambiguous; __clarify__ asks it, clears it and records the
4380 # exchange in ``clarifications``. Held in state — not recomputed — so a
4381 # resume replays __clarify__ against the exact questions the person saw.
4382 pending_clarification: dict[str, Any] | None = Field(
4383 default=None,
4384 description="Clarification payload awaiting an answer (set by triage or a skill step)",
4385 )
4386 clarifications: list[dict[str, Any]] = Field(
4387 default_factory=list,
4388 description="Answered scope clarifications: questions, answers, skipped",
4389 )
4390 # ``input`` as the person sent it, before __clarify__ folded the
4391 # ``<clarified_scope>`` block into it — set once, by the first
4392 # clarification. Memory reads and writes the request from here: the
4393 # block's scaffolding was being stored in episodes and matched in recall
4394 # as if the person had written it.
4395 request_before_clarification: str = Field(
4396 default="",
4397 description="The turn's input before a scope clarification changed it",
4398 )
4401if set(LANE_FIELDS.values()) - set(GraphState.model_fields):
4402 raise RuntimeError("Every kind of knowledge needs its lane's field in GraphState")
4405async def _build_kb_metadata(
4406 knowledge_bases: list[dict[str, Any]],
4407) -> tuple[str, bool]:
4408 """Build a compact, LLM-readable summary of what each KB contains.
4410 Fetched once by the gate node and stored in ``GraphState.kb_metadata`` so
4411 every downstream node (planning, retrieval, skill) can reason about available
4412 content without additional I/O.
4414 For **graph KBs**: uses the cached Neo4j schema (entity types, sample names,
4415 relationship types).
4416 For **vector KBs**: the documents come from svc-core's manifest and the
4417 index scan (``documents.list_documents``, the gate's cached listing) and
4418 the chunk count from the collection.
4420 The knowledge bases are read concurrently: the inventory is on the path
4421 to every turn's first model call.
4423 Returns ``(text, complete)``. ``complete`` is False when any knowledge
4424 base's contents could not be read — its count unknown, its documents not
4425 listed, or its schema unavailable — so routing knows the inventory may
4426 understate what is there. "Empty — do not query" is said only of a
4427 knowledge base confirmed empty.
4428 """
4429 if not knowledge_bases:
4430 return "", True
4432 described = await asyncio.gather(
4433 *(_kb_inventory(kb) for kb in knowledge_bases), return_exceptions=True
4434 )
4435 sections: list[str] = ["## Knowledge Base Contents\n"]
4436 complete = True
4437 for kb, outcome in zip(knowledge_bases, described):
4438 if isinstance(outcome, BaseException):
4439 logger.warning(
4440 "[graph] _build_kb_metadata: inventory unavailable for %s: %s",
4441 kb.get("id", ""),
4442 outcome,
4443 )
4444 lines, kb_complete = _unavailable_inventory(kb, "Metadata"), False
4445 else:
4446 lines, kb_complete = outcome
4447 sections.extend(_with_kind(lines, kb))
4448 sections.append("")
4449 complete = complete and kb_complete
4450 return "\n".join(sections), complete
4453def _named_empty(state: "GraphState") -> list[str]:
4454 """What the person named that holds nothing yet: a knowledge base, or a
4455 repository every knowledge base of which is empty, as the mention check
4456 words it ("repository 'Security guidance'"). Asked "According to the
4457 Security guidance repository, what are the NCSC's 10 Steps?" before it
4458 was crawled, the agent refused to answer."""
4459 empty = set(state.empty_kb_ids or ())
4460 if not empty:
4461 return []
4462 by_naming: dict[str, list[bool]] = {}
4463 for kb in state.knowledge_bases or []:
4464 naming = _naming(state.input or "", kb)
4465 if naming:
4466 by_naming.setdefault(naming, []).append(str(kb.get("id", "")) in empty)
4467 return [naming for naming, empties in by_naming.items() if all(empties)]
4470async def _confirmed_empty(knowledge_bases: list[dict[str, Any]]) -> list[str]:
4471 """The ids of the vector knowledge bases confirmed to hold nothing:
4472 an exact count of 0 (``rag.collection_metadata``, which the inventory has
4473 just read and cached). One whose count could not be read is not empty.
4474 No turn searches them (``knowledge.mix``, ``search_knowledge``): a first
4475 scenario run's agent searched eleven built-in sources not yet crawled on
4476 every turn, and answered from what its own pass made of finding nothing."""
4477 from app.services import rag as rag_service
4479 vector = [kb for kb in knowledge_bases if kb.get("source_type") != "graph"]
4480 if not vector:
4481 return []
4482 counts = await asyncio.gather(
4483 *(rag_service.collection_metadata(str(kb.get("id", ""))) for kb in vector),
4484 return_exceptions=True,
4485 )
4486 return [
4487 str(kb.get("id", ""))
4488 for kb, meta in zip(vector, counts)
4489 if isinstance(meta, dict) and meta.get("vector_count") == 0
4490 ]
4493def _with_kind(lines: list[str], kb: dict[str, Any]) -> list[str]:
4494 """A knowledge base's inventory lines with what its kind means under its
4495 header (``categories.Behaviour.inventory_note``): triage reads whether it
4496 is dated knowledge or a framework. A domain one is listed as it was."""
4497 note = knowledge_categories_registry.behaviour(kb).inventory_note
4498 if not note or not lines:
4499 return lines
4500 return [lines[0], f"Kind: {note}", *lines[1:]]
4503async def _kb_inventory(kb: dict[str, Any]) -> tuple[list[str], bool]:
4504 """One knowledge base's inventory lines, and whether they are complete."""
4505 from app.knowledge import documents as documents_service
4506 from app.services import rag as rag_service
4507 from app.util import neo4j_client
4509 kb_id: str = kb.get("id", "")
4510 kb_name: str = kb.get("name", kb_id)
4511 kb_desc: str = kb.get("description", "")
4512 source_type: str = kb.get("source_type", "file")
4514 if source_type == "graph":
4515 try:
4516 schema = await neo4j_client.get_graph_schema(kb_id)
4517 except Exception as exc:
4518 logger.warning(
4519 "[graph] _build_kb_metadata: graph schema unavailable for %s: %s",
4520 kb_id,
4521 exc,
4522 )
4523 return _unavailable_inventory(kb, "Schema"), False
4524 return _graph_kb_inventory(kb_name, kb_desc, schema), True
4526 try:
4527 meta, docs = await asyncio.gather(
4528 rag_service.collection_metadata(kb_id),
4529 documents_service.list_documents(kb_id, manifest=kb.get("documents")),
4530 )
4531 except Exception as exc:
4532 logger.warning(
4533 "[graph] _build_kb_metadata: vector metadata unavailable for %s: %s",
4534 kb_id,
4535 exc,
4536 )
4537 return _unavailable_inventory(kb, "Metadata"), False
4538 return _vector_kb_inventory(
4539 kb_name, kb_desc, source_type, meta.get("vector_count"), docs
4540 )
4543def _unavailable_inventory(kb: dict[str, Any], what: str) -> list[str]:
4544 kb_id: str = kb.get("id", "")
4545 source_type: str = kb.get("source_type", "file")
4546 lines = [f"### {kb.get('name', kb_id)} ({source_type})"]
4547 if kb.get("description"):
4548 lines.append(str(kb["description"]))
4549 lines.append(f"*{what} temporarily unavailable.*")
4550 return lines
4553def _graph_kb_inventory(kb_name: str, kb_desc: str, schema: dict) -> list[str]:
4554 total = schema.get("total_entities", 0)
4555 entity_types: list[dict] = schema.get("entity_types", [])
4556 rel_types: list[str] = schema.get("relationship_types", [])
4558 header = f"### {kb_name} (graph — {total} {'entity' if total == 1 else 'entities'})"
4559 if kb_desc:
4560 header += f"\n{kb_desc}"
4561 lines = [header]
4562 if total == 0:
4563 lines.append("*Empty graph — no entities yet. Do not query this KB.*")
4564 return lines
4565 et_parts = ", ".join(f"{et['label']} ({et['count']})" for et in entity_types[:12])
4566 lines.append(f"Entity types: {et_parts}")
4568 # Collect up to 20 sample names across all entity types.
4569 sample_names: list[str] = []
4570 for et in entity_types:
4571 sample_names.extend(et.get("names", [])[:3])
4572 if len(sample_names) >= 20:
4573 break
4574 if sample_names:
4575 lines.append(f"Sample entities: {', '.join(sample_names[:20])}")
4576 if rel_types:
4577 lines.append(f"Relationship types: {', '.join(rel_types[:15])}")
4578 return lines
4581#: Documents named per knowledge base in the routing inventory.
4582_INVENTORY_MAX_DOCUMENTS = 20
4585def _vector_kb_inventory(
4586 kb_name: str,
4587 kb_desc: str,
4588 source_type: str,
4589 vector_count: int | None,
4590 docs: list[Any],
4591) -> tuple[list[str], bool]:
4592 """One vector knowledge base's inventory lines, and whether they are
4593 complete. *vector_count* is ``None`` when the collection could not be
4594 read; *docs* are ``DocumentRef``s (empty when nothing could be listed,
4595 which ``list_documents`` does not tell apart from "none")."""
4596 sizes: list[str] = []
4597 if vector_count is not None:
4598 sizes.append(f"{vector_count} chunk{'s' if vector_count != 1 else ''}")
4599 if docs:
4600 sizes.append(f"{len(docs)} document{'s' if len(docs) != 1 else ''}")
4601 header = f"### {kb_name} ({source_type}" + (
4602 f" — {' across '.join(sizes)})" if sizes else ")"
4603 )
4604 lines = [header + (f"\n{kb_desc}" if kb_desc else "")]
4606 if vector_count == 0 and not docs:
4607 lines.append(
4608 "*Empty collection — no documents indexed yet. Do not query this KB.*"
4609 )
4610 return lines, True
4611 if docs:
4612 lines.append("Documents:")
4613 lines.extend(f" - {d.describe()}" for d in docs[:_INVENTORY_MAX_DOCUMENTS])
4614 if len(docs) > _INVENTORY_MAX_DOCUMENTS:
4615 lines.append(f" ... and {len(docs) - _INVENTORY_MAX_DOCUMENTS} more")
4616 elif vector_count:
4617 lines.append(f"*{vector_count} chunks indexed (document names unavailable).*")
4618 if vector_count is None:
4619 lines.append("*Its size could not be read just now.*")
4620 return lines, vector_count is not None and bool(docs or vector_count == 0)
4623async def _build_kb_tools_and_context(
4624 knowledge_bases: list[dict[str, Any]],
4625 attachments: Sequence[attachment_util.Attachment] = (),
4626 empty: Sequence[str] = (),
4627 default: Sequence[str] | None = None,
4628) -> tuple[list[Any], str]:
4629 """
4630 Build the unified knowledge tools and a system-prompt context section from
4631 raw KB descriptor dicts stored in GraphState.knowledge_bases.
4633 The tool set is fixed — ``search_knowledge``, ``read_document``,
4634 ``list_documents`` for vector KBs and ``explore_graph`` for graph KBs —
4635 with the knowledge base as an optional argument, so the interface does not
4636 change with the number or names of attached KBs (see
4637 ``registry.make_knowledge_tools``). The context section inventories every
4638 KB: id, type, stored documents (from svc-core's manifest, including
4639 indexing status) and, for graph KBs, the live Neo4j schema so the model
4640 can form precise, name-accurate queries.
4642 Returns:
4643 (tools, context_section)
4644 """
4645 if not knowledge_bases:
4646 return [], ""
4648 from app.knowledge import documents as documents_service
4649 from app.tools.registry import make_knowledge_tools
4651 # ``empty``: what the gate confirmed holds nothing, never searched.
4652 tools: list[Any] = list(
4653 make_knowledge_tools(knowledge_bases, attachments, empty=empty, default=default)
4654 )
4655 if not tools:
4656 return [], ""
4658 vector_kbs = [kb for kb in knowledge_bases if kb.get("source_type") != "graph"]
4659 graph_kbs = [kb for kb in knowledge_bases if kb.get("source_type") == "graph"]
4661 read = tool_registry.READ_DOCUMENT_TOOL
4662 lines = [
4663 "\n\n## Available Knowledge Bases",
4664 f"Query them with the knowledge tools: `{tool_registry.SEARCH_KNOWLEDGE_TOOL}` "
4665 f"(facts, figures, topics), `{read}` (full text of a named file — "
4666 f"approximate names are resolved), `{tool_registry.LIST_DOCUMENTS_TOOL}` "
4667 "(discover file names)"
4668 + (
4669 f", `{tool_registry.EXPLORE_GRAPH_TOOL}` (entities and relationships)"
4670 if graph_kbs
4671 else ""
4672 )
4673 + ". Pass `knowledge_base` only when you need to target one of several. "
4674 f"When the user names a file of these knowledge bases, read it with "
4675 f"`{read}` before answering; if it is reported missing, say so — never "
4676 "infer its contents. A document the person attached to the conversation "
4677 "is not one of these files: it is in your request.\n",
4678 ]
4680 for kb in vector_kbs:
4681 kb_id = str(kb.get("id", ""))
4682 kb_name = str(kb.get("name", kb_id))
4683 kb_desc = str(kb.get("description", "") or "")
4684 lines.append(f"### {kb_name} ({kb.get('source_type', 'file')} — id `{kb_id}`)")
4685 if kb_desc:
4686 lines.append(kb_desc)
4687 kind = knowledge_categories_registry.behaviour(kb).inventory_note
4688 if kind:
4689 lines.append(f"Kind: {kind}")
4690 try:
4691 docs = await documents_service.list_documents(
4692 kb_id, manifest=kb.get("documents")
4693 )
4694 except Exception as exc: # noqa: BLE001
4695 logger.warning("KB context: document listing failed for %s: %s", kb_id, exc)
4696 docs = []
4697 if docs:
4698 _MAX_SHOW = 25
4699 lines.append(f"Documents ({len(docs)}):")
4700 lines += [f" - {d.describe()}" for d in docs[:_MAX_SHOW]]
4701 if len(docs) > _MAX_SHOW:
4702 lines.append(
4703 f" ... and {len(docs) - _MAX_SHOW} more "
4704 f"(use {tool_registry.LIST_DOCUMENTS_TOOL})"
4705 )
4706 else:
4707 lines.append("*No documents stored yet.*")
4708 lines.append("")
4710 for kb in graph_kbs:
4711 kb_id = str(kb.get("id", ""))
4712 kb_name = str(kb.get("name", kb_id))
4713 kb_desc = str(kb.get("description", "") or "")
4714 lines.append(f"### {kb_name} (graph — id `{kb_id}`)")
4715 if kb_desc:
4716 lines.append(kb_desc)
4717 kind = knowledge_categories_registry.behaviour(kb).inventory_note
4718 if kind:
4719 lines.append(f"Kind: {kind}")
4720 graph_struct = (kb.get("source_config") or {}).get("description", "")
4721 if graph_struct:
4722 lines.append(f"Graph structure: {graph_struct}")
4723 try:
4724 from app.util import neo4j_client
4726 schema = await neo4j_client.get_graph_schema(kb_id)
4727 schema_context = neo4j_client.format_schema_as_context(schema)
4728 if schema_context:
4729 lines.append("\n**Graph schema:**")
4730 lines.append(schema_context)
4731 except Exception:
4732 logger.warning(
4733 "Could not fetch schema for graph KB %r — skipping schema context",
4734 kb_id,
4735 )
4736 lines.append("")
4738 return tools, "\n".join(lines).rstrip()
4741_KB_TOOLS_GUIDANCE = (
4742 "<knowledge_tools>\n"
4743 "When the request carries a <knowledge> block, it holds what was retrieved "
4744 "for this request from your knowledge bases. Answer from the passages that "
4745 "bear on the request and cite those by their [S#] ids; leave out any that "
4746 "do not, and never cite one you did not use. When the knowledge holds "
4747 "nothing relevant, answer without it and without mentioning it. Use the "
4748 "knowledge tools listed below ONLY for a specific detail that the request "
4749 "needs from your knowledge bases and the block does not contain — a "
4750 "figure, a clause, a named entity's relationships, or the full text of a "
4751 "named document. Never re-run broad searches that repeat the retrieved "
4752 "evidence, and never search them for a request they do not cover. If a "
4753 "tool reports that a document does not exist in them, say so. The "
4754 "documents the person attached are not in your knowledge bases: they are "
4755 "in your request, under <attachments>.\n"
4756 "</knowledge_tools>"
4757)
4760async def _kb_tools_for_skill_node(
4761 state: GraphState, node_id: str
4762) -> tuple[list[Any], str]:
4763 """Per-KB tools + guidance for a skill node, or ``([], "")`` without KBs."""
4764 if not state.knowledge_bases:
4765 return [], ""
4766 try:
4767 # A search that names no knowledge base reads what the turn's mix
4768 # reads; with nothing in the mix (a direct or web route), all of it.
4769 mix = _turn_mix(state)
4770 tools, schema_context = await _build_kb_tools_and_context(
4771 state.knowledge_bases,
4772 state.attachments,
4773 empty=state.empty_kb_ids,
4774 default=[kb_id for lane in mix.lanes for kb_id in lane.kb_ids] or None,
4775 )
4776 except Exception as exc: # noqa: BLE001 — tools are an enhancement, never a blocker
4777 logger.warning("[graph] skill node=%s KB tools unavailable: %s", node_id, exc)
4778 return [], ""
4779 if not tools:
4780 return [], ""
4781 return tools, _KB_TOOLS_GUIDANCE + schema_context
4784def _aggregate_prior_results(state: GraphState) -> str:
4785 """
4786 Build a comprehensive task description that includes the original user
4787 input and all completed node outputs.
4789 Used when ``state.results`` is non-empty (i.e. this is not the start node).
4790 Downstream agents receive the full picture of prior work rather than only
4791 the most recently completed node's output — this is critical for graphs
4792 with multiple convergent parents (e.g. ``[analyzer_a, analyzer_b] → validator``).
4793 """
4794 parts = [f"Original task:\n{state.input}"]
4795 for node_id, result in state.results.items():
4796 if result is None:
4797 continue
4798 if node_id == EVALUATOR_NODE_ID:
4799 # A revision: what to fix, in words, not the verdict's JSON.
4800 if not getattr(result, "passed", True):
4801 parts.append(f"--- Quality check ---\n{_revision_note(result)}")
4802 continue
4803 content = _result_text(result)
4804 if not content.strip():
4805 continue
4806 parts.append(f"--- Output from {node_id} ---\n{content}")
4807 return "\n\n".join(parts)
4810class AgentGraphBuilder(Generic[StateType]):
4811 """
4812 Builds dynamic execution graphs from WorkerAgent instances.
4814 Usage::
4816 builder = AgentGraphBuilder(state_schema=GraphState)
4817 builder.add_agent("planner", planner, start=True)
4818 builder.add_agent("analyzer", analyzer)
4819 builder.add_agent("validator", validator, end=True)
4820 builder.add_edge("planner", "analyzer")
4821 builder.add_edge("analyzer", "validator")
4822 graph = builder.build()
4823 result = await graph.ainvoke(GraphState(input="..."))
4825 Conditional routing::
4827 builder.add_conditional_edge(
4828 "analyzer",
4829 route_fn, # (GraphState) -> str
4830 {"complex": "complex_solver", "simple": "simple_solver"},
4831 )
4832 """
4834 def __init__(
4835 self,
4836 state_schema: type[StateType] = GraphState,
4837 llm: BaseLanguageModel | None = None,
4838 db: Any = None,
4839 require_approval: bool = False,
4840 store: Any = None,
4841 clarify_scope: bool = False,
4842 cost_profile: str | None = None,
4843 lighter_model: Any = None,
4844 structured_model: Any = None,
4845 ) -> None:
4846 self.state_schema = state_schema
4847 # How much pipeline work a turn does (``app/agents/effort.py``): the
4848 # key travels in the run's context; the builder reads it for the
4849 # run's step limit.
4850 self.cost_profile = cost_profile
4851 # The model an Economy profile does its lighter work on (svc-core's
4852 # choice, ``AgentConfig.lighter_model``), built once in ``build``:
4853 # the steps nobody reads (``_steps_llm``) and answers to what triage
4854 # calls simple (``_answer_llm``). None: the agent's own model does it.
4855 self.lighter_model = lighter_model
4856 # A model that decodes schemas natively, for the run's structured
4857 # system steps when the model making one cannot (svc-core's choice,
4858 # ``AgentConfig.structured_model``); carried in every run's config
4859 # (``run_config``) and checked again before it stands in
4860 # (``services/native_sibling.py``).
4861 self.structured_model = structured_model
4862 # The web sources CHAIN-R puts first for its own agent
4863 # (``AgentConfig.platform_sources``), set by the engine from the
4864 # request's spec and carried in every run's config (``run_config``),
4865 # where the web tools read them (``tools/web/platform_sources.py``).
4866 self.platform_sources: frozenset[str] = frozenset()
4867 # The shape the request asked the answer in, when it asked for JSON
4868 # (``app/inference/output_shape.AnswerShape``). Set by the engine that
4869 # builds the graph and read once the run has finished, so a resumed
4870 # run, built again by the same engine, shapes its answer too.
4871 self.answer_shape: Any = None
4872 self._steps_llm: BaseLanguageModel | None = None
4873 self._answer_llm: BaseLanguageModel | None = None
4874 self._system_llm: BaseLanguageModel | None = llm
4875 self._db: Any = db
4876 # When True, a __hitl__ node is inserted after SYNTHESIS to pause
4877 # execution and await human approval before the graph ends.
4878 # Requires a checkpointer to be passed to build().
4879 self.require_approval = require_approval
4880 # When True, triage also checks whether the request's scope is
4881 # ambiguous and, if so, a __clarify__ node pauses to ask before any
4882 # planning, retrieval or skill work runs. Interactive callers only
4883 # (a chat turn, an evaluation of one): a non-interactive caller has
4884 # nobody to answer. Requires a checkpointer, like require_approval.
4885 self.clarify_scope = clarify_scope
4886 # Whether anyone can answer this run's questions at all
4887 # (``ExecuteRequest.may_ask``): False for an unattended caller (a
4888 # dashboard tile), which is then never offered ``ask_user`` and never
4889 # runs the scope check. Set by the engine that builds the graph.
4890 self.may_ask = True
4891 # PostgresMemoryStore for durable cross-conversation agent memory.
4892 # When set, __memory_read__ and __memory_write__ nodes bracket the graph.
4893 self.store: Any = store
4894 # What the run's rules redact from what memory keeps and recalls
4895 # (``app.memory.service.Redaction``), set by the engine; None: nothing.
4896 self.memory_redaction: Any = None
4897 # An Output rule that can withhold the answer governs the run
4898 # (``RulesEnforcer.may_withhold``), set by the engine: memory keeps
4899 # the request alone, and tool calls are traced without their
4900 # arguments or results — a document's body is the answer itself.
4901 self.withholding = False
4902 self.nodes: dict[str, GraphNode] = {}
4903 self.edges: list[tuple[str, str]] = []
4904 self.start_node: Optional[str] = None
4905 self.end_nodes: set[str] = set()
4906 # Skill-level typed contract (schema v3 ``interface`` block) and the
4907 # state_vars seeded before the first node runs (declared defaults +
4908 # caller-supplied inputs). Both are read by the inference engines.
4909 self.skill_interface: dict[str, Any] = {}
4910 self._initial_state_vars: dict[str, Any] = {}
4912 # ------------------------------------------------------------------
4913 # Graph construction API
4914 # ------------------------------------------------------------------
4916 def add_agent(
4917 self,
4918 node_id: str,
4919 agent: WorkerAgent,
4920 start: bool = False,
4921 end: bool = False,
4922 output_key: str = "",
4923 prompt_template: str = "",
4924 input_keys: list[str] | None = None,
4925 inputs: dict[str, Any] | None = None,
4926 approval: dict[str, Any] | None = None,
4927 ask_user: bool = False,
4928 ) -> AgentGraphBuilder[StateType]:
4929 """Add a WorkerAgent as a node. Returns self for chaining.
4931 ``output_key`` / ``prompt_template`` / ``input_keys`` are the optional
4932 state bindings from skill graph schema v2; ``inputs`` are the typed
4933 field bindings from schema v3 — see GraphNode.
4934 """
4935 if node_id in self.nodes:
4936 raise ValueError(f"Node '{node_id}' already exists")
4938 node = GraphNode(
4939 id=node_id,
4940 agent=agent,
4941 is_start=start,
4942 is_end=end,
4943 output_key=output_key,
4944 prompt_template=prompt_template,
4945 input_keys=list(input_keys or []),
4946 inputs=dict(inputs or {}),
4947 approval=dict(approval) if approval else None,
4948 ask_user=bool(ask_user),
4949 )
4950 self.nodes[node_id] = node
4952 if start:
4953 if self.start_node is not None:
4954 raise ValueError("Only one start node is allowed")
4955 self.start_node = node_id
4957 if end:
4958 self.end_nodes.add(node_id)
4960 return self
4962 def add_edge(self, from_node: str, to_node: str) -> AgentGraphBuilder[StateType]:
4963 """Add a direct (unconditional) edge between two nodes."""
4964 self._assert_node_exists(from_node)
4965 if to_node != "end":
4966 self._assert_node_exists(to_node)
4968 self.edges.append((from_node, to_node))
4969 self.nodes[from_node].next_nodes["default"] = to_node
4970 return self
4972 def add_conditional_edge(
4973 self,
4974 from_node: str,
4975 condition_fn: Callable[[GraphState], str],
4976 edge_map: dict[str, str],
4977 ) -> AgentGraphBuilder[StateType]:
4978 """
4979 Add conditional routing from a node.
4981 Args:
4982 from_node: Source node ID.
4983 condition_fn: ``(GraphState) -> str`` — returns a key from edge_map.
4984 edge_map: Maps condition_fn return values to target node IDs.
4985 Use ``"end"`` as a target to route to END.
4987 Example::
4989 def route(state: GraphState) -> str:
4990 return "complex" if state.context.get("complexity", 1) > 3 else "simple"
4992 builder.add_conditional_edge(
4993 "analyzer",
4994 route,
4995 {"complex": "complex_solver", "simple": "simple_solver"},
4996 )
4997 """
4998 self._assert_node_exists(from_node)
4999 for target in edge_map.values():
5000 if target != "end":
5001 self._assert_node_exists(target)
5003 node = self.nodes[from_node]
5004 node.conditional_edges = condition_fn
5005 node.conditional_edge_map = edge_map
5006 return self
5008 # ------------------------------------------------------------------
5009 # Build
5010 # ------------------------------------------------------------------
5012 def build(self, checkpointer: Any = None) -> Any: # -> CompiledStateGraph
5013 """Compile the LangGraph execution graph.
5015 Every compiled graph is wrapped with core infrastructure nodes:
5017 ``__gate__`` — Zero-cost heuristic classifier; trivial inputs short-circuit to END.
5018 ``__planning__`` — Produces a structured ExecutionPlan for every downstream node.
5019 ``__knowledge_plan__`` — Plans the knowledge search once, for the turn's mix.
5020 ``__<kind>_retrieval__`` — A lane per kind of knowledge, searched side by side.
5021 ``__retrieval_join__`` — Where every retrieval branch meets; packs the lanes.
5022 ``__synthesis__`` — Consolidates all skill-node outputs into the final response.
5024 Optional nodes (enabled via constructor flags):
5026 ``__memory_read__`` — Recalls relevant memories from the store before planning
5027 (requires ``store`` to be set on the builder).
5028 ``__memory_write__`` — Persists a summary of the interaction after synthesis
5029 (requires ``store`` to be set on the builder).
5030 ``__hitl__`` — Pauses execution via ``interrupt()`` to await human
5031 approval before ending (requires ``require_approval=True`` and a
5032 ``checkpointer`` so state can be saved across the pause).
5034 Full topology:
5036 GATE → trivial → END
5037 GATE → any non-trivial route → RECON (complexity classification, no tools):
5038 direct_answer → SYNTHESIS (direct + simple; model answers without skill graph)
5039 to_planning → (MEMORY_READ? →) PLANNING → dispatch:
5040 direct → skill graph (or SYNTHESIS) → EVALUATOR → (HITL? →) (MEMORY_WRITE? →) END
5041 retrieve_* → retrieval → JOIN → skill graph (or SYNTHESIS) → EVALUATOR → …
5042 retrieve_* variants: internal (KBs), external (web), tools (geocode/calculate/etc.),
5043 both (KBs+web). Knowledge first goes to KNOWLEDGE_PLAN, which sends a
5044 lane per kind in the turn's mix and the web and tools beside them, in
5045 PARALLEL via Send; every branch meets once in the deferred JOIN.
5046 PLANNER AUTHORITY: when ExecutionPlan.active_nodes is empty, the skill
5047 graph is bypassed entirely — retrieval flows straight to SYNTHESIS,
5048 which answers in the agent persona from the retrieved context. This
5049 collates parallel retrieval results without a generic relay node
5050 re-summarising (and degrading) them.
5051 EVALUATOR → retry → skill graph (or SYNTHESIS when it was skipped)
5052 (severe fail only, ≤ complexity-scaled retry budget)
5053 EVALUATOR → retry_retrieval → KNOWLEDGE_PLAN → the evidence lanes → JOIN
5054 (gaps the knowledge searched this turn may fill: CRAG)
5055 Any critical error (status=="error") → routed to END at the next junction
5057 RECON is a zero-tool complexity classifier. It reads the task text and KB
5058 metadata already fetched by the gate to decide:
5059 - complexity (simple / moderate / complex)
5060 - use_skill_graph — only False for simple direct-route tasks
5061 - needs_synthesis — whether skill outputs need a final consolidation pass
5063 When needs_synthesis is True a SYNTHESIS node runs after the skill graph.
5064 This replaces the old 'plan' / 'plan_retrieve' gate prefix, moving the
5065 synthesis decision to a node that has complexity context (Adaptive RAG,
5066 Jeong et al. 2024).
5068 Args:
5069 checkpointer: LangGraph checkpointer (e.g. ``MemorySaver()``,
5070 ``AsyncPostgresSaver``) for persistent state and HITL resumption.
5071 Required when ``require_approval=True``.
5072 """
5073 if not self.start_node:
5074 raise ValueError(
5075 "No start node specified — call add_agent(..., start=True)"
5076 )
5077 if not self.end_nodes:
5078 raise ValueError("No end nodes specified — call add_agent(..., end=True)")
5080 system_llm = _deterministic(
5081 _ensure_system_token_budget(
5082 self._system_llm or self.nodes[self.start_node].agent.llm
5083 )
5084 )
5085 # An Economy profile's lighter model: the steps nobody reads run on
5086 # it, and it answers what triage calls simple (``effort.py``).
5087 effort = effort_registry.effort_of(self.cost_profile)
5088 lighter = (
5089 _lighter_llm_for(self.lighter_model)
5090 if effort.lighter_steps or effort.lighter_simple_answers
5091 else None
5092 )
5093 steps_llm = (
5094 _deterministic(_ensure_system_token_budget(lighter))
5095 if lighter is not None and effort.lighter_steps
5096 else system_llm
5097 )
5098 self._steps_llm = steps_llm if steps_llm is not system_llm else None
5099 self._answer_llm = lighter if effort.lighter_simple_answers else None
5101 skill_node_descriptors: list[dict[str, str]] = [
5102 {
5103 "node_id": node_id,
5104 "role": node.agent.role.value,
5105 "description": (node.agent.system_prompt or "")[:200],
5106 }
5107 for node_id, node in self.nodes.items()
5108 ]
5110 graph = StateGraph(self.state_schema)
5112 # Every node except the gate (the entry point — state is fresh there)
5113 # is wrapped in _abort_on_error so a critical failure upstream turns
5114 # downstream nodes into no-ops until a router exits to END.
5115 # Every node also names the messages it writes (_name_node_messages),
5116 # which is how history is told apart from this run's own messages.
5117 def _add(node_id: str, fn: Callable, *, defer: bool = False) -> None:
5118 graph.add_node(
5119 node_id,
5120 _span_node(
5121 node_id, _abort_on_error(node_id, _name_node_messages(node_id, fn))
5122 ),
5123 defer=defer,
5124 )
5126 # ── Core infrastructure nodes ─────────────────────────────────────
5127 graph.add_node(
5128 GATE_NODE_ID,
5129 _span_node(
5130 GATE_NODE_ID,
5131 _name_node_messages(
5132 GATE_NODE_ID,
5133 self._create_gate_node_fn(
5134 steps_llm,
5135 skill_node_descriptors,
5136 clarify_scope=self.clarify_scope and self.may_ask,
5137 # The profile's lighter model triages in place of
5138 # the deployment's triage model.
5139 triage_llm=(
5140 None
5141 if self._steps_llm is not None
5142 else _configured_triage_llm()
5143 ),
5144 ),
5145 ),
5146 ),
5147 )
5148 _add(
5149 PLANNING_NODE_ID,
5150 self._create_planning_node_fn(steps_llm, skill_node_descriptors),
5151 )
5152 # Knowledge retrieval: one plan, a lane per kind (side by side with
5153 # the web and the tools), and the join every branch meets in —
5154 # deferred, so it runs once, after them all.
5155 _add(
5156 KNOWLEDGE_PLAN_NODE_ID,
5157 self._create_knowledge_plan_node_fn(system_llm, planning_llm=steps_llm),
5158 )
5159 for category, lane_node_id in LANE_NODE_IDS.items():
5160 _add(
5161 lane_node_id,
5162 self._create_lane_node_fn(category, system_llm, planning_llm=steps_llm),
5163 )
5164 _add(
5165 RETRIEVAL_JOIN_NODE_ID,
5166 self._create_retrieval_join_node_fn(system_llm),
5167 defer=True,
5168 )
5169 _add(
5170 EXTERNAL_RETRIEVAL_NODE_ID,
5171 self._create_external_retrieval_node_fn(system_llm),
5172 )
5173 _add(TOOL_RETRIEVAL_NODE_ID, self._create_tool_retrieval_node_fn(system_llm))
5174 _add(SYNTHESIS_NODE_ID, self._create_synthesis_node_fn(system_llm))
5175 _add(EVALUATOR_NODE_ID, self._create_evaluator_node_fn(steps_llm))
5177 # ── Optional infrastructure nodes ─────────────────────────────────
5178 use_memory = self.store is not None
5179 if use_memory:
5180 _add(MEMORY_READ_NODE_ID, self._create_memory_read_node_fn())
5181 _add(MEMORY_WRITE_NODE_ID, self._create_memory_write_node_fn(steps_llm))
5183 if self.require_approval:
5184 _add(HITL_NODE_ID, self._create_hitl_node_fn())
5186 # Every question for the person is asked here: the scope check's
5187 # (only with clarify_scope on) and any agent's mid-task ``ask_user``.
5188 _add(CLARIFY_NODE_ID, self._create_clarify_node_fn())
5190 # ── Skill nodes ───────────────────────────────────────────────────
5191 for node_id, node in self.nodes.items():
5192 _add(node_id, self._create_skill_node_fn(node_id, node.agent, node))
5194 # ── Edges ─────────────────────────────────────────────────────────
5195 # Triage (``__gate__``) classifies the request once: where to get
5196 # data (route / retrieval_type, dispatched after planning) and the
5197 # task's shape (resource_strategy, needs_synthesis, a scope question).
5198 #
5199 # trivial → END (heuristic, zero LLM cost)
5200 # clarify → CLARIFY (pause, ask) → wherever triage would have gone
5201 # direct_answer → SYNTHESIS (a direct route that skips the skill graph)
5202 # to_planning → MEMORY_READ (if store set) → PLANNING → retrieval
5203 # (internal ∥ external ∥ tools, as routed) → skill graph
5204 #
5205 # A skill step's mid-task question comes to CLARIFY too
5206 # (``_synthesis_router``) and goes back to the skill graph once
5207 # answered (``_clarify_router``). The clarify node clears
5208 # pending_clarification, so the routers pick the real destination on
5209 # the way out.
5210 first_complex_node = MEMORY_READ_NODE_ID if use_memory else PLANNING_NODE_ID
5211 triage_path_map = {
5212 # Skip the skill graph entirely — synthesis answers directly.
5213 "direct_answer": SYNTHESIS_NODE_ID,
5214 # Proceed through memory → planning → dispatch.
5215 "to_planning": first_complex_node,
5216 "abort": END,
5217 }
5218 graph.add_conditional_edges(
5219 GATE_NODE_ID,
5220 _gate_router,
5221 {**triage_path_map, "trivial": END, "clarify": CLARIFY_NODE_ID},
5222 )
5223 graph.add_conditional_edges(
5224 CLARIFY_NODE_ID,
5225 _clarify_router,
5226 {**triage_path_map, "resume": self.start_node},
5227 )
5229 if use_memory:
5230 graph.add_edge(MEMORY_READ_NODE_ID, PLANNING_NODE_ID)
5232 # PLANNING → conditional dispatch to retrieval, straight to the skill
5233 # graph (direct route with skill nodes), or straight to synthesis
5234 # (direct route, planner skipped the skill graph). A route that
5235 # searches the knowledge goes to KNOWLEDGE_PLAN first; one that does
5236 # not runs the web and the tools (in parallel via Send).
5237 graph.add_conditional_edges(
5238 PLANNING_NODE_ID,
5239 _planning_router,
5240 {
5241 "to_skill": self.start_node,
5242 "to_synthesis": SYNTHESIS_NODE_ID,
5243 "knowledge": KNOWLEDGE_PLAN_NODE_ID,
5244 "external": EXTERNAL_RETRIEVAL_NODE_ID,
5245 "tools": TOOL_RETRIEVAL_NODE_ID,
5246 "abort": END,
5247 },
5248 )
5249 # KNOWLEDGE_PLAN → its lanes ∥ web ∥ tools (Send), or the join when
5250 # it planned no lane (the agentic mode searches in the join).
5251 graph.add_conditional_edges(
5252 KNOWLEDGE_PLAN_NODE_ID,
5253 _knowledge_plan_router,
5254 {"join": RETRIEVAL_JOIN_NODE_ID, "abort": END},
5255 )
5256 # Every branch is one node deep and meets in the join.
5257 for _branch in (
5258 *LANE_NODE_IDS.values(),
5259 EXTERNAL_RETRIEVAL_NODE_ID,
5260 TOOL_RETRIEVAL_NODE_ID,
5261 ):
5262 graph.add_edge(_branch, RETRIEVAL_JOIN_NODE_ID)
5264 # The join flows into the skill graph when the planner selected skill
5265 # nodes, otherwise directly to synthesis — the planner has full
5266 # authority, so no generic relay node degrades the retrieval output.
5267 graph.add_conditional_edges(
5268 RETRIEVAL_JOIN_NODE_ID,
5269 _skill_dispatch_router,
5270 {
5271 "to_skill": self.start_node,
5272 "to_synthesis": SYNTHESIS_NODE_ID,
5273 "abort": END,
5274 },
5275 )
5277 # Post-evaluator destination (HITL → MEMORY_WRITE → END, each optional).
5278 after_evaluator = (
5279 HITL_NODE_ID
5280 if self.require_approval
5281 else (MEMORY_WRITE_NODE_ID if use_memory else END)
5282 )
5284 # Both the synthesis and skip (no-synthesis) paths converge on EVALUATOR.
5285 synthesis_path_map = {
5286 "synthesise": SYNTHESIS_NODE_ID,
5287 "skip": EVALUATOR_NODE_ID,
5288 # A step asked the person something: ask it before anything else.
5289 "clarify": CLARIFY_NODE_ID,
5290 "abort": END,
5291 }
5293 # Skill graph edges
5294 terminal_nodes: set[str] = set(self.end_nodes)
5295 for from_node, to_node in self.edges:
5296 if to_node == "end":
5297 terminal_nodes.add(from_node)
5298 else:
5299 graph.add_edge(from_node, to_node)
5301 # Conditional edges from skill nodes — paths that previously mapped to
5302 # "end" (i.e. SYNTHESIS) are now routed through _synthesis_router so
5303 # that direct/retrieve routes bypass synthesis entirely.
5304 for node_id, node in self.nodes.items():
5305 if node.conditional_edges:
5306 end_keys = frozenset(
5307 k for k, v in node.conditional_edge_map.items() if v == "end"
5308 )
5309 if end_keys:
5310 original_fn = node.conditional_edges
5312 def _route_with_synthesis(state, _fn=original_fn, _ek=end_keys):
5313 result = _fn(state)
5314 return _synthesis_router(state) if result in _ek else result
5316 path_map = {
5317 k: v for k, v in node.conditional_edge_map.items() if v != "end"
5318 }
5319 path_map.update(synthesis_path_map)
5320 graph.add_conditional_edges(
5321 node_id, _route_with_synthesis, path_map
5322 )
5323 else:
5324 path_map = dict(node.conditional_edge_map)
5325 graph.add_conditional_edges(
5326 node_id, node.conditional_edges, path_map or None
5327 )
5329 # Terminal skill nodes → synthesis for plan/plan_retrieve, skip it otherwise.
5330 for terminal in terminal_nodes:
5331 graph.add_conditional_edges(terminal, _synthesis_router, synthesis_path_map)
5333 # Synthesis → Evaluator. The evaluator either accepts (→ HITL →
5334 # MEMORY_WRITE → END, each optional) or, on a failed pass with retry
5335 # budget remaining, loops back into the skill graph for a genuine
5336 # second attempt (bounded by _MAX_EVAL_RETRIES; each retry costs a
5337 # handful of supersteps against LangGraph's recursion_limit).
5338 graph.add_edge(SYNTHESIS_NODE_ID, EVALUATOR_NODE_ID)
5339 graph.add_conditional_edges(
5340 EVALUATOR_NODE_ID,
5341 _evaluator_router,
5342 {
5343 "retry": self.start_node,
5344 "retry_synthesis": SYNTHESIS_NODE_ID,
5345 # Corrective retrieval: gap-fill evidence from the evidence
5346 # lanes, then the normal skill-graph / synthesis dispatch
5347 # from the join.
5348 "retry_retrieval": KNOWLEDGE_PLAN_NODE_ID,
5349 "accept": after_evaluator,
5350 "abort": END,
5351 },
5352 )
5354 if self.require_approval:
5355 after_hitl = MEMORY_WRITE_NODE_ID if use_memory else END
5356 graph.add_edge(HITL_NODE_ID, after_hitl)
5358 if use_memory:
5359 graph.add_edge(MEMORY_WRITE_NODE_ID, END)
5361 graph.set_entry_point(GATE_NODE_ID)
5362 return graph.compile(checkpointer=checkpointer, store=self.store)
5364 def _may_ask(self, state: "GraphState") -> bool:
5365 """Whether a skill step may ask the person something now.
5367 Never in a run nobody attends (``may_ask``: a dashboard tile cached
5368 its question as its answer). One form a turn, whoever asks: not once
5369 the scope check or a step has asked. And never on a quality-check
5370 revision: what the check found missing is the agent's to fix —
5371 CHAINR Bot, told by the check it "should have asked", asked the
5372 person to find the images it had failed to embed.
5373 """
5374 return self.may_ask and not state.clarifications and not state.eval_retry_count
5376 def recursion_limit(self) -> int:
5377 """The supersteps one run of this graph may take before LangGraph
5378 stops it.
5380 LangGraph's default is 25, and a run's loops are bounded by the
5381 evaluator's revision budget rather than by any count LangGraph knows:
5382 each revision re-runs the skill graph, synthesis and the evaluator. A
5383 four-node skill (Research brief) takes about 12 steps on its first
5384 pass and 6 more for each revision, so its second revision crossed 25
5385 and the turn failed with ``GraphRecursionError`` after the work was
5386 done. The limit is every node once per pass, for the first pass and
5387 each revision, plus a margin. A skill graph is a DAG, so a pass runs
5388 each of its nodes at most once; one stored with a loop (nothing
5389 refuses it at save) is what this still stops.
5390 """
5391 per_pass = len(SYSTEM_NODE_IDS) + len(self.nodes)
5392 retries = effort_registry.effort_of(self.cost_profile).max_eval_retries
5393 # One more pass for a turn's one mid-task question (``ask_user``),
5394 # after which the skill graph runs again.
5395 return per_pass * (2 + retries) + _RECURSION_MARGIN
5397 def run_config(self, thread_id: str) -> dict[str, Any]:
5398 """The config every run of this graph is given: its checkpoint thread,
5399 its recursion limit, a fresh registry of the ids its sources are
5400 cited by (``util/source_registry``), its native sibling when
5401 svc-core named one (``services/native_sibling``), and the platform's
5402 sources for the built-in agent (``tools/web/platform_sources``).
5404 Per call, not bound with ``compiled.with_config``: ``astream_events``
5405 applies LangGraph's default of 25 over a bound limit (``ainvoke``
5406 keeps it), so a bound limit fixed batch runs and left every chat at
5407 25. ``tests/agents/test_recursion_limit.py`` checks both against the
5408 installed LangGraph.
5409 """
5410 from app.documents import images as document_images
5411 from app.services import embedding_cache, native_sibling
5412 from app.util import source_registry
5414 configurable: dict[str, Any] = {
5415 "thread_id": thread_id,
5416 # The ids the run's sources are cited by (``source_registry``).
5417 source_registry.CONFIG_KEY: source_registry.SourceRegistry(),
5418 # One embedding of each text the run's searches embed.
5419 embedding_cache.CONFIG_KEY: embedding_cache.EmbeddingCache(),
5420 # What each image a document links came to, so a revision or
5421 # synthesis rendering the same document fetches nothing twice.
5422 document_images.CONFIG_KEY: document_images.ImageCache(),
5423 }
5424 sibling = native_sibling.NativeSibling.of(self.structured_model)
5425 if sibling is not None:
5426 # The model that makes a structured system step's call when the
5427 # caller's cannot decode it natively (``native_sibling``).
5428 configurable[native_sibling.CONFIG_KEY] = sibling
5429 if self.platform_sources:
5430 # Sources a search puts first where no workspace rule chose any:
5431 # here, never in a tool's config, so no caller can set them.
5432 configurable[platform_sources.CONFIG_KEY] = frozenset(self.platform_sources)
5433 return {"configurable": configurable, "recursion_limit": self.recursion_limit()}
5435 # ------------------------------------------------------------------
5436 # Node execution wrappers
5437 # ------------------------------------------------------------------
5439 def _create_gate_node_fn(
5440 self,
5441 system_llm: BaseLanguageModel | None,
5442 skill_node_descriptors: list[dict[str, str]] | None = None,
5443 clarify_scope: bool = False,
5444 triage_llm: BaseLanguageModel | None = None,
5445 ) -> Callable[[GraphState], dict[str, Any]]:
5446 """
5447 Create the triage node function (id ``__gate__``): the one place a
5448 request is classified.
5450 Two stages — always heuristic first, a model only for substantive
5451 inputs:
5453 1. **Trivial** (heuristic, zero LLM cost) — greetings, one-word
5454 acknowledgements, farewells. A canned reply is written to
5455 ``results[SYNTHESIS_NODE_ID]`` and the run goes to ``END``,
5456 bypassing all pipeline layers.
5458 2. **Substantive** (one structured call, ``TriageProfile``) — decides
5459 both questions a request raises:
5461 - **where to get data** (``state.route`` / ``state.retrieval_type``):
5462 ``direct``, or ``retrieve`` from internal | external | tools |
5463 both, then held to the routing rules (a named knowledge base,
5464 ``always_retrieve``, a plain agent's own tools);
5465 - **the task's shape** (``state.resource_strategy``): complexity,
5466 whether the skill graph and a synthesis pass run, the tools it
5467 is likely to need, and — with ``clarify_scope`` on — whether to
5468 ask the person first (parked in ``pending_clarification`` for
5469 ``__clarify__``; this node never pauses, because a resume would
5470 replay its model call).
5472 When the call fails nothing asks again: the route comes from
5473 ``_fallback_route`` and the shape from safe defaults (the full
5474 pipeline, no scope check).
5476 This was two nodes. ``__recon__`` read the same triage answer and,
5477 when triage had failed, asked a model the same question in another
5478 prompt — a second call, on a guess, that wrote the scope form of the
5479 climbing-knots turn (a required question for the PDF's file name, and
5480 one knot recommended of a plural request).
5481 """
5483 async def gate_node_fn(state: GraphState) -> dict[str, Any]:
5484 from langchain_core.messages import AIMessage as _AIMessage
5486 step = state.step_count + 1
5488 # ── Stage 1: heuristic trivial check (zero LLM cost) ──────────────
5489 in_conversation = bool(_conversation_tail(state, max_turns=1))
5490 # A message that attached documents is never small talk, even
5491 # sent without a word.
5492 attached_now = bool(attachment_util.turn_names(state.attachments))
5493 if (
5494 not attached_now
5495 and _classify_input(state.input, in_conversation) == "trivial"
5496 ):
5497 response = _trivial_response(state.input, agent_name=state.agent_name)
5498 logger.info(
5499 "[graph] ▶ node=%s step=%d route=trivial (heuristic bypass)",
5500 GATE_NODE_ID,
5501 step,
5502 )
5503 return {
5504 "step_count": step,
5505 "status": "complete",
5506 "route": "trivial",
5507 "messages": [_AIMessage(content=response, name=GATE_NODE_ID)],
5508 "results": {SYNTHESIS_NODE_ID: response},
5509 }
5511 # ── Stage 2: LLM classification for substantive inputs ─────────────
5512 has_kbs = bool(state.knowledge_bases)
5514 # Fetch KB metadata once here — stored in state so planning and
5515 # retrieval nodes reuse it without additional I/O.
5516 kb_meta = state.kb_metadata # reuse if already fetched (e.g. HITL resume)
5517 # Nothing attached is nothing left unread.
5518 kb_complete = state.kb_inventory_complete if kb_meta else not has_kbs
5519 if not kb_meta and has_kbs:
5520 try:
5521 kb_meta, kb_complete = await _build_kb_metadata(
5522 state.knowledge_bases
5523 )
5524 except Exception as exc:
5525 logger.warning(
5526 "[gate] KB metadata fetch failed (%s) — routing without it", exc
5527 )
5528 kb_meta, kb_complete = "", False
5530 # Which of them hold nothing: no lane searches those.
5531 empty_ids = await _confirmed_empty(state.knowledge_bases) if has_kbs else []
5533 # Conversation context: follow-ups ("and section 3?") only make
5534 # sense with the previous turns, so the router sees them and
5535 # rewrites the request into a standalone query for retrieval
5536 # (conversational query reformulation; Ma et al. 2023).
5537 turns = _conversation_tail(state)
5538 history = _history_text(turns)
5540 # One triage call: the route and how the task is shaped.
5541 # An agent with dated knowledge is also asked how recent the
5542 # request wants it (``_RecencyCue``).
5543 dated = has_kbs and knowledge_categories_registry.holds(
5544 state.knowledge_bases, KnowledgeCategory.temporal
5545 )
5546 triage_schema: type[RequestProfile] = (
5547 (ScopedDatedTriageProfile if dated else ScopedTriageProfile)
5548 if clarify_scope
5549 else (DatedTriageProfile if dated else TriageProfile)
5550 )
5551 # Retrieve-then-judge (``RetrievalConfig.always_retrieve``) and
5552 # whether a web-only triage may stand against it.
5553 retrieval_cfg = state.retrieval_config or {}
5554 always = bool(retrieval_cfg.get("always_retrieve", True))
5556 tools = self._triage_tools(state)
5557 triage_schema = _naming_only(triage_schema, tuple(tools))
5559 async def classify(llm: BaseLanguageModel | None) -> tuple:
5560 return await _classify_request_route(
5561 state.input,
5562 has_kbs,
5563 # A profile is a few hundred tokens: a model that keeps
5564 # reasoning fails in seconds, not at the answer-sized cap.
5565 _capped_llm(llm, _classification_cap(llm)),
5566 kb_metadata=kb_meta,
5567 history=history,
5568 task_structure=_task_structure_brief(
5569 skill_node_descriptors or [], state, clarify_scope, tools
5570 ),
5571 triage_schema=triage_schema,
5572 always_retrieve=always,
5573 # The documents by name and size — never a body: triage
5574 # read a pasted report as the request.
5575 attachments=attachment_util.manifest_lines(state.attachments),
5576 has_attachments=attached_now,
5577 )
5579 if triage_llm is None or not _same_provider(triage_llm, system_llm):
5580 classified = await classify(system_llm)
5581 else:
5582 try:
5583 classified = await classify(triage_llm)
5584 except model_errors.ModelUnavailableError as exc:
5585 # A deployment's triage model it cannot reach is a
5586 # setting gone wrong, not this turn's failure.
5587 logger.warning(
5588 "[gate] TRIAGE_MODEL unavailable (%s) — triaging with "
5589 "the agent's own model",
5590 exc,
5591 )
5592 classified = await classify(system_llm)
5593 route, retrieval_type = classified[0], classified[1]
5594 standalone = classified[2] if len(classified) > 2 else ""
5595 # None exactly when the call failed or there was no model: the
5596 # gate always asks for the task structure, so a profile comes back.
5597 profile = classified[3] if len(classified) > 3 else None
5598 note = classified[4] if len(classified) > 4 else None
5599 failure = note if profile is None else None
5600 # What triage chose, before the rules below change it: the trace
5601 # shows both, so a forced retrieval reads as forced. A failed
5602 # triage says why (``failure``: a cut-off reply's shape too), and
5603 # one read by closing a reply that ran on says so (``recovered``).
5604 triage_route: dict[str, Any] = {
5605 "route": route,
5606 "retrieval_type": retrieval_type if route == "retrieve" else "",
5607 "source": "triage" if profile is not None else "fallback",
5608 "adjustments": [],
5609 **({"failure": failure} if failure else {}),
5610 **(
5611 {"recovered": note["recovered"]}
5612 if profile is not None and note and note.get("recovered")
5613 else {}
5614 ),
5615 }
5616 retrieval_query = (
5617 standalone or _heuristic_standalone_query(state.input, turns)
5618 ).strip() or state.input
5619 # The person's words, as the deterministic rules read them.
5620 asked = f"{state.input}\n{retrieval_query}"
5622 named: list[str] = []
5623 if has_kbs:
5624 # Deterministic override: naming a stored document or an
5625 # attached KB always means "look it up" — the LLM router must
5626 # not send such a request to 'direct' / external-only paths.
5627 # On a web-only triage only the person's own words count
5628 # (``_mention_text``): the agent's last reply names its own
5629 # sources.
5630 mentions = _mention_text(
5631 state.input,
5632 retrieval_query,
5633 turns,
5634 own_words_only=_web_only(route, retrieval_type),
5635 )
5636 named = _named_knowledge_bases(mentions, state.knowledge_bases)
5637 reason = await _knowledge_mention_reason(
5638 mentions,
5639 state.knowledge_bases,
5640 attached=attachment_util.names(state.attachments),
5641 attached_mentions=_attachment_mentions(state),
5642 )
5643 new_route, new_rtype = _apply_knowledge_override(
5644 route, retrieval_type, reason
5645 )
5646 if (new_route, new_rtype) != (route, retrieval_type):
5647 logger.info(
5648 "[gate] override %r/%r → %r/%r because request references %s",
5649 route,
5650 retrieval_type,
5651 new_route,
5652 new_rtype,
5653 reason,
5654 )
5655 route, retrieval_type = new_route, new_rtype
5656 triage_route["adjustments"].append(
5657 f"the request names {reason} → "
5658 f"{_route_label(route, retrieval_type)}"
5659 )
5661 # Retrieve-then-judge policy (see RetrievalConfig.always_retrieve),
5662 # which a successful web-only triage may stand against
5663 # (respect_triage_web_route).
5664 hold = _web_route_hold(
5665 bool(retrieval_cfg.get("respect_triage_web_route", True)),
5666 profile is not None,
5667 # Triage read it: no inventory text is none read at all.
5668 kb_complete and bool(kb_meta),
5669 reason,
5670 )
5671 # And a successful direct triage (respect_triage_direct_route).
5672 direct_hold = _direct_route_hold(
5673 bool(retrieval_cfg.get("respect_triage_direct_route", True)),
5674 profile is not None,
5675 kb_complete and bool(kb_meta),
5676 reason,
5677 period=dated
5678 and knowledge_categories_registry.named_window(asked)
5679 not in (None, "any"),
5680 )
5681 # When the route changed is web-only or direct, the trace
5682 # says why it did not stand.
5683 why = (
5684 f"always_retrieve; {hold}"
5685 if _web_only(route, retrieval_type)
5686 else f"always_retrieve; {direct_hold}"
5687 if route == "direct" and direct_hold
5688 else "always_retrieve"
5689 )
5690 new_route, new_rtype = _apply_kb_default(
5691 route, retrieval_type, has_kbs, always, keep_web_only=not hold
5692 )
5693 if (new_route, new_rtype) != (
5694 route,
5695 retrieval_type,
5696 ) and _attachment_route_hold(
5697 route, profile is not None, attached_now, reason
5698 ):
5699 # The documents the message attached are what it asks
5700 # about: the knowledge default stands aside.
5701 triage_route["adjustments"].append(
5702 "kept: the request is about the documents it attached, "
5703 "not the knowledge bases"
5704 )
5705 elif (
5706 (new_route, new_rtype) != (route, retrieval_type)
5707 and route == "direct"
5708 and not direct_hold
5709 ):
5710 # Triage judged that none of the knowledge bears on it.
5711 triage_route["adjustments"].append(
5712 "kept: triage judged the knowledge does not bear on the request"
5713 )
5714 elif (new_route, new_rtype) != (route, retrieval_type):
5715 logger.info(
5716 "[gate] kb default %r/%r → %r/%r (%s)",
5717 route,
5718 retrieval_type,
5719 new_route,
5720 new_rtype,
5721 why,
5722 )
5723 route, retrieval_type = new_route, new_rtype
5724 triage_route["adjustments"].append(
5725 f"knowledge default ({why}) → "
5726 f"{_route_label(route, retrieval_type)}"
5727 )
5729 # A request about what is current that triage sent to the web
5730 # alone still searches the agent's dated knowledge — and nothing
5731 # else of it, as the web-only route stood for the rest (the mix's
5732 # ``current_web`` profile).
5733 web_led = False
5734 if (
5735 dated
5736 and _web_only(route, retrieval_type)
5737 and _needs_live_data(triage_route, {}, asked)
5738 ):
5739 route, retrieval_type = "retrieve", "both"
5740 web_led = True
5741 triage_route["adjustments"].append(
5742 "the request is about what is current: its temporal "
5743 f"knowledge too → {_route_label(route, retrieval_type)}"
5744 )
5746 if len(self.nodes) == 1:
5747 plain = _plain_agent_route(route, retrieval_type)
5748 if plain != (route, retrieval_type):
5749 logger.info(
5750 "[gate] plain agent %r/%r → %r/%r — the agent searches "
5751 "and calls its tools itself",
5752 route,
5753 retrieval_type,
5754 *plain,
5755 )
5756 route, retrieval_type = plain
5757 triage_route["adjustments"].append(
5758 "plain agent: it searches and calls its tools itself → "
5759 f"{_route_label(route, retrieval_type)}"
5760 )
5761 elif state.context.get("pinned_node_ids") and self._searches_the_web():
5762 pinned = _pinned_skill_route(route, retrieval_type)
5763 if pinned != (route, retrieval_type):
5764 route, retrieval_type = pinned
5765 triage_route["adjustments"].append(
5766 "pinned skill: its own steps search the web → "
5767 f"{_route_label(route, retrieval_type)}"
5768 )
5770 # ── The task's shape, and whether to ask first ─────────────────
5771 strategy, pending, scope_check = self._task_shape(
5772 profile, route, clarify_scope, state
5773 )
5774 # Only tools the task can use: a name triage made up is dropped,
5775 # never handed to the planner.
5776 named_tools = [str(t) for t in strategy.get("relevant_tools") or []]
5777 usable = [t for t in named_tools if t in tools]
5778 if usable != named_tools:
5779 logger.info(
5780 "[gate] tools triage named that the task cannot use: %s",
5781 sorted(set(named_tools) - set(usable)),
5782 )
5783 strategy["relevant_tools"] = usable
5784 # Whether the request is about what is current is triage's
5785 # reading of the request, whatever tools the agent holds.
5786 as_triaged = {**strategy, "relevant_tools": named_tools}
5787 errors = (
5788 [
5789 f"{GATE_NODE_ID}: triage failed"
5790 + (f" ({failure['reason']})" if failure else "")
5791 + " — the full pipeline runs"
5792 ]
5793 if profile is None
5794 else []
5795 )
5796 # What the memory nodes read from triage: something to remember,
5797 # and a request for current information.
5798 cues: dict[str, Any] = {}
5799 if getattr(profile, "worth_remembering", False):
5800 cues[MEMORY_CUE_KEY] = True
5801 if _needs_live_data(triage_route, as_triaged, asked):
5802 cues[LIVE_DATA_KEY] = True
5803 if has_kbs:
5804 # The period the dated knowledge is kept to, read from the
5805 # person's words both ways (``categories.turn_window``).
5806 window = getattr(profile, "time_window", None)
5807 if dated:
5808 window, why = knowledge_categories_registry.turn_window(
5809 window, asked
5810 )
5811 if why:
5812 triage_route["adjustments"].append(why)
5813 # And what the retrieval node reads: what triage said about
5814 # the request (``categories.RetrievalTurn``), and from it the
5815 # turn's mix — which kinds of knowledge it searches, in what
5816 # role (``knowledge.mix``), decided once the route is final.
5817 turn = knowledge_categories_registry.RetrievalTurn(
5818 live=_needs_live_data(triage_route, as_triaged, asked),
5819 complexity=(
5820 str(strategy.get("complexity"))
5821 if strategy.get("source") == "triage"
5822 else None
5823 ),
5824 window_days=knowledge_categories_registry.window_days(window),
5825 named=frozenset(named),
5826 web_led=web_led,
5827 )
5828 cues[KNOWLEDGE_TURN_KEY] = turn.wire()
5829 cues[knowledge_mix.MIX_KEY] = knowledge_mix.decide(
5830 state.knowledge_bases,
5831 turn,
5832 internal=route == "retrieve"
5833 and "internal" in _retrieval_targets(retrieval_type),
5834 cfg=_retrieval_config(state),
5835 effort=effort_registry.of_state(state),
5836 empty=empty_ids,
5837 ).wire()
5839 logger.info(
5840 "[graph] ▶ node=%s step=%d route=%r retrieval_type=%r has_kbs=%s "
5841 "complexity=%r scope=%s",
5842 GATE_NODE_ID,
5843 step,
5844 route,
5845 retrieval_type,
5846 has_kbs,
5847 strategy.get("complexity"),
5848 scope_check,
5849 )
5850 return {
5851 "step_count": step,
5852 "route": route,
5853 "retrieval_type": retrieval_type,
5854 "retrieval_query": retrieval_query,
5855 "kb_metadata": kb_meta,
5856 "kb_inventory_complete": kb_complete,
5857 "empty_kb_ids": empty_ids,
5858 "triage_route": triage_route,
5859 "messages": [],
5860 "resource_strategy": strategy,
5861 "needs_synthesis": bool(strategy.get("needs_synthesis", False)),
5862 "pending_clarification": pending,
5863 "errors": errors,
5864 "attachment_plan": self._attachment_plan(state),
5865 **({"context": cues} if cues else {}),
5866 }
5868 return gate_node_fn
5870 def _tool_call_recorder(
5871 self, node_id: str, state: "GraphState"
5872 ) -> Callable[..., None] | None:
5873 """What a node's tool loop records each tool call with
5874 (``on_tool_call``): a ``tool_invocations`` row under the node, the
5875 turn's conversation and user, so the decision record's Tool calls and
5876 Web sources list it. Every node that calls tools passes it — the
5877 retrieval workers too, whose searches had reached the stream and
5878 nowhere else. None without a database."""
5879 on_tool_call = None
5880 if self._db is not None:
5881 from uuid import UUID as _UUID
5883 from app.db.postgres.enums import ToolInvocationEnum
5884 from app.services.conversation import persist_tool_invocation
5886 _db = self._db
5887 _execution_context = {
5888 "node_id": node_id,
5889 "skill_id": state.context.get("skill_id"),
5890 "skill_name": state.context.get("skill_name"),
5891 }
5892 _raw_conv_id = state.context.get("conversation_id")
5893 _conversation_id: Any = None
5894 if _raw_conv_id:
5895 try:
5896 _conversation_id = _UUID(str(_raw_conv_id))
5897 except (ValueError, TypeError):
5898 pass
5900 _raw_user_id = state.context.get("user_id")
5901 _user_id: Any = None
5902 if _raw_user_id:
5903 try:
5904 _user_id = _UUID(str(_raw_user_id))
5905 except (ValueError, TypeError):
5906 pass
5908 def on_tool_call(
5909 tool_name: str,
5910 input_args: dict,
5911 raw_output: str,
5912 latency_ms: int,
5913 status: ToolInvocationEnum.Status,
5914 error_detail: str | None,
5915 artifact: Any = None,
5916 ) -> None:
5917 citations = None
5918 if (
5919 tool_name == "web_search"
5920 and status == ToolInvocationEnum.Status.success
5921 ):
5922 from app.inference.engines.graph_based import extract_citations
5923 from app.tools.web import domain_quality_score
5925 citations = [
5926 {
5927 **citation,
5928 "index": idx,
5929 "relevance_score": domain_quality_score(citation["source"])
5930 / 4.0,
5931 }
5932 for idx, citation in enumerate(
5933 extract_citations(tool_name, input_args, raw_output),
5934 start=1,
5935 )
5936 ]
5938 # Under a withhold rule the call is traced without what
5939 # it was given or returned: its arguments may be the
5940 # answer itself (a document's body). A web search's
5941 # report is kept without the hosts it names.
5942 held = self.withholding
5943 report = web_search_report.SearchReport.read(artifact)
5944 if report is not None and held:
5945 report = report.without_hosts()
5946 persist_tool_invocation(
5947 _db,
5948 tool_name=tool_name,
5949 input_args=None if held else input_args,
5950 raw_output=None if held else raw_output,
5951 report=report.wire() if report is not None else None,
5952 status=status,
5953 latency_ms=latency_ms,
5954 error_detail=error_detail,
5955 execution_context=_execution_context,
5956 conversation_id=_conversation_id,
5957 user_id=_user_id,
5958 citations=citations,
5959 )
5961 return on_tool_call
5963 def _searches_the_web(self) -> bool:
5964 """Whether a step of this graph holds a web tool of its own."""
5965 return any(
5966 source_ledger.tool_kind(str(getattr(t, "name", ""))) == "web"
5967 for node in self.nodes.values()
5968 for t in getattr(node.agent, "tools", ()) or ()
5969 )
5971 def _triage_tools(self, state: GraphState) -> list[str]:
5972 """The tools triage may name for a task (``relevant_tools``): what the
5973 answering nodes hold, with the knowledge tools when there is
5974 knowledge and ``ask_user`` where a node may ask. A graph of several
5975 nodes adds every built-in, which its planner may hand a node. Not the
5976 attachment tools: they come and go with a conversation's documents,
5977 and triage's prompt is cached for the agent."""
5978 from app.tools import registry as tool_registry
5980 names: set[str] = set()
5981 for node in self.nodes.values():
5982 names |= {
5983 str(getattr(t, "name", "")) for t in getattr(node.agent, "tools", ())
5984 }
5985 if node.ask_user and self.may_ask:
5986 names.add(clarify.ASK_USER)
5987 if len(self.nodes) > 1:
5988 names |= set(tool_registry.BUILTIN_TOOLS)
5989 kinds = {kb.get("source_type") for kb in state.knowledge_bases or []}
5990 if kinds - {"graph"}:
5991 names |= {
5992 tool_registry.SEARCH_KNOWLEDGE_TOOL,
5993 tool_registry.READ_DOCUMENT_TOOL,
5994 tool_registry.LIST_DOCUMENTS_TOOL,
5995 }
5996 if "graph" in kinds:
5997 names.add(tool_registry.EXPLORE_GRAPH_TOOL)
5998 names.discard("")
5999 if not self.may_ask:
6000 names.discard(clarify.ASK_USER)
6001 return sorted(names)
6003 def _attachment_plan(self, state: GraphState) -> list[dict[str, Any]]:
6004 """How the agent that answers first is shown each of the
6005 conversation's documents (``attachments.plan`` for its model's
6006 window), as the trace records it — never a document's text."""
6007 if not state.attachments:
6008 return []
6009 start = self.nodes.get(self.start_node or "")
6010 llm = getattr(getattr(start, "agent", None), "llm", None)
6011 return [
6012 planned.summary()
6013 for planned in attachment_util.plan(state.attachments, _context_window(llm))
6014 ]
6016 def _task_shape(
6017 self,
6018 profile: "RequestProfile | None",
6019 route: str,
6020 clarify_scope: bool,
6021 state: GraphState,
6022 ) -> tuple[dict[str, Any], dict[str, Any] | None, str]:
6023 """The task's shape (``resource_strategy``, for the planner and the
6024 routers), the scope form to ask before any work (or None), and what
6025 the scope check found (``off`` / ``clear`` / ``ambiguous`` /
6026 ``unavailable``).
6028 From triage's answer when there is one, else the full pipeline: a
6029 failed triage is not asked again. Then the topology rules, whatever
6030 classified the task: skipping the skill graph is valid only for a
6031 direct route on a graph whose nodes the planner may choose between —
6032 a retrieve route needs its evidence answered, a stored skill
6033 (pinned) is the user's workflow, and a single node IS the agent
6034 (skipping it answered a chat from a generic synthesis node without
6035 the agent's tools). One node's answer needs no consolidation: a
6036 synthesis pass over it only rewrites the agent's reply.
6037 """
6038 strategy: dict[str, Any] = {
6039 "complexity": "moderate",
6040 "use_skill_graph": True,
6041 "needs_synthesis": False,
6042 "relevant_tools": [],
6043 "resource_notes": "",
6044 "source": "default",
6045 }
6046 scoped: ScopedResourceStrategy | None = None
6047 if isinstance(profile, ResourceStrategy):
6048 fields = (
6049 ScopedResourceStrategy if clarify_scope else ResourceStrategy
6050 ).model_fields
6051 strategy = {**profile.model_dump(include=set(fields)), "source": "triage"}
6052 if clarify_scope and isinstance(profile, ScopedResourceStrategy):
6053 scoped = profile
6054 # The questions travel in pending_clarification, not in the
6055 # strategy the planner reads.
6056 strategy.pop("clarifying_questions", None)
6058 single_node = len(self.nodes) == 1
6059 if route != "direct" or single_node or state.context.get("pinned_node_ids"):
6060 strategy["use_skill_graph"] = True
6061 if single_node:
6062 strategy["needs_synthesis"] = False
6064 pending = _scope_clarification(scoped) if scoped is not None else None
6065 # "unavailable" when the check was asked for and could not run: it
6066 # once read "clear", which says the scope was checked.
6067 if not clarify_scope:
6068 scope_check = "off"
6069 elif scoped is None:
6070 scope_check = "unavailable"
6071 else:
6072 scope_check = "ambiguous" if pending else "clear"
6073 strategy["scope_check"] = scope_check
6074 return strategy, pending, scope_check
6076 def _create_clarify_node_fn(self) -> Callable[[GraphState], dict[str, Any]]:
6077 """Create the clarification node — the one place a person is asked
6078 anything.
6080 Asks the questions parked in ``pending_clarification`` via
6081 ``interrupt()``: by triage's scope check before any work, or by a
6082 skill node whose agent called ``ask_user`` mid-task (``source``
6083 ``tool``, the step having ended there). It folds the answers into
6084 ``state.input`` as a ``<clarified_scope>`` block, so planning,
6085 retrieval, every skill node, synthesis and the evaluator all work to
6086 what the person chose without each needing to know a clarification
6087 happened. A mid-task question then goes back to the skill graph
6088 (``_clarify_router``), whose step starts again with the answers and
6089 its earlier tool calls listed. Memory is the exception: it reads the
6090 request as sent, kept once in ``request_before_clarification``, and
6091 the answers from ``clarifications`` (``clarify.answer_labels``).
6093 Deterministic by construction: it makes no model call, so the replay
6094 a resume triggers asks exactly the questions that were shown.
6095 Skipping (an empty answer set) is honoured, not re-asked — the agent
6096 is told to proceed on its best reading and state its assumptions.
6097 """
6098 from app.tools.clarify import (
6099 SOURCE_SCOPE,
6100 SOURCE_TOOL,
6101 answers_from_resume,
6102 format_answers,
6103 validate_questions,
6104 was_skipped,
6105 )
6107 async def clarify_node_fn(state: GraphState) -> dict[str, Any]:
6108 step = state.step_count + 1
6109 payload = dict(state.pending_clarification or {})
6110 if not payload:
6111 return {"step_count": step, "pending_clarification": None}
6112 questions = validate_questions(payload.get("questions") or [])
6113 source = (
6114 SOURCE_TOOL if payload.get("source") == SOURCE_TOOL else SOURCE_SCOPE
6115 )
6116 logger.info(
6117 "[graph] ▶ node=%s asking %d question(s) source=%s",
6118 CLARIFY_NODE_ID,
6119 len(questions),
6120 source,
6121 )
6123 # Suspends here; returns the resume payload once answered.
6124 response = lg_interrupt({**payload, "node_id": CLARIFY_NODE_ID})
6125 answers = answers_from_resume(response)
6126 skipped = was_skipped(answers)
6127 rendered = format_answers(questions, answers)
6128 if source == SOURCE_TOOL:
6129 said = (
6130 "While working on this request you asked the user some "
6131 "questions, and they chose not to answer. Carry on with the "
6132 "most reasonable reading and state the assumptions you made."
6133 if skipped
6134 else "While working on this request you asked the user some "
6135 "questions. Treat their answers as part of the request, and "
6136 "reuse the tool results you already have:\n\n" + rendered
6137 )
6138 else:
6139 said = (
6140 "The user was asked to clarify the scope of this request "
6141 "and chose not to answer. Proceed on the most reasonable "
6142 "reading and state the assumptions you made."
6143 if skipped
6144 else "Before any work started, the user clarified the "
6145 "scope of this request. Treat these answers as part of "
6146 "the request:\n\n" + rendered
6147 )
6148 block = f"<clarified_scope>\n{said}\n</clarified_scope>"
6149 logger.info("[graph] ✔ node=%s skipped=%s", CLARIFY_NODE_ID, skipped)
6150 from langchain_core.messages import AIMessage as _AI
6152 return {
6153 "step_count": step,
6154 "input": f"{state.input}\n\n{block}",
6155 "request_before_clarification": (
6156 state.request_before_clarification or state.input
6157 ),
6158 "pending_clarification": None,
6159 "clarifications": [
6160 *state.clarifications,
6161 {
6162 "source": source,
6163 "reason": payload.get("reason") or "",
6164 "questions": [q.model_dump() for q in questions],
6165 "answers": answers,
6166 "skipped": skipped,
6167 },
6168 ],
6169 "messages": [
6170 _AI(
6171 content=(
6172 "Clarification skipped"
6173 if skipped
6174 else "Clarified:\n" + rendered
6175 )
6176 if source == SOURCE_TOOL
6177 else (
6178 "Scope clarification skipped"
6179 if skipped
6180 else "Scope clarified:\n" + rendered
6181 ),
6182 name=CLARIFY_NODE_ID,
6183 )
6184 ],
6185 }
6187 return clarify_node_fn
6189 def _create_planning_node_fn(
6190 self,
6191 system_llm: BaseLanguageModel | None,
6192 skill_node_descriptors: list[dict[str, str]],
6193 ) -> Callable[[GraphState], dict[str, Any]]:
6194 """
6195 Create the planning node function.
6197 Runs before retrieval with no tools. Uses the LLM's structured-output
6198 capability to produce an ``ExecutionPlan`` covering every node that will
6199 actually execute for this request. The plan is stored as a plain dict in
6200 ``state.execution_plan`` for all downstream nodes to read.
6202 Falls back to an empty plan (all nodes use their base prompts) when
6203 structured output is unavailable or the LLM call fails.
6205 The graph description is built at runtime so it reflects the active route
6206 and retrieval_type — e.g. only ``__internal_retrieval__`` is listed when
6207 ``retrieval_type == "internal"``.
6208 """
6210 async def planning_node_fn(state: GraphState) -> dict[str, Any]:
6211 step = state.step_count + 1
6213 # ── One node: nothing to plan ─────────────────────────────────
6214 # A plain agent is a single-node graph. The planner's only
6215 # decision there was whether to run the agent — and choosing not
6216 # to handed the answer to a synthesis node without its tools. Its
6217 # per-node goal restated the request, and its tool guidance named
6218 # tools the agent is already given. Retrieval works from the
6219 # gate's standalone query.
6220 if len(self.nodes) == 1:
6221 only = next(iter(self.nodes))
6222 logger.info(
6223 "[graph] ▶ node=%s step=%d single node %r — no plan needed",
6224 PLANNING_NODE_ID,
6225 step,
6226 only,
6227 )
6228 from langchain_core.messages import AIMessage as _AIMessage
6230 return {
6231 "step_count": step,
6232 "messages": [
6233 _AIMessage(content=SINGLE_NODE_PLAN_NOTE, name=PLANNING_NODE_ID)
6234 ],
6235 "execution_plan": {},
6236 "active_node_ids": [only],
6237 "needs_synthesis": False,
6238 }
6240 kb_count = len(state.knowledge_bases)
6241 targets = _retrieval_targets(state.retrieval_type)
6243 # Build the graph description from the active route so the planner
6244 # only sees nodes that will actually run in this execution.
6245 will_retrieve = state.route in ("", "retrieve")
6246 runtime_system_nodes: list[dict[str, str]] = []
6247 if will_retrieve and "internal" in targets and kb_count > 0:
6248 runtime_system_nodes.append(
6249 {
6250 "node_id": INTERNAL_RETRIEVAL_NODE_ID,
6251 "role": "internal_knowledge_retrieval_specialist",
6252 "description": "Queries internal knowledge bases (entities, documents, relationships).",
6253 }
6254 )
6255 if will_retrieve and "external" in targets:
6256 runtime_system_nodes.append(
6257 {
6258 "node_id": EXTERNAL_RETRIEVAL_NODE_ID,
6259 "role": "external_data_retrieval_specialist",
6260 "description": "Searches external sources (web search, live APIs) for current information.",
6261 }
6262 )
6263 if will_retrieve and "tools" in targets:
6264 runtime_system_nodes.append(
6265 {
6266 "node_id": TOOL_RETRIEVAL_NODE_ID,
6267 "role": "tool_based_information_retrieval_specialist",
6268 "description": (
6269 "Fetches specific factual data using deterministic "
6270 f"tools ({vocab.listing(prompts.DETERMINISTIC_TOOLS, sep=', ')})."
6271 ),
6272 }
6273 )
6274 runtime_system_nodes.extend(skill_node_descriptors)
6275 # Include synthesis in the plan description only when it will actually
6276 # run — determined by triage's needs_synthesis assessment.
6277 if state.needs_synthesis:
6278 runtime_system_nodes.append(
6279 {
6280 "node_id": SYNTHESIS_NODE_ID,
6281 "role": "synthesis_specialist",
6282 "description": (
6283 "Consolidates all skill node outputs into the final response. "
6284 "Has the render tools (charts, plots, maps, diagrams) and geocode bound."
6285 ),
6286 }
6287 )
6288 graph_desc = "\n".join(
6289 f" - {n['node_id']} ({n['role']}): {n['description']}"
6290 for n in runtime_system_nodes
6291 )
6293 logger.info(
6294 "[graph] ▶ node=%s step=%d route=%r skill_nodes=%d kb=%d",
6295 PLANNING_NODE_ID,
6296 step,
6297 state.route,
6298 len(skill_node_descriptors),
6299 kb_count,
6300 )
6302 from app.tools.registry import BUILTIN_TOOLS as _BUILTIN_TOOLS
6304 available_tools = sorted(_BUILTIN_TOOLS.keys())
6305 metadata_ctx = prompts.build_metadata_context()
6307 worker = _SystemWorker(
6308 name=PLANNING_NODE_ID,
6309 llm=system_llm,
6310 system_prompt=(
6311 f"{metadata_ctx}\n\n"
6312 "You are an execution planner. Given a user task and the graph of agents "
6313 "that will process it, produce a precise execution plan specifying the "
6314 "goal and expected output for every skill node you dispatch (none, when "
6315 "you dispatch none). Plans must be specific and "
6316 "actionable — not generic. Reference the task details directly.\n\n"
6317 "For tool_guidance, give one entry per dispatched worker node: its "
6318 "node_id and the subset of available builtin tools relevant to the task. "
6319 "Only include tools that would genuinely help — do not recommend tools "
6320 "that are irrelevant."
6321 ),
6322 )
6324 retrieval_ctx = ""
6325 if will_retrieve:
6326 parts: list[str] = []
6327 if "internal" in targets:
6328 parts.append("internal knowledge bases (fill retrieval_focus)")
6329 if "external" in targets:
6330 parts.append("external web/APIs (fill external_retrieval_focus)")
6331 if "tools" in targets:
6332 parts.append(
6333 "deterministic tools "
6334 f"({vocab.listing(prompts.DETERMINISTIC_TOOLS, sep=', ')})"
6335 )
6336 retrieval_ctx = "Retrieval strategy: " + " AND ".join(parts) + "."
6337 if state.retrieval_query and state.retrieval_query != state.input:
6338 retrieval_ctx += (
6339 f"\nStandalone form of the request (history resolved): "
6340 f"{state.retrieval_query}"
6341 )
6343 kb_meta_section = ""
6344 if state.kb_metadata:
6345 kb_meta_section = (
6346 f"\n\nKnowledge base contents "
6347 f"(use this to write precise retrieval_focus / external_retrieval_focus):\n"
6348 f"{state.kb_metadata}"
6349 )
6351 strategy_section = ""
6352 if state.resource_strategy:
6353 notes = state.resource_strategy.get("resource_notes", "")
6354 seeded = state.resource_strategy.get("relevant_tools", [])
6355 complexity = state.resource_strategy.get("complexity", "")
6356 parts = []
6357 if complexity:
6358 parts.append(f"Complexity: {complexity}")
6359 if seeded:
6360 parts.append(f"Suggested tools from triage: {seeded}")
6361 if notes:
6362 parts.append(f"Resource notes: {notes}")
6363 if parts:
6364 strategy_section = (
6365 "\n\nResource strategy from triage:\n" + "\n".join(parts)
6366 )
6368 # ── Recent conversation context ───────────────────────────────
6369 # Include the last few conversation turns so the planner can produce
6370 # coherent follow-up plans ("expand on point 2", "now analyse for risk",
6371 # etc.). Without this the planner treats every request as isolated and
6372 # can produce redundant or out-of-context plans.
6373 # Capped at 3 turns (6 messages) to avoid bloating the planning call.
6374 conv_history_raw: list[dict] = state.context.get(
6375 "conversation_history", []
6376 ) or _conversation_tail(state)
6377 conv_section = ""
6378 if conv_history_raw:
6379 _PLAN_CONV_WINDOW = 6 # last 3 turns (user + assistant per turn)
6380 recent = conv_history_raw[-_PLAN_CONV_WINDOW:]
6381 conv_lines = []
6382 for m in recent:
6383 role = m.get("role", "")
6384 content = str(m.get("content", ""))[:400]
6385 if role in ("user", "assistant", "model"):
6386 label = "User" if role == "user" else "Assistant"
6387 line = f" {label}: {content}"
6388 # Annotate assistant messages with their evaluator quality
6389 # signal so the planner avoids repeating the same gaps.
6390 if role in ("assistant", "model"):
6391 ev = m.get("eval", {})
6392 if ev:
6393 ev_parts = []
6394 if ev.get("score") is not None:
6395 ev_parts.append(f"quality {ev['score']}/100")
6396 if ev.get("critique"):
6397 ev_parts.append(f'critique: "{ev["critique"]}"')
6398 if ev.get("gaps"):
6399 ev_parts.append(f"gaps: {ev['gaps']}")
6400 if ev_parts:
6401 line += f" [prev eval — {', '.join(ev_parts)}]"
6402 conv_lines.append(line)
6403 if conv_lines:
6404 conv_section = (
6405 "\n\nRecent conversation (use to plan follow-up responses correctly):\n"
6406 + "\n".join(conv_lines)
6407 )
6409 # The documents the conversation attached, by name and size:
6410 # every node is shown them, so none needs dispatching to read one.
6411 attached_lines = attachment_util.manifest_lines(state.attachments)
6412 attached_section = (
6413 "Documents the person attached (every node is shown them):\n"
6414 + "\n".join(attached_lines)
6415 + "\n\n"
6416 if attached_lines
6417 else ""
6418 )
6419 task = (
6420 f"Task:\n{state.input}\n\n"
6421 f"{attached_section}"
6422 f"Available builtin tools: {available_tools}\n\n"
6423 f"Knowledge bases available: {kb_count}\n"
6424 f"{retrieval_ctx}"
6425 f"{kb_meta_section}"
6426 f"{strategy_section}"
6427 f"{conv_section}\n\n"
6428 f"Execution graph (available nodes):\n{graph_desc}\n\n"
6429 "Produce an ExecutionPlan for this task.\n\n"
6430 "DISPATCH SELECTION — active_nodes:\n"
6431 " List in active_nodes ONLY skill nodes whose specialised role adds\n"
6432 " genuine value beyond retrieval + synthesis (e.g. domain analysis,\n"
6433 " validation, code generation). Nodes absent from active_nodes are\n"
6434 " skipped entirely.\n"
6435 " Leave active_nodes EMPTY to skip the skill graph: the pipeline then\n"
6436 " synthesises the final answer directly from the retrieved context.\n"
6437 " This is the right choice for lookups, factual questions, and\n"
6438 " summaries — a generic agent node would only re-summarise (and\n"
6439 " degrade) the retrieval output. Skipping is also safe for requests\n"
6440 " needing visuals (maps, charts, diagrams): __synthesis__ has the\n"
6441 " render tools and geocode bound and produces them itself.\n"
6442 " Never include system nodes (__retrieval__, __synthesis__, etc.).\n\n"
6443 "Only include node_plans for nodes listed in active_nodes.\n"
6444 "Include tool_guidance for each active skill node, incorporating any "
6445 "tool suggestions from the resource strategy above."
6446 )
6448 if state.memories:
6449 task = (
6450 f"{task}\n\nWhat the agent remembers of this person from earlier "
6451 "conversations (notes, which may not apply):\n"
6452 f"{memory_render.plain(state.memories)}"
6453 )
6455 try:
6456 llm = worker.resolve_llm()
6457 from langchain_core.messages import (
6458 HumanMessage as _HumanMessage,
6459 )
6460 from langchain_core.messages import (
6461 SystemMessage as _SystemMessage,
6462 )
6464 result = await structured_call(
6465 llm,
6466 ExecutionPlan,
6467 [
6468 _SystemMessage(content=worker.system_prompt),
6469 _HumanMessage(content=task),
6470 ],
6471 purpose=PLANNING_NODE_ID,
6472 )
6473 plan: ExecutionPlan = result.unwrap()
6474 plan_dict = plan.model_dump()
6475 # Stored as node_id → tools, the shape every reader expects.
6476 plan_dict["tool_guidance"] = plan.guidance_map()
6477 # Derive active_node_ids: prefer explicit active_nodes from the plan;
6478 # fall back to node_plans, then to every registered skill node.
6479 # Order-preserving dedupe keeps the planner's intended sequence.
6480 _registered_skill_ids = set(self.nodes.keys())
6481 _all_skill_ids = list(self.nodes.keys())
6483 def _validate_ids(candidates: list[str], source: str) -> list[str]:
6484 valid = list(
6485 dict.fromkeys(
6486 n
6487 for n in candidates
6488 if n in _registered_skill_ids and n not in SYSTEM_NODE_IDS
6489 )
6490 )
6491 hallucinated = [
6492 n
6493 for n in candidates
6494 if n not in _registered_skill_ids and n not in SYSTEM_NODE_IDS
6495 ]
6496 if hallucinated:
6497 logger.warning(
6498 "[graph] node=%s planner %s listed unregistered node IDs %s — ignored",
6499 PLANNING_NODE_ID,
6500 source,
6501 hallucinated,
6502 )
6503 return valid
6505 active_node_ids = _validate_ids(plan.active_nodes, "active_nodes")
6506 if plan.active_nodes and not active_node_ids:
6507 # Planner selected nodes but EVERY one was unregistered —
6508 # the selection can't be trusted; degrade gracefully by
6509 # running every registered skill node.
6510 logger.warning(
6511 "[graph] node=%s all planner-selected nodes were invalid — "
6512 "falling back to all %d skill node(s)",
6513 PLANNING_NODE_ID,
6514 len(_all_skill_ids),
6515 )
6516 active_node_ids = _all_skill_ids
6517 elif not plan.active_nodes:
6518 # active_nodes left empty — honour node_plans if the planner
6519 # specified skill work there; otherwise this is a DELIBERATE
6520 # skip: the skill graph is bypassed and __synthesis__ answers
6521 # directly from the retrieved context.
6522 active_node_ids = _validate_ids(
6523 [np.node_id for np in plan.node_plans], "node_plans"
6524 )
6526 # ── Pinned dispatch (skill execution) ─────────────────────
6527 # A stored skill graph is the user's explicit workflow — the
6528 # planner still contributes per-node goals and tool guidance,
6529 # but it must not prune or reorder the nodes. SkillEngine
6530 # sets context["pinned_node_ids"] to every graph node.
6531 pinned = [
6532 n
6533 for n in (state.context.get("pinned_node_ids") or [])
6534 if n in _registered_skill_ids
6535 ]
6536 if pinned and set(active_node_ids) != set(pinned):
6537 logger.info(
6538 "[graph] node=%s dispatch pinned to %s (planner selected %s)",
6539 PLANNING_NODE_ID,
6540 pinned,
6541 active_node_ids,
6542 )
6543 active_node_ids = pinned
6545 # ── Triage ↔ planner conflict guard ───────────────────────
6546 # Triage decides needs_synthesis BEFORE the planner selects
6547 # which skill nodes run. Force a synthesis pass when:
6548 # - the planner skipped the skill graph (synthesis IS the
6549 # answer-producing node on that path), or
6550 # - multiple skill nodes run (the skip-synthesis path would
6551 # surface only the LAST node's output, dropping the rest).
6552 needs_synthesis = state.needs_synthesis
6553 if not active_node_ids:
6554 logger.info(
6555 "[graph] node=%s planner skipped the skill graph — "
6556 "synthesis will answer directly from retrieved context",
6557 PLANNING_NODE_ID,
6558 )
6559 needs_synthesis = True
6560 elif len(active_node_ids) > 1 and not needs_synthesis:
6561 logger.info(
6562 "[graph] node=%s overriding needs_synthesis=True — triage predicted "
6563 "a single-node answer but the planner dispatched %d skill nodes",
6564 PLANNING_NODE_ID,
6565 len(active_node_ids),
6566 )
6567 needs_synthesis = True
6568 logger.info(
6569 "[graph] ✔ node=%s planned_nodes=%d active_skill_nodes=%s",
6570 PLANNING_NODE_ID,
6571 len(plan.node_plans),
6572 active_node_ids,
6573 )
6574 from langchain_core.messages import AIMessage as _AIMessage
6576 focus_parts = []
6577 if plan.retrieval_focus:
6578 focus_parts.append(f"Internal focus: {plan.retrieval_focus}")
6579 if plan.external_retrieval_focus:
6580 focus_parts.append(
6581 f"External focus: {plan.external_retrieval_focus}"
6582 )
6583 dispatch_line = (
6584 f"Dispatching {len(active_node_ids)} skill node(s): {active_node_ids}."
6585 if active_node_ids
6586 else "Skill graph skipped — synthesis will answer directly from retrieved context."
6587 )
6588 plan_summary = f"{dispatch_line}\nOverall goal: {plan.overall_goal}" + (
6589 "\n" + "\n".join(focus_parts) if focus_parts else ""
6590 )
6591 return {
6592 "step_count": step,
6593 "messages": [
6594 _AIMessage(content=plan_summary, name=PLANNING_NODE_ID)
6595 ],
6596 "execution_plan": plan_dict,
6597 "active_node_ids": active_node_ids,
6598 "needs_synthesis": needs_synthesis,
6599 }
6601 except Exception as exc:
6602 model_errors.raise_if_fatal(exc)
6603 logger.warning(
6604 "[graph] ✘ node=%s error=%s — continuing with empty plan",
6605 PLANNING_NODE_ID,
6606 model_errors.describe(exc),
6607 )
6608 from langchain_core.messages import AIMessage as _AIMessage
6610 # The failure is recorded for the trace (errors) and the log —
6611 # never in message content, which is part of the run's record
6612 # and once reached the answering model as its own reply.
6613 return {
6614 "step_count": step,
6615 "messages": [
6616 _AIMessage(
6617 content="Planning unavailable — dispatching every skill node.",
6618 name=PLANNING_NODE_ID,
6619 )
6620 ],
6621 "errors": [f"{PLANNING_NODE_ID}: {model_errors.describe(exc)}"],
6622 "execution_plan": {},
6623 # On a failed plan, explicitly dispatch every skill node —
6624 # an empty list now means "deliberately skip the skill
6625 # graph", which must never result from a planner error.
6626 "active_node_ids": list(self.nodes.keys()),
6627 }
6629 return planning_node_fn
6631 def _simple_answer_llm(
6632 self,
6633 state: GraphState,
6634 agent: Any,
6635 history: list[BaseMessage],
6636 *,
6637 system_text: str,
6638 task_text: str,
6639 tools: list[Any],
6640 ) -> BaseLanguageModel | None:
6641 """The lighter model, when it answers this request in place of the
6642 agent's own (an Economy profile, ``effort.lighter_simple_answers``):
6643 a plain agent's first pass at a request triage called simple, whose
6644 conversation the lighter model takes whole. A stored skill's graph is
6645 the user's own workflow and keeps its models; a revision, which only
6646 a failed check asks for, is the agent's own model's to write."""
6647 llm = self._answer_llm
6648 if llm is None or len(self.nodes) != 1:
6649 return None
6650 if (state.context or {}).get("pinned_node_ids"):
6651 return None
6652 if state.eval_retry_count:
6653 return None
6654 if (state.resource_strategy or {}).get("complexity") != "simple":
6655 return None
6656 from app.services import token_budget
6658 if not token_budget.fits(
6659 llm,
6660 history,
6661 system_text=system_text,
6662 task_text=task_text,
6663 tools=tools,
6664 profile_cap=getattr(agent, "history_token_cap", None),
6665 ):
6666 logger.info(
6667 "[graph] simple request, but the conversation does not fit the "
6668 "lighter model whole — the agent's own model answers"
6669 )
6670 return None
6671 return llm
6673 def _create_skill_node_fn(
6674 self, node_id: str, agent: WorkerAgent, node: GraphNode | None = None
6675 ) -> Callable[[GraphState], dict[str, Any]]:
6676 """
6677 Wrap a skill agent's ``process_with_history`` call as a LangGraph node.
6679 Skill nodes only have access to their own configured tools. Knowledge
6680 base retrieval is handled exclusively by the ``__retrieval__`` node;
6681 its output arrives here as ``state.retrieval_context`` injected into
6682 the system prompt as read-only context.
6684 State bindings (schema v2)
6685 --------------------------
6686 ``node`` carries the optional state bindings: ``output_key`` writes the
6687 node result into ``state.state_vars``; ``prompt_template`` replaces the
6688 default aggregated task content, rendering ``{key}`` placeholders from
6689 state variables; ``input_keys`` surfaces selected state variables as
6690 context. Operation agents (``is_operation``) bypass the whole LLM
6691 path and run deterministically against the state variables.
6693 Message trace
6694 -------------
6695 All messages produced by ``run_with_tools`` — tool-call AIMessages,
6696 ToolMessages, and the final synthesis AIMessage — are stored in
6697 ``GraphState.messages`` via the ``add_messages`` reducer.
6699 Prior context injection
6700 -----------------------
6701 The model reads ``[system, …earlier conversation turns, task]``
6702 (``_history_messages``). Earlier nodes' outputs arrive in the task
6703 content (``_aggregate_prior_results``) and evidence in ``<knowledge>``
6704 — never as replayed messages.
6705 """
6706 output_key = node.output_key if node else ""
6707 prompt_template = node.prompt_template if node else ""
6708 input_keys = list(node.input_keys) if node else []
6709 input_bindings: dict[str, Any] = dict(node.inputs) if node else {}
6711 def _bind_inputs(
6712 variables: dict[str, Any],
6713 ) -> tuple[dict[str, Any], list[str]]:
6714 """Render this node's typed input bindings and validate them.
6716 Returns ``(bound_values, problems)``. Every declared input_schema
6717 field with no explicit binding is auto-bound from a same-named
6718 graph variable (state key or node id) — so ``{"contract_text": …}``
6719 in state flows into a worker input called ``contract_text``
6720 without ceremony.
6721 """
6722 from app.agents.interfaces import validate_inputs
6723 from app.agents.operations import (
6724 _SINGLE_PLACEHOLDER_RE,
6725 render_binding,
6726 )
6728 bound: dict[str, Any] = {}
6729 problems: list[str] = []
6730 for name, binding in input_bindings.items():
6731 rendered = render_binding(binding, variables)
6732 # A binding that is exactly one unresolved {placeholder} is a
6733 # dangling reference (upstream node skipped / key never
6734 # written) — report it and treat the input as absent rather
6735 # than passing the literal "{path}" text to the worker.
6736 if (
6737 isinstance(binding, str)
6738 and rendered == binding
6739 and _SINGLE_PLACEHOLDER_RE.match(binding)
6740 ):
6741 problems.append(
6742 f"input {name!r}: unresolved reference {binding.strip()}"
6743 )
6744 continue
6745 bound[name] = rendered
6746 for spec in agent.input_schema:
6747 if spec.name not in bound and spec.name in variables:
6748 bound[spec.name] = variables[spec.name]
6749 if not agent.input_schema:
6750 return bound, problems
6751 coerced, errors = validate_inputs(agent.input_schema, bound)
6752 return coerced, problems + errors
6754 def _state_write(result: Any) -> dict[str, Any]:
6755 """state_vars delta for this node's result (empty when unbound)."""
6756 if not output_key:
6757 return {}
6758 value = (
6759 result
6760 if isinstance(result, (str, int, float, bool, dict, list))
6761 else (
6762 result.model_dump()
6763 if hasattr(result, "model_dump")
6764 else str(result)
6765 )
6766 )
6767 return {"state_vars": {output_key: value}}
6769 async def node_fn(
6770 state: GraphState, config: RunnableConfig | None = None
6771 ) -> dict[str, Any]:
6772 # ── Planner dispatch check ────────────────────────────────────
6773 # If the planner selected a specific set of skill nodes, skip any
6774 # node not in that set — avoids redundant LLM calls.
6775 active = state.active_node_ids
6776 if active and node_id not in active:
6777 logger.info(
6778 "[graph] ⏭ node=%s step=%d skipped (not in planner dispatch: %s)",
6779 node_id,
6780 state.step_count + 1,
6781 active,
6782 )
6783 return {"step_count": state.step_count + 1}
6785 # ── A question is waiting ─────────────────────────────────────
6786 # An earlier step asked the person something (``ask_user``); the
6787 # steps after it wait for the answer, which ``__clarify__`` gets.
6788 if state.pending_clarification:
6789 logger.info("[graph] ⏭ node=%s waiting for a clarification", node_id)
6790 return {"step_count": state.step_count + 1}
6792 # ── Approval gate ─────────────────────────────────────────────
6793 # First, before any work: a resume replays this node from the
6794 # top, and nothing above this line costs anything.
6795 reviewer_feedback = ""
6796 if node is not None and node.approval:
6797 reviewer_feedback = self._await_approval(node_id, node, state)
6799 step = state.step_count + 1
6800 agent_type = type(agent).__name__
6801 tool_names = [t.name for t in agent.tools] if agent.tools else []
6802 # Unified namespace: input + state variables + every completed
6803 # node's result under its id (so ``{node.field}`` resolves).
6804 from app.agents.conditions import graph_variables
6806 state_variables: dict[str, Any] = graph_variables(state)
6807 bound_inputs, input_problems = _bind_inputs(state_variables)
6808 if input_problems:
6809 logger.warning(
6810 "[graph] node=%s input binding problems: %s",
6811 node_id,
6812 input_problems,
6813 )
6814 if bound_inputs:
6815 # Bound inputs are addressable in templates / tool args as
6816 # ``{inputs.<field>}`` and shadow nothing else.
6817 state_variables = {**state_variables, "inputs": bound_inputs}
6819 # ── Operation fast-path (deterministic, no LLM) ───────────────
6820 # Tool / transform nodes run directly against the state variables:
6821 # no prompt assembly, no conversation threading, no LLM cost.
6822 if getattr(agent, "is_operation", False):
6823 logger.info(
6824 "[graph] ▶ operation node=%s agent=%s step=%d",
6825 node_id,
6826 agent_type,
6827 step,
6828 )
6829 try:
6830 op_result = await agent.run_operation(
6831 state_variables,
6832 # A tool step that fetches (url_fetch, a document's
6833 # images) does so under the run's web policy.
6834 web_config=state.context.get("web_search_config"),
6835 )
6836 if agent.output_schema and not isinstance(op_result, dict):
6837 from app.agents.interfaces import parse_structured_output
6839 parsed, _perr = parse_structured_output(
6840 op_result, agent.output_schema
6841 )
6842 if parsed is not None:
6843 op_result = parsed
6844 return {
6845 "step_count": step,
6846 "messages": [
6847 AIMessage(content=_result_text(op_result), name=node_id)
6848 ],
6849 "artifacts": _visual_fences(_operation_artifacts(op_result)),
6850 "documents": _document_entries(
6851 _operation_artifacts(op_result),
6852 pass_index=state.eval_retry_count,
6853 source=_FROM_STEP,
6854 ),
6855 "context": {f"{node_id}_output": op_result},
6856 "results": {node_id: op_result},
6857 "errors": [f"{node_id}: {p}" for p in input_problems],
6858 **_state_write(op_result),
6859 }
6860 except Exception as exc:
6861 logger.exception(
6862 "[graph] ✘ operation node=%s error=%s", node_id, exc
6863 )
6864 return {
6865 "step_count": step,
6866 "messages": [
6867 AIMessage(content=f"{node_id} failed.", name=node_id)
6868 ],
6869 "errors": [f"{node_id}: {model_errors.describe(exc)}"],
6870 "status": "error",
6871 }
6873 # ── Task content ──────────────────────────────────────────────
6874 # A prompt_template binding takes precedence: the node author has
6875 # declared exactly what this node should receive, rendered from
6876 # the user-visible state variables.
6877 # Otherwise — start node: original task only; subsequent nodes:
6878 # original task + ALL completed predecessor outputs so convergent
6879 # graphs work correctly.
6880 if prompt_template:
6881 from app.agents.operations import render_state_template
6883 task_content = render_state_template(prompt_template, state_variables)
6884 logger.info(
6885 "[graph] ▶ skill node=%s agent=%s tools=%s step=%d "
6886 "(templated task)",
6887 node_id,
6888 agent_type,
6889 tool_names or "none",
6890 step,
6891 )
6892 elif bound_inputs:
6893 # Typed inputs are the node author's declared contract: the
6894 # task is the original request plus exactly those values —
6895 # not every upstream output (which the aggregate path sends).
6896 task_content = (
6897 f"Task:\n{state.input}\n\n"
6898 "Inputs (bound from the skill state):\n"
6899 f"```json\n{safe_json.dumps(bound_inputs, ensure_ascii=False, indent=2)}\n```"
6900 )
6901 logger.info(
6902 "[graph] ▶ skill node=%s agent=%s tools=%s step=%d "
6903 "(typed inputs: %s)",
6904 node_id,
6905 agent_type,
6906 tool_names or "none",
6907 step,
6908 list(bound_inputs.keys()),
6909 )
6910 elif state.results:
6911 task_content = _aggregate_prior_results(state)
6912 logger.info(
6913 "[graph] ▶ skill node=%s agent=%s tools=%s step=%d "
6914 "prior_nodes=%s",
6915 node_id,
6916 agent_type,
6917 tool_names or "none",
6918 step,
6919 list(state.results.keys()),
6920 )
6921 else:
6922 task_content = state.input or attachment_util.unworded_task(
6923 state.attachments
6924 )
6925 logger.info(
6926 "[graph] ▶ skill node=%s agent=%s tools=%s step=%d (start)",
6927 node_id,
6928 agent_type,
6929 tool_names or "none",
6930 step,
6931 )
6933 # ── Prior message context ─────────────────────────────────────
6934 # The conversation so far, and only that: the model reads
6935 # [system, …earlier turns, this task]. Earlier nodes' outputs are
6936 # in task_content, evidence is in <knowledge> in the request
6937 # context below, and nothing
6938 # a system node wrote (status, errors) is replayed as a turn.
6939 prior_messages, history_notes = _history_messages(state)
6940 # The run's cost profile may cap the history in tokens too.
6941 agent.history_token_cap = effort_registry.of_state(state).history_token_cap
6943 # ── Context injection ─────────────────────────────────────────
6944 # Two well-formed XML documents, split by how often they change:
6945 #
6946 # * <agent_context> — the agent's name and the response standards —
6947 # joins the system prompt, which is then the same on every call
6948 # of this agent, so the provider can serve it (and the tool
6949 # definitions before it) from cache (``app.services.prompt_cache``).
6950 # * <request_context> — the date, plan, evidence, tool ledger,
6951 # state, inputs, notes and memory — opens the task message, after
6952 # the history. Retrieved text is data, not instructions, and no
6953 # longer reaches the model with the system role's authority.
6954 #
6955 # Ordering within <request_context> follows Anthropic's pattern:
6956 # plan first (instructions about this node's specific goal) →
6957 # knowledge (primary data source) →
6958 # memory (supplementary, lower-priority context).
6959 #
6960 # Retrieval content is wrapped in a CDATA section because it originates
6961 # from tool calls and KB documents which may contain raw HTML, code, or
6962 # angle-bracket characters that would corrupt the XML document otherwise.
6963 #
6964 # Memory items are XML-escaped (html.escape) since they are LLM-generated
6965 # prose and unlikely to be long enough to warrant CDATA.
6966 #
6967 # priority="primary" / priority="supplementary" attributes signal relative
6968 # importance, mitigating lost-in-the-middle degradation (Liu et al. 2023).
6969 import html as _html
6971 _now = prompts.today()
6973 plan_block = _PLAN_INJECTION_CHAIN.invoke(
6974 {
6975 "node_id": node_id,
6976 "task": state.input,
6977 "execution_plan": state.execution_plan,
6978 }
6979 )
6981 ctx_parts: list[str] = ["<agent_context>"]
6982 req_parts: list[str] = ["<request_context>"]
6984 # Agent identity — always first so the model grounds its persona
6985 # before reading task context (persona primacy, Anthropic guide).
6986 if state.agent_name:
6987 ctx_parts.append(
6988 f" <agent_name>{_html.escape(state.agent_name)}</agent_name>"
6989 )
6990 # The persona only where this node's own prompt lacks it: a plain
6991 # agent's node already carries the agent's prompt in full.
6992 if state.agent_system_prompt and (
6993 state.agent_system_prompt.strip() not in (agent.system_prompt or "")
6994 ):
6995 ctx_parts.append(
6996 " <agent_persona>"
6997 f"{_html.escape(state.agent_system_prompt)}"
6998 "</agent_persona>"
6999 )
7001 # Date with an explicit temporal-reasoning directive. The directive is
7002 # repeated here (it is also in the system prompt via build_metadata_context)
7003 # because the request context sits beside the task, and the recency
7004 # position reinforces the instruction (Liu et al. 2023, "Lost in the Middle").
7005 req_parts.append(
7006 f' <current_date use_for="temporal_reasoning">{_now}</current_date>'
7007 )
7008 # The documents the person attached, each with its [S#] — the
7009 # material the request is about comes before the rest of the
7010 # request's context (``attachments.render_block``).
7011 req_parts.extend(
7012 attachment_util.render_block(
7013 attachment_util.plan(state.attachments, _context_window(agent.llm))
7014 )
7015 )
7016 # The web sources the workspace's Tools rules set for this
7017 # request — per request, so here rather than in the cached system
7018 # message. The web tools enforce them; this says why a source is
7019 # missing and which to cite first.
7020 req_parts.extend(
7021 web_policy.request_context_lines(platform=platform_sources.current())
7022 )
7023 # A request for current information: what this agent remembers
7024 # of earlier conversations is no substitute for looking it up.
7025 if state.context.get(LIVE_DATA_KEY):
7026 req_parts.append(
7027 " <current_information>"
7028 + _live_data_note([t.name for t in agent.tools or []])
7029 + "</current_information>"
7030 )
7032 if plan_block:
7033 # Indent each line of the plan block by 2 spaces to nest cleanly
7034 # inside <agent_context>.
7035 req_parts.extend(" " + line for line in plan_block.splitlines())
7037 # The method to take comes before the evidence it is applied to.
7038 req_parts.extend(
7039 _frameworks_block(state.frameworks_context, _FRAMEWORKS_NOTE)
7040 )
7041 if state.retrieval_context:
7042 # CDATA protects arbitrary tool-returned content (web pages, code,
7043 # KB documents) from being parsed as XML by the model.
7044 note = (
7045 _UNJUDGED_KNOWLEDGE_NOTE
7046 if state.retrieval_report.get("judge_failure")
7047 else _KNOWLEDGE_NOTE
7048 )
7049 req_parts.append(f' <knowledge priority="primary" note="{note}">')
7050 req_parts.append(" <![CDATA[")
7051 req_parts.append(attachment_util.cdata(state.retrieval_context))
7052 req_parts.append(" ]]>")
7053 req_parts.append(" </knowledge>")
7054 elif state.context.get(KNOWLEDGE_NOT_RELEVANT_KEY):
7055 req_parts.append(
7056 " <knowledge_search>Your knowledge bases were searched for "
7057 "this request and hold nothing that bears on it. Answer "
7058 "without them, do not search them again for it, and cite "
7059 "none of them.</knowledge_search>"
7060 )
7061 named_empty = _named_empty(state)
7062 if named_empty:
7063 req_parts.append(
7064 " <knowledge_search>"
7065 + _html.escape(" and ".join(named_empty), quote=False)
7066 + " has nothing indexed yet, so it could not be searched. "
7067 "Answer from what you know, and say the answer is not "
7068 "from it.</knowledge_search>"
7069 )
7071 # Ledger of tool calls already made by earlier stages. Downstream
7072 # agents cannot see prior ToolMessages (stripped from context), so
7073 # without this digest their only way to recover a prior result is
7074 # to repeat the call — the primary source of duplicate tool calls.
7075 # A reviser re-checks the figures its answer stated: the blocks
7076 # holding them come first (``_draft_figures``).
7077 ledger = _tool_call_ledger(
7078 state.messages,
7079 keep=(
7080 _draft_figures(_result_text(state.results.get(node_id)))
7081 if state.eval_retry_count and state.results.get(node_id)
7082 else frozenset()
7083 ),
7084 )
7085 if ledger:
7086 req_parts.append(
7087 ' <prior_tool_calls note="Results already obtained by earlier '
7088 "pipeline stages. Reuse these values instead of re-calling a tool "
7089 "with the same arguments; only re-call when the digest below lacks "
7090 'what you need.">'
7091 )
7092 req_parts.append(" <![CDATA[")
7093 req_parts.append(attachment_util.cdata(ledger))
7094 req_parts.append(" ]]>")
7095 req_parts.append(" </prior_tool_calls>")
7097 # Selected skill-state variables (input_keys binding). Surfaced
7098 # even without a prompt_template so an agent node can read state
7099 # written by upstream tool/transform/agent nodes.
7100 if input_keys:
7101 bound = {
7102 k: state_variables[k] for k in input_keys if k in state_variables
7103 }
7104 if bound:
7105 req_parts.append(' <state_vars priority="primary">')
7106 for k, v in bound.items():
7107 text = v if isinstance(v, str) else str(v)
7108 req_parts.append(f' <var name="{_html.escape(k)}">')
7109 req_parts.append(" <![CDATA[")
7110 req_parts.append(text.replace("]]>", "]]]]><![CDATA[>"))
7111 req_parts.append(" ]]>")
7112 req_parts.append(" </var>")
7113 req_parts.append(" </state_vars>")
7115 # Typed inputs (schema v3). Always surfaced when bound — even
7116 # with a prompt_template — so the model can see the declared
7117 # contract alongside any narrative instructions.
7118 if bound_inputs and prompt_template:
7119 req_parts.append(' <inputs priority="primary">')
7120 req_parts.append(" <![CDATA[")
7121 req_parts.append(
7122 safe_json.dumps(bound_inputs, ensure_ascii=False, indent=2).replace(
7123 "]]>", "]]]]><![CDATA[>"
7124 )
7125 )
7126 req_parts.append(" ]]>")
7127 req_parts.append(" </inputs>")
7128 if input_problems:
7129 req_parts.append(" <input_warnings>")
7130 for p in input_problems:
7131 req_parts.append(f" <warning>{_html.escape(p)}</warning>")
7132 req_parts.append(" </input_warnings>")
7134 notes_block = _conversation_notes_block(history_notes)
7135 if notes_block:
7136 req_parts.extend(" " + line for line in notes_block.splitlines())
7138 # Recalled memory: tagged by kind and dated, with how to use it
7139 # (``app/memory/render.py``).
7140 req_parts.extend(memory_render.block(state.memories))
7142 # Reasoning standards — last in the request context (recency
7143 # position), so they are the final instructions the model reads
7144 # before the task. Reasoning rules address the three LLM failure modes identified in
7145 # benchmark testing: circular assumption, inconsistent derivation,
7146 # and incomplete solution sets — so they go only where a
7147 # derivation is asked for (``_needs_reasoning_standards``).
7148 reasoning_standards = (
7149 [
7150 " <reasoning_standards>",
7151 " <rule id='no_assumption'>Derive — never assume the form of what "
7152 + "is to be proved. If a proof requires f(x) = ax²+bx+c, derive that "
7153 + "form from the given conditions; do not take it as a starting point.</rule>",
7154 " <rule id='consistency'>Carry every approximation and assumption "
7155 + "consistently throughout. If you introduce a substitution or simplification "
7156 + "in step N, it must hold in step N+1. Never silently switch methods or "
7157 + "abandon an earlier approximation without explicitly justifying why.</rule>",
7158 " <rule id='completeness'>For problems asking 'find all X' or 'find "
7159 + "all solutions/functions/strategies', prove both existence and completeness "
7160 + "— show your answer works AND that no other answers exist.</rule>",
7161 " <rule id='known_results'>When applying a known theorem, protocol, or "
7162 + "strategy, verify that its invariants hold for this problem's exact "
7163 + "constraints before applying it. A misremembered detail can invert the "
7164 + "entire logic.</rule>",
7165 " <rule id='self_check'>Before presenting your final answer, re-read "
7166 + "your derivation as a sceptic: does each claim follow strictly from what "
7167 + "precedes it? If not, revise until it does.</rule>",
7168 " </reasoning_standards>",
7169 ]
7170 if _needs_reasoning_standards(state)
7171 else []
7172 )
7173 req_parts.extend(reasoning_standards)
7175 # Response standards — Markdown structure and inline-citation rules
7176 # shared with __synthesis__ and __evaluator__ (single source of
7177 # truth: prompts.RESPONSE_FORMATTING_STANDARDS). Facts from the
7178 # <knowledge> block above carry their passages' [S#] ids, web
7179 # pages and documents [n] markers, each resolved in a Sources
7180 # section; fabricated citations are flagged by the evaluator.
7181 ctx_parts.append(" <response_standards>")
7182 ctx_parts.extend(
7183 " " + line
7184 for line in prompts.RESPONSE_FORMATTING_STANDARDS.splitlines()
7185 )
7186 ctx_parts.append(" </response_standards>")
7188 ctx_parts.append("</agent_context>")
7189 extra_context = "\n".join(ctx_parts)
7190 # The format this request asks the answer in, last: the final
7191 # thing the model reads before its task.
7192 output_format = (state.context or {}).get(OUTPUT_FORMAT_KEY)
7193 if output_format:
7194 req_parts.append(" <output_format>")
7195 req_parts.append(" <![CDATA[")
7196 req_parts.append(str(output_format).replace("]]>", "]]]]><![CDATA[>"))
7197 req_parts.append(" ]]>")
7198 req_parts.append(" </output_format>")
7199 req_parts.append("</request_context>")
7200 request_context = "\n".join(req_parts)
7202 on_tool_call = self._tool_call_recorder(node_id, state)
7204 # ── Plan-driven tool injection ────────────────────────────────
7205 # The __planning__ node may recommend additional builtin tools for
7206 # this specific node via tool_guidance. Resolve them fresh here
7207 # (each resolve_tool call creates a new per-session call counter)
7208 # and pass as extra_tools — they merge with the agent's own tools,
7209 # with extra_tools winning on name collision.
7210 plan_tool_names: list[str] = state.execution_plan.get(
7211 "tool_guidance", {}
7212 ).get(node_id, [])
7213 plan_tools: list[Any] = []
7214 if plan_tool_names:
7215 from app.tools.registry import BUILTIN_TOOLS as _BT
7216 from app.tools.registry import resolve_tool as _rt
7217 from app.tools.registry import run_tool_config
7219 # Use conservative web_search config for plan-injected tools:
7220 # 5 results, 3 calls — enough to answer without runaway searches.
7221 _web_cfg = state.context.get(
7222 "web_search_config",
7223 {
7224 "max_results": 5,
7225 "max_calls": 3,
7226 },
7227 )
7228 # KB retrieval tools are redundant when __internal_retrieval__ has
7229 # already populated retrieval_context — skip them to avoid duplicate queries.
7230 _KB_TOOLS = frozenset({"query_knowledge_base", "query_knowledge_graph"})
7231 _skip_kb = bool(state.retrieval_context)
7232 for _tn in plan_tool_names:
7233 if _tn in _BT:
7234 if _skip_kb and _tn in _KB_TOOLS:
7235 logger.debug(
7236 "[graph] skill node=%s skipping KB tool %r "
7237 "(retrieval_context already populated)",
7238 node_id,
7239 _tn,
7240 )
7241 continue
7242 cfg = (
7243 _web_cfg
7244 if _tn == "web_search"
7245 else run_tool_config(_tn, _web_cfg)
7246 )
7247 try:
7248 plan_tools.append(_rt(_tn, cfg))
7249 except Exception:
7250 pass
7252 # ── On-demand knowledge tools ─────────────────────────────────
7253 # Skill nodes receive the retrieval node's evidence as read-only
7254 # context, but they can still hit a detail it lacks. Give them the
7255 # knowledge tools (search_knowledge / read_document / explore_graph) to fetch
7256 # exactly that on demand (Self-RAG, Asai et al. 2023) instead of
7257 # guessing — with an explicit instruction not to re-run retrieval.
7258 kb_tools, kb_tool_context = await _kb_tools_for_skill_node(state, node_id)
7259 if kb_tool_context:
7260 extra_context = f"{extra_context}\n\n{kb_tool_context}"
7261 if node is not None and node.ask_user and self._may_ask(state):
7262 from app.tools.registry import resolve_tool as _resolve
7264 if not any(
7265 getattr(t, "name", "") == clarify.ASK_USER for t in plan_tools
7266 ):
7267 plan_tools.append(_resolve(clarify.ASK_USER, {}))
7268 extra_context = (
7269 f"{extra_context}\n\nIf the task leaves something you need "
7270 "undecided, call ask_user with specific questions before "
7271 "doing any other work — do not guess."
7272 )
7273 if reviewer_feedback:
7274 request_context = (
7275 f"{request_context}\n\nA reviewer approved this step with "
7276 f"feedback — follow it:\n{reviewer_feedback}"
7277 )
7278 all_extra_tools = [
7279 *plan_tools,
7280 *kb_tools,
7281 *_attachment_tools(state, agent.llm),
7282 ]
7283 # An Economy profile's lighter model, when it answers this one
7284 # (``_simple_answer_llm``); None, and the agent's own does.
7285 answer_llm = self._simple_answer_llm(
7286 state,
7287 agent,
7288 prior_messages,
7289 system_text=f"{agent.system_prompt or ''}\n\n{extra_context}",
7290 task_text=f"{request_context}\n\n{task_content}",
7291 tools=[*agent.tools, *all_extra_tools],
7292 )
7294 # Once a turn and never on a revision; where it may not ask, the
7295 # agent is not offered ``ask_user`` (``clarify.may_ask``).
7296 may_ask = self._may_ask(state)
7298 try:
7299 with agent.answering_with(answer_llm), clarify.asking_allowed(may_ask):
7300 result, new_messages = await agent.process_with_history(
7301 task_content,
7302 prior_messages,
7303 extra_tools=all_extra_tools or None,
7304 extra_system_context=extra_context,
7305 on_tool_call=on_tool_call,
7306 config=config,
7307 request_context=request_context,
7308 # JSON asked for may look like a tool's arguments.
7309 answer_format_requested=bool(output_format),
7310 )
7312 content = _result_text(result)
7314 logger.info(
7315 "[graph] ✔ skill node=%s new_messages=%d output_chars=%d",
7316 node_id,
7317 len(new_messages),
7318 len(content),
7319 )
7321 # Delta-only updates — the reducers on context/results merge them.
7322 answered = (
7323 {ANSWERED_BY_KEY: _answered_by(answer_llm, "simple")}
7324 if answer_llm is not None
7325 else {}
7326 )
7327 return {
7328 "step_count": step,
7329 "messages": new_messages,
7330 "context": {
7331 f"{node_id}_output": result,
7332 **_history_figure(agent),
7333 **answered,
7334 },
7335 "results": {node_id: result},
7336 # Capture render fences from this node's ToolMessages so
7337 # they survive downstream rewrites (synthesis/evaluator).
7338 "artifacts": _visual_fences(_extract_artifact_fences(new_messages)),
7339 "documents": _document_entries(
7340 _extract_artifact_fences(new_messages),
7341 pass_index=state.eval_retry_count,
7342 source=_FROM_MODEL,
7343 ),
7344 "errors": [f"{node_id}: {p}" for p in input_problems],
7345 **_state_write(result),
7346 }
7348 except clarify.ClarificationRequested as asked:
7349 # The agent asked the person something. The step ends here
7350 # and ``__clarify__`` asks it; what the step did so far stays
7351 # in the trace, where the step that resumes reads its calls.
7352 logger.info(
7353 "[graph] ? skill node=%s asked the person %d question(s)",
7354 node_id,
7355 len(asked.payload.get("questions") or []),
7356 )
7357 fences = _extract_artifact_fences(asked.messages)
7358 return {
7359 "step_count": step,
7360 "messages": asked.messages,
7361 "pending_clarification": asked.payload,
7362 "artifacts": _visual_fences(fences),
7363 "documents": _document_entries(
7364 fences, pass_index=state.eval_retry_count, source=_FROM_MODEL
7365 ),
7366 }
7368 except GraphBubbleUp:
7369 # A pause (or another of LangGraph's own signals) is not a
7370 # failure of this step: it was swallowed here once, and no
7371 # mid-task question ever reached the person.
7372 raise
7374 except Exception as exc:
7375 model_errors.raise_if_fatal(exc)
7376 logger.exception("[graph] ✘ skill node=%s error=%s", node_id, exc)
7377 error_msg = AIMessage(content=f"{node_id} failed.", name=node_id)
7378 return {
7379 "step_count": step,
7380 "messages": [error_msg],
7381 "errors": [f"{node_id}: {model_errors.describe(exc)}"],
7382 "status": "error",
7383 }
7385 return node_fn
7387 def _create_knowledge_plan_node_fn(
7388 self,
7389 system_llm: BaseLanguageModel | None,
7390 planning_llm: BaseLanguageModel | None = None,
7391 ) -> Callable[[GraphState], dict[str, Any]]:
7392 """
7393 Create the ``__knowledge_plan__`` node function: what a turn's
7394 knowledge search looks for, decided once for every lane.
7396 It reads the turn's mix (``knowledge.mix``) — which kinds of
7397 knowledge run, in what role — and plans the search over the
7398 knowledge bases the mix searches: the query set, the literal terms
7399 and the documents the request names (``RetrievalPipeline.plan``).
7400 ``_knowledge_plan_router`` then starts a lane per kind, beside the
7401 web and the tools.
7403 The search query is ``state.retrieval_query`` (the gate's
7404 history-resolved rewrite) so follow-up turns retrieve on the full
7405 intent, not on "and section 3?".
7407 ``RetrievalConfig.mode`` selects the strategy:
7408 pipeline — lanes only.
7409 agentic — no lanes: the join runs the LLM tool loop over per-KB
7410 tools.
7411 hybrid — lanes first; the join runs an agentic gap-filling pass
7412 only when the evidence falls short (``agentic_when_thin``,
7413 ``_bundle_sufficient``). (default)
7415 Corrective re-retrieval: when the evaluator sends execution back here
7416 with content gaps (``_knowledge_can_fill_gaps``), only those gaps are
7417 searched, by the evidence lanes, leaving out the chunks the evidence
7418 already cites; the join appends the result as a delta section with
7419 continuing ``[S#]`` ids (CRAG, Yan et al. 2024).
7421 The query planner runs on the planning model with its own output cap
7422 (``_capped_llm``).
7423 """
7424 step_llm = planning_llm or system_llm
7425 planner_llm = _capped_llm(step_llm, _QUERY_PLANNER_MAX_TOKENS)
7427 async def knowledge_plan_node_fn(
7428 state: GraphState, config: RunnableConfig | None = None
7429 ) -> dict[str, Any]:
7430 from app.knowledge.retrieval import RetrievalPipeline
7432 step = state.step_count + 1
7433 mix = _turn_mix(state)
7434 knowledge_bases = knowledge_mix.searched(state.knowledge_bases, mix)
7435 retrieval_cfg = _retrieval_config(state)
7436 query = (state.retrieval_query or state.input).strip() or state.input
7437 # A query, not a document: every planning, judging and reranking
7438 # call carries it, and one carried a whole report.
7439 query = query[:_MAX_RETRIEVAL_QUERY_CHARS]
7440 attached = attachment_util.names(state.attachments)
7441 attached_mentions = _attachment_mentions(state)
7442 on = knowledge_categories_registry.today().isoformat()
7444 def planned(mode: str, **rest: Any) -> dict[str, Any]:
7445 # The mix rides along for the trace (ids and fixed reasons).
7446 return {
7447 "step_count": step,
7448 "knowledge_plan": {
7449 "mode": mode,
7450 "query": query,
7451 "on": on,
7452 "mix": mix.wire(),
7453 }
7454 | rest,
7455 }
7457 if state.knowledge_bases and not knowledge_bases:
7458 # Nothing it holds applies — no search, and no "searched"
7459 # mark, so no corrective pass goes back to it either.
7460 logger.info(
7461 "[graph] node=%s step=%d none of %d knowledge base(s) "
7462 "applies to this request",
7463 KNOWLEDGE_PLAN_NODE_ID,
7464 step,
7465 len(state.knowledge_bases),
7466 )
7467 return planned("none", lanes=[])
7469 # ── Corrective re-retrieval after an evaluator failure ────────
7470 # Only over knowledge this turn searched (``KNOWLEDGE_SEARCHED_KEY``):
7471 # ``retrieval_context`` alone also holds the web and tool
7472 # retrieval nodes' sections. A gap is a missing fact, so only the
7473 # evidence lanes search for it.
7474 eval_raw = state.results.get(EVALUATOR_NODE_ID)
7475 gaps: list[str] = list(getattr(eval_raw, "gaps", None) or [])
7476 evidence = _evidence_lanes(mix)
7477 if (
7478 gaps
7479 and state.context.get(KNOWLEDGE_SEARCHED_KEY)
7480 and state.retrieval_context
7481 and evidence
7482 ):
7483 gap_query = f"{query}\nMissing details to find: " + "; ".join(gaps[:5])
7484 held = {kb_id for lane in evidence for kb_id in lane.kb_ids}
7485 gap_kbs = [
7486 kb for kb in knowledge_bases if str(kb.get("id", "")) in held
7487 ]
7488 logger.info(
7489 "[graph] ▶ node=%s step=%d corrective retrieval for %d gap(s)",
7490 KNOWLEDGE_PLAN_NODE_ID,
7491 step,
7492 len(gaps),
7493 )
7494 try:
7495 pipeline = RetrievalPipeline.from_config(
7496 retrieval_cfg.model_copy(update={"mode": "pipeline"}),
7497 planner_llm,
7498 )
7499 plan = await pipeline.plan(
7500 gap_query,
7501 gap_kbs,
7502 state.kb_metadata,
7503 attached=attached,
7504 attached_mentions=attached_mentions,
7505 lanes=_lane_query_counts(evidence),
7506 )
7507 except Exception as exc:
7508 logger.exception("[graph] corrective retrieval failed: %s", exc)
7509 return planned(
7510 "gap",
7511 query=gap_query,
7512 lanes=[],
7513 gaps=gaps[:5],
7514 error=f"{KNOWLEDGE_PLAN_NODE_ID}: {model_errors.describe(exc)}",
7515 )
7516 return planned(
7517 "gap",
7518 query=gap_query,
7519 plan=plan.dump(),
7520 lanes=[lane.category for lane in evidence],
7521 gaps=gaps[:5],
7522 )
7524 mode = retrieval_cfg.mode if knowledge_bases else "agentic"
7525 logger.info(
7526 "[graph] ▶ node=%s step=%d knowledge_bases=%d mode=%s "
7527 "lanes=%s query_chars=%d",
7528 KNOWLEDGE_PLAN_NODE_ID,
7529 step,
7530 len(knowledge_bases),
7531 mode,
7532 [lane.category for lane in mix.lanes],
7533 len(query),
7534 )
7535 if mode not in ("pipeline", "hybrid"):
7536 # The agentic pass searches with the knowledge tools, in the
7537 # join: nothing to plan, no lane to run.
7538 return planned(mode, lanes=[])
7539 try:
7540 pipeline = RetrievalPipeline.from_config(retrieval_cfg, planner_llm)
7541 plan = await pipeline.plan(
7542 query,
7543 knowledge_bases,
7544 state.kb_metadata,
7545 attached=attached,
7546 attached_mentions=attached_mentions,
7547 # Two or more lanes: each gets its own queries.
7548 lanes=_lane_query_counts(mix.lanes),
7549 )
7550 except Exception as exc:
7551 logger.exception(
7552 "[graph] retrieval planning failed — falling back: %s", exc
7553 )
7554 return planned(
7555 mode,
7556 lanes=[],
7557 error=f"{KNOWLEDGE_PLAN_NODE_ID}: {model_errors.describe(exc)}",
7558 )
7559 return planned(
7560 mode,
7561 plan=plan.dump(),
7562 lanes=[lane.category for lane in mix.lanes if lane.kb_ids],
7563 )
7565 return knowledge_plan_node_fn
7567 def _create_lane_node_fn(
7568 self,
7569 category: KnowledgeCategory,
7570 system_llm: BaseLanguageModel | None,
7571 planning_llm: BaseLanguageModel | None = None,
7572 ) -> Callable[[GraphState], dict[str, Any]]:
7573 """
7574 Create one lane's node function (``LANE_NODE_IDS[category]``): the
7575 turn's search of one kind of knowledge (``RetrievalPipeline.search``)
7576 — hybrid dense + lexical search and graph traversal over the lane's
7577 own knowledge bases, judged by its own relevance judge, read for its
7578 kind, widened to the neighbours — beside the other lanes.
7580 Sized by its role in the turn's mix (``knowledge.mix.Lane``): its
7581 candidates per search, the passages its judge rates (which also cap
7582 each knowledge base's hits) and how many of the plan's queries it
7583 runs. A lane that is the agent's only kind runs at the
7584 configuration's own values, as one search always did.
7586 It writes its result to its own field (``LANE_FIELDS``) and nothing
7587 else; the join packs it. A search that fails outright is recorded on
7588 the lane (``LaneResult.failure``), and the other lanes go on. The
7589 judge runs on the planning model with its own output cap.
7590 """
7591 node_id = LANE_NODE_IDS[category]
7592 field_name = LANE_FIELDS[category]
7593 step_llm = planning_llm or system_llm
7594 reranker_llm = _capped_llm(step_llm, _RERANKER_MAX_TOKENS)
7596 async def lane_node_fn(
7597 state: GraphState, config: RunnableConfig | None = None
7598 ) -> dict[str, Any]:
7599 from dataclasses import replace
7601 from app.knowledge.retrieval import (
7602 KnowledgePlan,
7603 LaneResult,
7604 RetrievalPipeline,
7605 cited_spans,
7606 )
7608 step = state.step_count + 1
7609 planned = state.knowledge_plan or {}
7610 plan = KnowledgePlan.load(planned.get("plan"))
7611 lane = _turn_mix(state).lane(category)
7612 if plan is None or lane is None:
7613 return {"step_count": step, field_name: {}}
7614 kbs = [
7615 kb
7616 for kb in state.knowledge_bases
7617 if str(kb.get("id", "")) in lane.kb_ids
7618 ]
7619 retrieval_cfg = _retrieval_config(state)
7620 # The lane's size, by its role (the mix's own values for an
7621 # agent's only kind: the configuration's).
7622 lane_cfg = retrieval_cfg.model_copy(
7623 update={
7624 "candidate_k": lane.candidate_k or retrieval_cfg.candidate_k,
7625 "rerank_candidates": lane.judge_slots
7626 or retrieval_cfg.rerank_candidates,
7627 }
7628 )
7629 # Its own queries when the lanes were planned apart; else its
7630 # share of the one set.
7631 lane_plan = replace(
7632 plan,
7633 queries=plan.lane_queries.get(category.value)
7634 or plan.queries[: lane.max_queries or len(plan.queries)],
7635 )
7636 try:
7637 on = date.fromisoformat(str(planned.get("on")))
7638 except ValueError:
7639 on = None
7640 gap = planned.get("mode") == "gap"
7641 logger.info(
7642 "[graph] ▶ node=%s step=%d role=%s knowledge_bases=%d "
7643 "queries=%d judge_slots=%d%s",
7644 node_id,
7645 step,
7646 lane.role,
7647 len(kbs),
7648 len(lane_plan.queries),
7649 lane_cfg.rerank_candidates,
7650 " corrective" if gap else "",
7651 )
7652 try:
7653 pipeline = RetrievalPipeline.from_config(
7654 retrieval_cfg, None, reranker_llm=reranker_llm
7655 )
7656 result = await pipeline.search(
7657 lane_plan,
7658 kbs,
7659 # What the evidence already holds is not packed again
7660 # under a new id: the agent was handed it, and the
7661 # evaluator found it wanting.
7662 exclude=cited_spans(state.retrieval_citations) if gap else (),
7663 turn=knowledge_categories_registry.RetrievalTurn.read(
7664 state.context.get(KNOWLEDGE_TURN_KEY)
7665 ),
7666 on=on,
7667 cfg=lane_cfg,
7668 )
7669 except Exception as exc: # noqa: BLE001 — the other lanes go on
7670 logger.exception("[graph] ✘ node=%s error=%s", node_id, exc)
7671 result = LaneResult(
7672 kb_ids=list(lane.kb_ids), failure=model_errors.describe(exc)
7673 )
7674 result.category, result.role, result.share = (
7675 lane.category,
7676 lane.role,
7677 lane.share,
7678 )
7679 # The queries it ran ride along for the trace.
7680 return {
7681 "step_count": step,
7682 field_name: {**result.dump(), "queries": list(lane_plan.queries)},
7683 }
7685 return lane_node_fn
7687 def _create_retrieval_join_node_fn(
7688 self, system_llm: BaseLanguageModel | None
7689 ) -> Callable[[GraphState], dict[str, Any]]:
7690 """
7691 Create the ``__retrieval_join__`` node function: where every
7692 retrieval branch meets, once, before the answer.
7694 The knowledge lanes are packed into one evidence block within one
7695 budget (``RetrievalPipeline.pack``), cited in role order, and stored
7696 in ``state.retrieval_context`` with structured provenance in
7697 ``state.retrieval_citations``; the frameworks packed apart go to
7698 ``state.frameworks_context``. Then the web's section and the tools',
7699 in that order whatever order the branches finished in. Only the
7700 join writes what the answer reads, and it clears the staged branch
7701 fields.
7703 Over the packed evidence it runs what one retrieval step ran: the
7704 turn's marks (searched, dated, nothing relevant), its retrieval
7705 record, and in hybrid or agentic mode the agentic tool loop over the
7706 per-KB tools, which keeps the system model's budget.
7707 """
7709 async def retrieval_join_node_fn(
7710 state: GraphState, config: RunnableConfig | None = None
7711 ) -> dict[str, Any]:
7712 step = state.step_count + 1
7713 # The staged branches, cleared: what they found is handed on here.
7714 cleared: dict[str, Any] = {
7715 "knowledge_plan": {},
7716 **{name: {} for name in LANE_FIELDS.values()},
7717 "web_context": "",
7718 "tool_context": "",
7719 }
7720 knowledge: dict[str, Any] = (
7721 await self._join_knowledge(state, system_llm, config)
7722 if state.knowledge_plan
7723 else {}
7724 )
7725 context = _merge_retrieval_context(
7726 _merge_retrieval_context(
7727 knowledge.pop("retrieval_context", ""), state.web_context
7728 ),
7729 state.tool_context,
7730 )
7731 return {
7732 **knowledge,
7733 **cleared,
7734 "step_count": step,
7735 "retrieval_context": context,
7736 }
7738 return retrieval_join_node_fn
7740 async def _join_knowledge(
7741 self,
7742 state: GraphState,
7743 system_llm: BaseLanguageModel | None,
7744 config: RunnableConfig | None,
7745 ) -> dict[str, Any]:
7746 """What the join hands on of the knowledge: the lanes ``state``
7747 holds, packed, and everything one retrieval step wrote with them —
7748 ``retrieval_context`` (the knowledge's part alone), citations, the
7749 report, the frameworks, the turn's marks, its messages and errors."""
7750 from app.knowledge.retrieval import (
7751 KnowledgePlan,
7752 LaneResult,
7753 RetrievalPipeline,
7754 )
7756 planned = state.knowledge_plan
7757 turn = knowledge_categories_registry.RetrievalTurn.read(
7758 state.context.get(KNOWLEDGE_TURN_KEY)
7759 )
7760 mix = _turn_mix(state)
7761 knowledge_bases = knowledge_mix.searched(state.knowledge_bases, mix)
7762 kb_count = len(knowledge_bases)
7763 mode = str(planned.get("mode") or "")
7764 query = str(planned.get("query") or state.retrieval_query or state.input)
7765 retrieval_cfg = _retrieval_config(state)
7766 plan = KnowledgePlan.load(planned.get("plan"))
7767 lanes = [
7768 lane
7769 for lane in (
7770 LaneResult.load(getattr(state, LANE_FIELDS[category]))
7771 for category in KnowledgeCategory
7772 if category.value in (planned.get("lanes") or ())
7773 )
7774 if lane is not None
7775 ]
7776 try:
7777 on = date.fromisoformat(str(planned.get("on")))
7778 except ValueError:
7779 on = None
7781 if mode == "none":
7782 return {
7783 "messages": [
7784 AIMessage(
7785 content="No knowledge base applies to this request.",
7786 name=RETRIEVAL_JOIN_NODE_ID,
7787 )
7788 ],
7789 "retrieval_context": "",
7790 # The turn's retrieval record: none of it was searched.
7791 "context": {
7792 turn_report.KEY: turn_report.not_searched(
7793 state.knowledge_bases,
7794 turn,
7795 state.retrieval_query or state.input,
7796 mix=mix,
7797 )
7798 },
7799 }
7801 def lanes_failed() -> str:
7802 """Each lane's own failure, when every lane failed: the search
7803 itself failed, as one search failing did."""
7804 if not lanes or not all(lane.failure for lane in lanes):
7805 return ""
7806 return "; ".join(
7807 f"{LANE_NODE_IDS[KnowledgeCategory(lane.category)]}: {lane.failure}"
7808 for lane in lanes
7809 )
7811 # ── Corrective re-retrieval ──────────────────────────────────────
7812 if mode == "gap":
7813 gaps = [str(g) for g in planned.get("gaps") or []]
7814 failure = str(planned.get("error") or "") or lanes_failed()
7815 searched_kbs = [
7816 kb
7817 for kb in knowledge_bases
7818 if any(str(kb.get("id", "")) in lane.kb_ids for lane in lanes)
7819 ]
7820 bundle = None
7821 if not failure and plan is not None:
7822 try:
7823 bundle = RetrievalPipeline.from_config(
7824 retrieval_cfg.model_copy(update={"mode": "pipeline"})
7825 ).pack(
7826 plan,
7827 lanes,
7828 searched_kbs,
7829 citation_offset=len(state.retrieval_citations),
7830 on=on,
7831 )
7832 except Exception as exc:
7833 logger.exception("[graph] corrective retrieval failed: %s", exc)
7834 failure = f"{RETRIEVAL_JOIN_NODE_ID}: {model_errors.describe(exc)}"
7835 if bundle is None:
7836 return {
7837 "messages": [
7838 AIMessage(
7839 content="Corrective retrieval failed.",
7840 name=RETRIEVAL_JOIN_NODE_ID,
7841 )
7842 ],
7843 "errors": [failure or f"{RETRIEVAL_JOIN_NODE_ID}: nothing planned"],
7844 "retrieval_context": "",
7845 }
7846 gap_report = _retrieval_report(bundle)
7847 # What the quality check found missing and the knowledge did
7848 # not hold: the turn's retrieval record keeps it.
7849 gaps_recorded = (
7850 turn_report.with_gaps(state.context.get(turn_report.KEY), gaps)
7851 if bundle.is_empty
7852 else None
7853 )
7854 if bundle.is_empty:
7855 # What the knowledge bases lack, and no more: "state
7856 # plainly that these details are not available" had the
7857 # agent call unavailable what its own tools could find.
7858 section = (
7859 f"## Gap-fill evidence (retry {state.eval_retry_count})\n"
7860 "No additional knowledge base content was found for: "
7861 + "; ".join(gaps)
7862 + ". These details are not in the knowledge bases beyond "
7863 "the evidence already given; that says nothing about "
7864 "whether they can be found elsewhere."
7865 )
7866 citations: list[dict[str, Any]] = []
7867 else:
7868 section = (
7869 f"## Gap-fill evidence (retry {state.eval_retry_count})\n"
7870 + bundle.context_markdown
7871 )
7872 citations = bundle.citations
7873 return {
7874 "messages": [
7875 AIMessage(
7876 content=(
7877 f"Corrective retrieval: {len(bundle.passages)} passage(s), "
7878 f"{len(bundle.graph_facts)} graph fact(s) for "
7879 f"{len(gaps)} gap(s)."
7880 ),
7881 name=RETRIEVAL_JOIN_NODE_ID,
7882 )
7883 ],
7884 "retrieval_context": section,
7885 "retrieval_citations": citations,
7886 "retrieval_report": gap_report,
7887 **(
7888 {"context": {turn_report.KEY: gaps_recorded}}
7889 if gaps_recorded
7890 else {}
7891 ),
7892 }
7894 # ── The lanes, packed ─────────────────────────────────────────────
7895 bundle = None
7896 bundle_error = ""
7897 if kb_count and mode in ("pipeline", "hybrid"):
7898 bundle_error = str(planned.get("error") or "") or lanes_failed()
7899 if not bundle_error and plan is not None:
7900 try:
7901 bundle = RetrievalPipeline.from_config(retrieval_cfg).pack(
7902 plan, lanes, knowledge_bases, on=on
7903 )
7904 if bundle.errors:
7905 logger.warning(
7906 "[graph] retrieval pipeline partial errors: %s",
7907 bundle.errors,
7908 )
7909 except Exception as exc:
7910 logger.exception(
7911 "[graph] retrieval packing failed — falling back: %s", exc
7912 )
7913 bundle_error = (
7914 f"{RETRIEVAL_JOIN_NODE_ID}: {model_errors.describe(exc)}"
7915 )
7916 bundle = None
7918 # Every return below carries it once there is a bundle.
7919 report: dict[str, Any] = (
7920 {"retrieval_report": _retrieval_report(bundle)}
7921 if bundle is not None
7922 else {}
7923 )
7924 # And every return that hands on what the knowledge bases held
7925 # says so: the evaluator's gaps may then be searched for in them.
7926 # Dated evidence says so too: its answer is then not remembered.
7927 searched: dict[str, Any] = {
7928 "context": {
7929 KNOWLEDGE_SEARCHED_KEY: True,
7930 **(
7931 {DATED_KNOWLEDGE_KEY: True}
7932 if bundle is not None and bundle.dated_passages
7933 else {}
7934 ),
7935 }
7936 }
7937 # The frameworks packed apart, for the answering node's
7938 # ``<frameworks>``: nothing for knowledge that holds none.
7939 frameworks: dict[str, Any] = (
7940 {"frameworks_context": bundle.frameworks_markdown}
7941 if bundle is not None and bundle.frameworks_markdown
7942 else {}
7943 )
7944 have_bundle = bundle is not None and not bundle.is_empty
7945 # The search found passages and the relevance judge ruled out
7946 # every one: the knowledge does not cover this request. Searching
7947 # it again in the agentic pass finds the same things — it used to,
7948 # and the agent then cited them — so the turn goes on without it.
7949 nothing_relevant = (
7950 bundle is not None
7951 and bundle.is_empty
7952 and bundle.judged_out > 0
7953 and not bundle.errors
7954 )
7955 # What each source gave, for the turn's retrieval record.
7956 record: dict[str, Any] = (
7957 {
7958 turn_report.KEY: turn_report.from_bundle(
7959 bundle,
7960 state.knowledge_bases,
7961 knowledge_bases,
7962 turn,
7963 query,
7964 nothing_relevant=nothing_relevant,
7965 mix=mix,
7966 )
7967 }
7968 if bundle is not None
7969 else {}
7970 )
7971 searched["context"].update(record)
7972 if nothing_relevant and mode == "hybrid":
7973 logger.info(
7974 "[graph] node=%s the judge ruled out all %d passage(s) — "
7975 "the knowledge does not cover this request; no agentic pass",
7976 RETRIEVAL_JOIN_NODE_ID,
7977 bundle.judged_out,
7978 )
7979 mode = "pipeline"
7981 # Hybrid mode: the agentic pass exists to fill gaps. When the
7982 # pipeline found evidence and missed nothing it can name, there
7983 # is nothing to fill, so skip the (expensive) LLM tool loop.
7984 if (
7985 mode == "hybrid"
7986 and retrieval_cfg.agentic_when_thin
7987 and _bundle_sufficient(bundle)
7988 ):
7989 logger.info(
7990 "[graph] node=%s evidence sufficient (%d passages, %d facts) — "
7991 "skipping agentic pass",
7992 RETRIEVAL_JOIN_NODE_ID,
7993 len(bundle.passages),
7994 len(bundle.graph_facts),
7995 )
7996 mode = "pipeline"
7997 # Frameworks alone: the agentic pass searches evidence for gaps,
7998 # and there is none to search.
7999 if mode == "hybrid" and all(
8000 knowledge_categories_registry.behaviour(kb).separate
8001 for kb in knowledge_bases
8002 ):
8003 mode = "pipeline"
8005 def handed_on() -> dict[str, Any]:
8006 """What the lanes found, and nothing more."""
8007 if have_bundle:
8008 summary = (
8009 f"Retrieved {len(bundle.passages)} passage(s) and "
8010 f"{len(bundle.graph_facts)} graph fact(s) from {kb_count} "
8011 f"knowledge base(s) using {len(bundle.queries)} quer"
8012 f"{'y' if len(bundle.queries) == 1 else 'ies'}."
8013 )
8014 logger.info("[graph] ✔ node=%s %s", RETRIEVAL_JOIN_NODE_ID, summary)
8015 return {
8016 "messages": [
8017 AIMessage(content=summary, name=RETRIEVAL_JOIN_NODE_ID)
8018 ],
8019 "retrieval_context": bundle.context_markdown,
8020 "retrieval_citations": bundle.citations,
8021 **report,
8022 **searched,
8023 **frameworks,
8024 }
8025 return {
8026 "messages": [
8027 AIMessage(
8028 content="No relevant knowledge base content was found.",
8029 name=RETRIEVAL_JOIN_NODE_ID,
8030 )
8031 ],
8032 "errors": [bundle_error] if bundle_error else [],
8033 "retrieval_context": "",
8034 **report,
8035 # The answering node says so, so the agent neither cites
8036 # the knowledge nor searches it again with its tools.
8037 "context": {
8038 **record,
8039 **({KNOWLEDGE_NOT_RELEVANT_KEY: True} if nothing_relevant else {}),
8040 },
8041 }
8043 if mode == "pipeline":
8044 return handed_on()
8046 # ── The agentic tool loop (agentic mode, or hybrid gap-fill) ─────
8047 # Over the evidence only: a framework is applied, not searched for
8048 # gaps in.
8049 evidence_kbs = [
8050 kb
8051 for kb in knowledge_bases
8052 if not knowledge_categories_registry.behaviour(kb).separate
8053 ]
8054 kb_tools, kb_schema_context = await _build_kb_tools_and_context(evidence_kbs)
8055 if not kb_tools:
8056 # Nothing to search with. The pass used to summarise the task
8057 # alone, and the summary was handed on as the evidence.
8058 return handed_on()
8060 system_prompt = _RETRIEVAL_PROMPT_CHAIN.invoke(
8061 {
8062 "node_id": INTERNAL_RETRIEVAL_NODE_ID,
8063 "task": query,
8064 "execution_plan": state.execution_plan,
8065 }
8066 )
8068 # Bounded: it had the worker default's ten model rounds and a
8069 # prompt that said never to stop after one search.
8070 max_rounds = retrieval_cfg.agentic_max_iterations
8071 retrieval_agent = _SystemWorker(
8072 name=INTERNAL_RETRIEVAL_NODE_ID,
8073 llm=system_llm,
8074 system_prompt=system_prompt,
8075 max_iterations=max_rounds,
8076 )
8078 retrieval_focus = (
8079 state.execution_plan.get("retrieval_focus", "")
8080 if state.execution_plan
8081 else ""
8082 )
8083 evidence_seed = ""
8084 if have_bundle:
8085 evidence_seed = (
8086 "\n\n## Evidence already retrieved\n"
8087 "The passages and graph facts below were retrieved by the "
8088 "automated pipeline and WILL be provided to downstream agents "
8089 "verbatim. Do not repeat them. Use the tools ONLY to fill gaps: "
8090 "aspects of the task the evidence does not cover, exact figures "
8091 "that need verification, or entities whose relationships are "
8092 "missing. Refer to existing evidence by its [S#] id.\n\n"
8093 + bundle.context_markdown
8094 )
8096 focus_hint = (
8097 f"\nRetrieval focus from plan: {retrieval_focus}" if retrieval_focus else ""
8098 )
8099 has_graph = any(kb.get("source_type") == "graph" for kb in evidence_kbs)
8100 has_file = any(kb.get("source_type") != "graph" for kb in evidence_kbs)
8102 steps: list[str] = []
8103 if have_bundle:
8104 steps.append(
8105 "1. Review the evidence already retrieved and identify what "
8106 "the task still needs. If it is fully covered, return "
8107 "'No additional findings.' without calling any tool."
8108 )
8109 if has_file:
8110 n = len(steps) + 1
8111 steps += [
8112 f"{n}. With {tool_registry.SEARCH_KNOWLEDGE_TOOL}: issue "
8113 f"up to {max_rounds} targeted "
8114 f"quer{'y' if max_rounds == 1 else 'ies'}"
8115 + (
8116 ", only for the uncovered aspects."
8117 if have_bundle
8118 else " from different angles — rephrase the question, "
8119 "decompose into sub-topics, vary specificity."
8120 )
8121 + " Stop when the task is covered or a search adds "
8122 "nothing new.",
8123 f"{n + 1}. If the task names a document, or search results are "
8124 f"thin, use {tool_registry.READ_DOCUMENT_TOOL} with the document "
8125 "name (approximate names are resolved); use "
8126 f"{tool_registry.LIST_DOCUMENTS_TOOL} to discover names.",
8127 ]
8128 if has_graph:
8129 n = len(steps) + 1
8130 steps += [
8131 f"{n}. With {tool_registry.EXPLORE_GRAPH_TOOL}: call once per "
8132 "entity type label to "
8133 "enumerate all entities, then call with each relevant exact "
8134 "entity name to retrieve its relationships.",
8135 ]
8136 steps.append(
8137 f"{len(steps) + 1}. Stop: what the tools return is handed on as it "
8138 "is, so there is nothing to summarise."
8139 )
8141 task = f"Task:\n{query}{focus_hint}\n\n" + "\n".join(steps)
8143 try:
8144 result, new_messages = await retrieval_agent.process_with_history(
8145 task,
8146 [],
8147 extra_tools=kb_tools,
8148 # The schema is the agent's; the evidence is this request's.
8149 extra_system_context=kb_schema_context,
8150 on_tool_call=self._tool_call_recorder(RETRIEVAL_JOIN_NODE_ID, state),
8151 config=_unstreamed_config(config),
8152 request_context=evidence_seed.strip(),
8153 )
8154 # What its tools found is handed on; its own words never are.
8155 # Asked about the NCSC's news while the feed held nothing, its
8156 # summary ("no indexed documents… [S1, S2]") was the evidence,
8157 # with ids that named nothing, and the agent answered from it.
8158 findings = _pass_findings(new_messages)
8159 logger.info(
8160 "[graph] ✔ node=%s new_messages=%d kb_tools=%d seeded=%s "
8161 "found=%d chars note=%r",
8162 RETRIEVAL_JOIN_NODE_ID,
8163 len(new_messages),
8164 len(kb_tools),
8165 have_bundle,
8166 len(findings),
8167 str(result)[:200],
8168 )
8169 if not findings and not have_bundle:
8170 # Searched, and nothing found: as when the judge rules out
8171 # everything, the agent is told the knowledge holds nothing
8172 # on it, and neither cites it nor searches it again.
8173 return {
8174 "messages": new_messages,
8175 "retrieval_context": "",
8176 **report,
8177 "context": {**record, KNOWLEDGE_NOT_RELEVANT_KEY: True},
8178 **frameworks,
8179 }
8180 retrieval_context = "\n\n".join(
8181 part
8182 for part in (
8183 bundle.context_markdown if have_bundle else "",
8184 f"## Additional findings\n{findings}" if findings else "",
8185 )
8186 if part
8187 )
8188 return {
8189 "messages": new_messages,
8190 "retrieval_context": retrieval_context,
8191 "retrieval_citations": bundle.citations if have_bundle else [],
8192 **report,
8193 **searched,
8194 **frameworks,
8195 }
8196 except Exception as exc:
8197 model_errors.raise_if_fatal(exc)
8198 logger.exception("[graph] ✘ node=%s error=%s", RETRIEVAL_JOIN_NODE_ID, exc)
8199 return {
8200 "messages": [
8201 AIMessage(
8202 content="Internal retrieval failed.",
8203 name=RETRIEVAL_JOIN_NODE_ID,
8204 )
8205 ],
8206 "errors": [f"{RETRIEVAL_JOIN_NODE_ID}: {model_errors.describe(exc)}"],
8207 # Keep whatever the pipeline found even if the agentic pass died.
8208 "retrieval_context": bundle.context_markdown if have_bundle else "",
8209 "retrieval_citations": bundle.citations if have_bundle else [],
8210 **report,
8211 **(searched if have_bundle else {}),
8212 **frameworks,
8213 }
8215 def _create_external_retrieval_node_fn(
8216 self, system_llm: BaseLanguageModel | None
8217 ) -> Callable[[GraphState], dict[str, Any]]:
8218 """
8219 Create the external data retrieval node function.
8221 Searches external sources (web, live APIs) using ``web_search`` and
8222 ``url_fetch`` general tools. When ``retrieval_type == 'both'`` this
8223 node runs in PARALLEL with the knowledge lanes (Send fan-out from
8224 __knowledge_plan__). It stages its own "## External Sources" section
8225 in ``web_context``; the join hands it on after the knowledge.
8226 """
8228 async def external_retrieval_node_fn(
8229 state: GraphState, config: RunnableConfig | None = None
8230 ) -> dict[str, Any]:
8231 step = state.step_count + 1
8232 logger.info("[graph] ▶ node=%s step=%d", EXTERNAL_RETRIEVAL_NODE_ID, step)
8234 from app.tools.registry import general_tools as _general_tools
8236 web_cfg = state.context.get("web_search_config", {})
8237 ext_tools = [
8238 t
8239 for t in _general_tools({"web_search": web_cfg})
8240 if t.name in ("web_search", "url_fetch")
8241 ]
8243 # Date first: without it the model writes search queries (and
8244 # judges recency) against its training cutoff.
8245 system_prompt = (
8246 prompts.build_metadata_context()
8247 + "\n\n"
8248 + _EXTERNAL_RETRIEVAL_PROMPT_CHAIN.invoke(
8249 {
8250 "node_id": EXTERNAL_RETRIEVAL_NODE_ID,
8251 "task": state.input,
8252 "execution_plan": state.execution_plan,
8253 }
8254 )
8255 )
8257 ext_agent = _SystemWorker(
8258 name=EXTERNAL_RETRIEVAL_NODE_ID,
8259 llm=system_llm,
8260 system_prompt=system_prompt,
8261 )
8263 external_focus = (
8264 state.execution_plan.get("external_retrieval_focus", "")
8265 if state.execution_plan
8266 else ""
8267 )
8268 focus_hint = f"\nSearch focus: {external_focus}" if external_focus else ""
8269 existing = state.retrieval_context
8270 # Provide enough internal context for the external agent to avoid
8271 # duplicating topics already covered (RAG-Fusion, Ma et al., 2023).
8272 # In the parallel "both" fan-out this is empty (internal retrieval
8273 # has not merged yet); it is populated on evaluator retries or when
8274 # this node runs after another retrieval node.
8275 # If the internal context is short, pass it in full; otherwise pass
8276 # up to 1500 chars — enough to cover headings and key facts without
8277 # filling the agent's context window with retrieval prose.
8278 _CONTEXT_HINT_LIMIT = 1500
8279 if existing:
8280 _hint_body = (
8281 existing
8282 if len(existing) <= _CONTEXT_HINT_LIMIT
8283 else existing[:_CONTEXT_HINT_LIMIT] + "…"
8284 )
8285 context_hint = (
8286 f"\n\nInternal KB context already retrieved (search for what is MISSING or needs "
8287 f"external validation — do not duplicate topics already covered):\n{_hint_body}"
8288 )
8289 else:
8290 context_hint = ""
8291 standalone_hint = (
8292 f"\nStandalone form of the request: {state.retrieval_query}"
8293 if state.retrieval_query and state.retrieval_query != state.input
8294 else ""
8295 )
8296 task = (
8297 f"Task:\n{state.input}{standalone_hint}{focus_hint}{context_hint}"
8298 f"{_attached_hint(state)}\n\n"
8299 "Search for current, relevant information from external sources. "
8300 "Use web_search (search_type='news' and/or freshness for recent "
8301 "events) then url_fetch to read the most promising results in full. "
8302 "Cite sources (URL, title, publish date). Return a structured summary."
8303 )
8305 try:
8306 result, new_messages = await ext_agent.process_with_history(
8307 task,
8308 [],
8309 extra_tools=ext_tools,
8310 on_tool_call=self._tool_call_recorder(
8311 EXTERNAL_RETRIEVAL_NODE_ID, state
8312 ),
8313 config=_unstreamed_config(config),
8314 )
8315 ext_output = str(result)
8316 logger.info(
8317 "[graph] ✔ node=%s new_messages=%d chars=%d",
8318 EXTERNAL_RETRIEVAL_NODE_ID,
8319 len(new_messages),
8320 len(ext_output),
8321 )
8322 # Staged for the join, which hands it on after the knowledge
8323 # whichever branch finished first.
8324 return {
8325 "step_count": step,
8326 "messages": new_messages,
8327 "web_context": "## External Sources\n"
8328 + _retrieval_evidence(new_messages, ext_output),
8329 }
8330 except Exception as exc:
8331 model_errors.raise_if_fatal(exc)
8332 logger.exception(
8333 "[graph] ✘ node=%s error=%s", EXTERNAL_RETRIEVAL_NODE_ID, exc
8334 )
8335 return {
8336 "step_count": step,
8337 "messages": [
8338 AIMessage(
8339 content="External retrieval failed.",
8340 name=EXTERNAL_RETRIEVAL_NODE_ID,
8341 )
8342 ],
8343 "errors": [
8344 f"{EXTERNAL_RETRIEVAL_NODE_ID}: {model_errors.describe(exc)}"
8345 ],
8346 }
8348 return external_retrieval_node_fn
8350 def _create_tool_retrieval_node_fn(
8351 self, system_llm: BaseLanguageModel | None
8352 ) -> Callable[[GraphState], dict[str, Any]]:
8353 """
8354 Create the general tool retrieval node function.
8356 Executes deterministic general-purpose tools — geocode, calculate,
8357 current_time, web_search, url_fetch — to gather specific factual data
8358 (coordinates, computed values, live figures) before the skill graph runs.
8360 Unlike ``__external_retrieval__``, this node is not web-browsing oriented;
8361 it makes targeted, structured tool calls and stages the results in
8362 ``state.tool_context``, which the join hands on to downstream skill
8363 nodes after the knowledge and the web.
8364 """
8366 async def tool_retrieval_node_fn(
8367 state: GraphState, config: RunnableConfig | None = None
8368 ) -> dict[str, Any]:
8369 step = state.step_count + 1
8370 logger.info("[graph] ▶ node=%s step=%d", TOOL_RETRIEVAL_NODE_ID, step)
8372 from app.tools.registry import general_tools as _general_tools
8374 web_cfg = state.context.get("web_search_config", {})
8375 # Exactly the tools NODE_TOOL_RETRIEVAL describes.
8376 tool_names = set(prompts.TOOL_RETRIEVAL_TOOLS)
8377 retrieval_tools = [
8378 t
8379 for t in _general_tools({"web_search": web_cfg})
8380 if t.name in tool_names
8381 ]
8383 system_prompt = (
8384 prompts.build_metadata_context()
8385 + "\n\n"
8386 + _TOOL_RETRIEVAL_PROMPT_CHAIN.invoke(
8387 {
8388 "node_id": TOOL_RETRIEVAL_NODE_ID,
8389 "task": state.input,
8390 "execution_plan": state.execution_plan,
8391 }
8392 )
8393 )
8395 tool_agent = _SystemWorker(
8396 name=TOOL_RETRIEVAL_NODE_ID,
8397 llm=system_llm,
8398 system_prompt=system_prompt,
8399 )
8401 retrieval_focus = (
8402 state.execution_plan.get("retrieval_focus", "")
8403 if state.execution_plan
8404 else ""
8405 )
8406 focus_hint = (
8407 f"\nRetrieval focus from plan: {retrieval_focus}"
8408 if retrieval_focus
8409 else ""
8410 )
8411 standalone_hint = (
8412 f"\nStandalone form of the request: {state.retrieval_query}"
8413 if state.retrieval_query and state.retrieval_query != state.input
8414 else ""
8415 )
8416 task = (
8417 f"Task:\n{state.input}{standalone_hint}{focus_hint}"
8418 f"{_attached_hint(state)}\n\n"
8419 "Call the relevant tools to gather all specific factual data required. "
8420 "For location-based requests geocode every named place. "
8421 "For numeric tasks compute values with calculate. "
8422 "Return a concise structured summary of all retrieved facts."
8423 )
8425 try:
8426 result, new_messages = await tool_agent.process_with_history(
8427 task,
8428 [],
8429 extra_tools=retrieval_tools,
8430 on_tool_call=self._tool_call_recorder(
8431 TOOL_RETRIEVAL_NODE_ID, state
8432 ),
8433 config=_unstreamed_config(config),
8434 )
8435 tool_output = str(result)
8436 logger.info(
8437 "[graph] ✔ node=%s new_messages=%d tools=%d chars=%d",
8438 TOOL_RETRIEVAL_NODE_ID,
8439 len(new_messages),
8440 len(retrieval_tools),
8441 len(tool_output),
8442 )
8443 return {
8444 "step_count": step,
8445 "messages": new_messages,
8446 "tool_context": _retrieval_evidence(new_messages, tool_output),
8447 }
8448 except Exception as exc:
8449 model_errors.raise_if_fatal(exc)
8450 logger.exception(
8451 "[graph] ✘ node=%s error=%s", TOOL_RETRIEVAL_NODE_ID, exc
8452 )
8453 return {
8454 "step_count": step,
8455 "messages": [
8456 AIMessage(
8457 content="Tool retrieval failed.",
8458 name=TOOL_RETRIEVAL_NODE_ID,
8459 )
8460 ],
8461 "errors": [
8462 f"{TOOL_RETRIEVAL_NODE_ID}: {model_errors.describe(exc)}"
8463 ],
8464 "tool_context": "",
8465 }
8467 return tool_retrieval_node_fn
8469 def _create_synthesis_node_fn(
8470 self, system_llm: BaseLanguageModel | None
8471 ) -> Callable[[GraphState], dict[str, Any]]:
8472 """
8473 Create the post-skill-graph synthesis node function.
8475 Consolidates all skill-node outputs plus retrieval context into a
8476 single coherent final response. Has no tools — pure LLM synthesis.
8477 """
8479 async def synthesis_node_fn(state: GraphState) -> dict[str, Any]:
8480 step = state.step_count + 1
8481 logger.info(
8482 "[graph] ▶ node=%s step=%d skill_results=%d",
8483 SYNTHESIS_NODE_ID,
8484 step,
8485 len(state.results),
8486 )
8488 base_synthesis_prompt = _SYNTHESIS_PROMPT_CHAIN.invoke(
8489 {
8490 "node_id": SYNTHESIS_NODE_ID,
8491 "task": state.input,
8492 "execution_plan": state.execution_plan,
8493 }
8494 )
8495 # Prepend what the agent itself is told — the date, its name and
8496 # its persona — so synthesis answers as the agent rather than as a
8497 # generic pipeline consolidator. This is critical on the triage
8498 # direct_answer and planner-skip paths, where synthesis IS the only
8499 # response node: without the date it answered "what's on today?"
8500 # against its training cutoff.
8501 system_prompt = "\n\n".join(
8502 part
8503 for part in (
8504 prompts.build_metadata_context(),
8505 prompts.build_identity_context(state.agent_name),
8506 state.agent_system_prompt,
8507 base_synthesis_prompt,
8508 )
8509 if part
8510 )
8511 # Render tools + geocode — synthesis is the answer-producing node
8512 # on the triage direct_answer and planner-skip paths, where no skill
8513 # node runs; without these a "render a map/chart" request on those
8514 # paths can never produce a visual. geocode is included because
8515 # the map workflow requires verified coordinates.
8516 from app.tools.registry import (
8517 RENDER_TOOL_NAMES as _RENDER_NAMES,
8518 )
8519 from app.tools.registry import (
8520 resolve_tool as _resolve_tool,
8521 )
8522 from app.tools.registry import run_tool_config as _run_tool_config
8524 # A document's images are fetched under the run's web policy.
8525 _synth_web_cfg = state.context.get("web_search_config")
8526 render_tools: list[Any] = []
8527 for _tn in (*sorted(_RENDER_NAMES), "geocode"):
8528 try:
8529 render_tools.append(
8530 _resolve_tool(_tn, _run_tool_config(_tn, _synth_web_cfg))
8531 )
8532 except Exception:
8533 logger.warning(
8534 "[graph] node=%s could not resolve render tool %r",
8535 SYNTHESIS_NODE_ID,
8536 _tn,
8537 )
8539 synthesis_agent = _SystemWorker(
8540 name=SYNTHESIS_NODE_ID,
8541 llm=system_llm,
8542 system_prompt=system_prompt,
8543 )
8545 # Build the synthesis task as a structured XML document so section
8546 # boundaries are unambiguous even when the retrieved content or
8547 # skill outputs contain markdown, code, or angle-bracket characters.
8548 # Retrieval content is CDATA-wrapped for the same reason as in
8549 # skill node context injection.
8550 aggregated = _aggregate_prior_results(state)
8551 if not state.results:
8552 aggregated = (
8553 f"Original task:\n{state.input}\n\n"
8554 "No intermediate results were produced. Please respond directly to the task."
8555 )
8556 if not state.retrieval_context and attachment_util.citations(
8557 state.attachments
8558 ):
8559 # The person's documents are the material.
8560 aggregated += (
8561 "\nNothing was retrieved for this request: answer from "
8562 "the documents in <attachments>, citing them by their "
8563 "ids, and from your own knowledge where they leave off."
8564 )
8565 elif not state.retrieval_context:
8566 # Nothing was retrieved either: this is a direct answer.
8567 # NODE_SYNTHESIS forbids information absent from the
8568 # input, which here would forbid answering at all.
8569 aggregated += (
8570 "\nNothing was retrieved for this request, so answer from "
8571 "your own knowledge — the constraint on introducing "
8572 "information applies to pipeline results, and there are "
8573 "none. Say so where your knowledge may be out of date."
8574 )
8576 task_parts: list[str] = ["<synthesis_input>"]
8577 task_parts.extend(
8578 attachment_util.render_block(
8579 attachment_util.plan(state.attachments, _context_window(system_llm))
8580 )
8581 )
8582 task_parts.extend(
8583 _frameworks_block(state.frameworks_context, _FRAMEWORKS_NOTE)
8584 )
8585 if state.retrieval_context:
8586 # When the relevance judge failed, synthesis is told what the
8587 # answering agent is (``_UNJUDGED_KNOWLEDGE_NOTE``): it writes
8588 # a skill-graph agent's answer from the same passages, and saw
8589 # only their headers' "relevance unjudged".
8590 note = (
8591 f' note="{_UNJUDGED_KNOWLEDGE_NOTE}"'
8592 if state.retrieval_report.get("judge_failure")
8593 else ""
8594 )
8595 task_parts.append(f" <knowledge{note}>")
8596 task_parts.append(" <![CDATA[")
8597 task_parts.append(attachment_util.cdata(state.retrieval_context))
8598 task_parts.append(" ]]>")
8599 task_parts.append(" </knowledge>")
8600 task_parts.append(" <skill_outputs>")
8601 task_parts.append(" <![CDATA[")
8602 task_parts.append(attachment_util.cdata(aggregated))
8603 task_parts.append(" ]]>")
8604 task_parts.append(" </skill_outputs>")
8605 _reply_docs = _reply_documents(state.documents)
8606 if state.artifacts or _reply_docs:
8607 task_parts.append(
8608 ' <artifacts note="Pre-validated render fences produced by '
8609 "prior stages. Embed each one VERBATIM (byte-for-byte, including "
8610 "the fence lines) at the appropriate point in your response — "
8611 'never rewrite, regenerate, or drop one.">'
8612 )
8613 for _fence in _reply_docs:
8614 task_parts.append(" " + _document_note(_fence))
8615 for _fence in state.artifacts:
8616 task_parts.append(" <![CDATA[")
8617 task_parts.append(attachment_util.cdata(_fence))
8618 task_parts.append(" ]]>")
8619 task_parts.append(" </artifacts>")
8620 task_parts.append("</synthesis_input>")
8621 task = "\n".join(task_parts)
8623 # Conversation history — synthesis is the answer-producing node on
8624 # the planner-skip and triage direct_answer paths, so it needs the
8625 # same multi-turn context skill nodes get, and the same guarantee:
8626 # earlier turns only. Skill outputs and evidence are in `task`.
8627 prior_messages, history_notes = _history_messages(state)
8628 synthesis_agent.history_token_cap = effort_registry.of_state(
8629 state
8630 ).history_token_cap
8632 try:
8633 result, new_messages = await synthesis_agent.process_with_history(
8634 task,
8635 prior_messages,
8636 extra_tools=[
8637 *render_tools,
8638 *_attachment_tools(state, system_llm),
8639 ]
8640 or None,
8641 request_context=_conversation_notes_block(history_notes),
8642 )
8643 content = str(result)
8644 logger.info(
8645 "[graph] ✔ node=%s new_messages=%d output_chars=%d",
8646 SYNTHESIS_NODE_ID,
8647 len(new_messages),
8648 len(content),
8649 )
8650 return {
8651 "step_count": step,
8652 "messages": new_messages,
8653 "results": {SYNTHESIS_NODE_ID: result},
8654 "context": _history_figure(synthesis_agent),
8655 "status": "complete",
8656 # Synthesis may render new visuals itself now that it has
8657 # render tools — capture those fences too.
8658 "artifacts": _visual_fences(_extract_artifact_fences(new_messages)),
8659 "documents": _document_entries(
8660 _extract_artifact_fences(new_messages),
8661 pass_index=state.eval_retry_count,
8662 source=_FROM_MODEL,
8663 ),
8664 }
8665 except Exception as exc:
8666 model_errors.raise_if_fatal(exc)
8667 logger.exception("[graph] ✘ node=%s error=%s", SYNTHESIS_NODE_ID, exc)
8668 error_msg = AIMessage(
8669 content="Synthesis failed.", name=SYNTHESIS_NODE_ID
8670 )
8671 return {
8672 "step_count": step,
8673 "messages": [error_msg],
8674 "errors": [f"{SYNTHESIS_NODE_ID}: {model_errors.describe(exc)}"],
8675 "status": "error",
8676 }
8678 return synthesis_node_fn
8680 def _create_evaluator_node_fn(
8681 self, system_llm: BaseLanguageModel | None
8682 ) -> Callable[[GraphState], dict[str, Any]]:
8683 """
8684 Create the quality-gate evaluator node function.
8686 Runs after synthesis (or after the skill graph on routes that skip
8687 synthesis) as the final infrastructure node before optional HITL /
8688 memory-write. Uses a structured LLM call to:
8690 1. Extract every explicit requirement from the original request.
8691 2. Check each requirement against the draft response.
8692 3. Audit its claims against the evidence: the request itself (what
8693 the user supplied), tool results and retrieved knowledge.
8694 4. Pass the draft, or name what is wrong with it.
8696 It never writes the answer. On a failure that names something to fix,
8697 ``_evaluator_router`` sends the draft back to the agent (bounded by
8698 ``_MAX_EVAL_RETRIES``), with the verdict as a revision note via
8699 ``_aggregate_prior_results``. Once the budget is spent the agent's
8700 latest answer ships as it stands, ``failed``.
8702 The EvaluatorVerdict is stored under ``state.results[EVALUATOR_NODE_ID]``
8703 with the agent's answer as ``final_output``, which ``graph_based.py``
8704 reads as the authoritative pipeline output.
8705 """
8707 async def evaluator_node_fn(
8708 state: GraphState, config: RunnableConfig | None = None
8709 ) -> dict[str, Any]:
8710 step = state.step_count + 1
8711 logger.info("[graph] ▶ node=%s step=%d", EVALUATOR_NODE_ID, step)
8712 eval_errors: list[str] = []
8714 # ── Gather draft response ─────────────────────────────────────
8715 # Prefer synthesis output; fall back to last skill-node result.
8716 draft: str = ""
8717 synth_raw = state.results.get(SYNTHESIS_NODE_ID)
8718 if synth_raw is not None:
8719 draft = (
8720 synth_raw.final_output
8721 if hasattr(synth_raw, "final_output")
8722 else str(synth_raw)
8723 )
8725 # Free text — not a typed output's JSON — is what the answer's
8726 # citations are finalised in (``answer_sources``).
8727 draft_is_text = True
8728 if not draft:
8729 # Skip-synthesis path: find the last non-system result.
8730 for nid, res in reversed(list(state.results.items())):
8731 if nid not in SYSTEM_NODE_IDS and res is not None:
8732 draft = _result_text(res)
8733 draft_is_text = isinstance(res, str)
8734 break
8736 if not draft:
8737 # Absolute fallback: pass through a graceful message.
8738 draft = "No response was produced by the pipeline."
8740 # What the draft shows that nothing checked (``answer_artifacts``),
8741 # before the check reads it: a visual fence the agent wrote by
8742 # hand (or a copied note of one) is re-made by its tool or
8743 # removed, and an image no tool, evidence, earlier turn or the
8744 # person's words held goes, as does a link to no web address.
8745 remade: list[str] = []
8746 if draft_is_text:
8747 # A copied visual note is the fence it stood for, made again
8748 # by its tool below; a link to no web address goes.
8749 draft = answer_artifacts.notes_to_fences(draft)
8750 draft, remade = await answer_artifacts.remake_written_fences(
8751 draft, state.artifacts
8752 )
8753 draft, _ = answer_artifacts.drop_unseen_images(
8754 draft, _seen_by_the_run(state)
8755 )
8756 draft, _ = answer_artifacts.drop_dead_links(draft)
8758 # gpt-oss marks citations 【1】 and leaves cursor references
8759 # (【3†L1-L5】) in its prose; read as written, the draft's Sources
8760 # section is not found and the answer ships with them. Normalised
8761 # here, the check reads the citations and every verdict's
8762 # final_output carries ``[n]`` — passed through or skipped alike —
8763 # with its links made to render (``source_ledger.tidy_answer``).
8764 draft = source_ledger.tidy_answer(draft)
8766 # ── Build evaluator input as structured XML ───────────────────
8767 # XML tags give the evaluator model unambiguous section boundaries.
8768 # The draft response and tool results are CDATA-wrapped because they
8769 # originate from LLM + tool outputs that may contain angle brackets,
8770 # markdown, or code. Plan values are XML-escaped (they are planner
8771 # LLM output, shorter and less likely to contain angle brackets, but
8772 # correctness requires escaping regardless).
8773 import html as _html
8775 tool_lines: list[str] = []
8776 # The figures the draft states: the blocks of a long result that
8777 # hold them are what the check must see (``_draft_figures``).
8778 draft_figures = _draft_figures(draft)
8779 for msg in state.messages:
8780 tool_calls = getattr(msg, "tool_calls", None)
8781 if tool_calls:
8782 for tc in tool_calls:
8783 name = (
8784 tc.get("name", "?")
8785 if isinstance(tc, dict)
8786 else getattr(tc, "name", "?")
8787 )
8788 args = (
8789 tc.get("args", {})
8790 if isinstance(tc, dict)
8791 else getattr(tc, "args", {})
8792 )
8793 tool_lines.append(
8794 f" <call tool={_html.escape(str(name))!r} "
8795 f"args={_html.escape(str(args))!r} />"
8796 )
8797 tool_call_id = getattr(msg, "tool_call_id", None)
8798 if tool_call_id is not None:
8799 content = str(getattr(msg, "content", ""))
8800 # Keep render fences whole — a truncated fence can never be
8801 # restored into final_output by the evaluator's revision.
8802 # Anything else is read whole where it fits and otherwise
8803 # abridged block by block, so every result of a search is
8804 # in front of the check, not the first one.
8805 held_by_none = source_ledger.not_held(content)
8806 preview = attachment_util.cdata(
8807 source_ledger.NOT_HELD_NOTE.format(tool=held_by_none)
8808 if held_by_none
8809 else content[:_TOOL_FENCE_CHARS]
8810 if _ARTIFACT_FENCE_RE.search(content)
8811 else _tool_result_digest(content, keep=draft_figures)
8812 )
8813 tool_lines.append(f" <result><![CDATA[{preview}]]></result>")
8815 plan = state.execution_plan or {}
8816 plan_parts: list[str] = []
8817 if isinstance(plan, dict):
8818 if plan.get("overall_goal"):
8819 plan_parts.append(
8820 f" <overall_goal>{_html.escape(plan['overall_goal'])}</overall_goal>"
8821 )
8822 for np in plan.get("node_plans") or []:
8823 if isinstance(np, dict):
8824 nid = _html.escape(str(np.get("node_id", "?")))
8825 ngoal = _html.escape(str(np.get("goal", "")))
8826 plan_parts.append(f' <node id="{nid}">{ngoal}</node>')
8828 # Task complexity from triage — lets the evaluator scale its
8829 # strictness: a simple lookup is judged on answering the question,
8830 # not on exhaustive coverage of every related attribute.
8831 _complexity = str(
8832 (state.resource_strategy or {}).get("complexity", "") or "moderate"
8833 )
8835 ev_parts: list[str] = ["<evaluation_input>"]
8836 # The date the agent answered on: without it a plan dated from
8837 # today failed as "fabricates a current date", and "this week"
8838 # was judged against a guess.
8839 ev_parts.append(f" <current_date>{prompts.today()}</current_date>")
8840 # What the agent was told to do — so a deliberate decline, a
8841 # neutral answer or a privacy-minded omission it was instructed to
8842 # make is not read as a gap.
8843 instructions = (state.agent_system_prompt or "")[
8844 :_EVALUATOR_INSTRUCTIONS_CHARS
8845 ]
8846 if instructions.strip():
8847 ev_parts.append(
8848 " <agent_instructions><![CDATA["
8849 + instructions.replace("]]>", "]]]]><![CDATA[>")
8850 + "]]></agent_instructions>"
8851 )
8852 ev_parts.append(
8853 f" <request><![CDATA[{attachment_util.cdata(state.input)}]]></request>"
8854 )
8855 # On a revision, what the earlier checks of this answer said: a
8856 # check that never saw them failed a payroll plan for stating a
8857 # date, then the revision for saying it had none.
8858 ev_parts.extend(_earlier_checks_block(state.quality_checks))
8859 # The documents the person attached, as the agent was shown them:
8860 # they were inside <request> when they were pasted into it, and
8861 # the check judged an answer drawn from them as grounded.
8862 ev_parts.extend(
8863 attachment_util.render_for_evaluator(
8864 attachment_util.plan(state.attachments, _context_window(system_llm))
8865 )
8866 )
8867 # A follow-up ("make it shorter", "the second one") is judged
8868 # against what it asks in context. The evaluator saw the request
8869 # alone, so it could not tell whether a draft did what a
8870 # follow-up asked, and named gaps the conversation answered.
8871 if (
8872 state.retrieval_query
8873 and state.retrieval_query.strip() != state.input.strip()
8874 ):
8875 ev_parts.append(
8876 " <resolved_request><![CDATA["
8877 + state.retrieval_query.replace("]]>", "]]]]><![CDATA[>")
8878 + "]]></resolved_request>"
8879 )
8880 earlier = _conversation_tail(state, max_turns=_EVALUATOR_HISTORY_TURNS)
8881 if earlier:
8882 ev_parts.append(" <conversation>")
8883 # The latest answer is what a follow-up most often refers to
8884 # ("shorter", "the second one"): it keeps the most.
8885 last_answer = max(
8886 (i for i, t in enumerate(earlier) if t["role"] != "user"),
8887 default=-1,
8888 )
8889 for i, turn in enumerate(earlier):
8890 who = "user" if turn["role"] == "user" else "assistant"
8891 said = turn["content"]
8892 limit = (
8893 _EVALUATOR_TURN_CHARS
8894 if i == last_answer
8895 else _EVALUATOR_EARLIER_TURN_CHARS
8896 )
8897 if len(said) > limit:
8898 said = said[:limit] + "…"
8899 ev_parts.append(
8900 f" <{who}><![CDATA["
8901 + said.replace("]]>", "]]]]><![CDATA[>")
8902 + f"]]></{who}>"
8903 )
8904 ev_parts.append(" </conversation>")
8905 ev_parts.append(
8906 f" <task_complexity>{_html.escape(_complexity)}</task_complexity>"
8907 )
8908 if plan_parts:
8909 ev_parts.append(" <plan>")
8910 ev_parts.extend(plan_parts)
8911 ev_parts.append(" </plan>")
8912 else:
8913 ev_parts.append(" <plan>(no structured plan)</plan>")
8914 if tool_lines:
8915 ev_parts.append(" <tool_calls>")
8916 ev_parts.extend(tool_lines)
8917 ev_parts.append(" </tool_calls>")
8918 else:
8919 ev_parts.append(" <tool_calls>(none)</tool_calls>")
8920 # Everything the run retrieved — knowledge-base retrieval included,
8921 # which never appears in <tool_calls> — and a code-side verdict on
8922 # each entry of the draft's Sources section. See source_ledger.py
8923 # for why the model no longer judges citations on its own.
8924 ledger = source_ledger.build_ledger(
8925 [
8926 *attachment_util.citations(state.attachments),
8927 *state.retrieval_citations,
8928 ],
8929 state.messages,
8930 )
8931 registry = source_registry.current()
8932 citation_checks = source_ledger.verify_markers(
8933 draft, registry
8934 ) + source_ledger.verify_citations(
8935 source_ledger.parse_sources_section(draft), ledger
8936 )
8937 # With no ids handed out, every id is dropped as the answer ships
8938 # (``answer_sources.finalise``): nothing to send back for it.
8939 marker_problems = (
8940 answer_sources.check_markers(draft, registry)
8941 if draft_is_text and registry is not None and registry.issued()
8942 else []
8943 )
8944 # Both whole, as the agent read them: the packer bounds them, and
8945 # a check shown the first 12,000 characters judged claims
8946 # "unsupported" by passages it had been cut off from.
8947 ev_parts.extend(
8948 _frameworks_block(state.frameworks_context, _EVALUATOR_FRAMEWORKS_NOTE)
8949 )
8950 if state.retrieval_context:
8951 ev_parts.append(" <retrieved_knowledge><![CDATA[")
8952 ev_parts.append(attachment_util.cdata(state.retrieval_context))
8953 ev_parts.append(" ]]></retrieved_knowledge>")
8954 else:
8955 ev_parts.append(" <retrieved_knowledge>(none)</retrieved_knowledge>")
8956 ev_parts.extend(source_ledger.render_for_evaluator(ledger, citation_checks))
8957 _reply_docs = _reply_documents(state.documents)
8958 if state.artifacts or _reply_docs:
8959 ev_parts.append(" <artifacts>")
8960 for _fence in _reply_docs:
8961 # In full: what the reply says the document holds is
8962 # checked against it, and it is attached whatever the
8963 # draft says.
8964 ev_parts.append(" " + _document_for_check(_fence, registry))
8965 for _fence in state.artifacts:
8966 ev_parts.append(" <![CDATA[")
8967 ev_parts.append(attachment_util.cdata(_fence))
8968 ev_parts.append(" ]]>")
8969 ev_parts.append(" </artifacts>")
8970 ev_parts.append(" <draft><![CDATA[")
8971 # Without the markers that name no source: code drops them or
8972 # sends them back, and a check shown them judged them too.
8973 ev_parts.append(
8974 attachment_util.cdata(
8975 answer_sources.for_check(draft, registry)
8976 if draft_is_text
8977 else draft
8978 )
8979 )
8980 ev_parts.append(" ]]></draft>")
8981 ev_parts.append("</evaluation_input>")
8982 evaluator_input = "\n".join(ev_parts)
8984 # ── Pass-through fallback (no LLM / evaluation error) ──────────
8985 # passed=True so a broken evaluator can never trigger the retry
8986 # loop — retrying without a verdict is wasted compute. But it is
8987 # recorded as unchecked, with no score: a rule can then send the
8988 # answer to a person rather than read it as a pass. The critique
8989 # states the REAL reason so traces are not misleading.
8990 revision = state.eval_retry_count > 0
8992 def _passthrough(critique: str) -> EvaluatorVerdict:
8993 return EvaluatorVerdict(
8994 passed=True,
8995 score=None,
8996 critique=critique,
8997 final_output=draft,
8998 outcome="unavailable",
8999 )
9001 # A cost profile may answer a simple request unchecked
9002 # (``PipelineEffort.check_simple_tasks``). Recorded as ``skipped``
9003 # — chosen, not failed — so a rule on an unchecked answer can
9004 # still tell the two apart. A revision is always checked.
9005 skip_simple = (
9006 not effort_registry.of_state(state).check_simple_tasks
9007 and state.eval_retry_count == 0
9008 and str((state.resource_strategy or {}).get("complexity") or "")
9009 == "simple"
9010 )
9012 if system_llm is None:
9013 logger.warning(
9014 "[graph] node=%s no LLM — passing draft through", EVALUATOR_NODE_ID
9015 )
9016 eval_result = _passthrough(
9017 "Evaluation skipped — no evaluator LLM configured; "
9018 "draft passed through unreviewed."
9019 )
9020 elif skip_simple:
9021 logger.info(
9022 "[graph] node=%s simple request, cost profile %s — not checked",
9023 EVALUATOR_NODE_ID,
9024 state.context.get(effort_registry.CONTEXT_KEY),
9025 )
9026 eval_result = EvaluatorVerdict(
9027 passed=True,
9028 score=None,
9029 critique=SKIPPED_CRITIQUE,
9030 final_output=draft,
9031 outcome="skipped",
9032 )
9033 else:
9034 try:
9035 from langchain_core.messages import (
9036 HumanMessage as _HM,
9037 )
9038 from langchain_core.messages import (
9039 SystemMessage as _SM,
9040 )
9042 # A verdict, never the answer: a verdict-sized cap.
9043 check_llm = _capped_llm(system_llm, _check_cap(system_llm))
9044 set_aside: list[str] = []
9045 if state.quality_checks:
9046 # A revision is checked against what was asked of
9047 # it: the gaps still open, and errors it introduced.
9048 checked = await structured_call(
9049 check_llm,
9050 RevisionCheck,
9051 [
9052 _SM(content=prompts.NODE_REVISION_CHECK),
9053 _HM(content=evaluator_input),
9054 ],
9055 purpose=EVALUATOR_NODE_ID,
9056 cache_system=True,
9057 )
9058 eval_result: EvaluatorResult = _revision_result(
9059 checked.unwrap(), state.quality_checks
9060 )
9061 eval_result, set_aside = _set_aside_absent_documents(
9062 eval_result, attaches_document=bool(_reply_docs)
9063 )
9064 else:
9065 result = await structured_call(
9066 check_llm,
9067 EvaluatorResult,
9068 [
9069 _SM(content=prompts.NODE_EVALUATOR),
9070 _HM(content=evaluator_input),
9071 ],
9072 purpose=EVALUATOR_NODE_ID,
9073 # The same instructions on every check: served
9074 # from cache from the second on.
9075 cache_system=True,
9076 )
9077 # What the agent did itself, what was not asked
9078 # and presentation are noted, never failed.
9079 eval_result, set_aside = _split_gaps(result.unwrap())
9080 # The reply's document is attached whatever the
9081 # draft says: never missing.
9082 eval_result, absent = _set_aside_absent_documents(
9083 eval_result, attaches_document=bool(_reply_docs)
9084 )
9085 set_aside += absent
9086 # A request about now answered with nothing current
9087 # goes back to search the web, whatever the check said.
9088 eval_result = _with_live_gap(
9089 eval_result,
9090 _unsearched_live_gap(state, holds_web=self._searches_the_web()),
9091 )
9092 # Recover the omittable critique BEFORE the verdict
9093 # branches, so a failure always says what it found.
9094 if not eval_result.critique:
9095 issues = [_issue(g) for g in eval_result.gaps] + (
9096 eval_result.reasoning_errors or []
9097 )
9098 eval_result.critique = (
9099 "; ".join(issues[:3])
9100 if issues
9101 else (
9102 "Draft passed evaluation."
9103 if eval_result.passed
9104 else "Draft failed evaluation."
9105 )
9106 )
9107 # Two-dimensional pass check:
9108 # reasoning_errors present → failed whatever the model said
9109 # failed, nothing material → passed (presentation only)
9110 reasoning_errors = eval_result.reasoning_errors or []
9111 if reasoning_errors:
9112 eval_result = eval_result.model_copy(
9113 update={
9114 "passed": False,
9115 "score": min(
9116 eval_result.score,
9117 prompts.EVALUATOR_INVALID_REASONING_CAP,
9118 ),
9119 }
9120 )
9121 elif not eval_result.passed and not _material(eval_result):
9122 # A fail that names nothing to fix: the agent's
9123 # answer stands, and the objection stays in the
9124 # critique.
9125 eval_result = eval_result.model_copy(update={"passed": True})
9126 logger.info(
9127 "[graph] ✔ node=%s passed=%s score=%d gaps=%d "
9128 "set_aside=%d reasoning_errors=%d",
9129 EVALUATOR_NODE_ID,
9130 eval_result.passed,
9131 eval_result.score,
9132 len(eval_result.gaps),
9133 len(set_aside),
9134 len(reasoning_errors),
9135 )
9136 eval_result = _verdict(
9137 eval_result, draft, revision=revision, set_aside=set_aside
9138 )
9139 if marker_problems:
9140 # A marker naming no source cannot be finalised: the
9141 # agent revises it, with the ids it was given.
9142 eval_result = eval_result.model_copy(
9143 update={
9144 "passed": False,
9145 "outcome": "failed",
9146 "citation_problems": answer_sources.describe_problems(
9147 marker_problems, registry
9148 ),
9149 }
9150 )
9151 except Exception as exc:
9152 model_errors.raise_if_fatal(exc)
9153 logger.warning(
9154 "[graph] ✘ node=%s evaluation failed (%s) — passing draft through",
9155 EVALUATOR_NODE_ID,
9156 model_errors.describe(exc),
9157 )
9158 # The reason goes to the log and the trace, not the
9159 # critique: the critique is shown to people and written
9160 # to the agent's memory.
9161 eval_result = _passthrough(
9162 "Evaluation failed — the quality check could not be "
9163 "completed; draft passed through unreviewed."
9164 )
9165 eval_errors = [f"{EVALUATOR_NODE_ID}: {model_errors.describe(exc)}"]
9167 # ── Artifact guard ────────────────────────────────────────────
9168 # Rewrite passes (synthesis, evaluator revision) can drop render
9169 # fences despite the prompt rules; restore any fence type that
9170 # vanished entirely so the visual always reaches the user.
9171 # Documents run unconditionally: a document fence the model wrote
9172 # without calling render_document is not a document, and goes.
9173 restored = _attach_documents(
9174 _restore_missing_artifacts(
9175 eval_result.final_output,
9176 state.artifacts,
9177 _reply_documents(state.documents),
9178 ),
9179 _reply_documents(state.documents),
9180 )
9181 if restored != eval_result.final_output:
9182 logger.info(
9183 "[graph] node=%s restored render fence(s) / attached "
9184 "document(s) in final_output",
9185 EVALUATOR_NODE_ID,
9186 )
9187 eval_result.final_output = restored
9189 _re = getattr(eval_result, "reasoning_errors", []) or []
9190 retry_count = state.eval_retry_count
9191 budget = _eval_retry_budget(state)
9192 # Every failure that names something to fix goes back to the
9193 # agent while budget lasts. Must mirror _evaluator_router.
9194 failed = not eval_result.passed
9195 if failed:
9196 retry_count += 1
9197 if retry_count <= budget:
9198 logger.info(
9199 "[graph] ↻ node=%s failed score=%s (attempt %d/%d) — "
9200 "agent revises",
9201 EVALUATOR_NODE_ID,
9202 eval_result.score,
9203 retry_count,
9204 budget,
9205 )
9206 else:
9207 logger.info(
9208 "[graph] node=%s failed score=%s — no revisions left; "
9209 "the agent's answer ships as it stands",
9210 EVALUATOR_NODE_ID,
9211 eval_result.score,
9212 )
9213 # ── The delivered answer's sources ────────────────────────────
9214 # Only on the verdict that ships the answer: a draft going back
9215 # for a revision keeps the ids the agent cites by.
9216 if draft_is_text and _final_verdict(
9217 eval_result.passed, retry_count, budget
9218 ):
9219 finished = answer_sources.finalise(eval_result.final_output, registry)
9220 if finished.dropped:
9221 logger.info(
9222 "[graph] node=%s dropped markers naming no source: %s",
9223 EVALUATOR_NODE_ID,
9224 ", ".join(finished.dropped),
9225 )
9226 eval_result.final_output = finished.text
9227 eval_result.answer_sources = [
9228 AnswerSource(marker=c["marker"], citation_id=c["citation_id"])
9229 for c in finished.cited
9230 ]
9232 summary = AIMessage(
9233 content=(
9234 "Quality check skipped — the cost profile answers simple "
9235 "requests unchecked"
9236 if eval_result.outcome == "skipped"
9237 else "Evaluation unavailable — draft passed through unreviewed"
9238 if eval_result.score is None
9239 else f"Evaluation complete — score: {eval_result.score}/100, "
9240 f"passed: {eval_result.passed}"
9241 + (
9242 f", content gaps: {len(eval_result.gaps)}"
9243 if eval_result.gaps
9244 else ""
9245 )
9246 + (f", reasoning errors: {len(_re)}" if _re else "")
9247 + (
9248 f", revising ({retry_count}/{budget})"
9249 if failed and retry_count <= budget
9250 else ""
9251 )
9252 ),
9253 name=EVALUATOR_NODE_ID,
9254 )
9255 return {
9256 "step_count": step,
9257 "messages": [summary],
9258 "results": {EVALUATOR_NODE_ID: eval_result},
9259 "eval_retry_count": retry_count,
9260 "errors": eval_errors,
9261 # What this check asked for, read by the next one.
9262 "quality_checks": [_check_record(eval_result)] if failed else [],
9263 # A hand-written fence its tool re-made is one the run made:
9264 # a revision that drops it gets it back (the artifact guard).
9265 "artifacts": remade,
9266 }
9268 return evaluator_node_fn
9270 def _await_approval(self, node_id: str, node: GraphNode, state: GraphState) -> str:
9271 """Pause for a person to approve running ``node_id``.
9273 Shows what the graph has produced so far — every completed skill
9274 node's result — and the author's message. Returns the reviewer's
9275 feedback when approved; raises ``RunRejected`` when not.
9276 """
9277 completed = {
9278 nid: _result_text(result)[:APPROVAL_PREVIEW_CHARS]
9279 for nid, result in (state.results or {}).items()
9280 if nid in self.nodes
9281 }
9282 message = str((node.approval or {}).get("message") or "")
9283 logger.info("[graph] ⏸ node=%s awaiting approval", node_id)
9284 decision = lg_interrupt(
9285 {
9286 "type": APPROVAL_INTERRUPT,
9287 "node_id": node_id,
9288 "message": message,
9289 "task": state.input,
9290 "completed": completed,
9291 # What a client that knows only the whole-run gate displays.
9292 "output": "\n\n".join(
9293 f"## {nid}\n{text}" for nid, text in completed.items()
9294 ),
9295 }
9296 )
9297 approved, feedback = True, ""
9298 if isinstance(decision, dict):
9299 approved = bool(decision.get("approved", True))
9300 feedback = str(decision.get("feedback") or "")
9301 logger.info("[graph] ▶ node=%s approved=%s", node_id, approved)
9302 if not approved:
9303 raise RunRejected(node_id, feedback)
9304 return feedback
9306 def _create_hitl_node_fn(self) -> Callable[[GraphState], dict[str, Any]]:
9307 """
9308 Create the human-in-the-loop approval node.
9310 Calls LangGraph's ``interrupt()`` to pause execution and surface the
9311 current synthesis output to the caller. Execution resumes when the
9312 caller invokes the graph with ``Command(resume={...})``.
9314 The interrupt payload contains:
9315 - ``type``: ``"approval_request"``
9316 - ``task``: original user input
9317 - ``output``: current synthesis result awaiting approval
9319 On resume, ``feedback`` (str) and ``approved`` (bool) are available
9320 in ``state.context`` for downstream use or re-execution.
9321 """
9323 async def hitl_node_fn(state: GraphState) -> dict[str, Any]:
9324 eval_raw = state.results.get(EVALUATOR_NODE_ID)
9325 if eval_raw is not None and hasattr(eval_raw, "final_output"):
9326 current_output = eval_raw.final_output
9327 else:
9328 current_output = state.results.get(
9329 SYNTHESIS_NODE_ID, state.results.get("", "")
9330 )
9331 logger.info("[graph] ▶ node=%s awaiting human approval", HITL_NODE_ID)
9333 feedback = lg_interrupt(
9334 {
9335 "type": "approval_request",
9336 "task": state.input,
9337 "output": str(current_output),
9338 }
9339 )
9341 approved = True
9342 feedback_text = ""
9343 if isinstance(feedback, dict):
9344 approved = feedback.get("approved", True)
9345 feedback_text = feedback.get("feedback", "")
9347 logger.info("[graph] ✔ node=%s approved=%s", HITL_NODE_ID, approved)
9348 return {
9349 "context": {
9350 "hitl_approved": approved,
9351 "hitl_feedback": feedback_text,
9352 },
9353 }
9355 return hitl_node_fn
9357 def _create_memory_read_node_fn(self) -> Callable[[GraphState], dict[str, Any]]:
9358 """
9359 Create the memory-read node.
9361 Recalls what the agent keeps of this person (``app/memory``): every
9362 preference, and the facts, goals and earlier exchanges this request
9363 is about — none from another workspace, none superseded or expired,
9364 and none of this conversation's turns the history already replays.
9365 Recall used to be the newest eight memories whatever the request.
9366 Recalled text is redacted as the policy rules redact the prompt.
9367 After a scope clarification it matches the request as sent and the
9368 person's answers, not the ``<clarified_scope>`` block's wording.
9369 """
9370 store = self.store
9371 builder = self
9373 async def memory_read_fn(state: GraphState) -> dict[str, Any]:
9374 from app.common import workspace as workspace_ctx
9375 from app.memory import recall as memory_recall
9376 from app.memory import service as memory_service
9377 from app.memory import text as memory_text
9378 from app.tools import clarify
9380 user_id = state.context.get("user_id", "")
9381 scope = memory_service.scope_for(
9382 state.context, workspace_ctx.stamp(user_id)
9383 )
9384 if store is None or scope is None:
9385 return {"memories": []}
9386 logger.info(
9387 "[graph] ▶ node=%s agent=%s user=%s",
9388 MEMORY_READ_NODE_ID,
9389 scope.agent_id,
9390 scope.user_id,
9391 )
9392 # A request for current information recalls no earlier exchange:
9393 # the nearest is the same question, answered then.
9394 live = bool(state.context.get(LIVE_DATA_KEY))
9395 try:
9396 effort = effort_registry.of_state(state)
9397 history, _ = _history_messages(state)
9398 # The request as the person wrote it, with their answers to a
9399 # scope clarification but none of its scaffolding, and its
9400 # standalone form (the gate's rewrite of a follow-up), which
9401 # is what gets embedded: "the second option" means nothing on
9402 # its own.
9403 asked = memory_text.user_text(
9404 state.request_before_clarification or state.input
9405 )
9406 request = "; ".join(
9407 t
9408 for t in (asked, *clarify.answer_labels(state.clarifications))
9409 if t
9410 )
9411 texts = tuple(
9412 dict.fromkeys(
9413 t.strip()
9414 for t in (request, state.retrieval_query)
9415 if t and t.strip()
9416 )
9417 )
9418 memories = await memory_service.recall_for(
9419 store,
9420 scope,
9421 # Documents sent without a word are recalled by their
9422 # names: an earlier turn about the same file bears on it.
9423 texts=texts
9424 or (
9425 attachment_util.with_names(
9426 "", attachment_util.turn_names(state.attachments)
9427 )
9428 or state.request_before_clarification
9429 or state.input,
9430 ),
9431 conversation_id=state.context.get("conversation_id") or None,
9432 replayed_turns=sum(
9433 1 for m in history if isinstance(m, HumanMessage)
9434 ),
9435 limits=memory_recall.Limits(
9436 limit=effort.memory_recall_limit,
9437 max_chars=effort.memory_block_max_chars,
9438 item_max_chars=MEMORY_ITEM_MAX_CHARS,
9439 ),
9440 redaction=builder.memory_redaction,
9441 live=live,
9442 )
9443 logger.info(
9444 "[graph] ✔ node=%s recalled=%d memories%s",
9445 MEMORY_READ_NODE_ID,
9446 len(memories),
9447 " (episodes left out: live request)" if live else "",
9448 )
9449 return {
9450 "memories": memories,
9451 **(
9452 {"context": {RECALL_LEFT_OUT_KEY: {"episode": "live_request"}}}
9453 if live
9454 else {}
9455 ),
9456 }
9457 except Exception as exc:
9458 logger.warning(
9459 "[graph] ✘ node=%s error=%s",
9460 MEMORY_READ_NODE_ID,
9461 model_errors.describe(exc),
9462 )
9463 return {"memories": []}
9465 return memory_read_fn
9467 def _create_memory_write_node_fn(
9468 self, extract_llm: BaseLanguageModel | None = None
9469 ) -> Callable[[GraphState], dict[str, Any]]:
9470 """
9471 Create the memory-write node.
9473 Keeps an episode of the turn — what was asked, and the gist of the
9474 answer unless the quality check could not stand behind it — and,
9475 when the person's words or the triage say there is something to
9476 remember, what ``app/memory/extraction`` proposes and its validation
9477 keeps. Everything kept is redacted as the audit rules redact the
9478 answer. The quality check's verdict is no longer appended: it was
9479 the pipeline's judgement, never something the person said.
9480 """
9481 store = self.store
9482 builder = self
9483 # Memory summaries are a step nobody reads: an Economy profile's
9484 # lighter model writes them.
9485 _memory_llm = self._steps_llm or self._system_llm
9487 async def memory_write_fn(state: GraphState) -> dict[str, Any]:
9488 from app.common import workspace as workspace_ctx
9489 from app.memory import service as memory_service
9490 from app.memory import turn_outcome
9491 from app.tools import clarify
9493 user_id = state.context.get("user_id", "")
9494 eval_raw = state.results.get(EVALUATOR_NODE_ID)
9495 if eval_raw is not None and hasattr(eval_raw, "final_output"):
9496 final_output = eval_raw.final_output
9497 else:
9498 final_output = state.results.get(SYNTHESIS_NODE_ID, "")
9499 scope = memory_service.scope_for(
9500 state.context, workspace_ctx.stamp(user_id)
9501 )
9502 if store is None or scope is None or not final_output:
9503 return {}
9504 # This turn's tool calls and results: an answer they could not
9505 # stand behind, or one true only today, is not kept.
9506 kept = turn_outcome.of_turn(
9507 state.messages, dated=bool(state.context.get(DATED_KNOWLEDGE_KEY))
9508 )
9509 logger.info(
9510 "[graph] ▶ node=%s agent=%s user=%s",
9511 MEMORY_WRITE_NODE_ID,
9512 scope.agent_id,
9513 scope.user_id,
9514 )
9515 try:
9516 report = await memory_service.remember(
9517 store,
9518 scope,
9519 # What the person wrote, and what they answered to a scope
9520 # clarification — never the block that carried it.
9521 request=state.request_before_clarification or state.input,
9522 clarified=clarify.answer_labels(state.clarifications),
9523 attached=attachment_util.turn_names(state.attachments),
9524 # Charts and documents are the reply's attachments, not
9525 # what was concluded.
9526 # Nor are its citations: the markers and the Sources
9527 # block name sources a later turn is never shown.
9528 answer=answer_sources.plain(
9529 _ARTIFACT_FENCE_RE.sub("", _result_text(final_output))
9530 ).strip(),
9531 # Not an answer the quality check failed, nor one a
9532 # withhold rule may yet withhold (that is decided in
9533 # svc-core, after the run), nor one its tools could not
9534 # stand behind or that is true only today.
9535 keep_answer=getattr(eval_raw, "outcome", None) != "failed"
9536 and not builder.withholding
9537 and kept is turn_outcome.AnswerKept.kept,
9538 answer_left_out=(
9539 "" if kept is turn_outcome.AnswerKept.kept else kept.value
9540 ),
9541 conversation_id=state.context.get("conversation_id") or None,
9542 conversation=_conversation_tail(state, max_turns=2),
9543 summary_llm=_memory_llm,
9544 extract_llm=extract_llm,
9545 flagged=bool(state.context.get(MEMORY_CUE_KEY)),
9546 redaction=builder.memory_redaction,
9547 )
9548 logger.info(
9549 "[graph] ✔ node=%s kept episode + %d memories (%d restated, "
9550 "%d forgotten, %d dropped)",
9551 MEMORY_WRITE_NODE_ID,
9552 len(report.added),
9553 report.confirmed,
9554 report.forgotten,
9555 len(report.dropped),
9556 )
9557 return {"memory_write_result": report.describe()}
9558 except Exception as exc:
9559 logger.warning(
9560 "[graph] ✘ node=%s error=%s",
9561 MEMORY_WRITE_NODE_ID,
9562 model_errors.describe(exc),
9563 )
9564 return {}
9566 return memory_write_fn
9568 # ------------------------------------------------------------------
9569 # Helpers
9570 # ------------------------------------------------------------------
9572 def _assert_node_exists(self, node_id: str) -> None:
9573 if node_id not in self.nodes:
9574 raise ValueError(
9575 f"Node '{node_id}' not found — add it with add_agent() first"
9576 )
9578 def visualize(self) -> str:
9579 """Return a text diagram of the full execution topology."""
9580 use_memory = self.store is not None
9581 lines = ["Agent Execution Graph", "=" * 50]
9582 lines.append(
9583 f"[system] {GATE_NODE_ID} (triage: route + task shape; trivial → END)"
9584 )
9585 lines.append(f" └─ clarify → {CLARIFY_NODE_ID}")
9586 lines.append(f" └─ direct_answer → {SYNTHESIS_NODE_ID}")
9587 first = MEMORY_READ_NODE_ID if use_memory else PLANNING_NODE_ID
9588 lines.append(f" └─ to_planning → {first}")
9589 if use_memory:
9590 lines.append(f"[system] {MEMORY_READ_NODE_ID} (recall agent memories)")
9591 lines.append(f" └─ → {PLANNING_NODE_ID}")
9592 lines.append(
9593 f"[system] {PLANNING_NODE_ID} (execution planning with triage's strategy)"
9594 )
9595 lines.append(f" └─ → {RETRIEVAL_NODE_ID}")
9596 lines.append(f"[system] {RETRIEVAL_NODE_ID} (KB retrieval + context)")
9597 lines.append(f" └─ → {self.start_node}\n")
9599 for node_id, node in self.nodes.items():
9600 prefix = "→ " if node.is_start else " "
9601 suffix = " ✓" if node.is_end else ""
9602 lines.append(f"{prefix}{node_id} ({node.agent.role.value}){suffix}")
9603 for condition, target in node.next_nodes.items():
9604 lines.append(f" └─ {condition} → {target}")
9605 for key, target in node.conditional_edge_map.items():
9606 lines.append(f" └─ [{key}] → {target}")
9608 terminal_label = ", ".join(self.end_nodes) if self.end_nodes else "—"
9609 lines.append(f"\n[system] {SYNTHESIS_NODE_ID} (final synthesis)")
9610 lines.append(f" ← from: {terminal_label}")
9611 if self.require_approval:
9612 lines.append(f" └─ → {HITL_NODE_ID}")
9613 lines.append(
9614 f"[system] {HITL_NODE_ID} (human-in-the-loop approval — interrupt())"
9615 )
9616 lines.append(f" └─ → {'MEMORY_WRITE' if use_memory else 'END'}")
9617 if use_memory:
9618 lines.append(
9619 f"[system] {MEMORY_WRITE_NODE_ID} (persist interaction memory)"
9620 )
9621 lines.append(" └─ → END")
9622 if not self.require_approval and not use_memory:
9623 lines.append(" └─ → END")
9625 return "\n".join(lines)
9627 def __repr__(self) -> str:
9628 return (
9629 f"AgentGraphBuilder(nodes={len(self.nodes)}, "
9630 f"edges={len(self.edges)}, start={self.start_node!r})"
9631 )