Unit 11 of 12 · about 5 hours · implement

Deterministic fake models and secret-free replay manifests

A live model is a poor oracle for a cancellation bug. Scripted outcomes isolate gateway behavior, while a bounded manifest explains which parts of a past request can actually be reconstructed.

You'll be able to

  • Implement a scripted fake model and fake clock behind the same gateway interface as the local adapter.
  • Replay normalized outcomes and stream faults without network access or live generation.
  • Export a secret-free manifest that distinguishes exact synthetic replay from incomplete production diagnosis.

Covers

Deterministic fake models for success, refusal, invalid schema, timeout and partial streamsReplayable request, response and context manifests with secrets removed
1

Read

In this order, only the parts listed

0 of 3 done

  1. Separate deterministic assembly from model behaviorAI Engineering Handbook

    Two layers, two test strategies; Snapshot the assembled messages, nothing more; Property tests catch what hashes miss; Pin the prompt version on every span (page read 2026-10-18)

    Use canned sources and the existing gateway interface. Replace the example's text-only token counter with rendered accounting. Do not adopt its generic role-alternation rule; provider message contracts differ.

  2. A documented stream for offline fault fixturesClaude API Contracts: Messages, Stop Reasons, Tools, Streaming and Errors

    Full HTTP stream response; Error events; Input JSON delta (page read 2026-10-18)

    Reuse the stream accumulator already built. Transcribe synthetic text and tool-input fixtures from these shapes; do not make a hosted call.

  3. Content capture is a separate policy decisionAI Engineering Handbook

    In production, capture what the model actually saw; The loop, end to end (page read 2026-10-18)

    Skip telemetry SDKs and hosted backends. Do not follow the suggestion to enable content capture casually in staging; synthetic data, access control and retention rules still apply.

2

Focus on

  • The fake implements the real gateway protocol, including usage, terminal tags and streamed events. Match expected requests and fail on an unexpected send or an exhausted script instead of returning a default answer.
  • Inject time, waiting and scripted faults. Verify attempt order, deadline and cancellation without real sleeps. Keep normalized-outcome fixtures separate from provider-wire fixtures so normalization is tested too.
  • A replay manifest binds code, model, tokenizer, template, prompt, schema, source revisions, compiler policy, controls, budgets and ordered attempts. Record redaction policy, fixture digests and unavailable fields explicitly.
  • Commit only synthetic payloads and safe metadata. Redacted production content cannot promise byte-exact reconstruction; record that limitation. A hash is an identity check, not encryption, anonymization or authorization to fetch a private source.
Common mistakes · 3
  • Testing only the fake's return values. Independently assert the request sent, the accepted-result boundary and the number of actual attempts.
  • A fake that repairs malformed inputs or automatically invents missing terminal events. It can hide the exact adapter bug the suite should reveal.
  • Calling a production trace replayable when source text was redacted, deleted or changed. Preserve the limitation rather than restoring private text from an unauthorized store.
3

Try it yourself

Closed-book, before checking anything

Closed-book, script success, refusal, malformed JSON, a cut stream, timeout, cancellation and a prompt-version mismatch through the same gateway. Replay the synthetic requests with a fake clock and no network; require identical normalized outcomes, attempt order and request digests. Mutate a prompt or fixture byte and require a manifest mismatch rather than silently accepting the new input. Export the manifest with a synthetic secret canary in a forbidden field, and independently scan the serialized export and diagnostics to confirm the canary is absent.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.What should a scripted fake do when the gateway sends an unexpected second request?Answer

    Fail the test with safe request identity and sequence information. A default success would hide an unintended retry.

  2. 2.Does exact fake replay prove the local model will answer correctly?Answer

    No. It proves gateway behavior for the scripted inputs and outcomes. Local-model integration and task-quality evaluation are separate evidence.

  3. 3.Can a source digest reconstruct deleted content?Answer

    No. It can check the identity of content you already have lawful access to. It neither contains the content nor grants access to it.

You're done when

All seven scripted cases replay offline, an unexpected send or changed fixture fails explicitly, and the export contains enough safe identity to explain both successful replay and redaction-limited cases.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 10 more in the section
  • 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.

  • 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-level system, tool_use and tool_result blocks), tool definitions and forcing, structured-output schema limitations (optional properties allowed, no recursion), streaming event types (usage in message_delta is 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.

  • 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.

  • 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 Chat finish_reason values and Responses status and incomplete_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.

  • 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, selecting input_ids from the returned encoding. Compare with tiktoken only 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_format json_schema; the old guided_* fields were removed in 0.12.0) and tool calling (Qwen uses --tool-call-parser hermes with --enable-auto-tool-choice). On CPU use llama.cpp llama-server (--json-schema, grammars) or Ollama (format with 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 of required and emits a root oneOf for 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 through model_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-llms and type-hints-and-pydantic; the owned premium lessons streaming-and-conversation-management, context-engineering and the-ai-gateway-pattern extend them. The course calls a hosted router: point the client base_url and 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, required and extending closed schemas (unevaluatedProperties), and Validation 6.5.3 in the 2020-12 specification: properties does not require keys, required does not forbid null, and closing one subschema does not close a composed one. Check payloads with jsonschema (Draft202012Validator, iter_errors) and keep the full domain schema as the final validator even when a provider accepts only a subset.