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

On this page6 sections
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
| Harness layer | Job in the system | Key product decision |
|---|---|---|
| Model | Reasoning, synthesis, classification, tool selection | Which quality, latency and privacy constraints matter most for this step? |
| Context | Instructions, reusable skills, retrieved records, conversation history | Which sources are authoritative, fresh and trimmed to fit cleanly? |
| Tools | Structured read/write interfaces to databases, APIs and external systems | What exact inputs, outputs, timeouts and failure contracts does each tool expose? |
| Permissions | Auth, tenant scoping, action caps and approval gates | Whose identity executes the action, and what is blocked unconditionally in code? |
| State & memory | Short-term task state vs durable user/org preferences | What persists across turns or sessions, who can edit it and when does it expire? |
| Execution | Orchestration runtime, retries, budgets, rate limits, fallbacks | What caps total runtime, tool calls and spend per request? |
| Observability | Traces, inputs, tool logs, latency, token spend, user feedback | Can 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:
- STEP 01CHECKstale doc
Source corpus check
2026 policy exists in SharePoint, yet the 2025 PDF was never archived.
- STEP 02FAIL180 ms
Hybrid retrieval
Top chunk returned 2025 PDF (score 0.89) ahead of 2026 policy (0.84).
- STEP 03OK920 ms
Model synthesis
Model faithfully summarised the outdated chunk it was handed.
- STEP 04CHECKUX gap
UI presentation
Citation omitted document effective date, hiding the mismatch from the user.
- 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.
- 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.
- 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.
- 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_bookingbefore retryingcreate_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 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:
- 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.
- 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.
- 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.
- 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:
- 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).
- The exact three log fields you would add to the trace so the next occurrence isolates the cause immediately.
- 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.