17. An inference server

Why this layer exists

Every harness you run reaches its model through one protocol. Hermes, OpenCode and chapter 24’s aec client each hold a base URL and send POST /v1/chat/completions with a JSON body of messages; the answer comes back either as one JSON object or as a stream of server-sent events, one small JSON object per event, ending in data: [DONE]. On the fleet, llama-server is the program on the other end of that URL. This chapter builds one around tinygpt, so that none of the joints between an OpenAI-shaped request and a model’s tokens is a black box.

There are five of them, and each has a failure you have probably seen from the client side. The request’s messages have to become the model’s prompt: the chat template, applied at the server’s boundary, where a mismatch with what the model was trained on makes it answer badly without any error. The model produces tokens, and tokens are bytes, not characters: a server that decodes each token by itself sends a ’ split across two tokens as ��. Stop strings are text, and text does not align with tokens either: a server that checks each token for a stop string misses one that straddles two tokens and sends it to the client. An agent resends its whole conversation on every turn: a server that forgets everything between requests re-reads the whole history each time, and the cost grows with the square of the number of turns. And a client can leave in the middle of a stream: a server that does not notice keeps generating for nobody while the next request waits.

This server is for knowing those joints. It is not the daemon’s brain. From chapter 22 on, that is llama-server, supervised by a Go router the course builds; tinygpt stays a model small enough to read and a fixture for offline tests. Each section below says what llama-server does at the same joint, as of llama.cpp da89bb3 (2026-09-29), and the lab reads one of its streams on the fleet.

Mechanism

The protocol

A chat completion request is a JSON object. The fields this server acts on, and what each does:

  • messages, a list of {role, content} objects with roles system, developer, user, assistant and tool. An assistant message may carry tool_calls instead of content, and a tool message carries the tool_call_id it answers. Content is a string or a list of parts such as {"type": "text", "text": …}.
  • stream (default false), and stream_options.include_usage, which asks for a final chunk with token counts.
  • max_tokens or its newer name max_completion_tokens: the most tokens to generate.
  • temperature and top_p: chapter 12’s sampler settings. seed fixes the draw.
  • stop: a string or up to four strings; generation ends before the first one appears, and it is not returned.
  • tools, a list of {"type": "function", "function": {name, description, parameters}}, and tool_choice: "none", "auto", "required", or {"type": "function", "function": {"name": …}} to demand one tool.
  • logprobs and top_logprobs (0 to 20): report each generated token’s log-probability and the most likely alternatives.
  • response_format: {"type": "json_object"} or {"type": "json_schema", "json_schema": {"schema": …}}, output constrained to JSON. This chapter’s code answers it with 400; chapter 18 supplies the grammar, and python -m tinygpt.server passes it, so the server the lab runs honours the field.

model is ignored: this server has one model, whatever the request names. Routing by model id is chapter 22’s.

A non-streaming response is one chat.completion object: an id, created (Unix seconds), model, a choices list with one entry holding the message and its finish_reason, and usage, the counts prompt_tokens, completion_tokens and total_tokens. finish_reason says why generation ended: "stop" when the model emitted its end marker or a stop string appeared, "length" when max_tokens or the context ran out, "tool_calls" when the reply is a tool call. A streaming response is a sequence of chat.completion.chunk objects whose choices carry a delta instead of a message: the first delta has the role, later ones pieces of content, the last one an empty delta and the finish_reason. With include_usage, one more chunk follows with "choices": [] and the usage. An error is {"error": {"message", "type", "param", "code"}} with an HTTP status. GET /v1/models returns {"object": "list", "data": [{"id": …}]}, which is how a client finds out what it can ask for.

llama-server accepts all of these fields. Its request fields are declared in tools/server/server-schema.cpp and the chat-specific ones parsed by oaicompat_chat_params_parse in tools/server/server-common.cpp; max_tokens and max_completion_tokens are aliases of its own n_predict (server-schema.cpp:44-48), stop as a single string becomes a one-element array (server-common.cpp:1245-1250), top_logprobs defaults to 20 when logprobs is set (:1429-1438), and the developer role is mapped to system (common/chat.cpp:1004-1011). Fields it does not parse itself are copied into its internal parameters (server-common.cpp:1440-1448), so a llama.cpp-specific field such as mirostat or cache_prompt takes effect through the OpenAI endpoint, and anything else is dropped.

Where the two servers differ, each difference is a choice. llama-server clamps top_p into [0,1][0, 1] and temperature only from below, at 0 (server-schema.cpp:93-95, :116-118; the clamp is at :597-598); this server answers 400 and names the field, using OpenAI’s documented ranges, [0,2][0, 2] for temperature and [0,1][0, 1] for top_p, because a client that sent temperature: 3 has a bug it should hear about. llama-server accepts n up to its number of slots and refuses more with a 400 (server-schema.cpp:62-65 and the hard-limit check at :599-603); this server generates one choice and refuses n > 1. llama-server reads tool_choice with a helper that falls back to the default when the value has the wrong type (server-common.h:43-51), so the object form naming a function is served as "auto"; this server honours it, forcing a call (and, from chapter 18, forcing that tool’s schema). llama-server refuses logprobs together with tools and stream (server-common.cpp:1431-1433); this server allows the combination. Image and audio parts are the last difference and have their own section below.

Server-sent events

A streamed response is Content-Type: text/event-stream, the format of the WHATWG HTML Living Standard’s §9.2, Server-sent events. The body is UTF-8 text made of lines. A line field: value sets a field of the event being built; the field that matters here is data, and several data lines in one event are joined with newlines. A blank line ends the event and dispatches it. A line starting with a colon is a comment and is ignored. OpenAI’s convention on top of that is one JSON object per event on a single data: line, which works because JSON serialisation escapes every newline inside strings, and a final event whose data is the literal [DONE]. So the whole of this server’s framing is sse: data:, the compact JSON, and two newlines. llama-server’s format_oai_sse writes the same bytes (server-common.cpp:1644-1650) and ends with data: [DONE]\n\n (server-context.cpp:4436).

Why not a websocket? The traffic runs one way. After the request, the server talks and the client listens, and an event stream is an ordinary HTTP response that happens to arrive slowly: it passes through every proxy, load balancer and curl that handles HTTP, with no upgrade handshake. The cost is that intermediaries may buffer it or time it out while it is silent. §9.2.7 of the standard recommends a comment line every 15 seconds or so for exactly that, and llama-server sends :\n\n when a stream has been silent for its sse_ping_interval (server-context.cpp:4449-4459), which matters while a long prompt is processed and no token has come out yet. This server’s model generates in milliseconds and sends no pings.

How does the client know where the response ends? An HTTP/1.1 response either declares a Content-Length or uses chunked transfer coding, which frames the body in length-prefixed pieces so the connection can carry the next request afterwards. Neither suits a body of unknown length written as it is produced unless the server frames the chunks itself. The standard library’s BaseHTTPRequestHandler speaks HTTP/1.0 by default, and there a response without a length ends when the server closes the connection: RFC 9112 §6.3 still lists this as the last rule for a response’s length, “the number of octets received prior to the server closing the connection”. So this server writes events and closes, and needs no framing of its own. The same section warns that such a response cannot be told apart from one cut short by a network failure. That is what [DONE] is for: it is the server saying the response is complete, in-band. A stream that ends without it did not finish. In the openai Python package (v3.22.1), the stream iterator stops at [DONE] (_streaming.py:70) and also stops, silently, when the connection closes without it, because the for sse in iterator loop (:69) simply runs out and nothing after it checks for [DONE], so a client that needs to know checks that it saw a finish_reason.

Two more rules follow from the fact that the headers go first. The status line and headers are sent before the first event, so everything that can make a request fail must be checked before them: this server validates the request, renders the prompt and checks it against the context before sending a byte, and the handler asks chat_chunks for its first chunk before it sends the status. Anything that fails later can only be reported inside the stream: an event data: {"error": {…}} and no [DONE]. llama-server does the same (server-context.cpp:4470-4474, with the event formatted at :4403), and the openai package turns such an event into an APIError exception (_streaming.py:93-106).

UTF-8, derived

Chapter 7 showed that a token can end in the middle of a character. What a server has to do about it follows from how UTF-8 lays out bits, a layout that can be built up from the constraint that ASCII must stay ASCII.

A code point is an integer from 0 to 0x10FFFF\texttt{0x10FFFF}. Code points 0 to 127 are ASCII and are stored as themselves, one byte whose top bit is 0: 0xxxxxxx, 7 payload bits. Everything else takes several bytes, and every one of those bytes has its top bit set, so no byte of a multi-byte character can be mistaken for ASCII. The bytes of a multi-byte character are one lead byte followed by continuation bytes, and the high bits say which is which. A continuation byte is 10xxxxxx, 6 payload bits. A lead byte starts with as many 1 bits as the character has bytes, then a 0:

bytes layout payload bits code points
1 0xxxxxxx 7 U+0000 to U+007F
2 110xxxxx 10xxxxxx 5 + 6 = 11 U+0080 to U+07FF
3 1110xxxx 10xxxxxx 10xxxxxx 4 + 6 + 6 = 16 U+0800 to U+FFFF
4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 3 + 6 + 6 + 6 = 21 U+10000 to U+10FFFF

Each row’s upper bound is 2bits−12^{\text{bits}} - 1 (27−1=0x7F2^{7} - 1 = \texttt{0x7F}, 211−1=0x7FF2^{11} - 1 = \texttt{0x7FF}, 216−1=0xFFFF2^{16} - 1 = \texttt{0xFFFF}), except the last, where 21 bits could reach 0x1FFFFF\texttt{0x1FFFFF} but RFC 3629 stops at 0x10FFFF\texttt{0x10FFFF}, the last code point UTF-16 can represent. A character uses the shortest row that holds it; a longer encoding of the same code point is malformed. RFC 3629 notes the consequences: the bytes C0 and C1 (which could only start an over-long two-byte encoding) and F5 to FF never appear in well-formed UTF-8.

Read as numbers, the high bits sort every byte into one class: below 0x80 is ASCII, a character by itself; 0x80 to 0xBF is a continuation byte; 0xC0 to 0xDF leads a two-byte character; 0xE0 to 0xEF a three-byte one; 0xF0 to 0xF7 a four-byte one; 0xF8 to 0xFF starts nothing. So a decoder looking at any single byte knows how many bytes its pattern announces. C0, C1 and F5 to F7 announce a length but start nothing well-formed: a decoder waits for the bytes one announces, as for any lead, and they then decode to U+FFFD.

Encode ’, U+2019, by hand. 0x2019\texttt{0x2019} is at least 0x800\texttt{0x800} and at most 0xFFFF\texttt{0xFFFF}, so it takes three bytes and 16 payload bits: 0010 0000 0001 1001. Split them 4, 6, 6: 0010, 000000, 011001. Put each behind its marker: 1110 0010, 10 000000, 10 011001, which is E2 80 99. The model’s tokenizer learns byte strings, not characters, and chapter 7 found E2 80 as a single token in a BPE trained on Persuasion. Sampled one token at a time, ’ can arrive as E2 80 in one step and 99 in the next.

A JSON string holds Unicode characters, not bytes, so a server cannot put E2 80 into a content delta at all: it would have to decode it first, and the only decoding of an incomplete sequence is a replacement character, U+FFFD. Then the 99 that arrives next is a stray continuation byte and becomes a second U+FFFD. The client shows �� where the model wrote ’. The server has to hold bytes back until they form characters.

