Practicing LLM Agent Tasks: Model Selection, Cost, and Error Correction Essentials
This article provides a practical guide to building reliable LLM-based agents for complex, multi-step tasks. It outlines a framework for decomposing agent quality into measurable dimensions, constructing a benchmark task set, and implementing a unified adapter layer to decouple business logic from specific model providers. The discussion covers cost calculation based on real token usage, a three-tier self-checking and correction mechanism, and actionable tips for ensuring consistency and reliability before production deployment.
From Single-Turn Q&A to Multi-Step Agents
The fundamental difference between an agent and a standard Q&A system lies in its ability to interpret a goal, break it down into steps, call tools, observe results, and adjust course when necessary. A typical text analysis task, for example, involves reading source material, extracting key elements, synthesizing viewpoints, cross-verifying facts, and generating a report. An error at any step propagates downstream and can compromise the final conclusion.
In practice, multi-step tasks often encounter three common types of issues:
- Instruction Misunderstanding: The model treats a constraint as optional or misses a sub-goal. For instance, a prompt may ask for “original text evidence for each viewpoint,” but the model only returns the conclusions.
- Insufficient Planning: The model begins execution directly without first outlining steps, dependencies, and acceptance criteria, leading it astray mid-task.
- Lack of Self-Correction: The model fails to verify facts, numbers, or formatting after generating output, allowing errors to be treated as correct results and forwarded down the pipeline.
These problems are not heavily correlated with the raw parameter count of a model. They are more dependent on the model’s inherent abilities in planning, instruction-following, and reflection, as well as the quality of the prompt and workflow design. Therefore, when evaluating an agent’s capability, it is more effective to focus on these general-purpose abilities rather than on performance in a single demonstration.
Breaking Down “Good Performance” into Measurable Metrics
Subjective impressions are difficult to compare fairly across different models. A more robust approach is to decompose capability into several dimensions and score each one systematically. It is recommended to cover at least the following six aspects.
1. Instruction Following
Check whether the model fully executes all constraints, including output format, length limits, prohibited words, and citation requirements. This dimension can be judged directly using rules, making it objective and suitable as a basic entry-level test.
2. Task Comprehension
Examine whether the model can recognize implicit requirements. When information is missing, a good model will proactively ask for clarification or make a reasonable assumption with a clear statement of that assumption. Models that only mechanically execute literal prompts often require multiple iterations and rework in complex tasks.
3. Planning Ability
Observe whether the model presents an ordered set of steps and indicates the dependencies between them. Planning quality can be assessed through manual sampling or by using an evaluation prompt to score the plan.
4. Tool Usage
Check whether the model passes correct parameters when calling a tool, and whether it changes its strategy after receiving an error rather than repeating the same failed request.
5. Self-Correction
Assess whether the model can detect contradictions, omissions, and factual errors in its own output, and provide a revised version. This is critical for long-running, multi-step processes.
6. Cost and Latency
Track the number of input tokens, output tokens, and the total completion time for each task. Resource consumption can vary significantly across models for the same task, and this dimension directly impacts the long-term operating cost.
In addition, generalization capability is worth considering—whether the model can transfer the rules from examples to new, similar tasks. If a model can only reproduce training examples without extending beyond them, its applicability in real business scenarios will be narrow.
Building a Benchmark Task Set
The credibility of an evaluation depends on how the task set is designed. It is advisable to structure tasks by difficulty and type:
- Single-Step Tasks: For summarization, classification, and entity extraction, used to validate basic capabilities.
- Multi-Step Tasks: Such as extracting elements, comparing them, and then synthesizing conclusions, used to assess planning and execution continuity.
- Constrained Tasks: Tasks with specific requirements such as limited word count, defined output format, or mandatory citations, used to test instruction following.
- Trap Tasks: Materials containing intentionally contradictory data or missing information, used to see if the model can identify and flag issues.
To ensure comparability across models, prompts, temperature parameters, and output formats must be fixed. Since model results can fluctuate between runs, each test case should be sampled multiple times and the pass rate aggregated, rather than relying on a single run. A simplified evaluation framework is shown below:
import jsonfrom dataclasses import dataclass, fieldfrom typing import Callable@dataclassclass EvalCase:case_id: strprompt: strchecks: list[Callable[[str], bool]] = field(default_factory=list)def has_json_keys(keys: list[str]) -> Callable[[str], bool]:"""Checks that the output is valid JSON and contains specific fields."""def check(text: str) -> bool:try:data = json.loads(text)except json.JSONDecodeError:return Falsereturn isinstance(data, dict) and all(k in data for k in keys)return checkdef run_suite(adapter, cases: list[EvalCase], runs: int = 3) -> dict[str, float]:"""Runs each case multiple times and returns the pass rate."""report = {}for case in cases:passed = 0for _ in range(runs):output = adapter.generate(case.prompt)if all(check(output) for check in case.checks):passed += 1report[case.case_id] = passed / runsreturn report
Pass rates can be aggregated by dimension to form a capability profile. For critical business areas, a pass rate threshold should be included in the release process. Models or prompt versions that fall below the threshold should not be deployed to production.
Adapter Layer Design: Decoupling the Framework from the Model
The pace of model iteration is fast. If business code directly depends on the specific request formats and authentication of a single model provider, every model switch will require extensive changes. A more stable approach is to introduce a unified adapter layer, encapsulating the differences within the adapter itself:
class ModelAdapter:def generate(self, prompt: str, max_output_tokens: int) -> str:raise NotImplementedErrorclass VendorAAdapter(ModelAdapter):def generate(self, prompt: str, max_output_tokens: int) -> str:# Encapsulate the specific service's request format, authentication, and retry logic here....
The adapter layer brings three key benefits. First, switching models requires only adding a new adapter, while task definitions, evaluation sets, and business logic remain unchanged. Second, the adapter layer can uniformly log token usage, latency, and error types, producing comparable metrics. Third, it enables canary releases, where a portion of traffic is routed to a new model, metrics are observed, and only then is a full rollout considered.
Cost Calculation: Measure Per-Task Costs
When comparing usage-based billing with subscription plans, the per-task cost should be the baseline, not just the total bill or spending rate. The per-task cost for usage-based billing can be estimated as:
Per-task cost = (Input token count × Input unit price) + (Output token count × Output unit price)
The amortized per-task cost for a subscription plan is calculated as:
Amortized per-task cost = Monthly fee ÷ Estimated number of valid tasks completed per month
Both methods should use actual token consumption from real tasks, not estimates based on impressions. Note that reasoning-focused models may generate a lengthy internal reasoning chain before producing the final answer, and this chain is also billed as output tokens. When the reasoning chain is long, the actual cost can be noticeably higher than expected.
To control costs, consider the following measures:
- Set a maximum output token limit and truncate or route to failure handling when the limit is exceeded.
- Simplify system prompts by removing task-irrelevant descriptions, reducing the fixed overhead on every call.
- Break large tasks into smaller steps, passing only the necessary context between steps.
- Opt for smaller models for simple subtasks, such as format conversion or keyword extraction.
- Enable caching for repeated context if the provider supports it.
Designing a Self-Correction Mechanism
The reliability of an agent largely depends on its error correction capabilities. A three-tier approach can be implemented:
- Structural Validation: Check the output format using JSON Schema or regular expressions. Format errors trigger a retry immediately.
- Rule-Based Validation: Verify that numbers match the original text, citations are actually from the given material, and word counts are within the required limits. These checks are handled programmatically, making them low-cost and stable.
- Model Review: Trigger an additional call to have the model inspect a specific concern rather than rewriting the entire text. The review prompt should be narrowly scoped, for example, “Only verify if the data in the third paragraph is consistent with the table.”
The number of retries must be capped. It is recommended to allow at most two retries, after which the output should return a failure reason and be escalated to manual review. Without a cap, a task caught in a loop can consume significant tokens without generating a usable result.
Practical Recommendations
- Define acceptance criteria before writing the prompt. Once the criteria are clear, both evaluation and error correction have a solid reference point.
- Specify the input, output format, and prohibited behaviors in the task description to reduce the model’s room for improvisation.
- Set timeouts and token limits for long-running tasks to prevent a single call from running indefinitely.
- Save logs for each run, including input, output, latency, and token usage, to support troubleshooting and model comparison.
- Base model selection on evaluation pass rates and per-task costs, not single experiences. A successful single demo does not guarantee stable performance on batch tasks.
