Multi-Step AI Agents: Model Selection and Cost Optimization in Practice
Multi-step agentic work is where large language model capability is being pushed hardest today: producing professional reports, writing and debugging code, or running workflows in a terminal. Each of these requires the model to complete a full chain — understand the request, plan the steps, call tools, verify results, and deliver the output. The difficulty is no longer single-turn accuracy, but stability across long chains, adherence to format constraints, and the number of tokens needed to do the same amount of work. Price per token alone therefore tells you little about cost. This article offers a practical framework across six dimensions: task characteristics, cost modeling, tiered model selection, prompt and caching engineering, evaluation, and observability.
Multi-step agentic tasks are the current main battleground for large model capability. Whether the job is generating a professional report, writing and debugging code, or executing a workflow inside a terminal, the model has to complete an entire chain: understand the requirement, plan the steps, call tools, verify the results, and deliver the output. The challenge these tasks pose is no longer limited to single-turn answer accuracy. It shows up in the stability of long chains, the degree to which format constraints are respected, and the number of tokens required to complete the same amount of work. Nor can model cost be judged by unit price alone. This article presents an actionable framework across six layers: task characteristics, the cost model, tiered model selection, prompt and caching engineering, evaluation systems, and observability.
1. Task characteristics: why multi-step tasks are harder
1.1 Errors accumulate along the chain
A multi-step task is fundamentally a sequential decision process: the output of each step becomes the input of the next. Even with a 95% single-step success rate, the probability that 20 consecutive steps are all correct drops to roughly 36%. As the chain lengthens, propagation and amplification of errors is close to inevitable. The core goal of agent design, then, is to raise single-step quality while shortening the effective chain, strengthening verification, and making it possible to stop the bleeding quickly once something goes wrong.
1.2 Context keeps growing and dilutes attention
Tool return values, intermediate reasoning, and conversation history accumulate continuously and quickly stretch the context window. Three problems follow:
- Critical information gets buried under irrelevant content, and instruction-following degrades;
- Every step must reprocess a long prefix, so inference cost grows linearly;
- Model responses slow down, and end-to-end latency becomes hard to reconcile with interactive requirements.
1.3 Deliverables impose strict format constraints
Output in professional settings usually carries explicit external constraints: enterprise report templates, data table schemas, interface definitions, chart styling. The model must not only be “correct” but also “compliant.” A small formatting deviation can make the output unparseable by downstream systems, forcing the entire round of work to be redone.
1.4 Task cost is determined by total tokens, not by a single call
A task typically needs models of different sizes at different stages. Calling the most capable model at every step multiplies cost; relying on the cheapest model at every step can push total cost up through repeated rework. The key to cost control is allocating model resources sensibly by stage and by difficulty.
2. Cost model: evaluate “cost per task” instead of unit price
2.1 Standard billing dimensions
Mainstream large model APIs generally bill three categories of tokens:
- Input tokens: user prompts, conversation history, system instructions, tool definitions, and tool return values;
- Cached input tokens: the common prefix that matches an earlier request; once a cache hit occurs, these are typically billed at a price significantly below standard input;
- Output tokens: the generated body text, tool call arguments, and reasoning content.
Output tokens deserve particular attention. They usually carry the highest unit price, and they directly determine response latency, which makes them the first lever to pull in any cost optimization effort.
2.2 How to calculate cost per task
The economics of an agent system should be measured by “the average cost of completing one task,” not by a simple unit-price comparison:
Cost per task = cost per step × average effective steps × (1 + rework rate)
Cost per step is the sum of input, cache-hit, and output token counts each multiplied by its respective unit price. This formula exposes a fact that is easy to miss:
- A weaker model with a higher rework rate can end up with a higher real total cost, not a lower one;
- A model that produces verbose output and takes many steps is not necessarily the economical choice, even at a lower unit price.
2.3 Why cost predictability matters
Enterprises care about more than “cheap” — they care about “predictable.” In budget-constrained scenarios, a model that can reliably keep cost per task under a threshold is often more valuable than one with better paper benchmarks but larger cost variance.
def task_cost(input_price, cached_price, output_price, usage, steps=1, retry_rate=0.0):"""Estimate the total cost of completing a single task.input_price / cached_price / output_price: price per million tokensusage: cumulative token usage for one callsteps: average steps per task; retry_rate: failure rework rate"""fresh_tokens = max(usage["input"] - usage["cached"], 0) # input tokens that missed the cachestep_cost = (fresh_tokens * input_price+ usage["cached"] * cached_price+ usage["output"] * output_price) / 1_000_000return step_cost * steps * (1 + retry_rate)
3. Tiered selection: combining flagship and general-purpose models
3.1 How the two model classes are positioned
Mainstream model offerings have settled into two broad positions:
- Flagship models: aimed at complex professional work, offering a higher ceiling in professional writing, scientific research, software development, and visual design. They generally follow complex templates more faithfully, produce higher-quality slides, spreadsheets, and documents, and are stronger at front-end development, game development, and 3D design.
- General-purpose models: aimed at everyday tasks, balancing efficiency with general capability. They typically offer better token economics, complete routine agent flows with fewer tokens, and still produce natural, fluent prose.
The point of selection is not to ask “which model is strongest,” but “which layer of capability matches the difficulty of the task at hand.”
3.2 Tiering principles
| Task type | Recommended strategy | Key consideration |
|---|---|---|
| Complex professional documents, research data analysis | Flagship model as the default | High quality bar; keep rework rate under control first |
| Routine code writing, unit tests | General-purpose model first, escalate on failure | Structured feedback is explicit and easy to verify automatically |
| Multi-turn agent flows | General-purpose model drives the main loop; call the flagship model at critical nodes | Many steps, and the cost of each one accumulates |
| Simple Q&A, summarization, format conversion | General-purpose or small model | Optimize for low latency and high throughput |
3.3 Cascade routing
Tiering loses its point if simple tasks are also handed to flagship models. Cascade routing works like this: first try the cheaper general-purpose model and return the result if verification passes; on failure, hand the existing context to the flagship model rather than starting from scratch.
def run_with_cascade(task, verify, max_rounds=2):"""Cascade routing: try the general-purpose model first, then hand the context to the flagship model on failure."""context = {"task": task, "history": []}models = [("general", 0.1), ("flagship", 1.0)] # ordered from lowest to highest costfor tier, cost_factor in models:for _ in range(max_rounds):context["history"].append({"tier": tier, "task": task})output = call_model(tier, context, cost_factor=cost_factor)if verify(task, output): # the verifier decides whether the output can be deliveredreturn output, tiertask = build_feedback(output) # feed verification errors back to the modelreturn None, None # all attempts failed; hand off to a human or a fallback
In practice you also need a cost ceiling and a fallback path. For example, when every automated attempt fails, route the task to a human review queue so the agent never ends up in an endless retry loop.
4. Improving token efficiency: less output, more completion
Reducing the tokens needed to complete a task improves the cost structure more than simply pushing unit prices down. There are three places to start:
- Replace free-form generation with structured constraints. Use structural constraints such as a JSON Schema to define output fields, so the model generates only what is necessary while downstream parsing becomes more reliable.
RESULT_SCHEMA = {"type": "object","properties": {"summary": {"type": "string", "description": "Conclusion in no more than 100 words"},"data": {"type": "array", "items": {"type": "number"}},"notes": {"type": "string"},},"required": ["summary", "data"],"additionalProperties": False,}
Trim prompts and tool descriptions. Cut repeated examples and redundant instructions, keeping only the constraints that actually affect the task; make tool parameter descriptions precise so the model makes fewer invalid calls caused by misunderstanding.
Cap output length and produce in segments. Set a reasonable maximum output length per turn and generate long documents section by section. This lowers per-turn latency and makes verification and correction more granular.
5. Caching and batching: bring repeated cost down
In agent systems, the system prompt, tool definitions, and long documents form a common prefix that recurs on every call. Designing request structure deliberately lets that portion hit the cache:
- Put stable, unchanging content (system prompt, tool definitions, long-term documents) at the very front;
- Put per-turn content such as user input and tool results at the end;
- Avoid inserting volatile content such as timestamps or random IDs into the common prefix, or the cache will be invalidated.
def build_request(system_prompt, tools, fixed_docs, dynamic_messages):# Fixed prefix: the cacheable part, placed firstprefix = ({"role": "system", "content": system_prompt}+ tools+ fixed_docs)# Dynamic suffix: content that changes every turn, placed lastreturn {"messages": prefix + dynamic_messages}
Task queues and batch processing are also worth introducing. For offline work such as batch document generation or batch data cleaning, accumulating requests into batches and running them asynchronously improves resource utilization and smooths peak load. For non-critical paths with loose consistency requirements, returning results asynchronously is sufficient.
6. Evaluation: build your own task-level benchmark
6.1 Public leaderboards are only a reference
Public evaluations reflect a model’s average capability, but they have three limitations:
- Test items may overlap with training data;
- The evaluation set may diverge from your actual business scenarios;
- Leaderboards generally do not disclose cost per task.
Enterprises therefore need an internal evaluation set that reflects real business.
6.2 Evaluation dimensions
| Dimension | Representative metrics | Notes |
|---|---|---|
| Quality | Task pass rate, field accuracy, code test pass rate | Measured per task, not per single-turn answer |
| Cost | Average token usage per task, cache hit rate | Equally important as quality |
| Latency | Time to first token, task completion time | Affects the interactive experience |
| Stability | Failure rework rate, format parsing failure rate | Determines how far production can rely on it |
6.3 Evaluation process
- Sample tasks from real business traffic to form a tiered evaluation set — for example, simple tasks, multi-step tasks, and professional tasks in set proportions;
- Define an automatically executable verifier for each task (unit tests, field comparison, template rule checks), supplemented by human spot checks where necessary;
- After every model or prompt change, run a regression on the fixed evaluation set and record how the quality and cost curves move;
- Use a canary release so a new version runs on a portion of traffic first, then expand gradually.
6.4 Common pitfalls
- Looking at accuracy without looking at cost: a model that is slightly better but several times more expensive may not suit large-scale use;
- Substituting a general leaderboard for business evaluation: a high leaderboard score does not mean the model can do your task;
- Ignoring long-tail failures: mistakes in a few critical scenarios (such as tasks involving security or compliance judgments) can cancel out the overall gains.
7. Engineering and observability
7.1 A controlled agent execution environment
Agents that touch the terminal, execute code, or read and write files should run in a controlled environment:
- Use containers or sandboxes to isolate the execution environment, and restrict network and file system access;
- Apply an allowlist to tool calls and forbid execution of unauthorized commands;
- Verify execution results a second time so erroneous operations do not spread.
def agent_loop(task, tools, verify, max_steps=20, max_cost=1.0):"""Agent main loop with budget control."""messages = [{"role": "user", "content": task}]total_cost = 0.0for _ in range(max_steps):reply = call_model(messages, tools) # the model returns text or a tool calltotal_cost += reply.usage_costif total_cost > max_cost: # budget guardreturn {"status": "budget_exceeded", "messages": messages}if reply.tool_calls:for call in reply.tool_calls:result = execute_in_sandbox(call) # execute inside the sandboxmessages.append(tool_result(call.id, result))else:if verify(reply.text):return {"status": "done", "output": reply.text}messages.append({"role": "user", "content": "The result did not pass verification; please correct it and retry."})return {"status": "max_steps_reached", "messages": messages}
7.2 End-to-end observability
Bring model calls, tool executions, and verification results into a unified log, and record the token usage and cost of every call. Combined with logging services and monitoring alerts, watch for these anomalies and alert early:
- A sudden spike in cost per task;
- A rise in tool call failure rate;
- An abnormal increase in average steps per task.
8. Recommendations for enterprise adoption
- Tier by task, not by loyalty to a model: let general-purpose models handle high-frequency, low-complexity work, and reserve flagship models for genuinely complex, critical tasks;
- Use cost per task as the common metric: with comparable quality, prefer the option with better token efficiency and better cache friendliness;
- Build a sustainable evaluation loop: treat the business evaluation set as a technical asset and regress against it on every change;
- Bake cost and reliability into system design: budget ceilings, cascade routing, fallback paths, and sandbox isolation make agents controllable, auditable, and optimizable in production.
As model capability keeps evolving, model selection is no longer a one-time decision but a dynamic process that must stay aligned with business scenarios, cost structure, and reliability requirements. Mastering the methods above is what turns large model capability into real productivity — stably and economically.
