Evaluating and Optimizing Large Language Models for AI Agent Workloads
A practical framework for evaluating and optimizing LLMs in production agent workflows, covering tool-call correctness, instruction following, long-running tasks, multi-step execution, latency, token usage, cost, and reliability. The article also provides metric definitions, a minimal evaluation harness, engineering safeguards, and a model selection checklist.
1. The Starting Point: Two Paths to Optimization
Once AI agents enter production, a recurring pattern emerges: two foundation models may perform similarly on general-purpose benchmarks, yet achieve success rates that differ by an order of magnitude in real automation workflows. The difference is usually not the amount of knowledge they contain, but the quality of their execution.
The industry generally follows one of two paths.
The first is “general-purpose model plus post-training adaptation.” Teams select a strong general-purpose foundation model and compensate for weaknesses in tool use and long-running workflows through prompt engineering, external orchestration frameworks, and retry strategies.
The second is scenario-native optimization. During training, the model is optimized for the core requirements of a target scenario, such as tool calling, instruction following, scheduled and persistent tasks, and long-chain execution. The goal is to make the model more capable of—and more likely to—complete an entire task successfully.
Neither approach is universally superior, but their engineering implications are fundamentally different. The first pushes complexity into the application layer, causing orchestration code to become increasingly elaborate. The second internalizes more complexity in the model, allowing the application layer to remain thinner.
This distinction is essential when interpreting the release of any scenario-optimized model. Its value is primarily reflected in specific workflows, not necessarily in a major change to its position on general-purpose benchmarks.
2. Breaking “Scenario Capability” into Measurable Dimensions
Before evaluating a model designed for automated execution, vague ideas such as “easy to use” must be translated into observable dimensions. At a minimum, an evaluation should cover the following six areas.
1. Tool-call correctness
Do not measure only whether the model called a tool. Evaluate all of the following:
- Whether the function name exists in the provided tool list
- Whether all required parameters are present
- Whether parameter types and value ranges are valid
- Whether the model remains silent when no tool should be called, avoiding unnecessary tool use
2. Instruction following and constraint retention
Focus on scenarios with multiple simultaneous constraints, including formatting requirements, length limits, prohibited items, and conflicting priorities.
A practical metric is the constraint satisfaction rate:
Constraint satisfaction rate =Number of satisfied constraints / Total number of constraints
3. Scheduled and persistent tasks
Evaluate whether the model can correctly express recurring trigger semantics, preserve the task objective over long time spans, and resume from stored state after an interruption instead of restarting from scratch.
4. Long-chain execution
The core metrics are end-to-end success rate and average effective step count. As the chain becomes longer, a 95% per-step reliability rate declines to approximately 36% after 20 steps. Therefore, evaluations must measure step-level success rather than looking only at the final answer.
5. Multi-agent collaboration
Evaluate whether task decomposition is reasonable, whether subtask boundaries are clear, whether conflicts can be detected and reported during result aggregation, and whether agents perform redundant work.
6. High-throughput performance and stability
Under concurrent load, measure latency distributions such as P50, P90, and P99, along with error rates and rate-limit events. A single-call average is not sufficient.
3. Rigorous Definitions for Four Key Metrics
For an evaluation to be reproducible, every metric must have a clear calculation method.
- Accuracy: Number of correct cases divided by the total number of cases. Report accuracy by dimension as well so that the overall score does not conceal specific weaknesses.
- Average latency: Mean end-to-end duration of a single call. The report should specify whether queueing and network time are included. For production model selection, P90 and P99 are generally more informative.
- Average token usage: Mean number of tokens consumed per call. Input and output tokens should be reported separately because they have different billing and latency characteristics. In long-chain scenarios, also measure total tokens per task rather than tokens per individual call.
- Cost per 1,000 calls: This can be derived using the following formulas, making it easier to compare models with different prices.
Cost per 1,000 calls = Average tokens × 1,000 × Unit price / 1,000,000Cost per task = Average calls per task × Average tokens per call × Unit price / 1,000,000
Any specific figure is comparable only when the evaluation set, concurrency level, and decoding parameters are the same. Quoting numbers from different reports without aligning these conditions is one of the most common sources of incorrect model-selection decisions.
4. Why General-Purpose Benchmarks Miss Core Agent Capabilities
This is one of the easiest points to misunderstand. General Chinese-language benchmarks typically focus on single-turn question answering, reading comprehension, general knowledge, and academic tasks. Their agent-related components often cover only lightweight tool selection. They do not adequately represent multi-step dependencies, state retention, failure recovery, or the accumulation of long-context information found in real workflows.
As a result:
- A model specifically optimized for long-chain execution may show only a minor change on a general-purpose benchmark.
- Such a change is statistically expected. It neither proves that the optimization was ineffective nor proves that it was effective.
- The correct conclusion is that general-purpose evaluations reflect the model’s underlying capabilities, not its complete competitiveness in a specific production scenario.
The appropriate approach is to build a private evaluation set that closely matches the target business workflows. A recommended set contains several hundred to several thousand cases, sampled by dimension. Each case should include a reference answer and automatically verifiable validation logic. Random seeds and decoding parameters should also be fixed to ensure reproducibility.
5. The Strategic Shift Behind Faster Inference
When a new model version delivers roughly the same accuracy but significantly lower latency, the result is usually not capability degradation. More often, the inference strategy has shifted from “thinking harder” to “executing more efficiently.”
Common industry techniques include:
- Parallel draft generation and verification during decoding
- Reusing cached prefixes and tool definitions
- Routing requests to different models according to task difficulty
- Distillation and quantization for frequently occurring subtasks
These techniques share the same objective: reduce latency and token consumption while preserving quality. The result is a direct reduction in cost per task.
For users, a combination such as “accuracy increases by 0.5 percentage points while latency is cut in half” often creates more value through cost and user experience than through benchmark ranking. Technical decisions should therefore elevate cost per task and P90 latency to first-class metrics.
6. A Minimal Evaluation Harness
The following example shows the core structure of an evaluation framework and can be mapped to almost any model service interface.
import time, statisticsasync def run_case(client, case, judge):t0 = time.perf_counter()resp = await client.chat(model=MODEL,messages=case.messages,tools=case.tool_specs,temperature=0, # Fix decoding parameters for reproducibility)latency = time.perf_counter() - t0ok, detail = judge(case, resp)return {"id": case.id,"dimension": case.dimension,"ok": ok,"latency": latency,"in_tokens": resp.usage.prompt_tokens,"out_tokens": resp.usage.completion_tokens,"detail": detail,}def summarize(records):n = len(records)acc = sum(r["ok"] for r in records) / nlat = sorted(r["latency"] for r in records)avg_tok = statistics.mean(r["in_tokens"] + r["out_tokens"] for r in records)return {"accuracy": round(acc * 100, 1),"p50": round(lat[int(n * 0.5)], 2),"p99": round(lat[min(int(n * 0.99), n - 1)], 2),"avg_tokens": round(avg_tok, 1),}
For automatic tool-call evaluation, use a two-layer approach: structural validation plus semantic validation.
First, check whether the function name exists and whether required fields, types, and enumerated values are valid. Then verify that the parameter semantics match the intent of the test case—for example, whether a time range is reasonable or whether a target identifier belongs to the candidate set.
def validate_tool_call(call, spec):if call.name not in spec.functions:return False, "unknown_function"schema = spec.functions[call.name]missing = set(schema.required) - set(call.arguments)if missing:return False, f"missing:{sorted(missing)}"for key, rule in schema.properties.items():if key in call.arguments and not rule.check(call.arguments[key]):return False, f"invalid:{key}"return True, "ok"
7. Additional Engineering Constraints for Long-Chain Workflows
Beyond model evaluation, production deployments require three additional safeguards. Otherwise, improvements in model capability may be offset by engineering defects.
- Idempotency and recoverability: Attach an idempotency key to every tool action. Persist task state in external storage so that execution can resume from the most recent checkpoint.
- Step and budget limits: Set maximum step counts, token budgets, and timeouts. When a limit is exceeded, terminate gracefully and report the condition instead of allowing an infinite loop to amplify cost.
- Observability: Record each step’s tool inputs, response summary, duration, and token usage in a logging system. Set monitoring and alerting thresholds for success rate and P99 latency. Distributed tracing is the only reliable way to identify exactly where a workflow began to deviate.
8. Model Selection and Load-Testing Checklist
- Use a private evaluation set rather than public benchmarks for final decisions.
- Report accuracy by dimension instead of relying only on an aggregate score.
- Report P50, P90, and P99 latency together with cost per task.
- Load-test at the target concurrency level and monitor rate limiting and error rates.
- Fix decoding parameters and evaluation-set versions to ensure comparability across model releases.
- Use a gradual rollout and continuously run regression tests on a small proportion of real traffic.
9. Conclusion
The value of a scenario-optimized model is not determined by how many places it advances on a general-purpose leaderboard. Its real value lies in improving three production metrics at the same time: long-chain success rate, instruction-constraint satisfaction rate, and cost per task.
For developers, the essential capability is to establish an evaluation system with clear definitions, automatic validation, and regression support. Once that system is in place, every model iteration can be verified quickly and objectively, and model selection can move from “evaluating marketing claims” to “evaluating data.”
If evaluation data, task state, and workflow traces need to be hosted, general-purpose cloud services for object storage, message queues, container platforms, logging, and monitoring are sufficient. The implementation does not need to be tied to a specific provider or architecture.
