How to Evaluate LLMs for AI Agent Scenarios: An Empirical Approach

    Selecting the right Large Language Model (LLM) for AI agent scenarios requires a different evaluation strategy compared to traditional Q&A tasks. This article explores key metrics for empirical LLM evaluation, including context caching and cost optimization, tool-calling stability, response latency, and multimodal capabilities. It also provides a reusable Python evaluation framework to help you systematically compare candidate models and make informed selection decisions for your agent workflows.

    1. Why Agent Scenarios Require Dedicated Evaluation

    In traditional Q&A scenarios, a model receives a prompt and returns text, with evaluation focusing primarily on accuracy and fluency. Agent scenarios are fundamentally different. A model must read configurations, query states, call tools, parse returned results, and decide the next action. Each step depends on the output of the previous one, meaning early errors propagate down the execution chain.

    These tasks typically share three characteristics:

    • Long sessions: History messages and tool results continuously accumulate, causing input token counts to grow rapidly.
    • Frequent calls: A single task may trigger dozens of model requests, amplifying latency and cost iteratively.
    • Structured output: Tool parameters must strictly adhere to predefined formats; otherwise, the execution step fails immediately.

    Given these three points, model selection should prioritize cost structure, calling stability, and latency. General benchmark scores should only serve as a secondary reference.

    2. Context Caching and Cost

    In long sessions, each request resubmits a large amount of historical context. If the server-side supports prefix caching (prompt caching), the computation results of identical prefixes can be reused, thereby reducing compute overhead and input-side costs.

    Cache effectiveness can be measured using the hit rate:

    1. Cache hit rate = Cached input tokens / Total input tokens

    Three main factors influence this hit rate:

    First is prefix stability. System prompts and tool definitions should be placed at the beginning of the message sequence and kept constant. Any modification at a given position invalidates the cache for all content following it—for example, inserting a timestamped field at the start of a prompt.

    Second is session length. Longer sessions mean more stable prefixes and higher reuse value. Short sessions yield limited caching benefits.

    Third is request interval. Caches typically have a Time To Live (TTL). If the interval between two requests is too long, the cache will expire.

    In practice, you can adopt the following strategies to improve the hit rate:

    1. Fix system prompts and tool schemas at the beginning of the request, placing dynamic content at the end.
    2. Manage historical messages using an append-only approach to avoid inserting or rearranging in the middle.
    3. Truncate or summarize large blocks of content returned by tools to prevent inefficient context growth.

    Note that caching only reduces input-side costs. The billing for output tokens is unaffected by caching; these should be calculated separately during model selection.

    3. Tool Calling Stability

    Tool calling is the entry point for an agent to interact with external systems and is the most failure-prone link in the chain. Evaluation should focus on three categories of metrics:

    • Format correctness: Whether the generated call parameters comply with the JSON Schema.
    • Selection correctness: Whether the model selects the correct tool among multiple candidates.
    • Chain integrity: During continuous multi-step calls, whether the model stays focused on the original goal without deviating from the path.

    A common practice is to design multi-step test tasks, such as “read a configuration file, compare differences between two versions, and write the results into a structured report.” For each task, record the result of every step to identify where failures concentrate, thereby pinpointing the model’s weak spots.

    Engineering safeguards are equally important:

    • Apply strict schema validation to tool parameters. If validation fails, pass the error message back to the model, allowing it to correct and retry.
    • Set timeouts and maximum retry limits for each tool to prevent the model from entering an infinite loop.
    • Introduce human-in-the-loop confirmation nodes for operations with side effects (e.g., write, delete, send) rather than granting the model complete decision-making authority.

    4. Response Speed and Reasoning Overhead

    An agent’s overall execution time is the cumulative latency of multiple model calls, so single-response speed directly determines task completion time. Common observation metrics include:

    • Time To First Token (TTFT): The time from sending the request to receiving the first output token, determining the perceived startup speed.
    • Output throughput (tokens per second): The number of tokens generated per second during the generation phase, determining the completion time for long outputs.

    Some models support a reasoning mode, generating internal reasoning tokens before providing the final answer. These tokens consume the output quota and add latency. During evaluation, track the ratio of reasoning tokens to visible output tokens to determine if the overhead for complex tasks is acceptable. A high reasoning ratio does not equate to better results; it must be judged alongside task accuracy.

    5. Multimodal Input Capabilities

    Some models can directly process images. In agent scenarios, UI screenshots, charts, and scanned documents can enter the reasoning pipeline without requiring an additional OCR step. During selection, confirm two things: first, the supported image formats, sizes, and resolution limits; second, whether the model can output images. Image reading and generation capabilities are independent of each other; supporting the former does not imply support for the latter.

    6. A Reusable Evaluation Framework

    The following example demonstrates a minimal multi-step task evaluation function. client, run_tool, and validate_tool_args should be replaced with your actual environment implementations. Usage field names may vary across different providers and require proper field mapping.

    1. import json
    2. import time
    3. MAX_STEPS = 20
    4. def evaluate_task(client, model, messages, tools, validate_tool_args, run_tool):
    5. """Evaluate a single multi-step task and return key metrics."""
    6. stats = {
    7. "steps": 0,
    8. "tool_ok": 0,
    9. "tool_fail": 0,
    10. "prompt_tokens": 0,
    11. "cached_tokens": 0,
    12. "reasoning_tokens": 0,
    13. "output_tokens": 0,
    14. "latency_s": [],
    15. }
    16. for _ in range(MAX_STEPS):
    17. t0 = time.perf_counter()
    18. resp = client.chat(model=model, messages=messages, tools=tools)
    19. stats["latency_s"].append(time.perf_counter() - t0)
    20. stats["steps"] += 1
    21. usage = resp["usage"]
    22. stats["prompt_tokens"] += usage["prompt_tokens"]
    23. stats["cached_tokens"] += usage.get("cached_tokens", 0)
    24. stats["reasoning_tokens"] += usage.get("reasoning_tokens", 0)
    25. stats["output_tokens"] += usage["completion_tokens"]
    26. call = resp.get("tool_call")
    27. if call is None:
    28. break # Model provided the final answer, task ends
    29. messages.append(resp["assistant_message"])
    30. try:
    31. args = json.loads(call["arguments"])
    32. validate_tool_args(call["name"], args)
    33. result = run_tool(call["name"], args)
    34. stats["tool_ok"] += 1
    35. except Exception as exc:
    36. stats["tool_fail"] += 1
    37. result = f"error: {exc}"
    38. messages.append({
    39. "role": "tool",
    40. "tool_call_id": call["id"],
    41. "content": str(result),
    42. })
    43. return stats
    44. def summarize(stats):
    45. """Convert raw counts into comparable ratio metrics."""
    46. calls = stats["tool_ok"] + stats["tool_fail"]
    47. return {
    48. "Cache hit rate": stats["cached_tokens"] / max(stats["prompt_tokens"], 1),
    49. "Tool call success rate": stats["tool_ok"] / max(calls, 1),
    50. "Reasoning token ratio": stats["reasoning_tokens"] / max(stats["output_tokens"], 1),
    51. "Avg step latency (s)": sum(stats["latency_s"]) / max(len(stats["latency_s"]), 1),
    52. }

    When evaluating, run the candidate models sequentially using the same set of tasks, tools, and initial context. Take the mean and variance of each metric over multiple runs. Single-run results are susceptible to network jitter and server load, and should not be used directly as a final conclusion.

    7. Recommendations for Model Selection

    Based on the dimensions above, you can organize the selection process in the following order:

    1. Clearly define your business task types, distinguishing between single-turn Q&A, short-process tool calls, and long-chain agent workflows.
    2. Build a test set using real-world multi-step tasks rather than relying solely on generic benchmarks.
    3. Record cache hit rate, tool success rate, reasoning overhead, and latency separately to form a comparison table.
    4. Weigh cost against the cost of failure. For example, tool success rates for high-risk operations should be prioritized over single-response speed.
    5. Conduct a gradual rollout in a low-traffic environment to verify if online metrics align with offline tests.

    Model capability improvements are typically incremental, with differences between versions often reflected in stability, speed, and cost. For agent systems, these metrics often dictate the final user experience more than single-point intelligence. Establishing a fixed evaluation process and re-running it upon model version updates is the foundation for maintaining optimal model selection.