The hold-back rule. After each token, append its bytes to a buffer. Look back from the end, over at most the last four bytes, for the last byte that is not a continuation byte. If it is a lead byte whose character needs more bytes than there are from it to the end, hold everything from that byte on and decode the rest; otherwise decode everything. When generation ends, decode whatever is still held with replacement: a character the stream ended inside really is malformed. Utf8Decoder implements this.

The held tail is at most three bytes. It is held only when its lead byte needs nn bytes and fewer than nn are present, and n≤4n \le 4, so at most n−1≤3n - 1 \le 3 bytes are held. Looking back four bytes is enough for the same reason: a character that later bytes could still complete has at most four bytes and is missing at least one, so its lead byte is among the last three.

The rule has to be right on malformed input as well, because a model can emit any byte sequence its vocabulary spells: a stray continuation byte, a lead byte followed by ASCII. The property the lab tests is exact: for any byte string and any way of cutting it into pieces, joining what feed returns and then flush gives the same text as decoding the whole string at once with bytes.decode("utf-8", "replace"). The argument uses how that replacement decoder works. The Unicode Standard (version 17.0.0, §3.9.6, U+FFFD Substitution of Maximal Subparts) describes the practice: at a point where no well-formed sequence starts, the decoder replaces the maximal subpart, the longest run that is the beginning of some well-formed sequence (or one byte, if none is), with a single U+FFFD, and continues after it. The standard does not require the practice for conformance; it notes that implementations increasingly follow it as the W3C encoding standard specifies. Python’s replacement decoder behaves this way: b"\xe1\x80\xe2\xf0\x91\x92\xf1\xbf\x41".decode("utf-8", "replace") gives four U+FFFD and A (run on talos), the first two bytes one maximal subpart, then E2, then F0 91 92, then F1 BF. Every byte after the first of a well-formed sequence is a continuation byte, so neither a character nor a maximal subpart ever runs through a byte that is not a continuation byte. feed cuts in one of two places. Either it cuts just before a lead byte, which no character or maximal subpart crosses, so whatever the whole-string decoder did before that byte it does to the prefix alone, and it starts fresh at the lead byte in both cases. Or it cuts at the end of the buffer because the last lead byte’s character already has all its bytes (or there is no lead byte in the last four), and then anything that arrives later starts afresh in both decodings too: a lead byte starts a new sequence, and a continuation byte can only be a stray, since the character before it is complete or already broken. In both cases the decoding of the pieces is the decoding of the whole.

llama-server solves the same problem with validate_utf8 (server-common.cpp:903-929). It scans the last four bytes of the text generated so far, and if it finds a lead byte whose character is cut off, nothing new is sent at that step: the stop-string search and the send are both skipped until a later token completes the character (server-context.cpp:1825-1864). The two rules agree on well-formed UTF-8. They differ on malformed input, which exercise (f) takes apart.

A production BPE often has no split to worry about for common characters: in the fleet capture in the lab, ornith-1.5-9b spells ’s as a single token, id 725, bytes [226,128,153,115]. The lab’s tests use a byte-level tokenizer, with no merges, precisely so that every character is split and the hold-back is exercised.

Stop strings

A stop string is text, and it can end anywhere relative to tokens: ### might arrive as #, ## or as the end of .###. Checking each new token for the stop string misses those that span tokens, and checking the accumulated text after sending each token is too late, because the first # has already gone to the client.

The rule is the same shape as the UTF-8 one. Keep the text not yet sent in a buffer. After each piece of text, if some stop string occurs in the buffer, send everything before its first occurrence and end the stream; the stop string and anything after it are dropped. Otherwise find the longest tail of the buffer that is a proper prefix of some stop string, the part that the next token could complete, hold it, and send the rest. When generation ends without a stop string, send what is held. StopBuffer implements this. Its input is the UTF-8 decoder’s output, so it works on characters, and test_stop_buffer_releases_a_false_alarm checks that a held # that turns out not to begin ### is sent after all.

The held text is at most maxs∣s∣−1\max_s |s| - 1 characters, with ss ranging over the stop strings: it is a proper prefix of some ss, so it is shorter than ∣s∣|s|, and so shorter than the longest. That is also the most a stop string can delay text the client would otherwise see.

Holding the longest such tail is what makes the rule complete. Suppose a stop string ss first completes at some step, in an occurrence that starts at a position jj which an earlier step already sent. Look at the step that sent position jj. Its buffer contained jj, and the occurrence of ss ran past the end of that buffer, since it completes later. So the text from jj to the end of that buffer was a proper prefix of ss and a tail of the buffer; and it was longer than the tail that step held, because it includes jj, which was sent. That contradicts holding the longest such tail. So every occurrence starts inside the held text or later, and it is found in the buffer at the step it completes.

llama-server does the same with bytes: after each token, if the text is not cut off inside a character, it searches for a complete stop string near the end, and otherwise for a partial one with string_find_partial_stop, and sends nothing while a partial match is pending (find_stopping_strings, server-context.cpp:537-566, called at :1835 and :1842).

The figure follows one reply through the path step by step, with stop string ###: each row is one decoding step, and each column a stage, from the sampled token to the event written.

The streaming path of one reply, step by step, from sampled token ids to server-sent events A table with one row per decoding step and one column per stage, left to right: the sampled token, the UTF-8 buffer, the stop buffer with stop string ###, the chunk's content, and the event written. Step 1 samples byte e2: the UTF-8 buffer holds e2, and nothing else happens. Step 2 samples 80: the UTF-8 buffer holds e2 80, since a lead byte 1110xxxx needs 3 bytes. Step 3 samples 99: the right single quotation mark leaves the UTF-8 buffer, passes the stop buffer, and is sent as a chunk and a data event. Step 4 does the same for s. Step 5 samples a hash sign: it leaves the UTF-8 buffer and the stop buffer holds it, because it may begin ###. Step 6 samples another: the stop buffer holds two. Step 7 samples a third: ### is found and cut, nothing of it is sent, the last chunk carries finish reason stop, and after its event the stream ends with data: [DONE]. Step Token UTF-8 buffer Stop buffer Chunk Event 1 2 3 4 5 6 7 e2 80 99 s # # # e2 e2 80 # # # ’ s # # # ’ s "’" "s" data: {…} data: {…} data: {…} data: [DONE] ### found: cut finish: stop — — — — — — — — — — Shaded cells: what a buffer holds back after that step. Text: what leaves it. ’ is e2 80 99, and e2 is a lead byte 1110xxxx: 3 bytes. The stop string is ###.

The cache between requests

An agent loop resends the whole conversation on every turn: the system prompt and tool definitions, the user’s request, every call the model made and every result it got back, and then asks for the next reply. Let the fixed prefix be PP tokens and let each turn add Δ\Delta tokens (the model’s previous reply and the message that answers it), so that turn kk’s prompt is P+kΔP + k\Delta tokens, for k=1,…,Kk = 1, \ldots, K, and let each reply be rr tokens. Count every position the model runs, for the prompt and while generating. Generating rr tokens runs r−1r - 1 positions: each sampled token is run to produce the next, except the last, which is sampled and returned without being run. A server that keeps nothing between requests runs turn kk’s whole prompt and then r−1r - 1 generated positions:

∑k=1K(P+kΔ+r−1)=K(P+r−1)+Δ∑k=1Kk. \sum_{k=1}^{K} (P + k\Delta + r - 1) = K(P + r - 1) + \Delta \sum_{k=1}^{K} k .

The sum of the first KK integers is K(K+1)/2K(K+1)/2: write it forwards and backwards and add term by term, (1+K)+(2+(K−1))+⋯+(K+1)(1 + K) + (2 + (K - 1)) + \cdots + (K + 1), which is KK pairs each summing to K+1K + 1, twice the sum. So the total is

K(P+r−1)+ΔK(K+1)2. K(P + r - 1) + \frac{\Delta K (K+1)}{2} .

A server that keeps the keys and values of the last request runs each position once. Turn kk’s prompt extends turn k−1k - 1’s prompt and reply, and the cache already holds that prompt and every reply token but the last, which was sampled and returned without being run through the model. So turn kk runs that last reply token and the new message, then generates. Over the whole loop each position of the final prompt is run once, and the last reply adds its r−1r - 1: P+KΔ+r−1P + K\Delta + r - 1 in all. For P=2000P = 2000, Δ=150\Delta = 150, K=10K = 10 and r=50r = 50 that is 10×2,049+150×55=28,74010 \times 2{,}049 + 150 \times 55 = 28{,}740 positions without reuse against 2,000+1,500+49=3,5492{,}000 + 1{,}500 + 49 = 3{,}549 with it, 8.10 times fewer (computed by a script). The count without reuse grows as K2K^2, and the count with it as KK. Attention’s cost grows faster still, since each position is compared with every earlier one: exercise (c).

Engine keeps one KVCache and the list of ids whose keys and values it holds. On each request it finds the longest common prefix of that list and the new prompt, truncates the cache to it (chapter 12’s truncate) and runs only the rest. There is one exception: when the new prompt is entirely cached, it keeps one position back and runs the prompt’s last token again, because its logits are what the first new token is sampled from and the cache holds keys and values, not logits. On talos, the trained model’s tool loop shows the effect: the first turn’s prompt is 23 tokens, all run, and the reply is a 32-token call; the second turn’s prompt is 64 tokens (those 55, the tool result and a new generation prompt), of which the engine runs 10: the call’s final <|end|> and the 9 new tokens.

This is llama-server’s cache_prompt, on by default: “the prompt is compared to the previous completion and only the ‘unseen’ suffix is evaluated” (tools/server/README.md at da89bb3), kept per slot; chapter 12 described it as keeping the common prefix, truncating after it and appending the new suffix, which is what Engine does with chapter 12’s truncate. The README adds a caveat that applies here too: the logits of a position computed in a batch of prompt positions need not be bit-identical to those computed one at a time, so a cached and an uncached run can differ in the last bits. The engine’s test compares greedy tokens, which agree. A single cache also means a single conversation: two agents taking turns on this server would each truncate the other’s cache back to their common prefix. Chapter 19 gives each slot its own cache, and chapter 29 turns prefix stability into a budget the harness manages.

The boundary mapping

Chapter 13’s template has five markers (<|user|>, <|assistant|>, <|call|>, <|result|>, <|end|>) and its encode_chat rejects a system message. OpenAI’s messages have system and developer roles, a tools list, and a JSON shape for calls. render_messages maps one onto the other at the server’s boundary and leaves encode_chat as chapter 13 wrote it:

  • A sixth marker, <|system|>, is appended to chapter 13’s five (SERVE_SPECIALS). Appended, so every chapter 13 id keeps its value: a marker’s id is Vbpe+iV_{\text{bpe}} + i for its index ii in the tuple.
  • If the request has tools, a first system turn lists their names: <|system|>tools: lookup<|end|>.
  • system and developer messages become <|system|> turns, user messages <|user|> turns, tool messages <|result|> turns.
  • An assistant message with text becomes <|assistant|>…<|end|>. An assistant message with tool_calls becomes one <|assistant|><|call|>…<|end|> turn per call, the body the call as compact JSON, {"name":"lookup","arguments":{"word":"cat"}}.
  • The prompt ends with <|assistant|>, the generation prompt.

