Part III · Building and operating AI/Chapter 11 of 20/8 min read

The Model Harness and Routing

How context infrastructure, tool contracts, trace debugging, caching and model routing turn raw models into dependable products.

A model harness connects context, tools, permissions, memory, evaluation and optional routing paths.
A model harness connects context, tools, permissions, memory, evaluation and optional routing paths.Plate 11
On this page6 sections
  1. 01Map the seven layers of a harness
  2. 02Debug failures systematically with traces
  3. 03Treat context as maintained infrastructure
  4. 04Write ironclad tool contracts (especially for retries)
  5. 05Route, cache and fall back only when measured
  6. 06Try it: inspect an incomplete trace

Swap a flagship model for a competitor's flagship inside a weak system and almost nothing improves. Put a well-engineered harness around a mid-tier model and it will routinely outperform a raw frontier model at a fraction of the cost and latency.

The harness is everything around the model that turns token generation into a reliable product: context assembly, tool execution, permission enforcement, state management, observability and routing. Product managers do not write every line of harness code, yet most product quality, cost and trust decisions live directly inside it.

(If tokens, retrieval and tool calling are unfamiliar, start with How Models Fit Into a Product.)

Map the seven layers of a harness

FIG 11.1The Seven-Layer Model Harness
THE MODEL HARNESS (PRODUCT & ENGINEERING CONTROL PLANE)CONTEXT & SKILLSAuthoritative docs, MCP, versioned proceduresTOOLS & IDEMPOTENCYTyped schemas, timeouts, read-before-retryPERMISSIONS IN CODETenant scope, spend caps, approval gatesCOREFoundationModelSTATE & MEMORYEphemeral task scratchpad vs scoped prefsROUTING & CACHINGPrompt cache, fast vs reasoning tiers, fallbackTRACES & EVALSChronological logs, slices, regression gates
The foundation model sits inside six engineering and product layers. Most reliability, security and cost wins come from the harness rather than swapping models.
Harness layerJob in the systemKey product decision
ModelReasoning, synthesis, classification, tool selectionWhich quality, latency and privacy constraints matter most for this step?
ContextInstructions, reusable skills, retrieved records, conversation historyWhich sources are authoritative, fresh and trimmed to fit cleanly?
ToolsStructured read/write interfaces to databases, APIs and external systemsWhat exact inputs, outputs, timeouts and failure contracts does each tool expose?
PermissionsAuth, tenant scoping, action caps and approval gatesWhose identity executes the action, and what is blocked unconditionally in code?
State & memoryShort-term task state vs durable user/org preferencesWhat persists across turns or sessions, who can edit it and when does it expire?
ExecutionOrchestration runtime, retries, budgets, rate limits, fallbacksWhat caps total runtime, tool calls and spend per request?
ObservabilityTraces, inputs, tool logs, latency, token spend, user feedbackCan the team reconstruct why a bad output happened in under five minutes?

Every layer is a product lever. A slow user experience might be a missing streaming layer rather than a slow model; a wrong policy answer is far more often a stale source or a broken retrieval query than weak reasoning.

Debug failures systematically with traces

A trace is the complete chronological record of a single run: exact prompt assembled, retrieved passages with scores, model calls, tool requests and responses, latency per step and final rendered output.

Suppose a workplace policy assistant tells an employee the wrong parental-leave entitlement and cites last year's handbook. Walk the trace in four strict steps before changing a single prompt word:

Execution traceWrong parental-leave policy answer
  1. STEP 01CHECK

    Source corpus check

    2026 policy exists in SharePoint, yet the 2025 PDF was never archived.

    stale doc
  2. STEP 02FAIL

    Hybrid retrieval

    Top chunk returned 2025 PDF (score 0.89) ahead of 2026 policy (0.84).

    180 ms
  3. STEP 03OK

    Model synthesis

    Model faithfully summarised the outdated chunk it was handed.

    920 ms
  4. STEP 04CHECK

    UI presentation

    Citation omitted document effective date, hiding the mismatch from the user.

    UX gap
  1. Check the source of truth: Does the current policy actually exist in the indexed corpus, and was the deprecated version archived? If the source repository itself is stale, fix the content ownership process first.
  2. Check retrieval: Did the search step return the current policy in its top results? Inspect the exact query generated, the returned chunk scores, metadata filters and document dates. Poor ranking, broken chunking or overly broad queries show up immediately here.
  3. Check model interpretation: If the current policy reached the model cleanly, did the prompt or conflicting retrieved chunks confuse it? Replay the exact input in an isolated test with only the right passage to verify whether the issue is instruction clarity or model capability.
  4. Check presentation and recovery: Did the UI surface the document date and clickable passage so the employee could spot the mismatch and flag it?

