Unit 5 of 12 · about 5 hours · derive, implement
Streaming event state machines, partial output and finish reasons
HTTP success starts a stream; it does not certify an answer. A state machine prevents an early fragment or late error from being mistaken for a completed result.
You'll be able to
- Specify valid transitions from stream start through partial content to one terminal outcome.
- Accumulate text and tool arguments by their provider identifiers while keeping partial validation provisional.
- Classify completion, tool proposal, refusal, truncation, transport loss and cancellation without accepting partial output.
Covers
Read
In this order, only the parts listed
0 of 5 done
- Chat stream chunks and completion reasonsOpenAI API Contracts: Structured Outputs, Function Calling, Streaming and Errors
stream_options.include_usage; streaming example; responsefinish_reasonandrefusalfields (page read 2026-10-18) - Responses is a different stream protocolOpenAI API Contracts: Structured Outputs, Function Calling, Streaming and Errors
Read the responses:
response.created,response.output_text.delta,response.completedanderror(page read 2026-10-18) - Responses terminal statusOpenAI API Contracts: Structured Outputs, Function Calling, Streaming and Errors
Response object:
status,error,incomplete_detailsand refusal content blocks (page read 2026-10-18)Compare the contract with Chat; implementing a hosted Responses client is not required.
- Claude block events and streamed errorsClaude API Contracts: Messages, Stop Reasons, Tools, Streaming and Errors
Event types; Ping events; Error events; Other events; Content block delta types; Full HTTP stream response (page read 2026-10-18)
Use text and tool-input fixtures. Skip thinking and server-tool examples.
- Claude stop reasons are not HTTP errorsClaude API Contracts: Messages, Stop Reasons, Tools, Streaming and Errors
Quick reference; Stop reason values; Streaming considerations (page read 2026-10-18)
Focus on
- Start with states for waiting, receiving, validating and terminal outcomes. Specify which events are legal in each state, including timeout, cancellation and duplicate termination. No accepted result precedes final validation.
- Chat deltas are not complete messages. Tool arguments can span chunks; accumulate by choice and tool index. A final usage chunk can have empty
choices, followed bydata: [DONE]. - Claude has
message_start, indexed content-block start/delta/stop events,message_deltaandmessage_stop. Usage inmessage_deltais cumulative, not an increment to sum. Anerrorcan arrive after HTTP 200. - Preserve raw terminal fields. Chat
stopcan mean a natural stop or a stop sequence;lengthis truncation and refusal is separate. Claude distinguishestool_use,pause_turn,refusaland window exhaustion. Responses usesstatusandincomplete_details, not Chat finish reasons.
Common mistakes · 3
- Parsing an incomplete JSON prefix as if missing fields were final defaults. Partial parsing may support a preview, never an accepted action.
- Treating connection close or HTTP 200 as successful completion. Both can occur with incomplete content.
- Ignoring an unfamiliar semantic event and declaring success. Tolerate harmless extension events, but fail closed when their effect on acceptance is unknown.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A Chat stream chunk has an empty choices array and usage. Is it malformed?Answer
Not when usage streaming was requested. The final usage chunk has that shape; handle it without indexing a choice.
2.Claude reports
pause_turn. Is the user task complete?AnswerNo. A server-tool turn paused. The application may continue it under a new bounded request, but must not label it a final answer.
3.A complete-looking JSON object arrives and then an overload event. Can it be accepted?Answer
No. The provider did not complete successfully. Keep the object as partial diagnostic data, not an accepted answer or executable proposal.
4.Two Claude usage updates report 10 and 15 output tokens. What cumulative count do they establish?Answer
15, not 25. The later cumulative value replaces the earlier one. Missing final usage still leaves the final total uncertain.
You're done when
Every fixture reaches exactly one classified terminal outcome, no partial proposal becomes executable, and a post-200 error cannot enter the success path.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 10 more in the section
- OpenAI API Contracts: Structured Outputs, Function Calling, Streaming and ErrorsOpenAI · required
Read Structured Outputs (
#supported-schemas,#refusals: root must be an object, every field required with a nullable union for optional values,additionalProperties: false), Function calling (#the-tool-calling-flow,#strict-mode,#streaming), the Chatfinish_reasonvalues and Responsesstatusandincomplete_details, the error codes and rate-limit headers, and prompt caching (#how-caching-works, the per-model table). Record fixtures from the documented shapes; no paid calls are needed. - Claude API Contracts: Messages, Stop Reasons, Tools, Streaming and ErrorsAnthropic · required
Read the stop-reason values (
end_turn,max_tokens,stop_sequence,tool_use,pause_turn,refusal,model_context_window_exceeded), Messages (top-levelsystem,tool_useandtool_resultblocks), tool definitions and forcing, structured-output schema limitations (optional properties allowed, no recursion), streaming event types (usage inmessage_deltais cumulative; an error event can follow HTTP 200), the error table (529 overloaded) and prompt-caching usage fields. Translate semantics in your adapter instead of forwarding JSON between providers.
Also in this section
- AI Agents in DepthBojie Li · primary
Read Chapter 1 sections 1.1 and 1.2.4 to 1.2.6 (agent, workflow, harness and guardrail distinctions), then Chapter 2: 2.2.1 to 2.2.5 (message roles and the tool loop), 2.3 KV-cache-friendly context design, 2.4 with 2.4.7 prompt injection, 2.6 and 2.7 (dynamic context and compression). Use the live English edition on the rendered site; the older PDF numbers some sections differently. The book does not cover streaming events, finish reasons or schema subsets, so take those from the provider contracts.
- AI Engineering HandbookHandbook Academy · required
Study Part 2 Working with Model APIs and Part 5 Context Engineering (
/curriculum/context-engineering/): calling models, streaming, structured outputs, function tools, errors, retries, fallbacks, model choice, gateways, prompt caching, context assembly and compression. Skip the transformer overview owned by LLM Foundations. - Effective Context Engineering for AI AgentsAnthropic · required
Study context as a finite resource, just-in-time retrieval, compaction, note taking and context isolation. Convert the advice into explicit selection and truncation policies, then test where each policy loses decisive information.
- Chat Templates and Token AccountingHugging Face; OpenAI · required
Read "Using apply_chat_template" and
add_generation_prompt, then the tools section of the chat extras page. Count the rendered request (roles, separators, system prompt, tool definitions, generation prefix) with the model's own tokenizer, selectinginput_idsfrom the returned encoding. Compare withtiktokenonly as an OpenAI-family reference; it is not a universal counter for local models. - Local OpenAI-Compatible Server: vLLM, llama.cpp or OllamavLLM; ggml-org; Ollama · support
Pick one local server. vLLM 0.31.0: structured outputs (
response_formatjson_schema; the oldguided_*fields were removed in 0.12.0) and tool calling (Qwen uses--tool-call-parser hermeswith--enable-auto-tool-choice). On CPU use llama.cppllama-server(--json-schema, grammars) or Ollama (formatwith a JSON schema). Pin the server version and model revision, and test the exact wire shapes your adapter accepts. - Pydantic Strict Mode, Extra Data and Discriminated UnionsPydantic · support
Read strict mode,
ConfigDict(extra="forbid"), discriminated unions and JSON Schema generation. A generated schema leaves defaulted fields out ofrequiredand emits a rootoneOffor a union, so it is not an OpenAI strict schema as is: adapt the wire schema explicitly and keep the model as the final validator. Never pass untrusted tool arguments throughmodel_construct. - Timeouts, Retries, and Backoff with JitterAmazon Builders' Library · support
Read "Timeouts", "Retries and backoff" and "Jitter". A timeout does not mean the work did not happen; retry at one layer only. The five-layer example uses three tries per layer, so the amplification is
3**5 = 243; state attempts and retries explicitly in your own budget. - AlgoMaster AI EngineeringAlgoMaster · support
Read the free lessons
making-your-first-llm-api-call(the error table and the retry wrapper that skips permanent errors),understanding-llm-parameters,structured-output-from-llmsandtype-hints-and-pydantic; the owned premium lessonsstreaming-and-conversation-management,context-engineeringandthe-ai-gateway-patternextend them. The course calls a hosted router: point the clientbase_urland model at your local server instead, and keep this stage's stricter versioning, replay and fault checks. - The Hitchhiker's Guide to Agentic AIHaggai Roitman · support
Use v3 Chapter 18: 18.2 context management (18.2.6 token counting and budget monitoring), 18.3 prompt architecture, 18.4.1 (the OpenAI and Anthropic tool schemas side by side), 18.4.3 error normalization and retry, 18.7.1 backoff with jitter. It is a breadth audit of the gateway after it works, not a contract reference.
- JSON Schema LearnJSON Schema Project · reference
Read the object reference sections on
additionalProperties,requiredand extending closed schemas (unevaluatedProperties), and Validation 6.5.3 in the 2020-12 specification:propertiesdoes not require keys,requireddoes not forbid null, and closing one subschema does not close a composed one. Check payloads withjsonschema(Draft202012Validator,iter_errors) and keep the full domain schema as the final validator even when a provider accepts only a subset.