Sub topic 18
Cost, Latency, and Moving to Production
This chapter assumes you have read the earlier chapters on the agent loop, error handling, guardrails, evaluation, and tracing. It covers what an agent costs to run, why it can feel slow, and what to check before you ship it.
Why agents cost more than single calls
Each trip around the loop is one model call. The call sends the whole message history again, so the input grows with every step. A run with 8 steps does not cost 8 times one call. It costs more, because step 8 re-sends the results of steps 1 to 7.
Cost per run is roughly the sum, over every step, of the input tokens times the input price plus the output tokens times the output price. The step count matters, and so does the history size.
Measuring a run
You cannot manage cost or latency you do not measure. Wrap the loop so it records steps, tokens, and elapsed time. This example assumes your model reply includes a usage dictionary with token counts, which most provider APIs return in some form.
import time
def run_with_metrics(call_model, run_tool, user_goal, max_steps=8):
messages = [{"role": "user", "content": user_goal}]
metrics = {"steps": 0, "input_tokens": 0, "output_tokens": 0}
start = time.perf_counter()
answer = "Stopped: step limit reached."
for _ in range(max_steps):
reply = call_model(messages)
metrics["steps"] += 1
usage = reply.get("usage", {})
metrics["input_tokens"] += usage.get("input_tokens", 0)
metrics["output_tokens"] += usage.get("output_tokens", 0)
messages.append({"role": "assistant", "content": reply.get("content"),
"tool_call": reply.get("tool_call")})
call = reply.get("tool_call")
if call is None:
answer = reply["content"]
break
result = run_tool(call["name"], call["arguments"])
messages.append({"role": "tool", "name": call["name"], "content": result})
metrics["seconds"] = round(time.perf_counter() - start, 3)
return answer, metricsLog these numbers for every run. Averages hide problems, so look at the slowest and most expensive runs too.
Levers for cost and latency
| Lever | Effect | Trade-off |
|---|---|---|
| Lower `max_steps` | Caps worst-case cost | Hard tasks may stop early |
| Trim or summarize history | Fewer input tokens per step | Detail may be lost |
| Smaller model for easy steps | Lower price, faster replies | May make more mistakes |
| Prompt caching, if your provider offers it | Cheaper repeated prefixes | Needs a stable prompt start |
| Parallel tool calls | Fewer round trips | Only for independent calls |
| Stream the final answer | Faster perceived response | Does not reduce total time |
Put the system prompt and tool definitions at the start and keep them stable. That makes caching possible and keeps behavior predictable.
Moving to production
Before release, check each item:
- Hard limits: step count, token budget, wall-clock timeout, and a per-user spending cap.
- Retries with backoff for rate limits and temporary network failures.
- Guardrails from the earlier chapter, including approval for risky actions.
- A regression suite of test tasks that runs on every change to the prompt, tools, or model.
- Traces stored for every run, with secrets and personal data removed.
- A rollout plan: start with a small share of traffic and watch cost, failure rate, and latency.
Exercise
An agent averages 6 steps per run, and its input tokens per step grow as history accumulates. Name two changes that reduce cost without changing the model, and one risk of each.
Show answer
Trim or summarize the history, which risks dropping details the agent needs later. Lower max_steps, which risks stopping before hard tasks finish. Caching a stable prompt prefix is also valid, with the risk that any change to the prefix invalidates the cache.