The API: messages, system prompts, streaming, stop reasons
One endpoint, a stateless conversation you resend every turn, six stop reasons your code must handle, and the retry rules that keep a chat loop correct
Your code sends a non-streaming Messages request with a 30-second client timeout. The model is still generating at 30 seconds, the client gives up, and the SDK retries automatically. What has happened on the server?
Every Claude feature you will use in this course, from tool use to structured output to caching, goes through one endpoint: POST /v1/messages. This chapter takes that endpoint apart: the request and response shapes, how streaming works on the wire, what each stop reason means for your code, which errors to retry and how, and why history is your problem and not the API’s. The lab builds a command-line chat that gets all of it right, then runs the portable part against a local model.
Model ids, prices and limits in this chapter are for claude-opus-5-5 as of November 2026: $4 per million input tokens, $20 per million output tokens, a 1M-token context window and up to 128K output tokens per request.
One endpoint, one shape
A minimal request over raw HTTP:
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-opus-5-5",
"max_tokens": 1024,
"system": "You are a terse assistant for engineers.",
"messages": [
{"role": "user", "content": "What does fsync do?"}
]
}'
Three fields are required:
model: an exact model id. Use the ids from the models page as written, with no date suffix you remember from somewhere else; a wrong id is a 404.max_tokens: the ceiling on generated tokens for this response. It is a hard stop, not a target. On models that think before answering, thinking tokens count towards it.messages: the conversation so far. Roles areuserandassistant, the first message must beuser, and consecutive messages with the same role are merged into one turn.
system is a top-level field, not a message with a system role. It holds the operator’s instructions and is placed ahead of the conversation. It accepts a string or a list of text blocks; the list form lets you mark part of it for caching.
A message’s content is either a string or a list of content blocks. A string is shorthand for one text block. The other block types are how everything else travels: image and document for inputs, tool_use and tool_result for tools, thinking for the model’s reasoning. Learn to think of content as a list, because the response always is one.
Sampling parameters are not part of the current shape. Older code sets temperature, top_p or top_k; current Claude models reject them with a 400. Control comes from the prompt and from output_config.effort (low, medium, high, xhigh, max), which sets how much the model thinks and how thoroughly it answers. On Claude Opus 5.5 thinking is always on and effort defaults to medium.
The response
{
"id": "msg_01...",
"type": "message",
"role": "assistant",
"model": "claude-opus-5-5",
"content": [
{"type": "thinking", "thinking": "", "signature": "EqQB..."},
{"type": "text", "text": "It blocks until the file's data and metadata reach stable storage."}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {"input_tokens": 31, "output_tokens": 118,
"cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}
}
Three things trip people up:
contentis a list, and the first block is not always text. A thinking model returns athinkingblock before its text. By default the thinking text is omitted (an empty string with a signature), but the block is there and its tokens are billed. Iterate and selecttype == "text"; never readcontent[0].text.output_tokensincludes thinking. The visible answer above is about 15 tokens; the bill says 118. Cost estimates based on the length of the visible text are wrong for any thinking model.input_tokensis only the uncached part. With caching on, total input isinput_tokens + cache_creation_input_tokens + cache_read_input_tokens, and the three are priced differently.
Every response also has a request-id header (exposed as message._request_id in the Python SDK). Log it; it is what support needs to find your request.
Streaming
Set "stream": true and the response is a stream of server-sent events. Each event has a name and a JSON payload, in this order:
| Event | Carries | What you do with it |
|---|---|---|
message_start |
The message shell: id, model, usage.input_tokens |
Record input tokens and the id |
content_block_start |
A new block at index, with its type |
Start a buffer for that block |
content_block_delta |
A piece of the block: text_delta, thinking_delta, signature_delta, or input_json_delta for tool inputs |
Append; print text deltas as they arrive |
content_block_stop |
The block at index is complete |
Close the buffer |
message_delta |
stop_reason, stop_sequence, cumulative usage.output_tokens |
Record why it stopped and the final output count |
message_stop |
End of stream | Done |
ping |
Nothing | Ignore; it keeps idle connections alive |
error |
An error object, such as overloaded_error |
Treat as a failed request (below) |
Two consequences of this design matter for your code. First, the HTTP status is 200 before the first token is generated, so an error can arrive mid-stream as an error event, after you have already shown the user half an answer. Your retry logic has to handle failures after output started, not only failures before it. Second, the stop reason and the final token count arrive near the end, in message_delta, so anything that depends on them (logging, cost, deciding whether the answer is complete) runs after the stream ends.
The SDKs wrap this. In Python, client.messages.stream(...) is a context manager; stream.text_stream yields text deltas, and stream.get_final_message() returns the same Message object a non-streaming call would, accumulated from the events. Stream by default for anything interactive or long. It improves perceived latency (the first words appear while the rest is generated), and it changes what a time-out means: the read timeout measures silence between events, not total generation time. The SDK refuses a non-streaming request it estimates will exceed ten minutes for exactly this reason.
Expect a pause before the first text event on a thinking model: the thinking happens first. With thinking display omitted, you see content_block_start for a thinking block, one empty delta and a signature, and then the text.
Stop reasons
stop_reason tells you why generation ended. Each value needs its own branch in your code:
stop_reason |
Meaning | What your code does |
|---|---|---|
end_turn |
The model finished its answer | Use the response |
max_tokens |
Hit your max_tokens ceiling |
The answer is truncated. Tell the user, raise the limit, or ask the model to continue; never parse it as complete JSON or a complete plan |
stop_sequence |
Produced one of your stop_sequences; stop_sequence says which |
Expected if you set one; the matched string is not included in the text |
tool_use |
The model wants to call a tool | Run the tool, send a tool_result, call again (module A2) |
pause_turn |
A long server-side tool turn was paused | Send the conversation back as is to let it continue |
refusal |
Safety classifiers declined the request; stop_details has a category |
Do not show partial content as an answer; tell the user, and do not keep the turn in history |
A refusal is an HTTP 200, not an error. Code that only checks for exceptions will treat it as a successful empty answer. Claude Opus 5.5 and other current models run classifiers that can decline, occasionally on benign requests near security or biology topics, and the API offers server-side fallbacks: with the beta header server-side-fallback-2026-07-01 and fallbacks: "default", a declined request is re-run on a recommended fallback model inside the same call. The lab’s chat enables it, and reports which model served the answer when that happens.
The rule this course follows. Every lab request to claude-opus-5-5 or claude-sonnet-5-5 goes through client.beta.messages (create, stream or parse) with betas=["server-side-fallback-2026-07-01"] and fallbacks="default", and checks stop_reason == "refusal" before reading content; a refusal on such a response means the whole chain declined. Three cases send no fallbacks: claude-haiku-5-5, which has no server-side fallback (a declined request stays declined, so handle the refusal in your code); Message Batches requests, where the parameter is rejected; and count_tokens, which generates nothing. A rescued response may begin with a fallback content block and names the model that served it in model; code that selects blocks by type is unaffected, and a non-streaming response can go back into the history as it came. Short snippets in the chapter text leave the two arguments out to stay readable; lab code always includes them.
Errors and retries
| Status | Type | Retry? |
|---|---|---|
| 400 | invalid_request_error |
No. The request is wrong; also returned when your own spend limit is reached |
| 401 / 403 | authentication_error / permission_error |
No. Fix the key or the workspace |
| 404 | not_found_error |
No. Usually a mistyped or retired model id |
| 413 | request_too_large |
No. Messages requests are capped at 128 MB |
| 429 | rate_limit_error |
Yes, after retry-after seconds. Except the monthly spend-cap 429: no retry-after, and error.details.error_code is enforced_spend_limit_reached |
| 500 | api_error |
Yes, with backoff |
| 504 | timeout_error |
Yes, and switch to streaming for long requests |
| 529 | overloaded_error |
Yes, with backoff; the whole API is busy, not only you |
The SDK retries connection errors, 408, 409, 429 and 5xx twice by default with exponential backoff, honouring retry-after. That is fine for a batch job. For an interactive loop you often want control: how many attempts, what the user sees while waiting, and what happens when the failure comes mid-stream, which the SDK cannot retry because output has already been delivered. The lab turns the SDK’s retries off and writes the loop itself.
The rules for a correct retry loop are standard, and the lessons on retries, backoff and jitter cover why:
- Exponential backoff with jitter. 1, 2, 4, 8 seconds, each multiplied by a random factor, capped. Without jitter every client that failed together retries together.
- Honour
retry-afterwhen the server sends it. It knows when your bucket refills. - Bound the attempts and the total time. Five or six attempts, or a deadline. A loop that retries forever turns an overload into a retry storm.
- Never retry a non-retryable error. A 400 will fail identically every time.
Rate limits are per organisation and per model class, measured as requests per minute, input tokens per minute and output tokens per minute, and enforced with a token bucket, so short bursts can trip them even under the per-minute figure. On the Start tier, Claude Opus 5.5’s limits are 4,000 requests, 2,000,000 input tokens and 400,000 output tokens per minute. For most current models, cache reads do not count towards the input-token limit, which makes caching a throughput tool as well as a cost tool. Each response carries anthropic-ratelimit-* headers with the limit, the remaining capacity and the reset time; log them when you are near the edge.
Timeouts and idempotency
The Messages API has no idempotency key. A retried request is a new request: billed again, sampled again, with a different answer. For a chat this is harmless, apart from cost. For a system that acts on the model’s output, it is the same double-execution bug as a payment retried without a key, and the fix is the same: the action carries an id you generate, and the thing performing the action deduplicates on it. The idempotency lesson covers the pattern; module A2 applies it to tool calls.
Timeouts need three numbers, not one:
- Connect timeout: a few seconds. If you cannot open a connection in 5 s, retrying is better than waiting.
- Read timeout: the longest silence you accept between bytes. With streaming, the server sends events and pings throughout, so 60 s of silence means something is wrong. Without streaming, the read timeout has to exceed the whole generation, which for a long answer on a thinking model can be minutes.
- Overall deadline: what the user will tolerate. The SDK’s default timeout is ten minutes, and timed-out requests are retried, so the wall-clock worst case is the timeout multiplied by the number of attempts. Set a deadline your product can live with.
Cancellation is the place the Why’s bug lived. When the user presses Ctrl-C mid-stream, close the stream (the SDK’s context manager does this), discard the partial answer from history, and do not reuse anything half-written. Exit paths are where shared state gets corrupted.
SDK or raw HTTP
Use the SDK. It gives you typed exceptions (anthropic.RateLimitError, anthropic.APIStatusError, anthropic.APIConnectionError) instead of string-matching on messages, retries with the right defaults, stream accumulation, request ids on every response, the long-request guard, and credentials from the environment or an ant auth login profile. Raw HTTP is worth knowing because it shows what is actually on the wire, and it is what you debug with when something behaves oddly: curl -N with "stream": true prints every event as it arrives.
History is your job
The API is stateless. Every request carries the entire conversation, and the model remembers nothing between calls. That has three consequences.
Cost grows with the square of the conversation. If each turn adds 300 tokens, turn 20 sends 6,000 input tokens, and the whole 20-turn conversation sends 300 × (1 + 2 + … + 20) = 63,000 input tokens: about $0.25 on Claude Opus 5.5 before any output. A support conversation that runs to 60 turns sends over half a million.
You must decide what to keep. The simplest correct policy is a token budget: count the tokens the next request will send, and if it is over budget, drop the oldest whole user-and-assistant pairs, so the history still starts with a user turn. client.messages.count_tokens(model=..., system=..., messages=...) returns the exact input count, is free to use, and has its own rate limit separate from message creation. Drop in chunks, down to half the budget, rather than one pair per turn; the reason is caching, below. The alternatives, summarising old turns or server-side compaction, are covered in the agents and long-context chapters.
What you store matters. Current Claude models bind each thinking block to the exact conversation that produced it. If you resend thinking blocks after editing or dropping earlier turns, they no longer match; depending on the model and account, the API drops them or rejects the request with a 400. A chat with no tools does not need its old thinking at all, so the lab stores only the text of each assistant turn. When you add tools in A2, the rule tightens: an assistant turn that contains a tool_use goes back exactly as it came, thinking included, until its tool round is complete.
Caching softens the cost. With cache_control: {"type": "ephemeral"} at the top level of the request, the API caches the longest reusable prefix, and a later request with the same prefix reads it at a fraction of the input price ($0.20 per million instead of $4 on Claude Opus 5.5, and the first write costs about 1.25 times the input price). Any change to the prefix invalidates everything after it, which is why trimming one pair per turn is a bad policy: it changes the start of the conversation on every request. Prefixes below a model-dependent minimum, from a few hundred to a few thousand tokens, are not cached at all, so short chats show cache_read_input_tokens: 0.
The portable subset
Many local and hosted models expose an OpenAI-compatible Chat Completions endpoint, including Ollama at http://localhost:11434/v1. The core of a chat loop translates directly. The details do not:
| Concept | Anthropic Messages API | OpenAI-compatible Chat Completions |
|---|---|---|
| Instructions | Top-level system |
A message with role system |
| Output ceiling | max_tokens, required |
max_tokens, optional |
| Response text | List of content blocks; select text |
choices[0].message.content, a string |
| Why it stopped | stop_reason: end_turn, max_tokens, stop_sequence, tool_use, pause_turn, refusal |
finish_reason: stop, length, tool_calls, content_filter |
| Usage | input_tokens, output_tokens, cache fields |
prompt_tokens, completion_tokens |
| Streaming | Named events with typed deltas | Unnamed chunks with a delta, then [DONE] |
| Token counting before sending | count_tokens endpoint |
None; estimate |
The portable subset is: messages with roles, streaming text, a maximum length, a “why it stopped” field, and usage counts. Everything else, from thinking and refusals to caching, structured outputs and tool-use details, differs by provider. Ollama also offers an Anthropic-compatible /v1/messages endpoint that supports a subset of the Messages API, which is convenient for local testing but does not make provider-specific features portable. Write the core against an interface you own, and keep provider features behind it; the multi-provider reliability chapter in module A4 builds on that seam.
You will watch the raw stream, then build a chat that streams, keeps and trims history by token count, handles every stop reason, retries 429 and 529 with backoff, and logs cost per turn. Then you will break it on purpose with a fake overloaded server, and run the portable core against a local model. Work in labs/ai/chat/ (mkdir -p labs/ai/chat from the root of your checkout); the labs/ai uv project from the first chapter’s lab already has anthropic.
1. Look at the wire.
curl -sN https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" -H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model": "claude-opus-5-5", "max_tokens": 1024, "stream": true,
"output_config": {"effort": "low"},
"messages": [{"role": "user", "content": "Name three uses of fsync, one line each."}]}'event: and data: lines: message_start with input tokens, a content_block_start for a thinking block at index 0 with an empty thinking_delta and a signature_delta, then a text block at index 1 whose text_delta events arrive a few tokens at a time, perhaps a ping, then message_delta with "stop_reason":"end_turn" and the output token count, and message_stop. The output count is larger than the visible text because it includes thinking. This costs about a tenth of a cent.2. The chat. Create labs/ai/chat/chat.py:
"""A CLI chat that streams, trims history by tokens, handles stop reasons, retries, and logs cost."""
import os, random, sys, time
import anthropic
MODEL = os.environ.get("CHAT_MODEL", "claude-opus-5-5")
MAX_TOKENS = int(os.environ.get("CHAT_MAX_TOKENS", "16000"))
BUDGET = int(os.environ.get("CHAT_HISTORY_TOKENS", "20000")) # input tokens per request
STOP = [s for s in os.environ.get("CHAT_STOP", "").split(",") if s]
SYSTEM = "You are a concise assistant for software engineers. Prefer short answers with numbers."
PRICES = {"claude-opus-5-5": (4.00, 20.00, 0.20), "claude-sonnet-5-5": (2.00, 10.00, 0.10)}
RETRY_STATUS = {408, 409, 429, 500, 502, 503, 504, 529}
MAX_ATTEMPTS = 6
# Retries are ours, not the SDK's, so we control what happens mid-stream.
client = anthropic.Anthropic(max_retries=0, timeout=anthropic.Timeout(60.0, connect=5.0))
history: list[dict] = [] # text-only turns; see the chapter on thinking blocks
session_cost = 0.0
def spend_cap(err: anthropic.APIStatusError) -> bool:
body = err.body if isinstance(err.body, dict) else {}
body = body.get("error", body)
return (body.get("details") or {}).get("error_code") == "enforced_spend_limit_reached"
def retry_delay(err: Exception, attempt: int) -> float | None:
"""Seconds to wait before retrying, or None if retrying cannot help."""
backoff = min(30.0, 2.0 ** attempt) * random.uniform(0.5, 1.0)
if isinstance(err, anthropic.APIConnectionError): # includes timeouts
return backoff
if isinstance(err, anthropic.APIStatusError):
if spend_cap(err):
return None
retryable = (err.status_code in RETRY_STATUS or
getattr(err, "type", None) in ("overloaded_error", "api_error", "rate_limit_error"))
if retryable:
after = err.response.headers.get("retry-after")
return float(after) if after else backoff
return None
def trim() -> int:
"""Drop the oldest user+assistant pairs until the request fits; return its input tokens."""
n = client.messages.count_tokens(model=MODEL, system=SYSTEM, messages=history).input_tokens
if n <= BUDGET:
return n
while len(history) > 1 and n > BUDGET // 2: # drop in a chunk so the cache survives
del history[:2]
n = client.messages.count_tokens(model=MODEL, system=SYSTEM, messages=history).input_tokens
print(f"[history trimmed to {len(history)} messages, {n} tokens]", file=sys.stderr)
return n
def stream_once():
extra = {"stop_sequences": STOP} if STOP else {}
with client.beta.messages.stream(
model=MODEL, max_tokens=MAX_TOKENS, system=SYSTEM, messages=history,
output_config={"effort": "low"}, cache_control={"type": "ephemeral"},
betas=["server-side-fallback-2026-07-01"], fallbacks="default", **extra,
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
return stream.get_final_message()
def stream_with_retries():
for attempt in range(MAX_ATTEMPTS):
try:
return stream_once()
except (anthropic.APIConnectionError, anthropic.APIStatusError) as err:
delay = retry_delay(err, attempt)
if delay is None or attempt == MAX_ATTEMPTS - 1:
raise
print(f"\n[{type(err).__name__} {getattr(err, 'status_code', '')}: "
f"retry {attempt + 1}/{MAX_ATTEMPTS - 1} in {delay:.1f}s; any partial output discarded]")
time.sleep(delay)
def cost(u) -> float:
if MODEL not in PRICES:
return 0.0
pin, pout, pread = PRICES[MODEL]
return (u.input_tokens * pin + (u.cache_creation_input_tokens or 0) * pin * 1.25
+ (u.cache_read_input_tokens or 0) * pread + u.output_tokens * pout) / 1e6
def handle(msg) -> str | None:
"""Return the assistant text to keep in history, or None to drop this turn."""
text = "".join(b.text for b in msg.content if b.type == "text")
r = msg.stop_reason
if msg.model != MODEL:
print(f"\n[served by fallback model {msg.model}]")
if r == "end_turn":
return text
if r == "max_tokens":
print(f"\n[truncated at max_tokens={MAX_TOKENS}; thinking counts towards it]")
return text or None
if r == "stop_sequence":
print(f"\n[stopped at stop sequence {msg.stop_sequence!r}]")
return text or None
if r == "refusal":
d = getattr(msg, "stop_details", None)
print(f"\n[declined: {getattr(d, 'category', None)}; this turn is not kept]")
return None
if r == "pause_turn": # only server tools pause; this chat declares none
print("\n[paused turn without server tools: unexpected, not kept]")
return None
if r == "tool_use": # we send no tools, so this is a bug somewhere
raise RuntimeError("tool_use with no tools declared")
print(f"\n[unknown stop_reason {r!r}; not kept]") # new values appear over time
return None
def main():
global session_cost
print(f"model {MODEL}, history budget {BUDGET} tokens. /reset clears, /quit exits.")
while True:
try:
line = input("\nyou> ").strip()
except (EOFError, KeyboardInterrupt):
break
if line in ("/quit", "/exit"):
break
if line == "/reset":
history.clear()
continue
if not line:
continue
history.append({"role": "user", "content": line})
try:
trim()
print("claude> ", end="", flush=True)
msg = stream_with_retries()
except KeyboardInterrupt:
print("\n[cancelled; turn discarded]")
history.pop()
continue
except anthropic.APIError as err:
print(f"\n[request failed: {type(err).__name__}: {err}]")
history.pop()
continue
text = handle(msg)
if text is None:
history.pop() # keep the history starting with user and alternating
else:
history.append({"role": "assistant", "content": text})
c = cost(msg.usage)
session_cost += c
u = msg.usage
print(f"\n[{msg.stop_reason} in {u.input_tokens} cache r/w {u.cache_read_input_tokens or 0}/"
f"{u.cache_creation_input_tokens or 0} out {u.output_tokens} "
f"${c:.4f} session ${session_cost:.4f} {msg.id}]")
if __name__ == "__main__":
main()cd labs/ai/chat
uv run chat.pyHave a short conversation: ask a question, then a follow-up that only makes sense with the first answer (“and on macOS?”).
[end_turn in 54 cache r/w 0/0 out 212 $0.0045 session $0.0045 msg_01...]. The follow-up is answered in context because the whole history was resent; in grows every turn. Cache reads stay at 0 until the conversation passes the model’s minimum cacheable length; after that you see cache r/w reads on each turn, billed at $0.20 per million instead of $4. The chat enables server-side fallbacks (fallbacks: "default" with the server-side-fallback-2026-07-01 beta), so a declined turn is re-run on a recommended fallback model and the chat prints which model served it.3. Make it stop in each way.
CHAT_MAX_TOKENS=300 uv run chat.pyAsk: “Explain B-trees, write-ahead logging and MVCC in detail.” Then quit and run with a stop sequence:
CHAT_STOP=END uv run chat.pyAsk: “Write three short lines about databases, then the word END, then a fourth line.”
max_tokens with the truncation warning. In the second run the reply stops after the third line, the chat prints [stopped at stop sequence 'END'], and END itself is not in the text. Both partial answers are kept in history, so a follow-up such as “continue” works.4. Retries against an overloaded API, for free. Create fake_api.py, a stand-in that is always overloaded:
"""A fake Messages API that fails every request, to exercise retry logic without cost."""
import json, os
from http.server import BaseHTTPRequestHandler, HTTPServer
STATUS = int(os.environ.get("STUB_STATUS", "529"))
TYPE = {529: "overloaded_error", 429: "rate_limit_error", 400: "invalid_request_error"}[STATUS]
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
self.rfile.read(int(self.headers.get("content-length", 0)))
if self.path.startswith("/v1/messages/count_tokens"):
code, body, headers = 200, {"input_tokens": 42}, {}
else:
code = STATUS
body = {"type": "error", "error": {"type": TYPE, "message": "stub"}}
headers = {"retry-after": "3"} if STATUS == 429 else {}
data = json.dumps(body).encode()
self.send_response(code)
self.send_header("content-type", "application/json")
self.send_header("request-id", "req_stub")
for k, v in headers.items():
self.send_header(k, v)
self.send_header("content-length", str(len(data)))
self.end_headers()
self.wfile.write(data)
HTTPServer(("127.0.0.1", 8529), Handler).serve_forever()In one terminal run python3 fake_api.py; in another:
ANTHROPIC_BASE_URL=http://127.0.0.1:8529 ANTHROPIC_API_KEY=stub \
uv run chat.pyType anything. Then restart the stub with STUB_STATUS=429 python3 fake_api.py and try again.
[request failed: OverloadedError: Error code: 529 ...] (the SDK’s class for 529, a subclass of APIStatusError), and the user turn is removed so history stays valid. The stub terminal shows six POSTs to /v1/messages. With 429 the delays are exactly 3 seconds each, because the chat honours retry-after. In both cases the chat survives and accepts the next message.5. History trimming by token count.
CHAT_HISTORY_TOKENS=1500 uv run chat.pyAsk for something long, such as “Explain TCP congestion control in about 400 words”, three or four times with different topics.
[history trimmed to N messages, M tokens] appears on stderr, M is at or below 750 (half the budget), and the in figure on the status line drops. Ask “what was my first question?” and the model no longer knows: it was trimmed. That is the policy working, and it shows the cost of it. On the turn after a trim, cache reads fall to 0, because the start of the conversation changed.6. The portable core, on a local model. Create chat_portable.py:
"""The same loop through an OpenAI-compatible endpoint (Ollama by default). Portable subset only."""
import os
from openai import OpenAI, APIConnectionError, APIStatusError
MODEL = os.environ.get("PORTABLE_MODEL", "llama3.2:3b")
client = OpenAI(base_url=os.environ.get("PORTABLE_BASE_URL", "http://localhost:11434/v1"),
api_key=os.environ.get("PORTABLE_API_KEY", "ollama"), max_retries=3, timeout=120)
SYSTEM = "You are a concise assistant for software engineers. Prefer short answers with numbers."
BUDGET = 3000 # tokens, estimated: no count_tokens endpoint here
history: list[dict] = []
def estimate(msgs): # about 4 characters per token for English
return sum(len(m["content"]) for m in msgs) // 4 + 4 * len(msgs)
while True:
try:
line = input("\nyou> ").strip()
except (EOFError, KeyboardInterrupt):
break
if line == "/quit":
break
if not line:
continue
history.append({"role": "user", "content": line})
while estimate(history) > BUDGET and len(history) > 1:
del history[:2]
parts, finish, usage = [], None, None
try:
stream = client.chat.completions.create(
model=MODEL, max_tokens=1024, stream=True, stream_options={"include_usage": True},
messages=[{"role": "system", "content": SYSTEM}] + history)
for chunk in stream:
if chunk.choices:
choice = chunk.choices[0]
if choice.delta and choice.delta.content:
print(choice.delta.content, end="", flush=True)
parts.append(choice.delta.content)
finish = choice.finish_reason or finish
if chunk.usage:
usage = chunk.usage
except (APIConnectionError, APIStatusError) as err:
print(f"[request failed: {err}]")
history.pop()
continue
if finish == "length":
print("\n[truncated at max_tokens]")
history.append({"role": "assistant", "content": "".join(parts)})
print(f"\n[{finish} in {getattr(usage, 'prompt_tokens', '?')} "
f"out {getattr(usage, 'completion_tokens', '?')} $0 (local)]")uv add openai && uv run chat_portable.pystop in place of end_turn and prompt_tokens / completion_tokens in place of input_tokens / output_tokens. What did not port: exact token counting (this version estimates at 4 characters per token, so its trimming is approximate), refusals as a distinct stop reason, fallbacks, thinking, cache accounting, and typed overload errors. Those are the parts to keep behind your own interface.STUB_STATUS=400 and send a message: the chat fails at once with BadRequestError and does not retry, which is correct, because the same request will fail the same way. Now break retry_delay so it retries everything (add return backoff straight after the line that computes it) and run again: six identical requests in about 30 seconds, every one of them a guaranteed failure. Against the real API that is wasted rate limit and, multiplied across clients, exactly the kind of retry storm that keeps an overloaded service down. Put the classification back. A retry policy is mostly a list of errors you refuse to retry.Template
# API integration design note: <feature>
Owner: <engineer>. Approver: <head of engineering>. Date: <date>. Status: draft / agreed.
Decision needed: <what, from whom, by when>. Out of scope: <what this note does not cover>.
## 1. What the feature calls
<endpoint, model, max_tokens, streaming on or off, fallbacks on or off>
## 2. Stop reasons
| stop_reason | What the product does | What the user sees |
|---|---|---|
| end_turn | | |
| max_tokens | | |
| stop_sequence | | |
| refusal | | |
| tool_use / pause_turn | | |
## 3. Streaming
<what appears when, the pause before the first text, what happens on an error event mid-stream>
## 4. Timeouts and retries
- Connect <s>, read <s>, overall deadline <s>
- Retried: <statuses>, up to <n> attempts, backoff <rule>, honours retry-after
- Never retried: <statuses and the spend-cap 429>
## 5. When it fails: what the user sees
| Failure | What the user sees | What we log |
|---|---|---|
## 6. Cost and numbers
<every figure, with its source: lab output, eval run or assumption>
## 7. How this could be wrong
<one way, and what would show it> WORKED EXAMPLE
At a real company the engineer who builds the chat writes this note with the support lead, and the head of engineering approves it.
API integration design note: the shop’s support chat. Owner: the engineer who built it. Approver: the head of engineering. Date: 20 November 2026. Decision needed: approve this failure behaviour before the chat goes to customers. Out of scope: tools and order lookups (module A2).
Stop reasons. end_turn is shown as it streamed. max_tokens shows the answer with a note, “This answer was cut short”, and the turn stays in history so the customer can type “continue”; the lab at 300 tokens cut off mid-sentence. stop_sequence is not used in production. refusal is an HTTP 200: the customer sees “I can’t help with that here; a person will pick this up”, the turn is dropped from history, and the chat hands over to a human. Fallbacks are on, so that message appears only if the whole chain declined.
Streaming. Text appears as it arrives after a pause of a second or two while the model thinks. If an error event arrives mid-stream, the partial text is discarded, the user sees a retry notice, and the request is repeated.
Timeouts and retries. Connect 5 s, read 60 s of silence, as in the lab. Overall deadline 45 s per message, an assumption (the lab sets none), so the deadline can end the retries before six attempts. Six attempts at most: five retries with delays of roughly 1, 2, 4, 8 and 16 s, each multiplied by 0.5 to 1. A 429 waits exactly the 3 s the server asks for. A 400 is never retried.
When it fails. After six attempts on 529 the customer sees “We’re busy; please send that again in a minute”, and their message is removed from history.
Cost. A typical turn printed in 54, out 212, $0.0045.
How this could be wrong. The 60 s read timeout was only tried in the lab, not at high effort; we would see read-timeout retries in the log.
Now you
You work at Kolanut Mobile, a virtual operator hosted on Lumora Mobile’s network, with 45 people and 250,000 subscribers in its launch year. Traders recharge at market agents’ stalls, and when a recharge fails the agent has to explain why. The head of technology wants a chat assistant in the agent app that helps agents explain failed recharges to customers. A person must edit and send every reply, so nothing reaches a customer unreviewed, and the app drops any call that takes longer than 30 seconds.
Write the API integration design note. Reuse your own runs of the lab: the 300-token ceiling from step 3, the stub’s 529 and 429 behaviour from step 4, and the status line from step 2. Where a figure is missing, state it as an assumption.
The head of technology approves the note; the customer-care lead reads section 5 to check that the messages an agent would see are ones they can act on. The decision it supports is whether the assistant can go to the market agents on Monday.
Self-check
Your shop's support chat on Claude Opus 5.5 is getting expensive. Median conversations are 8 turns, but the top 5% run past 60 turns and account for 40% of input-token spend. Agents say customers in long chats often refer back to an order number from the start. What history policy do you ship?
- DOC Messages API reference Anthropic
Every request field and content block type. Read the request body section once end to end; skip the server-tool block types until module A2.
- DOC Streaming messages Anthropic
The event types, delta types, error events mid-stream and a full raw stream to compare with your curl output. The tool-use and thinking stream examples are worth a skim now.
- DOC Claude API errors Anthropic
Status codes and types, request ids, request size limits, and the long-request guidance behind streaming by default. The common validation errors section explains most 400s you will hit.
- DOC Rate limits Anthropic
RPM, ITPM and OTPM per tier and model, the token bucket, cache-aware input limits, the spend-cap 429 and the response headers. Read the response headers table before you build any monitoring.
- DOC Token counting Anthropic
The free count_tokens endpoint used for history trimming, including counts for tools, images and documents. Note its rate limit is separate from message creation.
- DOC OpenAI compatibility Ollama
Which Chat Completions fields Ollama supports, including streaming usage. Use it to see exactly where the portable subset ends for local models.
- POST March 20 ChatGPT outage: Here's what happened OpenAI, 2023
A short, honest postmortem of a cancellation bug in a client library that leaked user data. Read it as a reminder that LLM applications fail in ordinary distributed-systems ways.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.