The Workhorse LLM in the Multi-Agent Era: Model Selection, Evaluation, and Token Efficiency Practices

    As AI applications move from single-turn chat to multi-step execution, the model that runs most production traffic — the "workhorse" model — sets both the cost baseline and the quality baseline of an AI platform. This article explains what capabilities a workhorse model needs, how to evaluate it with public benchmarks plus your own dataset, why token efficiency matters more than output length, which engineering techniques actually reduce token cost, and how to route, budget, and govern models in multi-agent systems. It includes a cost model that shows why input tokens grow quadratically with the number of rounds, a reusable evaluation harness, context-compression and budget-control patterns, a task-routing strategy, and a pre-launch checklist.

    Introduction: Why the model that “does the work” became AI infrastructure

    LLM product lines usually form a pyramid:

    • At the top are flagship models: the highest capability ceiling, the highest unit cost.
    • At the bottom are lightweight models: low latency, low price, suited to batch and structured tasks.
    • In the middle sits the workhorse model: strong all-round ability and efficient reasoning, built to absorb the high-frequency everyday workload.

    Once AI applications moved from single-turn Q&A to multi-step execution, call volume rose sharply — and most of the cost landed on this middle tier. In code generation, knowledge work, and multi-agent collaboration, the workhorse model often runs continuously for minutes or longer, carrying a large context on every turn. That is why the industry now cares less about raw capability and more about cost per successful task and stability on long-running tasks.

    This article covers five questions:

    1. What capabilities should a workhorse model have?
    2. How do you evaluate it with objective benchmarks and your own data?
    3. Why does token efficiency matter?
    4. How can engineering optimize token cost?
    5. How do you architect and govern models in multi-agent scenarios?

    1. What Is a “Workhorse Model”?

    “Workhorse model” is not an official technical term. It is industry shorthand for a model’s positioning: the model that handles the most common, highest-frequency tasks in production. The tiers around it each have a distinct job:

    Model tier Typical characteristics Suited tasks
    Flagship Strongest complex reasoning and multi-step planning; high cost per call Architecture design, hard problem analysis, long-horizon planning
    Workhorse Strong all-round ability, concise output, low cost per task Code generation and repair, knowledge Q&A, multi-step tool calls
    Lightweight / high throughput Low latency, low unit price, good for batch calls Text classification, information extraction, format conversion
    Vertical / specialized Tuned for a specific domain Vulnerability detection, compliance review, domain Q&A

    For an agent platform running a million tasks a month, the workhorse model determines the overall cost baseline and the quality baseline. And when that tier is upgraded, both baselines move.

    Recent public information about a workhorse-tier upgrade reports gains across four areas: coding, machine learning experimentation, computer use, and general capability.

    Evaluation dimension Previous-generation workhorse New-generation workhorse Improvement
    Code generation and repair (code benchmarks) 37% 49% +12pp
    Machine learning experimentation (ML engineering benchmarks) 49.7% 63.9% +14.2pp
    Computer use (computer-use benchmarks) 78.4% 83.0% +4.6pp
    General capability (composite score, 100-point scale) 1349 1421 +72 points

    Two things to keep in mind:

    • “pp” means percentage points — an absolute difference, not a relative gain. A +12pp change corresponds to a relative increase of roughly 32%.
    • The benchmark names above have been generalized. Refer to the publisher’s public information for full names and evaluation protocols.

    More interesting is the token efficiency improvement reported alongside those numbers:

    • On general capability evaluations, output tokens dropped by about 17% on average versus the previous generation.
    • In the code-generation-specific evaluation, output tokens fell by up to about 65%.
    • With fewer reasoning steps and fewer tool calls, the number of calls needed to complete the same task also went down.

    In other words: think a little less, call a few fewer times, say a few fewer words — and cost drops directly without sacrificing task quality.


    2. What a Workhorse Upgrade Actually Changes: From a Capability Curve to a Cost Curve

    When people evaluated models in the past, they usually focused on the ceiling: can the model solve the hardest problem? The real significance of a workhorse upgrade is that it pushes the entire capability–cost curve outward.

    You can idealize the problem as a straight line:

    1. C = a + b × L
    2. C: total cost of completing one task
    3. L: task complexity
    4. a: fixed per-round overhead (system prompt, tool specs, etc.)
    5. b: marginal per-round overhead (retrieved content, conversation history, tool results, etc.)

    The previous generation could reliably complete tasks up to a complexity of roughly Lmax_old; the new generation reaches Lmax_new. Because the whole curve shifts outward, a more capable model typically needs fewer rounds and shorter contexts at the same L, so both a and b shrink. Teams can take on more complex tasks with the same budget, or finish existing tasks with less.

    Example 1: Comparing task complexity against cost (illustrative; the interface is fictional)

    1. # Illustrative code: a unified inference service interface
    2. client = InferenceClient(base_url="https://your-gateway.example.com", api_key=API_KEY)
    3. def run_task(model, complexity):
    4. """Simulate one multi-step task at a given complexity (a real system is driven by an agent loop)."""
    5. total = {"input_tokens": 0, "output_tokens": 0, "steps": 0, "success": False}
    6. history = []
    7. for step in range(complexity * 2 + 1): # rounds grow with complexity
    8. # Each round carries the system prompt, prior history, tool specs and tool results
    9. ctx = SYSTEM_PROMPT + TOOL_SPECS + "".join(history)
    10. resp = client.chat(
    11. model=model,
    12. messages=[{"role": "user", "content": f"Step {step}: continue the task"}],
    13. system=ctx,
    14. max_output_tokens=2048,
    15. )
    16. total["input_tokens"] += resp.usage.input_tokens
    17. total["output_tokens"] += resp.usage.output_tokens
    18. total["steps"] += 1
    19. history.append(resp.text)
    20. if resp.text.strip().endswith("[DONE]"):
    21. total["success"] = True
    22. break
    23. return total
    24. MODEL_COST = {"workhorse-v1": 1.0, "workhorse-v2": 1.0} # cost per million tokens; identical here
    25. for L in [2, 4, 6, 8]:
    26. row = [f"L={L}"]
    27. for m in ["workhorse-v1", "workhorse-v2"]:
    28. r = run_task(m, L)
    29. tokens = r["input_tokens"] + r["output_tokens"]
    30. row.append(f"{m}: {r['steps']} rounds / {tokens} tokens"
    31. + ("" if r["success"] else " (incomplete)"))
    32. print(" | ".join(row))

    This toy model only illustrates the trend; it is not real product data:

    • L=2, L=4 (simple tasks): the newer generation reasons more concisely and needs fewer rounds, so cost per task is lower.
    • L=6 (medium tasks): both generations can finish, and the newer one still costs less.
    • L=8 (hard tasks): the previous generation exceeds the ceiling of the current strategy and ends in failure. Failure does not mean no tokens were spent — on the contrary, wasted attempts are billed too.
    • The new generation: with a smaller marginal cost coefficient b, total cost grows more slowly as L increases, so it can reliably complete longer chains.

    The selection principle follows: don’t just ask “which model scores highest.” Ask “on my task distribution, which model has the lowest cost per successful task, and does not run out of control on hard tasks.”


    3. Why These Four Capability Dimensions Matter

    The public upgrade data covers four directions. They are not isolated metrics — each maps to a typical stage of agent deployment.

    3.1 Code generation and repair: the baseline for engineering agents

    When an agent joins a development workflow, the typical path is “read the requirement → search the code → modify files → run tests → fix based on errors.” That chain demands three things from the model:

    • Code understanding: locate the actual source of a bug across files and modules, rather than patching only the line that threw the error.
    • Code generation: output that compiles and passes tests, and conforms to the project’s conventions.
    • Autonomous iteration: after a failure, read the error, adjust direction, and avoid pointless retries.

    A 12pp gain on code benchmarks means the same engineering agent workflow can absorb more tasks with less human intervention.

    3.2 Machine learning experimentation: an assistant for data teams

    ML engineering tasks form a longer chain: understand the data → choose a model → write training scripts → analyze metrics → iterate. They place heavy demands on context — dataset descriptions, evaluation metrics, prior experiment results. A roughly 14pp improvement suggests the model can more reliably respect experimental constraints and extract useful adjustment directions from failed runs.

    3.3 Computer use: from “writing code” to “operating systems”

    Many enterprise processes can only be completed through a graphical interface: legacy internal systems, third-party consoles, approval flows that require manual form filling. Raising the computer-use score to 83.0% means the model is more robust at locating UI elements, switching between applications, and handling unexpected dialogs. That gives the “RPA plus LLM” combination a higher automation ceiling.

    3.4 General capability: the stability base for long tasks

    Composite evaluations measure information integration, multi-step reasoning, and cross-domain knowledge. This is what determines whether an agent can stay globally consistent: does it forget constraints in long conversations, can it prioritize when multiple tools are involved, does it recognize uncertainty when information is unreliable? Going from 1349 to 1421 indicates a stronger ability to “stay on track” over long chains.

    3.5 Token efficiency: the common support behind all four gains

    Look at the four improvements together and one trait stands out: stronger capability usually comes from fewer, more accurate reasoning steps. Get it right on the first attempt and there is no need for repeated tries; make reasoning steps more precise and there is no need to fill the context with lengthy “thinking.” Token efficiency and capability are not a trade-off.


    4. How Token Efficiency Works: Fewer Calls Matter More Than Shorter Outputs

    Tokens are the basic unit of LLM billing and context management. To understand token efficiency, start with what task cost is made of:

    1. Input tokens: system prompts, tool specs, conversation history, retrieval results, code snippets.
    2. Output tokens: the model’s reasoning, code, call parameters, and final answer.
    3. Number of calls: how many model calls an agent needs to finish one task.

    Many teams optimize only output length, but in agent tasks the bulk of the tokens is on the input side. The reason is that context accumulates across rounds: every tool result is appended to the next round’s input, so more rounds means more repeated billing.

    A simplified model shows why:

    1. Task cost = Σ (input_i × input price + output_i × output price)
    2. If every round carries I input tokens and produces O output tokens, over N rounds,
    3. and full history is retained:
    4. Total cost ≈ (I × N² / 2 + O × N) × price

    Two points matter here:

    • Input cost grows quadratically with the number of rounds, because round N’s input contains the history of the previous N-1 rounds.
    • Output cost grows linearly with the number of rounds.

    Example 2 compares the effect of different optimization tactics quantitatively.

    Example 2: Cost comparison across optimization tactics (illustrative)

    1. def estimate_cost(I, O, n_rounds, p_in, p_out):
    2. """Input cost accounts for accumulated history (approximate); output cost grows linearly with rounds."""
    3. input_tokens = sum(I * (r + 1) for r in range(n_rounds))
    4. return (input_tokens * p_in + O * n_rounds * p_out)
    5. I, O = 8000, 500 # base input/output tokens per round (illustrative)
    6. p_in, p_out = 0.30e-6, 2.50e-6 # price per million input/output tokens (illustrative)
    7. base = estimate_cost(I, O, 20, p_in, p_out)
    8. scenarios = {
    9. "Baseline: 20 rounds, 500 output tokens": dict(I=I, O=O, N=20),
    10. "Shorter output only (-17%)": dict(I=I, O=int(O * 0.83), N=20),
    11. "Slimmer context only (-40%)": dict(I=int(I * 0.6), O=O, N=20),
    12. "Slimmer context + fewer rounds (-25%)": dict(I=int(I * 0.6), O=O, N=15),
    13. }
    14. for name, s in scenarios.items():
    15. cost = estimate_cost(s["I"], s["O"], s["N"], p_in, p_out)
    16. print(f"{name}: {cost:.4f} units/task, {(1 - cost / base) * 100:.1f}% below baseline")

    For the typical agent task where input far exceeds output, the results are:

    • Cutting output by 17% alone reduces total cost by only about 1.7%.
    • Trimming context by 40% reduces total cost by about 24%.
    • Cutting the number of rounds as well brings the reduction close to 40%.

    The key conclusion:

    The real lever of token efficiency is “get it right the first time and make fewer calls,” not simply “say less.”

    This also explains why the new-generation workhorse model can cut output tokens by up to 65% in code generation. Code tasks are especially clear-cut: the longer the output, the higher the chance of errors, and the more retries follow. More precise code often passes tests on the first attempt, which removes entire rounds of calls — not just a few hundred output tokens.


    5. Don’t Trust Leaderboards Alone: Build Your Own Evaluation Loop

    Public benchmarks provide a horizontal reference, but they have three limitations:

    • Training data may overlap with them.
    • Task distributions differ from your business scenarios.
    • Scoring criteria cannot reflect your team’s real tech stack, coding conventions, and domain knowledge.

    So enterprises have to build their own evaluation system.

    5.1 Building the evaluation set

    • Real sources: sample from production tickets, code commits, and historical conversations; cover typical, edge, and failure cases.
    • Layered design: split into easy, medium, and hard tiers so you can locate capability boundaries.
    • Verifiable answers: judge with executable scripts (code compiles and unit tests pass, structured output passes schema validation) or with rubrics written by your team.
    • Moderate size: 50–200 cases per scenario is enough, but the set must be refreshed regularly to avoid overfitting to it.

    5.2 Metrics

    Metric Definition What it tells you
    Task success rate Share of tasks completed Final quality
    First-pass rate Share correct on the first output Whether retries are needed
    Average rounds Model calls needed per task Efficiency and cost
    Average tool calls External tool invocations per task External dependency cost
    Tokens per task Input tokens + output tokens Cost baseline
    Cost per successful task Total cost / successful tasks Basis for overall decisions
    P95 latency 95% of tasks finish within this time User experience

    5.3 Evaluation workflow

    Example 3: A reusable model evaluation harness (illustrative)

    1. import json
    2. import time
    3. from collections import defaultdict
    4. client = InferenceClient(base_url="https://your-gateway.example.com", api_key=API_KEY)
    5. def evaluate(model, dataset):
    6. """Run a batch of tasks against a model and collect task-level metrics."""
    7. stats = defaultdict(float)
    8. for case in dataset: # each case has id, task, grader
    9. t0 = time.time()
    10. rounds = 0
    11. total_in = total_out = 0
    12. history = []
    13. for step in range(MAX_ROUNDS): # cap rounds to prevent infinite loops
    14. rounds += 1
    15. resp = client.chat(
    16. model=model,
    17. messages=[{"role": "user", "content": case["task"]}],
    18. system=build_system_prompt(case), # system prompt + tool specs
    19. max_output_tokens=4096,
    20. )
    21. total_in += resp.usage.input_tokens
    22. total_out += resp.usage.output_tokens
    23. history.append(resp.text)
    24. if resp.tool_calls:
    25. # Execute the tools, append results to history, then call the model again
    26. pass
    27. else:
    28. break # the model produced its final answer
    29. success = case["grader"](history[-1]) if history else False
    30. cost = (total_in * p_in + total_out * p_out) / 1e6
    31. stats["tasks"] += 1
    32. stats["success"] += int(success)
    33. stats["rounds"] += rounds
    34. stats["in"] += total_in
    35. stats["out"] += total_out
    36. stats["cost"] += cost
    37. stats["latency"] += time.time() - t0
    38. n = stats["tasks"]
    39. return {
    40. "model": model,
    41. "success_rate": stats["success"] / n,
    42. "avg_rounds": stats["rounds"] / n,
    43. "avg_tokens": (stats["in"] + stats["out"]) / n,
    44. "cost_per_task": stats["cost"] / n,
    45. "cost_per_success": stats["cost"] / max(stats["success"], 1),
    46. "p95_latency": stats["latency"] / n, # compute a real percentile here; simplified to the mean
    47. }
    48. # Fix randomness and temperature to reduce evaluation variance
    49. results = [evaluate(m, DATASET) for m in ["workhorse-v1", "workhorse-v2"]]
    50. print(json.dumps(results, ensure_ascii=False, indent=2))

    5.4 Rollout strategy

    • Run offline evaluation first, then a small-traffic canary.
    • During the canary, collect quality metrics and cost metrics together, and define rollback thresholds (for example, roll back if success rate drops by more than 2%).
    • Before switching generations, run a regression pass on historical real cases, so you don’t end up with something that “looks stronger but actually regresses in your own scenarios.”

    6. Engineering Cost Reduction: Just as Important as Model Efficiency

    Efficiency gains inside the model are the foundation; engineering multiplies the return. Most of the following techniques are model-agnostic and work on any workhorse model.

    6.1 Slimming down the system prompt

    • Put fixed content — the system prompt, tool specs — at the very front of the context so prefix caching can hit.
    • Remove redundant instructions, merge duplicate rules, and split long documents into knowledge snippets loaded on demand.
    • Periodically measure the token share of each prompt block and compress the largest block first.

    6.2 Context management

    • Sliding window plus summarization: keep the most recent turns verbatim and have a lightweight model compress older history into a summary.
    • Retrieval augmentation: don’t stuff an entire codebase or document set into the context; retrieve only the fragments relevant to the current task.
    • Tool result trimming: truncate oversized logs and return only the key fields.

    6.3 Structured output

    • Use constrained formats (for example, a JSON schema) or function calling so the model emits parseable structure directly.
    • This noticeably reduces the waste of “generate a long blob, then parse it,” and makes validation and retries easier.
    • For structured tasks, cap the output at what is actually needed instead of letting the model ramble on.

    Example 4: An agent call with budget control and context compression (illustrative)

    1. def compress_history(history, keep_turns=4, max_chars=6000):
    2. """Keep the most recent N turns verbatim; summarize everything older."""
    3. recent = history[-keep_turns:]
    4. older = history[:-keep_turns]
    5. if not older:
    6. return "".join(recent)
    7. summary = client.chat(
    8. model="lite-model", # use a lightweight model to compress
    9. messages=[{"role": "user",
    10. "content": "Summarize the following history into key points of no more than 300 words:\n" + "".join(older)}],
    11. max_output_tokens=512,
    12. ).text
    13. text = "[History summary]" + summary + "\n[Recent conversation]" + "".join(recent)
    14. return text[:max_chars] # truncate if it overflows
    15. def call_with_budget(prompt, budget=8000, max_retries=2):
    16. """Set an output budget and a retry limit for a single call."""
    17. for _ in range(max_retries):
    18. resp = client.chat(
    19. model="workhorse-v2",
    20. messages=[{"role": "user", "content": prompt}],
    21. max_output_tokens=budget,
    22. temperature=0.2, # lower randomness, higher first-pass rate
    23. )
    24. if resp.finish_reason != "length": # not truncated by the length limit
    25. return resp
    26. return resp # fall back to this; let the caller retry or escalate

    6.4 Constraining output length

    • State it explicitly in the instructions: “answer concisely, don’t explain your reasoning, give the code directly.”
    • For code tasks, use a “code block first, then necessary notes” structure and avoid long preambles.
    • For simple classification or extraction, limit output to a single sentence or a set of structured fields.

    6.5 Prefix caching

    • Most inference services offer a context or prefix caching mechanism. A fixed prefix can be reused within its validity window, and cached portions are usually billed well below normal input.
    • The usage pattern is to put fixed content — the system prompt, tool specs — at the very front of the message list and keep the order stable.
    • Note that caching rules (validity window, minimum length, billing method) differ across services; follow the official documentation of the service you use.

    6.6 Task routing

    Not every task deserves the most expensive model. Route by complexity:

    • Lightweight tasks (classification, extraction, format conversion, simple Q&A): send to a lightweight model.
    • Routine tasks (code completion, standard Q&A, multi-step tool calls): send to the workhorse model.
    • Hard tasks (architecture design, difficult problems, long-horizon planning): send to a flagship model, or let the workhorse model produce a plan and have the flagship review it.

    Example 5: A routing strategy based on task characteristics (illustrative)

    1. def route(task):
    2. """Pick a model tier based on task complexity and risk level."""
    3. if task["complexity"] <= 1 and task["risk"] == "low":
    4. return "lite-model" # lightweight, high-throughput model
    5. if task["complexity"] >= 3 or task["risk"] == "high":
    6. return "flagship-model" # flagship model
    7. return "workhorse-v2" # workhorse model

    7. Multi-Agent Systems: Structural Gains from a Workhorse Upgrade

    Beyond single-agent setups, more production systems use a “planner + executor + reviewer” collaboration pattern. Model efficiency gains are amplified in this mode:

    • Planner: decomposes the task and assigns subtasks. With more precise reasoning from the workhorse model, plans contain fewer steps and total downstream tokens drop.
    • Executor: calls tools and generates code or documents. Fewer output tokens means each round is more focused, with less pointless rework.
    • Reviewer: checks results for completeness and safety. Shorter context and more accurate reasoning reduce both false positives and missed findings.
    • Communication overhead: messages passed between agents count as tokens too. More concise output is equivalent to lower collaboration cost.

    Example 6: Token budgeting in multi-agent collaboration (illustrative)

    1. def multi_agent_task(task):
    2. """Plan-execute-review collaboration with a global token budget."""
    3. budget = {"total": 200_000, "used": 0}
    4. def charge(usage):
    5. budget["used"] += usage.input_tokens + usage.output_tokens
    6. # 1. Planning: emit a structured plan instead of long prose
    7. plan = client.chat(
    8. model="workhorse-v2",
    9. messages=[{"role": "user", "content": task}],
    10. system="Break the task into no more than 5 subtasks and return a JSON array",
    11. response_format={"type": "json_object"},
    12. )
    13. charge(plan.usage)
    14. # 2. Execution: run each subtask independently, pass summarized results along
    15. results = []
    16. for sub in json.loads(plan.text):
    17. if budget["used"] >= budget["total"]:
    18. break # budget exhausted; stop further execution
    19. out = client.chat(
    20. model="workhorse-v2",
    21. messages=[{"role": "user", "content": sub["desc"]}],
    22. )
    23. charge(out.usage)
    24. results.append(out.text[:1000]) # pass only the key result
    25. # 3. Review: validate the aggregated results once
    26. review = client.chat(
    27. model="flagship-model",
    28. messages=[{"role": "user",
    29. "content": "Review whether the following execution results meet the requirements:\n" + "\n".join(results)}],
    30. )
    31. charge(review.usage)
    32. return review.text, budget["used"]

    8. Architecting and Governing Token Costs

    8.1 Layered deployment

    The diagram below organizes model calls, the gateway, caching, storage, logging, and monitoring into one piece of infrastructure. Every component is described in generic terms.

    1. ┌─────────────────────────────────────────────────────────┐
    2. │ Apps: IDE plugins / enterprise assistants / dev agents │
    3. │ / data analysis agents │
    4. └───────────────────────────┬─────────────────────────────┘
    5. │
    6. ┌───────▼─────────┐
    7. │ Model routing │ routes by task complexity
    8. │ gateway │
    9. └───┬─────────┬───┘
    10. ┌─────────────┘ └─────────────┐
    11. ┌─────▼──────┐ ┌─────▼──────┐ ┌────▼──────┐
    12. │ Lite model │ │ Workhorse │ │ Flagship │
    13. └────────────┘ │ model │ │ model │
    14. └────────────┘ └───────────┘
    15. │
    16. ┌───────────┬───────┴───────┬─────────────┐
    17. ┌────▼───────┐┌──▼──────────┐┌─▼──────────┐┌─▼────────┐
    18. │ Context ││ Eval ││ Logs & ││ Monitoring│
    19. │ cache ││ dataset ││ usage ││ & alerting│
    20. │ (cache/DB) ││ (storage) ││ collection ││ │
    21. └────────────┘└─────────────┘└────────────┘└───────────┘

    8.2 Key design principles

    • Cache first: for high-frequency repeated requests (fixed system prompts, common questions), hit the cache before running inference again.
    • Async batching: non-real-time work (bulk code review, log analysis, report generation) goes through an async queue and runs off-peak, avoiding contention during traffic spikes.
    • Observability: log the model version, input/output tokens, rounds, latency, cost, and success rate for every call so you have a traceable call chain.
    • Budgets and quotas: set token quotas and alert thresholds per application and per team so runaway tasks get caught.

    8.3 A practical reference implementation

    Using Python and FastAPI, you can implement caching, quotas, and metrics collection at the gateway layer:

    1. # gateway.py (illustrative)
    2. from fastapi import FastAPI, Request, HTTPException
    3. import hashlib, json, time
    4. app = FastAPI()
    5. client = InferenceClient(base_url="https://your-gateway.example.com", api_key=API_KEY)
    6. cache = {} # replace with Redis or similar in production
    7. quota = {"tenant_a": {"limit": 1_000_000, "used": 0}}
    8. def cache_key(model, messages, system):
    9. raw = json.dumps({"m": model, "s": system, "msg": messages}, sort_keys=True)
    10. return hashlib.sha256(raw.encode()).hexdigest()
    11. @app.post("/v1/chat")
    12. async def chat(request: Request):
    13. body = await request.json()
    14. tenant = request.headers.get("X-Tenant", "default")
    15. q = quota.get(tenant)
    16. if q and q["used"] >= q["limit"]:
    17. raise HTTPException(429, "Token quota exceeded")
    18. key = cache_key(body["model"], body["messages"], body.get("system", ""))
    19. if key in cache: # cache hit, return immediately
    20. return {**cache[key], "cached": True}
    21. t0 = time.time()
    22. resp = client.chat(
    23. model=body["model"],
    24. messages=body["messages"],
    25. system=body.get("system", ""),
    26. max_output_tokens=body.get("max_tokens", 4096),
    27. )
    28. result = {"text": resp.text, "usage": resp.usage, "latency": time.time() - t0}
    29. cache[key] = result
    30. if q:
    31. q["used"] += resp.usage.total_tokens
    32. return result

    9. Pre-Launch Checklist

    Check What to verify Done when
    Evaluation set Covers typical, edge, and hard tasks ≥50 cases per scenario, with executable graders
    Baseline Current model’s quality and cost baseline recorded Success rate, cost per task, and P95 latency all measured
    Routing Traffic split by complexity Lightweight tasks are not routed to the flagship model
    Context Compression and retrieval optimization applied Average input tokens down ≥20% vs. baseline
    Caching Prefix or result caching enabled Fixed-prefix hit rate is observable
    Budget Tenant-level quotas and alerts in place Automatic degradation or circuit breaking on overrun
    Observability Tokens and cost logged for every call Aggregatable by app / team / model
    Regression Regression pass run before an upgrade Success rate holds, cost improves

    Conclusion

    A workhorse model upgrade essentially pushes the whole capability–cost curve outward: the same budget handles more complex tasks, and the same tasks cost less. For engineering teams, the right way to capture that dividend is not to “wait for a new model” but to build a closed loop of evaluate → route → cache → observe.

    In that loop:

    • Evaluation tells you whether an upgrade is worth it.
    • Routing and caching tell you how to spend less.
    • Observability tells you whether you’ve drifted.

    Together, they move AI agents from “usable” to genuinely “good and sustainable.”