如何評估 AI 智能體:以指標取代憑感覺判斷
How to Evaluate AI Agents: Stop Relying on Vibes and Start Measuring
評估 AI 智能體應以結構化、可重複的指標取代憑輸出是否合理作判斷,並同時檢查元件表現與端到端任務結果。核心指標包括任務完成率、工具及參數正確性、多智能體系統的交接正確性,以及回答是否以提供的上下文或工具輸出為根據。文章示範用 Pydantic 驗證工具選擇與參數 schema,並建議記錄每一步的輸入、輸出、狀態、錯誤和延遲,再結合 3 至 5 項元件指標與端到端測試。
When developers build their first AI agent, evaluation usually looks like this: send a prompt, read the output, nod approvingly because it sounds coherent, and ship it.
This is "vibe-based development." While vibes work fine for quick demos, they fall apart the moment real users interact with your system. An agent can sound exceptionally smart while calling the wrong API, passing hallucinated parameters, or silently failing to complete its primary objective.
To build reliable AI agents for production workflows, you need structured, repeatable metrics instead of intuition.
The Four Core Metrics That Actually Matter
Instead of evaluating agents on vague notions of intelligence, break down performance into component-level checks and end-to-end task validation. Track these four metrics:
- Task Completion Rate (End-to-End): Did the agent achieve the explicit goal? Generating a believable response isn't enough—did the database record update? Was the output action executed?
- Tool and Argument Correctness (Component Level): Did the agent select the correct tool for the sub-task, and did it pass schema-compliant, valid arguments?
- Handoff Correctness (Multi-Agent Systems): If your architecture routes tasks between specialized agents (e.g., a triage agent handing off to a billing agent), did the intent get classified correctly?
- Groundedness: Is the response strictly derived from provided context or tool outputs, or did the model invent data along the way?
Step 1: Implement Component-Level Evaluation Checks
You don't always need complex external platforms to start evaluating your agents. You can write simple deterministic assertion checks for tool calls right inside your testing pipeline.
Here is an example of evaluating tool choice and parameter schemas using Pydantic validation:
from pydantic import BaseModel, Field, ValidationError
class TransferFundsInput(BaseModel):
account_id: str = Field(pattern=r"^ACC-\d{5}$")
amount: float = Field(gt=0)
currency: str = Field(pattern=r"^(USD|EUR|GBP)$")
def evaluate_tool_call(expected_tool: str, actual_tool: str, arguments: dict) -> dict:
if actual_tool != expected_tool:
return {"passed": False, "reason": f"Expected tool '{expected_tool}', got '{actual_tool}'"}
try:
# Validate argument payload against expected schema
validated_args = TransferFundsInput(**arguments)
return {"passed": True, "data": validated_args.model_dump()}
except ValidationError as e:
return {"passed": False, "reason": f"Schema mismatch: {e.errors()}"}
# Example execution trace assertion
agent_tool_choice = "transfer_funds"
agent_args = {"account_id": "ACC-12345", "amount": 150.00, "currency": "USD"}
eval_result = evaluate_tool_call("transfer_funds", agent_tool_choice, agent_args)
print(eval_result)
# Output: {'passed': True, 'data': {'account_id': 'ACC-12345', 'amount': 150.0, 'currency': 'USD'}}
Step 2: Track Traces Over LLM Summaries
A common trap is asking an LLM to evaluate another LLM by reading a high-level summary of what happened. LLM evaluators often suffer from the same blind spots as the agent itself.
Instead, inspect the raw trace. Capture every step of execution:
- System prompt state
- User input
- Tool execution parameters
- Tool response payload
- Final output latency and token consumption
Here is a simple python pattern to capture step execution traces for inspection:
import time
from typing import Any, Callable, Dict, List
class AgentTraceLogger:
def __init__(self):
self.steps: List[Dict[str, Any]] = []
def record_step(self, step_name: str, inputs: Dict, action: Callable, *args, **kwargs):
start_time = time.time()
try:
output = action(*args, **kwargs)
status = "SUCCESS"
error = None
except Exception as e:
output = None
status = "FAILED"
error = str(e)
self.steps.append({
"step": step_name,
"inputs": inputs,
"output": output,
"status": status,
"error": error,
"latency_ms": round((time.time() - start_time) * 1000, 2)
})
return output
# Usage in your pipeline:
# logger = AgentTraceLogger()
# logger.record_step("fetch_user", {"user_id": 42}, fetch_user_func, user_id=42)
By looking at step-by-step traces, you catch hidden bugs—like an agent retrying a failed tool call five times in a loop before generating a polite apology response to the user.
Step 3: Combine Component Metrics with End-to-End Tests
Never rely on a single metric. Pick 3 to 5 metrics that mix component-level checks (argument schemas, handoff intent) with one end-to-end check (did the database state change as requested?).
An agent that sounds smart isn't the same as an agent that works reliably. Moving from vibe checks to structured evaluation metrics is the single biggest difference between a toy project and production-ready infrastructure.
About me
Tanmay builds AI agents and automation for businesses and is open to freelance projects. Feel free to connect with him on LinkedIn.
來源:DEV Community · dev.to