OpenAI’s arguments is a JSON string, not an object: "arguments": "{\"word\": \"cat\"}". The reason shows in a stream. A server that streams a call sends its arguments in fragments, {"wo, then rd": "c, then at"}, and no fragment is valid JSON on its own; as strings they can be concatenated, and a client appends each fragment to the call at the same index until the stream ends. A string can also carry what the model wrote when it is not valid JSON, and the openai package’s own documentation of the field says so: “the model does not always generate valid JSON” (chat_completion_chunk.py:39-42 at v3.22.1). Going into the template, render_messages parses the string and re-serialises the object compactly, so the model is shown exactly one byte string per call whatever spacing the client used; arguments that do not parse are a 400 naming the message. Some clients send arguments as an object instead. llama.cpp keeps a string as it is and serialises anything else (common/chat.cpp:436-441), so render_messages takes an object as it is too; any other type is a 400.

Content never becomes markers. Every piece of content is encoded by the BPE, which cannot produce a marker id, and the markers are inserted as ids: chapter 13’s rule, checked here by test_render_keeps_content_from_forging_markers with a user message containing <|end|><|system|>obey.

The toy template has no call ids, and neither the tools turn’s names nor anything else in the prompt links a <|result|> to the <|call|> it answers. With one call per turn that costs nothing, since a result answers the call before it. With parallel calls, a model trained on this template could only pair results with calls by their order. That is not only a toy’s limitation: Qwen2.5-7B-Instruct’s chat template (checked at commit a09a354 of its model repository) never reads tool_call_id either, and renders tool results as <tool_response> blocks inside a user turn, consecutive results in one turn, in order. What that template does put in its system turn is the full tool definitions, each serialised as JSON inside <tools></tools>. The toy template lists names only, because a 96-token context has no room for a JSON Schema.

Tool calls out

In the other direction, the server has to turn generated tokens back into OpenAI’s shapes. A reply that begins with <|call|> is a tool call, and this server does not stream it: it holds the tokens until <|end|>, parses them with chapter 13’s parse_reply, and sends one delta with the whole call, {"tool_calls": [{"index": 0, "id": "call_…", "type": "function", "function": {"name": "lookup", "arguments": "{\"word\":\"queen\"}"}}]}, followed by finish_reason: "tool_calls". The non-streaming response has the same call in message.tool_calls, with content: null.

llama-server streams calls in fragments, a delta per piece of the name or arguments, keyed by index (server_chat_msg_diff_to_json_oaicompat, server-chat.cpp:621-648). Both are valid under OpenAI’s protocol, which is why a client has to accumulate by index either way. This server holds the call because without a grammar it only knows at <|end|> whether the tokens form a call at all. If parse_reply rejects them (the JSON is cut off, or there is a stray marker inside), the reply is passed on as text, the decoded ordinary tokens, with finish_reason "stop" or "length". What a harness does with such text is chapter 25’s subject; chapter 18 makes it impossible at the source by masking every token that could not continue a valid call.

tool_choice as a mask

tool_choice: "none" means the reply must not be a call; "required" means it must be. Both are enforced on the first generated token. An additive mask m\mathbf{m}, shape (V,), is added to the logits z\mathbf{z}, shape (V,), before sampling: for "none", mt=−∞m_t = -\infty for tt = <|call|> and 0 elsewhere, at every step; for "required", at the first step only, mt=0m_t = 0 for <|call|> and −∞-\infty elsewhere. A named function is enforced like "required" in this chapter; chapter 18 constrains the rest of the call to that function’s schema.

What the mask does to the distribution follows from the softmax. Let AA be the set of allowed tokens, those with mt=0m_t = 0. Since e−∞=0e^{-\infty} = 0, the masked distribution is

q(t)=ezt+mt∑uezu+mu=ezt[t∈A]∑u∈Aezu, q(t) = \frac{e^{z_t + m_t}}{\sum_{u} e^{z_u + m_u}} = \frac{e^{z_t}\,[t \in A]}{\sum_{u \in A} e^{z_u}} ,

and dividing the numerator and denominator by ∑uezu\sum_{u} e^{z_u} turns each eze^{z} into the model’s own probability pp:

q(t)=p(t)[t∈A]∑u∈Ap(u)=p(t∣t∈A). q(t) = \frac{p(t)\,[t \in A]}{\sum_{u \in A} p(u)} = p(t \mid t \in A) .

The masked distribution is the model’s distribution conditioned on the allowed set: the relative probabilities of the allowed tokens are unchanged, and the forbidden ones get none. Temperature and top-p apply to the masked logits afterwards, so they act on the conditioned distribution. This is chapter 12’s kind of filter, and the one-token case of chapter 18’s grammar masks, which are the same addition with a different AA at every step.

Logprobs

With logprobs: true, each generated token comes back with logprob, the natural logarithm of its probability, and top_logprobs, the most probable alternatives. The probability is the model’s own, logsoftmax(z)\log \mathrm{softmax}(\mathbf{z}) of the raw logits, before temperature, filters or mask: chapter 12 found that llama-server reports the same by default. So a masked-out token can appear among the alternatives with its model probability, and a token sampled at high temperature can have a very low logprob.

Each entry also has bytes, the token’s bytes as a list of integers. The field exists because of the previous section: a token can be part of a character, and its token text then cannot represent it. test_logprobs_have_openais_shape generates ’ as three single-byte tokens and checks the three entries’ bytes, [226], [128], [153]. llama-server’s entries also carry the token’s id (server-task.cpp:282-301), and it truncates the token text at an incomplete character with validate_utf8; this server decodes it with replacement, so the text of such a token is U+FFFD and only bytes is exact.

Validation and errors

parse_request turns the body into a ChatRequest or raises OpenAIError with status 400 and a param naming the field. Missing or empty messages, an assistant’s tool_calls that is not a list of objects each holding a function object (whose arguments, if present, is a string or an object), n other than 1, a temperature or top_p out of range, a max_tokens that is not a positive integer, more than four stop strings, top_logprobs outside 0 to 20, an unknown response_format type, a negative seed, a stream_options that is not an object, a tool_choice that needs tools when there are none or names a tool that is not offered: each is an error. Fields the server has no use for (user, metadata, parallel_tool_calls and the rest) are ignored; llama-server drops such fields too, once it has copied the ones it knows. Then chat_chunks renders the prompt, which can fail on the messages themselves (an unknown role, unparseable arguments, a media part), and checks that the prompt fits in the context: a prompt of nn tokens needs n<Cn < C for a context of CC positions. A max_tokens beyond what fits is clamped: positions 00 to C−1C - 1 can hold the prompt and all but the last generated token, which is sampled and never run, so at most C−n+1C - n + 1 tokens can be generated, and a reply that reaches that is cut with finish_reason: "length". At n=Cn = C that bound still allows one token, from position C−1C - 1’s logits; the server refuses the case rather than answer with a reply of one token.

The server is text only. tinygpt has no vision encoder, and a request with an image_url, input_image, input_audio or file part is a 400 whose message names the part and says where such input goes on the fleet: a vision model with its projector (llama-server --mmproj) for images, a transcript from whisper.cpp for audio, both chapter 16’s. llama-server without a projector answers the same request with an error too, “image input is not supported - hint: if this is unexpected, you may need to provide the mmproj” (server-common.cpp:1156, and the audio one at :1169), but it raises it as a std::runtime_error, and its handler wrapper turns every exception other than std::invalid_argument into a 500 (tools/server/server.cpp:60-77). A 500 tells a client the server failed and a retry might work; a 400 tells it the request is wrong and a retry will not.

Concurrency

ThreadingHTTPServer handles each connection in a thread of its own, so the server accepts any number of requests at once. The engine does not: Engine holds one lock from the first token of a generation until it ends or is abandoned, and a second request blocks on it until the first is done. A streamed second request gets its status, headers and first delta (the role) immediately, because chat_chunks yields that before it touches the engine, and then waits. The lab measures that wait (exercise (e)). The queue is unbounded and invisible: blocked threads, each holding a connection. Chapter 19 replaces the lock with slots, several sequences decoded together, and bounds the queue: a request that arrives when it is full is answered at once with 503 and a Retry-After header rather than left waiting. Chapter 23’s Go proxy passes that 503 and its Retry-After through to the client unchanged, and chapter 24’s client is where the retry happens.

A client that leaves in the middle of a stream has to release the engine. The server finds out only when a write fails: BrokenPipeError or ConnectionResetError from the socket. The handler then closes the chunk generator, which closes the engine’s step generator inside it, and closing a generator raises GeneratorExit at the yield where it is suspended; the with self.lock block around that yield exits and releases the lock. test_a_client_that_leaves_mid_stream_frees_the_engine opens a raw socket, starts a 400-token stream, reads 64 bytes and closes; the next request must complete. The handler’s socket timeout of 30 seconds covers the other case, a client that stays connected but stops reading. Propagating a cancel through a proxy to the upstream server is chapter 23’s lab.

Bounded caches

A server runs for weeks and sees text without end: every user message, every tool result, every file an agent reads. Any cache keyed by that text grows without bound unless something bounds it, and a client can grow it on purpose by sending text that never repeats. Chapter 7’s BPE.encode memoises the encoding of each pre-tokenized chunk in a dictionary, and that dictionary is bounded: _cache_limit = 1 << 16 (py/tinygpt/bpe.py:81), and when it is full it is cleared (:97-98), which costs only re-encoding. test_encode_cache_stays_bounded (py/tests/test_bpe.py:24) checks the bound. The server’s other state is bounded by construction: the KV cache by the context, the request body by MAX_BODY, 1 MiB, with 413 for a larger body, 411 for one without a Content-Length and 400 for a Content-Length that is not a non-negative integer.

The model

Chapter 13’s lab trains its assistant in memory and does not save it, and its template has no system turn. The server needs a model trained on exactly the prompts it will render, so tinygpt.train_chat trains one. Its data, serving_conversations, extends chapter 13’s toy task to what an OpenAI client sends, in four kinds taken in turn: a subject question (subject of: the bird bites a king .) answered in text, with the tool offered or not; a word question (what is a queen ?) with the lookup tool, answered by a call; the same followed by the tool’s result and an answer that repeats it; and a word question with no tools, which the model declines, i cannot look that up .. Half the conversations open with a system message drawn from three, which changes nothing about the answer, so the model learns to read past system turns.

Each conversation is rendered by render_messages itself, the function the server calls, so the training prompts and the served prompts cannot disagree about a single token; a template mismatch between training and serving is one of the silent failures this chapter opened with. The labels are chapter 13’s masked cross-entropy: each assistant reply and its <|end|> are targets, everything else is −1-1. The context is 96 positions: the longest rendered conversation, a tool call with its result and answer, is 82 tokens with the tokenizer the model uses (computed by a script), so 96 leaves room for a longer word. The model has 2 layers, 4 heads and width 64, trained for 600 steps with Adam at 3×10−33 \times 10^{-3} on batches of 16, seed 0; on talos it takes about 90 seconds. Like train_gpt, train_chat refuses to write inside the repository: models are outputs, and it saves to /tmp/tinygpt-chat.

Walkthrough

The reference module is py/tinygpt/serve.py; the HTTP server is py/tinygpt/server.py, and the training command py/tinygpt/train_chat.py. The byte buffer first.

