The chat pipeline
A chat turn is one POST /api/chat that streams Server-Sent Events back. The Worker runs the whole agentic loop server-side: it calls the model, runs any tools it asks for, calls it again with the results, and streams text and activity to the browser as they happen.
The code is api/src/chat/service.ts (prepareChatTurn, then runChatTurn, an async generator of ChatEvents) and api/src/chat/routes.ts (which refuses, or writes each event as an SSE frame).
1. Validate and resolve
ChatRequest (zod, packages/shared/src/chat.ts) is parsed first. A malformed body is a 400 before any streaming starts. The request must carry either:
claim: the document itself. The demo and every embedding host send this, because the page already has the claim it is rendering.claimId: a reference the Worker looks up in its own store. The Prompt Lab's runner uses this.
From here on, everything sees a Claim and nothing knows which way it arrived.
Refusing before streaming
prepareChatTurn does everything that can refuse a question before the stream opens, so the caller gets an ordinary JSON error with a proper status rather than an error line inside a 200. An embedding page can show the right state, and monitoring sees a refusal as what it is.
| Condition | Status | code |
|---|---|---|
| Malformed body | 400 | invalid_request (with zod's issues) |
| No model configured | 503 | not_configured |
A claimId the store does not hold | 404 | claim_not_found |
Unknown capability | 400 | unknown_capability |
The body is {"error": "<a sentence for a person>", "code": "…"}. In the browser, api.chat() throws an ApiError carrying the status and code, and the widget shows the message as an error line.
Only a failure during the answer (the model or a provider call throwing) is an error event, because by then the stream has started.
Prompt overrides
The request's promptOverrides (the browser's Prompt Lab versions) apply unless PROMPT_OVERRIDES is off. While they apply, anyone who can reach the API can change the assistant's prompts, so a deployment whose prompts must be fixed switches it off. Whatever the setting, system.safety is locked and never replaced. See Security.
2. Assemble the system prompt
assemblePrompt() in api/src/chat/system.ts builds the system instruction in a fixed order. The order is part of the safety design: nothing read from the claim can come before the boundaries.
| # | Block | Source | When |
|---|---|---|---|
| 1 | Identity and working style | system.base | always |
| 2 | Pointing at the screen | system.screen_actions | only if screenActions |
| 3 | Safety and boundaries | system.safety | always |
| 4 | Spelling, dates and terminology | system.locale_uk or system.locale_us | by locale |
| 5 | The claim brief | buildClaimBrief(claim, today, locale) | always |
| 6a | ## Task: <label> + the capability's playbook | capability.<id> | a quick action |
| 6b | Free-chat guidance + a list of the specialist tasks | capability.claim_qa + buildCapabilityGuide() | free chat |
| 7 | Spoken-style tail | system.voice | voice only |
Every prompt block goes through resolvePrompt(id, overrides): the request's Prompt Lab override if one is allowed and usable (never for a locked prompt), otherwise the code default. Then applyBrand() fills in {{assistant}}, {{product}} and {{pronunciation}} for the requested brand. The claim brief is never branded or overridden.
The claim brief
buildClaimBrief (api/src/chat/context.ts) is a dozen lines: the claim and today's date, line of business, status, client and handler, policy period and state, claimant, incident, loss estimate, coverage and liability position, money totals, risk flags, and the size of the schedule and file. It ends with the list of sections get_claim_section can read.
It is small and stable on purpose. It only changes when the claim changes, so it caches well, and it is enough for the model to orient itself and answer simple questions without a tool call. Detail comes from tools.
Its money and dates are formatted with the same helpers as the claim screen and the tools (packages/shared/src/format.ts): £27,800, and 22/07/2026 or 07/22/2026 by the request's locale. It names the claimant but carries no contact details.
3. Offer the tools
allTools({ screenActions }) returns every tool, shared readers first so the prompt-cache prefix stays stable. All tools are offered on every turn, whatever the capability. A capability's playbook tells the model which to call first.
highlight_panel is a screen action. It is offered only when the request sets screenActions: true. A caller that cannot highlight anything is never told it can, so the model cannot claim to have done it.
Attached files are read first
When the question carries files (see Attached files), prepareChatTurn checks them before anything streams, and runChatTurn reads each image, PDF, recording or video once before the first round: one call with no tools and the system.attachment_read prompt, through scrubForModel like every other call. Its note is cleaned again, sent as attachment_read, and added to the question's text, so the answer is written with the file and its note. The read calls' tokens are counted in the turn's usage. A file that cannot be read is answered from as it is, without a note. On later questions the conversation carries the note in place of the file (toModelMessages, api/src/chat/attachments.ts).
4. Run the loop
For up to 8 iterations:
- Build the request (
system,messages,tools,toolChoice,thinkingLevel,maxOutputTokens: 8000,signal), pass it throughscrubForModel(the egress check, below), and callai.streamTurn. The thinking level is the capability's own if it sets one, otherwise the deployment default. - Forward each text chunk as a
text_deltaimmediately. - On
done, add the usage and keep the adapter'sproviderState. - Append the assistant turn to the in-request history, with its
providerState. - If there were no tool calls, stop.
- Otherwise, for each call:
- an unknown tool name gets an error result (
Unknown tool <name>) and no activity chip; - a known one emits
activitywith the tool's present-tense label, runs throughrunTool, emitstool_resultwith the result truncated to 400 characters, and emits aclient_actionfor each screen action it returned.runToolturns a throw into an error result rather than a crash, and presents the result: money, rates and dates formatted the way the claim screen shows them (see Capabilities and tools).
- an unknown tool name gets an error result (
- Append the tool results to the history and go round again.
Several lookups in one step
A round can ask for several lookups at once. They run one after another in the Worker, each with its own activity and tool_result, and all their results go back to the model together in one following call, so three lookups asked for at once cost one round, not three. Gemini does this when asked, and system.base asks: request every lookup the question needs at once, and prefer the lookup that answers the whole question (money_timeline, list_deadlines, check_policy_in_force) to piecing an answer together from several.
The last round may only answer
The eighth round is answer-only. The tools stay declared, because Gemini can reject a history of function calls when no functions are declared, but toolChoice: 'none' switches calling off (FunctionCallingConfigMode.NONE in the Gemini adapter), and the system prompt gains the system.final_round instruction: answer from what the lookups returned, and say which part could not be answered and what to ask next. Any calls that still come back are dropped.
So a question that uses all its lookups still gets an answer from them. If the model writes nothing at all, the Worker answers "I looked up … but couldn’t put an answer together. Try asking for one part of the question at a time."
The egress check
scrubForModel (api/src/chat/egress.ts) is the one check on everything sent to the model, applied to every request in the loop and, through the same functions, to the voice relay's set-up and tool responses. A claim is personal data by nature, so the rule is minimisation:
| Withheld | Kept |
|---|---|
| Contact details of anyone: phone, email, postal address, postcode | Names and roles |
| Dates of birth (tools give an age where it matters) | Claim, policy and document references |
| Bank, card and government identifiers (sort code and account, IBAN, card, NI, SSN) | The loss location's description, injury and medical narrative, money and dates |
It works in two layers. In any tool result that is JSON, a value under a withheld key (contact, address, dateOfBirth, …) becomes [withheld] wherever it sits, so a new tool that serialises a whole section is safe by default. In every piece of text (the system prompt, the questions, earlier answers, tool results and tool arguments) patterns replace the identifiers that turn up in free text with labels such as [phone removed]. The model's own replayed turn (providerState) is passed back unchanged. The safety prompt tells the model what is withheld and to leave placeholders such as [claimant's address] in drafts.
api/test/egress.test.ts proves it: personal data planted throughout a claim, every tool called with arguments that do real work, for every capability and for voice, and none of it reaches the model.
Why providerState is replayed
Gemini 3 signs its turns: function-call parts carry a thoughtSignature that must be echoed back verbatim when the turn is replayed, or the next call is rejected. The Gemini adapter rebuilds the model's own parts as it streams and returns them as opaque providerState. The turn loop stores it on the assistant message and hands it back unchanged. Never rebuild an assistant turn from its text and calls when replay parts exist.
History on the wire
Between turns the browser keeps only text: user messages and the assistant's final answers. Tool round-trips stay inside one request. toAiMessages drops any leading assistant messages so the model always starts with the user. Requests are capped at 60 messages of 20,000 characters each.
5. Finish
The last event is always done (unless an error ended the stream):
{
"type": "done",
"model": "gemini-3.1-flash-lite",
"usage": { "inputTokens": 5210, "outputTokens": 412, "cacheReadTokens": 3968 },
"turnId": "4f6b2c1e-8a9d-4c3b-9e2f-1d7a5b0c6e93",
"prompts": { "fingerprint": "default", "overridden": [] },
"unmatched": [],
"unmatchedInContext": [],
"workedOut": []
}
turnIdis a fresh UUID. Nothing is stored against it on the Worker. It comes back with a thumbs up or down, which is how a vote is tied to one answer (see Answer feedback).prompts.fingerprintisdefault, or the first 12 hex characters of a SHA-256 over the overrides that actually applied, in id order. The same Prompt Lab versions in any browser give the same fingerprint.unmatchedis the figure check: figures in the answer that match nothing the model was given (below).unmatchedInContextcarries the same figures, each with the words either side of it.workedOutlists figures the check found as a one-step sum, with the sum.
The figure check
When the answer is complete, figureCheck (api/src/chat/figures.ts) reads every figure in it (money in £, $ or US$, percentages, multiples, counts and dates) and looks for each among what the model was given: the system prompt with its brief, the questions, and every tool result. It allows for the rounding the answer was written to: "£28k" matches £27,800 and "1,800" matches 1,794, but "100" does not match 148, because the allowance is capped at a tenth of the figure. Dates must match exactly, in any common form. Both ends of a range ("18–20 June 2026", "June 18–20, 2026", "1 January–31 December 2026") are read as dates. A date written without its year ("18 June") matches that day in any year.
Shown working counts. When the answer writes a sum out in the same sentence as its result, the check works it: "£2,500 (£3,500 − £1,000)", "£1.2m + £800k = £2.0m", "£700 (£3,500 × 20%)". If every part of the sum is itself matched, and the sum comes to the result within its rounding, the result is not flagged. Results can feed a later sum. A dash or an x counts as an operator only with a space each side, so ranges and multiples are never read as sums. A wrong result, a part the tools never gave, or working in a different paragraph is still flagged.
One-step sums are worked out and shown. When a figure is left over, the check tries it as a sum or difference of two figures of the same kind (money with money, a percentage with a percentage) in the same paragraph or list item, both of which matched the lookups. "Deductible £2,500. Loss item: £35,000. Net exposure after deductible: £32,500." gives £32,500 = £35,000 − £2,500. Differences are tried before totals. A figure found this way goes in workedOut, with its sum, not in unmatched, and later mentions of it are covered too. The parts must have matched before anything was worked out, so one worked-out figure never feeds another. A figure no pair of nearby figures gives is still flagged.
Small counts ("the top 3"), years, identifiers ("DOC-4", "CP-AUT-260381"), times and legal references ("Part 36", "CPR 44.2") are not figures to check. A unit of measure joined to a number ("20ft", "20-foot", "30mph", "80kg", "48hrs", "3.5km") does not make it an identifier: the number is read as a count, so "fell 20ft" in a tool result supports "20 feet" in the answer. Ordinals ("4th", "1st") are still prose. A bare number in a tool result can support money, a percentage (0.31 for 31%) or a multiple, because whole claim sections still carry plain numbers.
A figure that matches nothing was added up without showing how, converted or invented by the model. Up to eight come back in unmatched, and in unmatchedInContext with the words around each. The widget shows Check before sharing under the answer and quotes each figure in its place, for example “…after falling 20 feet due to a structural…”, because a bare "20" is hard to find in a long answer. Worked-out figures get their own quieter note above it, Worked out: £32,500 = £35,000 − £2,500, quoted the same way: not a warning, but the handler still sees how the number was reached. The Prompt Lab trace lists both. system.base tells the model to use figures exactly as the tools give them, and to write the sum beside any figure it works out itself ("Net exposure: £32,500 (£35,000 − £2,500)"), which the check then accepts with no note at all. Voice answers are not checked.
Cancellation
The route passes an AbortSignal into the loop and aborts it when the client disconnects. The browser's Stop button aborts its fetch, the stream closes, and the model call stops with it.
Reading the stream in the browser
api.chat() in frontend/src/lib/api.ts is an async generator over the response body. It splits frames on blank lines and parses each data: line as a ChatEvent, however the bytes are chunked. useChat then:
| Event | Effect |
|---|---|
text_delta | Appends to the streaming answer |
activity | Inserts a chip before the answer, so the answer reads as the conclusion |
tool_result | Adds to the answer's lookups trace |
client_action | highlight_panel → highlightPanel(panel); navigate → the host's callback, if any |
done | Records usage, the turn id, the model, the prompt fingerprint and any unmatched figures on the answer |
error | Adds an error line to the transcript |
The full event schema is in the chat protocol reference.