LLM Backends
Supported LLM providers, configuration, and provider-prefix routing.
Overview
Cogitator supports 11 LLM providers out of the box. Backends are created lazily -- a provider's client is only instantiated the first time an agent needs it. The provider is determined by the model string prefix.
const cog = new Cogitator({
llm: {
defaultProvider: 'openai',
providers: {
openai: { apiKey: process.env.OPENAI_API_KEY! },
anthropic: { apiKey: process.env.ANTHROPIC_API_KEY! },
ollama: { baseUrl: 'http://localhost:11434' },
},
},
});Provider Routing
Model strings follow the provider/model-name format:
'openai/gpt-6.1-sol'; // routes to OpenAI
'anthropic/claude-sonnet-5-5'; // routes to Anthropic
'ollama/llama3.3:latest'; // routes to Ollama
'google/gemini-3.8-flash'; // routes to GoogleIf the model string has no prefix, or its prefix is not a built-in provider, a backend in llm.backends or a registered plugin, the whole string goes to defaultProvider (or ollama if unset). That is how meta-llama/llama-3.3-70b reaches an OpenAI-compatible default provider unchanged. An agent's provider field skips the prefix check and sends the model string as it is.
The parseModel() utility handles this splitting:
import { parseModel } from '@cogitator-ai/core';
parseModel('openai/gpt-6.1-sol');
// { provider: 'openai', model: 'gpt-6.1-sol' }
parseModel('llama3.3:latest');
// { provider: null, model: 'llama3.3:latest' }Supported Providers
Ollama
Local inference with Ollama. No API key required.
providers: {
ollama: {
baseUrl: 'http://localhost:11434', // default
apiKey: process.env.OLLAMA_API_KEY, // optional: Ollama Cloud (https://ollama.com) or an authenticated server
headers: { 'X-Gateway-Key': process.env.GATEWAY_KEY! }, // optional, sent with every chat request
},
}llm.providers.ollama.headers are sent with backend chat requests, streaming and non-streaming, for example when Ollama runs behind an authentication proxy. The CLI sends the same headers with model discovery, pulls, run model detection, doctor and status probes. Memory embeddings do not use them: set memory.embedding.headers separately for /api/embed. Content-Type stays application/json. If apiKey is set, its Authorization: Bearer ... replaces any custom authorization header, regardless of header-name casing. Without apiKey, a custom authorization header is preserved. Invalid HTTP headers are rejected when the backend is constructed. Trailing slashes on baseUrl are removed before adding /api/chat.
model: 'ollama/llama3.3:latest';
model: 'ollama/codellama:34b';
model: 'ollama/mistral:7b-instruct';OpenAI
providers: {
openai: {
apiKey: process.env.OPENAI_API_KEY!,
baseUrl: 'https://api.openai.com/v1', // optional, for proxies
api: 'responses', // optional: 'responses' | 'chat-completions'
profile: 'vllm', // optional: what the server at baseUrl takes, see Server Profiles below
headers: { 'X-Gateway-Key': process.env.GATEWAY_KEY! }, // optional, sent with every request
},
}model: 'openai/gpt-6.1-sol'; // default when no model is given
model: 'openai/gpt-6-luna';
model: 'openai/gpt-6-astra';The official OpenAI backend talks to the Responses API. GPT-6 models only support tool calling there, and GPT-5.x/GPT-6 reject non-default sampling parameters on Chat Completions. Requests are stateless (store: false); encrypted reasoning items are kept on ToolCall.replay and sent back with the call on the next turn, so reasoning models keep their chain of thought across tool calls (also after a memory round-trip).
| Behaviour | Details |
|---|---|
| Wire API selection | responses for the official endpoint (no baseUrl, or a baseUrl on api.openai.com), chat-completions when baseUrl points anywhere else. api forces either path |
| Stop sequences | The Responses API has no stop parameter, so a request with stop sequences is sent through Chat Completions |
| Sampling params | Reasoning models (o-series, GPT-5 and later) get no temperature / top_p, on the Responses API and on Chat Completions alike, including the agent default 0.7, gpt-4o / gpt-4.1 and -chat variants keep them |
maxTokens | Sent as max_output_tokens on the Responses API, on Chat Completions as max_completion_tokens for the official endpoint and for reasoning models, otherwise in the field the server's profile names |
| Structured output | responseFormat maps to text.format (json_object / json_schema), images are sent as input_image |
| Usage | usage.cachedInputTokens and usage.reasoningTokens are reported when OpenAI returns them (both already included in inputTokens / outputTokens) |
OpenAI-compatible providers (Azure, Mistral, Groq, Together, DeepSeek, vLLM, any custom baseUrl) stay on Chat Completions, with the fields their profile allows. DEFAULT_OPENAI_MODEL and isOpenAIReasoningModel(model) are exported from @cogitator-ai/core.
Anthropic
providers: {
anthropic: {
apiKey: process.env.ANTHROPIC_API_KEY!,
baseUrl: 'https://gateway.example.com/anthropic', // optional, default https://api.anthropic.com
headers: { 'X-Team': 'search' }, // optional, sent with every request
},
}baseUrl puts a proxy or gateway in front of Anthropic. loadConfig() reads it from COGITATOR_ANTHROPIC_BASE_URL or ANTHROPIC_BASE_URL.
model: 'anthropic/claude-sonnet-5-5'; // default when no model is given
model: 'anthropic/claude-opus-5-5';
model: 'anthropic/claude-haiku-4-5';The backend adapts each request to what the target Claude model accepts (model ids from the Anthropic API, Vertex AI and Bedrock, including inference-profile prefixes and ARNs, are recognised):
| Model family | Behaviour |
|---|---|
| Claude 4.7+, 5.x, Fable | temperature / top_p are omitted (these models reject non-default sampling params), including the agent default 0.7 |
| Claude 4.0 – 4.6 | At most one of temperature / top_p is sent; temperature wins when both are set |
| Claude 4.5+, Fable | json_schema response format uses native structured outputs (output_config) instead of a forced tool |
| Claude Opus 5.5, Sonnet 5.5, Fable | Forced tool choice ('required' or a named function) falls back to auto with a system-prompt instruction naming the tool, plus a one-time warning per model |
The stop reasons model_context_window_exceeded and pause_turn are reported as finishReason: 'length', and refusal as 'refusal'.
Google (Gemini)
providers: {
google: {
apiKey: process.env.GOOGLE_API_KEY!,
baseUrl: 'https://gateway.example.com/gemini/v1beta', // optional, with the API version
headers: { 'X-Team': 'search' }, // optional, sent with every request
},
}baseUrl includes the API version, the default is https://generativelanguage.googleapis.com/v1beta. loadConfig() reads it from COGITATOR_GOOGLE_BASE_URL.
model: 'google/gemini-3.8-flash';
model: 'google/gemini-3.1-pro-preview';
model: 'google/gemini-3.5-flash-lite';Gemini has no null schema type, so .nullable() fields in tool parameters and response schemas are sent as nullable: true. A prompt Gemini blocks (promptFeedback.blockReason) fails with LLM_CONTENT_FILTERED. Gemini attaches a thought signature to function calls, stored on ToolCall.thoughtSignature (also in memory) and sent back with the call on the next request, which Gemini 3 models require for multi-step tool use. Thought-summary parts are excluded from the response text.
Azure OpenAI
providers: {
azure: {
endpoint: 'https://your-resource.openai.azure.com',
apiKey: process.env.AZURE_OPENAI_API_KEY!,
apiVersion: '2025-04-01-preview', // optional, the default
deployment: 'prod-chat', // optional default deployment
model: 'gpt-5', // optional: the model the deployments serve, when their names do not say
},
}A deployment that serves a reasoning model (o-series, GPT-5 and later) gets no temperature / top_p and its token limit as max_completion_tokens, as Azure requires. The backend tells by the deployment name (azure/gpt-5) or, when the name is your own, by model. Other deployments keep sampling parameters and max_tokens.
AWS Bedrock
providers: {
bedrock: {
region: 'us-east-1',
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
endpoint: 'https://vpce-0abc.bedrock-runtime.us-east-1.vpce.amazonaws.com', // optional
},
}Bedrock needs the optional @aws-sdk/client-bedrock-runtime package. endpoint sends requests to a VPC endpoint or a proxy instead of the region's own. Without explicit credentials it uses the AWS credential chain (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_PROFILE, SSO, instance roles). Temporary credentials passed explicitly need their sessionToken too, and profile picks a named profile from the shared AWS config files.
model: 'bedrock/global.anthropic.claude-sonnet-5-5';
model: 'bedrock/global.anthropic.claude-haiku-4-5-20251001-v1:0';Claude models on Bedrock follow the same sampling-parameter and forced-tool-choice rules as the Anthropic backend. json_object and json_schema response formats are supported. json_object is requested through a system-prompt instruction; json_schema is enforced with Converse outputConfig.textFormat on Claude 4.5 – 4.6 (the only Claude versions Bedrock serves structured outputs for) and otherwise sent as a system-prompt instruction that includes the schema.
OpenAI-Compatible Providers
Mistral, Groq, Together, DeepSeek, OpenRouter and vLLM use the OpenAI SDK under the hood with a provider-specific base URL. Hosted providers only need an API key, vLLM needs the base URL of your OpenAI-compatible server. OpenRouter reaches the models of every provider through one key (OPENROUTER_API_KEY through @cogitator-ai/config), and its decision models through cog.decide().
providers: {
mistral: { apiKey: process.env.MISTRAL_API_KEY! },
groq: { apiKey: process.env.GROQ_API_KEY! },
together: { apiKey: process.env.TOGETHER_API_KEY! },
deepseek: { apiKey: process.env.DEEPSEEK_API_KEY! },
openrouter: { apiKey: process.env.OPENROUTER_API_KEY! },
vllm: { baseUrl: 'http://localhost:8000/v1' },
}model: 'mistral/mistral-large-latest';
model: 'groq/llama-3.3-70b-versatile';
model: 'together/meta-llama/Llama-3.3-70B-Instruct-Turbo';
model: 'deepseek/deepseek-chat';
model: 'openrouter/anthropic/claude-sonnet-5.5';
model: 'vllm/mistral-7b';headers on openai, openrouter and vllm are sent with every request, for example OpenRouter's HTTP-Referer and X-Title app attribution or the key of a gateway in front of vLLM.
Server Profiles
OpenAI-compatible servers take different parts of the Chat Completions API, and some reject a field they do not know (Mistral answers 422). A profile says what a server takes, so a request carries only that:
| Field | What it controls |
|---|---|
maxTokensField | Whether the token limit goes in max_tokens or max_completion_tokens |
streamUsage | Whether streams ask for usage with stream_options: { include_usage: true } |
reasoningEffort | Whether reasoning.effort is sent as reasoning_effort: true as it is, false never, or the efforts the server takes, an effort it lacks sent as the nearest one (ties go to the higher) |
profile on llm.providers.openai and llm.providers.vllm is a preset name (openai, generic, vllm, ollama, lmstudio, llamacpp, groq, together, deepseek, mistral, openrouter) or an object of these fields over a preset:
providers: {
openai: {
apiKey: 'lm-studio',
baseUrl: 'http://localhost:1234/v1',
profile: 'lmstudio',
},
vllm: {
baseUrl: 'http://gpu-box:8000/v1',
profile: { server: 'vllm', maxTokensField: 'max_completion_tokens', reasoningEffort: false },
},
}The built-in providers use their own preset: Mistral gets no stream_options and efforts none to high, DeepSeek takes none, low, high and max, Together takes low, medium and high and streams usage unasked, Groq gets max_completion_tokens. The official endpoint uses openai. Any other server gets generic, the request as it was before profiles: max_tokens, stream_options and reasoning_effort as given. OPENAI_COMPATIBLE_PROFILES, resolveOpenAICompatibleProfile(fallback, profile) and reasoningEffortFor(profile, effort) are exported from @cogitator-ai/core.
Message Conversion
All backends receive the same Message[]. Every system message (the agent instructions plus any later ones, such as reflection hints or context summaries) is combined into the provider's system prompt for Anthropic, Gemini and Bedrock, and consecutive tool results are sent together in a single turn, as those APIs expect for parallel tool calls. Images in tool results are placed where each API accepts them (see Images in Tool Results).
Turn Outcomes
Every backend reports why a turn ended with the same finishReason: stop, tool_calls, length, content_filter, refusal or error. The rules are the same everywhere:
- Only a
tool_callsturn runs tools. A finished turn with complete tool calls is one even when the provider reportedstop, as vLLM, LM Studio and other OpenAI-compatible servers do for a forced tool. - A turn cut at the token limit (
length), filtered, refused or failed carries no tool calls, so a call cut off in the middle of its arguments never runs with partial or empty ones. - A finished turn whose tool arguments are not valid JSON fails with
LLM_INVALID_RESPONSE, streamed or not. content_filtercovers OpenAI and Azurecontent_filter, GeminiSAFETY,RECITATION,BLOCKLIST,PROHIBITED_CONTENTandSPII, and Bedrock or Anthropicguardrail_intervenedandcontent_filtered.refusalcovers the OpenAIrefusalmessage (its text becomes the content) and the Anthropicrefusalstop reason.
A run reports a filtered or refused last answer as result.blocked and a cut-off one as result.truncated (see Agents). The built-in backends settle each turn with normalizeTurn() from @cogitator-ai/core, and the runtime applies it to every turn, so a backend of your own only has to report the provider's reason and the complete tool calls.
Custom Backends
Backend Instances
A backend implements LLMBackend (provider, chat(), chatStream()), usually by extending BaseLLMBackend, or OpenAICompatibleBackend for servers that speak the OpenAI API. Its provider field is an LLMBackendProvider: a built-in provider name or any name of your own (usually the one it is registered under). Routing goes by the name in llm.backends or the plugin's provider, not by this field.
Pass backends of your own to llm.backends. An agent whose model starts with the name, or whose provider is the name, runs on it; the rest of the model string is sent as the model name. A name of a built-in provider replaces it, for example with a withDebug() wrapper:
const cog = new Cogitator({
llm: {
backends: {
local: new MyCustomBackend({ url: 'http://gpu-box:8000' }),
openai: withDebug(new OpenAIBackend({ apiKey: process.env.OPENAI_API_KEY! })),
},
},
});
const agent = new Agent({ name: 'a', model: 'local/my-finetune', instructions: '...' });cog.route('local/my-finetune') returns the backend and model name a run would use. A run that names a provider nobody provides fails with CONFIGURATION_ERROR. cog.knowsProvider('local') tells whether a local/... prefix routes to that provider (a backend in llm.backends, a built-in provider or a registered plugin) or stays part of the model name on llm.defaultProvider.
Plugin System
Register custom LLM backends for providers not included by default. The runtime creates a plugin's backend the first time an agent uses its provider name, with the config under that name in llm.plugins:
import { defineBackend, registerLLMBackend } from '@cogitator-ai/core';
const myBackend = defineBackend<{ apiKey: string }>({
provider: 'my-provider',
metadata: {
name: 'My Provider', // version, description and author are optional
version: '1.0.0',
},
create: (config) => new MyCustomBackend(config),
validateConfig: (config): config is { apiKey: string } =>
typeof config === 'object' && config !== null && 'apiKey' in config,
});
registerLLMBackend(myBackend);
const cog = new Cogitator({ llm: { plugins: { 'my-provider': { apiKey: '...' } } } });
const agent = new Agent({ name: 'a', model: 'my-provider/model-x', instructions: '...' });Registering a provider name twice throws, and unregisterLLMBackend(provider) removes one, as does the disposer registerLLMBackend returns. A backend plugin is also one kind of plugin contribution: context.registerLLMBackend(plugin) of a plugin makes the provider known to that runtime only, and unloads it with the plugin. The built-in providers themselves are registered this way, by the core's own plugin cogitator@builtin. llm.backends wins over plugin providers, the built-in names over a plugin of the same name. A failing validateConfig makes the first run on that provider fail with Invalid configuration for provider '...'.
List registered plugins:
import { listLLMPlugins, hasLLMPlugin } from '@cogitator-ai/core';
console.log(listLLMPlugins());
console.log(hasLLMPlugin('my-provider'));Debug Wrapper
Wrap any backend with debug logging to inspect requests and responses:
import { withDebug } from '@cogitator-ai/core';
const debugBackend = withDebug(backend, {
logRequest: true,
logResponse: true,
logStream: false,
redactApiKeys: true,
maxContentLength: 2000,
logger: {
log: (level, message, data) => console.log(`[LLM:${level}]`, message, data ?? ''),
},
});Without a logger it prints timestamped entries to the console. Put the wrapped backend into llm.backends under the provider's name to debug every run on it.
Reasoning
reasoning on an agent (or a run, or a ChatRequest) controls reasoning models the same way on every provider:
reasoning: {
effort: 'high', // none | minimal | low | medium | high | xhigh | max
budgetTokens: 8000, // providers that take a thinking budget
summary: true, // return a readable summary of the reasoning
}| Provider | What reasoning becomes |
|---|---|
| Anthropic, Bedrock | Claude 4.6+ / 5.x / Fable: thinking: { type: 'adaptive' } and the closest output_config.effort the model accepts; none turns thinking off where the model allows it (disabled, or between_tools on Sonnet 5.5) and asks for the lowest effort where it does not (Opus 5.5, Fable). Claude 3.7 – 4.5: a thinking budget (budgetTokens, or derived from the effort) added on top of maxTokens. |
| OpenAI (Responses) | reasoning.effort and, with summary, reasoning.summary: 'auto' — reasoning models only |
| OpenAI-compatible | reasoning_effort; reasoning text comes from reasoning_content / reasoning (DeepSeek, vLLM, Groq, OpenRouter) |
Gemini 3+: thinkingConfig.thinkingLevel; Gemini 2.5: thinkingBudget (Pro never below 128); summary → includeThoughts | |
| Ollama | think: a level for gpt-oss, on or off for other thinking models |
The reasoning comes back as ChatResponse.reasoning and delta.reasoning while streaming; agent runs collect it into RunResult.reasoning and stream it to onReasoning. Reasoning tokens are reported in usage.reasoningTokens and counted in outputTokens (Gemini bills them as output too). Summaries are best-effort on some providers: Gemini omits the thought summary from a fair share of streamed responses even when it thought (reasoningTokens is still set), while non-streamed responses carry it.
Reasoning across tool calls. Claude and OpenAI reasoning models keep thinking between tool calls only if their reasoning comes back with the next request. Backends keep it with the tool calls it preceded (ToolCall.replay) and send it back while the agent works through a tool loop. Claude's thinking blocks are tied to the conversation that produced them, so they are replayed only after the latest user message; if history was rewritten in between (context compression), the backend retries once without them.
Prompt Caching
Agent runs cache their prompt by default. Anthropic and Bedrock cache only what the request marks, so their backends mark the stable prefix (tools, system prompt, history); OpenAI and Gemini cache on their own. Every provider reports what it served from cache, and the run's cost prices those tokens at the model's cache price:
const result = await cog.run(agent, { input });
result.usage.cachedInputTokens; // read from the cache (about a tenth of the input price on Claude)
result.usage.cacheWriteTokens; // written to it (Anthropic: 1.25× the input price, 2× with the 1-hour TTL)Anthropic requests carry up to four cache breakpoints, Anthropic's limit. The first marks the end of the agent's instructions at the start of the system prompt, which stays the same from run to run while what a run adds after it changes, so runs with different input still read the instructions from the cache. The second marks the end of the conversation, so the next turn reads everything before it: in an agent loop every iteration resends the previous one's prompt, and after the first call most of the input is a cache read. It is set when another turn is likely, that is when the request offers tools or continues earlier turns, because a single turn with unique input would only pay the write premium on it. llm.promptCache: { conversation: true } always marks it, false never does.
The others mark the end of each message with cacheBreakpoint: true. A context built from memory puts it on two messages of the history: its last message, before the turn context and the input (see Message Order and Prompt Caching), and the last message of the turn before it, so the next run on the thread reads the system prompt and the history from the cache even though its input and recalled facts differ, and still finds the prefix this turn cached when this turn added many messages. A message whose last block is thinking carries no mark.
llm.promptCache: { ttl: '1h' } keeps Anthropic's cache for an hour instead of five minutes, and the run's cost prices those writes at the 1-hour rate (ChatUsage.cacheWrite1hTokens), llm.promptCache: false turns marking off. A single ChatRequest takes the same setting as cache, and cachePrefix names the stable start of its system prompt.
Claude through OpenRouter (an OpenAIBackend with provider: 'openrouter' or an openrouter.ai base URL, model anthropic/...) is marked the same way: the system message becomes text blocks with cache_control on the instructions, the last text of each message with cacheBreakpoint takes cache_control too (a message with no text, such as tool calls alone, stays unmarked), and the conversation end takes the top-level cache_control, since OpenRouter caches Claude only when asked. Its usage reports cache_write_tokens as cacheWriteTokens, and the cost OpenRouter reports already prices reads and writes. Other OpenAI-compatible servers get no marking, as they may reject fields they do not know.
Retries
The runtime retries LLM calls that fail with a retryable error: rate limits (429), server errors (5xx), timeouts and dropped connections. Authentication, bad requests, content filters and an exhausted quota fail at once, the last one even when the provider sends it as a 429. Retries are on by default for every backend an agent runs on, including your own llm.backends and plugins:
const cog = new Cogitator({
llm: {
defaultModel: 'anthropic/claude-sonnet-5-5',
retry: {
maxRetries: 3, // attempts after the first one (default 2)
baseDelay: 1000, // first backoff, doubled on each retry (default 1000 ms)
maxDelay: 30_000, // backoff cap (default 30000 ms)
maxRetryAfter: 60_000, // longest Retry-After worth waiting for (default 60000 ms)
requestTimeout: 180_000, // abort and retry a call with no answer by then (off by default)
onRetry: ({ provider, attempt, delay, error }) =>
console.warn(`${provider}: retry ${attempt} in ${delay}ms (${error.message})`),
},
},
});- Retry-After. When the provider names a wait (
retry-after,retry-after-msor Gemini'sRetryInfo), the runtime waits exactly that long. If the wait is longer thanmaxRetryAfter, the call fails at once instead of holding the run. - Hung calls. With
requestTimeout, a call that has not answered in time is aborted and retried asLLM_TIMEOUT, so one request a provider never answers does not use up the run'stimeout. A stream gets that long for each chunk. Without it a call waits as long as the provider's SDK does, ten minutes for OpenAI-compatible servers. - Streaming. A stream is retried only until its first chunk. After that the caller has already seen part of the answer, so the error is passed on.
- Cancellation. The run's timeout and abort signal stop the waits between attempts too. A call the caller aborts fails with the signal's
reason, never with a retryable LLM error, on every backend and also for a stream that already began (see Aborted Calls). - One layer. Backends created by the runtime make one attempt per call: the OpenAI, Anthropic, Azure and Bedrock SDKs have their own retries switched off, so attempts never multiply.
retry: false turns retries off. To use a backend on its own with the same behaviour, wrap it with withLLMRetry(backend, { maxRetries: 3 }).
Fallback Models
Retries keep a turn on the same model. When that model cannot answer at all, an agent with fallbackModels moves the turn to the next one, in order:
const agent = new Agent({
name: 'support',
model: 'anthropic/claude-sonnet-5-5',
fallbackModels: [
'openai/gpt-6.1-sol',
{ model: 'deepseek/deepseek-v4-pro', provider: 'openrouter' },
],
instructions: 'Answer support questions.',
});
const result = await cog.run(agent, {
input,
onModelFallback: ({ from, to, error }) =>
console.warn(`${from} failed (${error.message}), using ${to}`),
});
result.modelUsed; // 'openai/gpt-6.1-sol' when the final answer came from a fallbackWhether a failure moves the turn follows the error kind:
| Failure | What happens |
|---|---|
rate_limit, overloaded, server_error, timeout, network | Retried on the same model (llm.retry), then moves |
quota, authentication, permission, not_found | Moves at once, retrying would not help |
context_overflow, invalid_response | Moves at once, a bigger or another model may fit |
content_filter, invalid_request | Fails the turn: another model would refuse it as well |
| The run was aborted or timed out | Fails the turn |
- Every turn starts again from
model. A fallback answers one turn, the next turn tries the primary model first. - Circuit breakers. Each model has a breaker shared by all runs of the runtime. After
failureThresholdfailures in a row, or at once for an out-of-quota account, a rejected key or a missing model, turns skip it forresetTimeoutms and then try it again. Configure them withllm.modelCircuitBreaker: { failureThreshold: 5, resetTimeout: 30_000, halfOpenRequests: 3 }(the defaults). - Streaming. A stream moves to the next model only before its first token reaches
onTokenoronReasoning, since after that the caller has seen part of the answer, unless the run hasonStepReset: then the run tells it to take back what the step streamed ({ reason: 'fallback', model }) and the step streams anew on the next model. Server streams do it with areset-stepevent (see Data parts, state and step resets). The same callback hears{ reason: 'empty_answer' }when a streamed answer came out empty and the model is asked again. - Cost and traces. A fallback turn is priced at the model that answered it, its
llm.chatspan names that model, and every move adds anllm.fallbackspan withllm.fallback.from,llm.fallback.toandllm.fallback.reason(the error kind or code, never the error's text). - All models failed. The run ends with the error code all models failed with, or
LLM_UNAVAILABLEwhen they failed differently. Its message names each model and its error kind, which server adapters pass on to clients, whiledetails.attemptsholds each model's errorcode,kindand message andcausethe first failure, for your logs. - Long threads. A turn that moves to a model with a smaller window than the agent's
modelgets its messages cut to that window, minus the answer and the tool schemas: the system prompt and the newest messages stay, and no tool result loses its call. A local Ollama counts with the 4096 tokens it serves by default. - Turns that end in an error. A turn the provider ends with
finishReason: 'error'(Gemini'sMALFORMED_FUNCTION_CALL, a failed Responses API answer) moves like aninvalid_responsefailure. Its tokens count in the run's usage and cost, and itsllm.chatspan has the statuserror. - Routing. Each fallback is routed like
model:provider/model, or{ model, provider }for a model whose name does not start with its provider. All of them are routed when the run starts, so a misconfigured fallback fails right away instead of in the middle of an outage. Handoffs use the fallback models of the agent that takes over.
An agent without fallbackModels behaves exactly as before: its errors are thrown as they are, and no breaker is involved.
Error Handling
All backends throw typed LLMError instances with structured error codes:
import { LLMError, ErrorCode } from '@cogitator-ai/core';
try {
await cog.run(agent, { input: 'Hello' });
} catch (e) {
if (e instanceof LLMError) {
if (e.kind === 'quota') {
// out of credits or over a daily quota, waiting will not help
} else if (e.code === ErrorCode.LLM_RATE_LIMITED) {
// still rate limited after the runtime's retries, e.retryAfter is the provider's hint, if any
}
}
}Error codes include LLM_UNAVAILABLE, LLM_RATE_LIMITED, LLM_QUOTA_EXCEEDED, LLM_TIMEOUT, LLM_INVALID_RESPONSE, LLM_CONTEXT_LENGTH_EXCEEDED and LLM_CONTENT_FILTERED. e.details carries the provider, model, status code and request id. Rate limit, overload, server, timeout and connection errors are marked as retryable, and retryAfter holds the wait the provider asked for, when it named one.
Error Kinds
e.kind (also e.details.kind) says why the call failed, finer than the code, which for example groups a wrong API key and an overloaded server as LLM_UNAVAILABLE:
| Kind | Code | Retried | Meaning |
|---|---|---|---|
rate_limit | LLM_RATE_LIMITED | yes | Too many requests or tokens for now |
quota | LLM_QUOTA_EXCEEDED | no | Out of credits, or over a daily or billing quota |
authentication | LLM_UNAVAILABLE | no | The API key or credentials are missing, wrong or expired |
permission | LLM_UNAVAILABLE | no | The credentials may not use this model, region or feature |
not_found | LLM_UNAVAILABLE | no | No such model or endpoint |
invalid_request | VALIDATION_ERROR | no | The provider rejected the request as malformed |
context_overflow | LLM_CONTEXT_LENGTH_EXCEEDED | no | The prompt does not fit the model's context window |
content_filter | LLM_CONTENT_FILTERED | no | The provider's safety policy blocked the prompt or answer |
overloaded | LLM_UNAVAILABLE | yes | The provider is over capacity |
server_error | LLM_UNAVAILABLE | yes | The provider failed on its side |
timeout | LLM_TIMEOUT | yes | The call did not finish in time (also an HTTP 504) |
network | LLM_UNAVAILABLE | yes | The provider could not be reached |
invalid_response | LLM_INVALID_RESPONSE | no | The provider answered with something the backend cannot read |
The kind comes from the provider's own error codes first and the HTTP status second:
- OpenAI and OpenAI-compatible servers by
error.codeanderror.type. A 429 withinsufficient_quota,credit_balance_exhausted, an organization or project spend limit ororganization_usage_limit_exceededisquota, notrate_limit, and so is a 402, as OpenRouter answers when its credits run out. A numericcodeof an error inside a stream (OpenRouter passing on the model provider's failure) counts as that HTTP status, and a Gemini error behind an OpenAI-compatible endpoint is read by the Gemini rules. - Anthropic by
error.type:billing_error(402) and aninvalid_request_errororrate_limit_errorabout a credit balance or a usage limit arequota,overloaded_errorisoverloaded. - Gemini by
statusand theQuotaFailureandErrorInfodetails:RESOURCE_EXHAUSTEDis a rate limit at 429, andquotaat 402 or when a quota counted per day ran out, which resets only at midnight Pacific time. - Bedrock by the AWS exception name:
ThrottlingExceptionis a retryable rate limit,ServiceQuotaExceededExceptionisquota,ModelTimeoutExceptionis a retryableLLM_TIMEOUT,ValidationExceptionandAccessDeniedExceptionare not retried.
An error the provider reports inside a stream that already began is classified the same way. classifyProviderError(provider, status, body) from @cogitator-ai/core returns the kind for a status and an error body, for backends of your own.
The message always ends with what the provider said, for example [openai] Bad request: Unsupported parameter: 'max_tokens' is not supported with this model, and e.details.responseBody keeps the raw body. LLM_CONTEXT_LENGTH_EXCEEDED is reported only for the providers' own context overflow errors (context_length_exceeded, maximum context length, prompt is too long, input is too long, the Ollama and llama.cpp exceeds the context length and the like), so a request rejected for a parameter that merely mentions tokens stays a VALIDATION_ERROR.
Aborted Calls
A call whose signal the caller aborts fails with signal.reason, the error the caller aborted with, or an AbortError when the reason is not an Error. That holds for every backend, for a request still waiting and for a stream that already began, including the OpenAI and Bedrock streams whose SDKs used to end quietly, so a cut-off answer is never taken for a whole one and a retry or fallback layer never acts on an abort:
const controller = new AbortController();
setTimeout(() => controller.abort(new Error('The user closed the page')), 2000);
try {
await cog.run(agent, { input, signal: controller.signal });
} catch (e) {
// e is the Error passed to abort()
}abortReason(signal) from @cogitator-ai/core returns that error, or undefined while the signal is not aborted, for backends of your own.