Skip to content
MSO CloudDocumentation

ADR 0056 — AI provider adapters, capability profiles and caching policy

On this page
  • Status: Accepted (2026-10-20); amended 2026-11-07 (see "Amendment 2026-11-07").
  • Date: 2026-10-20
  • Owners: Platform (packages/ai).
  • Related: ADR 0005 (connections and failover), §61 (one resolver, one failover), §63 (truncation guard), §155 (this boundary).

Context#

Each model accepts a different request. Claude Opus 5.5, Sonnet 5.5 and Fable 5.1 return a 400 on a forced tool_choice (any / named tool); Sonnet 5.5 and Haiku 5.5 return a 400 on a non-default temperature; Opus/Sonnet 5.5 return a 400 on thinking: disabled; every Claude 5.x model returns a 400 on a thinking budget and on an assistant prefill. DeepSeek V4 rejects tool_choice while thinking. The Admin probe sent toolChoice: 'required' to every model and reported Claude Sonnet 5.5 as unable to call functions.

Decisions#

D1 — One ProviderAdapter per registry provider

packages/ai/src/adapters/ holds one adapter for each of anthropic, openai, google, deepseek, mistral, openrouter, ollama, openai-compatible. The adapter owns:

Concern Member
Model construction createModel(config)
Capability profile profile(modelId)
Request shaping shapeCall(params, modelId)
Error classification classifyError(error)
Usage normalisation normaliseUsage(usage)

createLanguageModel builds the vendor model through the adapter and wraps it in AI SDK middleware that runs shapeCall for that exact model id. Every failover candidate is therefore shaped for itself. Call sites state an intent and never branch on a provider.

D2 — Call intent, not vendor options

Call sites pass providerOptions from buildProviderOptions / buildToolProviderOptions (conversation), buildBoundedProviderOptions (bounded or bounded-reasoning) or buildProbeProviderOptions (probe). The intent travels in a yng namespace that the middleware removes before the vendor SDK runs. One intent object is valid for every candidate of a mixed failover chain.

D3 — Capability profile rule

A profile states: function calling, forced tool choice, thinking mode and how to minimise it (disabled accepted or effort only), thinking budget, effort, sampling parameters, prefill, structured-output mode, max output, context window, cache kind and minimum cacheable prefix.

  • Profiles resolve by family and version parsed from the model id (platform prefix and snapshot suffix ignored).
  • An id the table does not name, of a known family at or above the current generation, resolves to the fail-closed profile: no forced tool choice, no sampling parameters, no prefill, no thinking-off, no thinking budget (known: false).
  • Every model in CURATED_MODELS must resolve to a known profile (guard test).

D4 — Request shaping

Applied by the middleware, per model:

  • Sampling parameters are removed when the profile rejects them.
  • Forced tool choice on a model without it becomes auto, strict: true on the named tools, and a system instruction naming the tool, inserted after the cached system prompt. Callers that need a tool call still verify one came back.
  • thinking: disabled on a model that rejects it becomes effort: low; a thinking budget on a model without budgets becomes adaptive.
  • Effort: bounded and probe run at low; conversation runs at medium on Claude models whose thinking is on by default. DeepSeek V4 and Gemini 2.5 Flash run non-thinking for bounded, probe, and any call carrying tools (DeepSeek).
  • A capped call on a model whose thinking is on by default gets 4096 tokens of headroom, so the cap keeps meaning the length of the answer.

D5 — Caching policy per provider

Provider Policy
Anthropic Explicit cache_control on the last tool and the last leading system message. conversation: TTL 1h on that prefix plus top-level automatic caching (5m) for the tail. bounded: 5m on the prefix, no tail. probe: none.
OpenAI Automatic prefix caching; prompt_cache_key = hash of system prompt and tool names (never an org id). probe: none.
Gemini Implicit caching only; no explicit cachedContent resources.
DeepSeek Automatic disk cache; nothing sent. The stable system prompt stays first.
OpenRouter, Mistral, Ollama, OpenAI-compatible No cache fields.

Volatile content (per-request instructions, the user turn) sits after the last breakpoint. At most four breakpoints per request. A prefix below the model's minimum is sent with its marker and is not cached; the marker costs nothing.

D6 — Errors and usage

classifyError returns { kind, retryable, statusCode } with kinds authentication, quota, rate_limited, model_not_found, unsupported_request, invalid_request, overloaded, server_error, timeout, network, unknown; it never returns the provider body. Usage is normalised to uncached input, cache reads, 5m and 1h cache writes, output and reasoning tokens; aiCostMicroVnd prices each at its own rate when the price table carries it.

D7 — Admin probe

probeAiConnection (packages/ai/src/probe.ts) is the single probe for org and platform connections. It requests a tool call with toolChoice: 'required' through the adapter-wrapped model, passes only on a schema-valid call to connection_probe, and reports mode (forced or instructed) and a typed failure reason. Probe results are not stored; re-running Test re-probes.

Enforcement#

  • Middleware on every model built by createLanguageModel.
  • packages/ai/src/adapters/adapters.test.ts (profiles, shaping, cache placement, errors, usage, curated-model guard) and anthropic-request.test.ts (recorded request bodies for claude-sonnet-5-5 and claude-haiku-5-5).
  • scripts/audit/ai-adapter-boundary.py in audit:all (§155): no vendor provider import and no vendor request knob outside packages/ai/src/adapters/ (audit-ok-ai-adapter).

