Workbench Chat
Workbench Chat is a streamed assistant that answers questions by calling read-only lookups (tools) over the Workbench's own data. Its design is ported from Claimpilot Chat (a provider port, a server-side tool loop and a small event protocol), rebuilt on the Workbench's AI door, metering, row-level security and provenance.
The shape of a question
browser (ChatProvider) API (POST /api/chat)
scope + text of earlier turns ───────────▶ validate (chatRequestSchema)
resolve scope as the user (RLS) ─ 404 / 409
question names an ID? ─ 400, audited
AI available? daily limit? ─ 503 / 429
◀── text/event-stream ──
activity chip ◀── {type:"activity"} loop (≤ 6 model calls):
answer text ◀── {type:"text"} metered model call (streamed)
lookup trace ◀── {type:"tool_result"} run the lookups it asks for, as the user
page button ◀── {type:"action"} feed results back
labels, sources ◀── {type:"done"} check the answer's figures
audit (no question or answer text)
- Protocol:
packages/core/src/chat.ts(chatRequestSchema,ChatEvent,chatFeedbackSchema). The server is stateless: the browser sends the text of earlier turns with each question (at most 24 messages), and conversations never leave the tab. - Route:
apps/api/src/routes/chat.ts. Everything that can refuse a question happens before the stream starts, so refusals are ordinary JSON errors. Viewers can ask: every lookup is read-only. - Loop:
services/chat/service.ts(runChatTurn). Each model call goes throughmeteredChatStream(services/ai-metering.ts) andscrubForModel(services/chat/egress.ts). - Model:
services/ai-chat.tsstreams Gemini'sstreamGenerateContentwith function declarations (parametersJsonSchema), overfetch(no SDK). Gemini 3's thought signatures are replayed unchanged.AI_PROVIDER=fakegives a deterministic stand-in (ai-fake.ts) that calls the lookup its question's words point to and answers by quoting the lookup's figures. - Worker: a streamed response outlives
app.fetch, soworker.tscloses the Neon pool only when the stream ends or the reader goes.
Scopes and lookups
The scope comes from the page (apps/web/src/lib/chat-scope.ts): a staff list, an engagement, or global. resolveScope (services/chat/scope.ts) checks access as the user and describes the scope for the prompt (organisations by name, never people).
| File | Lookups |
|---|---|
tools/staff-list.ts (cached summary) | overview, scenarios, breakdown, org_structure, classification_coverage, offshore, value_chain, research_alignment |
tools/rows.ts (rows scored on the server with the same core functions as the browser) | value_chain_breakdown, savings_by_group, spans_and_layers, copilot_case, rollout_plans, job_titles |
tools/engagement.ts | staff_lists, compare_staff_lists, engagement_overview, title_overrides |
tools/platform.ts | engagements (global only), benchmarks, methodology, reference_data, user_guide, open_page |
Staff-list lookups take an optional staff_list_id (from staff_lists or engagements); in an engagement only its own staff lists are reachable. Lookups run in short asUser transactions, never across a model call; a staff list's scored rows are memoised for the question. benchmarks uses services/benchmarks.ts, the same reviewed service path as the Benchmarks page, so the five-engagement minimum and rounding hold.
user_guide searches services/chat/guide-index.ts, generated from docusaurus/docs/user by npm run chat:guide (the Worker has no file system). test/chat-guide.test.ts fails when the index is out of step with the guide.
open_page returns an action: the browser shows a button and navigates only when the person clicks it, and only to a page they can reach (checked when the lookup runs).
No personal data reaches the model
This is a hard rule (see Security and privacy). The controls, in order:
- Lookups return allow-listed aggregates. Each lookup builds its
datafield by field: no names, emails, employee or manager IDs, reporting lines or rows. Leaders are named by position (Layer 2, organisation 3). Lookups never reademployee_identities. - Small groups are withheld. Pay-derived figures for a group of fewer than
CHAT_MIN_GROUP(5) people become withheld (fewer than 5 people), throughgroupFigure. - Questions are screened.
candidateIdTokenspicks out words that could be IDs (mixed letters and digits, or a number after employee, ID, number…);questionNamesAnIdrefuses the question if one is an employee or manager ID in scope, before anything is sent, and auditschat_question_refused. - Every outgoing request is scrubbed.
scrubForModelremoves email addresses from the instructions, every typed and earlier message, lookup arguments and results. - A test proves it.
test/chat.test.tsseeds distinctive names, emails and IDs, calls every lookup in one question, records every request the model would have received and asserts none of them appears, and that a one-person group's cost is withheld.
What can't be prevented is a person typing someone's name; the composer asks people not to, and no lookup can find an individual.
The environment lookup returns the cached environmental estimate. Tonnes follow FTE, so it folds groups of fewer than five into "Other" and withholds every group's figures in a breakdown when "Other" is still under five (partition in tools/environment.ts). toolDataForModel passes its tCO2e figures, its own fixed explanations and published reference labels (regions, climate bands, scenarios, role groups) verbatim; business names are replaced with ordinals like any editable label.
Labelling and checking answers
The done event carries the metrics the lookups declared (shown as provenance badges under Sources) and unmatched: figures in the answer that match nothing a lookup returned, by unmatchedFigures (money, percentages, multiples and counts, allowing for the rounding the answer was written to; small counts and years are prose). Lookups hand the model figures already formatted (gbp, pct, num) so it quotes them as they are; a figure the model worked out itself is flagged Review before sharing.
Metering and limits
- Every model call reserves and settles like any other AI call. The first call of a question is metered as
chatand counts towardsAI_ASK_DAILY_LIMIT(shared with the retired Ask); the calls after its lookups arechat-step. Prompt Lab runs areprompt-lab. assertQuestionAllowancerefuses an over-limit question before streaming (a reviewed metering read on the service connection); admission still enforces the limit atomically.- The usage estimate is the request's UTF-8 size (an overestimate of tokens) plus twice the output allowance, with no
countTokensround trip. - At most
CHAT_MAX_ROUNDS(6) model calls a question. The last may only answer: its lookups stay declared buttoolChoice: "none"(Gemini's function-calling modeNONE) forbids calling one, andFINAL_ROUNDasks for an answer from what was found. If even that writes nothing, the answer lists the lookups made.
Prompt and Prompt Lab
The chat prompt (packages/core/src/prompts.ts) is the model's instructions: its system text, then its template filled with {{scope}} and {{today}}. The Prompt Lab's Run test for it (services/chat/lab.ts) runs the real loop on a question, on a chosen staff list or the Workbench as a whole, and reports the answer, the lookups it used and any unmatched figures.
Feedback
POST /api/chat/feedback stores one vote per answer in chat_feedback (migration 0010): the rating, reason chips, prompt version and model, never the question or answer. Votes can only be filed against a scope the person can read (RLS and resolveScope).
Adding a lookup
- Add a
ChatToolto the right file inservices/chat/tools/and its list: a JSON-schemadeclarationwith a description the model can choose by, thescopesit's offered in, a present-tenselabel, andrun. - Read through
ctx.asUser(orstaffListFor/ the row loader) so access and RLS apply. - Return only aggregates you have named field by field, formatted with the core formatters; wrap pay-derived figures in
groupFigure; setwithheldwhen you withhold; declare themetricsthe figures rest on. - Add it to the arguments in the personal-data test (
ALL_TOOL_ARGSintest/chat.test.ts) if it needs any, and a test of its own; teach the stand-in model (CHAT_ROUTESinai-fake.ts) if an end-to-end journey should reach it.