class Utf8Decoder:
    """Turn a stream of byte chunks into text without ever splitting a character.

    feed() returns every complete character so far and keeps an incomplete one back; flush() ends
    the stream, and an incomplete character still held then is malformed and becomes U+FFFD. For any
    split of any byte string, the pieces joined equal bytes.decode("utf-8", "replace").
    """

    def __init__(self):
        self.held = b""

    @staticmethod
    def _need(lead):
        """Bytes in the character a lead byte starts: 0xxxxxxx 1, 110xxxxx 2, 1110xxxx 3, 11110xxx 4;
        0 for a continuation byte 10xxxxxx, 1 for bytes no character starts with (decoded as U+FFFD)."""
        if lead < 0x80:
            return 1
        if lead < 0xC0:
            return 0
        if lead < 0xE0:
            return 2
        if lead < 0xF0:
            return 3
        return 4 if lead < 0xF8 else 1

    def feed(self, data):
        buf = self.held + bytes(data)
        cut = len(buf)
        for back in range(1, min(4, len(buf)) + 1):     # the last lead byte, if it is within 4 of the end
            need = self._need(buf[-back])
            if need:
                if need > back:                        # its character is not complete yet: hold it
                    cut = len(buf) - back
                break
        self.held = buf[cut:]
        return buf[:cut].decode("utf-8", errors="replace")

    def flush(self):
        out, self.held = self.held.decode("utf-8", errors="replace"), b""
        return out

_need classifies a byte by its value ranges, which are the high-bit patterns of the table read as numbers: a continuation byte needs 0 (it starts nothing), ASCII 1, a lead byte 2, 3 or 4, and a byte from 0xF8 up, which starts nothing well-formed, 1, so that it is decoded (to U+FFFD) at once rather than held. feed walks back from the end at most four bytes; the first byte that is not a continuation byte decides. If its character needs more bytes than there are from it to the end, the cut moves to just before it. Everything before the cut is decoded with errors="replace", which is the right treatment there: anything malformed before the cut stays malformed whatever comes next. flush decodes what is held, so a stream that ends inside a character ends with one U+FFFD, as test_utf8_decoder_holds_back_only_an_incomplete_character checks with f0 9d.

class StopBuffer:
    """Hold back text that could be the start of a stop string, and cut the stream at one.

    feed(text) returns (text safe to send, whether a stop string was found); the stop string itself
    and anything after it are never sent. flush() releases what is held when generation ends.
    """

    def __init__(self, stops):
        self.stops = [s for s in stops if s]
        self.held = ""

    def feed(self, text):
        buf = self.held + text
        hits = [i for i in (buf.find(s) for s in self.stops) if i >= 0]
        if hits:
            self.held = ""
            return buf[:min(hits)], True
        keep = 0                                         # longest tail of buf that begins some stop string
        for s in self.stops:
            for n in range(min(len(s) - 1, len(buf)), keep, -1):
                if buf.endswith(s[:n]):
                    keep = n
                    break
        self.held = buf[len(buf) - keep:]
        return buf[:len(buf) - keep], False

    def flush(self):
        out, self.held = self.held, ""
        return out

Empty stop strings are dropped, since the empty string occurs everywhere. feed searches the held text plus the new text for every stop string and cuts at the earliest match. Without a match, the inner loop tries, for each stop string, tail lengths from the longest possible down to one more than the best found so far, and keeps the first that matches: the longest tail of the buffer that is a proper prefix of some stop string. It sends the rest. With no stop strings at all, keep stays 0 and text passes straight through.

def stream_generate(model, ids, cache, max_new, rng, stop_ids=(), mask=None, top_logprobs=0, **sampling):
    """Yield a Step per generated token, extending cache as it goes; ids is the whole prompt.

    cache must hold the keys and values of a proper prefix of ids (possibly none): only the rest is
    run through the model. mask(out) -> additive (V,) array or None is consulted before each token,
    with out the ids generated so far. Each logprob is the model's own, log_softmax of the raw
    logits, as llama-server reports by default. Stops after max_new tokens or after a stop id.
    """
    ids = list(ids)
    if not ids or len(cache) >= len(ids):
        raise ValueError(f"cache holds {len(cache)} of {len(ids)} prompt positions; it must hold fewer")
    if len(ids) + max_new > model.cfg.context + 1:
        raise ValueError(f"prompt {len(ids)} + max_new {max_new} exceeds context {model.cfg.context}")
    new, out = ids[len(cache):], []
    for _ in range(max_new):
        logits = forward_cached(model, new, cache)[-1]           # (V,): the next token's logits
        extra = mask(out) if mask is not None else None
        tok = sample_token(logits if extra is None else logits + extra, rng, history=ids + out, **sampling)
        lp = log_softmax(logits)
        top = np.argsort(-lp, kind="stable")[:top_logprobs] if top_logprobs else ()
        out.append(tok)
        yield Step(tok, float(lp[tok]), tuple((int(t), float(lp[t])) for t in top))
        if tok in stop_ids or len(ids) + len(out) > model.cfg.context:
            return
        new = [tok]

stream_generate is chapter 12’s cached generate turned into a generator that reports what it did. The cache must hold a proper prefix of the prompt, possibly empty; the first call to forward_cached runs the rest of the prompt, and each later call runs the one token just sampled. The context check allows len(ids) + max_new to be C+1C + 1, the clamping arithmetic of the Mechanism’s validation section. The mask is added to the logits before sample_token, and history=ids + out gives chapter 12’s repetition penalty the whole sequence. The logprob comes from log_softmax(logits), the raw logits, not the masked ones. np.argsort(-lp, kind="stable") orders the alternatives by probability, ties by id. Generation stops after a stop id (the <|end|> marker, in the server), after max_new tokens, or when the sequence reaches the context. test_stream_generate_equals_chapter_12_generate checks that the tokens equal chapter 12’s generate for the same seed, greedy and sampled; test_stream_generate_reports_the_models_logprobs recomputes every logprob and the top three from an uncached forward pass.

class Engine:
    """A model, its chat tokenizer and a name, serving one request at a time.

    Keeps the KV cache of the last request: a new prompt that extends it (an agent resending its
    conversation with one more turn) runs only the positions after the common prefix, as
    llama-server's cache_prompt does.
    """

    def __init__(self, model, tok, name="tinygpt"):
        self.model, self.tok, self.name = model, tok, name
        self.context = model.cfg.context
        self.lock = threading.Lock()
        self.cache, self.cached = KVCache(model.cfg.n_layers), []   # cached: ids whose K, V the cache holds
        self.prompt_positions = 0                                    # positions run for prompts, for tests

    def stream(self, ids, max_new, rng, stop_ids=(), mask=None, top_logprobs=0, **sampling):
        """An iterator of Steps; the engine is held from the first token until it is exhausted or closed."""
        return self._run(list(ids), max_new, rng, stop_ids, mask, top_logprobs, sampling)

    def _run(self, ids, max_new, rng, stop_ids, mask, top_logprobs, sampling):
        with self.lock:
            n = next((i for i, (a, b) in enumerate(zip(self.cached, ids)) if a != b), min(len(self.cached), len(ids)))
            n = min(n, len(ids) - 1)                   # the last prompt token must run: its logits are needed
            self.cache.truncate(n)
            self.cached = ids[:n]
            self.prompt_positions += len(ids) - n
            out = []
            try:
                for step in stream_generate(self.model, ids, self.cache, max_new, rng, stop_ids, mask,
                                            top_logprobs, **sampling):
                    out.append(step.token)
                    yield step
            finally:
                self.cached = (ids + out)[:len(self.cache)]         # what the cache now holds

stream returns the generator _run without starting it, so the lock is taken on the first next(), not when the request is parsed. _run computes the common prefix of self.cached and the new prompt: the first index where they differ, or the shorter length when one is a prefix of the other. It caps that at one less than the prompt length, truncates the cache, and runs the rest through stream_generate. The finally block runs whether the generator is exhausted, stops at a stop id or is closed by the server, and records what the cache now holds: the prompt and the generated tokens, cut to the cache’s length, which drops the last generated token, the one that was never run. test_engine_reuses_the_cache_of_a_shared_prefix sends a conversation, then the same one a turn longer, checks that three positions ran (the last reply token and two new ones), that the result equals a cold engine’s, and that a prompt diverging after two tokens also matches.

def _text(content, where):
    """A message's content as text: a string, or a list of parts of which only text parts are served."""
    if content is None:
        return ""
    if isinstance(content, str):
        return content
    if not isinstance(content, list):
        raise OpenAIError(400, f"{where}.content must be a string or a list of parts", param=f"{where}.content")
    texts = []
    for part in content:
        kind = part.get("type") if isinstance(part, dict) else None
        if kind == "text":
            texts.append(str(part.get("text", "")))
        elif kind in ("image_url", "input_image", "input_audio", "file"):
            raise OpenAIError(400, f"{where} has a content part of type {kind}; this server serves text only. "
                              "Images need a vision model with its projector (llama-server --mmproj) and audio "
                              "a transcript from whisper.cpp; see chapter 16", param=f"{where}.content")
        else:
            raise OpenAIError(400, f"{where} has an unknown content part {kind!r}", param=f"{where}.content")
    return "".join(texts)


def render_messages(tok, messages, tools=None):
    """OpenAI messages (and tool definitions) -> prompt ids ending with the generation prompt.

    Chapter 13's template plus a <|system|> turn: tool names go in a first system turn, "tools: a, b";
    system (and developer) messages become system turns; an assistant's tool_calls become one
    <|call|> turn per call, with arguments parsed from OpenAI's JSON string to the object the template
    writes (an object, which some clients send, is taken as it is); a tool message becomes a <|result|> turn.
    """
    S = tok.special

    def turn(marker, body):
        return [S[marker]] + body + [S["<|end|>"]]

    ids = []
    if tools:
        ids += turn("<|system|>", tok.encode("tools: " + ", ".join(t["function"]["name"] for t in tools)))
    for i, m in enumerate(messages):
        where, role = f"messages[{i}]", m.get("role")
        if role in ("system", "developer"):
            ids += turn("<|system|>", tok.encode(_text(m.get("content"), where)))
        elif role == "user":
            ids += turn("<|user|>", tok.encode(_text(m.get("content"), where)))
        elif role == "tool":
            ids += turn("<|result|>", tok.encode(_text(m.get("content"), where)))
        elif role == "assistant" and m.get("tool_calls"):
            for call in m["tool_calls"]:
                fn = call["function"]
                args = fn.get("arguments") or "{}"
                if isinstance(args, str):
                    try:
                        args = json.loads(args)
                    except ValueError:
                        raise OpenAIError(400, f"{where}: tool call arguments are not JSON", param=where) from None
                body = json.dumps({"name": fn.get("name"), "arguments": args}, separators=(",", ":"))
                ids += [S["<|assistant|>"]] + turn("<|call|>", tok.encode(body))[:-1] + [S["<|end|>"]]
        elif role == "assistant":
            ids += [S["<|assistant|>"]] + tok.encode(_text(m.get("content"), where)) + [S["<|end|>"]]
        else:
            raise OpenAIError(400, f"{where}.role must be system, developer, user, assistant or tool, "
                              f"not {role!r}", param=f"{where}.role")
    return ids + [S["<|assistant|>"]]

_text accepts a string, None (an assistant message that made a call has content: null), or a list of parts, of which it keeps the text parts in order. Media parts get the error that points to chapter 16; an unknown part type gets a plain one. render_messages builds the template with turn, which brackets a body in a marker and <|end|>. The assistant-call branch builds its turn from turn("<|call|>", …) without its <|end|>, adds one, and puts <|assistant|> in front, so the call reads <|assistant|><|call|>{…}<|end|>, as chapter 13’s template writes it. Missing arguments count as an empty object; a string is parsed, and an object is taken as it is.

def reply_message(tok, ids, call_id):
    """Generated ids -> (OpenAI assistant message, whether it is a tool call).

    A reply chapter 13's parse_reply accepts as a call becomes tool_calls with arguments as a JSON
    string; anything else is returned as content, the text of its ordinary tokens.
    """
    parsed = parse_reply(tok, ids)
    if parsed is not None and "tool_call" in parsed:
        call = parsed["tool_call"]
        fn = {"name": call["name"], "arguments": json.dumps(call["arguments"], separators=(",", ":"))}
        return {"role": "assistant", "content": None,
                "tool_calls": [{"id": call_id, "type": "function", "function": fn}]}, True
    text = tok.bpe.decode([i for i in ids if i not in tok.names])
    return {"role": "assistant", "content": text}, False

