Sub topic 18
Cost, latency, and moving to production
This chapter assumes you can write the agent loop from earlier chapters and have run tool-calling code against a model API. You should also be comfortable with Python and JSON. It covers where an agent's money and time go, how to reduce both, and what changes when the agent leaves your laptop.
Where the cost comes from
Model APIs bill per token, and output tokens usually cost several times more than input tokens. A single LLM call is easy to price. An agent is harder because the loop resends the whole history on every step.
Suppose the system prompt and tool definitions take 2,000 tokens. Each step adds about 1,000 tokens of assistant text and tool results. Step k then sends roughly 2,000 + 1,000 × (k − 1) input tokens.
- A 10-step run sends 10 × 2,000 + 1,000 × (0 + 1 + … + 9) = 65,000 input tokens.
- The new content is only 11,000 tokens, so the resending dominates.
- At an example price of $3 per million input tokens and $15 per million output tokens, with 300 output tokens per step, the run costs about $0.195 + $0.045 = $0.24.
Input cost grows with the square of the step count, so one extra step costs more than the step before it. Long tool outputs make this worse, because each one is carried through every later step.
Levers for reducing cost
| Lever | What it does | Trade-off |
|---|---|---|
| Prompt caching | Providers that support it bill a repeated prefix (system prompt, tool schemas) at a reduced rate. | Keep the prefix byte-identical and put changing content at the end. Rules and discounts vary by provider. |
| Model routing | Use a small model for simple steps such as classification or extraction, and a larger model for hard reasoning. | You need a rule or classifier for routing, and you must test both paths. |
| Trimming tool output | Return only the fields the model needs, and truncate long text with a marker. | Over-trimming hides facts the model needs. |
| Summarizing history | Replace old turns with a short summary (see the memory chapter). | Summaries lose detail and cost a model call. |
| Fewer steps | Write tools that do more per call, and give clear stop conditions. | Large tools are harder to name and describe well. |
Measure before optimizing. Log input tokens, output tokens, and step count for every run, then look at the most expensive runs. They are usually runs stuck in a retry loop, not typical runs.
Latency
Latency is the time a user waits. For an agent it is roughly the sum of every model call plus every tool call, so most of the time goes to the sequence of steps.
- Model time. Each call has a delay before the first token and then generates tokens at a steady rate. Long outputs take longer, so ask for short answers in intermediate steps.
- Tool time. A slow API or database query adds directly to the total. Set a timeout on every tool.
- Step count. Each extra step adds a full model call. This is usually the biggest factor.
Three techniques help most:
- Stream the final answer. The user sees text right away, though total time is unchanged.
- Run independent tool calls in parallel. If the model requests three lookups that do not depend on each other, run them with a thread pool or
asyncioand return all results in one step. - Cut steps. Combine tools that are always called together, and give the model the facts it would otherwise fetch.
Cost and latency often move together, because fewer steps and shorter context improve both. Routing to a smaller model is a trade-off: it is faster and cheaper but may be less accurate, so check the effect with your evaluation tasks.
Enforcing a budget in code
The max_steps limit stops runaway loops, but it does not bound dollars or time. A step with a huge tool result can cost more than ten small ones. Add explicit cost and time limits.
The model reply in this example carries a usage field with token counts. Most APIs return something similar, though field names differ.
import json
import time
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Budget:
max_cost_usd: float
max_seconds: float
input_price: float = 3.00 / 1_000_000 # example price per input token
output_price: float = 15.00 / 1_000_000 # example price per output token
spent_usd: float = 0.0
started: float = field(default_factory=time.monotonic)
def record(self, usage: dict) -> None:
self.spent_usd += usage["input_tokens"] * self.input_price
self.spent_usd += usage["output_tokens"] * self.output_price
def exceeded(self) -> Optional[str]:
if self.spent_usd >= self.max_cost_usd:
return f"cost limit reached (${self.spent_usd:.4f} spent)"
if time.monotonic() - self.started >= self.max_seconds:
return "time limit reached"
return None
def run_agent_budgeted(call_model, run_tool, goal, budget, max_steps=8):
messages = [{"role": "user", "content": goal}]
for _ in range(max_steps):
reply = call_model(messages)
budget.record(reply["usage"])
call = reply.get("tool_call")
messages.append({"role": "assistant", "content": reply.get("content"), "tool_call": call})
if call is None:
return reply["content"]
reason = budget.exceeded()
if reason:
return f"Stopped: {reason}."
result = run_tool(call["name"], call["arguments"])
messages.append({"role": "tool", "name": call["name"], "content": result})
return "Stopped: step limit reached."
def endless_model(messages):
# Never finishes: always asks for another tool call.
return {
"content": None,
"tool_call": {"name": "echo", "arguments": {"text": "again"}},
"usage": {"input_tokens": 20_000, "output_tokens": 500},
}
def run_tool(name, arguments):
return json.dumps({"echo": arguments.get("text")})
budget = Budget(max_cost_usd=0.20, max_seconds=30)
print(run_agent_budgeted(endless_model, run_tool, "Loop forever", budget))Each step costs 20,000 × $3/M + 500 × $15/M = $0.0675. After the third step the total is $0.2025, which passes the $0.20 limit, so the run prints Stopped: cost limit reached ($0.2025 spent). The check runs after the model call but before the tool call, so an over-budget run does not pay for a tool it will never use.
Moving to production
A prototype that works in a notebook still needs the following before real users depend on it.
- Timeouts and retries on every external call. Retry only transient failures (rate limits, network errors), with exponential backoff and a retry cap. Do not retry a call that failed because its arguments were wrong.
- Idempotent tools. A retry or a restarted run must not send an email twice or charge a card twice. Pass an idempotency key for any action with side effects.
- Rate-limit handling. Many concurrent agents share one API quota. Use a queue or a concurrency limit so a traffic spike degrades into waiting, not into errors.
- Durable state. Long runs outlive a single request. Save the message history and step count to storage so a crashed worker can resume, and run slow agents in a background job instead of inside a web request.
- Versioned prompts, tools, and models. Record which versions produced each run. A silent model upgrade can change behavior in ways your tests have not covered.
- Release gates. Run your evaluation tasks before each change and compare against the last release. Roll out to a small share of traffic first.
- Monitoring. Track cost per run, steps per run, latency percentiles, tool error rates, and how often runs stop at a limit. Alert on sudden changes, and keep traces (see the tracing chapter) so you can inspect any bad run.
- Guardrails stay on. Permission checks and human approval for risky actions apply in production exactly as in testing. Never relax them to save time.
Common mistakes
- Optimizing the average. A few runaway runs often account for most of the bill. Look at the top 1% of runs by cost.
- Breaking the cache. Putting a timestamp or user name at the start of the system prompt makes the prefix differ on every call, which removes the benefit of caching.
- Choosing a model by price alone. A cheaper model that needs twice as many steps, or fails more often, can cost more overall. Compare cost per successfully completed task.
- No partial result on a stop. When a limit ends a run, return what was found so far and say why it stopped. A bare error wastes the money already spent.
Exercise
An agent run has a 3,000-token prefix (system prompt plus tools) and each step adds 2,000 tokens of new content. Step 1 sends only the prefix. How many total input tokens does a 4-step run send, and which change would reduce cost more: caching the prefix or cutting one step?
Show answer
Step k sends 3,000 + 2,000 × (k − 1) tokens, so the four steps send 3,000, 5,000, 7,000, and 9,000, for a total of 24,000 input tokens. The prefix accounts for 4 × 3,000 = 12,000 of them. Caching bills those at a reduced rate, which cuts about half of the input tokens' cost, depending on the provider's discount. Dropping the last step removes 9,000 tokens plus a model call, which is about 37% of input tokens and also saves latency. The two are close, so the choice depends on the cache discount. If the discount is steep, cache the prefix. Cutting steps also reduces latency and error risk, so do both when you can.