Sub topic 15
Cost and latency trade-offs
Every agent you add to a workflow means more model calls, more tokens sent, and more waiting. This chapter shows where that cost comes from, how the handoff and orchestrator patterns differ in cost, and which changes reduce it. It assumes you have read the earlier chapters on handoffs, orchestrators, and context passing. It also assumes you can read basic Python and know that model providers bill input and output tokens separately.
Where the cost comes from
A model call costs roughly input_tokens × input_price + output_tokens × output_price. Output tokens usually cost several times more than input tokens. Input tokens are still often the larger bill, because an agent loop re-sends the same content on every turn:
- the agent's instructions
- the tool definitions
- the full message history so far
A call on turn 5 pays again for everything sent on turns 1 to 4. Total input tokens therefore grow roughly with the square of the number of turns, not linearly.
Multi-agent designs change this in three ways:
- Extra calls. An orchestrator adds a call for each delegation decision. Each specialist adds its own loop of calls.
- Repeated context. In a handoff, the next agent receives the whole history. In an orchestrator, a worker receives only the task text, but the orchestrator re-reads every worker result on its later turns.
- Different models per role. Each agent can use a different model, so a cheap model can handle simple work.
A small cost model
The following script estimates the cost of one run. It ignores tool-result tokens, which would make the history grow faster. It still shows the shape of the cost.
from dataclasses import dataclass
@dataclass
class Price:
input_per_m: float # dollars per million input tokens
output_per_m: float # dollars per million output tokens
BIG = Price(3.00, 15.00)
SMALL = Price(0.25, 1.25)
def call_cost(price: Price, input_tokens: int, output_tokens: int) -> float:
return (input_tokens * price.input_per_m
+ output_tokens * price.output_per_m) / 1_000_000
def loop_cost(price, instructions, first_input, turns, output_tokens):
"""Cost of one agent loop. Each turn re-sends instructions plus history."""
total, history = 0.0, first_input
for _ in range(turns):
total += call_cost(price, instructions + history, output_tokens)
history += output_tokens
return total
single = loop_cost(BIG, 500, 300, turns=4, output_tokens=200)
orchestrator = loop_cost(BIG, 500, 300, turns=4, output_tokens=200)
workers = 2 * loop_cost(SMALL, 400, 150, turns=2, output_tokens=300)
print(f"single agent: ${single:.4f}")
print(f"orchestrator + workers: ${orchestrator + workers:.4f}")It prints $0.0252 for the single agent and $0.0274 for the orchestrator with two small-model workers. The multi-agent run costs about 9% more per request here, even with cheap workers. That is the baseline. Multi-agent design has to buy something with that extra cost, such as better quality, smaller prompts per agent, or lower latency through parallel work.
Latency: sums and maxima
Latency follows a simpler rule than cost. Sequential calls add up. Parallel calls take as long as the slowest one.
def sequential_latency(seconds: list[float]) -> float:
return sum(seconds)
def parallel_latency(seconds: list[float]) -> float:
return max(seconds)
worker_times = [6.0, 4.5, 5.0]
print(sequential_latency(worker_times)) # 15.5
print(parallel_latency(worker_times)) # 6.0Parallel fan-out cuts the wait but not the bill. You pay for three workers either way. Fan-out only helps when the subtasks are independent. If the writer needs the researcher's output, you cannot run them at the same time.
Comparing the patterns
| Factor | Handoff | Orchestrator |
|---|---|---|
| Extra calls | Few. The receiving agent continues the same conversation. | More. The orchestrator decides, delegates, and reads results. |
| Context sent per call | Full history, growing each turn | Orchestrator: growing. Workers: only the task text |
| Latency | Sequential by nature | Can parallelize independent workers |
| Main cost risk | Long shared history re-billed every turn | Many small calls plus repeated orchestrator reads |
| Cheap-model opportunity | Triage agent can be small | Workers can be small, orchestrator is often large |
A handoff chain is cheap when the conversation is short. It becomes expensive when many agents hand off in a long conversation, because each new agent re-reads everything. An orchestrator keeps worker contexts small but pays for coordination.
Ways to reduce cost and latency
Apply these in order of how much they usually save.
- Use the smallest model that passes your tests. Triage and routing agents often need only a small model. Keep the large model for the agent that reasons or writes the final answer. Check each downgrade against your evaluation set, not by feel.
- Pass a summary, not the history. The structured
HandoffPayloadfrom the context chapter replaces thousands of history tokens with a few hundred. This is the most effective fix for handoff chains. - Parallelize independent workers. Make sure the orchestrator issues the calls concurrently, for example with
asyncio.gather, rather than one per model turn. - Keep instructions short and tool lists small. Each agent should carry only the tools it needs. Tool definitions count as input tokens on every call.
- Cap output length. Set a maximum output token limit for each agent. Workers that return essays force the orchestrator to re-read essays.
- Use
max_turnsas a cost limit. The loop guard from the termination chapter also bounds spending. Pick it from the longest legitimate run you have measured, not from a round number. - Do not split work that one agent handles well. If the single agent passes your tests, a second agent adds only cost.
Edge cases that raise the bill
- Prompt caching and handoffs. A handoff swaps the system instructions and tool list, which sit at the start of the prompt. The cached prefix no longer matches, so the next call pays full price for the whole history. Handoffs can therefore cost more than their token counts suggest.
- Retries multiply cost. If each worker call is retried up to 3 times, a failing run can cost 4 times a clean one. Retry only errors that can succeed on a second try, such as timeouts and rate limits. Do not retry on a wrong answer without changing something.
- Retries inside retries. An orchestrator that retries a worker, where the worker also retries its model calls, gives a product of attempts. Set the retry limit at one level.
- Parallel calls hit rate limits. Ten workers started together may exceed your requests-per-minute quota. The rejected calls are retried, which adds delay and can erase the gain from parallelism. Limit concurrency with a semaphore.
- Ping-pong loops. Two agents handing the task back and forth burn tokens until
max_turnsstops them. A long history makes each turn in the loop more expensive than the last. - Time to first token. Users often perceive latency as the wait before anything appears. In an orchestrator, the user sees nothing until the final agent starts. Streaming progress messages, such as "Researching...", improves perceived speed without changing real speed.
Measuring it
Cost and latency need data from the tracing setup from the observability chapter. For each model call, record:
- the agent name
- the model
- input and output token counts
- duration
- whether it was a retry
Then compute cost per agent and per request, and the share of wall-clock time spent waiting on sequential steps. The agent with the highest cost is not always the one you expect. Often it is a mid-chain agent that carries a long history.
Exercise
A three-agent handoff chain (triage, billing, refunds) runs on one large model. The conversation history reaches 6,000 tokens by the time the refunds agent starts, and every call re-sends it. A teammate proposes making triage a small model. Name one change that would save more tokens than that, and say why.
Show answer
Replace the full history with a structured handoff payload (goal, facts, open questions, constraints) when control moves to billing and again to refunds. Triage runs only once, early, with a short history, so shrinking its model saves little. The 6,000-token history is re-sent on every later call, so cutting it to a few hundred tokens reduces input on every remaining turn. Switching agents also breaks the prompt-cache prefix, so a shorter payload reduces the uncached portion too.
Exercise
An orchestrator calls three independent workers that take 6, 4.5, and 5 seconds. Each retries once on a timeout, and the orchestrator also retries a failed worker once. What is the latency of the parallel run when nothing fails, what is the worst-case number of model attempts for one worker, and which design fix removes the multiplication?
Show answer
With no failures, the parallel latency is the slowest worker, 6 seconds. In the worst case a worker makes 4 attempts: the orchestrator's 2 attempts, each containing the worker's own 2 attempts. Retrying at only one level, for example in the orchestrator, removes the multiplication and caps attempts at the limit you choose.