Unit 7 of 12 · about 5 hours · implement

Provider and local-model adapters behind one narrow gateway interface

Compatible JSON shapes do not imply compatible behavior. An adapter earns its place by exposing differences instead of hiding them behind a string-returning helper.

You'll be able to

  • Implement a narrow gateway interface with provider-specific request translation and normalized outcomes.
  • Preserve raw provider semantics alongside normalized usage, stop classification and capability failures.
  • Test the local OpenAI-compatible adapter without requiring hosted credentials.

Covers

Provider and local-model adapters behind one narrow interface
1

Read

In this order, only the parts listed

0 of 5 done

  1. One gateway, explicit backendsAI Engineering Handbook

    The pattern: one endpoint, many backends (page read 2026-10-18)

    Stop before Cheap-then-expensive. Build a library boundary, not a proxy fleet. Self-hosting the gateway does not keep data local if its backend is hosted.

  2. OpenAI usage and tool outcomesOpenAI API Contracts: Structured Outputs, Function Calling, Streaming and Errors

    Response message.tool_calls, refusal, finish_reason and usage; compare inclusive input accounting under https://developers.openai.com/api/docs/guides/prompt-caching (pages read 2026-10-18)

  3. Claude usage categories are disjointClaude API Contracts: Messages, Stop Reasons, Tools, Streaming and Errors

    Tracking cache performance; FAQ, How do I calculate total input tokens from the usage fields? (page read 2026-10-18)

    Read the usage fields only; cache layout and model-specific limits come later. Reuse the Messages and stop-reason contracts already read.

  4. vLLM's structured-output wire contractLocal OpenAI-Compatible Server: vLLM, llama.cpp or Ollama

    vLLM 0.31.0, Online Serving (OpenAI API), especially response_format with json_schema

    Skip offline inference and automatic SDK parsing. For tool support inspect Named Function Calling and Qwen Models at https://docs.vllm.ai/en/v0.31.0/features/tool_calling/.

  5. CPU local-server alternativeLocal OpenAI-Compatible Server: vLLM, llama.cpp or Ollama

    Build; Quick Start; API Endpoints, OpenAI-compatible chat completions (page read 2026-10-18)

    Choose this instead of vLLM when using CPU. Pin the selected llama.cpp build and a small quantized model revision; do not enable built-in effect tools. Fakes alone can run every contract check.

2

Focus on

  • Reuse the Programming unit on typed interfaces. Define one request and a tagged outcome for answer, tool proposal, refusal, truncation, failure and cancellation; carry usage and request identity separately from answer text.
  • Give each adapter a capability record for roles, schema subset, controls, stream events and usage. Reject unsupported requests explicitly. Preserve raw fields in access-controlled, redacted diagnostics.
  • OpenAI input totals already include cached input. Claude totals require adding input_tokens, cache_creation_input_tokens and cache_read_input_tokens. Keep cache categories without counting them twice.
  • Classify a local tool proposal from its payload as well as its finish reason. Include a compatibility fixture with tool_calls present and finish_reason: 'stop'; do not silently turn it into a final text answer.
Common mistakes · 3
  • A helper that returns only text discards refusals, tool proposals, incomplete output and unknown usage.
  • Assuming OpenAI-compatible means complete OpenAI behavior. Test the endpoint, parser, model and server version together.
  • Using the removed vLLM guided_json fields. In 0.31.0 use response_format or structured_outputs, and retain independent final validation.
3

Try it yourself

Closed-book, before checking anything

Closed-book, send one internal request through OpenAI Chat, Claude Messages and local-server fixture adapters. Require equivalent internal outcomes while retaining different wire fields. Normalize synthetic OpenAI input total 1,000 with 700 cached, and Claude input 100 plus cache creation 200 plus cache reads 700: both totals are 1,000, but their cache categories differ. Run the same adapter against your local model if available, recording the server, checkpoint and template; use fakes when no model fits your machine.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Should the domain layer import provider response classes?Answer

    No. Keep them in the adapters. The domain consumes normalized outcomes and can inspect a controlled diagnostic reference when needed.

  2. 2.Why is adding cached tokens to OpenAI's input total wrong?Answer

    The cached count is already a breakdown of that total. Adding it again double-counts input. Claude's input field uses a different convention.

  3. 3.A local reply contains a valid tool call but says stop. What should your adapter do?Answer

    Apply its declared local compatibility rule, preserve the raw reason, and return a validated tool proposal rather than a completed text answer. It still must not execute the tool.

You're done when

All adapters pass the same outcome suite, the tool-with-stop fixture remains a proposal, and normalized usage totals agree without losing provider categories.

Only when you can do this without notes.

Leads to

Notes

Resources · 4 for this unit, 8 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.

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

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

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

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.

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

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