Model and Context Contracts
A model call is an unreliable dependency with probabilistic behavior. This stage makes requests, streams, refusals, context selection, privacy and failure behavior typed, versioned and replayable before any retrieval or agent loop is added.
Section 1 of 8 · 12 units · about 52 hours
By the end you can Build a typed model gateway and versioned context compiler, then replay success, refusal, malformed output, partial stream, timeout, cancellation and version-drift cases while tracing every retained token to an authorized source.
Units
- Model, context, orchestration and policy owners, and message roles around untrusted data3h
- Model, snapshot, template and prompt identity, with changelogs and rollback4h
- Sampling controls and request budgets for context, output, latency and cost3h
- Structured output and tool-request schemas with strict and domain validation5h
- Streaming event state machines, partial output and finish reasons5h
- Normalized model errors, bounded retries, deadlines and cancellation5h
- Provider and local-model adapters behind one narrow gateway interface5h
- A context compiler with authorized sources, provenance, selection and ordering4h
- Token accounting, explicit truncation policy and conversation compaction5h
- Redaction, retention and tenant scope in context, and cache-safe prefix layout4h
- Deterministic fake models and secret-free replay manifests5h
- Locked-evaluation comparison of interface and context variants4h
Build it
Mini project · about 14 to 18 hours
Typed gateway with authorized context and deterministic replay
Create agentlab around a bounded permissioned-document workflow that will later propose approved actions. Build a typed gateway and context compiler whose contracts, authority boundaries and failures are testable without generation. Use Python and the section's pinned libraries, deterministic fakes or your small open local model, without paid APIs.
- 1Create
agentlabwithgateway/,context/,fakes/,evals/,corpus/,retrieval/,tools/,workflow/,agent/,security/,ops/,extension/,tests/andreports/. Map ownership; check OpenAI Chat and Claude Messages fixtures against documented roles and tool linkage. Retain an injected-document denial proving text cannot change tenant authority. - 2Implement the typed gateway with provider-wire, local-compatible and scripted fake adapters. Check paired wire schemas against documented provider subsets and strict Pydantic validation against jsonschema; retain capability, schema/domain rejection and usage-normalization matrices, including local tool proposals with a stop finish reason.
- 3Implement stream transitions and normalized errors with a fake clock. Check documented events against an independent transition table; retain partial-stream, refusal, truncation, post-success-status error, duplicate-terminal and cancellation regressions. Test admission, actual sends and shared attempt, rendered-token, deadline and synthetic-spend budgets at every retry boundary.
- 4Version immutable request bundles, prompt changelogs and the context compiler's authorized source registry. Check rendered snapshots, shuffled-source ordering and rollback against reviewed fixtures; retain selection provenance, stale/revoked-source denials and version-drift failures, with prompt, schema, model, tokenizer and template identities bound together.
- 5Measure complete rendered tokens against the pinned tokenizer's chat-template encoding before generation. Retain content-only comparisons, omission manifests and overflow regressions; check atomic tool exchanges and decisive-fact compaction against original typed constraints rather than trusting a shorter summary.
- 6Enforce tenant scope, redaction and retention across context, summaries, application caches, errors, traces and replay exports. Check synthetic canaries and fake-clock expiry/revocation against an independent sink scan; retain derived-summary invalidation and shared-prefix token comparisons, distinguishing prefix eligibility from measured cache hits.
- 7Export version-bound synthetic replay manifests; reject unexpected sends and fixture drift offline. After contract/privacy gates, compare a context variant with fixed cases, scorer and budgets across repeated paired trials; retain failures, attempts, tokens and timings. Optionally smoke-test your local OpenAI-compatible server; label fake-only quality/speed unmeasured.
What you hand in
- Typed
gateway/, versionedcontext/compiler and ownership map with provider, local and fake contracts. - Synthetic fault, authorization, privacy, token-accounting and rollback regressions with secret-free replay manifests in
fakes/andtests/. - Locked baseline/variant evidence in
reports/, including paired failures, resource ledgers, decision and fake-only limitations.
How to check it
- Self-grade with the rubric below
How it's graded
Gateway acceptance boundary
Pass: Your documented-wire fixtures and independent schema checks validate adapter outcomes, usage and rejection rules. Transition-table and fake-clock tests reject partial acceptance and bound actual sends, deadline and spend.
Great: Planted normalization, nested-retry and premature-acceptance defects fail their intended checks; cancellation closes reception and prevents subsequent sends without claiming remote computation stopped.
Context and authority
Pass: Your independent source and sink assertions verify stable authorized selection, rendered token counts, omissions, complete tool exchanges, decisive constraints, tenant isolation and expiry/revocation across derived artifacts.
Great: Changing source arrival order preserves assembly; planted summary, prefix and omission defects fail without allowing model text to alter authority. Residual free-text privacy risks are stated.
Identity and comparison
Pass: Your rollback and offline replay tests restore reviewed requests and reject drift. Fixed-case paired comparisons preserve scorer and budgets, failed trials and privacy gates, distinguishing real measurements from fake accounting.
Great: A fresh replay reconstructs each attempt and decision from safe manifests; negative or inconclusive results remain visible, with unknown usage and redaction-limited reconstruction explicitly distinguished.
Resources
- AI Agents in DepthBojie Li
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
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
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.
- OpenAI API Contracts: Structured Outputs, Function Calling, Streaming and ErrorsOpenAI
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
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. - Chat Templates and Token AccountingHugging Face; OpenAI
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
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
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
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
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
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
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.