24. Wire protocols
Why this layer exists
From this chapter on, every chat request the book’s Go programs make goes through one Go interface, llm.Client: the agent loop of chapter 26, the provider chains of chapter 28, the eval harness and judge of Part VI, and the gateway and daemon of Part VII (embeddings go through their own small clients, chapters 28 and 32). The endpoints behind it are the reader’s own: the llama.cpp routers on straylight and dixie at :11434, tether in front of dixie at :11435, aec-router from chapter 22, and z.ai’s glm-5.3-flash. All of them speak the OpenAI chat-completions dialect, and each speaks it a little differently. llama-server puts a thinking model’s reasoning in a reasoning_content field that the OpenAI API does not have, takes typed content parts, and also serves the Anthropic Messages dialect at /v1/messages. The fixtures of this chapter cover llama-server on dixie and straylight. z.ai’s endpoint was not captured, so nothing below claims what its bodies look like. The Anthropic Messages API is the contrast. It does the same job with different choices, and the places where the two disagree show which parts of the OpenAI dialect are accidents of history and which are necessities of the problem.
The client owns five things: the encoding of a request, the parsing of a stream, the assembly of a stream into one answer, the retry matrix, and the canonical types the rest of the program is written against. It does not own others, and the boundaries are what keep it small. It never reinterprets bytes it forwards; that is internal/proxy (chapter 23), which keeps its own wire structs because it must copy what it cannot read, while this package interprets everything it receives. It never decodes a tool call, because the model’s text is the subject of chapter 25. It never fails over to another provider, which is chapter 28’s chain. It never budgets tokens, which is chapter 29. A client that did any of these would have to know about the loop that calls it.
Three promises made earlier land here. Chapter 13 explained reasoning_content, the field in which the server returns a model’s reasoning apart from its reply, and this client accepts it in responses and in streams and keeps it separate from content. Chapter 22 decided that the router’s refusals are permanent (400) or transient (503 with Retry-After), and chapter 23’s last paragraph on pass-through says: “The retry decision belongs to chapter 24’s client, which reads both the same way.” Chapter 16 says chapter 41’s gateway carries images and whisper transcripts as message parts, which is why a message’s content is a slice of parts from the first line of code.
Mechanism
One message type, two wires
llm.Message is a role, a slice of Parts, a Reasoning string beside the parts, a slice of ToolCalls, and, for a tool’s answer, the id of the call it answers. Reasoning is never concatenated into the parts, because a caller that asked for the answer must not receive the model’s scratch work as if it were the answer. A ToolCall carries its Arguments as text, exactly as the provider delivered it. The figure maps this one type onto both wires, row by row. The text row is a rename: a string or typed parts on one side, an array of blocks on the other. The other six rows are not.
The system prompt. On the OpenAI wire it is a message with role: "system", one among many and possibly in the middle. On the Messages wire it is a top-level system field, and the reference’s prose says “there is no "system" role for input messages in the Messages API” (Create a Message, fetched 2026-10-01). The adapter joins several system messages with blank lines, so position information is lost on that wire and must not carry meaning.
Tool calls: a string against an object. This is the central contrast. On the OpenAI wire a call is tool_calls[i].function.arguments, a JSON string holding what the model wrote. The SDK’s own docstring warns the reader: “Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function” (chat_completion_message_function_tool_call.py at openai-python 10f88169, a file generated from the OpenAPI specification). On the Messages wire a call is a tool_use block with an id, a name and an input, which the vendor describes as “An object containing the input being passed to the tool, conforming to the tool’s input_schema” (Handle tool calls, fetched 2026-10-01). One wire hands the client the model’s bytes; the other hands it a parsed value. A parsed value removes one failure, text that is not JSON. It removes none of the others: a wrong key, a wrong type, a value the tool should refuse. So the client keeps Arguments as text on both wires, compacting the object back to its JSON on the Anthropic side, and chapter 25’s decoder treats the two the same. Chapter 25 exists because of the first wire.
Here is one conversation, a system prompt, a question, an assistant turn that calls read_file, and the tool’s answer, encoded for both wires on talos. The OpenAI side is Provider.Encode; the Anthropic side is the adapter’s encode. The program printed the messages after the first turn, one per line, and the Anthropic request’s system field:
OpenAI wire
messages[2]: {"role":"assistant","content":null,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"/etc/hosts\"}"}}]}
messages[3]: {"role":"tool","content":"127.0.0.1 localhost","tool_call_id":"call_1"}
Anthropic wire
system: "You have tools."
messages[1]: {"content":[{"id":"call_1","input":{"path":"/etc/hosts"},"name":"read_file","type":"tool_use"}],"role":"assistant"}
messages[2]: {"content":[{"content":"127.0.0.1 localhost","tool_use_id":"call_1","type":"tool_result"}],"role":"user"}
Tool results. The OpenAI wire gives each result a message of its own, role: "tool" with the tool_call_id. The Messages wire has no tool role: a result is a tool_result block inside a user turn, and the vendor’s wording for the continuation is “a user message of tool_result blocks, one for every tool_use block in the response” (Stop reasons and fallback). Two parallel calls therefore produce two tool messages that must become one user turn with two blocks, so the adapter merges consecutive messages of one role. The reference says it would do the same (“Consecutive user or assistant turns in your request will be combined into a single turn”), but the merge is the adapter’s job for a second reason: the Handle tool calls page requires that “the tool_result blocks must come FIRST in the content array. Any text must come AFTER all tool results”, so the adapter puts them first. The vendor’s page adds a flag the OpenAI wire has no counterpart for: “is_error (optional): Set to true if the tool execution resulted in an error”. llm.Message carries it as IsError, set by chapter 26’s loop from chapter 27’s Result.IsError; the Anthropic adapter sends it, and the OpenAI encoder drops it, so on that wire the error has to be in the text.
Reasoning. llama-server returns reasoning_content beside content, and the OpenAI API has no request field to send it back (Provider.SendReasoning, recorded in DECISIONS.md, is the opt-in; by default an assistant message goes back with content and tool calls only). Anthropic’s thinking is a block of type thinking with a signature, “an encrypted copy of the full reasoning that you pass back unchanged in multi-turn and tool-use conversations”, and the rule for passing it back is strict: “Within the latest assistant message, the sequence of consecutive thinking blocks must match what the model generated in the original request: you can’t rearrange, edit, or partially drop them. This includes redacted_thinking blocks” (Thinking, fetched 2026-10-01). A string beside the parts cannot represent that, because the signature belongs to a block at a position. So the adapter returns the text in Reasoning as on the other wire, and also keeps each block as a Part of type thinking (text in Text, signature in Data) or redacted_thinking (opaque Data), in the message that received them. Order matters beyond the thinking blocks themselves. The same page says that on current models a progress update “comes back as its own thinking block with its own signature” and “sits immediately before the tool_use … block it introduces”, so a turn with two tools is [thinking, tool_use, thinking, tool_use], and a replay that listed both thinking blocks first would be a reordered sequence. ToolCalls live in their own slice, so the adapter leaves a third part type in the sequence, tool_use, whose Text is the call’s id; encode expands it from the matching ToolCall where it stands, and a call with no placeholder goes after the parts. The OpenAI encoder skips all three part types. A history built on the Messages wire therefore replays onto the OpenAI wire with the reasoning text dropped unless SendReasoning is set. The other direction loses something that cannot be rebuilt: an OpenAI-wire history carries no signed blocks, and the Thinking page lists “Required: within a tool-use turn, pass thinking blocks back”, so a chain that falls over from one wire to the other in the middle of a tool-use turn starts that turn again.
Why it stopped. The SDK’s finish_reason is one of five words: stop, length, tool_calls, content_filter, and function_call, which the docstring marks deprecated. The Messages wire has seven stop_reason values (Stop reasons and fallback, fetched 2026-10-01): end_turn, max_tokens, stop_sequence, tool_use, pause_turn, refusal and model_context_window_exceeded. The client’s FinishReason is the OpenAI word. end_turn and stop_sequence map to stop, max_tokens and model_context_window_exceeded to length, tool_use to tool_calls, refusal to content_filter. pause_turn has no equivalent, since it means a server-side tool loop hit its iteration limit and, in the vendor’s words, the conversation continues “by sending the response back as-is”, so it is kept as the provider’s own word. Any value the table does not know passes through unchanged. A caller that tests for "stop" then handles both wires. The adapter cannot continue a paused turn: it keeps text, thinking and client tool_use blocks and drops the others (server_tool_use, search results, fallback), so there is nothing to send back as it was. The fleet’s tools are all client tools, so no answer here carries it, and nothing later handles it: chapter 26’s loop takes a pause_turn reply without tool calls as final. A caller that gives the Anthropic wire server-side tools has to test FinishReason itself.
The end of a stream. OpenAI-dialect streams end with data: [DONE]; Messages streams end with an event named message_stop. Both surface as io.EOF from Stream.Next. A stream that ends otherwise is a different error, and the streaming section below gives the reason.
llama-server serves both dialects from one process: /v1/chat/completions and, at line 1570 of its README at b29c606, /v1/messages, whose description reads “While no strong claims of compatibility with the Anthropic API spec are made, in our experience it suffices to support many apps. … Tool use requires --jinja flag.” Both fleet hosts run --jinja, which is visible in GET /v1/models as an entry in each model’s status.args. The same request can therefore be sent both ways to the same local model. This chapter’s tests never contact it.
Encoding
Provider.Encode turns a Request into the bytes of a chat completion, and four rules keep those bytes acceptable to every server in the fleet.
A message with exactly one text part sends content as a plain string, which every server accepts; anything else sends the typed array. An assistant message that has tool calls and no parts sends content: null, as the API returns it. A tool with no schema sends {"type":"object","properties":{}}: OpenAI treats an omitted parameters as an empty list, but llama-server renders the schema into the prompt, and an explicit empty object serves both. Provider-specific fields travel in Extra, copied last, and a key that collides with a field the request names (model, messages, tools, stream and the rest) is an error at send time and never a silent override. The captures use this: the elicitation fixtures set reasoning_format and chat_template_kwargs through Extra.
The bytes are deterministic. json.Marshal of a map writes its keys in sorted order, and the top level of a request is a map of raw values, so one Request always encodes to the same bytes. Messages and tools are structs, which fix the order of their own fields. A recorded request can therefore be compared byte for byte, and the property costs nothing.
For a stream, the encoder adds stream: true and stream_options: {"include_usage": true}. The second is not optional in practice, and the next section shows why.
Streaming and assembly
A streamed chat completion is a sequence of chat.completion.chunk objects. In the SDK’s types (chat_completion_chunk.py at 10f88169), each chunk’s choice has a delta with optional content, optional tool_calls, and a finish_reason that is null until the last chunk of the choice. llama-server adds reasoning_content to the delta. A tool call arrives as ChoiceDeltaToolCall, a record with an integer index, an optional id, and an optional function holding an optional name and an optional arguments. The client has to turn this sequence into the object a non-streaming request would have returned, and the pieces assemble by three different rules.
Text is concatenation. Write the content deltas of a choice in arrival order as , each a string; the server cut the message into them, so , where juxtaposition is concatenation. Concatenation is associative, so where the server put the chunk boundaries cannot matter, and appending each delta to a buffer reconstructs . An empty delta is the identity and changes nothing. reasoning_content is a second string, cut the same way, and it gets its own buffer; this is the reason the delta type has separate Text and Reasoning fields.
Tool calls merge by index. Fragments of a message with calls carry the index of their call, . The first fragment of call carries id and name, and every fragment contributes a piece of arguments. For a fixed the pieces arrive in order over one TCP stream, so the arguments are the content rule applied once per index. Different calls’ fragments may interleave, so the merge has to be keyed by index, not by arrival order and not by id, which only a call’s first fragment carries. An absent index is read as 0, which is right for a server that sends one call without numbering it and wrong for one that sends several without; llama-server at b29c606 numbers its fragments (the captures below show 0, and 0 and 1), and exercise (c) runs the wrong case. Calls are emitted in index order.
finish_reason is last-writer-wins among the non-null values, so a later null cannot erase it. usage is not in any chunk unless the request asks, and then it arrives in one more chunk after the finish chunk, with an empty choices array. The SDK’s docstring for include_usage says so, and adds: “If set, an additional chunk will be streamed before the data: [DONE] message. The usage field on this chunk shows the token usage statistics for the entire request, and the choices field will always be an empty array. … NOTE: If the stream is interrupted, you may not receive the final usage chunk which contains the total token usage for the request” (chat_completion_stream_options_param.py). That note is why a stream that ends without [DONE] is a distinct error. A consumer that saw the stream stop cannot tell a complete answer from one cut off at a connection reset, and the missing usage chunk is only the symptom you can measure. So Next returns io.EOF only at [DONE]; the end of the body without it is ErrNoDone, which Response reports as well, along with whatever was assembled. The consumer decides what a partial answer is worth. The Messages wire has the same shape of problem and the same answer: a stream that ends without message_stop is ErrNoStop.
Two smaller rules. llama-server’s first chunk carries only the role ({"role":"assistant","content":null} in the fixtures), so the stream skips every chunk that carries nothing. And Response.Raw is the chunks as received, as one JSON array, so a trace or a fixture can be rebuilt from a response without a second parse.
The reader follows the WHATWG text (§9.2.5–9.2.6), dropping a leading byte order mark as it asks, except in three places, which the reader’s comment lists. A lone CR does not end a line: only LF and CRLF do, which is what llama-server and the Messages API send, and a CR-terminated stream fails as one malformed line instead of parsing. Data at the end of the body without its closing blank line is kept, where the text discards it, because a server that dies after data: [DONE] and before the blank line has still said everything. And an event with a name and no data, such as a bare event: error, is returned, because for this client the name is the content. None of the three can turn a cut-off stream into a complete one, since [DONE] is what ends a complete one.
A 2xx can also carry an error. A server that answers 200 with {"error": …} as a JSON body, to Complete or to a request for a stream, gets a *StatusError with Status 200 and the server’s own message, not ErrNoChoices or ErrNotStream; Transient is false for it, so it is not retried.
The retry matrix, derived
What a client should retry follows from what a request that was refused has in common with one that will succeed later. Take the router’s code first. Handler.fail (go/internal/router/handler.go, lines 160–174) maps ErrUnknownModel, ErrNotLoaded and ErrTooLarge to 400: for the request as sent, the same bytes cannot succeed, so retrying is wasted work. It maps ErrClosed, ErrUnloaded and ErrStopping to 503 with Retry-After: 5 (the constant is at line 19): the router is shutting down or the model went away, and it says when to ask again. Everything else is 500, an internal fault. The proxy passes a child’s status and headers through, Retry-After included (proxy.go, lines 224 and 228), answers 502 when the child is unreachable (line 216) or its stream cannot be assembled (line 305), and 500 for an error the child sent inside its stream (lines 299–303). A 499 appears only as a metrics label after the client has gone (line 182), so no client ever receives one.
The standards say what the header means. RFC 9110 §10.2.3 defines Retry-After = HTTP-date / delay-seconds, gives the two examples Retry-After: Fri, 31 Dec 1999 23:59:59 GMT and Retry-After: 120 (“In the latter example, the delay is 2 minutes”), and says that sent with a 503 it “indicates how long the service is expected to be unavailable to the client”. §15.6.4 adds, for a 503, “The server MAY send a Retry-After header field (Section 10.2.3) to suggest an appropriate amount of time for the client to wait before retrying the request”. RFC 6585 §4 says the same of 429: the response “MAY include a Retry-After header indicating how long to wait before making a new request”. The Messages API sends 529 for overload, which the vendor’s streaming page says an overloaded_error “would normally correspond to” outside a stream.
From these the rule follows: the client retries only what has delivered nothing to the caller. Concretely, that is a transport error with no response at all, and a transient status, 408, 429, 502, 503, 504 or 529, before any 2xx has begun. 408 and 504 are an intermediary giving up before the model’s answer exists, so they have delivered nothing and are the same case as 502. A transport error that reports itself permanent is the exception to the first case: an error implementing interface{ Permanent() bool } that returns true is a refusal by the caller’s own transport (chapter 28’s fleet guard declining to send is one), and retrying can only repeat it, so the client returns it at once. Every other answer is returned at once as a *StatusError: 400, 401, 403, 404, 413, 422 and 500 are not transient, and neither is a 3xx. The client does not follow redirects, because a 302 turns the POST into a GET and a 307 sends the prompt, and the key, wherever the answer points; the redirect comes back as a StatusError for the caller to read. A 500 is an internal fault, so by definition not something waiting repairs, and whether a different provider gets the request is the decision of chapter 28’s chain, which can read StatusError.Transient and RetryAfter and has what it needs to make it.
The boundary is “has a 2xx begun?”, and the rule is deliberately weaker than “the model has not started”. A transport error after the request was sent, or the router’s 502 when its child dies mid-generation, can mean the model did work whose result was lost; the retry repeats that work. A 504 from a cloud gateway is the same case, and may repeat a whole generation as a 502 may. What makes the repeat acceptable is that a completion has no effect outside the server’s compute. The side effects of a turn happen when the loop runs the tools in a finished response, and by then the retry question is long over. Once a 2xx has begun the client stops: a failure reading its body, or any error after the stream was handed to the caller, is returned with what was received, because retrying would run the generation twice and, for a stream, hide from the consumer that it already saw part of an answer. Whether a turn that crashed is replayed is chapter 40’s question. Conversely, a 503 before the stream starts has delivered nothing and is retried like any other.
HTTP has a rule about automatic retries of a POST, and the client keeps half of it. RFC 9110 §9.2.2 says: “A client SHOULD NOT automatically retry a request with a non-idempotent method unless it has some means to know that the request semantics are actually idempotent, regardless of the method, or some means to detect that the original request was never applied.” A chat completion is a POST. The next paragraph gives the way out: “a user agent can repeat a POST request automatically if it knows (through design or configuration) that the request is safe for that resource”. This client knows by design, for the reason above: the server’s compute is the only effect. It also lists the guess that a transport error before any response was received may be retried, “particularly if an idle persistent connection was used”, which is the first row of the matrix. The section ends with two sentences: “A proxy MUST NOT automatically retry non-idempotent requests. A client SHOULD NOT automatically retry a failed automatic retry.” The first binds chapter 23’s proxy, which has no retries. The second the client does not keep. Three attempts are two automatic retries, and what bounds the second is the attempt count and the jitter, not the standard; a caller who wants the rule sets Attempts to 2.
The wait follows from two inputs. If the response has a usable Retry-After, the client waits that long, capped at MaxWait (30 s by default): the server’s estimate is better than ours, but an unbounded wait lets a faulty server stall the caller. ParseRetryAfter reads delta-seconds, which are ASCII digits only (RFC 9110’s 1*DIGIT, so +5 is not one), or an HTTP-date relative to the client’s clock; a date in the past counts as absent, and so does anything it cannot parse. A string of digits too large for a duration is not absent but a cap, and MaxWait then applies. If there is none, the client waits with full jitter, which needs a derivation.
Let be the base wait (500 ms), the cap (30 s), and the index of the attempt that just failed. The ceiling of the wait after it is
Under full jitter the wait is drawn uniformly from , , with density on that interval, so
With attempts there are waits, since the last failure returns instead of waiting, so the expected total is . For the defaults, and the ceilings are s and s, so the expected total wait is s, against s for the same schedule without jitter. In the worst case no wait exceeds , so a call that fails times spends at most waiting, 60 s by default, plus the time of the requests themselves.
Why add randomness at all? The worst case is the same and the expected wait is half. The failures that matter arrive together. Suppose clients fail at the same instant, say a router restarting under them. Without jitter, every one of them returns at , so the server sees the same requests again at once, and again at the next doubling. With jitter, client returns at , independently ( the ceiling). Two of them land within of each other when . The pair is uniform on the square , whose area is . The band is the square minus two right triangles at opposite corners, each with legs and area . So the band’s area is , and for
There are pairs, so the expected number of colliding pairs is for large and , using . A check of the band formula by simulation on talos (seed 1, two million draws, , ) gave 0.189963 against the formula’s 0.19. With , ms and ms, the exact expectation is 196.02 colliding pairs and the approximation 200, out of 4,950 pairs that collide with certainty without jitter; the herd is spread over the window instead of landing together. Marc Brooker’s simulation of clients contending for one database row (Further reading) compares full jitter with equal and decorrelated jitter. The client uses full jitter, the simplest of the three; he finds it does the least work of them, at slightly more time than decorrelated jitter.
Two details of the header. Its date form is relative to the client’s clock, so clock skew shows up as a longer or shorter wait: a client 10 s behind the server waits 10 s longer than the server meant. A past date counts as absent, so a client far ahead of the server falls back to backoff, and the cap bounds the damage either way. A cancelled context ends the loop wherever it is, before the request or in the middle of a wait, and returns ctx.Err().
Fixtures
A wire client is easy to test against a fake that the same author wrote, and such a test finds nothing the author did not already believe. The fixtures here are the responses of real servers, recorded by aec-capture, a tool run by hand and never by a test. It sends requests built by Provider.Encode to the reader’s llama.cpp routers and writes each exchange as one JSON file: the provider, model, capture date, the machine that ran the tool, the request path and body, and the response status, headers and body.
The fleet rule is enforced in the tool’s code, not left to the operator. aec-capture re-reads GET /v1/models immediately before every request that names a model and refuses unless that model’s status.value is loaded; it sends the request with ?autoload=false. A sleeping model is not loaded, because at llama.cpp b29c606 a request wakes it and the router counts it as running. One model on one host, ornith-1.5-35b-a3b on straylight, may be woken with an explicit flag; it was already loaded and the flag was not used. The tool ignores the environment’s proxy settings and follows no redirect, so the guard and the request reach the same server. It logs one line per check. Its error lines can carry a provider’s words, so on a terminal they pass through termtext.Line (chapter 42 lists it) and to a pipe or a file they are the bytes. It refuses a request whose body names a different model than the one it checked.
What a fixture pins is behaviour, never layout. The header allowlist keeps Content-Type and Retry-After: the status, the content type and the retry hint decide what the client does, and nothing else a server sends (dates, request ids, counters that move on every run) should break a test. Redaction runs before a file is written, over the body as well as the headers (listing ch24-redact below): the value of every *_API_KEY or *_TOKEN variable in the environment first, then the known key shapes (a value that itself holds a shape is replaced whole, where a shape run first would cut it and leave a tail that matches nothing; chapter 37 fixed the order for eval.Redact and chapter 48 made the two one redactor). TestNoSecretsInTestdata walks every testdata directory under go/, not only this chapter’s, and fails on header names, a bearer token, an OpenAI-style key, a z.ai-, Hugging Face- or GitHub-shaped token, or the full value of any key variable in the environment. It reports the file and the byte offset and never the match, and a second test plants each shape in a temporary tree to prove it would notice. TestFixtures replays all 23 files through the client and checks structure: a 2xx parses, a stream assembles with reasoning apart from content, a tool call the server parsed arrives with a name and argument text, usage is read where the body has it, and a non-2xx is a *StatusError. It never compares an id, a count or a timing.
Twenty-five requests were captured on 2026-10-02 (UTC) from talos: 23 to dixie’s ornith-1.5-9b-uncensored and 2 to straylight’s ornith-1.5-35b-a3b. They gave 21 dixie fixtures and 2 straylight ones, and 7 corpus records for chapter 25 (five of them from elicitation fixtures; two from requests that gave only a record). What they showed, by fixture name:
tool.json: the server parsed the model’s call.tool_callsholds oneread_filecall,contentis""(OpenAI returnsnull),finish_reasonistool_calls,reasoning_contentis present, and the call carries noindex, since a non-streaming call needs none. The call’s id is 32 random characters with no prefix: ids are opaque.tool-stream.json: 38 chunks. The first carries only the role. Then 28reasoning_contentchunks, then 7 tool-call fragments, all"index":0, then a finish chunk with an empty delta, then the usage chunk, then[DONE]. Only the first fragment carriesid,typeandname; the arguments{"path":"/etc/hosts"}arrive as{,"path":",/etc,/,hosts,"and}.parallel-stream.jsonhas two calls with indexes 0 and 1, 8 and 9 fragments, each call’s first fragment carrying its own id. llama-server sent call 0 completely before call 1, so the capture contains no interleaving. Interleaving is what the SDK’s shape permits and what the lab’s synthetic test sends.forced-stream.jsonneeds 12 fragments for{"pattern":"TODO","path":"src","max_results":100}, the last number arriving as1,0,0. The non-streamedforced.jsonchose 1000, the schema’s maximum: two generations, two values. The two forced captures sendtool_choiceas the object{"type":"function","function":{"name":"search_files"}}, with one tool offered and a prompt that asks for a search, so they cannot show whether the server enforces the choice. At b29c606 llama-server readstool_choiceas a string and falls back toautoon anything else (chapter 25 traces the code), andforced-other.jsonis the observation that fits it: two tools offered,tool_choicenamingread_file, a prompt that asks for a search, and the 9b answered with asearch_filescall (finish_reasontool_calls). It is one request, so it is consistent with the fallback and does not prove it.reasoning.jsonandreasoning-stream.json: the server splits the think block:reasoning_contentis 406 characters andcontentis17 × 23 = 391. In the stream 177 chunks carry reasoning and 11 carry content, reasoning first. Every other successful 9b capture also carriesreasoning_content, includingplain.json(58 characters of reasoning for the answerready) andtool.json(74).elicit-truncated.jsonhas noreasoning_content, but only because its request setreasoning_formattonone(andenable_thinkingfalse throughchat_template_kwargs): the server then left an empty<think>\n\n</think>block incontent. It is a different configuration, not a case of the model not thinking.parallel.json: withparallel_tool_calls: truein the request, the 9b made twoget_weathercalls (Berlin, Oslo) with different ids, and also wrote a sentence incontent. Whether it would have made two calls without the flag was not tested.schema.json(max_tokens128,response_formata strict JSON schema): the answer is empty.finish_reasonislength,contentis"", andreasoning_contentis 522 characters: the 128 tokens ran out while the model was thinking.schema-stream.jsonis the same request streamed: 125 reasoning chunks and one content chunk,{", then the cut. Withmax_tokens1024 the answers parse:schema-1024.jsonhas content{\n "city": "Oslo",\n "millions": 1.0\n}andschema-1024-stream.jsonhas{\n "city": "Oslo",\n "millions": 0.7\n}(the escapes are newlines). The two runs disagree on the population, and neither is a claim about Norway.- All 7 dixie streams end with
data: [DONE]and carry a usage chunk.Content-Typeistext/event-streamfor streams andapplication/json; charset=utf-8otherwise.bad-request.jsonis a 400 with body{"error":{"code":400,"message":"Expected 'messages' to be an array","type":"invalid_request_error"}}, which has the OpenAI envelope withcodean integer. The client readscodeas raw text for that reason. There is noRetry-After. - Every successful body also carries a
system_fingerprint(b10964-b29c606) and atimingsobject of per-request speeds; the client ignores both.
The straylight captures, tool.json and tool-stream.json, have the same shape as dixie’s.
The Anthropic adapter
go/internal/llm/anthropic implements llm.Client over the same canonical types. It has no retries of its own: a non-2xx is a *llm.StatusError with Retry-After parsed, for chapter 28’s chain to judge, and 529 is in Transient. The request carries anthropic-version: 2023-06-01 and the key as Authorization: Bearer <key>. The vendor’s API overview lists that header first, “where <token> is your API key or a short-lived access token”, and describes x-api-key as “Your API key from Console. Legacy fallback for Authorization, still supported” (fetched 2026-10-01). The adapter sends only the first.
The mapping, going out. System messages become the top-level system; every other message is a turn of blocks; consecutive messages of one role merge. Text parts become text blocks, and an image part becomes an image block (a data: URL as a base64 source with its media type, any other URL as a URL source); the adapter’s tests check the data-URL case and the vendor’s image documentation was not fetched for this chapter. Tool calls become tool_use blocks whose input is the arguments text, sent as given, so a 20-digit integer is not rounded through a float; an empty string means {}. Arguments that are not exactly one JSON object, that are null, or that repeat a key at any depth are an error on this wire, because a parser keeps the last value and a reader of the text may keep the first, and neither the model nor an injected string should choose which one the API sees. Empty text parts are skipped, because a text block must not be empty, and a message left with no block is dropped. Signed thinking in a user message, and a tool_choice without tools, are errors rather than requests the API would reject. A tool message becomes a tool_result block in a user turn, with is_error set from IsError; an image in the result makes its content an array of blocks. max_tokens is always sent, 1,024 when the request sets none: Create a Message lists it among the body parameters without “optional” (- max_tokens: number), so it is required. The same page says “Set to 0 to populate the prompt cache without generating a response”, which this adapter cannot ask for, since 0 in llm.Request.MaxTokens means unset. ToolChoice maps required to {"type":"any"}, a name to {"type":"tool","name":…}, and none to {"type":"none"}; ParallelToolCalls: false becomes disable_parallel_tool_use: true inside tool_choice, where the vendor puts it (“It is not a top-level request parameter”). ResponseFormat is an error, ErrResponseFormat, because this adapter does not map it. The Messages API has constrained decoding of its own: its structured-outputs page (https://platform.claude.com/docs/en/build-with-claude/structured-outputs, fetched 2026-10-01) says “Structured outputs constrain Claude’s responses to follow a specific schema” and names two features, JSON outputs in output_config.format (type: "json_schema") and strict tool use (strict: true). The adapter sends neither; the idiom it takes is a forced tool whose input_schema is the schema (exercise (d)). It has no request field for reasoning text either; thinking blocks go back as parts.
Going in, decode maps text blocks to text parts, thinking blocks to Reasoning and a thinking part, redacted_thinking to its part, and tool_use blocks to ToolCalls whose Arguments is the compact JSON of input. For streaming, the event machine is message_start, then blocks, then message_delta, then message_stop. message_start carries the message id and the input token count; the usage on message_delta is cumulative (“The token counts shown in the usage field of the message_delta event are cumulative”), so the adapter takes both counts from the last one that has them; content_block_start opens a block by index (for a tool_use block the id and name arrive here, before any input); content_block_delta carries text_delta, thinking_delta, signature_delta or input_json_delta; message_delta carries stop_reason and the output tokens; ping is skipped. The vendor says of input_json_delta that “the deltas are partial JSON strings, whereas the final tool_use.input is always an object”, and the adapter therefore concatenates the partial strings by block index and does not parse them: streamed arguments keep the spacing the model produced, where non-streamed ones are compacted. Both are valid JSON, and chapter 25 reads both. A tool_use start’s own input is ignored, as the documented flow begins it empty and streams it; a delta for a block that no start opened ends the stream with an error. The index of a ToolCallDelta here is the block index, so a tool call that follows a text block is index 1, and the assembled message carries a tool_use placeholder part where each call stood. Usage.Prompt is input_tokens alone: the response’s usage carries cache_creation_input_tokens and cache_read_input_tokens as fields of their own (the SDK’s Usage type lists all three), so a caller that budgets on Prompt under prompt caching may count less than the request used (chapter 29 returns to it). An error event is a *llm.StreamError, whether its data is JSON or not, since the name is checked before the data is parsed: the streaming page’s example, an overloaded_error in the middle of an answer, is “an HTTP 529 in a non-streaming context”, and in a stream it arrives after the 200. The page also says that “new event types may be added, and your code should handle unknown event types gracefully”, so unknown events are skipped.
None of this adapter’s runs is a captured run. The course has no Anthropic key, so the adapter is tested against five fixtures transcribed verbatim from the vendor’s own pages: the basic stream, the tool-use stream, the thinking stream and the error event from the streaming page, and the tool-use message from the Handle tool calls page (apart from the page’s own indentation of that JSON). Each one names its source URL and fetch date and says “Not a captured run”, and TestDocFixtures refuses a fixture that does not. No count in them is invented: where a vendor example carries no usage, the fixture’s expectation is that the adapter reports none. The thinking_tokens field of the release notes of 27 May 2026 is exercised by a unit test with a made-up message_delta, not by a fixture. What the fixtures check is that the adapter reads these documented shapes; whether the live API still emits them is a claim they cannot make.
Walkthrough
The types come first. Part, Message, ToolCall, Tool, Request, Response, Delta, Stream and Client are the vocabulary of every later chapter, and StatusError carries what a failed call knows. Message and Usage carry JSON tags because chapter 40 saves sessions.
// Role is a chat role on the OpenAI wire. The Anthropic adapter maps "system"
// to the top-level system field and "tool" to a tool_result block.
type Role string
const (
System Role = "system"
User Role = "user"
Assistant Role = "assistant"
ToolRole Role = "tool"
)
// Part is one typed piece of message content. Chapter 24 uses text; chapter 41
// adds images and whisper transcripts as parts without changing Message
// (ch 16:7's promise), so content is a slice from the first chapter. The
// anthropic adapter (this chapter) adds thinking, redacted_thinking and a
// tool_use placeholder as part types, to replay a turn's blocks in order.
type Part struct {
Type string `json:"type"` // "text" | "image_url" | "input_audio" | "thinking" | "redacted_thinking" | "tool_use"
Text string `json:"text,omitempty"`
URL string `json:"url,omitempty"` // image_url.url: https:, or data:image/...;base64,
Data []byte `json:"data,omitempty"` // input_audio.data; base64 on the wire
Format string `json:"format,omitempty"` // input_audio.format
}
// Message is one turn. Reasoning is reasoning_content: kept beside Parts,
// never concatenated into them, and sent back only when the provider asks
// for it (contract §3). A single text part is sent as a plain string on the
// OpenAI wire, as every server accepts; several parts go as the typed array.
// IsError marks a tool message whose tool reported an error (chapter 27's
// Result.IsError): the Anthropic adapter sends it as tool_result.is_error;
// the OpenAI wire has no such flag, so there the text itself starts with
// "error: ". It is serialized, because a session saved for resume (chapter 40)
// must keep it.
type Message struct {
Role Role `json:"role"`
Parts []Part `json:"content"`
Reasoning string `json:"reasoning_content,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"` // assistant only
ToolCallID string `json:"tool_call_id,omitempty"` // tool only
Name string `json:"name,omitempty"`
IsError bool `json:"is_error,omitempty"` // tool only: the run failed; the wire carries the flag with the reply
}
// Text builds a one-part text message.
func Text(role Role, s string) Message {
return Message{Role: role, Parts: []Part{{Type: "text", Text: s}}}
}
// ToolCall is a call as the wire delivers it: Arguments is the raw JSON text
// the model produced, which chapter 25 decodes. ID is the provider's.
type ToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Arguments string `json:"arguments"`
}
// Tool is a tool definition. Parameters is a JSON Schema object.
type Tool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters json.RawMessage `json:"parameters"`
Strict bool `json:"strict,omitempty"`
}
// ToolChoice: Mode is "" (provider default), "auto", "none" or "required";
// Name asks for one tool: the Anthropic adapter maps required→any and
// Name→tool, and the OpenAI guide documents a forced function. llama-server
// at b29c606 reads tool_choice as a string and, by its code, falls back to
// auto (with a logged warning) for the object, so there Name is a request,
// not a guarantee.
type ToolChoice struct {
Mode string
Name string
}
// ResponseFormat is structured output: "json_object", or "json_schema" with
// Schema (and Strict), as llama-server and OpenAI both accept.
type ResponseFormat struct {
Type string
Name string
Schema json.RawMessage
Strict bool
}
// Request is one chat completion. Extra carries provider-specific fields
// through untouched (llama-server's reasoning_format, chat_template_kwargs,
// n_probs); a key that collides with a named field is an error at send time.
type Request struct {
Model string
Messages []Message
Tools []Tool
ToolChoice *ToolChoice
ParallelToolCalls *bool
ResponseFormat *ResponseFormat
MaxTokens int
Temperature *float64
TopP *float64
Stop []string
Extra map[string]json.RawMessage
}
// Usage is what the provider reports. Reasoning is the reasoning share when
// the provider breaks it out (OpenAI completion_tokens_details.reasoning_tokens,
// Anthropic output_tokens_details.thinking_tokens), else 0. Chapter 29 budgets
// on it and chapter 49 prices it.
type Usage struct {
Prompt int `json:"prompt_tokens"`
Completion int `json:"completion_tokens"`
Reasoning int `json:"reasoning_tokens,omitempty"`
// Cached is prompt_tokens_details.cached_tokens when the provider breaks
// it out (llama-server at b29c606, z.ai, OpenAI), else 0; it is a share of
// Prompt, not an addition to it. Chapter 29 reads it against the stable
// prefix it predicted.
Cached int `json:"cached_tokens,omitempty"`
}
// Response is one assembled completion. FinishReason is the OpenAI word
// ("stop", "length", "tool_calls", "content_filter") or the provider's own
// when it has no OpenAI equivalent (Anthropic "pause_turn").
type Response struct {
ID string
Model string
Message Message
FinishReason string
Usage *Usage
Raw json.RawMessage // the body or assembled chunks, for traces and fixtures
}
// Delta is one streamed increment. ToolCalls fragments carry the index the
// provider gave; an absent index is 0 (llama-server at b29c606 numbers them).
type Delta struct {
Text string
Reasoning string
ToolCalls []ToolCallDelta
FinishReason string
Usage *Usage
}
// ToolCallDelta is one fragment of a streamed tool call.
type ToolCallDelta struct {
Index int
ID string
Name string
Arguments string
}
// Stream yields deltas until io.EOF at the terminator ([DONE], or Anthropic's
// message_stop). Response assembles what was received, content and reasoning
// separately, tool calls merged by index as proxy.Assemble does.
type Stream interface {
Next() (Delta, error)
Response() (*Response, error)
Close() error
}
// Client is what every later chapter programs against.
type Client interface {
Complete(ctx context.Context, req Request) (*Response, error)
Stream(ctx context.Context, req Request) (Stream, error)
}
StatusError.Transient is the whole retry matrix’s table. Code is a string because OpenAI’s error.code is one and aec-router’s is an integer; parseErrorBody in wire.go reads it as raw text and unquotes.
// StatusError is a non-2xx answer. RetryAfter is parsed from Retry-After as
// delta-seconds or an HTTP-date (RFC 9110 §10.2.3); zero when absent.
type StatusError struct {
Status int
Code string // error.code when the body has the OpenAI shape
Type string // error.type
Message string
RetryAfter time.Duration
Body []byte
}
func (e *StatusError) Error() string {
if e.Message == "" {
return fmt.Sprintf("llm: HTTP %d", e.Status)
}
return fmt.Sprintf("llm: HTTP %d: %s", e.Status, e.Message)
}
// Transient reports whether the same request may succeed later, having
// delivered nothing: 408, 429, 502, 503, 504, 529 (Anthropic overloaded),
// and nothing else.
func (e *StatusError) Transient() bool {
switch e.Status {
case http.StatusRequestTimeout, http.StatusTooManyRequests, http.StatusBadGateway,
http.StatusServiceUnavailable, http.StatusGatewayTimeout, 529:
return true
}
return false
}
The encoder is the four rules of the Mechanism in order. On visible, thinking parts from the Anthropic adapter are filtered out before the string-or-array decision, so a message that held a thinking part and a text part still sends a plain string. Errors from the later set calls are collected and joined, not returned one at a time.
// encodeRequest writes one chat completion request. A message with exactly
// one text part sends content as a plain string, which every server accepts;
// anything else sends the typed array. An assistant message with tool calls
// and no parts sends content null, as the API returns it. Reasoning goes
// back only when SendReasoning is set (D11). Extra keys are copied last and
// may not collide with a named field.
func encodeRequest(p *Provider, req Request, stream bool) ([]byte, error) {
body := map[string]json.RawMessage{}
set := func(key string, v any) error {
raw, err := json.Marshal(v)
if err != nil {
return fmt.Errorf("llm: encode %s: %w", key, err)
}
body[key] = raw
return nil
}
msgs := make([]wireMessage, 0, len(req.Messages))
for _, m := range req.Messages {
w := wireMessage{Role: string(m.Role), ToolCallID: m.ToolCallID, Name: m.Name}
if p.SendReasoning {
w.ReasoningContent = m.Reasoning
}
for _, c := range m.ToolCalls {
w.ToolCalls = append(w.ToolCalls, wireToolCall{ID: c.ID, Type: "function",
Function: wireFunction{Name: c.Name, Arguments: c.Arguments}})
}
// Anthropic's signed thinking blocks and tool_use placeholders (parts of type thinking,
// redacted_thinking and tool_use, which the anthropic adapter adds) have no place
// on this wire: Reasoning carries the text, so they are skipped here.
visible := make([]Part, 0, len(m.Parts))
for _, part := range m.Parts {
if part.Type != "thinking" && part.Type != "redacted_thinking" && part.Type != "tool_use" {
visible = append(visible, part)
}
}
switch {
case len(visible) == 1 && visible[0].Type == "text":
w.Content = visible[0].Text
case len(visible) == 0 && len(m.ToolCalls) > 0:
w.Content = nil
case len(visible) == 0:
w.Content = ""
default:
parts := make([]wirePart, 0, len(visible))
for _, part := range visible {
wp := wirePart{Type: part.Type}
switch part.Type {
case "text":
wp.Text = part.Text
case "image_url":
wp.ImageURL = &wireImageURL{URL: part.URL}
case "input_audio":
wp.InputAudio = &wireInputAudio{Data: base64.StdEncoding.EncodeToString(part.Data), Format: part.Format}
default:
return nil, fmt.Errorf("llm: unknown part type %q", part.Type)
}
parts = append(parts, wp)
}
w.Content = parts
}
msgs = append(msgs, w)
}
if err := errors.Join(set("model", req.Model), set("messages", msgs)); err != nil {
return nil, err
}
if len(req.Tools) > 0 {
tools := make([]wireTool, 0, len(req.Tools))
for _, t := range req.Tools {
params := t.Parameters
if len(params) == 0 {
params = emptyParameters
}
tools = append(tools, wireTool{Type: "function", Function: wireToolDefinition{
Name: t.Name, Description: t.Description, Parameters: params, Strict: t.Strict}})
}
if err := set("tools", tools); err != nil {
return nil, err
}
}
var errs []error
if tc := req.ToolChoice; tc != nil {
switch {
case tc.Name != "":
errs = append(errs, set("tool_choice", map[string]any{"type": "function", "function": map[string]string{"name": tc.Name}}))
case tc.Mode != "":
errs = append(errs, set("tool_choice", tc.Mode))
}
}
if req.ParallelToolCalls != nil {
errs = append(errs, set("parallel_tool_calls", *req.ParallelToolCalls))
}
if rf := req.ResponseFormat; rf != nil {
switch rf.Type {
case "json_object":
errs = append(errs, set("response_format", map[string]string{"type": "json_object"}))
case "json_schema":
name := rf.Name
if name == "" {
name = "response"
}
js := map[string]any{"name": name, "schema": rf.Schema}
if rf.Strict {
js["strict"] = true
}
errs = append(errs, set("response_format", map[string]any{"type": "json_schema", "json_schema": js}))
default:
return nil, fmt.Errorf("llm: unknown response_format type %q", rf.Type)
}
}
if req.MaxTokens > 0 {
errs = append(errs, set("max_tokens", req.MaxTokens))
}
if req.Temperature != nil {
errs = append(errs, set("temperature", *req.Temperature))
}
if req.TopP != nil {
errs = append(errs, set("top_p", *req.TopP))
}
if len(req.Stop) > 0 {
errs = append(errs, set("stop", req.Stop))
}
if stream {
errs = append(errs, set("stream", true))
errs = append(errs, set("stream_options", map[string]bool{"include_usage": true}))
}
if err := errors.Join(errs...); err != nil {
return nil, err
}
for k, v := range req.Extra {
if reserved[k] {
return nil, fmt.Errorf("llm: Extra[%q] collides with a named field", k)
}
if len(v) == 0 || !json.Valid(v) {
return nil, fmt.Errorf("llm: Extra[%q] is not valid JSON", k)
}
body[k] = v
}
return json.Marshal(body) // keys sorted: the same request always encodes to the same bytes
}
EventReader is the pull-style reader of chapter 23’s algorithm. It is a second implementation by design: the client must not import the router’s packages, or cmd/aec would link the router, and TestReadersAgree holds the two to identical event sequences, apart from a leading byte order mark, which this reader drops and the proxy’s does not. The Anthropic adapter shares it.
// EventReader reads a text/event-stream one event at a time. It is the same
// algorithm as chapter 23's proxy.ReadEvents, in pull form so that a Stream
// can hand out one Delta per call: lines end in LF or CRLF (a lone CR does
// not end one, unlike the WHATWG text; llama-server and the Messages API send
// LF); a leading byte order mark is dropped; a line starting
// with ':' is a comment; "field: value" drops one space after the colon;
// several data lines join with newlines; an event ends at a blank line, or at
// EOF if lines were read after the last blank line (the WHATWG text discards
// such an event; here a final data line without its blank line is kept, and
// an event with a name and no data, as `event: error` can be, is returned).
// The client has its own
// reader because it must not depend on the router's packages
// (TestReadersAgree holds the two to the same event sequences, apart from
// a leading byte order mark, which this reader drops and the proxy's does not);
// the Anthropic adapter shares it.
type EventReader struct {
br *bufio.Reader
line []byte
started bool
}
// NewEventReader reads events from r.
func NewEventReader(r io.Reader) *EventReader {
return &EventReader{br: bufio.NewReaderSize(r, 64<<10)}
}
// Next returns the next event, or io.EOF when the stream ended cleanly after
// a blank line (or was empty). A read error, or ErrEventTooLong, ends the
// stream with that error.
func (er *EventReader) Next() (Event, error) {
var ev Event
var data []string
for {
part, err := er.br.ReadSlice('\n')
er.line = append(er.line, part...)
if len(ev.Raw)+len(er.line) > MaxEvent {
return Event{}, ErrEventTooLong
}
if err == bufio.ErrBufferFull {
continue // the line goes on past the buffer
}
if len(er.line) > 0 {
if !er.started {
er.started = true
er.line = bytes.TrimPrefix(er.line, []byte("\xEF\xBB\xBF")) // a leading byte order mark is not part of the stream
}
ev.Raw = append(ev.Raw, er.line...)
text := strings.TrimRight(string(er.line), "\r\n")
er.line = er.line[:0]
switch {
case text == "":
ev.Data = strings.Join(data, "\n")
return ev, nil
case text[0] == ':':
// a comment: kept in Raw, no field
default:
field, value, _ := strings.Cut(text, ":")
value = strings.TrimPrefix(value, " ")
switch field {
case "event":
ev.Name = value
case "data":
data = append(data, value)
}
}
}
if err == io.EOF {
if len(ev.Raw) > 0 {
ev.Data = strings.Join(data, "\n")
return ev, nil // the final event, without its blank line
}
return Event{}, io.EOF
}
if err != nil {
return Event{}, err
}
}
}
The assembler is the three rules of the streaming section, and it is shared with llm.Fake so a scripted stream assembles exactly as a wire stream does. Next is the state machine around it: skip what carries nothing, [DONE] is io.EOF, anything else that ends the stream is final and sticky.
// assembler folds deltas into one Response: text and reasoning concatenated
// separately, tool calls merged by index (the first fragment carrying id and
// name, every fragment adding to the arguments), finish_reason from the last
// delta that has one, usage from the last delta that has one. It is shared
// by the wire Stream and by Fake, so a scripted stream assembles exactly as a
// real one does.
type assembler struct {
id, model string
text strings.Builder
reasoning strings.Builder
calls map[int]*ToolCall
args map[int]*strings.Builder
finish string
usage *Usage
chunks []json.RawMessage
}
func (a *assembler) add(d Delta) {
a.text.WriteString(d.Text)
a.reasoning.WriteString(d.Reasoning)
for _, f := range d.ToolCalls {
if a.calls == nil {
a.calls, a.args = map[int]*ToolCall{}, map[int]*strings.Builder{}
}
call := a.calls[f.Index]
if call == nil {
call = &ToolCall{}
a.calls[f.Index], a.args[f.Index] = call, &strings.Builder{}
}
if f.ID != "" {
call.ID = f.ID
}
if f.Name != "" {
call.Name = f.Name
}
a.args[f.Index].WriteString(f.Arguments)
}
if d.FinishReason != "" {
a.finish = d.FinishReason
}
if d.Usage != nil {
u := *d.Usage
a.usage = &u
}
}
func (a *assembler) response() *Response {
msg := Message{Role: Assistant, Reasoning: a.reasoning.String()}
for _, i := range sortedInts(a.calls) {
c := *a.calls[i]
c.Arguments = a.args[i].String()
msg.ToolCalls = append(msg.ToolCalls, c)
}
if text := a.text.String(); text != "" || len(msg.ToolCalls) == 0 {
msg.Parts = []Part{{Type: "text", Text: text}}
}
resp := &Response{ID: a.id, Model: a.model, Message: msg, FinishReason: a.finish, Usage: a.usage}
if a.chunks != nil {
resp.Raw, _ = json.Marshal(a.chunks) // the chunks as received, as one JSON array
}
return resp
}
// Next returns the next delta. A chunk that carries nothing (llama-server's
// first chunk is only {"role":"assistant"}) is skipped. [DONE] ends the
// stream with io.EOF; an end without it is ErrNoDone; an error event or an
// error chunk is a *StreamError. Every error other than io.EOF is final.
func (s *stream) Next() (Delta, error) {
if s.done {
return Delta{}, io.EOF
}
if s.err != nil {
return Delta{}, s.err
}
for {
ev, err := s.er.Next()
if err == io.EOF {
return s.fail(ErrNoDone)
}
if err != nil {
return s.fail(err)
}
if ev.Name == "error" {
return s.fail(&StreamError{Body: errorBody([]byte(ev.Data))})
}
if ev.Data == "" {
continue // a comment or an empty event
}
if ev.Data == "[DONE]" {
s.done = true
return Delta{}, io.EOF
}
var c chunk
if err := json.Unmarshal([]byte(ev.Data), &c); err != nil {
return s.fail(fmt.Errorf("llm: stream chunk is not JSON: %w", err))
}
if len(c.Error) > 0 && string(c.Error) != "null" {
return s.fail(&StreamError{Body: errorBody(c.Error)})
}
s.asm.chunks = append(s.asm.chunks, json.RawMessage(ev.Data))
if s.asm.id == "" && c.ID != "" {
s.asm.id, s.asm.model = c.ID, c.Model
}
d := Delta{Usage: c.Usage.usage()}
if len(c.Choices) > 0 {
ch := c.Choices[0]
d.Text, d.Reasoning = ch.Delta.Content, ch.Delta.ReasoningContent
if ch.FinishReason != nil {
d.FinishReason = *ch.FinishReason
}
for _, tc := range ch.Delta.ToolCalls {
d.ToolCalls = append(d.ToolCalls, ToolCallDelta{Index: tc.Index, ID: tc.ID,
Name: tc.Function.Name, Arguments: tc.Function.Arguments})
}
}
if d.Text == "" && d.Reasoning == "" && len(d.ToolCalls) == 0 && d.FinishReason == "" && d.Usage == nil {
continue
}
s.asm.add(d)
return d, nil
}
}
The backoff is the derivation’s and a draw from ; the shift is guarded against overflow, and Rand is injectable, which is what lets the lab’s rig make every wait its ceiling.
// backoff is full jitter (Brooker, 2015): a uniform draw from
// [0, min(MaxWait, Base·2^attempt)]. Rand is injectable; nil uses math/rand/v2.
func (p *Provider) backoff(attempt int) time.Duration {
capped := p.base() << uint(attempt)
if capped > p.maxWait() || capped <= 0 {
capped = p.maxWait()
}
r := rand.Float64
if p.Retry.Rand != nil {
r = p.Retry.Rand
}
return time.Duration(r() * float64(capped))
}
// ParseRetryAfter parses a Retry-After value as delta-seconds (ASCII digits
// only, RFC 9110 §10.2.3's 1*DIGIT, so no sign), else as an HTTP-date
// relative to the injected clock; zero when absent, unparseable or in the
// past. A value of digits too large for a duration is a cap, not an absence:
// the caller's MaxWait then applies.
func ParseRetryAfter(v string, now time.Time) time.Duration {
v = strings.TrimSpace(v)
if v == "" {
return 0
}
if isDigits(v) {
secs, err := strconv.ParseUint(v, 10, 64)
if err != nil || secs > uint64(math.MaxInt64/time.Second) {
return time.Duration(math.MaxInt64)
}
return time.Duration(secs) * time.Second
}
if t, err := http.ParseTime(v); err == nil {
if d := t.Sub(now); d > 0 {
return d
}
}
return 0
}
do is the matrix. The loop returns on a 2xx; on a transport error it returns a cancelled context’s error at once, else waits and tries again; on a status it builds the StatusError, returns it if it is not transient or the attempts are spent, and otherwise waits the Retry-After or the backoff, capped at MaxWait. Nothing here runs after a 2xx has begun: Complete and Stream call do once and own everything after it.
// do sends the request until a 2xx arrives or the matrix says stop. It
// retries only what has delivered nothing to the caller: a transport error
// with no response at all, or a transient status (408, 429, 502, 503, 504, 529). A 503
// (or any transient answer) with Retry-After waits that long, capped at
// MaxWait; without it, full-jitter backoff. Any other status is returned at
// once: the router's 400s are permanent for this request, its 500 is an
// internal fault, and chapter 28's chain, not this client, decides whether
// another provider gets the request. A transport error that implements
// interface{ Permanent() bool } and returns true (a refusal by the caller's
// own transport, such as chapter 28's fleet guard declining to send) is
// returned at once: retrying it can only repeat the refusal. A cancelled
// context ends the loop wherever it is.
func (p *Provider) do(ctx context.Context, body []byte, stream bool) (*http.Response, error) {
attempts := p.attempts()
for attempt := 0; ; attempt++ {
hreq, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(p.BaseURL, "/")+"/chat/completions", bytes.NewReader(body))
if err != nil {
return nil, err
}
hreq.Header.Set("Content-Type", "application/json")
hreq.Header.Set("Accept", "application/json")
if stream {
hreq.Header.Set("Accept", "text/event-stream")
}
if p.APIKey != "" {
hreq.Header.Set("Authorization", "Bearer "+p.APIKey)
}
resp, err := p.client().Do(hreq)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
var perm interface{ Permanent() bool }
if attempt+1 >= attempts || (errors.As(err, &perm) && perm.Permanent()) {
return nil, fmt.Errorf("llm: %s: %w", p.Name, err)
}
if err := p.sleep(ctx, p.backoff(attempt)); err != nil {
return nil, err
}
continue
}
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return resp, nil
}
se := &StatusError{Status: resp.StatusCode, RetryAfter: ParseRetryAfter(resp.Header.Get("Retry-After"), p.now())}
se.Body, _ = io.ReadAll(io.LimitReader(resp.Body, maxErrorBody))
resp.Body.Close()
parseErrorBody(se)
if !se.Transient() || attempt+1 >= attempts {
return nil, se
}
wait := se.RetryAfter
if wait <= 0 {
wait = p.backoff(attempt)
}
if wait > p.maxWait() {
wait = p.maxWait()
}
if err := p.sleep(ctx, wait); err != nil {
return nil, err
}
}
}
The contrast is encode, the Messages wire’s request: system joined, turns merged, blocks in the response’s order (a tool_use placeholder expanded from its call), tool results with is_error, the tool choice with disable_parallel_tool_use inside it.
// encode maps a Request onto the Messages wire. System messages become the
// top-level system string (several are joined by blank lines); every other
// message is a turn of content blocks; consecutive messages of one role are
// merged into one turn, which is how several tool results travel (one user
// turn, one tool_result block each, is_error from the message's IsError, and
// the tool_result blocks first, as the vendor requires). An assistant turn
// replays its blocks in the order the response had them: thinking parts as
// they are, and a tool_use placeholder part expanded to the tool call it
// names; a call without a placeholder follows the parts. Text parts that are
// empty are skipped, and a message left with no block is dropped, because
// the API refuses empty text blocks. What would be sent wrongly is refused:
// arguments that are not one JSON object without repeated keys, signed
// thinking in a user turn, a tool choice without tools.
func (c *Client) encode(req llm.Request, stream bool) ([]byte, error) {
if req.ResponseFormat != nil {
return nil, ErrResponseFormat
}
if len(req.Tools) == 0 && (req.ToolChoice != nil || (req.ParallelToolCalls != nil && !*req.ParallelToolCalls)) {
return nil, errors.New("anthropic: a tool choice needs tools")
}
body := map[string]any{"model": req.Model}
var system []string
var turns []map[string]any
add := func(role string, blocks ...any) {
if len(blocks) == 0 {
return
}
if n := len(turns); n > 0 && turns[n-1]["role"] == role {
have := turns[n-1]["content"].([]any)
for _, blk := range blocks {
if bm, ok := blk.(map[string]any); ok && bm["type"] == "tool_result" {
i := 0
for i < len(have) && have[i].(map[string]any)["type"] == "tool_result" {
i++
}
have = append(have[:i], append([]any{blk}, have[i:]...)...)
continue
}
have = append(have, blk)
}
turns[n-1]["content"] = have
return
}
turns = append(turns, map[string]any{"role": role, "content": append([]any{}, blocks...)})
}
for _, m := range req.Messages {
switch m.Role {
case llm.System:
for _, p := range m.Parts {
if p.Type == "text" {
system = append(system, p.Text)
}
}
case llm.ToolRole:
var text string
var content []any
rich := false
for _, p := range m.Parts {
switch p.Type {
case "text":
text += p.Text
if p.Text != "" {
content = append(content, map[string]any{"type": "text", "text": p.Text})
}
case "image_url":
src, err := imageSource(p.URL)
if err != nil {
return nil, err
}
content = append(content, map[string]any{"type": "image", "source": src})
rich = true
default:
return nil, fmt.Errorf("anthropic: no tool_result content for part type %q", p.Type)
}
}
block := map[string]any{"type": "tool_result", "tool_use_id": m.ToolCallID, "content": text}
if rich {
block["content"] = content
}
if m.IsError {
block["is_error"] = true
}
add("user", block)
case llm.User, llm.Assistant:
var blocks []any
used := map[int]bool{}
for _, p := range m.Parts {
switch p.Type {
case "text":
if p.Text != "" {
blocks = append(blocks, map[string]any{"type": "text", "text": p.Text})
}
case PartThinking, PartRedactedThinking, PartToolUse:
if m.Role != llm.Assistant {
return nil, fmt.Errorf("anthropic: a %s part belongs in an assistant message", p.Type)
}
switch p.Type {
case PartThinking:
blocks = append(blocks, map[string]any{"type": "thinking", "thinking": p.Text, "signature": string(p.Data)})
case PartRedactedThinking:
blocks = append(blocks, map[string]any{"type": "redacted_thinking", "data": string(p.Data)})
default:
for i, tc := range m.ToolCalls {
if !used[i] && tc.ID == p.Text {
b, err := toolUse(tc)
if err != nil {
return nil, err
}
blocks = append(blocks, b)
used[i] = true
break
}
}
}
case "image_url":
src, err := imageSource(p.URL)
if err != nil {
return nil, err
}
blocks = append(blocks, map[string]any{"type": "image", "source": src})
default:
return nil, fmt.Errorf("anthropic: no block for part type %q", p.Type)
}
}
for i, tc := range m.ToolCalls {
if used[i] {
continue
}
b, err := toolUse(tc)
if err != nil {
return nil, err
}
blocks = append(blocks, b)
}
add(string(m.Role), blocks...)
default:
return nil, fmt.Errorf("anthropic: unknown role %q", m.Role)
}
}
if len(system) > 0 {
body["system"] = strings.Join(system, "\n\n")
}
body["messages"] = turns
body["max_tokens"] = DefaultMaxTokens
if req.MaxTokens > 0 {
body["max_tokens"] = req.MaxTokens
}
if len(req.Tools) > 0 {
var tools []map[string]any
for _, t := range req.Tools {
schema := t.Parameters
if len(schema) == 0 {
schema = json.RawMessage(`{"type":"object","properties":{}}`)
}
tool := map[string]any{"name": t.Name, "input_schema": schema}
if t.Description != "" {
tool["description"] = t.Description
}
tools = append(tools, tool)
}
body["tools"] = tools
}
if tc := req.ToolChoice; tc != nil || (req.ParallelToolCalls != nil && !*req.ParallelToolCalls) {
choice := map[string]any{"type": "auto"}
if tc != nil {
switch {
case tc.Name != "":
choice = map[string]any{"type": "tool", "name": tc.Name}
case tc.Mode == "required":
choice = map[string]any{"type": "any"}
case tc.Mode == "none":
choice = map[string]any{"type": "none"}
case tc.Mode == "auto", tc.Mode == "":
default:
return nil, fmt.Errorf("anthropic: unknown tool choice mode %q", tc.Mode)
}
}
if req.ParallelToolCalls != nil && !*req.ParallelToolCalls && choice["type"] != "none" {
choice["disable_parallel_tool_use"] = true
}
body["tool_choice"] = choice
}
if req.Temperature != nil {
body["temperature"] = *req.Temperature
}
if req.TopP != nil {
body["top_p"] = *req.TopP
}
if len(req.Stop) > 0 {
body["stop_sequences"] = req.Stop
}
if stream {
body["stream"] = true
}
for k, v := range req.Extra {
if reserved[k] {
return nil, fmt.Errorf("anthropic: Extra[%q] collides with a named field", k)
}
body[k] = v
}
return json.Marshal(body)
}
// toolUse is a tool call as a tool_use block. The arguments must be one JSON
// object with no repeated key (a parser keeps the last, a reader of the text
// may keep the first, and neither the model nor an injector should choose);
// their text is sent as it is, so a 20-digit integer is not rounded.
func toolUse(tc llm.ToolCall) (map[string]any, error) {
input := json.RawMessage(`{}`)
if args := strings.TrimSpace(tc.Arguments); args != "" {
if err := checkObject(args); err != nil {
return nil, fmt.Errorf("anthropic: tool call %s: arguments must be one JSON object on this wire: %w", tc.ID, err)
}
input = json.RawMessage(args)
}
return map[string]any{"type": "tool_use", "id": tc.ID, "name": tc.Name, "input": input}, nil
}
// checkObject reports whether s is exactly one JSON object whose objects, at
// every depth, have distinct keys.
func checkObject(s string) error {
dec := json.NewDecoder(strings.NewReader(s))
tok, err := dec.Token()
if err != nil {
return err
}
if d, ok := tok.(json.Delim); !ok || d != '{' {
return errors.New("not an object")
}
if err := scanObject(dec); err != nil {
return err
}
if _, err := dec.Token(); err != io.EOF {
return errors.New("data after the object")
}
return nil
}
// scanObject reads an object's members after its '{' and the closing '}'.
func scanObject(dec *json.Decoder) error {
seen := map[string]bool{}
for dec.More() {
k, err := dec.Token()
if err != nil {
return err
}
key := k.(string)
if seen[key] {
return fmt.Errorf("repeated key %q", key)
}
seen[key] = true
if err := scanValue(dec); err != nil {
return err
}
}
_, err := dec.Token()
return err
}
func scanValue(dec *json.Decoder) error {
tok, err := dec.Token()
if err != nil {
return err
}
d, ok := tok.(json.Delim)
if !ok {
return nil
}
if d == '{' {
return scanObject(dec)
}
for dec.More() {
if err := scanValue(dec); err != nil {
return err
}
}
_, err = dec.Token()
return err
}
// decode maps a Messages response onto llm.Response: text blocks become text
// parts, thinking blocks become Reasoning (the text) and a thinking part
// (text plus signature, for replay), tool_use blocks become ToolCalls whose
// Arguments is the compact JSON of input (an object here, a string on the
// other wire: the chapter's central contrast), stop_reason is mapped.
func decode(body []byte) (*llm.Response, error) {
var w wireMessage
if err := json.Unmarshal(body, &w); err != nil {
return nil, fmt.Errorf("anthropic: response is not JSON: %w", err)
}
msg := llm.Message{Role: llm.Assistant}
var reasoning strings.Builder
for _, b := range w.Content {
switch b.Type {
case "text":
msg.Parts = append(msg.Parts, llm.Part{Type: "text", Text: b.Text})
case "thinking":
reasoning.WriteString(b.Thinking)
msg.Parts = append(msg.Parts, llm.Part{Type: PartThinking, Text: b.Thinking, Data: []byte(b.Signature)})
case "redacted_thinking":
msg.Parts = append(msg.Parts, llm.Part{Type: PartRedactedThinking, Data: []byte(b.Data)})
case "tool_use":
args, err := compact(b.Input)
if err != nil {
return nil, fmt.Errorf("anthropic: tool_use %s: %w", b.ID, err)
}
msg.Parts = append(msg.Parts, llm.Part{Type: PartToolUse, Text: b.ID})
msg.ToolCalls = append(msg.ToolCalls, llm.ToolCall{ID: b.ID, Name: b.Name, Arguments: args})
}
}
msg.Reasoning = reasoning.String()
return &llm.Response{ID: w.ID, Model: w.Model, Message: msg, FinishReason: mapStop(w.StopReason), Usage: w.Usage.usage(), Raw: json.RawMessage(body)}, nil
}
// Next maps the event stream onto deltas: message_start carries the id and
// the input tokens; content_block_start opens a block by index (a tool_use
// block's id and name arrive here, before any input); content_block_delta
// carries text_delta, thinking_delta, input_json_delta (partial JSON text of
// the input, merged by block index) or signature_delta; message_delta carries
// stop_reason and the output tokens; message_stop is io.EOF; ping is skipped;
// an error event is a *llm.StreamError. An end without message_stop is
// ErrNoStop. Unknown event types are skipped, as the vendor asks.
func (s *stream) Next() (llm.Delta, error) {
if s.done {
return llm.Delta{}, io.EOF
}
if s.err != nil {
return llm.Delta{}, s.err
}
for {
ev, err := s.er.Next()
if err == io.EOF {
return s.fail(ErrNoStop)
}
if err != nil {
return s.fail(err)
}
if ev.Name == "error" {
// Named an error, whatever its data is: JSON or not.
return s.fail(&llm.StreamError{Body: []byte(ev.Data)})
}
if ev.Data == "" {
continue
}
var e wireEvent
if err := json.Unmarshal([]byte(ev.Data), &e); err != nil {
return s.fail(fmt.Errorf("anthropic: event is not JSON: %w", err))
}
if e.Type == "error" {
return s.fail(&llm.StreamError{Body: []byte(ev.Data)})
}
s.events = append(s.events, json.RawMessage(ev.Data))
var d llm.Delta
switch e.Type {
case "message_start":
if e.Message != nil {
s.id, s.model = e.Message.ID, e.Message.Model
if u := e.Message.Usage.usage(); u != nil {
s.usage = u
}
}
continue
case "content_block_start":
if e.ContentBlock == nil {
continue
}
b := &block{typ: e.ContentBlock.Type, id: e.ContentBlock.ID, name: e.ContentBlock.Name, data: e.ContentBlock.Data}
b.text.WriteString(e.ContentBlock.Text)
s.blocks[e.Index] = b
s.order = append(s.order, e.Index)
if b.typ == "tool_use" {
d.ToolCalls = []llm.ToolCallDelta{{Index: e.Index, ID: b.id, Name: b.name}}
return d, nil
}
continue
case "content_block_delta":
var wd wireDelta
if err := json.Unmarshal(e.Delta, &wd); err != nil {
return s.fail(fmt.Errorf("anthropic: delta is not JSON: %w", err))
}
b := s.blocks[e.Index]
if b == nil {
return s.fail(fmt.Errorf("anthropic: a delta for block %d, which no content_block_start opened", e.Index))
}
switch wd.Type {
case "text_delta":
b.text.WriteString(wd.Text)
d.Text = wd.Text
case "thinking_delta":
b.text.WriteString(wd.Thinking)
d.Reasoning = wd.Thinking
case "input_json_delta":
b.text.WriteString(wd.PartialJSON)
d.ToolCalls = []llm.ToolCallDelta{{Index: e.Index, Arguments: wd.PartialJSON}}
case "signature_delta":
b.signature += wd.Signature
continue
default:
continue
}
return d, nil
case "message_delta":
var wd wireDelta
json.Unmarshal(e.Delta, &wd)
if wd.StopReason != "" {
s.finish = mapStop(wd.StopReason)
d.FinishReason = s.finish
}
if e.Usage != nil {
if s.usage == nil {
s.usage = &llm.Usage{}
}
s.usage.Completion = e.Usage.OutputTokens
if e.Usage.InputTokens > 0 {
s.usage.Prompt = e.Usage.InputTokens
}
if e.Usage.Details != nil {
s.usage.Reasoning = e.Usage.Details.Thinking
}
u := *s.usage
d.Usage = &u
}
if d.FinishReason == "" && d.Usage == nil {
continue
}
return d, nil
case "message_stop":
s.done = true
return llm.Delta{}, io.EOF
default: // ping, content_block_stop, and anything newer
continue
}
}
}
A replay
Provider against five of the dixie fixtures, as TestShowReplays in internal/llm runs it on every go test and compares with testdata/show.golden; the block below is that file, produced on talos. The test replays each fixture’s recorded response through llm.NewFakeServer and llm.Provider with Retry.Attempts 1, and prints what the client made of it. The fixtures were captured through dixie’s ornith-1.5-9b-uncensored on 2026-10-02 (UTC), and the token counts belong to that capture.
case: plain
status: 200
finish_reason: stop
parts: 1
reasoning bytes: 58
usage: prompt 17, completion 18
case: tool
status: 200
finish_reason: tool_calls
parts: 0
reasoning bytes: 74
tool call: read_file, 21 bytes of arguments
usage: prompt 413, completion 50
case: tool-stream
status: 200
deltas: 37
[DONE] seen: true
finish_reason: tool_calls
parts: 0
reasoning bytes: 105
tool call: read_file, 21 bytes of arguments
usage: prompt 413, completion 57
case: reasoning-stream
status: 200
deltas: 190
[DONE] seen: true
finish_reason: stop
parts: 1
reasoning bytes: 331
usage: prompt 30, completion 191
case: bad-request
status: 400
error: *llm.StatusError status=400 type="invalid_request_error" transient=false retry_after=0s
message: Expected 'messages' to be an array
attempts: 1
tool has no text part: the server’s content was "" with a tool call beside it, so the message has zero parts, and parts: 0 with one tool call is a tool-call-only turn. plain has one text part, the answer; a message with no tool calls always has at least one part, which may be empty. The 37 deltas of tool-stream are the 38 chunks minus the role-only one. Its reasoning is 105 bytes where the non-streaming tool has 74; these are two separate generations. bad-request was attempted once, which the last line shows: a 400 is returned at the first answer.
A few lines of tool-stream.json, quoted from the file, show the shapes the Mechanism described: the first fragment of the call, a later one, the finish chunk, and the usage chunk with its empty choices and the server’s timings.
data: {"choices":[{"finish_reason":null,"index":0,"delta":{"tool_calls":[{"index":0,"id":"6cPr33yr4uqXpwwPDpUuemAw8O0dgoRj","type":"function","function":{"name":"read_file","arguments":"{"}}]}}],"created":1790906405,"id":"chatcmpl-IHCF2C0s3TFWagUoA0zFsIqjJYEUA5AR","model":"ornith-1.5-9b-uncensored","system_fingerprint":"b10964-b29c606","object":"chat.completion.chunk"}
data: {"choices":[{"finish_reason":null,"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"/etc"}}]}}],"created":1790906405,"id":"chatcmpl-IHCF2C0s3TFWagUoA0zFsIqjJYEUA5AR","model":"ornith-1.5-9b-uncensored","system_fingerprint":"b10964-b29c606","object":"chat.completion.chunk"}
data: {"choices":[{"finish_reason":"tool_calls","index":0,"delta":{}}],"created":1790906406,"id":"chatcmpl-IHCF2C0s3TFWagUoA0zFsIqjJYEUA5AR","model":"ornith-1.5-9b-uncensored","system_fingerprint":"b10964-b29c606","object":"chat.completion.chunk"}
data: {"choices":[],"created":1790906406,"id":"chatcmpl-IHCF2C0s3TFWagUoA0zFsIqjJYEUA5AR","model":"ornith-1.5-9b-uncensored","system_fingerprint":"b10964-b29c606","object":"chat.completion.chunk","usage":{"completion_tokens":57,"prompt_tokens":413,"total_tokens":470,"prompt_tokens_details":{"cached_tokens":409}},"timings":{"cache_n":409,"prompt_n":4,"prompt_ms":63.414,"prompt_per_token_ms":15.8535,"prompt_per_second":63.0775538524616,"predicted_n":57,"predicted_ms":1056.354,"predicted_per_token_ms":18.863464285714286,"predicted_per_second":53.01253178385276}}
The Anthropic replays
The adapter against its five document fixtures. These are replays of transcribed documents, not of captured runs. TestShowReplays in internal/llm/anthropic prints what the adapter made of each and compares it with that package’s testdata/show.golden; the block below is that file, produced on talos. parts counts the tool_use placeholder beside the text.
case: doc-stream-text
deltas: 3
ended with: EOF
finish_reason: stop
parts: 1
reasoning bytes: 0
usage: prompt 25, completion 15, reasoning 0
case: doc-stream-tool
deltas: 21
ended with: EOF
finish_reason: tool_calls
parts: 2
reasoning bytes: 0
tool call: toolu_01T1x1fJ34qAmk2tNTrN7Up6 get_weather {"location": "San Francisco, CA"}
usage: prompt 472, completion 89, reasoning 0
case: doc-stream-thinking
deltas: 6
ended with: EOF
finish_reason: stop
parts: 2
reasoning bytes: 174
thinking part: 174 bytes, signature EqQBCgIYAhIM1gbcDa9GJwZA2b3hGgxBdjrkzLoky3dl1pkiMOYds...
case: doc-stream-error
deltas: 0
ended with: llm: error in stream: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
finish_reason:
parts: 0
reasoning bytes: 0
case: doc-message-tool-use
finish_reason: tool_calls
parts: 2
reasoning bytes: 0
tool call: toolu_01A09q90qw90lq917835lq9 get_weather {"location":"San Francisco, CA","unit":"celsius"}
The two tool calls show the difference in Arguments spelling: the streamed one keeps the spacing of the vendor’s example ("location": "San Francisco, CA"), the non-streamed one is compact. The stream’s 21 deltas are the 13 text deltas, the tool_use block’s start, the 6 input_json_deltas and the final message_delta; the 472 input tokens come from message_start and the 89 output tokens from message_delta, which are the page’s numbers. doc-stream-thinking has two parts, the thinking part with its signature and the text, and Reasoning holds the 174 bytes; the page’s example carries no usage at all, so the adapter reports none, and the thinking block is opened with "signature": "" and filled by the signature_delta. doc-stream-error is the page’s error event alone: no delta, and the StreamError carries the event’s body.
Exercises
(a) A 503 arrives with Retry-After: Thu, 01 Oct 2026 12:00:30 GMT. The server’s clock reads 12:00:00, so it meant 30 s; the client’s clock reads 12:00:40. What does the default client do, and how far from the server’s request does it come back?
Answer
The date is 10 s in the client’s past, so ParseRetryAfter returns 0 and the client falls back to jittered backoff: the first wait is uniform on s with expectation 0.25 s, so it returns about 29.75 s earlier than the server asked. If the server still refuses, the second wait is uniform on s (expectation 0.5 s) and the third failure is returned, so the client sends three requests inside about 1.5 s at most, where the server asked for one after 30 s. The attempts bound the cost; a clock ahead by more than the header’s delay turns a polite client into one that retries at its backoff schedule.
(b) With Base 200 ms, Attempts 5 and MaxWait 1 s, give each wait’s ceiling and the expected total wait under full jitter, and the total without jitter.
Answer
There are four waits, with ceilings : 0.2, 0.4, 0.8 and 1.0 s, the fourth capped (1.6 s uncapped). Under full jitter each has expectation , so the expected total is s. Without jitter the waits are the ceilings, s. A script on talos computing both gave 1.2 and 2.4.
(c) Two parallel tool calls stream with no index on their fragments. What does the assembler produce, and why does llama-server’s documentation say parallel calls are off by default?
Answer
One call. The index is the only key and an absent one is 0, so both calls’ fragments land in the same slot, the arguments concatenate, and the later name and id overwrite the earlier. A program on talos that streamed a fragment id c1, name f, arguments {"a":1} and one id c2, name g, arguments {"b":2}, neither with an index, printed 1 call(s) and id=c2 name=g arguments={"a":1}{"b":2}: not valid JSON, and the name of the wrong call. Parallel calls need a template that emits several calls and a parser that numbers them, so llama.cpp’s docs/function-calling.md (line 24) says “Multiple/parallel tool calling is supported on some models but disabled by default, enable it by passing "parallel_tool_calls": true”, and the server README (line 1330) says it is “only supported on some models, verification is based on jinja template” (the server’s code defaults the flag to the template’s capability instead; chapter 25). The 9b’s capture parallel.json sent the flag; the default was not tested.
(d) Write the Anthropic request that gets a JSON object with keys city and millions without response_format.
Answer
A tool whose input_schema is the schema and a tool_choice that names it; the answer is the tool_use.input object. disable_parallel_tool_use inside tool_choice keeps it to one block. The adapter encoded this request on talos; the two fields that matter, printed from the encoded body, were:
tool_choice: {"disable_parallel_tool_use":true,"name":"answer","type":"tool"}
tools: [{"description":"Report the answer.","input_schema":{"type":"object","properties":{"city":{"type":"string"},"millions":{"type":"number"}},"required":["city","millions"],"additionalProperties":false},"name":"answer"}]
The request must also carry messages and max_tokens. One caveat is the vendor’s own: “Not every model and setting supports forced tool use. Where it isn’t supported, tool_choice: {"type": "any"} and tool_choice: {"type": "tool", "name": "..."} fail” (Define tools, fetched 2026-10-01), and the same page says forced use “prefills the assistant message”, so the model will not explain itself first. Where it fails, auto plus an instruction to call the tool is the fallback, and chapter 25’s decoder has to be ready for the case where it does not.
(e) Read-only, on dixie: with a urllib script of your own, GET /v1/models (naming no model) and read status.args of the loaded 9b. Which flags decide how a tool call is rendered and parsed, and where does the template live?
Answer
The flags are --jinja and --chat-template-file, which points at a store path ending -ornith-9b-chat-template.jinja; read on 2026-10-01 from talos, the same entry also carried --reasoning-budget 2048. The template’s source decides the parser: at b29c606, common/chat.cpp lines 1205–1209 select the Qwen3-Coder format when the template source contains <tool_call>, <function= and <parameter=, so the server parses the model’s XML-shaped call into tool_calls and the client sees OpenAI-shaped fields. --reasoning-budget N is, in the README’s words, a “token budget for thinking: -1 for unrestricted, 0 for immediate end, N>0 for token budget”. With --jinja absent, tool use over /v1/messages does not work either (“Tool use requires --jinja flag”), and both fleet hosts have it on.
(f) A streaming request is answered 200 and three deltas arrive. Then the server (a) closes the connection cleanly, with no [DONE], or (b) resets it. What does Next return in each case, what does Response hold, and is anything retried?
Answer
(a) A clean close ends the body, so the event reader reports end of input and Next returns ErrNoDone, not io.EOF. (b) A reset surfaces as the transport’s read error — connection reset by peer for a reset, or unexpected EOF when a chunked body is cut short — which Next returns as it is. In both cases the error is final and sticky, and Response returns the content, reasoning and tool-call fragments of the three deltas together with the same error, so the caller can decide what a partial answer is worth. Nothing is retried, because a 2xx has begun; the lab’s “a stream without [DONE] is ErrNoDone, not io.EOF” and “an error after the first streamed byte is never retried” cases pin the two.
Lab
The mechanics are chapter 22’s. go/labs/ch24/lab.go declares Impl, a constructor taking an llm.Provider configuration (name, base URL, key, HTTP client, retry policy, clock and sleeper) and returning an llm.Client, and checks at compile time that the reference and go/labs/ch24/mine have the same API. Write mine/client.go, the OpenAI-compatible client (request encoding, the stream parser and assembler, and the retry matrix), and run
make lab CH=24 IMPL=mine
make lab CH=24 runs the same tests against the reference. Provided: the canonical types; llm.Fake, a scripted client that pops one step per call and assembles a scripted stream with the same assembler, parsing an HTTP-date Retry-After against its own Clock (listing ch24-fake below); llm.FakeServer, an httptest server with queued answers, a Retry-After header option, a hang and an abort, and llm.SSE, which builds an event stream with CRLF, comment pings, multi-line data or no [DONE] at your choice; the recorded fixtures; and aec-capture, whose redaction is listing ch24-redact below.
// take records the request and consumes the next step: the head of Script
// is popped, so a test may top up or reassign Script between calls, and
// len(Script) is the number of answers still to come.
func (f *Fake) take(req Request) (Step, error) {
f.mu.Lock()
defer f.mu.Unlock()
i := len(f.Calls)
f.Calls = append(f.Calls, req)
if len(f.Script) == 0 {
return Step{}, fmt.Errorf("%w: call %d", ErrScriptExhausted, i+1)
}
s := f.Script[0]
f.Script = f.Script[1:]
if s.Match != nil {
if err := s.Match(req); err != nil {
return Step{}, &MismatchError{Step: i, Err: err}
}
}
return s, nil
}
// now is the Fake's clock, for an HTTP-date Retry-After in a Step.
func (f *Fake) now() time.Time {
if f.Clock != nil {
return f.Clock()
}
return time.Now()
}
// err turns a step's Err into what a Provider would have returned: a
// *StatusError when Status is set, else the error itself.
func (s Step) err(now time.Time) error {
if s.Err == nil {
return nil
}
if s.Status != 0 {
return &StatusError{Status: s.Status, Message: s.Err.Error(),
RetryAfter: ParseRetryAfter(s.RetryAfter, now)}
}
return s.Err
}
// Complete answers from the next step. A Deltas step is assembled exactly as
// a wire stream would be, so one script serves both calls.
func (f *Fake) Complete(ctx context.Context, req Request) (*Response, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
s, err := f.take(req)
if err != nil {
return nil, err
}
if err := s.err(f.now()); err != nil {
return nil, err
}
if s.Response != nil {
r := *s.Response
return &r, nil
}
if s.Deltas != nil {
var a assembler
for _, d := range s.Deltas {
a.add(d)
}
return a.response(), nil
}
return nil, errors.New("llm: fake step has no Response, Deltas or Err")
}
// Stream answers from the next step as a stream of its Deltas; a Response
// step becomes one delta carrying the whole message.
func (f *Fake) Stream(ctx context.Context, req Request) (Stream, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
s, err := f.take(req)
if err != nil {
return nil, err
}
if err := s.err(f.now()); err != nil {
return nil, err
}
switch {
case s.Deltas != nil:
return &fakeStream{deltas: s.Deltas}, nil
case s.Response != nil:
r := s.Response
d := Delta{Reasoning: r.Message.Reasoning, FinishReason: r.FinishReason, Usage: r.Usage}
for _, p := range r.Message.Parts {
if p.Type == "text" {
d.Text += p.Text
}
}
for i, c := range r.Message.ToolCalls {
d.ToolCalls = append(d.ToolCalls, ToolCallDelta{Index: i, ID: c.ID, Name: c.Name, Arguments: c.Arguments})
}
fs := &fakeStream{deltas: []Delta{d}}
fs.asm.id, fs.asm.model = r.ID, r.Model
return fs, nil
}
return nil, errors.New("llm: fake step has no Response, Deltas or Err")
}
// redactHeaders keeps only the allowlisted header fields.
func redactHeaders(h http.Header) map[string]string {
out := map[string]string{}
for _, k := range keptHeaders {
if v := h.Get(k); v != "" {
out[k] = v
}
}
return out
}
// secrets returns every value in the environment that looks like a key:
// any variable whose name ends in _API_KEY or _TOKEN, plus the key the run
// used. Values shorter than eight characters are ignored (they would redact
// ordinary text). The values are compared, never printed.
func secrets(used string) []string {
var out []string
if len(used) >= 8 {
out = append(out, used)
}
for _, kv := range os.Environ() {
name, value, ok := strings.Cut(kv, "=")
if !ok || len(value) < 8 {
continue
}
if strings.HasSuffix(name, "_API_KEY") || strings.HasSuffix(name, "_TOKEN") {
out = append(out, value)
}
}
return out
}
// redactText replaces every known secret value, then every secret-shaped
// token, in s with [REDACTED], through chapter 48's one redactor. Values go
// first: a value that itself holds a token shape (sk-…/tail) is replaced
// whole, where a shape run first would cut it and leave a remainder that
// matches nothing. The shapes are secrets.Patterns, the list internal/eval
// and the daemon redact with, so the three cannot drift.
func redactText(s string, values []string) string {
return sec.Redactor{Values: values}.Redact(s)
}
The tests pin:
- The retry matrix, a case per row and per edge. 503 with
Retry-Afterin seconds and as an HTTP-date, and without it; a header aboveMaxWaitcapped; 502, 504, 408, 429 (with and without the header) and 529 retried; 400, 401, 404, 413, 422 and 500 never; the attempts exhausted, the waits recorded by an injected sleeper that makes every wait its ceiling; a transport error before any response, and a timeout before the first byte, retried; a context cancelled mid-wait or before the request returning at once; an error after the first streamed byte, and a failure reading a 2xx body, never retried; the headers a request carries. - Request encoding (
TestRequestEncoding), through your client against aFakeServer: the chapter’s four-message exchange; one text part as a string and several as the typed array;nullcontent for a message of tool calls alone; the empty schema; tool choice, parallel calls, response format, sampling and stop;Extrapassing through and a collision, five names tried, failing before anything is sent; reasoning sent only underSendReasoning; the thinking, redacted-thinking and tool-use part types of the Anthropic adapter not sent; every cause of an encoding error reported; and a stream asking for usage. Layout is not compared, only the JSON. - Stream fragments. Reasoning and content assembling separately, with the usage-only and role-only chunks; fragments with no index or id; two parallel calls interleaved by index, and six calls in a shuffled order coming out in index order; CRLF, pings and multi-line data; a stream without
[DONE]asErrNoDoneand notio.EOF, with no second POST;event: erroranddata: {error}mid-stream; a chunk that is not JSON; an event over 16 MiB; a 200 that is not an event stream; a 503 before the stream retried;Closecancelling the server’s request. - The fixtures. All 23 replay with their structure intact, and no secret is in any
testdatadirectory undergo/.
Measured on 2026-10-01 with go test -count=1, as make lab runs it: the reference passes in 0.430 to 0.440 s over four runs on talos (under other load) and in 0.435 s and 0.437 s over two on straylight. The starter fails 68 subtests: 23 in the fixtures, 24 in the retry matrix, 12 in the stream cases and 9 in the request encoding, and TestToolCallOrder besides. Sixteen one-line faults were made to the reference on talos, each of which compiles; fifteen were caught, and the sixteenth survives as an equivalent (the table names the test that catches each). The next paragraph explains why the survivor is equivalent.
| Fault | Caught by |
|---|---|
| a 500 made transient | TestRetryMatrix, TestStatusErrorParsing, TestTransientStatuses |
| reasoning written into the text buffer | TestAssembler, TestFixtures, TestStreamFragments |
a missing [DONE] read as io.EOF |
TestStreamFragments |
Retry-After ignored |
TestRetryMatrix, TestStreamFragments |
| the end-of-stream branch taken on every successful read | TestReadersAgree, TestStreamFragments, TestDocFixtures, TestErrorEventWithNonJSONData |
| tool calls in map order | TestToolCallOrder, TestAssembler |
no cap on Retry-After |
TestRetryMatrix |
an Extra key allowed to collide |
TestRequestEncoding |
| encoding errors reported first-only, not joined | TestEncodeJoinsErrors, TestRequestEncoding |
| 504 removed from the transient set | TestRetryMatrix, TestTransientStatuses |
| 408 removed from the transient set | TestRetryMatrix, TestTransientStatuses |
| the shift-overflow guard in the backoff removed | TestBackoffGuardAndDefaults |
| a usage-less delta erasing the assembled usage | TestAssemblerKeepsUsage |
the default MaxWait replaced by a year |
TestBackoffGuardAndDefaults |
| the Anthropic part types sent on the OpenAI wire | TestRequestEncoding, TestOpenAIEncoderSkipsPlaceholder |
Removing the comment-line case from the reader is the one fault that survives, and it is equivalent: a comment line cut at its colon has an empty field name, which the default branch ignores as it does the case. Two further faults, applied by hand on talos, made it re-POST after a stream ended without [DONE] or carried an event: error; the stream cases caught both.
Further reading
- R. Fielding, M. Nottingham and J. Reschke (eds.), RFC 9110, HTTP Semantics, June 2022, §9.2.2 “Idempotent Methods”, §10.2.3 “Retry-After” and §15.6.4 “503 Service Unavailable”.
- M. Nottingham and R. Fielding, RFC 6585, Additional HTTP Status Codes, April 2012, §4 “429 Too Many Requests”.
- WHATWG, HTML Living Standard, §9.2 “Server-sent events”, as chapter 23 cites it.
- Marc Brooker, “Exponential Backoff And Jitter”, AWS Architecture Blog, 2015-03-04: the comparison of full, equal and decorrelated jitter under contention.
- OpenAI, the chat completions types generated from the OpenAPI specification,
openai/openai-pythonat10f88169(chat_completion.py,chat_completion_chunk.py,completion_create_params.py,chat_completion_stream_options_param.py); the specification itself isopenai/openai-openapiatc300cf28, a file too large forsiftto fetch whole, cited for the record. - OpenAI, the Function calling and Structured model outputs guides (fetched 2026-10-01; the
platform.openai.com/docs/guides/addresses redirect there). - Anthropic, the Messages API pages (Create a Message), Streaming messages, Handle tool calls, Define tools, Parallel tool use, Stop reasons and fallback, Thinking, API overview and the Claude Platform release notes (all fetched 2026-10-01).
- llama.cpp at b29c606:
tools/server/README.md(/v1/chat/completions,/v1/messages,reasoning_content),docs/function-calling.mdandcommon/chat.cpp.