reply_message is the inverse at the other end. It hands the ids to chapter 13’s parse_reply, which accepts a call only if it ends in <|end|>, contains no other marker, and is a JSON object with a string name and an object arguments. An accepted call’s arguments are serialised back to a compact JSON string, the shape OpenAI clients expect. Anything else becomes content: the ids that are not markers, decoded. That includes a malformed call, whose JSON fragment is then what the client sees.

def parse_request(body):
    """Validate a /v1/chat/completions body into a ChatRequest; OpenAIError 400 names the bad field.

    Fields this server does not act on (user, metadata, parallel_tool_calls, ...) are ignored, as
    llama-server ignores them; fields it cannot honour (n > 1) are errors.
    """
    if not isinstance(body, dict):
        raise OpenAIError(400, "the request body must be a JSON object")
    messages = body.get("messages")
    if not isinstance(messages, list) or not messages or not all(isinstance(m, dict) for m in messages):
        raise OpenAIError(400, "messages must be a non-empty list of objects", param="messages")
    for i, m in enumerate(messages):
        calls = m.get("tool_calls") if m.get("role") == "assistant" else None
        if calls is not None and not (isinstance(calls, list) and all(
                isinstance(c, dict) and isinstance(c.get("function"), dict)
                and isinstance(c["function"].get("arguments", ""), (str, dict)) for c in calls)):
            raise OpenAIError(400, f"messages[{i}].tool_calls must be a list of {{function: {{name, arguments}}}} "
                              "with arguments a JSON string or an object", param=f"messages[{i}].tool_calls")
    if body.get("n", 1) != 1:
        raise OpenAIError(400, "only n = 1 is supported", param="n")
    max_tokens = body.get("max_completion_tokens", body.get("max_tokens"))
    if max_tokens is not None and (isinstance(max_tokens, bool) or not isinstance(max_tokens, int) or max_tokens < 1):
        raise OpenAIError(400, f"max_tokens must be a positive integer, not {max_tokens!r}", param="max_tokens")
    stop = body.get("stop") or ()
    stop = (stop,) if isinstance(stop, str) else stop
    if not isinstance(stop, (list, tuple)) or not all(isinstance(s, str) for s in stop) or len(stop) > 4:
        raise OpenAIError(400, "stop must be a string or a list of at most 4 strings", param="stop")
    tools = body.get("tools") or None
    if tools is not None and not (isinstance(tools, list) and all(
            isinstance(t, dict) and t.get("type") == "function" and isinstance(t.get("function"), dict)
            and isinstance(t["function"].get("name"), str) for t in tools)):
        raise OpenAIError(400, "tools must be a list of {type: function, function: {name, parameters}}",
                          param="tools")
    choice = body.get("tool_choice", "auto" if tools else "none")
    names = {t["function"]["name"] for t in tools or ()}
    if isinstance(choice, dict):
        name = (choice.get("function") or {}).get("name")
        if choice.get("type") != "function" or name not in names:
            raise OpenAIError(400, f"tool_choice names no tool in tools: {choice!r}", param="tool_choice")
    elif choice not in ("none", "auto", "required") or (choice != "none" and not tools):
        raise OpenAIError(400, f"tool_choice {choice!r} needs to be none, auto or required, with tools for "
                          "the last two", param="tool_choice")
    top_logprobs = body.get("top_logprobs", 0) or 0
    if isinstance(top_logprobs, bool) or not isinstance(top_logprobs, int) or not 0 <= top_logprobs <= 20:
        raise OpenAIError(400, "top_logprobs must be an integer in [0, 20]", param="top_logprobs")
    fmt = body.get("response_format")
    if fmt is not None and (not isinstance(fmt, dict) or fmt.get("type") not in ("text", "json_object", "json_schema")):
        raise OpenAIError(400, "response_format.type must be text, json_object or json_schema",
                          param="response_format")
    seed = body.get("seed")
    if seed is not None and (isinstance(seed, bool) or not isinstance(seed, int) or seed < 0):
        raise OpenAIError(400, "seed must be a non-negative integer", param="seed")
    options = body.get("stream_options")
    if options is not None and not isinstance(options, dict):
        raise OpenAIError(400, "stream_options must be an object", param="stream_options")
    return ChatRequest(
        messages=messages, max_tokens=max_tokens, stop=tuple(stop), tools=tools, tool_choice=choice,
        temperature=_number(body, "temperature", 0.0, 2.0, 1.0), top_p=_number(body, "top_p", 0.0, 1.0, 1.0),
        stream=bool(body.get("stream", False)),
        include_usage=bool((options or {}).get("include_usage", False)),
        logprobs=bool(body.get("logprobs", False)), top_logprobs=top_logprobs,
        response_format=fmt if fmt and fmt.get("type") != "text" else None, seed=seed)

Validation is written out field by field so that each error can name its field. isinstance(x, bool) is checked before int because in Python True is an int, and "max_tokens": true should be an error, not one token. max_completion_tokens takes precedence over max_tokens when both are present. tool_choice defaults to "auto" when tools are offered and "none" otherwise, OpenAI’s defaults. A response_format of type "text" is the same as none, so it is stored as None.

def tool_choice_mask(tok, choice):
    """Chapter 17's one-token masks for tool_choice: none forbids <|call|>; required or a named tool
    forces it as the first token (chapter 18's grammars constrain the rest of the call)."""
    call = tok.special["<|call|>"]

    def mask(out):
        m = np.zeros(tok.vocab_size)
        if choice == "none":
            m[call] = -np.inf
        elif not out:
            m[:] = -np.inf
            m[call] = 0.0
        return m
    return None if choice == "auto" else mask

The mask function receives the tokens generated so far. For "none" it returns the same mask at every step, and for the others it forces <|call|> when nothing has been generated and allows everything after. For "auto" there is no mask at all, so stream_generate skips the addition.

def chat_chunks(engine, req, mask=None):
    """The response as OpenAI chat.completion.chunk dicts, then one usage chunk with no choices.

    Text is sent as it forms, through the UTF-8 and stop buffers; a reply that begins with <|call|>
    is held until it ends and sent as one tool_calls delta. mask(out) -> additive (V,) array or None
    constrains every token (chapter 18); without one, tool_choice gets chapter 17's one-token masks.
    Errors in the request are raised before the first chunk, so a server can still answer 4xx/5xx.
    """
    tok = engine.tok
    S = tok.special
    prompt = render_messages(tok, req.messages, req.tools)
    if len(prompt) >= engine.context:
        raise OpenAIError(400, f"the prompt is {len(prompt)} tokens; the context is {engine.context}",
                          param="messages")
    room = engine.context - len(prompt) + 1                  # the last token generated needs no position
    max_new = min(req.max_tokens or room, room)
    if req.response_format is not None and mask is None:
        raise OpenAIError(400, "response_format needs chapter 18's grammars", param="response_format")
    steps = engine.stream(prompt, max_new, np.random.default_rng(req.seed), stop_ids=(S["<|end|>"],),
                          mask=mask or tool_choice_mask(tok, req.tool_choice),
                          top_logprobs=req.top_logprobs if req.logprobs else 0,
                          temperature=req.temperature, p=req.top_p)
    base = {"id": f"chatcmpl-{next(_ids)}", "object": "chat.completion.chunk", "created": int(time.time()),
            "model": engine.name}

    def chunk(delta, finish=None, entries=None):
        logprobs = {"content": entries} if req.logprobs else None
        return base | {"choices": [{"index": 0, "delta": delta, "logprobs": logprobs, "finish_reason": finish}]}

    yield chunk({"role": "assistant", "content": ""})
    utf8, stops, out, entries, finish, cut = Utf8Decoder(), StopBuffer(req.stop), [], [], "length", False
    try:
        for step in steps:
            out.append(step.token)
            if req.logprobs:
                entries.append(_token_entry(tok, step.token, step.logprob)
                               | {"top_logprobs": [_token_entry(tok, t, lp) for t, lp in step.top]})
            if step.token == S["<|end|>"]:
                finish = "stop"
                break
            if out[0] == S["<|call|>"] or step.token in tok.names:
                continue                                     # a call is sent whole; markers are not text
            text, cut = stops.feed(utf8.feed(tok.bpe.vocab[step.token]))
            if text:
                yield chunk({"content": text}, entries=entries)
                entries = []
            if cut:                                          # a stop string: it and what follows are dropped
                finish = "stop"
                break
    finally:
        getattr(steps, "close", lambda: None)()              # frees the engine if the client went away
    if out and out[0] == S["<|call|>"]:
        message, is_call = reply_message(tok, out, f"call_{base['id'][9:]}")
        if is_call:
            yield chunk({"tool_calls": [dict(c, index=0) for c in message["tool_calls"]]}, entries=entries)
            finish, entries = "tool_calls", []
        else:                                                # a malformed call is passed on as text
            yield chunk({"content": message["content"]}, entries=entries)
            entries = []
    elif not cut:                                            # release what the buffers still hold
        text, cut = stops.feed(utf8.flush())
        text += "" if cut else stops.flush()
        finish = "stop" if cut else finish
        if text:
            yield chunk({"content": text}, entries=entries)
            entries = []
    yield chunk({}, finish, entries=entries)
    yield base | {"choices": [], "usage": {"prompt_tokens": len(prompt), "completion_tokens": len(out),
                                           "total_tokens": len(prompt) + len(out)}}

chat_chunks is the whole response, and both the streaming and the non-streaming paths consume it. Everything that can fail on the request’s content happens before the first yield: rendering, the context check, and the refusal of response_format without chapter 18’s mask. engine.stream only creates the generator, so those checks run before the engine is touched. The first chunk is the role. Then each step’s token goes one of three ways. <|end|> ends the reply with finish_reason: "stop". A token of a reply that began with <|call|>, or any other marker, is only collected. Any other token’s bytes go through the UTF-8 decoder and then the stop buffer, and whatever comes out is sent as a content delta, carrying the logprob entries of all the tokens since the last delta, including tokens that produced no text of their own. The finally closes the step generator whatever happened, which is what frees the engine when the handler closes chat_chunks after a failed write. After the loop, a collected call is parsed and sent as one tool_calls delta, or passed on as text if it does not parse; an ordinary reply that ended without a stop string releases what the buffers hold, the UTF-8 decoder’s tail through the stop buffer, which may still find a stop string in it. The last chunk carries the finish_reason, and the usage chunk follows, with completion_tokens counting every generated token including <|end|>.

aggregate, not listed, folds that stream into a chat.completion: it concatenates the content deltas, collects the tool calls without their index, gathers the logprob entries, and keeps the last finish_reason and the usage. The non-streaming response is aggregate(chat_chunks(…)), so the two modes run one code path and test_stream_and_non_stream_agree checks that they return the same text and usage for the same seed.

The HTTP side is tinygpt.server.

