Unit 4 of 12 · about 5 hours · implement
Structured output and tool-request schemas with strict and domain validation
Parseable JSON is not a valid business result. The gateway must validate both the shape the provider promises and the constraints your workflow actually needs.
You'll be able to
- Compile a domain contract into each provider's supported generation schema without weakening final validation.
- Reject missing fields, coercions, extra keys and domain-invalid values before accepting an answer or tool proposal.
- Distinguish schema failure from refusal and truncated generation.
Covers
Read
In this order, only the parts listed
0 of 5 done
- OpenAI strict structured outputsOpenAI API Contracts: Structured Outputs, Function Calling, Streaming and Errors
Supported schemas: root objects, required fields, closed objects, unsupported composition, definitions and recursion; Refusals with Structured Outputs (page read 2026-10-18)
- Claude's different schema subsetClaude API Contracts: Messages, Stop Reasons, Tools, Streaming and Errors
How SDK transformation works; JSON Schema limitations; Property ordering; Invalid outputs (page read 2026-10-18)
- Presence, null and closed objectsJSON Schema Learn
Additional Properties; Extending Closed Schemas; Required Properties (page read 2026-10-18)
Apply JSON Schema 2020-12 with jsonschema 4.26.0. Review only the absent/null and composition cases not settled by the Programming unit on typed interfaces and runtime validation.
- Strict validation and generated schemasPydantic Strict Mode, Extra Data and Discriminated Unions
Generating JSON Schema, especially the defaulted nullable fields; pair with Strict Mode, As a configuration value, at https://pydantic.dev/docs/validation/latest/concepts/strict_mode/ (pages read 2026-10-18)
Use Pydantic 2.14.1. Keep the domain model strict with forbidden extra fields; inspect the actual generated wire schema rather than assuming provider compatibility.
- Tool parameters have a generation contract tooOpenAI API Contracts: Structured Outputs, Function Calling, Streaming and Errors
Strict mode (page read 2026-10-18)
Focus on
- OpenAI strict schemas require an object root, every property in
requiredandadditionalProperties: falseon every object. A required nullable value is not an absent property. - Claude permits optional properties but not recursive schemas or numeric and string-length constraints in the generation schema. OpenAI supports recursion. Date and retain a capability matrix instead of assuming one universal subset.
- Keep three checks distinct: provider schema admission, strict payload validation and domain validation. Schema-valid tool arguments are still proposals, not permission to act.
- Pydantic 2.14.1 leaves a defaulted
note: str | None = Noneoutsiderequired. Its generated schema therefore needs explicit adaptation for OpenAI strict mode.
Common mistakes · 3
- Taking the provider pages' opening 'always valid' wording literally. Refusals and length cutoffs still need separate handling, and valid fields can contain wrong facts.
- Deleting unsupported constraints from both the wire schema and your final validator. Only the generation subset should lose them.
- Using
model_constructon model-generated arguments. It bypasses validation.
Try it yourself
Closed-book, before checking anything
model_config = ConfigDict(strict=True, extra='forbid'), required n: int and note: str | None = None. Validate {}, {'n': '1'}, {'n': 1, 'extra': True} and {'n': 1, 'note': None}. Get missing, int_type, extra_forbidden and success respectively. Check its generated schema independently with jsonschema 4.26.0, then adapt a copy to require the nullable note for OpenAI. Add a separate positive-value domain check that rejects {'n': -1} even though its shape is valid.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.If a string-or-null field is required, does omitting it mean null?Answer
No. Presence and value type are separate constraints. An omitted required key fails; an explicit null passes only if the field permits null.
2.Why retain a numeric domain bound when the provider cannot enforce it?Answer
Generation constraints and acceptance constraints are different. The gateway must reject out-of-domain values even when they satisfy the provider's simpler schema.
3.A valid tool payload names another tenant's resource. May it execute?Answer
Not on schema validity alone. The effect-owning code must check the authenticated principal, tenant, resource and action.
You're done when
Your tests distinguish absent, null, coerced, extra and domain-invalid values, and no refused or truncated response reaches the accepted-result path.
Only when you can do this without notes.
Leads to
Notes
Resources · 4 for this unit, 8 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. - 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. - 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.
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. - 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.