Model client
@felix/ai is the boundary between Felix and a model provider. It defines what a conversation,
a tool call and a streamed reply look like, and ships one adapter per provider that turns those
into a provider’s wire format and back. The agent loop and the harness depend only on the
contract: they never pick a provider or read a credential. The package has no runtime
dependencies and no provider SDK.
Exports
Section titled “Exports”| Import | What it holds |
|---|---|
@felix/ai |
The contract types, completeModel, the parsers (parseMessage, parseConversation, parseTokenUsage) and the errors (ProviderError, ContextOverflowError, isRetryable, isContextOverflow). |
@felix/ai/workers-ai |
workersAiModel over an injected transport, and workersAiRestModel over the Cloudflare REST inference endpoint. The default provider. |
@felix/ai/anthropic |
anthropicModel, over the Messages API with fetch. |
@felix/ai/openai-responses, /openai-compatible, /google, /mistral, /bedrock |
openAiResponsesModel, openAiCompatibleModel, googleModel and vertexModel, mistralModel, bedrockModel. |
@felix/ai/aws |
The AWS Signature Version 4 request signing Bedrock uses. |
@felix/ai/workers-ai-images, /openai-images, /google-images, /openrouter-images |
Image generation models. |
@felix/ai/workers-ai-transcription |
workersAiTranscriber, Workers AI speech-to-text. |
@felix/ai/workers-ai-classifier, /system-one |
Classifier models. |
@felix/ai/sse |
sseData, the server-sent events decoder the streaming adapters use. |
@felix/ai/testing |
scriptedModel, a deterministic model that needs no credentials or network. |
@felix/ai/testing/anthropic, @felix/ai/testing/bedrock |
Synthetic Messages streams and Bedrock event-stream frames for adapter and harness tests. |
The testing exports are for tests and the demo. Runtime code does not import them; see Testing.
The contract
Section titled “The contract”All of it lives in packages/ai/src/types.ts.
| Type | Shape |
|---|---|
Message |
{ role: 'user', text, images? }, { role: 'assistant', text, calls, reasoning?, replay? } or { role: 'tool', callId, text, error, images? }. An image is inline base64 (at most 5 MiB) or a sha256: reference the application resolves before inference. |
ToolCall |
{ id, name, arguments, argumentsError? }, where arguments is a JSON value. A call with argumentsError is never run; the error goes back to the model as its result. |
ToolDeclaration |
{ name, description, parameters }, where parameters is a JSON Schema as a JSON value. |
ModelRequest |
{ system, messages, tools, signal, cacheKey?, reasoning? }. The system prompt is separate from the messages. cacheKey routes prompt caching for one conversation and is never sent as content; reasoning is a level from off to max, ignored by models without reasoning. |
ModelEvent |
{ type: 'text', text } or { type: 'reasoning', text } for a piece of the reply, { type: 'call_delta', index, name, id?, text } for a piece of a tool call’s arguments, { type: 'usage', usage } for usage reported so far, then one { type: 'complete', message, usage? }. |
Model |
One method: stream(request), which returns an AsyncIterable<ModelEvent>. |
TokenUsage |
{ inputTokens, outputTokens, cachedInputTokens?, cacheWriteInputTokens?, longCacheWriteInputTokens? }, as the provider reported them for one inference. Cached reads and cache writes are included in inputTokens; one-hour writes are included in cacheWriteInputTokens. |
A tool result is its own message with role: 'tool', and error: true marks a failed or refused
call. The text events are for display. The complete event carries the whole assistant message,
and that message, not the joined text events, is what gets saved.
usage is optional. When it is missing the count is unknown, not zero. The Workers AI adapter
reports usage when the provider sends prompt_tokens and completion_tokens. The Anthropic
adapter reports it from message_start and message_delta, including cache reads.
Completing an inference
Section titled “Completing an inference”completeModel(model, request, onText, onReasoning, onCall, onUsage) drains one stream and returns
{ message, stopReason, usage? }, where stopReason is stop, tool_calls or length. The
agent loop calls it for every model turn. It:
- awaits
onTextfor each text event before reading the next, so a slow consumer slows the stream rather than buffering it; - checks the abort signal before the stream, after every event and at the end;
- re-validates the
completemessage withparseMessageand requires it to be an assistant message; - fails if the stream ends without a
completeevent, sends an event after it, or sends an event type it does not know.
parseConversation checks a whole history before it is sent: every tool result must answer a call
from the assistant message before it, and no call may be left without a result. Stored history and
HTTP input go through it, so a malformed transcript is refused before any inference.
Streaming and SSE
Section titled “Streaming and SSE”The Workers AI, Anthropic, OpenAI, OpenAI-compatible, Google and Mistral adapters read
server-sent events through sseData. It decodes data: fields across any byte,
UTF-8 and line boundary, accepts \n, \r and \r\n line endings, and yields a frame only on its
blank line, so an unfinished final frame is dropped rather than half-read. A frame larger than
4 MiB fails the stream. When the consumer stops early, the decoder cancels the response body.
Workers AI. A turn with no tools asks for an SSE stream and yields text as it arrives. The
stream must end with [DONE] after at least one response event. A turn with tools asks for a
buffered response instead, so the complete tool arguments can be checked before anything runs; on
those turns the text arrives in one piece. Tool calls without an id get a generated one, which
stays with the result in later history. A JSON response can be the binding’s direct output or the
REST envelope ({ success, result }).
Anthropic. Every turn streams. The adapter tracks content blocks by index, joins text deltas
and input_json_delta fragments, and builds the message only at message_stop. ping and event
types it does not recognise are ignored.
Validation: what fails closed
Section titled “Validation: what fails closed”An adapter either yields a complete, valid assistant message or throws. It never returns a partial reply as if it were finished, because the agent saves the message and then runs its tool calls. A truncated or malformed reply could run a tool the model never finished asking for.
| Condition | Result |
|---|---|
The stream closes before its completion marker ([DONE], message_stop). |
Error. |
The reply was cut off at the token limit (finish_reason: 'length', stop_reason: 'max_tokens') and holds no tool call. |
Error, unless the request set its own maxOutputTokens and the Anthropic reply reached it. |
| The same, but the reply holds tool calls. | The calls are not run. Each goes back to the model as an error asking it to re-issue the call with complete arguments. |
Anthropic’s stop reason is not end_turn, tool_use, stop_sequence, pause_turn or max_tokens, or says tool_use without a tool call (or the reverse). model_context_window_exceeded is a ContextOverflowError. |
Error. |
A content block is duplicated, unclosed, or receives a delta after it closed; an event arrives before message_start. |
Error. |
| Tool arguments are not valid JSON after one repair of their strings (raw control characters, or a backslash before a character JSON cannot escape), or are not a JSON object. | The call is not run; the model reads why, with what it sent. |
| Tool arguments are cyclic, nest deeper than 64 levels or hold more than 10,000 values. | Error. |
| A tool call has an empty or duplicate id, or an empty name. | Error. |
Workers AI returns a stream when a buffered response was asked for. Turns with tools are buffered unless streamToolCalls is on. |
Error. |
| A content block type Felix does not handle. | Error. |
A Workers AI model ID must have the form @cf/vendor/model or @hf/vendor/model. The adapter does
not guess a model, and it does not turn plain text into a tool call.
Errors
Section titled “Errors”An adapter throws a ProviderError when the provider answers with an HTTP error, and the
Anthropic adapter also when its request gets no response or its stream reports an error. A Workers
AI transport that throws instead of returning a response becomes a plain error, which is not
retried, unless its message names the context limit.
| Field | Meaning |
|---|---|
retryable |
The failure is transient: HTTP 408, 425, 429, a 5xx other than 501 and 505. A 429 that reports a gateway spend limit (SpendLimitError) or an exhausted quota or billing limit is not. For Anthropic, also a request that got no response, or an overloaded_error or api_error during the stream. |
status |
The HTTP status, when there was one. |
retryAfterMs |
The delay the provider asked for in retry-after-ms or retry-after (seconds or an HTTP date), capped at five minutes. |
ContextOverflowError is a ProviderError that is never retryable. It means the request is larger
than the model’s context window: HTTP 413, or an error whose text names the context limit (for
Anthropic, a 400 invalid_request_error). isRetryable and isContextOverflow are the type guards
the agent loop uses.
Error messages carry at most the provider name and the HTTP status. A provider’s error body can echo user input, so the adapters read at most 16 KiB of it to classify the failure and never put it in a message.
The agent loop acts on these errors before any text or tool call has streamed; reasoning that
had streamed is withdrawn first. It retries a retryable error up
to its retry.maxRetries, with backoff that respects retryAfterMs; the API and the terminal
client both set two retries. After a context overflow it lets the harness compact the history and
tries once more. See Models and embeddings for the setting that turns
compaction on.
Adapter options
Section titled “Adapter options”| Function | Options |
|---|---|
workersAiModel |
model, run(model, input, signal) returning a Response, maxTokens (default 4096), vision (default false: images become a text note) and streamToolCalls (default false). The API Worker passes the AI binding’s run with returnRawResponse: true. |
workersAiRestModel |
accountId (32 hex characters), apiToken, model, maxTokens, vision, streamToolCalls, userAgent, and an optional fetch. |
anthropicModel |
apiKey, model, maxTokens (default 4096), vision, userAgent, and an optional fetch. |
A new adapter implements Model and keeps the same promises: honour the signal, throw
ProviderError with a status but no body text, and yield complete only for a finished, valid
reply.
© Felix. All rights reserved.