class _Handler(http.server.BaseHTTPRequestHandler):
    timeout = 30                   # seconds a socket read or write may block before the connection drops

    def log_message(self, format, *args):
        pass                       # quiet: tests and labs print their own measurements

    def _json(self, status, obj, headers=None):
        data = json.dumps(obj).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        for k, v in (headers or {}).items():
            self.send_header(k, str(v))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        engine = self.server.engine
        if self.path == "/v1/models":
            self._json(200, {"object": "list", "data": [
                {"id": engine.name, "object": "model", "created": 0, "owned_by": "tinygpt"}]})
        elif self.path == "/health":
            self._json(200, {"status": "ok"})
        else:
            self._json(404, {"error": {"message": f"no route {self.path}", "type": "not_found_error"}})

    def do_POST(self):
        api = self.server.api
        if self.path != "/v1/chat/completions":
            return self._json(404, {"error": {"message": f"no route {self.path}", "type": "not_found_error"}})
        try:
            length = self.headers.get("Content-Length")
            if length is None:
                raise api.OpenAIError(411, "a body with a Content-Length up to 1 MiB is required")
            try:
                n = int(length)
            except ValueError:
                n = -1
            if n < 0:
                raise api.OpenAIError(400, f"Content-Length must be a non-negative integer, not {length!r}")
            if n > MAX_BODY:
                raise api.OpenAIError(413, "a body with a Content-Length up to 1 MiB is required")
            try:
                body = json.loads(self.rfile.read(n))
            except (ValueError, RecursionError):  # not JSON, or nested too deeply for the parser
                raise api.OpenAIError(400, "the body is not JSON, or is nested too deeply") from None
            req = api.parse_request(body)
            mask = self.server.constrain(self.server.engine, req) if self.server.constrain else None
            chunks = api.chat_chunks(self.server.engine, req, mask)
            first = next(chunks)                 # request errors surface here, before any header is sent
            reply = None if req.stream else api.aggregate([first, *chunks])
        except api.OpenAIError as e:
            return self._json(e.status, e.body(), e.headers)
        except Exception as e:                   # e.g. the sampler found no token left (chapter 18): still
            return self._json(500, {"error": {   # before the first byte, so a 500, never a dropped connection
                "message": f"{type(e).__name__}: {e}", "type": "server_error", "param": None, "code": None}})
        if req.stream:
            return self._stream(req, first, chunks)
        self._json(200, reply)

    def _stream(self, req, first, chunks):
        api = self.server.api
        self.send_response(200)
        self.send_header("Content-Type", "text/event-stream")
        self.send_header("Cache-Control", "no-cache")
        self.end_headers()                       # HTTP/1.0: the stream ends when the connection closes
        try:
            self.wfile.write(api.sse(first))
            try:
                for c in chunks:
                    if c["choices"] or req.include_usage:
                        self.wfile.write(api.sse(c))
                        self.wfile.flush()
            except (api.OpenAIError, ValueError) as e:   # too late for a status code: an error event, no [DONE]
                self.wfile.write(api.sse({"error": {"message": str(e), "type": "server_error"}}))
                return
            self.wfile.write(b"data: [DONE]\n\n")
        except (BrokenPipeError, ConnectionResetError, TimeoutError):
            pass                                 # the client went away
        finally:
            chunks.close()                       # stops generation and frees the engine

do_POST reads exactly Content-Length bytes, refusing a missing length (411), one that is not a non-negative integer (400) or one over 1 MiB (413) before reading anything; test_bad_content_length_is_an_openai_error sends each over a raw socket. The api it calls is a module, tinygpt.serve by default, which is how the lab’s HTTP tests run the server over the reader’s starter instead. next(chunks) is the line that makes request errors 4xx: it runs chat_chunks up to its first yield, and any OpenAIError it raises becomes a JSON error response before a status line has gone out. A non-streaming request folds the rest of the stream inside the same try. A body nested too deeply for json.loads raises RecursionError, not ValueError, and is caught beside it as a 400. Any other exception up to this point, such as the ValueError from the sampler in chapter 18’s case of a mask that leaves no token, is a 500 with type: "server_error": before the first byte there is still a status to send, so a client gets an error object, never a dropped connection. _stream writes text/event-stream headers with no length, which under HTTP/1.0 means the body ends when the connection closes, then writes each chunk as an event and flushes it, so each reaches the client as it is produced. The usage chunk, whose choices is empty, is written only if the client asked for it. An error after the headers becomes an error event and the stream ends without [DONE]. A failed write means the client left, and the finally closes the generator.

make_server wraps this in a ThreadingHTTPServer subclass with daemon_threads, so a handler thread stuck on a slow client never blocks shutdown(). load_engine rebuilds the tokenizer from the saved BPE and SERVE_SPECIALS, loads the weights with chapter 11’s load, and returns an Engine named tinygpt-chat; test_load_engine_serves_the_saved_model checks that the loaded engine generates what the model it saved generates.

The training data comes from tinygpt.train_chat.

def serving_conversations(n, rng):
    """n (messages, tools) pairs in OpenAI's shapes, four kinds in turn: a subject question answered
    in text (tools offered or not); a word question with the lookup tool, answered by a call; the
    same followed by the tool's result and an answer that repeats it; and a word question with no
    tools, which the model declines. Half carry a system message, which changes nothing."""
    out = []
    for i in range(n):
        subj, obj, kind = str(rng.choice(NOUNS)), str(rng.choice(NOUNS)), i % 4
        tools = [LOOKUP] if kind in (1, 2) or (kind == 0 and rng.random() < 0.5) else None
        msgs = [{"role": "system", "content": str(rng.choice(SYSTEMS))}] if rng.random() < 0.5 else []
        if kind == 0:
            msgs += [{"role": "user", "content": f"subject of: the {subj} {VERBS[subj]} a {obj} ."},
                     {"role": "assistant", "content": subj}]
        elif kind == 3:
            msgs += [{"role": "user", "content": f"what is a {subj} ?"},
                     {"role": "assistant", "content": "i cannot look that up ."}]
        else:
            call = {"id": f"call_{i}", "type": "function",
                    "function": {"name": "lookup", "arguments": json.dumps({"word": subj})}}
            msgs += [{"role": "user", "content": f"what is a {subj} ?"},
                     {"role": "assistant", "content": None, "tool_calls": [call]}]
            if kind == 2:
                answer = f"a {subj} is {MEANINGS[subj]} ."
                msgs += [{"role": "tool", "tool_call_id": f"call_{i}", "content": answer},
                         {"role": "assistant", "content": answer}]
        out.append((msgs, tools))
    return out

The conversation kind is i % 4, so every four consecutive conversations hold one of each, which test_conversations_are_seeded_and_cover_four_kinds checks. Every choice is drawn from rng, so a seed fixes the data. The call’s arguments are written with json.dumps and its default spacing, {"word": "queen"}; the template re-serialises them compactly, so the model never sees the spacing.

def training_example(tok, messages, tools):
    """(ids, labels) for one conversation, rendered by the server's own render_messages, so the model
    is trained on exactly the prompts it will be served. Labels cover each assistant reply and its
    <|end|>; everything else is -1."""
    ids = render_messages(tok, messages, tools)[:-1]      # drop the trailing generation prompt
    labels = [-1] * len(ids)
    for i, m in enumerate(messages):
        if m["role"] == "assistant":
            start = len(render_messages(tok, messages[:i], tools))      # just after <|assistant|>
            stop = len(render_messages(tok, messages[:i + 1], tools)) - 1
            labels[start:stop] = ids[start:stop]
    return ids, labels

The labelled spans are found by rendering prefixes of the conversation: rendering the messages before an assistant message ends with the generation prompt, so its length is where the reply starts, and rendering through that message, minus the next generation prompt, is where the reply’s <|end|> ends. For a call, the reply span starts at <|call|>. The rendered conversation drops its own final generation prompt, since no reply follows it. test_training_examples_label_only_the_replies checks, over 40 conversations, that the labelled tokens contain one <|end|> per assistant message and none of the markers the model is never asked to produce. train_chat then trains exactly as chapter 13’s supervised fine-tuning does, with chapter 13’s collate padding each batch.

Exercises

(a) Encode ’ (U+2019) and 𝄞 (U+1D11E, the treble clef) in UTF-8 by hand. If each arrives one byte per token, what does Utf8Decoder hold after each token?

Answer

’: 0x2019\texttt{0x2019} is between 0x800\texttt{0x800} and 0xFFFF\texttt{0xFFFF}, so three bytes and 16 payload bits, 0010 0000 0001 1001. Split 4, 6, 6 and prefix: 1110 0010, 10 000000, 10 011001, that is E2 80 99. Fed one byte at a time, the decoder holds E2 (a three-byte lead, one byte present), then E2 80 (two present), and on 99 returns ’ and holds nothing.

𝄞: 0x1D11E\texttt{0x1D11E} is above 0xFFFF\texttt{0xFFFF}, so four bytes and 21 payload bits. 0x1D11E\texttt{0x1D11E} is 1 1101 0001 0001 1110, 17 significant bits; padded to 21, 000 011101 000100 011110. With markers: 11110 000, 10 011101, 10 000100, 10 011110, that is F0 9D 84 9E. The decoder holds F0, then F0 9D, then F0 9D 84, and on 9E returns the character. Three bytes held is the most it ever holds.

(b) The Mechanism proves both hold-back rules sufficient. Show that neither can be made cheaper in the obvious way. (i) A decoder that holds back only when the last byte is a lead byte of an incomplete character, instead of looking back past continuation bytes. (ii) A stop buffer that holds the shortest tail that is a proper prefix of a stop string, instead of the longest. For each, give an input on which it sends the client something the full rule does not.

Answer

(i) Feed E2 80 as one token, then 99. After the first token the last byte, 80, is a continuation byte, so the shortened rule holds nothing and decodes E2 80 at once, to U+FFFD; 99 then arrives alone and is a second U+FFFD. The client gets ��. The full rule looks back past 80 to the lead byte E2, sees a three-byte character with two bytes present, holds both, and sends ’ on the next token. A token boundary after a lead byte’s first continuation byte is exactly the case chapter 7 found in a real vocabulary (E2 80 is one token of its Persuasion BPE).

(ii) Stop string aab, text fed as xaa then b. After xaa the tails that are proper prefixes of aab are a and aa. The shortened rule holds a and sends xa; the next buffer is ab, which does not contain aab, so it sends ab as well. The client receives the whole stop string and generation does not stop. The full rule holds aa, sends x, finds aab in the next buffer and stops, sending nothing more. A script running both on talos:

StopBuffer ('x', False) ('', True)
Shortest ('xa', False) ('ab', False)

This is where the completeness argument uses “longest”: a stop string can begin with a repeated prefix, so a short tail that matches the start of s is not the only candidate for where an occurrence starts.

(c) Compute, with a script, the positions an agent loop runs through the model with and without the prefix cache, for P=2000P = 2000, Δ=150\Delta = 150, K=10K = 10 and replies of r=50r = 50 tokens. Then count attention’s work: the number of query-key pairs, where the query at position ii is compared with the i+1i + 1 keys at positions 00 to ii.

Answer

A sequence of nn positions processed from scratch compares ∑i=0n−1(i+1)=n(n+1)/2\sum_{i=0}^{n-1} (i + 1) = n(n+1)/2 pairs, and a generated position compares with every key before it in the same way, so a turn that runs its prompt and then r−1r - 1 generated positions costs the pairs of n=P+kΔ+r−1n = P + k\Delta + r - 1 positions. Without the cache the loop costs ∑k=1Knk(nk+1)/2\sum_{k=1}^{K} n_k(n_k + 1)/2 with nk=P+kΔ+r−1n_k = P + k\Delta + r - 1. With it, each position is run once and still compares with every earlier key, which is in the cache, so the loop costs the pairs of the last turn’s positions alone, nK(nK+1)/2n_K(n_K + 1)/2.

