Skip to main content
Blitz
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

015 · Models

Model providers, resilience, fallback and per-model settings (spec_015_models)

Status Implemented. Reverse-engineered from 53f8c53 (2026-09-24) and kept with the code since; its paths checked 2026-09-27 (//tools/specs).
Source pkg/engine/runtime/model_factory.go, anthropic.go, openai_images.go, images.go, documents.go, fallback.go, httpclient.go, settings.go, usage.go, speech.go, painter.go, apipictures.go, apiprovider.go, apiresponse.go, apitoken.go, scriptrun.go; pkg/config/apiprovider.go; pkg/engine/breaker
Tests pkg/engine/runtime/anthropic_test.go, fallback_test.go, httpclient_test.go, settings_test.go, pin_test.go, images_test.go, speech_test.go, painter_test.go, apipictures_test.go, apiprovider_test.go, apitoken_test.go, scriptrun_test.go; pkg/config/apiprovider_test.go; pkg/engine/breaker/breaker_test.go
Depends on spec_002_config
Used by spec_016_engine

1. Purpose

Every model is an ADK model.LLM. A factory builds one from a model reference for one of four providers, wraps it with per-model settings, images and (optionally) a fallback chain, and gives every SDK a shared HTTP client with retry and stall limits.

2. Model references

  • MDL-01 A reference is provider/model or a bare model. ParseModelRef(ref, default) splits on the first / only when the prefix is a known provider (gemini, anthropic, openai, ollama, bedrock, azure, vertex-anthropic, api, case-insensitive); otherwise the whole string is a model of the default provider. OpenRouter-style names therefore need the provider spelled out: openai/anthropic/claude-sonnet-5.
  • MDL-01a 2026-11-04 (scan N26-engine-runtime#17, #18: an unknown llm.provider from a file or LLM_PROVIDER quietly ran on Gemini when a Gemini key was set, and the provider list was kept three times). The providers llm.provider takes are one list, config.Providers (the runtime’s prefixes add enterprise, which comes from the connection); ValidProvider, ProviderList and the unknown-provider error use it. An unknown provider fails the model’s build with unknown provider "antropic" (gemini, anthropic, openai, ollama, bedrock, azure, vertex-anthropic or api) whatever keys are set, and the settings check reports it at its line.
  • MDL-02 NewModel(cfg, override) uses override else cfg.ModelName(), builds the primary, and if llm.fallback_models is non-empty wraps primary + each buildable fallback in a fallback model. Fallbacks that fail to build are logged and skipped. NewModelRef builds exactly one model (no chain) — used by doctor and pins.

3. Providers

Provider Implementation Credentials
gemini ADK gemini.NewModel over genai Since 2026-10-09 (the owner’s request), one credential, the first there is: an API key (api_key, api_key_command, GEMINI_API_KEY/GOOGLE_API_KEY), alone, to the Gemini API; else Google Cloud’s credentials, to Vertex AI: Application Default Credentials (GOOGLE_APPLICATION_CREDENTIALS), else the Google account signed in with gcloud (auth = "oauth", gcloud’s application-default login), else a Google Cloud machine’s (the metadata server). auth doesn’t change the order: with a key, adc and oauth wait until it’s removed. On Vertex AI: project project_id, else GOOGLE_CLOUD_PROJECT, else the credentials’ own (a service account’s key file), required; location location, else GOOGLE_CLOUD_LOCATION, else global. The credentials sign that model’s requests only (a copy of the shared HTTP client), never another model’s, so a request never carries a key and a token.
anthropic Native adapter over anthropic-sdk-go Beta Messages API auth = "oauth": the ant auth login (Anthropic Console) profile profile, else ant’s (ANTHROPIC_PROFILE, the active profile, default), with the SDK’s environment defaults off so no API key or token shadows it; a missing profile fails the model build. auth = "adc": Claude on Vertex AI (the SDK’s vertex.WithCredentials) with Application Default Credentials found as for Gemini (missing ones fail the build; the SDK’s WithGoogleAuth would panic), project and location as for Gemini ([llm.anthropic] project_id, location), the quota project sent, first-party credentials ignored, and server-side refusal fallback off (Vertex AI has none); the models need enabling in Vertex AI’s Model Garden. Otherwise api_key, else SDK resolution (ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, ant auth login profile, workload identity); optional base_url
openai ADK OpenAI model (Responses API) wrapped for images and text tool calls [llm.openai] key and base URL
ollama Same as openai Uses [llm.openai]; base URL defaults to http://localhost:11434/v1 when unset or still the OpenAI default; key is always the placeholder ollama (never the OpenAI key)
bedrock The anthropic adapter with the SDK’s bedrock option (SigV4, Bedrock’s URL for the region) [llm.bedrock] region (else AWS_REGION, the profile’s), profile, auth (since 2026-10-04: "oauth", an AWS IAM Identity Center sign-in for the profile; "" access keys; both through the chain), model (a Bedrock model or inference profile ID, required). AWS’s standard chain (environment, shared config and credentials, SSO, instance and task roles) checked when the model is built (30 s), or a Bedrock API key in AWS_BEARER_TOKEN_BEDROCK. No server-side refusal fallbacks
azure A model whose name starts with claude: the anthropic adapter over the SDK’s foundry client (https://<resource>.services.ai.azure.com/anthropic/, or anthropic_base_url); any other: the openai adapter over Azure OpenAI’s v1 API (https://<resource>.openai.azure.com/openai/v1/, or base_url) [llm.azure] resource, model (the deployment, required), api_key (else AZURE_OPENAI_API_KEY, or ANTHROPIC_FOUNDRY_API_KEY for Claude; sent as api-key or x-api-key), or auth = "entra": Azure’s default credential chain (environment, workload and managed identity, the Azure CLI and Developer CLI logins), a token for cognitiveservices.azure.com or ai.azure.com per request, one checked when the model is built
vertex-anthropic anthropic with auth = "adc" as anthropic’s adc ([llm.anthropic] project and location)
api The openai adapter (Responses API, §3.4) with request and response middleware for gateways that speak it [llm.api] base_url, headers, and a token from token_script (shell, Python or TypeScript) put wherever {{TOKEN_SCRIPT}} appears; no API key, no OpenAI settings from the environment

Since 2026-10-04 Blitz also signs in for the account methods above, as an addition to API keys: the desktop app’s Sign in and blitz auth login run the vendor’s own tool on the service’s machine (gcloud, ant, aws, az; spec_021_service SVC-56), then the service builds the failed models again.

  • MDL-10 Empty provider: pick Gemini if a Gemini key exists, else Anthropic if its key exists (its configured model unless default_model is set), else OpenAI-compatible if key or base URL set, else local Ollama. Unknown provider: Gemini if a Gemini key exists, else error “unsupported or unconfigured LLM provider”.
  • MDL-10a 2026-11-04 (scan N26-engine-runtime#17). An unknown provider is an error whatever keys are set (MDL-01a), no longer Gemini when a Gemini key exists.
  • MDL-12 2026-10-29. Ollama with no model ([llm.ollama] model empty) uses the first model Ollama lists, found on the first call (a stopped Ollama doesn’t stop Blitz starting) and kept (ollamaAuto, pkg/engine/runtime/ollama.go); none pulled, or Ollama not answering, fails the call with what to do (ollama pull …; open the Ollama app or ollama serve). An OpenAI-compatible call that fails carries what the provider said (providerError: the SDK’s OpenAI API error: 404 Not Found leaves the message out), the key and remembered secrets masked; Ollama’s 404 names the model it doesn’t have and suggests choosing one or ollama pull.
  • MDL-12a 2026-10-29 (the owner’s request, after replaying a conversation on qwen2.5-coder:7b). Ollama’s limits as an agent are said where it’s chosen: with Ollama selected, Settings › Providers shows desktop.keys.ollama_limits under the form (as OpenAI shows openai_key_only). It says local models are less reliable as agents (small ones describe the steps instead of running them, or write tool calls as text), and to choose one with strong tool calling (such as qwen3:8b or larger) for agent work, leaving small ones for chat and quick questions. The providers guide’s Ollama section says the same at more length.

3.1 Anthropic adapter

  • MDL-20 Default model claude-opus-5; default max_tokens 16000 unless the request sets one.
  • MDL-21 The system instruction becomes one system text block with ephemeral cache control (prompt caching).
  • MDL-21a Tool and rolling conversation cache breakpoints (spec_056 CA-28): besides the system block, the adapter places an ephemeral cache_control breakpoint on the last tool declaration (p.Tools[len(p.Tools)-1]) and on the last cacheable content block of the conversation’s last stable turn (the second-to-last message, p.Messages[len(p.Messages)-2], when len(p.Messages) >= 2), so the tool prefix and earlier turns and tool results are read from the prompt cache as the conversation grows.
  • MDL-22 Function declarations become tools with JSON Schema input (raw JSON schema preferred; genai Schema converted: lower-case types, enums, formats, items, properties, required, nullable → [type,"null"]). An absent schema is an empty object.
  • MDL-23 Contents map to messages; consecutive same-role contents merge (so parallel tool results share one user message). The conversation must start with a user message. FunctionCall ⇄ tool_use; FunctionResponse → tool_result (JSON body; is_error when the response has a non-empty error). An image directly after a tool result is placed inside that tool result (for view_image); other images are image blocks; a PDF is a document block, inside the tool result after view_document (spec_011_images IMG-53); other unsupported inline media become a text placeholder.
  • MDL-24 Thinking blocks round-trip unchanged: thinking text in Thought with its signature in ThoughtSignature; redacted thinking is stored with a redacted: prefix. Unsigned thoughts and user-side thoughts are dropped.
  • MDL-25 temperature is sent only to models that accept sampling (prefixes claude-haiku-4-5, claude-sonnet-4-6, claude-opus-4-6, claude-sonnet-4-5, claude-opus-4-5, claude-opus-4-1, claude-sonnet-4-, claude-opus-4-0, claude-3); current models reject it with 400.
  • MDL-26 Server-side refusal fallback on claude-opus-5* and claude-fable-5*: fallbacks = "default" routes by category (beta server-side-fallback-2026-07-01); a model ID pins one fallback (beta 2026-06-01); off disables.
  • MDL-26a On Vertex AI (auth = "adc", vertex-anthropic), which has no server-side fallback, a refusal is retried client-side by the SDK’s lib/betafallback middleware on any model: a model ID is the fallback, and default falls back to claude-opus-4-8 (none when that is the model itself). The middleware wraps Vertex’s, so the retry’s model reaches the URL path. Each session keeps its own BetaFallbackState (the ADK’s invocation names it), so a session that fell back stays on the fallback and others start on the primary (BL-ENG-22).
  • MDL-27 Streaming yields partial text deltas, then one aggregated final response (same shape as Gemini). Non-streaming yields one response. A non-streaming request the SDK won’t send unstreamed (max_tokens a reply could take more than ten minutes to fill: an engine turn’s full output, or a thinking budget) is streamed anyway and yields only the final response, rather than failing with “streaming is required for operations that may take longer than 10 minutes” (2026-10-29: the coder subagent on [llm.api]).
  • MDL-28 Stop reasons: max_tokens → MaxTokens; refusal → Safety with ErrorCode=refusal and the note “The model declined to continue this request. ()” appended as text; else Stop. An empty final response gets one empty text part. ModelVersion = the model that served.
  • MDL-28a 2026-11-04 (scan N26-engine-runtime#23: a tool_use cut off at max_tokens went to the tool with {}, the SDK having emptied its unfinished input). A tool call the reply stopped in (the last block of a max_tokens reply, or input that doesn’t parse) isn’t run: the reply gets the note “(The call to was cut off before its arguments were complete, so it wasn’t run.)”, and the turn ends with ErrOutputLimit as before.
  • MDL-29 Usage: prompt = input + cache reads + cache writes; cached = cache reads; cache writes reported via CustomMetadata["cache_creation_input_tokens"].
  • MDL-30 Errors: 401/403 → “authentication failed … check llm.anthropic.api_key or ANTHROPIC_API_KEY”; 429 → “rate limited” (unless it’s a quota, MDL-30a); other status → “API error (N)”.
  • MDL-30a Quota: a refusal with Google’s RESOURCE_EXHAUSTED — a genai APIError with that status (Gemini, on the API or Vertex AI), or a 429 whose body is a Google error (or a list of them, as Vertex AI sends) with that status (Claude on Vertex AI) — is a *runtime.QuotaError: “quota exceeded: <Google’s message> (raise the quota in the Google Cloud console, IAM & Admin › Quotas, or wait for it to reset)”, never “rate limited”. Every provider model’s errors pass through it (the settings wrapper), so turn errors, doctor --online and job runs say so; ModelErrorSummary keeps a quota error whole, on one line, where it keeps only the first line of others. SDK retries still apply (a per-minute quota recovers).

3.2 OpenAI-compatible wrapper

  • MDL-40 Never streams (text-encoded tool calls are only recognisable in complete responses).
  • MDL-41 Text tool calls: a text part that is (optionally code-fenced) JSON {"name", "arguments"|"args"|"parameters"} becomes a FunctionCall only if the name is a tool offered in that request, so quoted JSON can’t trigger arbitrary tools. file_path is aliased to path.
  • MDL-42 Images: the ADK OpenAI model rejects image parts, so each image is replaced by a unique marker text (prefixed U+2063) and a request middleware swaps markers for input_image data URLs in the outgoing JSON. Markers travel in the request context; nothing is shared between requests.

3.3 Images in history

  • MDL-45 Every model is wrapped so stored-image references in a request are expanded to bytes just before sending; history and session files only ever hold references (spec_011_images).

3.4 API provider (api)

Since 2026-10-21 (the owner’s request: a provider for a gateway that speaks OpenAI’s Responses API but signs requests with its own headers and a short-lived token).

  • MDL-100 Settings: [llm.api] base_url (required, absolute http/https; a model’s requests go to its API’s path under it, MDL-113), model, headers (a table of header name → value, at least one), token_script and token_script_language (shell, the default, python or typescript). A model is built through the adapter for the API it speaks behind the gateway (MDL-100b); for the Responses API that is the openai adapter (§3.2: images, text tool calls; streaming as MDL-100c says) with Blitz’s shared HTTP client (§4). Config that breaks these rules fails the build (the model is then unavailable, WS-05), saying which rule: a bad URL, {{TOKEN_SCRIPT}} in the URL’s scheme or host, no headers, a header name that isn’t an HTTP token, {{TOKEN_SCRIPT}} used with no token_script, a token_script that nothing uses, an unknown language.
  • MDL-100b Until 0.9.10; MDL-112 and MDL-113 replace the name’s choice and the one path with settings. The model’s name decides the API its requests are written in, since a gateway passes each vendor’s request on as it is: a claude… model speaks Anthropic’s Messages API through the anthropic adapter (§3.1: streaming, prompt caching, thinking, tool use; no server-side fallback, fallbacks = "off"), any other model OpenAI’s Responses API. Both are sent to <base_url>/responses (the anthropic adapter’s /v1/messages and its ?beta=true are rewritten) and signed alike (MDL-101–105). The anthropic client takes nothing from the environment (ANTHROPIC_API_KEY, ANTHROPIC_BASE_URL), and its placeholder key’s X-Api-Key and Authorization are removed unless configured. MDL-104’s body rules and MDL-104b and MDL-106 are the Responses API’s; a Messages request and answer are the anthropic adapter’s as they are. Verified 2026-10-21 against a gateway: claude-sonnet-5-5 (Messages, tool use), gpt-6-luna (Responses, tool use); that gateway’s gemini-… models answered 500 to both formats, so Gemini’s own API isn’t offered.
  • MDL-100c Built (2026-11-01). The api provider asks for the Responses API streamed (stream: true), so a long reply keeps data flowing and is never cut by a timeout between Blitz and the model, as Claude’s Messages are streamed (MDL-27). The openai adapter reads replies whole, so the stream is folded into the one response its last event carries (response.completed, response.incomplete, or response.failed, whose error fails the call; an error event fails it too, and a stream that ends without one is “the model’s reply ended before it was complete”); comments and events Blitz doesn’t need are skipped (foldStream in pkg/engine/runtime/apiresponse.go). A gateway that refuses stream as OpenAI refuses a parameter (400 with param: "stream", as gateways and Blitz Enterprise services before GW-04 do) gets the request again unstreamed, and the model’s later requests are sent whole, so it’s asked once. A gateway that answers a streamed request with plain JSON is read as before.
  • MDL-101 {{TOKEN_SCRIPT}} (exactly that) in a header’s value or in base_url’s path or query is replaced, on each request, by the token: every occurrence, in the URL escaped as a query value. It is never replaced in the request body, which holds the conversation. The script isn’t run when nothing uses the placeholder.
  • MDL-102 The token is the script’s output, trimmed; empty output, more than one line, a failure or 30 s without finishing is an error naming the script’s language and its standard error (trimmed to 256 characters, any token in it redacted). shell runs /bin/sh -c <script>; python runs python3 -c <script>; typescript writes the script to a temporary .ts file and runs node --experimental-strip-types --no-warnings <file> (Node 22.6 or later). A missing interpreter says which one to install. The script runs with the service’s environment, outside the agent’s sandbox, like api_key_command (MDL-55); a project’s settings can’t set it (CFG-05, llm is never taken from a project).
  • MDL-103 The token is kept per session (the ADK session the call belongs to; calls outside a session share one entry), in memory only, for at most 64 sessions (least recently used dropped). The script runs when a session first needs a token and again after the token is dropped (MDL-105); a new session runs it afresh. Concurrent calls in one session share one run. Since 0.9.10, one cache serves every model and the model list (MDL-114) with the same token script (its language and text), so listing the gateway’s models doesn’t run the script again for a call, nor a call for a listing. It isn’t run when the model is built, so a short-lived token isn’t spent before a session starts; blitz doctor --online runs it in its model request (MDL-109). A script that fails ends the call before any request is sent, with [llm.api] token script: <error>, and nothing is kept.
  • MDL-104 Requests: the configured headers are set on each one (replacing the SDK’s). Authorization, OpenAI-Organization and OpenAI-Project are removed unless configured, so no OpenAI key or setting from the environment (OPENAI_API_KEY, OPENAI_ORG_ID, OPENAI_PROJECT_ID) reaches the gateway; the SDK is given a placeholder key for the same reason. A POST to …/responses always has "store": false and "stream": false in its JSON body; the rest of the body is kept as the adapter wrote it, except for MDL-104b.
  • MDL-104b The request follows the model, not the adapter: a model known to reject sampling gets no temperature or top_p (current Claude models, as supportsSampling decides for the anthropic provider, and OpenAI’s reasoning models, gpt-5*, o1*, o3*, o4*). A gateway’s model names can be aliases, so a 400 that refuses a field (OpenAI’s code unsupported_parameter or unsupported_value with its param, or a message Unsupported parameter: '<field>' or Unsupported value: '<field>' …) is sent again without that field, and the model’s requests leave it out from then on (in memory, until the service restarts). Only fields a request can do without are dropped: temperature, top_p, reasoning, max_output_tokens, parallel_tool_calls; a refusal of any other field is the call’s error.
  • MDL-105 Errors: a 401 or 403 drops the session’s token, runs the script once more and sends the request once more with the new token. A second 401/403 (or a script failure then) fails the call with [llm.api] the API rejected the token (HTTP <status>). Check the token script, sign in again if needed, then retry (no final full stop, as for every error), never read as a model response. A connection error or 5xx drops the session’s token, so the SDK’s retry (MDL-52) runs the script for a fresh one. Any other HTTP error reads [llm.api] HTTP <status> <text>: <reason>, the reason being the body’s error.message, else the start of the body (either redacted, MDL-108, and cut to 256 characters), since the SDK’s own text is only the status. An error response the SDK can’t read (the gateway’s own {"status":500,"error":"Internal Server Error",…}) is reported the same way, from the status and body the middleware keeps for the call’s last attempt. Every api provider error starts [llm.api], never the adapter’s openai: call failed, whatever model the gateway serves; an Anthropic error’s own text, which quotes the request’s URL, isn’t used.
  • MDL-105a 2026-11-04 (scan N26-engine-runtime#15, #16: the errors’ hints named the wrong credentials where an adapter is reused, and the organization’s errors said [llm.api] and “the token script”). A refused sign-in names what to check for how the model signs in: [llm.anthropic]’s key or api_key_command, ant auth login (auth = "oauth"), Google Cloud’s credentials (Claude on Vertex AI), AWS credentials and [llm.bedrock], or [llm.azure]’s key or Entra sign-in. Every OpenAI-compatible model’s error adds what the server said, masked (providerError), Azure OpenAI’s and those built without a provider name too. Through an organization’s service (the enterprise provider) the errors are its: “your organization’s service refused your sign-in (HTTP 401): sign in again (Settings › Organization, or blitz enterprise login), then retry”, and other errors “your organization’s service: HTTP 404 Not Found: …”, without [llm.api]. Gemini’s errors other than quota still carry the SDK’s text only.
  • MDL-106 Responses: a successful (2xx) JSON response from …/responses whose error.message isn’t empty is a failure, whatever its status (the gateway can answer 200 with a logical error): it is read as "status": "failed" (the adapter’s ErrResponseFailed, quoting the message). A message’s content part of type text is read as output_text. Everything else is the adapter’s: output items in order (reasoning gives only hidden thoughts; function_call items become calls, whose results go back as function_call_output with the same call_id), usage as tokens, no text and no call an error (ErrNoTextOrToolContent).
  • MDL-107 providerOf names the api model by its API (MDL-100b): anthropic for a Claude model, so per-model settings are Anthropic’s (supportsSampling and the rest, MDL-72), else openai, so they drop seed as for OpenAI.
  • MDL-108 Tokens never reach logs, the audit log, errors or doctor’s output: each token is remembered by the redactor (redact.Remember, pkg/redact) when fetched, and errors quote the script’s standard error only after redaction.
  • MDL-108a 2026-11-21 (re-check of N26 engine-runtime#27). The organization’s token fetched again after a 401 is remembered by the redactor too, not only the first.
  • MDL-108a 2026-11-04 (scan N26-engine-runtime#27). The organization’s access token (the enterprise provider) is remembered by the redactor too, each time it is fetched.
  • MDL-109 blitz doctor reports the api provider under credentials: MDL-100’s checks, its endpoint and its headers by name (never a value), and whether the token comes from a script. The script isn’t run for that; --online’s model request runs it first, so its result says which failed: the script ([llm.api] token script: …), the token (MDL-105) or the model. blitz models api lists only [llm.api] model, as for Bedrock and Azure (MDL-56).
  • MDL-112 0.9.10 (issue #105: the gateway’s models each speak their own API, and Blitz can’t know every gateway’s). Each model’s API is the settings’: [llm.api.apis] maps a model’s name to one of responses (OpenAI’s Responses API, the openai adapter), chat_completions (OpenAI’s Chat Completions, what OpenAI-compatible servers speak: the same adapter, openaimodel.APIChatCompletions), messages (Anthropic’s Messages, streamed: Claude’s, and Anthropic-compatible servers’), gemini (the Gemini API’s generateContent) or vertex (Vertex AI’s, for Google’s models); "*" is every model not named. A model in neither goes by its name (APIOf): claude… Messages, gemini… the Gemini API (before 0.9.10, the Responses API), any other the Responses API. Google’s two go through the gemini adapter with a placeholder key (Vertex AI’s express mode: no project, location or Google credentials, none taken from GOOGLE_CLOUD_PROJECT or the rest of the environment) and the provider’s middleware as its client’s transport, so they’re signed, retried, and their errors worded as the others’ (MDL-101–105); X-Goog-Api-Key and Authorization are removed unless configured. Per-model settings follow the API (MDL-107: Google’s are gemini’s, with their thought signatures kept); no provider-side tools are offered through the gateway, so Gemini’s include_server_side_tool_invocations is never sent. An API that isn’t one of these fails the build, naming the model and the five.
  • MDL-113 Each API’s model requests go to its path under base_url: [llm.api.paths] by API, else /responses (Responses, and Messages, where gateways that route by the request’s model take Claude’s), /chat/completions, /models/{model}:{method} (Gemini) and /publishers/google/models/{model}:{method} (Vertex AI). {model} is the model’s name as it is (a / in it stays a path separator, as gateways that route on it expect; Google’s names have none) and {method} Google’s generateContent or streamGenerateContent (a streamed call, ?alt=sse kept); nothing else is filled in, and a path is a path alone: it starts with / and has no query, fragment, spaces or {{TOKEN_SCRIPT}}. Since 2026-11-14 (the owner’s request: the gateway shouldn’t enforce Google’s) the fill-ins are offered, never required: a Google path without {method} (or {model}) is the gateway’s to route, such as one fixed path for every Gemini call; the form shows each API’s fill-ins in a tooltip (an ⓘ beside its path) instead of requiring them. base_url’s query goes on every request (MDL-101). Requests that aren’t model calls go where the adapter sends them. The organization’s service (spec_053_enterprise EN-20) takes Claude’s at /messages.
  • MDL-114 The gateway’s models are what it lists: a GET to models_path under base_url (default /models), signed as the model requests are, whose JSON is read in the shapes servers give it: {"data": [...]} (OpenAI’s, Anthropic’s and compatible servers’), {"models": [...]} (Gemini’s, models/ dropped, those that can’t generateContent left out; Ollama’s), or a list; each entry an id, model or name, or the name alone. The first page only. models_path = "none" says the gateway doesn’t list them: the menus have model, models and the models [llm.api.apis] names ("*" aside; MOD-42, which [llm.api] models is too). A list that fails (an HTTP error, worded as MDL-105’s; not JSON; empty) is the provider’s error beside those configured models, the default path’s included: a gateway with no list says so (HTTP 404) until models_path is set or none (the owner’s call, 2026-11-10: errors are reported, never hidden). blitz models api, the model menus and blitz doctor (each model’s API and path, and where the list is) use it.
  • MDL-115 2026-11-12 (#111). The list can be on another server: models_path is a path under base_url or an absolute http/https URL ({{TOKEN_SCRIPT}} only in its path or query, as base_url’s). [llm.api.models_headers] sign the list’s request in place of headers, {{TOKEN_SCRIPT}} in them as in headers (the gateway’s token script and cache, MDL-103). A path under base_url or a URL on its server (scheme, host and port) is sent models_headers, else the gateway’s headers, and a path gets base_url’s query; a URL on another server is sent models_headers alone, never the gateway’s headers or query, so none of the gateway’s credentials reach it. Header names and values are checked as headers’ are (MDL-100). Describe withholds their values as it does headers’ (CFG-44); the desktop form shows Model list headers under the list’s field while the gateway lists its models (DSK-61), and blitz doctor names them (“models listed at https://catalog.example.com/models with headers X-Catalog”, or “with no headers”).
  • MDL-110 The settings are written by SetProvider with ApiProviderSettings (spec_002_config CFG-45b) and shown by DescribeConfig with header values withheld (CFG-44), so the desktop form (spec_024_desktop DSK-61) never receives one.
  • MDL-111 2026-10-26 (the owner’s usability pass). ConfigService.CheckApiKey tries a key that isn’t saved: the scope’s settings with the key in place of the provider’s own (its key command and sign-in set aside: Gemini’s and Anthropic’s auth cleared), listing the provider’s models with it (ListModels’ listing, so the same timeout and retries). It answers whether the key works, why not, and the models it reaches; nothing is written, and the key isn’t kept or cached. It takes gemini, anthropic and openai; other providers, or an empty key, are refused (InvalidArgument). The desktop form tries a key as it’s pasted (spec_024_desktop DSK-104).

4. HTTP client, retries, stalls

  • MDL-50 All SDKs share an HTTP client: dial timeout 30 s, TLS handshake 15 s, response-header timeout = stall limit, and a body wrapper that cancels the request if no bytes arrive for the stall limit (each read resets the timer), returning ErrStalled “model API stopped responding: no data for ”.
  • MDL-51 Stall limit = llm.stall_timeout_seconds (default 600 s; ≤0 → 10 min). It also bounds non-streamed generations, so it must exceed the longest one.
  • MDL-51a 2026-11-04 (scan N26-engine-runtime#19: the default was written twice and the error named no setting). The default is config.DefaultStallTimeoutSeconds (600), used by both; the error says “model API stopped responding: no data for 10m0s (llm.stall_timeout_seconds sets how long to wait)”.
  • MDL-51a The client health-checks its HTTP/2 connections: one that receives nothing for 30 s is pinged and closed when no answer comes within 15 s. Its requests fail with a connection error, which the SDKs retry on a new connection, so a connection dropped without a word (a VPN, NAT or network change) costs under a minute rather than the stall limit for each attempt. A slow model still answers pings and isn’t cut off.
  • MDL-51b When a request’s connection fails (not cancelled) and retries are on (llm.max_retries > 0), the transport tells the turn in passing (runtime.WithTurnStatus, a transient notice): “model.reconnecting”, with the gist of the error (“unexpected EOF”, not the method and URL). Clients are shared by stall limit and whether retries are on. Background tasks don’t send it to the turn.
  • MDL-52 Retries = llm.max_retries (default 3; negative → 0) on rate limits, overload, 5xx and dropped connections. Gemini: Attempts = retries+1, initial delay 1 s, max 30 s. Anthropic and OpenAI: SDK backoff (0.5 s doubling to 8 s with jitter, honouring Retry-After).
  • MDL-53 A stream that fails after output has been shown is not retried.
  • MDL-54 Proxies (PAR-MOD-05): the shared client clones Go’s default transport via pkg/netutil (netutil.CloneDefaultTransport), so HTTPS_PROXY, HTTP_PROXY and NO_PROXY apply, as they do to MCP and web search. [network] ca_file (a PEM bundle) is loaded through pkg/netutil (netutil.SetExtraCAs, invoked by engine.SetupNetwork when a workspace opens; an unreadable file or one without certificates is a warning) without mutating http.DefaultTransport in place across concurrent requests, so every client built with netutil.CloneDefaultTransport or netutil.NewClient trusts it, web_fetch included (via netutil.TLSConfig). web_fetch also goes through the proxy the environment names: the host is resolved and every address checked as public first (unless web.allow_private), and only the proxy’s own address, often private, is dialled without the check (spec_008_web WEB-04). [network] is never taken from a project. The browser’s traffic doesn’t go through an upstream proxy.
  • MDL-55 Keys from a command (PAR-MOD-04): with api_key empty, llm.<provider>.api_key_command (gemini, openai, anthropic) runs through /bin/sh when a model is built (a failure, an empty output or more than one line fails the build) and again when api_key_ttl (a Go duration, default 5m) has passed; each request carries the current key (Gemini’s x-goog-api-key, OpenAI’s Authorization: Bearer, Anthropic’s X-Api-Key), so a rotated key keeps working in a long session. The output is cached in memory only, per command and TTL, and shared by the models using it; the command has 30 s. A provider with a key command counts as set up (blitz models, project models).
  • MDL-56 blitz models [provider…] (PAR-MOD-03) asks each configured provider (a key or key command, adc, oauth; Ollama when it’s llm.provider; Bedrock and Azure, which show only their configured model, their consoles listing the rest), or those named, for its models, in parallel with 20 s each, through the same clients: Gemini’s model list (those that generate content, models/ stripped), Anthropic’s and OpenAI’s (OpenAI-compatible, Ollama’s too) model endpoints. Each is printed provider/model with the price Blitz knows (input and output per million tokens, [pricing] included) or -. A provider that can’t answer is shown with why, and the command exits 1; none set up is a usage error.

5. Fallback chain

  • MDL-60 The chain reports the primary’s name. It tries models in order, skipping those whose circuit breaker is open (threshold: 1 failure — SDK retries already ran). If every breaker is open, it tries them all rather than fail unasked. Breakers are consulted just before each attempt (a half-open trial is reserved).
  • MDL-61 It moves on only when a model fails before yielding anything. After output has been yielded, an error ends the call (a failure is recorded). Cancellation never moves on and records no verdict (Abandon). A consumer stopping early counts as success.
  • MDL-61a 2026-11-05 (scan N26 engine-runtime#20: the spec didn’t say which errors move on; the owner decided every one does). The chain moves on, and opens the failed model’s breaker, for every error a model returns before yielding anything, client errors included: a 400, 401/403 (a broken key), 404 (an unknown model), a context too long, an organization’s budget refusal (ErrOrgLimit), as well as 5xx, 429/529, connection failures and stalls. A cancelled call (context.Canceled, or its context done) is still no error to fall back on. So that a broken key or a bad model name isn’t hidden behind the fallback, the fallback’s response also carries the primary’s error (CustomMetadata["blitz_fallback_reason"]: this call’s, or, while its breaker is open, the one that opened it; one line, cut at 300 characters), and the notice names it: “model.fallback_error” (" failed (); answering with fallback for now."), “model.fallback” when no error is known.
  • MDL-61b 2026-11-05 (spec_056 CA-111). One error doesn’t move the chain on at once: a context too long (api.ErrContextLength). The conversation is summarised to fit and the same model tried again first; only then does the chain move on.
  • MDL-62 A response from a fallback is marked CustomMetadata["blitz_fallback_from"] = <primary> and ModelVersion = <fallback> if empty, so cost is priced by the model that answered.
  • MDL-63 If all fail: “every model failed: ”.
  • MDL-64 The engine notifies the user once when a fallback starts answering (“model.fallback”) and once when the primary is back (“model.fallback_recovered”), not on every call. During a turn the notice is one of the turn’s events (notice, runtime.WithTurnNotices), so the terminal and the desktop show it in the conversation; outside a turn it goes to WithNotice (the service’s log).
  • MDL-64a 2026-11-04 (scan N26-engine-runtime#8: the state was one per engine, so a background task on its fallback and the turn on its primary flipped the notices on every call, and “is answering again” named the active agent’s model). “Once per change” is per run: per session, and per background task apart from it. “model.fallback_recovered” names the primary that recovered. Forgetting a session drops its state.
  • MDL-65 Breaker behaviour (pkg/engine/breaker): after the threshold the breaker opens for 15 s, doubling up to 5 min; then one half-open trial call is allowed.

6. Per-model settings

  • MDL-70 [model_settings."<model>"] keys are normalised to the bare model name (provider prefix dropped); when both gpt-5 and openai/gpt-5 exist, the bare key wins deterministically.
  • MDL-71 Every built model (primary, each fallback, each pinned agent’s model) is wrapped to apply its own settings on each call from a lookup carried in the run context, so changes apply from the next call, even in turns already running. The request is copied, never mutated (it is shared across the chain). (Decision: settings apply per built model, not per agent; applying them per agent would give fallbacks the primary’s settings.)
  • MDL-72 Unsupported settings are dropped from the request (debug-logged) and reported by /model_settings: OpenAI/Ollama have no seed; Anthropic accepts max_tokens, and temperature only on sampling-capable models; top_p and seed are not sent to Anthropic. Gemini accepts all.
  • MDL-73 reasoning_effort (minimal|low|medium|high|max; xhigh is read as max) and thinking_budget (tokens, 0 = off) become genai ThinkingConfig (level and budget; max is high there). The OpenAI adapter maps them to reasoning.effort (a budget only chooses none or some). Gemini 2.5 takes no level; Gemini 3 rejects a level with a budget, so the level wins. Anthropic: the exact effort reaches the adapter in the request context and goes to output_config.effort (minimal → low) on models that take it (Opus 4.5, Sonnet/Opus 4.6+, and models without sampling parameters); a budget becomes thinking enabled (at least 1024, max_tokens raised above it, no temperature) or disabled at 0, on Claude 3.7 and later. Models that think adaptively (those without sampling parameters: Opus 4.7 and later, Sonnet 5, Fable) refuse budget_tokens: there a budget above 0 sends thinking adaptive and, unless an effort is set, the effort it stands for (up to 4096 tokens low, 16384 medium, 65536 high, above that max); 0 sends disabled, except to models that always think (Opus 5.5, Fable), which refuse it: it isn’t sent, and SettingApplies (the value-aware SettingSupported) makes /model_settings report it unsupported (MDL-72). Thinking blocks round-trip with their signatures (MDL-24).
  • MDL-73a 2026-11-05 (spec_056 CA-10, CA-13). Each model has one record (ModelInfo), which these rules read:
    • Names: Bedrock’s (us.anthropic.claude-…-v1:0), Vertex AI’s (claude-…@version) and Gemini’s (models/…) are read as the model they name. Claude on Bedrock now takes its effort, thinking and sampling settings as Claude does elsewhere.
    • Learned refusals: a setting a model refuses with a 400 (OpenAI’s “Unsupported parameter”, Gemini’s “Unknown name”, Anthropic’s “Extra inputs are not permitted”) is learned and left out from then on, the call sent again once without it. So are tools, images, a stream, system instructions and reasoning settings.
    • Kept and cleared: what’s learned is kept in ~/.blitz/models.learned.toml for 30 days. blitz models forget <model> clears it.
  • MDL-74 The session effort (/effort, --effort, SetSetting effort) overrides every model’s reasoning_effort for the requests only: ModelSettings and saved settings are unchanged. auto (or empty) clears it. It is not persisted.

5a. Attachments

  • MDL-85 What each model takes as attachments, and how (inline, uploaded, as text), is runtime.AcceptedMedia (spec_011_images IMG-62): Gemini images (HEIC too), PDFs, text, audio and video (Files API above 14 MB, on the Gemini API); Claude images, PDFs and text; others images, text and PDFs as their text. The expansion wrapper routes each stored file by it (IMG-64), and an Anthropic request takes text files as text blocks.

6a. Speech

  • MDL-90 [audio] model (provider/model) is the speech model generate_audio reads aloud with (spec_006_filetools FS-74); empty, the default, means none. runtime.NewSpeaker builds it when the workspace opens and again when its settings are reloaded (a key or the model set in the desktop): a Gemini speech model through genai’s client as [llm.gemini] signs in (an API key, a key command or Application Default Credentials on Vertex AI), or an OpenAI one (/audio/speech, with [llm.openai]’s key and base URL). Another provider is refused (“can’t generate speech”), and a model that can’t be built is a warning when the workspace opens, never a failure, and is reported by the workspace’s settings (speech_error).
  • MDL-91 Gemini: each chunk of text (at most 4,000 characters, cut at paragraphs, then lines, then sentences, then words, so a conversation’s lines stay whole) is one generateContent call with response modality AUDIO and a prebuilt voice ([audio] voice, the call’s, else Kore), or for two speakers a multi-speaker voice configuration (each {name, voice}, defaults Kore and Puck) and the prompt “TTS the following conversation between A and B:”. The 16-bit PCM of every chunk (its rate from the media type, 24 kHz by default) is joined and given a WAV header; the result has its length in seconds.
  • MDL-92 OpenAI: MP3, the voice the call’s or [audio] voice, else coral. Two speakers are spoken turn by turn (a run of one speaker’s lines, a line naming no speaker staying with the last), each in its voice (defaults coral and ash), and the MP3s joined; one voice is spoken in chunks of 4,000 characters.
  • MDL-93 A speech call’s usage (Gemini’s tokens, summed over its chunks; reported even when a chunk fails) goes in the session’s usage, priced by [pricing] (defaults for gemini-2.5-flash-preview-tts and gemini-2.5-pro-preview-tts) but never as the conversation’s last prompt; a call without usage (OpenAI’s) makes the session’s cost unknown rather than wrong.
  • MDL-95 2026-11-06. [images] model (provider/model) is the image model generate_image draws with (spec_006_filetools FS-80); empty, the default, means none. runtime.NewPainter builds it as NewSpeaker builds the speech model (when the workspace opens and when its settings are reloaded), a Gemini image model through genai’s client as [llm.gemini] signs in; another provider is refused (“can’t draw pictures”), and a model that can’t be built is a warning, reported by the workspace’s settings (image_error). A call is one generateContent with the prompt and the pictures to start from, response modalities TEXT and IMAGE, and an ImageConfig when a shape or size is asked for. The first picture in the answer is kept (thoughts skipped, its text returned with it); an answer without one is an error giving the model’s text, its finish reason or the prompt’s block reason.
  • MDL-95a 2026-11-06 (the owner chose the organization’s gemini-3.1-flash-image as a conversation’s model and got “openai: response included no output items”). The organization’s image models. [images] model = "enterprise/<id>" (or the bare id when [llm] provider is enterprise) draws through the organization’s service: newOrgPainter signs with the person’s session as the organization’s models do (enterpriseProvider, EN-20) and posts a Responses request to /api/v1/responses with an image_generation tool (aspect_ratio, image_size: the enterprise gateway’s GW-04b) and the pictures to start from as input_image data URLs; the first image_generation_call’s result is the picture (its type sniffed), the messages’ text comes with it, and usage is billed as MDL-96 says. A model the organization doesn’t offer by that id is refused, never its default; a Messages model (Claude) can’t draw. A failed answer gives the service’s message (GW-04c’s empty_output included), an HTTP error the service’s words. In a conversation, a picture in an organization model’s answer (or any [llm.api] gateway’s) reaches it as a picture: the api provider swaps each image_generation_call item, whole or streamed, for a marker message the ADK adapter reads, keeping the picture in the call’s context, and puts the picture back in its place (apipictures.go); it is then kept like any picture a model made (spec_056 CA-70).
  • MDL-96 An image call’s usage goes in the session’s usage as a speech call’s does (MDL-93), as an image call in its ledger (RecordMedia), priced by [pricing]: defaults for gemini-3.1-flash-image ($0.50 in, $60 out a million tokens, about $0.067 a 1K picture), gemini-3.1-flash-lite-image ($0.25, $30) and gemini-3-pro-image ($2, $120).
  • MDL-97 2026-11-06. gemini-4-argon’s default price is its published one, no longer a placeholder at Gemini 3.8 Flash’s: $2 in, $10 out and $0.10 cached a million tokens through 2026-11-30, then $4, $20 and $0.20 (a PriceChanges entry).
  • MDL-97a 2026-11-26 (the owner’s figures). The rest of Gemini 4 is priced too, a million tokens, output including thinking tokens: gemini-4-carbon as Argon ($2 in, $10 out, $0.10 cached through 2026-11-30, then $4, $20 and $0.20: its own PriceChanges entry); gemini-4-neon $3, $15 and $0.15; gemini-4-hydrogen $1.50, $7.50 and $0.075. A dated version (gemini-4-carbon-001) has its model’s price (PriceFor’s longest prefix); a Gemini 4 model not listed has none. spec_002’s pricing line, which still gave Argon its placeholder price, says the same now.

7. Test model

  • MDL-80 MockLLM returns scripted contents in order (then “Done.”), records requests, and can attach usage, ServedBy and metadata. It backs tests; a model that can’t be built is NewUnavailableModel instead, which fails every call (WS-05).

8. Known gaps

  • Reasoning settings per model (effort, thinking budgets) are not implemented.