AI providers
Chat, voice set-up and the claim generator depend on one interface, AiProvider in api/src/ai/provider.ts, never on a vendor SDK. The one place an adapter is chosen is makeAiProvider(env) in api/src/ai/index.ts.
The port
export interface AiProvider {
readonly configured: boolean; // false without a key: chat answers with an error event
readonly model: string; // reported by /api/health and in the done event
readonly generatorModel: string;
readonly liveModel: string;
readonly thinkingLevel?: ThinkingLevel;
readonly attachmentKinds: readonly AttachmentKind[]; // which attached files it can hand its model
/** One model call with function calling, streamed. The caller runs the tools and calls again. */
streamTurn(req: TurnRequest): AsyncIterable<TurnEvent>;
/** One JSON-mode call, for the generator. */
generateJson(req: JsonRequest): Promise<unknown>;
}
export type TurnEvent =
| { type: 'text'; text: string }
| { type: 'tool_calls'; calls: ToolCall[] }
| { type: 'done'; usage: Usage; providerState?: unknown };
Messages are provider-neutral: user text (with any attached files, as base64 data or as text), assistant turns (text, tool calls and an opaque providerState), and tool results. Tool definitions are plain JSON Schema. The adapter translates both ways.
The port does not run tools or loop. That is runChatTurn's job, so the loop, the limits and the events are the same whatever the model.
Gemini
api/src/ai/gemini.ts uses the official @google/genai SDK, which is fetch-based and runs on Workers.
- Streaming with function calling.
generateContentStreamwith the system instruction, the tools as function declarations (parameters passed as JSON Schema; parameterless tools omit them),maxOutputTokensand the abort signal. - Thought parts are skipped. Text parts stream out as
textevents. Function calls are collected and emitted once astool_calls. - Thought signatures are kept. Gemini 3 signs function-call parts with a
thoughtSignaturethat must be echoed back when the turn is replayed. The adapter rebuilds the model's own parts as it streams and returns them asproviderState. When an assistant turn hasproviderState,toContentsreplays those parts verbatim instead of rebuilding them from text and calls. - Usage maps
promptTokenCount,candidatesTokenCount + thoughtsTokenCountandcachedContentTokenCountto input, output and cache-read tokens. - Thinking levels map
low | medium | highto Gemini's levels. Unset leaves the model default. - JSON mode (
generateJson) setsresponseMimeType: 'application/json', addsresponseJsonSchemaonly when a schema is passed, strips a stray code fence, and throws with the finish reason if the reply is not JSON.
responseJsonSchemaGemini's constrained decoding has a complexity cap that the Claim schema exceeds: it fails at roughly 20 of its 33 top-level sections. So the generator puts the full JSON Schema in the prompt, and zod validates the reply. Constrained decoding is for small shapes only. Keep it that way.
Azure AI Foundry
api/src/ai/azure.ts is selected with AI_PROVIDER=azure. It uses the official openai SDK, which is fetch-based and runs on Workers, pointed at the resource's OpenAI-compatible v1 endpoint (AZURE_AI_ENDPOINT plus /openai/v1). It speaks the Responses API. Chat and generation move to Azure; voice does not (see below).
AI_PROVIDER=azure
AZURE_AI_ENDPOINT=https://my-resource.openai.azure.com
AZURE_AI_API_KEY=…
AZURE_AI_DEPLOYMENT=my-chat-deployment
- Deployments, not models. Azure routes on the deployment name, so
AZURE_AI_DEPLOYMENTis what/api/healthreports as the model.AZURE_AI_GENERATOR_DEPLOYMENTdefaults to it. - Stateless. Every call sets
store: false, so Azure keeps no conversation state. The whole history goes up each round, as it does for Gemini. - Encrypted reasoning is replayed. With reasoning on, the adapter asks for
reasoning.encrypted_content. The response's output items (reasoning, messages and function calls) come back asproviderState, andtoInputreplays them verbatim on the next round. This is the Responses counterpart of Gemini's thought signatures: without it, a reasoning model loses its reasoning across tool calls. - Tools are sent as non-strict function tools with their JSON Schema unchanged. Calls come from the completed response's
function_callitems.call_idbecomesToolCall.id, and the JSONargumentsare parsed. Arguments that do not parse reach the tool as none, and the tool says what is missing. Results go back asfunction_call_output, with errors wrapped as{"error": …}. - Answer-only round.
toolChoice: 'none'becomestool_choice: 'none', with the tools still declared. - Usage maps
input_tokens,output_tokens(which includes reasoning tokens) andinput_tokens_details.cached_tokens. - Reasoning effort. A thinking level becomes
reasoning.effort.AZURE_AI_REASONING_EFFORTsets the deployment default. Set it toofffor a deployment without reasoning (gpt-4.1, say). Reasoning parameters are then never sent, even when a capability asks for a level. - JSON mode uses
text.format: json_object, or a non-strictjson_schemawhen a schema is passed. The Claim schema still goes in the prompt and zod validates it, as for Gemini. Strict mode needs every property required, which the Claim schema does not promise. - A cut-off response is kept.
response.incompleteends the turn with what was produced.response.failedand streamerrorevents throw. - Authentication is the resource key, sent both as the bearer token and as
api-key. Workers cannot use a managed identity. An Entra ID token is the route on Azure hosting.
Azure traffic goes straight to the Foundry endpoint, so it is not logged in Cloudflare AI Gateway. /api/health reports gateway: null with provider: "azure". Foundry's own monitoring is where to look instead.
The voice relay speaks the Gemini Live protocol, so with AI_PROVIDER=azure voice still needs GEMINI_API_KEY, uses GEMINI_LIVE_MODEL and goes through the gateway if one is configured. Set VOICE_ENABLED=false for a deployment that should send nothing to Google.
The scripted adapter
api/src/ai/scripted.ts is selected with AI_PROVIDER=scripted. It plays the model's part deterministically so the API integration tests and the Playwright suite exercise the real Worker without Gemini:
- On a new question it calls
get_claim_sectionfor the section the question is about (parties →involvements, money words →financials, anything else →incident), plushighlight_panelfor the matching panel when that tool is offered. - Given the tool results back, it streams "Scripted answer about {claim id} — {title}. I looked up: {tools}." in three chunks.
- A question containing
[scripted:fail]makes it throw. generateJsonalways throws: the scripted adapter does not generate claims.
It reads the claim's id and title from the system prompt's brief, so a test can tell the right claim reached the model. Never set it on a deployment. See Testing.
AI Gateway
api/src/ai/gateway.ts builds every gateway URL. With both AI_GATEWAY_ACCOUNT_ID and AI_GATEWAY_ID set:
| Path | Used for | Base URL |
|---|---|---|
google-ai-studio | Chat and generation, as the SDK's baseUrl | https://gateway.ai.cloudflare.com/v1/<account>/<id>/google-ai-studio |
google | The voice relay's upstream socket | https://gateway.ai.cloudflare.com/v1/<account>/<id>/google |
gatewayHeaders() adds cf-aig-authorization: Bearer <CF_AIG_TOKEN> when a token is set. The request body, tools and streaming are untouched: the gateway is a base-URL swap. See Configuration for what to set where.
Thinking levels
Three places can set reasoning depth, and the most specific wins:
- A capability's
thinkingLevel(for examplehighfor policy validation,mediumfor next actions). GEMINI_THINKING_LEVEL(orAZURE_AI_REASONING_EFFORTon Azure) for the deployment.- The model's own default, when neither is set.
Adding a provider
See Add a model provider. azure.ts is a worked example. The voice relay speaks the Gemini Live protocol directly and would need its own equivalent.