Agent Graph — System Nodes and Context Injection
How svc-ai turns a user turn plus the agent's customisations (skillsets, toolkits, knowledge repositories) into a grounded answer, which system node is responsible for what, and the research each design choice draws on.
The October 2026 review of this pipeline — findings, evidence and the remaining plan — is Agent Graph Review.
Topology
Every execution — a plain agent, an agent with a skill graph, or a stored skill — is compiled by AgentGraphBuilder.build() into the same wrapper around the user's skill nodes:
__gate__ (triage) ──trivial──▶ END (one call: route + task shape)
│ (route + retrieval_type + retrieval_query + resource_strategy)
├──(scope ambiguous)──▶ [__clarify__] ⏸ ──▶ (triage's destination)
├──direct_answer──▶ __synthesis__ (multi-node, unpinned graphs only)
▼
[__memory_read__] ▶ __planning__ (no model call for a single-node graph)
│
├─ direct ─────────────────────────────▶ skill graph │ __synthesis__
└─ retrieve ─▶ [__knowledge_plan__] ─▶ ┌ __domain_retrieval__ ┐
(only when the route │ __temporal_retrieval__ │ the lanes the
searches knowledge) │ __reasoning_retrieval__ │ turn's mix runs,
│ __external_retrieval__ │ and the web and the
└ __tool_retrieval__ ┘ tools: parallel Send
│
▼
__retrieval_join__ (deferred: once, after every branch)
│
▼
skill graph (planner-selected nodes) or __synthesis__
│
▼
__evaluator__ ──retry──────────▶ skill graph
│ ──retry_synthesis▶ __synthesis__
│ ──retry_retrieval▶ __knowledge_plan__ (gap-fill:
│ the evidence lanes, then the join)
▼
[__hitl__] ▶ [__memory_write__] ▶ END
A plain agent is a single-node graph, and the agent always answers. Triage's skip-the-skill-graph shortcut and the planner's empty dispatch exist for graphs with several skill nodes to choose between; on a single node they handed the answer to __synthesis__, which has none of the agent's tools, and a synthesis pass after one agent only rewrote its answer. So for a single node: use_skill_graph is always true, needs_synthesis always false, and __planning__ returns that node with no model call. A stored skill (pinned_node_ids) is never skipped either — it is the user's workflow. A chat turn that retrieves nothing is three model calls: triage, the agent, the evaluator.
What each customisation feeds
| Customisation | Where it enters | Which nodes use it |
|---|---|---|
Retrieval config (spec.retrieval, from Agent.config["retrieval"]) | GraphState.retrieval_config | gate (always_retrieve, respect_triage_web_route), the knowledge nodes (mode, budgets, targeting, agentic_max_iterations) |
Toolkits → builtin / webhook tools (spec.tools) + MCP servers | Worker tools / mcp_servers on the skill node's agent | skill nodes — so the agent, which always answers a chat; on a multi-node graph the planner recommends per-node tools via tool_guidance |
Skillsets → skill graph_definition | Skill nodes + edges on the builder | planner selects active_nodes; retrieval evidence is injected as <knowledge priority="primary"> into every skill node |
Persona (agent_name, agent_system_prompt) | GraphState fields | gate trivial replies, skill nodes, synthesis |
| Conversation history | context["conversation_history"] (skills) or state.messages (agents, as the unnamed messages); read by _history_entries | gate (standalone query rewrite + mention detection, _conversation_tail), planning, skill nodes and synthesis (_history_messages — see What a model is shown) |
System-node contract
__gate__is triage, the one place a request is classified (fe-core labels it "Triage"). It makes one call (TriageProfile, orScopedTriageProfilewithclarify_scope): where data comes from and, separately, how the task is shaped. The prompt keeps the two apart — the route is chosen by data source only, never by complexity. It resolves follow-ups into a standaloneretrieval_query, forces internal retrieval whenever the request names an attached KB or stored document, and — withalways_retrieve(default) — includes internal retrieval when knowledge bases are attached, unless a successful triage chose the web alone or judged the knowledge irrelevant (direct, since 28 October 2026); the model otherwise only adds external / tool sources on top. Triage is shown the tools the task can use (AgentGraphBuilder._triage_tools: a plain agent's own, its knowledge tools,ask_userwhere it may ask; every built-in on a graph of several nodes), and arelevant_toolsname outside them is dropped. Shown the whole registry, it had named tools the agent did not hold and some that do not exist. Since 28 October 2026 the field is aLiteralof exactly those names (_naming_only, one schema per tool set under the schema's own name), so constrained decoding can write no other, and a name function calling still gets wrong is dropped, not the profile. The task's shape goes toresource_strategy(source: "triage") through the topology rules above (_task_shape): complexity, whether the skill graph runs, whether a synthesis pass is needed, and (withclarify_scope) whether the request is ambiguous enough to ask about first, parking validated questions inpending_clarification. The call has a classification-sized output cap (_classification_cap): 4,096 tokens for a model whose reasoning counts against it (ModelCapabilities.reasons_before_answering: gpt-oss, OpenAI's reasoning families, Claude with thinking, open-weight "thinking" models; a healthy gpt-oss triage writes about 1,850), and 2,048 for one that answers straight away (1,536 for one run; a scope check of four questions reached 1,381). On the answer-sized cap a gpt-oss triage that kept reasoning ran to 16,384 tokens and 42 s; on 4,096, Qwen3 235B Instruct (healthy profiles 120–990 tokens) ran on to the cap on 6 of 31 scenario turns, 30–39 s each. When it fails nothing asks again: the route comes from_fallback_route, the shape from safe defaults (source: "default", the full pipeline,scope_checkunavailable), anderrorssays so in one line, with the reason. The trace says why (28 October 2026): the gate'striagerecord carriesfailure(StructuredResult.failure_record), and a reply cut off at the cap carries its shape (app/services/cut_replies.py): its length, the schema field it stopped in (relevant_tools[],resource_notes), whether it stopped inside a string, and whether its tail is whitespace, one item repeated (and how often) or running text. Keys and counts only, never the reply's words; the same line is logged. A reply that ran on in whitespace is read (28 October 2026, run 5):cut_replies.closedcloses what such a reply left open — only when it stopped outside a string — andstructured_outputreads the result whole and validates it (StructuredResult.recovered = "closed", logged; the gate'striage.recovered). The shape says what the whitespace was (blank: newlines, spaces, tabs, mixed). Decisions first (29 October 2026, run 6): the closing never fired, because every runaway of runs 5 and 6 (seven turns) stopped inworth_remembering— then the first field of every triage schema, since pydantic lays fields out from the last base and_MemoryCuewas listed last. Qwen3 235B wrote whitespace before any of the profile; the one agent whose schema opened with an enum (time_window) never ran away. The bases are now listed last-field-first (TriageProfile(_MemoryCue, ResourceStrategy, RequestProfile), the cue mixins first), sorouteis asked first and the cues last, and the quality check listsgapsandreasoning_errorsbeforepassedandscore. A key the reply never gave a value is dropped, never given one, so a runaway at the last field reads with its default and one before the decision still falls back;CutShape.value_writtensays which. No svc-ai or svc-core schema may open with a boolean (test_no_schema_opens_with_a_boolean,test_it_does_not_open_with_a_boolean).Why one node (October 2026). Since Phase 2 one triage call answered both questions, and
__recon__re-read it: a pure function of the gate's output, a superstep, and a stage named "Reconnaissance" that scouted nothing. When triage failed, recon asked a model the same question again in another prompt (a "task-complexity classifier" with a second copy of the scope check) — an extra ~6 s call on a guess. On "render pdf of different climbing knots" that call asked for the PDF's file name, gave "the knowledge base lacks it" as a reason, and recommended one knot of a plural request. Its work moved into the gate node (_task_shape,_after_triage); stored traces keep their__recon__stage, which fe-core still draws.A web-only triage stands (
respect_triage_web_route, default on, 18 October 2026) when triage answered, the inventory it read was complete and not empty (kb_inventory_complete), and the person's own words name no attached document, knowledge base or file. For a web-only triage the mention check reads only the request, triage's standalone query and the person's previous message, never the agent's previous reply, which names the agent's own sources. On every other route it reads the whole previous exchange. With knowledge attached a failed triage never yields a web-only route. On a plain agent the kept route becomesdirect, so the agent searches the web itself and no internal retrieval runs. See Which turns search the knowledge.A turn's attached documents are not the request (24 October 2026, Attachments). They are
GraphState.attachments, apart frominput. Triage reads a manifest of them (names, sizes, a preview, never a body) and routes a request about themdirect; the knowledge default does not override that (_attachment_route_hold), a failed triage answers from them, and a message of documents alone is never trivial. An attachment's name, or a file name only an attachment mentions, is no knowledge mention. The gate's frame records how each reaches the agent (attachments, fromattachment_plan: whole, listed or unavailable).Triage judges a knowledge base by its purpose (
prompts.GATE_KB_PURPOSE_RULE, in the inventory's retrieval rule and in decision step 2): what it is for, from its description, not a document or section whose name shares a word with the request.The inventory says whether it is complete (
GraphState.kb_inventory_complete, on the frame): False when a count, a listing or a graph schema could not be read, and fe-core says so beside the route.The frame says what triage chose (
result.triage, fromGraphState.triage_route):{route, retrieval_type, source, adjustments}. That is triage's own route before any rule changed it,sourcetriageorfallback, and one line per change, each ending in the resulting route: "the request names document 'Annual Report 2024.pdf' → retrieve · both", "knowledge default (always_retrieve; the knowledge inventory is incomplete) → retrieve · both", "plain agent: it searches and calls its tools itself → direct". It is absent on a trivial turn.result.route/retrieval_typestay the final route: for CHAINR Bot on a web-only triage,direct/internal, with triage'sretrieve·externalbeside it. fe-core's gate stage shows "Triage chose: …" and each adjustment.
__clarify__asks triage's scope questions (and any skill step's mid-taskask_user) withinterrupt()and appends the answers tostate.inputas a<clarified_scope>block, so every later node works to the scope the person chose. Memory is the exception: it reads and writes the request as sent (GraphState.request_before_clarification, set by the first clarification) with the answers as[clarified: …](see Memory). It makes no model call, so the replay a resume triggers asks exactly what was shown. See Human in the Loop.__planning__produces theExecutionPlan(retrieval_focus,tool_guidance,active_nodes, and anode_plansentry — goal, expected output, success criteria — for each dispatched skill node). An emptyactive_nodesskips the skill graph and lets synthesis answer from the evidence directly; the plan then has no node plans, which is valid. System nodes are never planned, so they work tooverall_goal. A plan that fails anyway dispatches every skill node and records why inerrors. For a single-node graph it makes no model call (SINGLE_NODE_PLAN_NOTE): its only decision there was whether to run the agent, its node goal restated the request, and its tool guidance named tools the agent already has.The knowledge nodes run the retrieval pipeline described in Knowledge Retrieval, in lanes (Searched in lanes):
__knowledge_plan__plans the search once (RetrievalPipeline.plan; with several lanes one call writes each its own queries), a lane per kind of knowledge in the turn's mix searches and judges its own knowledge bases (__domain_retrieval__,__temporal_retrieval__,__reasoning_retrieval__;RetrievalPipeline.search), side by side with__external_retrieval__and__tool_retrieval__, and__retrieval_join__packs them (RetrievalPipeline.pack). Only the join writesretrieval_context(Markdown evidence with stable[S#]ids: the knowledge, then the web's section, then the tools') andretrieval_citations(structured provenance); the branches stage theirs (knowledge_plan,<kind>_lane,web_context,tool_context) and the join clears them. Until 26 October 2026 one__internal_retrieval__node did all of it; the name stays in stored traces and in the model-facing text that names the stage. Passages the relevance judge rates belowmin_relevanceare dropped (Relevance). Its query planner and each lane's judge run with their own output caps (4,096 and 8,192 tokens,_capped_llm). Inhybridmode the agentic gap-filling pass runs only when the evidence falls short (nothing found, a failed search, a named document missed; no passage count), for at mostagentic_max_iterationsrounds — and not at all when the judge ruled out everything the search found: the knowledge does not cover the request, the answering node is told so (KNOWLEDGE_NOT_RELEVANT_KEY→<knowledge_search>), and the evaluator sends no gap back to it.knowledge_searched(KNOWLEDGE_SEARCHED_KEYinstate.context) is set when the join handed on knowledge-base content: a pipeline success, an agentic success over a pipeline bundle or the knowledge tools, or an agentic failure that kept the pipeline's evidence. It is not set when the search found nothing, every passage was judged out, or there were no knowledge tools. Corrective retrieval reads it.retrieval_report(GraphState, on the join's frame asresult.report): the query planner's and the judges' failures (with several lanes, each named by its lane), search legs that could not run (degraded) and passages judged out; andlanes, how each lane fared in packing (the frame'sresult.lanes). A judge that failed leaves its passages unjudged and marked so, and the answering node (and synthesis) is told they were not checked.Corrective retrieval. On an evaluator retry with content gaps
__knowledge_plan__plans a search for those gaps only, run by the evidence lanes alone (a framework holds no missing fact, and_knowledge_can_fill_gapssends nothing back to frameworks alone), leaving out the chunks the evidence already cites (cited_spans); the join appends a delta section with continuing ids. When it finds nothing the agent is told the details are not in the knowledge bases, which says nothing about whether they can be found elsewhere.
__external_retrieval__/__tool_retrieval__gather web content and deterministic tool outputs; they can run in parallel with internal retrieval and their sections merge through theretrieval_contextreducer. Like the join's agentic pass, they are not streamed and their tool calls are stored under their node (28 October 2026; see Enough evidence, and the agentic pass).The live note names the web tool (
_live_data_note): a request for current information tells the agent to search the web now, naming its web tools, when it holds one. On a plain agent the web is the agent's own to search, and told only "use the tool" it answered from an empty news feed that the NCSC had issued no warnings.Skill nodes receive the evidence read-only plus the knowledge tools with an explicit "only for a detail the evidence lacks" instruction, so they can fetch a missing clause or entity without re-running retrieval.
__synthesis__consolidates the outputs of several skill nodes, with the evidence, into the persona's answer with inline[S#]citations. It never runs after a single node. It is told what the agent is told — the date, the agent's name, its persona — because on a multi-node graph's direct-answer and planner-skip paths it is the answer. When nothing was retrieved and no skill node ran, it may answer from the model's own knowledge.__evaluator__checks coverage and reasoning; severe failures re-enter the skill graph, synthesis, or corrective retrieval. A failed draft goes back to the knowledge bases (retry_retrieval) only when no web tool answered the run (source_ledger.web_answered, checked first), knowledge bases are attached, the check named gaps, the judge did not rule out everything, and internal retrieval searched the knowledge this turn (knowledge_searched;_knowledge_can_fill_gaps). Otherwise it goes back to the agent to revise (retry, orretry_synthesiswhen the planner skipped the skill graph). Every gap in a failed draft used to send it to the knowledge when KBs were attached, so CHAINR Bot's failed news answer was "filled" from its user guide.It sees whole tool results. Each result is read whole up to 3,000 characters; past that its blank-line blocks share the budget, short ones whole and long ones cut to one shared limit (never below 400, marked
…), with those that do not fit counted (_tool_result_digest). A result carrying a render fence keeps 8,000. Until 18 October 2026 each tool message was cut to its first 800 characters, so results 2–5 of a five-result web search were invisible and correct headlines were failed as unsupported. Since 28 October 2026 the blocks that hold a figure the draft states (_draft_figures: amounts, percentages, decimals, ids; not bare years or one- and two-digit numbers) come first and whole, within the same 3,000, still in the tool's order: run 4 failed answers for an IBISWorld market size "not in any of the tool results" that sat further down the 8,000-character page than the check could see.It reads normalised markers. The draft is normalised as soon as it is gathered (
source_ledger.normalise_citation_markers), so gpt-oss's【n】are read as[n], its tool-output references are gone, and the verdict'sfinal_outputis normalised on every outcome. Its<citation_check>reads Sources sections as models write them (counted headings, unmarked bullets, link lines); see Citations.What it judges against (28 October 2026, from two scenario runs). Five of one run's 19 answers shipped failed on verdicts like these:
The date.
<current_date>opens its input with today's date and the day the week began (prompts.today(), the same line the agent, triage and synthesis read). Without it, a payroll plan dated from today failed as "fabricates a current date", and "this week" was read as the past seven days.Its earlier checks. On a revision,
<earlier_checks>lists what each earlier check of this answer asked for (GraphState.quality_checks, appended on every failure), the latest check's items numbered. Without them, a plan failed for stating a date and then for saying it had none, and a list of the NCSC's 10 Steps failed for being unverified and then for being incomplete.A revision is checked against what was asked of it, structurally (28 October 2026, after run 3). Told only not to, the check still raised new objections on every pass: one discharge answer failed three checks, each on different advice, and the loops were most of the run's cost. A revision's check now fills
RevisionCheckunder its own prompt (prompts.NODE_REVISION_CHECK):open_gaps, the numbers of the latest check's items still unfixed, andnew_errors, factual errors the revision introduced (never advice, analysis or general knowledge). Code builds the verdict from them (_revision_result): a number naming no item is dropped, and a revision can fail on nothing else.Facts, not advice (the first check, after run 3). The evidence audit is of factual claims: figures, names, dates, quotations, what a source, a law or the person's situation says. The agent's analysis, advice, proposals, interpretations and general knowledge are judged on soundness, never as "unsupported". An illustrative figure is a gap only when it is presented as the person's data. Coverage is of what the request asks at every complexity, so extras are critique. A closing offer ("Would you like me to…?") is never a question in place of the answer.
Each gap has a kind, and code decides what fails (28 October 2026, after run 5). Told in words, the first check still failed the agent's own work three passes running: a payroll plan for its own dates and thresholds, an offsite agenda for a venue's availability nobody asked about, and claims cited to a search result whose page returned 403 though its snippet held them. Each false failure cost two more tool loops. Every gap is now an item
{issue, kind}(graph.Gap), its kind fromprompts.GapKindwith guidance per kind (GAP_KIND_GUIDE, rendered throughvocab). Onlycontradicted,unsupported_fact,missingandworkingfail a draft (prompts.FAILING_GAP_KINDS,_split_gaps);own_work(analysis, plan, proposal, estimate, example),not_askedandpresentationare set aside. A bare string, an item with no kind or a kind outside the vocabulary ismissing, so older replies and scripts fail as every gap used to. The verdict'sgapsare the failing ones, in words, as before: the revision note,<earlier_checks>, the stored answer and next turn's planning read only them.EvaluatorVerdict.set_aside("own_work: …") rides on the evaluator's trace frame and is stored asmeta.eval_set_aside(the scenario export'squality.set_aside), never sent back to the agent. The prompt adds that a search result supports what its snippet says whether or not its page could be read.RevisionCheckis unchanged: it numbers only what failed.What the reply attaches, in full; a summary's problems back to the summary (29 October 2026, after run 6). The check saw an attached document as its title alone (
_document_note), so Research brief's summary failed twice on its claims about its own report, and each failure re-ran the whole skill (43 tool calls, $0.15 after the check); pdf-brief failed for "not referencing the PDF".<artifacts>now holds each document the reply attaches in full (_document_for_check: summary, key findings and body to 8,000 characters, a visual inside named as[chart: <title>], never its data), and both check prompts say a claim about what a document holds is supported when it holds it, and a document is attached whether or not the draft names it. History keeps the note: a model is never asked to copy a document. A failure whose gaps are all the summary's own (_summary_can_fix: synthesis wrote the draft, and no gap ismissing) re-runs synthesis alone (retry_synthesis, which already reads the revision note); amissinggap, or one whose kind went unrecorded, re-runs the skill graph. Kinds travel with the verdict (EvaluatorVerdict.gap_kinds), each check's record and the evaluator's frame, so a revision's open items keep theirs (_revision_result; a revision's new errors areunsupported_fact, a still-open reasoning error stays one).What the person gets, all of it (29 October 2026, after run 7). Three blind spots each failed a sound answer:
Every part of a document its PDF prints.
_document_for_checkshowed a document's summary, key findings and body only. Now it shows the subtitle, confidence, summary, key findings, body (to 8,000 characters), open questions and the sources list, in the PDF's order. Each source is numbered as the body cites it, with the id it has in<sources>whererender_documentbuilt the line from one (_document_sources_for_check). In run 7 the command turn's summary named the brief's open questions and was read as contradicted, so Research brief re-ran twice. pdf-brief's body cited[1]against a list the check never saw.tests/agents/test_check_sees_the_reply.pyfills everyDocumentSpecfield and requires each in the PDF's text and the check's view, so a new field fails it until it is shown.An attached document is never missing, in code. Told in words, pdf-brief's check said "the draft does not include the PDF attachment" in all three checks, and shipped failed at 50. When the reply carries a document, a failing gap that says the document itself is absent (
_ABSENT_DOCUMENT_RE: not attached, not included, no PDF, with the document as the object) is set aside aspresentation(_set_aside_absent_documents), on the first check and a revision's. Gaps about what the document holds still fail. Both prompts say CHAIN-R attaches it as a downloadable PDF and the draft never includes or links it.Markers that name no source are code's. The check reads the draft without them (
answer_sources.for_check): ids the run never handed out and placeholders are taken out, and ids it did hand out stay for<citation_check>. With no ids handed out, nothing is sent back (finalisedrops them as the answer ships). With ids handed out, an unknown one is still sent back with the ids the agent may use. a-acronym wrote[S3]on a direct turn, the check called it unsupported, the revision took it out, and the revision check kept the item open, so a correct answer shipped failed at 40.
A request about now gets something current (29 October 2026, after run 7). c-ai-rules ("What's new in UK AI regulation this month?") was marked live and told to search the web; it answered from the statute text that no new regulations came into force in October 2026, with no tool call, and the check passed it at 92 (run 6 had searched eight times). Now code records a failing gap,
missing(UNSEARCHED_LIVE_GAP,_unsearched_live_gap,_with_live_gap), whatever the check made of the draft, when all of these hold: triage marked the request live (LIVE_DATA_KEY), a step holds a web tool (_searches_the_web), no web tool ran (source_ledger.web_searched, which counts a search that found nothing), and the evidence held no dated passages (DATED_KNOWLEDGE_KEY). The revision note tells the agent to search. On a revision the gap is taken out once a search ran, and kept, failing the answer, if none did. Corrective retrieval never answers it (_knowledge_can_fill_gaps): the knowledge already answered with what was indexed. Pinned bytests/agents/test_live_without_search.py.The method is the agent's. The
<frameworks>note no longer says "check that it applied one". A draft fails only for misapplying a method it uses, or for crediting a framework with what it does not say. It had failed a plan for not using the spiral model.The whole evidence.
<retrieved_knowledge>and<frameworks>are read whole: the packer bounds them. They were cut at 12,000 and 4,000 characters, so claims were judged unsupported by passages the check had never been shown.The reviser's note says a claim the check found unsupported is taken out or marked unconfirmed, never stated again. One answer was revised three times, searching each time and restating the same figures.
One id per document.
source_registry.source_keykeys a document by its id alone. A hit thatsearch_knowledgereturned carried no knowledge base, so a packed passage came back under a second id, and the check called a correct citation fabricated.Markers (
answer_sources). Grouped ids ([S1, S2]) are verified like single ones (source_ledger.SID_GROUP). When the run handed out no ids, every[S#]names nothing:finalisedrops it, and since 29 October 2026 the check neither sees it nor sends it back (answer_sources.for_check). Placeholders such as[knowledge]are dropped.A malformed tool call is left out (
written_calls.without_invalid_calls, 28 October 2026): a call whose arguments were not a JSON object is taken out of the reply — its content block andinvalid_tool_calls— and the model is told it could not run, after the round's results, or asked once to call again when nothing else ran. Sent back as it was, one made Bedrock refuse the next request ("toolUse.input is invalid"), and the turn failed mid-revision with no check after it.A reply with no words outside brackets (
written_calls.holds_no_answer, such as.followed by[Applied framework: …]) is sent back once from the tool loop, with the tools still bound or after the last round. A short answer has words, so it is not sent back.
Pinned by
tests/agents/test_quality_check_input.py(through the real graph),test_answer_sources.py,test_source_ledger.py(TestGroupedIds),tests/util/test_source_registry.pyandtest_tool_turn_text.py.It reads the request in its conversation: the two turns before it (
<conversation>: the latest answer up to 1,200 characters, other messages 400) and the gate's standalone rewrite (<resolved_request>), told that earlier turns are context only (October 2026, Conversation Quality Review). It used to see the request alone, so "make it shorter" or "the second one" was judged without what it referred to.Citations are verified in code, not left to the evaluator model (
app/agents/source_ledger.py). A source list is built from everything the run retrieved: pipeline retrieval'sretrieval_citations(knowledge-base documents, website pages, graph facts), plus every tool result read in full by its tool's parser (source_ledger.CITATION_PARSERS, keyed by exact tool name:web_search,url_fetch, the knowledge and document tools; a knowledge tool's source carries itsknowledge_base). Each entry of the draft's Sources section is then matched against it. A citation with a URL must match a retrieved URL; one without must name, as whole words, a retrieved document, page title, entity, knowledge base orS#id. The evaluator receives<sources>,<citation_check>(verified / unmatched per entry) and<retrieved_knowledge>, and is told never to remove a verified citation. Before this, it saw only<tool_calls>, each result then cut to 800 characters. Knowledge retrieval, which makes no tool call, therefore looked fabricated, and a knowledge tool's source list (appended at the end of its result) was never seen.
__memory_read__recalls what the agent keeps of this person (Memory): every preference, and the facts, ongoing work and earlier exchanges the request bears on — matched by words and, where memories are embedded, by meaning (app/memory/recall.py), against the request as sent (before a clarification, with its answers as[clarified: …]) and its standalone form. Nothing superseded, expired or from another workspace comes back, nor an episode of this conversation the history already replays; an older turn of a long conversation does, when the request is about it. When nothing passes, the request carries no memory block. Recall used to be the newest eight memories from other conversations, whatever the request. The block is held to the profile's size (memory_recall_limit,memory_block_max_chars), dated and tagged by kind, and redacted as the Input rules redact the prompt.__memory_write__keeps an episode of the turn — the person's request as sent (attachments named, not quoted; a clarification's answers as[clarified: …], never the<clarified_scope>scaffolding) and the gist of the answer, or the request alone when the quality check could not stand behind the answer — and, when the person's words carry a cue or triage flagged the request (worth_remembering), what one extraction call proposes and code validation keeps (app/memory/extraction.py): facts, preferences and goals quoted from the person's own words, corrections replacing what they correct. Everything kept is redacted as the Output rules redact the answer. The quality check's verdict is no longer appended. A summary is made when a model is there to write one (turns over 1,200 characters); otherwise the turn is cut to 400 characters of request and 800 of answer.
The trivial shortcut
__gate__ answers some inputs with a canned reply and no model call. Two kinds, because only one is safe mid-conversation:
| Kind | Examples | Short-circuits |
|---|---|---|
| Bare reply | yes, no, ok, great, later | only with no conversation — after "Shall I draft it?", "yes" is the whole answer and goes through the pipeline |
What a model is shown
An answering node — a skill node, or __synthesis__ — reads
[system, …earlier turns of the conversation, this turn's task]
and nothing else as messages (_history_messages, capped at _HISTORY_TURNS turns):
Earlier nodes' outputs arrive in the task content (
_aggregate_prior_results), evidence in<knowledge>, earlier tool calls in<prior_tool_calls>, artifacts in<artifacts>. None of them is replayed as a turn.<prior_tool_calls>(_tool_call_ledger), which the reviser and every skill node read, carries each result as the quality check reads it: whole up to 3,000 characters, else abridged block by block (on a revision, the blocks holding a figure of the answer being revised first:keep). It was cut to 400, so a reviser could not re-check its own web results and dropped the headlines. The ledger is capped at about 12,000 characters: the newest calls whole, earlier ones cut to their result's first line (at most 200 characters, marked[abridged]), and what still does not fit, or comes past 25 calls, left out. A first line counts both.state.messagesis a trace, not a conversation. Every node names the messages it writes (_name_node_messages, applied to every node inbuild()), so the caller's history is exactly the unnamed messages. A tool loop's model replies are unnamed when they come back from the worker; the wrapper names them before they reach state.System messages in the history become a
<conversation_notes>block in the node's system context, because Anthropic refuses a system message after the first turn.The history is fitted to the model (
app/services/token_budget.py, cost-control plan B1.3): inside its context window and below its long-context price tier, measured against this call's system prompt, tools and task. When it does not fit, earlier turns' pasted documents become stubs first (since the attachments work a turn's documents travel apart from the history, so only a block the boundary could not lift out is left to stub), then whole turns go from the start in blocks of four (so the kept history starts at the same message for several turns and its cache holds), then a newest turn too large on its own is cut. The model is told in a<history_note>in its request context, and the node'snode_endframe carrieshistory_turns_omittedinto the decision record's step. Direct model chat fits its conversation the same way (llm._build_messages).Cache breakpoints (
app/services/prompt_cache.py, B1.1): besides the system prompt, the end of the history is marked (mark_last) so the next turn reads the conversation from cache, and every tool-loop round caches up to its last block (tail_options) so the next round reads it — on Anthropic and on Claude via Bedrock, at most four marks a request. Triage and the quality check mark their own system prompts (structured_call(cache_system=True)); triage's no longer holds the conversation, which travels in its user message (prompts.build_gate_request).
Before October 2026 every non-tool message was replayed: the current question first, then the history, then each system node's status line, the retrieval summary and any error text — all as replies the agent had given. tests/agents/test_answer_context.py runs the compiled graph on a scripted model and pins the order above.
What a tool loop delivers
Every read of a model's reply goes through the reply's format (app/services/reply_formats, 19 October 2026). The format is one registered class per wire behaviour, chosen per route by ModelCapabilities.reply_format from the model the client reports (of_client / of_traced: LangSmith's ls_provider / ls_model_name, which every chat model and wrapper here forwards):
| Format | Routes | Where reasoning arrives | What is the answer |
|---|---|---|---|
inline_tags | open-weight models on Bedrock other than gpt-oss (Qwen), Groq, local servers | between <think> / <thinking> / <reasoning> tags, anywhere; or before a lone </think> when the chat template opened the block in the prompt | the text with those blocks removed, and nothing shown live inside an open one |
gpt_oss | gpt-oss on any route | the analysis channel as answer text, run into the answer with no break ("…Now produce final answer.Here’s a quick roundup…") | what it writes in the envelope (below) |
gpt-oss writes its reply in an envelope. Its system prompt (tool-less calls too, never a typed-output worker's) carries prompts.REPLY_ENVELOPE_CONTRACT: write the reply between <reply_to_user> and </reply_to_user>, and keep your working outside. The answer is the text after the last opener, up to its closer or the end (cleaning.envelope). It is the last opener because analysis can name the tag before the reply uses it, and it runs to the end because a reply cut off at the token cap may not have closed it. Its earlier answers are replayed in the envelope (ReplyFormat.wrap_history), so the conversation shows it answering that way; the wrapping is deterministic, so the history still reads from cache.
A gpt-oss reply without an envelope falls back to cleaning.answer, logged as a WARNING:
harmony markers (
<|channel|>final<|message|>, oranalysis…assistantfinalwith the brackets stripped);tagged blocks;
the seam: a stop straight after a whole lower-case word, then a capital or a markdown opener, within 1,500 characters, after at least three words of plain prose. Apostrophes are Unicode (
'’ʼ) — #396's version took only an ASCII', so "Here’s" never matched and the second incident's analysis shipped. Dotted names, abbreviations, markdown or code before the seam: kept whole.
The tool loop (Reader.tool_loop_answer):
A model whose tool-turn text is answer (
answer_prose_in_tool_turns: Claude) delivers all of it, in order.Any other model delivers its last message read by its format.
An empty last message is filled by
ReplyFormat.tool_turn_answer: the tool-turn text for GPT-style models ("Here is the chart." beside a render call), and for gpt-oss only a reply it closed in an envelope there — its tool-turn text is analysis.A render fence written in a tool turn is never lost: the graph restores every fence a tool returned (
_restore_missing_artifacts).A fence written by hand is made again by its tool (28 October 2026,
agents/answer_artifacts.remake_written_fences, before the quality check reads the draft): a visual fence no tool returned this run is turned back into its tool's arguments (FENCE_ARGS, one entry a kind, each pinned to round-trip its tool's own fence) and the tool called; its fence replaces the one written (and joinsartifacts), and one the tool refuses is removed, so the check sees the visual missing. Asked to "make it a pie chart", the first capabilities run's agent had copied its earlier answer's fence.An earlier answer's visuals are replayed as written; its documents as notes (
graph._earlier_answer). For one day (28 October 2026, Z4) visuals were replayed as notes,[chart drawn by render_chart — …: <spec>], and the rendering hint described them. Scenario run 5 copied that note format into answers: the pie follow-up asand the note (passed by the check at 95), and the map turn, with no history at all, as "[map drawn by render_map]" from the hint's example. The remake above makes a copied fence harmless, so the fence is shown again, the hint names no format, and a copied note is turned back into its fence (answer_artifacts.notes_to_fences, in history and in a draft) and re-made, or removed when it holds no spec. A document stays its one-line note: it runs to 6–8,000 characters.A link or image to no web address goes (
answer_artifacts.drop_dead_links, outside code):and[brief.pdf](sandbox:/mnt/data/brief.pdf)— what a model writes for a file it imagines it made — open nothing; a link keeps its words. Citation anchors, mail and phone links stay.
A tool call written out as text is sent back (app/agents/written_calls.py, 20 October 2026). CHAINR Bot on gpt-oss answered a quality-check revision with a JSON object shaped exactly like render_document's arguments: the person got the arguments, and no document was made. Two things invite it:
at the round cap (
max_iterations, 10 for a plain agent) the closing call runs with tools unbound, and langchain-aws writes earlier calls into the text as[Called <tool> with parameters: {…}];<prior_tool_calls>quoted the earlier call's arguments.
Now:
A final reply that is a bound tool's arguments as a JSON object (fenced or not), or that
[Called …]form (written_calls.written_tool_call: keys within the tool's arguments, its required ones present), is sent back once with the tools still bound (SEND_BACK). Never for a typed worker, nor when the request chose the answer's format (answer_format_requested, fromOUTPUT_FORMAT_KEY): JSON asked for may look like a tool's arguments.The cap's closing call says tools are gone and asks for prose (
TOOLS_SPENT). A written call there gets one more call (TOOLS_GONE); a second ships as written, with a WARNING, for the quality check to read.<prior_tool_calls>lists a document call by its title, with the tool's note on it (images it could not embed), never its arguments or fence (_tool_call_ledger). That body was up to 60,000 characters a reviser copied.
Pinned by tests/agents/test_written_calls.py, through the real tool loop.
A tool that raises is a failed call on the record (28 October 2026). The first capabilities scenario run asked for a plot and a graph, and both answers said rendering had "a technical issue", with no tool call in the trace. Two faults lay under that:
The items arrived as models. LangChain validates a call against the tool's
args_schema, then passes each nested item to the function as the schema's model (_PlotSeriesItem), not the dict the model sent.render_plotandrender_graphread their items with.get(), so every call raised.render_chartdid too whenever it was givenseries. They now take their items throughregistry._plain, as dicts with unset fields left out. No test had called any of the three:tests/tools/test_builtin_tools.pynow invokes every general tool throughainvoke, as the tool loop does, with nested items, and checks each render tool returns its fence.A raised call left no trace. It fires no
on_tool_end:ToolNodehands the modelError: … Please fix your mistakes., and nothing else saw it._stream_graphnow sends atool_callframe foron_tool_error(failed_tool_frame: statuserror, previewfailed (<class>), never the error's text), andsource_ledger.tool_failedreads that wording as a failure. A pause (ask_user'sClarificationRequested) is none.
Pinned by tests/agents/test_failed_tool_frames.py, through the real graph's stream.
Fewer rounds (28 October 2026). Tool-loop rounds were 55–60% of every scenario run's spend: each round sends the whole prompt again, Qwen on Bedrock takes no cache marks, and it made one call a round (74 calls in 77 rounds). Now:
A tool past its call limit is offered no more.
web_search,url_fetchandgeocodeeach keep alimits.Budgeton the tool (attach) and word their limit throughapp/tools/limits.py(reached).run_with_toolsoffers none already spent (an earlier pass of the same run used it: run 5's pdf-brief made six moreurl_fetchcalls across its revisions), withdraws one as soon as its budget is used or it reports its limit (spent), rebinds the rest and says so (withdrawn_note); with no tool left, the model answers unbound. In run 4 an agent made nine more calls after both web tools had said "call limit … reached".read_documentreads a part at a time (12,000 characters from an offset,registry.READ_PART_CHARS; the paging isapp/util/text_pages.py, shared withread_attachment).Independent calls in one turn were asked for in both tool-turn hints for one run (Z3) and removed: Qwen's calls per round went from 0.96 to 1.03 while its calls rose from 74 to 90.
Pinned by tests/agents/test_tool_limits.py (the real loop and the real url_fetch) and tests/tools/test_knowledge_tools.py (TestReadDocumentInParts).
The prompt says what the loop does: prompts.tool_turn_hint gives Claude TOOL_TURN_HINT ("delivered verbatim … never narrate"), and every other model TOOL_TURN_HINT_FINAL_ONLY ("only your last message is delivered").
Every exit reads through the format:
the tool loop, an answer without tools, and the max-iterations wrap-up;
continuations: fragments are joined first, then read once, so an envelope one fragment opened and its continuation closed reads as one;
typed-output repair;
_SystemWorkerand every role worker (base.reply_text);memory summaries, which are also tagged
reply_formats.UNSTREAMED_TAGso their text never streams;direct model chat (
engines/model.py, by catalogue identity: the LiteLLM path holds no LangChain client);the trace. The tool loop keeps two lists.
current_messages, sent back to the model, are as it wrote them.new_messages— the trace, which reaches skill-run steps and the batch API'smessages— areReader.tracecopies: no reasoning blocks, no commentary, tool turns keeping their tool calls and only text that is answer.
The stream shows only answer. _stream_graph feeds every model call's chunks to its node's filter (NodeStreams). There is one filter per node run, not per call, because a continuation is a new call carrying on the same answer. It applies the format's own rule as the text arrives (ReplyFormat.visible), so:
gpt-oss shows nothing until its envelope opens, then the reply as it is written;
an inline-tags model shows nothing inside a block;
a typed model's commentary never streams.
A tag's first characters are held back until they are known to be one (x < y is not held). When a call ends, the filter settles on exactly what answer() makes of it: {"type": "token_reset", "worker_agent_slug": <node>} and the answer again when what streamed was not it, and a reset for a turn that called tools on a model whose tool-turn text is not answer. The frame means the node's text since it started, or since its last reset, was not answer:
svc-core drops that text from the answer it falls back to, from the node's stored segment, and from what a failed or stopped turn is stored as — agent chat and model chat's Stop alike (
ai_client.astream_execute,_invoke_model_streamed, the router's_on_trace). It never stores the frame in the trace.fe-core clears the preview (
util/tokenReset.ts).A redaction rule's
StreamGuarddrops what it was holding back for that node.
The quality check counts working as a gap. NODE_EVALUATOR: text the agent wrote to itself (planning what to write, notes on tools, sources or citations, a draft before the answer) is not part of an answer; it is a gap, never a presentation issue. It had passed the second incident at 92 as "only a presentation issue". This is a safety net, not the defence: the evaluator often runs on the same model.
Telemetry. Each delivered answer logs which format read it and how (reply_formats.log_reply; a gpt-oss answer without its envelope is a WARNING), and the agent's span carries reply.path and reply.removed_chars.
The probe (python -m app.diagnostics.reply_probe, run by hand on a deployed host, a few cents) records how a route's replies arrive. It covers streamed or not × without tools or with one scripted search × reasoning_effort none/low/medium/high × envelope on or off, plus LiteLLM's route. Each case prints one JSON line of block types, sizes, the first 80 characters of each text block, the stop reason and the markers found, and never the full text or credentials. Whether Bedrock returns gpt-oss's reasoning as reasoning_content once reasoning_effort is set decides whether the envelope stays on; svc-ai sets no effort for gpt-oss today (supports_effort false).
Pinned by:
tests/services/test_reply_formats.py: every format, the second incident verbatim (U+2019), and stream parity at every split point;tests/agents/test_tool_turn_text.py: both incidents through the tool loop and through a real streaming model in a compiled graph with the stream guard;tests/memory/test_migration_30.py;svc-core's
tests/test_token_reset.py.
Structured output
Every step that asks a model to fill a schema — triage (TriageProfile / ScopedTriageProfile), planning (ExecutionPlan), evaluator (EvaluatorResult), the retrieval query planner (QueryPlan) and reranker (RerankResult), PlannerAgent (ProposedPlan), a typed worker's output and its repair, an LLM router's choice, and a run's answer held to the JSON shape its request declared (all three since 20 October 2026, below) — goes through one function, app.services.structured_output.structured_call. It never raises for a bad reply; it returns a StructuredResult (value, method, attempts, failure), and unwrap() raises model_errors.StepFailed with the one-line failure for a step whose except degrades.
Native constrained decoding when the model takes it (
model_capabilities.native_structured_output). On the vendors' APIs: GPT-4o and later, the GPT-5/6 and o-series reasoning families; Claude Haiku 4.5, Sonnet / Opus 4.5 and later, Fable, Mythos. On Bedrock, where its card lists "Structured outputs" (the route's flag): Claude Haiku 4.5, Sonnet and Opus 4.6, gpt-oss-120b and Qwen3 235B, not Claude 5.x. The schema sent isstrict_schema(Schema)(app/util/model_output.py, shared with svc-core byte for byte): every property required,additionalProperties: false,$defsinlined, and nothing buttype/properties/required/additionalProperties/items/enum/anyOf/description. Defaults and bounds stay out — OpenAI's strict mode refusesdefault— and stay enforced by the pydantic class the reply is validated against. It is bound as an OpenAI-styleresponse_format, which langchain-openai sends unchanged (Chat Completions) or astext.format(Responses API), langchain-anthropic converts tooutput_config.formatbesideeffort, and langchain-aws to Converse'soutputConfig.textFormat. A decoded reply cannot omit a field or invent an enum value.Function calling otherwise: for other models (Claude 5.x on Bedrock among them), for a schema strict decoding cannot express (a request's own JSON Schema that leaves a field optional or uses a keyword outside the strict set,
model_output.is_strict_shaped), and when a provider answers the native request with a 400 (19 October 2026):A refusal of the schema is remembered, for that model and schema, for the life of the process (
app/services/provider_refusals.py,model_errors.refused_schema: a 400 naming the schema,outputConfig,response_formatoroutput_config). Any other 400 — a prompt too long for the window — falls back for that call alone; it used to switch the schema to function calling for good.The refused request is no attempt. Function calling gets its own try and the corrective retry after it; it used to get one try and no correction.
The schema tool is forced only where the model takes it (
ModelCapabilities.forced_tool_choice, the route's flag on Bedrock: Claude 4.5 and 4.6). Elsewhere it is offered and the model is told to call it (structured_output._call_the_tool), and an object it writes as text instead is read. Claude 5.x thinks by default and refuses a forcedtoolChoicewhile it thinks, which langchain-aws would have sent on every Claude 5.x fallback; Converse offers gpt-oss and Qwen no tool choice at all. A model that refuses a forced call anyway (model_errors.refused_tool_choice) is offered the tool from then on.
Salvage. Native replies are read with
safe_json.loads_lenient(a fenced or prefixed JSON still parses); under function calling the raw tool-call arguments are validated even when LangChain's parser gave up. Not a reply that ended unfinished (18 October 2026): one cut off at the output token limit (finish_reasonlength,stop_reason/stopReasonmax_tokens, a Responses APIincomplete), at the model's context window (model_context_window_exceeded) or by a content filter (content_filter, Conversecontent_filtered). That is read whole withsafe_json.loads_exactor not at all, on both paths. Under function calling the client's own parse is not trusted, because a streamed reply's arguments are closed up for it; only raw argument text that parses whole is accepted. An acceptance logs[structured:<purpose>] <Schema> reply hit the output cap; accepted only because it parsed whole(or "the context window", "a content filter"). Otherwise the failure reads "the reply was cut off at the output token limit" (or "…at the model's context window", "…by the provider's content filter"). The relevance judge's cut-off{"scores": [{"index": 0, "relevance": 1.0}, {"index": 1, "rel…had been salvaged asRerankResult(scores=[]): a judge that rated nothing, so the relevance gate stood aside in silence.RerankResult.scoresis now required (a decision), and the reranker reports the failure.One retry that says what was wrong — the reply is sent back with its validation error ("ExecutionPlan did not validate: task_summary (missing)"). Not after a refusal or a reply that ended unfinished, where asking again gets the same answer.
Fatal provider errors raise
ModelUnavailableError(see Failure handling).
The calls carry STRUCTURED_OUTPUT_TAG, and _stream_graph drops their tokens: a natively decoded reply is JSON text, which is the pipeline's, not the person's. Since 19 October 2026 they are sent whole, never streamed (structured_output._unstreamed, a disable_streaming copy of the client): under a chat turn's astream_events every call used to go out as a stream (ConverseStream on Bedrock), whose tokens were thrown away and whose tool-call arguments were parsed as partial JSON.
Typed worker outputs (20 October 2026)
A skill node with an output schema (interface.outputs, interfaces.build_output_model) is filled like any system step. Its model inherits WorkerOutput (a ModelOutput), so it decodes natively where the route can:
An
objectfield travels as JSON text ("a JSON object, written as text"), read back exactly (safe_json.loads_exact) and returned to the graph as the object. A free-form object is something strict decoding cannot express, so every typed output used to go to function calling.Reserved names are renamed on the wire (
reasoning→explanation,rationale→justification,thinking→considerations,trace→steps), and the graph still reads them under their own names.Without tools the node makes one structured call (purpose
<worker>.output): no free-text pass, noOUTPUT CONTRACTin its system prompt. A reply that never fits is the declared defaults plus_error, and the graph flows on.With tools the tool loop answers as before, told the contract, and its final message is read whole or as its one fence, never an object dug out of prose (
interfaces._candidate_json_blobsis gone). Anything else is repaired by one native structured call (<worker>.output_repair). No continuation is asked of a typed answer, and gpt-oss's envelope is not looked for in it (reply_formats.whole_json).
The router's choice (20 October 2026)
An LLM router edge (RouterAgent) used to ask for a node name in prose and scan the reply for one. It now fills RouteChoice_<hash> (next_node: Literal[<its candidates>], basis), built once per router from its candidates (vocab.listing in the ask), purpose route. The choice is stored as a RoutingDecision, so route_from_state reads it rather than asking again. A failed choice goes to the first candidate with confidence="low"; no candidates ends the run.
A request's own shape (20 October 2026)
A request may ask for its answer as JSON: output_format="json" with an output_schema (a chat's chosen format, a dashboard tile's reply schema). The answering node is told so in its <request_context> (llm.build_format_instruction), but a graph's answer is a tool loop, a revision or a synthesis, none decoded to it. So the finished answer is held to it in the engine, before the run's Output rules (app/inference/output_shape.py, on the batch response, the stream's done frame and a HITL resume):
An answer already in shape costs nothing: JSON that parses whole, or the one fenced block it is, and with a schema, matches it.
Otherwise one structured call rewrites it (purpose
reply.format) on the run's own model: the agent's, or a skill's override or default model. The schema is aJsonShape(app/services/json_shape.py): reduced to Bedrock's subset (bedrock_json_schema), decoded natively when it is strict-shaped, offered as a tool otherwise, checked by a subset validator that names a path, never a value. svc-core still validates the reply against the class it wrote the schema from.Failing that, the answer goes as it was, with the problem in one line as
output_format_erroron the response context and the done frame.
Only JSON is checked: YAML, CSV and XML stay as the instruction asked. What the answer cites (cited_citations) is read from the answer as it was written. tests/test_structured_replies.py keeps it this way: JSON is asked for in prose only by build_format_instruction and a tool-loop worker's contract, json.loads reads no reply (each remaining call says why), and the lenient reader is used only by structured_call's salvage and a skill's parse transform.
A native sibling (20 October 2026, off)
Claude 5.x on Bedrock decodes no schema natively (its card), so an agent on it fills every structured system step by function calling. With NATIVE_STRUCTURED_SIBLING on (svc-core, off by default), a native sibling makes those calls instead:
svc-core chooses it per turn (
app/services/native_sibling.py), beside an Economy profile's lighter model and from the same inputs: the same maker's model, in the same region, that decodes natively (the catalogue'sdecodes_natively), with vision where needed, never one a rule in force names; nearest in tier, then cheapest. It stands in for the lighter model when Economy chose one, else for the turn's model. None when a person chose the model, or the model already decodes natively. Every path that builds an agent request sends it (agent_spec.build(structured=…)→structured_model): chat on both paths, evaluation cells and dashboard tiles.svc-ai checks it again (
app/services/native_sibling.py): it rides the run config (run_config, so batch, stream and resume carry it, as the source registry does), andstructured_callhands a call to it only when the call is a system step's (stand_in=True, the default; a typed worker's own output passesFalse), the schema is strict-shaped, the caller would not decode it natively, and the sibling is the same provider, in the same region (inference_routes.data_region; unknown never matches), and native on its route. It takes the caller's temperature and output budget, within its own ceiling.It is given up for the run when it cannot be built or the provider refuses it outright (
ModelUnavailableError, but not a spend limit, which the caller's model would meet too); the call then goes to the caller's model.Metered under its own model, step by step like any call. The ledger is unchanged: the turn's cost already includes every call.
Why off. On today's catalogue Haiku 5.5 and Opus 5 (EU) can drop only to Haiku 4.5, about ten times Haiku 5.5's price per token, whose Bedrock end of life may now come at any time; Sonnet 5 (London) drops to Sonnet 4.6. Unmeasured. The setting is part of CHAINR Bot's benchmark key (
benchmark.pipeline_key), so turning it on re-runs the bot.
Pinned by svc-ai tests/services/test_native_sibling.py (a Haiku 5.5 agent with a Haiku 4.5 sibling through the real graph, read off the meter; another region ignored; a native model untouched; given up on a refusal) and svc-core tests/test_native_sibling.py (the choice, the request, every path).
Strict tool use (on for gpt-oss and Qwen3, 20 October 2026)
A tool call is structured output too: a name and arguments. On a Bedrock route that holds tool arguments to their schema (ModelCapabilities.strict_tools, the route's flag, set where the structured probe measured it: gpt-oss-120b and Qwen3 235B; the Claude 4.5 / 4.6 routes wait for Anthropic access and a run) and with STRICT_BUILTIN_TOOLS on (the default), the tool loop (BaseAgent.run_with_tools) binds wire.for_binding(tools, llm): each tool the platform wrote (wire.platform_owned, set by resolve_tool, general_tools and make_knowledge_tools, carried by a scripted stand-in) as a strict spec of strict_tool_schema(args), everything else as it is. ToolNode still runs the tools themselves, so pydantic still checks what the strict schema states only in words. A refusal is retried with the tools as they are and remembered (wire.refused, Feature.STRICT_TOOLS). The probe (app/diagnostics/structured_probe.py) found no compile cost a turn would notice on either route, nor a recompile when a set is reordered or grows: its results are in docs/system/deployment/bedrock-migration.md.
Model-facing schemas
Every schema above inherits ModelOutput (app/util/model_output.py, re-exported by app/services/structured_output.py):
Decisions are required; everything that is empty in the normal case has a default. A model may omit
node_planswhen it dispatches nothing — it was told to. A list whose emptiness is itself a failure (ProposedPlan.steps) stays required, so a reply without it is sent back once.nullon a defaulted field reads as the default. One such value used to fail the whole object.A malformed list item is dropped, not the object (
OnErrorOmitonnode_plans,clarifying_questions, rerankscores).Near-miss values are read: a
tool_guidancegiven as the old{node_id: tools}map, a loneactive_nodesstring, a score of85.5,"85"or0.85, a rerank relevance on a 0–10 scale.Strict decoding must be able to express it: no
dict[str, X]maps (Anthropic's schema transform turns one into an object that can only be{}; OpenAI's strict mode refuses it) —tool_guidanceis a list of{node_id, tools}items, stored as a map viaguidance_map(); noAny; no recursion.Only what the model decides.
PlannerAgentused to hand the model the domainExecutionPlan, with itsplan_id,status, timestamps and a free-formcontext; the model now fillsProposedPlanandto_plan()builds the domain object.No field named for the model's reasoning (
reasoning,rationale,thinking,trace): Claude 5.x can refuse such a field, billed, asreasoning_extraction. The gate's field isbasis, the planner'ssummaryandpurpose.
The tests:
tests/services/test_structured_output.pywalks everyModelOutputsubclass inappand fails one that strict decoding cannot express, that breaks OpenAI's strict rules, that names a reserved field, or that has a list with no default. It also checks, offline, the request each client actually builds (_get_request_payload) for Chat Completions, the Responses API and Anthropic, and drives the native / function-calling / retry / refusal / 400-fallback / fatal paths.tests/agents/test_system_node_schemas.pydrives each schema with raw tool-call arguments throughwith_structured_outputitself (tests/agents/scripted_model.py, which also answers a nativeresponse_formatwith JSON text). A new schema must add a minimal example there.Mocking
with_structured_outputto return a constructed object, as older tests do, never exercises this boundary.
Failure handling
Two kinds of failure, handled differently:
Fatal — the provider refused the credentials (401), the account may not use the model (403), the model does not exist (404) or the account has no quota left. No later call to the same provider could succeed, so every model-driven node re-raises it (
model_errors.raise_if_fatal) asModelUnavailableError. The stream ends with one error frame,{"type": "error", "message": <what an administrator must fix>, "code": "auth" | "permission" | "model_not_found" | "quota"}; the batch API answers 502 with the samedetailandcode. A model refused while the graph is being built (no route on this backend) gets the same frame (GraphBasedEngine._do_infer_stream); it used to end the stream with none. svc-core raises a frame with acodeasModelRefusedErrorand shows its message in the chat, and treats a stream that ends with no result and no error as a failure rather than an empty answer. Before, with a bad key, gate, recon (since merged into it) and planning each failed, wrote the provider's response body into the run, and carried on. The retrieval query planner and reranker still degrade on one: retrieval also runs without a chat model behind it (knowledge search), and in a turn the gate has already reported it.Everything else — a reply that does not parse, a 400, a timeout after the client's own retries — degrades the step, which records why in
state.errorsas one line (model_errors.describe: a pydantic error names its fields, a provider error its HTTP status). The text never goes into message content, the evaluator's critique, or the agent's memory. A person is never shown an exception's text: the model and pipeline engines' error frames saymodel_errors.user_message(exc).
| Node | On a degrading failure |
|---|---|
__planning__ | Dispatches every skill node with no plan |
| retrieval nodes | Empty (or partial) evidence; the run continues. A failed query planner falls back to the passthrough plan; a failed relevance judge keeps every passage unjudged and marked so. Both are reported on the frame (result.report) |
skill node, __synthesis__ | status = "error"; the run ends at the next router |
__evaluator__ | Passes the draft through with outcome = "unavailable" (no score) — the built-in quality rule then sends it to review |
__memory_write__ | Nothing stored; an unavailable evaluation is never remembered |
System steps have output caps. The system LLM is raised towards 16,384 output tokens (_ensure_system_token_budget), because synthesis writes whole answers. The quality check writes a verdict, never the answer, and is capped below it (_check_cap, 28 October 2026): 4,096 for a model whose reasoning counts against the cap, 2,048 otherwise. On the raised cap a revision check ran on in whitespace to 16,384 tokens and 128 s, and came back unavailable (run 5's illusions PDF). The retrieval pipeline's two structured steps write a few hundred tokens and are capped below it (_retrieval_step_llm): the query planner at 4,096 (_QUERY_PLANNER_MAX_TOKENS), the relevance judge at 8,192 (_RERANKER_MAX_TOKENS), on the first pass and the corrective one. Only max_tokens changes: each runs on the model it ran on before (the planning model, so the Economy profile's lighter model where it applies), at the same temperature and metering, and a smaller configured cap is kept. The agentic pass (a tool loop), synthesis and the other system steps keep the raised budget. Both helpers leave alone a model that does not declare max_tokens itself (_declares_max_tokens), such as a with_fallbacks wrapper: a copy would set it on the wrapper only, and _ensure_system_token_budget used to log such a copy as raised. Nothing builds fallbacks today.
Reasoning-effort control for system steps is deferred (Known gap 18). gpt-oss is not classed as a reasoning model in model_capabilities (_OPENAI_REASONING_PREFIXES lacks it), so it gets the 120 s timeout and takes no effort setting. With the caps, a reasoning model that keeps thinking fails at about 4k or 8k tokens instead of succeeding slowly.
A run's step limit is sized to the graph (AgentGraphBuilder.recursion_limit): every node once per pass, for the first pass and each revision the evaluator may ask for (_MAX_EVAL_RETRIES), plus a margin — 61 steps for Research brief's four nodes. LangGraph's default of 25 stopped a Research brief turn on its second revision, after the work was done (GraphRecursionError). Every run is given the limit per call (run_config: batch, stream and HITL resume); astream_events applies the default over a limit bound with compiled.with_config, which would have fixed batch runs and left every chat at 25. A turn that still fails late is stored as the text of the node that was writing, not every node's text run together (svc-core clears its partial at each node_end, as fe-core's preview does). Pinned by tests/agents/test_recursion_limit.py, which also checks the run fails at the default.
Serialisation
Every SSE frame is written by
app.util.safe_json.dumps, which never raises: datetimes go out with their UTC offset, UUIDs / Decimals / sets / models / messages are converted, non-finite floats becomenull, a cycle is cut. Its separators matchjson.dumps, whichrules.audit_done_framerelies on._result_textis the one way a node result becomes text — for the next node, the evaluator and the reply. A structured result goes out as JSON, never a Python repr.Model text is read as JSON with
safe_json.loads_lenient(the whole text, a fenced block, or the outermost{…}/[…]) — by the structured-call layer and by theparsetransform, which used to abort a whole run on fenced JSON. A reply that may be cut off is read withsafe_json.loads_exact: the whole stripped text or nothing, because the lenient reader finds a balanced span inside a cut-off value and reads it as the answer.Checkpoints (the state a paused run resumes from) are written by
app.agents.checkpoint.CheckpointSerializer. It registers every pydantic model and enum the agent modules define (STATE_MODULES) so they revive as themselves — underLANGGRAPH_STRICT_MSGPACK, the stated future default, an unregistered one comes back as a dict — and a write cannot fail: a value msgpack refuses (an integer beyond 64 bits, an object no encoder knows) is written as an encodable copy, or as JSON.tests/agents/test_checkpoint.pyfails when a module defining state types is missing from the list.A checkpoint outlives only a pause. A run's checkpoint thread is the conversation id, so every turn of a conversation shares it. svc-ai evicts the thread on every exit except a pause: finished, failed, rejected and stopped (svc-core's Stop cancels the stream, or the stream is closed at a frame). This holds on the stream (
_stream_graph) and batch (_do_infer) paths and on resumes, which run through_stream_graph. A stopped turn's checkpoint used to seed the conversation's next turn with every merging channel kept: its retrieved knowledge, a judge failure,knowledge_searched, web results and cited passages. The stream also closes its event stream before evicting, which stops the graph task; closed at a frame, that task used to run on, and could keep calling models, until it was finalised. Pinned bytests/inference/test_stopped_turn.py. One edge remains: a stream closed at a frame is evicted when the dropped generator is finalised, which CPython does at once unless a reference cycle delays it.
Research basis
| Choice | Source |
|---|---|
| Route by data source at the gate, complexity downstream | Adaptive-RAG — Jeong et al. 2024 |
| Standalone rewrite of conversational follow-ups before retrieval | Query rewriting for RAG — Ma et al. 2023; conversational query reformulation (CQR) |
| Multi-query expansion fused with reciprocal-rank fusion; hybrid dense + lexical | RAG-Fusion; Cormack et al. 2009 (RRF); BM25 + dense hybrids (e.g. Pinecone/Elastic evaluations) |
| Neighbour-chunk expansion, token-budgeted packing, evidence first in context | "Lost in the Middle" — Liu et al. 2023 |
| Listwise LLM reranking | RankGPT — Sun et al. 2023 |
| On-demand tool retrieval inside reasoning nodes | ReAct — Yao et al. 2022; Self-RAG on-demand retrieval |
| Plan first, then execute selected nodes | Plan-and-Solve — Wang et al. 2023; ReWOO — Xu et al. 2023 |
| Evaluator-driven correction loop with bounded retries | Reflexion — Shinn et al. 2023; CRAG corrective loop. Caveat: prompted self-correction without external feedback does not reliably help (Huang et al. 2024; Kamoi et al. 2024) — see Conversation Quality Review |
| Relevance-gated, dated memory recall; preferences always; nothing irrelevant | Generative Agents — Park et al. 2023 (recency × relevance); LongMemEval — Wu et al. 2025 (temporal, update, abstention); distractors — Shi et al. 2023, Cuconasu et al. 2024. See Memory |
Tuning
All knobs live in RetrievalConfig (see the table in Knowledge Retrieval). The ones that change routing rather than search:
| Key | Default | Effect |
|---|---|---|
respect_triage_web_route | true | A successful triage's web-only route stands on an agent with knowledge (complete inventory, nothing named in the person's own words). Off, always_retrieve forces internal retrieval onto it, as before |
mode | hybrid | pipeline never runs the LLM tool loop; agentic always does |
agentic_when_thin | true | In hybrid, run the agentic pass only when the pipeline's evidence falls short: nothing found, a failed search, or a named document missed. min_sufficient_passages is gone |
agentic_max_iterations | 4 | The agentic pass's model rounds (1–10), plus one call to write up |
Cost profiles
How much pipeline work a turn does is the agent's cost profile (agents.cost_profile, svc-core migration 96), from a vocabulary both services carry byte for byte (app/util/cost_profiles.py, tools/test_shared_modules.py). svc-core stores it and sends it on every request (app/services/agent_spec.py); svc-ai decides what it does, in one place (app/agents/effort.py): each profile is a PipelineEffort —
| Setting | thorough | balanced | economy | Read by |
|---|---|---|---|---|
history_block_turns | none (one at a time) | 4 | 4 | _windowed: the window's start moves four turns at a time, so 6–9 turns are replayed and the cached history prefix holds for four turns |
max_eval_retries / simple_eval_retries | 2 / 1 | 1 / 0 | 1 / 0 | _eval_retry_budget, recursion_limit |
check_simple_tasks | yes | no | no | __evaluator__: a request triage calls simple is answered unchecked, outcome skipped (never a pass; a revision is always checked) |
memory_recall_limit / memory_block_max_chars | 8 / 6,000 | 4 / 3,000 | 4 / 3,000 | __memory_read__, recall.Limits (recall._within) |
history_token_cap | none | 24,000 | 24,000 | token_budget's H_profile |
lighter_steps | no | no | yes | build: triage, the planner, retrieval's query planning and reranking, the quality check and memory summaries run on the lighter model (_steps_llm); synthesis and the retrieval workers keep the agent's own |
lighter_simple_answers | no | no | yes | the agent node (_simple_answer_llm): a plain agent's first pass at a request triage called simple is written by the lighter model, when the conversation fits it whole (token_budget.fits); a skill graph's nodes keep their models |
The run carries only the profile's key (state.context["cost_profile"]), so a checkpoint stays serialisable, and an unknown key runs thorough. thorough is the pipeline exactly as it ran before profiles: tests/agents/test_cost_profiles.py pins its values to the old constants and a thorough turn to the requests an unprofiled one sent, and drives Balanced through the real graph (no check on a simple request, a check on a complex one, one revision rather than two).
Balanced and Economy are unmeasured (cost_profiles.MEASURED): an agent may choose either (the agent page's Cost profile, marked "Not yet measured"), nothing defaults to either, and CHAINR Bot stays thorough. One becomes the default for new agents only once the gold datasets show it answers as well — measured with the Cost profiles evaluation preset (agent-graph-review.md#cost-levers-october-2026). A skipped check reads as skipped everywhere: the stream's verdict, the stored answer, the quality_check rule field, the decision record (with why) and fe-core's badge ("Not checked (simple request)", neutral). The built-in rule that sends answers the check could not stand behind to review matches failed and unavailable, not skipped.
Economy: a lighter model for the lighter work (cost-control plan B3). Economy is Balanced plus the one lever that changes the model rather than how much is sent to it. svc-core chooses the lighter model, because the choice is governance (app/services/lighter_model.py): the cheapest available chat model of the agent's model's own maker, in the same region, in a lighter tier (svc-ai's effort: light < balanced < deep < frontier) and cheaper; with vision when the agent's model has it; never a model a rule in force for the workspace names; and none when a person chose the turn's model. It travels as lighter_model (AgentConfig / SkillSpec); svc-ai builds it once (_lighter_llm_for) and falls back to the agent's own model when it cannot. Economy's lighter model triages in place of TRIAGE_MODEL. An answer it wrote reports answered_by (the stream's done frame, ExecuteResponse.context), which svc-core puts on the ledger row (ai_model_id), the stored answer (model_name, meta.lighter_model) and the decision record; the chat names it. An agent already on its maker's lightest model in its region gains nothing (the agent page says so, GET /app/agents/cost-profiles?agent_id=), which on today's deployment, whose two models are light, is every agent. Economy is unmeasured like Balanced and measured beside it (B2.3). Pinned by svc-ai's tests/agents/test_cost_profiles.py (through the real graph) and svc-core's tests/test_lighter_model.py.
One request, built once. Every path that runs an agent — its chat over the socket, the batch prompt, an evaluation cell, a dashboard tile — builds svc-ai's request with agent_spec.build (through its skill graph when it has one, as itself otherwise). They used to assemble it separately, and an evaluation never ran the agent's skill graph. tests/test_agent_spec.py pins the builder and that no other module writes the request's keys.
Diagnosing "the agent ignored my knowledge"
Check the gate trace frame:
route/retrieval_typeare the final route, andresult.triageis what triage chose and each change the gate made. Internal retrieval ran whenrouteisretrieveandretrieval_typecontainsinternal. If not:always_retrieveis off, or a successful triage chose the web alone (respect_triage_web_route; on a plain agent the route then readsdirect).kb_inventory_complete: falsemeans routing saw less than the knowledge bases hold.Check the
__retrieval_join__frame (__internal_retrieval__on traces before 26 October 2026): itsretrieval_contextpreview should start with## Retrieved Knowledge; each lane's frame says what it found, judged and handed on. An empty preview with an error means Qdrant / Neo4j / embeddings failed — theerrorsfield names the KB.result.reportsays when the query planner or relevance judge failed, a semantic leg could not run, or the judge ruled passages out.Use
POST /app/repositories/{id}/searchwith the same question to see exactly what the pipeline returns outside the agent.For a named file, the "Documents explicitly requested" section tells you whether it was resolved, and with what coverage.
list_documentsshows each file's indexing status; afailedstatus carries the indexing error.svc-ai must have the MinIO credentials (
dotenv/dev/minio.envis in itsenv_file); without them the log shows a loud error at first document access.
A node's input tokens on the trace are the sum of its calls' full inputs (_stream_graph, 18 October 2026). They were a delta against whichever call ran just before, which showed the quality check as "0 in". That was display only: the meter and the ledger always counted every call's whole prompt. graph_based.collect_usage still under-counts input, and the batch route replaces it with the meter's figures.