P, D, K, r = 2000, 150, 10, 50
L = [P + k * D + r - 1 for k in range(1, K + 1)]      # positions turn k runs without reuse: prompt, then r - 1 decoded
without, reuse = sum(L), P + K * D + r - 1
print("positions without reuse", without, "=", K * P + D * K * (K + 1) // 2 + K * (r - 1), "with reuse", reuse,
      "ratio", round(without / reuse, 2))
tri = lambda n: n * (n + 1) // 2
print("attention pairs without", sum(tri(n) for n in L), "with", tri(reuse), "ratio",
      round(sum(tri(n) for n in L) / tri(reuse), 2))
positions without reuse 28740 = 28740 with reuse 3549 ratio 8.1
attention pairs without 42241875 with 6299475 ratio 6.71

The positions saved, a factor of 8.10, are the work of the weight matrices, which is proportional to the positions run. Attention saves a factor of 6.71, less, because the cache does not remove the comparisons of a new position with the old ones: the late turns’ positions are the expensive ones under both schemes. Both totals without the cache grow faster in KK than with it: the positions as K2K^2 against KK, and the pairs as K3K^3 (a sum of squares) against K2K^2.

(d) Show a stream of tool_calls deltas whose arguments fragments are valid only as concatenated text, and say what a client must do with them. Why would an object instead of a string not work?

Answer

Three deltas for one call, as a server that streams arguments sends them:

{"tool_calls": [{"index": 0, "id": "call_1", "type": "function", "function": {"name": "lookup", "arguments": ""}}]}
{"tool_calls": [{"index": 0, "function": {"arguments": "{\"wo"}}]}
{"tool_calls": [{"index": 0, "function": {"arguments": "rd\": \"queen\"}"}}]}

Neither {"wo nor rd": "queen"} parses as JSON. The client keeps, per index, the id, the name and a growing string; it appends each arguments fragment to the string at that index, and only when the stream ends (finish_reason: "tool_calls") parses the string, and handles a parse failure as a malformed call. An object could only be sent once it was complete, or as a series of partial objects with some merge rule that JSON does not define; a string is concatenated. The string also carries a model’s output that is not valid JSON at all, unchanged, so the client, not the server, decides what to do with it. Several calls in one reply are told apart by index, which is why every delta carries it.

(e) With the server running the chapter’s model, measure time to the first content delta and to the end, streamed and not streamed, over 20 requests; explain the numbers. Then send two streamed requests at once and explain the second one’s times.

Answer

A script, run with the server from the lab on port 8017, using the second turn of the tool loop (the reply is a queen is a ruler ., 7 tokens with <|end|>):

"""Latency of the chapter 17 server on 127.0.0.1:8017: 20 requests streamed, 20 not, then two at once."""
import json
import statistics
import threading
import time
import urllib.request

LOOKUP = {"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}
MESSAGES = [{"role": "system", "content": "be brief ."}, {"role": "user", "content": "what is a queen ?"},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "call_1", "type": "function",
             "function": {"name": "lookup", "arguments": "{\"word\":\"queen\"}"}}]},
            {"role": "tool", "tool_call_id": "call_1", "content": "a queen is a ruler ."}]


def request(stream):
    """(seconds to the first content delta, seconds to the end of the response)."""
    body = {"model": "tinygpt-chat", "messages": MESSAGES, "tools": [LOOKUP], "temperature": 0, "stream": stream}
    req = urllib.request.Request("http://127.0.0.1:8017/v1/chat/completions", json.dumps(body).encode(),
                                 {"Content-Type": "application/json"})
    t0, first = time.perf_counter(), None
    with urllib.request.urlopen(req, timeout=20) as r:
        for line in r:
            if first is None and b'"content":"' in line and b'"content":""' not in line:
                first = time.perf_counter() - t0
    end = time.perf_counter() - t0
    return first if stream else end, end


def ms(xs):
    return f"median {1000 * statistics.median(xs):.1f} ms, max {1000 * max(xs):.1f} ms"


for _ in range(3):                       # warm up: the engine's cache now holds this prompt
    request(True)
s = [request(True) for _ in range(20)]
n = [request(False) for _ in range(20)]
print("streamed:     first delta", ms([a for a, _ in s]), "| end", ms([b for _, b in s]))
print("not streamed: end", ms([b for _, b in n]))
for _ in range(5):                       # two streamed requests at once, five times
    out = []
    ts = [threading.Thread(target=lambda: out.append(request(True))) for _ in range(2)]
    for t in ts:
        t.start()
    for t in ts:
        t.join()
    print("two at once (first delta, end):",
          "; ".join(f"{1000 * a:.1f} ms, {1000 * b:.1f} ms" for a, b in sorted(out)))

On talos:

streamed:     first delta median 1.4 ms, max 2.3 ms | end median 4.6 ms, max 6.1 ms
not streamed: end median 3.5 ms, max 4.5 ms
two at once (first delta, end): 1.1 ms, 3.2 ms; 3.2 ms, 4.6 ms
two at once (first delta, end): 1.9 ms, 7.0 ms; 7.1 ms, 8.9 ms
two at once (first delta, end): 1.4 ms, 3.4 ms; 3.2 ms, 4.6 ms
two at once (first delta, end): 1.7 ms, 5.9 ms; 6.3 ms, 7.1 ms
two at once (first delta, end): 2.0 ms, 6.1 ms; 6.2 ms, 8.7 ms

Every request sends the same prompt, so after the warm-up the engine’s cache holds all of it, and each request runs one prompt position (the last one, rerun for its logits) and then one position per generated token. The first content delta needs the connection, the parse, and one forward pass over that last prompt position, whose logits give the first token: about 1.4 ms. The rest of the reply is six more steps plus a write and a flush per event, so the streamed response ends about 3 ms later. The non-streamed response does the same generation and writes one body, and ends a little sooner than the stream; for this model the difference is the per-event writes, and for a large model, whose steps take tens of milliseconds, the gap between first delta and end is the generation itself, which is what streaming hides from a user.

Two at once: the first request’s times are about a single request’s. The second one’s first content delta arrives within 0.4 ms of the first request’s end in all five pairs, because it waits on the engine’s lock for the whole of the first generation (its headers and role delta went out at once, which the script does not time). It can even come slightly before the first request’s end, as in the third pair, because the lock is released when the first generation stops, before that response’s last events have been written and read. Its end follows its first delta by 0.8 to 2.5 ms, somewhat less than the 3.2 ms from first delta to end of a single streamed request in the first line; at this scale the client threads and scheduling move each figure by a millisecond, so the pairs show the ordering, not a generation time. On a busier server that wait is the whole queue: each request waits for everything ahead of it, which is what chapter 19’s slots and bounded queue change.

(f) Read validate_utf8 at da89bb3 (tools/server/server-common.cpp:903-929). Give a byte string on which it and Utf8Decoder hold back different amounts, or show there is none.

Answer

validate_utf8 looks at the last byte, then the one before, up to four, and returns (holding from there) at the first lead byte whose character needs more bytes than remain; it does not stop at a byte that is complete. Utf8Decoder stops at the first byte, from the end, that is not a continuation byte, and holds only if that byte’s character is incomplete. They differ when the last non-continuation byte is complete (for instance ASCII) but an earlier lead byte within four bytes is cut short by it: E2 61, a three-byte lead followed by a. validate_utf8 finds 61 complete, moves on, finds E2 needing three bytes with two present, and holds both bytes; Utf8Decoder stops at 61, holds nothing, and returns U+FFFD followed by a. A transcription of validate_utf8 in Python, compared with the decoder over all strings of up to four bytes from a small alphabet on talos, finds E2 61 and F0 61 as the shortest differences; F0 C3 A9 (a four-byte lead, then é) is another, with three bytes held against none.

On well-formed UTF-8 they agree. There, every byte after a lead byte and before the next non-continuation byte is one of that lead’s continuation bytes, so if some lead byte within the last four has fewer bytes after it than it needs, no later non-continuation byte exists, and it is also the last non-continuation byte, which is where Utf8Decoder looks. The difference costs llama-server only latency: on ill-formed output it keeps the text back until more bytes arrive and the lead byte falls outside the last four.

Lab

Implement the stubs in py/labs/ch17/starter.py: the two buffers (Utf8Decoder, StopBuffer), the token stream and the engine (stream_generate, Engine), the mapping in both directions (render_messages, reply_message), validation (parse_request), the masks (tool_choice_mask) and the chunk stream (chat_chunks). OpenAIError, Step, ChatRequest, aggregate and sse are provided. Run

make lab CH=17 IMPL=mine

until it passes. The HTTP tests start tinygpt.server with your module as its api, so they exercise your code through real sockets; each server binds 127.0.0.1 on a free port and is shut down after its test. The tests pin the UTF-8 decoder against bytes.decode on 2,000 random byte strings cut at random places; the stop buffer across chunks and on false alarms; the token stream against chapter 12’s generate, its logprobs against an uncached forward pass, its context limit and masks; prefix reuse and release of the engine; the template mapping, marker forging and the text-only refusal; the tool-call and logprob shapes; each validation error by its field; the SSE framing with a character split across tokens; agreement of streamed and non-streamed responses; tool_choice over HTTP; stop strings; error objects; and a client that disconnects mid-stream. The acceptance test, test_a_tool_loop_against_the_trained_model, trains a small chat model for 150 steps and then acts as a client written only against OpenAI’s API: it asks what is a queen ? with the lookup tool, gets a call with arguments {"word": "queen"}, sends back the result a queen is a ruler ., and must receive exactly that as the streamed answer; without tools, the same question must be declined.

Then train the full model and serve it. From py/:

OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python -m tinygpt.train_chat /tmp/tinygpt-chat

On talos:

step  100  loss 0.086  17s
step  200  loss 0.009  32s
step  300  loss 0.002  46s
step  400  loss 0.002  61s
step  500  loss 0.001  74s
step  600  loss 0.001  91s
saved /tmp/tinygpt-chat: vocab 390, 155,776 parameters

The vocabulary is the BPE’s 384 ids and six markers. Start the server in one terminal:

PYTHONPATH=. uv run python -m tinygpt.server /tmp/tinygpt-chat

It prints serving /tmp/tinygpt-chat at http://127.0.0.1:8017/v1. In another, talk to it with the unmodified openai package. Save as /tmp/openai_lab.py:

"""An unmodified OpenAI client against the tinygpt server on port 8017.

    uv run --no-project --with openai python /tmp/openai_lab.py
"""
from openai import OpenAI

LOOKUP = {"type": "function", "function": {
    "name": "lookup", "description": "What a word means.",
    "parameters": {"type": "object", "properties": {"word": {"type": "string"}}, "required": ["word"]}}}

client = OpenAI(base_url="http://127.0.0.1:8017/v1", api_key="unused")
print("models:", [m.id for m in client.models.list()])

messages = [{"role": "system", "content": "be brief ."}, {"role": "user", "content": "what is a queen ?"}]
reply = client.chat.completions.create(model="tinygpt-chat", messages=messages, tools=[LOOKUP], temperature=0)
choice = reply.choices[0]
call = choice.message.tool_calls[0]
print("finish:", choice.finish_reason, "| call:", call.id, call.function.name, call.function.arguments)

messages += [choice.message.model_dump(exclude_none=True),
             {"role": "tool", "tool_call_id": call.id, "content": "a queen is a ruler ."}]
stream = client.chat.completions.create(model="tinygpt-chat", messages=messages, tools=[LOOKUP], temperature=0,
                                        stream=True, stream_options={"include_usage": True})