Amendment 2026-11-07#

Supersedes the D5 table and extends D1, D6 and ADR 0005's failover. Everything not named here stands.

A1 — Endpoint kind per adapter

Every adapter declares endpointKind (packages/ai/src/adapters/types.ts), and a recorded-request test per adapter pins the URL path, the body keys and the parsed usage (packages/ai/src/adapters/recorded-*.test.ts, stubbed fetch, no network).

Adapter endpointKind Factory
anthropic anthropic-messages @ai-sdk/anthropic
openai openai-responses createOpenAI()(id)
google google-generate-content @ai-sdk/google
deepseek openai-chat @ai-sdk/deepseek
mistral openai-chat createOpenAI({ baseURL }).chat(id)
openrouter openai-chat createOpenAICompatible with a request-body hook
openai-compatible openai-chat createOpenAICompatible
ollama ollama ollama-ai-provider-v2

Mistral posted to /v1/responses, which Mistral does not serve; .chat() is the fix and the recorded test is the guard for the class.

A2 — Cache strategy per provider (replaces the D5 table)

Provider What is sent Minimum cacheable prefix (profile)
Anthropic Unchanged from D5: conversation = 1h cache_control on the last tool and the last leading system block plus top-level automatic (5m) for the tail; bounded = 5m on the prefix; probe = none. 512 to 4096 by model
OpenAI Automatic prefix cache; prompt_cache_key = hash of system prompt and tool names. No retention or TTL option is sent, so GPT-6 caches at the vendor default (30-minute write). 1024
Gemini Implicit caching only; nothing sent. 2048 (2.5), 4096 (3.x); 3.5 Flash-Lite unstated
DeepSeek Automatic disk cache; nothing sent. 64
OpenRouter anthropic/* The Anthropic policy, passed through: conversation = 1h breakpoint on the last leading system block (covers the tools, which Anthropic caches first) plus top-level automatic; bounded = 5m on the system block. Profile inherits the upstream model. upstream model's
OpenRouter other, Mistral, Ollama, OpenAI-compatible No cache fields. n/a

Prefix order for every caller: tool schemas, static system rules, per-org blocks, date or period header, conversation. Chat and deck chat put the date and deck context after the static rules, so the 1h breakpoint lands on a block that does not change per request. A client-supplied system message is rejected (chatRequestSchema).

A3 — Thinking on multi-turn and tool calls

  • Anthropic: assistant reasoning parts before the last user turn are dropped before the request. They come back from the client, possibly edited, and an edited thinking block is a 400; dropping them is valid.
  • Claude Sonnet 5.5, conversation with a function tool: thinking: between_tools plus effort: medium. Other Claude models keep effort: medium only.

A4 — Usage recording (extends D6)

One writer, recordAiUsage (packages/ai/src/server.ts), prices each attempt through aiUsageForCost and inserts one ai_usage_log row per call. Migration packages/schema/drizzle/0248_ai_usage_cache_tokens.sql adds:

Column Type Meaning
cached_input_tokens integer, default 0 Cache reads, inside input_tokens
cache_write_tokens integer, default 0 5m (or only) cache writes
cache_write_1h_tokens integer, default 0 Anthropic 1h cache writes
reasoning_tokens integer, default 0 Thinking tokens, inside output_tokens
finish_reason varchar(32), nullable Vendor finish reason
served_index smallint, default 0 Failover position that served the call
price_table_version varchar(16), nullable AI_PRICE_TABLE_VERSION that priced the row; NULL = unpriced

Rows written before 0248 read 0 in the four token buckets and NULL in price_table_version, so a cache-hit share is computed over priced rows only. OpenRouter's reported usage.cost is normalised as providerCost but not stored. Every curated Anthropic, OpenAI, Gemini and DeepSeek id carries a price row (guard in packages/ai/src/pricing.test.ts); Mistral, OpenRouter and Ollama ids record no cost.

A5 — Failover cooldown

createFailoverModel skips a candidate for 60 s after it fails with authentication, quota or model_not_found (classifyAiError), keyed connectionId:modelId, process-local; the last candidate still standing is always tried. The 60 s is a proposal with no published standard (docs/architecture/reference/limits-and-budgets.md#ai-failover-cooldown). The per-attempt first-token timeout now applies to a lone candidate too (docs/architecture/reference/limits-and-budgets.md#ai-attempt-timeout).

A6 — Enforcement added

  • packages/ai/src/adapters/recorded-*.test.ts: endpoint path, body and usage per adapter.
  • packages/ai/src/record-usage.test.ts: cost to the micro-VND for an Anthropic 1h write plus read.
  • packages/ai/src/pricing.test.ts: every curated id of a priced provider has a price row.
  • apps/web/src/__tests__/ai-failover.test.ts: cooldown skip and expiry, lone-candidate timeout.
  • apps/web/src/__tests__/chat-prompt-prefix-order.test.ts: static rules first, date header last.

Amendment 2026-11-28#

  • Provider list. D1 names the providers in prose; the authority is ADAPTERS, typed by AiProviderEnum (packages/ai/src/adapters/index.ts, packages/ai/src/providers.ts). An adapter also declares provider and endpointKind (A1); the member table in D1 omits both.
  • Slug lists. The registry slug google is stored as gemini (AI_DB_PROVIDER_IDS); the schema unions AiProvider and AiConnectionProvider are hand-listed copies, so a new provider touches all three lists (Add a language-model provider).