Sub topic 16
Cost, Latency and When Not to Use an Agent
This chapter assumes you can read the agent loop from earlier in the tutorial, with its MAX_STEPS cap and tool results appended to messages. It also assumes you know how a classic retrieve-then-generate pipeline works. The question here is practical: what does letting the model drive retrieval cost, and when is it the wrong choice?
Where the extra cost comes from
Classic RAG makes one retrieval and one model call. An agent makes one model call per step, and each call re-sends the whole conversation so far: the system prompt, the question, every earlier tool call and every tool result. Input tokens therefore grow with each step, and total input across a run grows roughly with the square of the step count.
| Property | Classic RAG | Agentic RAG |
|---|---|---|
| Model calls per question | 1 | 1 plus the number of searches |
| Retrievals per question | Exactly 1 | 0 to `MAX_STEPS` |
| Input tokens | Prompt plus one set of chunks | Grows every step |
| Latency | One retrieval plus one generation | Sum of all steps, run in sequence |
| Variance | Low | High, since easy and hard questions take different paths |
| Behavior | Same path every time | Depends on what the model decides |
The variance row matters most in production. Average cost can look acceptable while the slowest and most expensive 5% of questions are many times worse.
A simple cost model
This function estimates the cost of one run. Each search adds the tool result and the assistant's tool-call message to the history. Prices are in dollars per million tokens, and the defaults are placeholders, so use your provider's real prices.
def estimate_run(searches, base_tokens=500, result_tokens=800,
output_tokens=150, price_in=3.0, price_out=15.0):
"""Estimate cost of an agent run with a given number of searches.
The run makes searches + 1 model calls. Call i re-sends the base
prompt plus everything added by the earlier calls.
"""
calls = searches + 1
growth = result_tokens + output_tokens # added to history per search
input_total = sum(base_tokens + growth * i for i in range(calls))
output_total = output_tokens * calls
cost = (input_total * price_in + output_total * price_out) / 1_000_000
return {"calls": calls, "input_tokens": input_total,
"output_tokens": output_total, "cost": cost}
for n in (0, 1, 2, 4):
r = estimate_run(n)
print(f"searches={n} calls={r['calls']} "
f"input={r['input_tokens']} cost=${r['cost']:.5f}")With these numbers the cost is about $0.00375 with no search, $0.01035 with one, $0.0198 with two and $0.04725 with four. Four searches cost about 12 times as much as answering directly. The model is no more expensive per token. The cost comes from paying for the history again at every step.
Many providers bill a repeated, unchanged prefix at a discount through prompt caching. Because an agent's history is a stable prefix that only grows at the end, it benefits from caching. Check your provider's rules before you rely on it. Caching often has a minimum prefix length and an expiry time.
Where latency comes from
Steps run one after another, because the model cannot choose its second query until it has seen the first results. Latency is roughly the sum of each model call plus each retrieval. Users also see nothing of the final answer until the last step starts generating.
Ways to reduce it:
- Allow parallel tool calls. When the model decomposes a question into independent sub-queries, it can request them in one turn, and you can run them concurrently. Your loop already handles a list of
tool_calls, so use a thread pool orasyncioto run them together. - Use a smaller model for cheap decisions. Routing and grading often work with a faster model. Reserve the large model for the final answer.
- Keep tool results small. Lower
top_kand truncate passages, assearch_docsdoes. This cuts tokens in every later step. - Cache retrieval. Identical or near-identical queries are common. A cache keyed on the normalized query skips both the search and the wait.
- Stream. Send status events such as "searching docs" while the loop runs, and stream the final answer as it is generated.
- Set timeouts per step. One slow backend should not consume the whole latency allowance.
Enforce budgets in code
A step limit alone does not bound cost, because a step with large results can cost far more than a step with small ones. Track steps, tokens and wall-clock time together.
import time
class Budget:
def __init__(self, max_steps=5, max_tokens=20000, max_seconds=20.0):
self.max_steps = max_steps
self.max_tokens = max_tokens
self.max_seconds = max_seconds
self.steps = 0
self.tokens = 0
self.started = time.monotonic()
def record(self, tokens):
self.steps += 1
self.tokens += tokens
def exhausted(self):
"""Return the reason the budget is spent, or None."""
if self.steps >= self.max_steps:
return "step limit"
if self.tokens >= self.max_tokens:
return "token limit"
if time.monotonic() - self.started >= self.max_seconds:
return "time limit"
return None
budget = Budget(max_steps=10, max_tokens=5000)
for step_tokens in (1200, 2400, 2600):
budget.record(step_tokens)
reason = budget.exhausted()
if reason:
print(f"stop after {budget.steps} steps: {reason}")
breakIn the agent loop, call budget.exhausted() before each model call. When it returns a reason, take the same exit as the MAX_STEPS case: ask for a final answer with no tools offered, and have the model say what is missing.
When not to use an agent
Use classic RAG, or no retrieval at all, in these cases:
- Most questions are single-hop. If one search with the user's words nearly always finds the answer, extra steps only add cost.
- Latency is tight. If the budget is one or two seconds, a sequential loop will miss it at the 95th percentile.
- The corpus is small. If all the documents fit in the context window, put them in the prompt and skip retrieval.
- You need predictable behavior. Regulated or audited flows are easier to defend when the same input always follows the same path.
- Volume is high and value per question is low. A 10x cost multiplier on millions of simple questions is rarely justified.
- The model is weak at tool calling. Small models often skip needed searches, repeat a query, or write malformed arguments.
Use an agent when questions need several lookups, the answer depends on which of several sources to consult, or queries are ambiguous. The strongest reason is evidence: you measured classic RAG on your questions and it fails in ways a second search would fix.
Middle paths
You can choose a point between the two extremes:
- Rewrite once, then retrieve. One cheap model call rewrites the query, then a fixed pipeline runs. This fixes many conversational failures at about the cost of two calls.
- Route, then run a fixed pipeline. A classifier picks the source or skips retrieval. Each branch is a plain pipeline.
- Retry on weak evidence. Run classic RAG first. Only if a grading step finds the results insufficient, hand the question to the agent loop. Easy questions stay cheap and hard ones get more effort.
- Fixed decomposition. If your questions always have the same shape, such as "compare A and B", write the sub-queries in code and run them in parallel.
Decide with measurements
Run both designs on the same evaluation set from the previous chapter and compare:
- Answer accuracy and grounding, to see what the agent buys.
- Cost per question at the mean and the 95th percentile.
- Latency at the median and the 95th percentile.
- The distribution of step counts, and how often the budget is hit.
- The share of agent runs that repeat a query. Repeats signal wasted spend, and a query cache or a repeated-query check in the loop removes them.
Then compute the price of the improvement: extra accuracy gained per extra dollar and per extra second. If a few more points of accuracy cost an extra five seconds on every question, restrict the agent to the question types where it helps.
Exercise
Using estimate_run with its default values, an agent averages 3 searches per question. What does one question cost, and what does a day of 10,000 questions cost? Name one change that would lower the figure without lowering answer quality much.
Show answer
With 3 searches there are 4 model calls. Input tokens are 500 + 1450 + 2400 + 3350 = 7700 and output tokens are 4 x 150 = 600. Cost is (7700 x 3 + 600 x 15) / 1,000,000 = 0.0231 + 0.009 = $0.0321 per question, so about $321 per day for 10,000 questions. Valid reductions include lowering topk or truncating passages (a smaller resulttokens), using a cheaper model for routing and grading, caching repeated queries, or relying on prompt caching for the repeated history prefix.
Exercise
Your support bot answers questions from one 30-page FAQ, nearly every question needs a single lookup, and the target response time is under two seconds. Should you build an agent loop? Give two reasons.
Show answer
No. Classic RAG, or putting the whole FAQ in the prompt, fits better. Single-hop questions get no benefit from extra searches, and a sequential loop adds a model call per step, which makes the two-second target hard to meet at the 95th percentile. A 30-page corpus is also small enough to fit in the context window, which removes the retrieval problem the agent would solve.