for chunk in stream:
    if chunk.choices:
        print("delta:", repr(chunk.choices[0].delta.content), chunk.choices[0].finish_reason)
    if chunk.usage:
        print("usage:", chunk.usage.prompt_tokens, "+", chunk.usage.completion_tokens)

try:
    client.chat.completions.create(model="tinygpt-chat", messages=[{"role": "user", "content": [
        {"type": "text", "text": "what is this ?"},
        {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}}]}])
except Exception as e:  # the openai package raises BadRequestError for a 400
    print(type(e).__name__, e.status_code, e.body["message"])

and run uv run --no-project --with openai python /tmp/openai_lab.py. --no-project with --with openai builds a throwaway environment for the one run, so py/pyproject.toml and uv.lock are untouched and the course’s dependencies stay numpy and pytest. On talos, with openai 3.22.1:

models: ['tinygpt-chat']
finish: tool_calls | call: call_1 lookup {"word":"queen"}
delta: '' None
delta: 'a' None
delta: ' queen' None
delta: ' is' None
delta: ' a' None
delta: ' ruler' None
delta: ' .' None
delta: None stop
usage: 64 + 7
BadRequestError 400 messages[0] has a content part of type image_url; this server serves text only. Images need a vision model with its projector (llama-server --mmproj) and audio a transcript from whisper.cpp; see chapter 16

The client listed the model, sent a request with a tool, got a call back in OpenAI’s shape, appended the call and its result to the conversation as any agent loop does, and streamed the answer, one token per delta: the empty role delta, six content deltas, the finish, and the usage chunk (64 prompt tokens, 7 generated including <|end|>). The image request came back as the openai package’s BadRequestError, with the server’s message intact. The call id is call_1 because the server numbers its responses from 1 since it started.

Optionally, point a harness at it: any harness that accepts a custom OpenAI-compatible provider takes the base URL http://127.0.0.1:8017/v1, any API key, and the model tinygpt-chat. The model only knows its four kinds of conversation, and a real harness’s system prompt and tool list will not fit in 96 tokens, so what this shows is that the requests arrive and where they fail: a 400 naming the prompt’s length.

Now the same joint on the fleet, read-only. First look at this server’s raw events. Save as /tmp/local_stream.py:

"""The raw event stream of the chapter 17 server: the second turn of the tool loop, three tokens, logprobs."""
import json
import urllib.request

messages = [{"role": "system", "content": "be brief ."}, {"role": "user", "content": "what is a queen ?"},
            {"role": "assistant", "content": None, "tool_calls": [{"id": "call_1", "type": "function",
             "function": {"name": "lookup", "arguments": "{\"word\":\"queen\"}"}}]},
            {"role": "tool", "tool_call_id": "call_1", "content": "a queen is a ruler ."}]
body = {"model": "tinygpt-chat", "messages": messages, "stream": True, "max_tokens": 3, "temperature": 0,
        "logprobs": True, "top_logprobs": 2,
        "tools": [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}]}
req = urllib.request.Request("http://127.0.0.1:8017/v1/chat/completions", json.dumps(body).encode(),
                             {"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=20) as r:
    print(r.status, r.headers["Content-Type"])
    for line in r:
        if line.strip():
            print(line.decode().rstrip())

python3 /tmp/local_stream.py, on talos:

200 text/event-stream
data: {"id":"chatcmpl-192","object":"chat.completion.chunk","created":1790751378,"model":"tinygpt-chat","choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":{"content":null},"finish_reason":null}]}
data: {"id":"chatcmpl-192","object":"chat.completion.chunk","created":1790751378,"model":"tinygpt-chat","choices":[{"index":0,"delta":{"content":"a"},"logprobs":{"content":[{"token":"a","logprob":-0.0006775910374046157,"bytes":[97],"top_logprobs":[{"token":"a","logprob":-0.0006775910374046157,"bytes":[97]},{"token":"\"","logprob":-8.814616035109342,"bytes":[34]}]}]},"finish_reason":null}]}
data: {"id":"chatcmpl-192","object":"chat.completion.chunk","created":1790751378,"model":"tinygpt-chat","choices":[{"index":0,"delta":{"content":" queen"},"logprobs":{"content":[{"token":" queen","logprob":-0.004053804968918497,"bytes":[32,113,117,101,101,110],"top_logprobs":[{"token":" queen","logprob":-0.004053804968918497,"bytes":[32,113,117,101,101,110]},{"token":" king","logprob":-7.375298411943343,"bytes":[32,107,105,110,103]}]}]},"finish_reason":null}]}
data: {"id":"chatcmpl-192","object":"chat.completion.chunk","created":1790751378,"model":"tinygpt-chat","choices":[{"index":0,"delta":{"content":" is"},"logprobs":{"content":[{"token":" is","logprob":-0.0009430850027441802,"bytes":[32,105,115],"top_logprobs":[{"token":" is","logprob":-0.0009430850027441802,"bytes":[32,105,115]},{"token":"t","logprob":-8.638698055398786,"bytes":[116]}]}]},"finish_reason":null}]}
data: {"id":"chatcmpl-192","object":"chat.completion.chunk","created":1790751378,"model":"tinygpt-chat","choices":[{"index":0,"delta":{},"logprobs":{"content":[]},"finish_reason":"length"}]}
data: [DONE]

The logprobs are printed to the last bit, and those bits depend on the machine that trained the model, not on the code: a model trained on dixie (Intel, like talos) printed these values, and one trained on straylight (AMD) gave queen −0.004053804968918718 and king −7.375298411943442. The losses, the replies, the token counts and every number chapter 18 prints came out the same from either model.

max_tokens: 3 cut the reply after is, so the last chunk says "length". The model is sure of its answer: the runner-up to queen has logprob −7.4-7.4, a probability of about e−7.4≈6×10−4e^{-7.4} \approx 6 \times 10^{-4}.

The fleet’s routers autoload: a request that names a model which is not loaded loads it, and may evict another. The script below never does that. It reads GET /v1/models first, refuses to send anything unless the model’s status is loaded, and adds ?autoload=false, so that if the model is unloaded between the check and the request the router answers 400 instead of loading it. Save as /tmp/fleet_stream.py:

"""Read-only: one short streamed chat completion from a model a fleet router already has loaded.

    python3 /tmp/fleet_stream.py HOST MODEL        e.g. dixie ornith-1.5-9b-uncensored

Never loads a model: it reads /v1/models first, refuses unless the model's status is "loaded", and
sends ?autoload=false so the router answers 400 rather than load anything."""
import json
import sys
import time
import urllib.request

host, model = sys.argv[1], sys.argv[2]
base = f"http://{host}:11434"


def get(path):
    with urllib.request.urlopen(base + path, timeout=10) as r:
        return json.loads(r.read())


status = {m["id"]: (m.get("status") or {}).get("value") for m in get("/v1/models")["data"]}
if status.get(model) != "loaded":
    raise SystemExit(f"{model} is {status.get(model)!r} on {host}, not loaded; nothing sent")
print("date", time.strftime("%Y-%m-%d %H:%M %Z"), "host", host, "build", get("/props")["build_info"], "model", model)
body = {"model": model, "stream": True, "max_tokens": 12, "temperature": 0, "logprobs": True, "top_logprobs": 2,
        "messages": [{"role": "user", "content": "Reply with exactly: it’s done"}],
        "chat_template_kwargs": {"enable_thinking": False}}
req = urllib.request.Request(base + "/v1/chat/completions?autoload=false", json.dumps(body).encode(),
                             {"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=60) as r:
    print(r.status, r.headers["Content-Type"])
    for line in r:
        if line.strip():
            print(line.decode().rstrip()[:400])

Run python3 /tmp/fleet_stream.py dixie ornith-1.5-9b-uncensored (or straylight ornith-1.5-35b-a3b); if the model is not loaded it prints why and sends nothing. A capture from talos against dixie, each line cut to 400 characters by the script:

date 2026-09-29 23:47 PDT host dixie build b10964-b29c606 model ornith-1.5-9b-uncensored
200 text/event-stream
data: {"choices":[{"finish_reason":null,"index":0,"delta":{"role":"assistant","content":null}}],"created":1790750838,"id":"chatcmpl-6miSc0K7emupyvOmuQ9EuvDRU9LQTgr1","model":"ornith-1.5-9b-uncensored","system_fingerprint":"b10964-b29c606","object":"chat.completion.chunk"}
data: {"choices":[{"finish_reason":null,"index":0,"delta":{"content":"it"},"logprobs":{"content":[{"id":275,"token":"it","bytes":[105,116],"logprob":-0.008901700377464294,"top_logprobs":[{"id":275,"token":"it","bytes":[105,116],"logprob":-0.008901700377464294},{"id":2064,"token":"It","bytes":[73,116],"logprob":-5.493896484375}]}]}}],"created":1790750838,"id":"chatcmpl-6miSc0K7emupyvOmuQ9EuvDRU9LQT
data: {"choices":[{"finish_reason":null,"index":0,"delta":{"content":"’s"},"logprobs":{"content":[{"id":725,"token":"’s","bytes":[226,128,153,115],"logprob":-0.12455926835536957,"top_logprobs":[{"id":725,"token":"’s","bytes":[226,128,153,115],"logprob":-0.12455926835536957},{"id":579,"token":"'s","bytes":[39,115],"logprob":-2.1509149074554443}]}]}}],"created":1790750838,"id":"chatcmpl-6miSc0K7emup
data: {"choices":[{"finish_reason":null,"index":0,"delta":{"content":" done"},"logprobs":{"content":[{"id":2725,"token":" done","bytes":[32,100,111,110,101],"logprob":-0.0010433869902044535,"top_logprobs":[{"id":2725,"token":" done","bytes":[32,100,111,110,101],"logprob":-0.0010433869902044535},{"id":30758,"token":".done","bytes":[46,100,111,110,101],"logprob":-8.828123092651367}]}]}}],"created":1
data: {"choices":[{"finish_reason":"stop","index":0,"delta":{}}],"created":1790750838,"id":"chatcmpl-6miSc0K7emupyvOmuQ9EuvDRU9LQTgr1","model":"ornith-1.5-9b-uncensored","system_fingerprint":"b10964-b29c606","object":"chat.completion.chunk","timings":{"cache_n":0,"prompt_n":19,"prompt_ms":67.869,"prompt_per_token_ms":3.572052631578947,"prompt_per_second":279.9510822319468,"predicted_n":4,"predicte
data: [DONE]

The build is b10964-b29c606, from 2026-09-14 and 300 commits behind the da89bb3 whose source this chapter quotes, so where the two disagree the capture is the older behaviour. Field by field against this server’s stream: the framing is the same, data: lines and data: [DONE]. The first delta carries the role with content: null where this server sends "" (server-task.cpp:1134-1139); both are valid, and a client must accept either. The id is a random string rather than a counter. Each chunk has system_fingerprint, the build. Each logprob entry has the token’s id besides token, bytes, logprob and top_logprobs, and the logprobs sit only in chunks that carry content. The last chunk carries timings (chapter 12’s prompt_n, predicted_n and cache_n), a llama.cpp extension a client ignores. And ’s arrives whole in one delta because it is one token of this model’s vocabulary, the token 725 of the UTF-8 section; the lab’s byte-level tokenizer splits every such character.

Finally, the live test, which sends a reply full of curly quotes through the same guard and checks that the stream is event-stream, ends in [DONE], and contains no U+FFFD. From py/:

AEC_LIVE=dixie uv run pytest -q tests/test_live_serving.py

It passed against dixie on 2026-09-29 (1 passed). Without AEC_LIVE, or with no chat model loaded, it skips; it never loads one.

Further reading

results matching ""

    No results matching ""