Change one variable at a time and re-run the affected cases alongside your regression suite. If your traces do not record the actual search query and retrieved passages, adding observability is step one before any prompt tuning.

Treat context as maintained infrastructure

Most teams treat context as an afterthought, pasting instructions into prompts and pointing retrieval at a messy company wiki. That works until agents scale beyond a prototype.

Reliable systems treat context as shared, maintained infrastructure across three distinct buckets:

  • Static and shared knowledge: Current policies, product specs, playbooks and domain rules, each with an explicit source of truth, freshness date and owner. Standardised context and tool interfaces such as MCP (Model Context Protocol) let multiple agents and tools read from the same governed systems of record instead of maintaining brittle one-off connectors.
  • Reusable skills and procedures: Versioned instruction modules defining repeatable team standards (how to grade a lead, format a release brief or triage an incident), reviewed and updated like code rather than trapped in private chat histories.
  • Scoped state and memory: Separate ephemeral working state (active task scratchpad) from durable memory (user preferences, account settings). Durable memory needs explicit correction and expiry rules; stale preferences silently poison future runs.

Write ironclad tool contracts (especially for retries)

Every tool exposed to a model needs a strict contract in code: validated input schemas, scoped permissions, explicit error messages the model can act on, hard timeouts and clear handling for partial completion.

Pay special attention to timeouts and idempotency, one of the sharpest operational traps in agent harnesses. Suppose an agent calls a create_refund or book_appointment tool, and the downstream API succeeds right before a network timeout returns an error to the harness. If the harness blindly retries, the customer gets refunded or booked twice.

Prevent duplicates in the harness layer, never via prompt instructions:

  • Attach a deterministic idempotency key (tied to the originating task/request ID) to every write tool call so duplicate requests safely return the original result.
  • Where a third-party API lacks idempotency, require a read-before-retry check (lookup_booking before retrying create_booking) or halt and surface the uncertain state for human confirmation.
  • Cap retries, wall-clock runtime and tool-call counts per task, and log every attempted and executed write call for auditability.

Route, cache and fall back only when measured

A task branches through a routing layer to specialised models and tools before evaluation.

A routing layer directs each task (or sub-step) to a different model or execution path based on complexity, latency, privacy or cost. Done well, routing cuts inference bills and p95 latency dramatically. Done prematurely, it adds classification bugs, extra network hops and multiple model behaviours to evaluate and maintain.

Start with a single capable model that clears your quality bar, then introduce optimisations in order of payoff:

  1. Prompt caching first: Before splitting traffic across models, cache stable prefixes (system instructions, tool definitions, shared policy context). Caching cuts input cost and time-to-first-token significantly with near-zero architectural risk.
  2. Task-level model tiering: Assign different models to clearly distinct pipeline steps by design rather than runtime guessing. Use fast, low-cost models for structured extraction, intent classification and simple formatting; reserve larger reasoning models for ambiguous synthesis, planning and complex exception resolution.
  3. Dynamic routing when volume warrants it: Use a lightweight classifier or explicit heuristic (input length, account tier, confidence/validation failure) to start on a fast model and escalate only hard cases to a heavier model. Measure router misclassification cost alongside token savings; a router that misroutes 10% of hard cases to a weak model destroys quality faster than it saves money.
  4. Provider fallback chains: For high-availability workflows, configure automatic failover to a secondary model or region when primary latency spikes or rate limits trip. Always benchmark fallback models against your eval suite beforehand; a fallback that stays online while silently breaking JSON schemas or safety boundaries is worse than an honest outage message.

Keep model-specific quirks (system prompt syntax, reasoning parameters, tool-call quirks) behind a clean abstraction layer, without falling for the myth that models are drop-in interchangeable. Switching models always requires re-running your evaluation suite and re-checking unit economics before traffic flips.

Try it: inspect an incomplete trace

A workplace assistant answers a question about customer return windows and cites a policy dated fourteen months ago. The trace shows only that retrieval returned three chunks, one was passed to the model and the call succeeded in 1.4 seconds. It does not log the search query, the two discarded chunks or when the knowledge index last synced.

Before proposing a fix, write down:

  1. Three distinct root causes consistent with this incomplete trace (for example: stale index sync, outdated document outranking the new one in search, or a prompt truncating chunks two and three).
  2. The exact three log fields you would add to the trace so the next occurrence isolates the cause immediately.
  3. The smallest controlled test you would run with an engineer before changing the prompt or swapping models.

Good harness debugging starts by resisting the urge to guess when the trace cannot yet prove what happened.

Handbook v4.0 · Ch. 11Updated Nov 2026