ag2-evaluation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseEvaluation — run, grade, and track an agent
评估——运行、评分并追踪Agent
When to use
适用场景
- Evaluate / test / benchmark an AG2 , or build a regression / CI gate
Agent - Grade answers for correctness, tool use, cost, or subjective quality
- Track a metric across versions (did this change help or regress?)
To compare two-plus builds head-to-head or on a leaderboard, use .
ag2-eval-comparison- 评估/测试/基准测试AG2 ,或构建回归/CI准入门槛
Agent - 针对正确性、工具使用、成本或主观质量对答案进行评分
- 跨版本追踪指标(此次变更带来了提升还是导致了退化?)
如需对两个及以上版本进行直接对比或查看排行榜,请使用。
ag2-eval-comparisonInstall
安装
bash
pip install "ag2[openai,tracing]"run_agenttracingpip installbash
pip install "ag2[openai,tracing]"run_agenttracingpip installThe loop — dataset, agent, scorers, run_agent
流程——数据集、Agent、评分器、run_agent
python
import asyncio
from ag2 import Agent
from ag2.config import OpenAIConfig
from ag2.eval import Suite, run_agent
from ag2.eval.scorers import final_answer_matches
suite = Suite.from_list([
{"task_id": "france", "inputs": {"input": "Capital of France?"}, "reference_outputs": {"answer": "Paris"}},
{"task_id": "japan", "inputs": {"input": "Capital of Japan?"}, "reference_outputs": {"answer": "Tokyo"}},
])
agent = Agent("geographer", prompt="Answer with the capital city.", config=OpenAIConfig(model="gpt-4o-mini"))
async def main():
result = await run_agent(
suite, agent=agent,
scorers=[final_answer_matches(field="answer", matcher="contains")],
store_dir="./runs",
)
print(result.summary()) # the scorecard
print(result.pass_rate("final_answer_matches")) # 1.0
asyncio.run(main())inputs["input"]reference_outputspython
import asyncio
from ag2 import Agent
from ag2.config import OpenAIConfig
from ag2.eval import Suite, run_agent
from ag2.eval.scorers import final_answer_matches
suite = Suite.from_list([
{"task_id": "france", "inputs": {"input": "Capital of France?"}, "reference_outputs": {"answer": "Paris"}},
{"task_id": "japan", "inputs": {"input": "Capital of Japan?"}, "reference_outputs": {"answer": "Tokyo"}},
])
agent = Agent("geographer", prompt="Answer with the capital city.", config=OpenAIConfig(model="gpt-4o-mini"))
async def main():
result = await run_agent(
suite, agent=agent,
scorers=[final_answer_matches(field="answer", matcher="contains")],
store_dir="./runs",
)
print(result.summary()) # 计分卡
print(result.pass_rate("final_answer_matches")) # 1.0
asyncio.run(main())inputs["input"]reference_outputsScorers
评分器
A scorer asks ONE question. Its RETURN TYPE picks the aggregation:
| return | aggregation | accessor |
|---|---|---|
| pass rate | |
| mean / p50 / p95 | |
| value counts | |
Prebuilt (): , , , , , .
ag2.eval.scorersfinal_answer_matches(field=, matcher="contains"|"casefold"|"exact")tool_called(name)no_tool_errors()token_budget(n)failure_attribution(...)agent_judge(...)Custom — decorate a function that declares what it needs by name (, , , , ):
outputstracereference_outputsinputstaskpython
from ag2.eval import scorer
@scorer
def answered_briefly(outputs) -> bool:
return len(outputs["body"]) < 100 # outputs["body"] = final answer textagent_judge==python
from ag2.eval.scorers import agent_judge
judge = agent_judge(OpenAIConfig(model="gpt-4o"), criterion="Helpful and accurate.", key="quality")每个评分器仅针对一个问题。其返回类型决定了聚合方式:
| 返回类型 | 聚合方式 | 访问方法 |
|---|---|---|
| 通过率 | |
| 平均值/中位数/95分位数 | |
| 数值统计 | |
预构建评分器():、、、、、。
ag2.eval.scorersfinal_answer_matches(field=, matcher="contains"|"casefold"|"exact")tool_called(name)no_tool_errors()token_budget(n)failure_attribution(...)agent_judge(...)自定义评分器——通过装饰器定义函数,并声明所需参数(、、、、):
outputstracereference_outputsinputstaskpython
from ag2.eval import scorer
@scorer
def answered_briefly(outputs) -> bool:
return len(outputs["body"]) < 100 # outputs["body"] = 最终答案文本agent_judge==python
from ag2.eval.scorers import agent_judge
judge = agent_judge(OpenAIConfig(model="gpt-4o"), criterion="Helpful and accurate.", key="quality")CI — deterministic, no API key
CI集成——确定性、无需API密钥
Swap the model for a cassette (a canned reply per task) so CI is free and repeatable. is a — one cassette per task — and overrides the agent's own config for that task:
TestConfigmodel_configdict[task_id, ModelConfig]python
from ag2.testing import TestConfig
agent = Agent("geographer", prompt="Answer with the capital city.") # an Agent instance, not a factory
canned = {"france": TestConfig("Paris"), "japan": TestConfig("Tokyo")}
result = await run_agent(suite, agent=agent, scorers=scorers, model_config=canned, store_dir="./runs")
assert result.pass_rate("final_answer_matches") == 1.0 # the gate将模型替换为测试用例(每个任务对应一个预设回复),使CI流程免费且可重复。为——每个任务对应一个测试用例——会覆盖Agent针对该任务的自有配置:
TestConfigmodel_configdict[task_id, ModelConfig]python
from ag2.testing import TestConfig
agent = Agent("geographer", prompt="Answer with the capital city.") # Agent实例,而非工厂类
canned = {"france": TestConfig("Paris"), "japan": TestConfig("Tokyo")}
result = await run_agent(suite, agent=agent, scorers=scorers, model_config=canned, store_dir="./runs")
assert result.pass_rate("final_answer_matches") == 1.0 # 准入校验Persist, track, grade existing traces
持久化、追踪、评估现有追踪数据
store_dir=python
from ag2.eval import load_run, evaluate_traces, DirectoryTraceSource
assert not result.diff(load_run("./runs/<run_id>.json")).regressions # scorers that flipped pass -> fail
graded = await evaluate_traces(DirectoryTraceSource("./traces"), scorers=scorers, store_dir="./runs")store_dir=python
from ag2.eval import load_run, evaluate_traces, DirectoryTraceSource
assert not result.diff(load_run("./runs/<run_id>.json")).regressions # 从通过变为失败的评分器
graded = await evaluate_traces(DirectoryTraceSource("./traces"), scorers=scorers, store_dir="./runs")Common pitfalls
常见陷阱
- Missing extra —
tracingcan't reconstruct traces. Installrun_agent.ag2[<provider>,tracing] - Return type vs aggregation — for pass/fail, a number for stats, a
boolfor categories; look results up by the scorer'sstr.key - Same model answers and judges — biases ; use a different judge model.
agent_judge
- 缺少扩展包——
tracing无法重建追踪记录。请安装run_agent。ag2[<provider>,tracing] - 返回类型与聚合方式不匹配——用于通过/失败判断,数值类型用于统计,
bool用于分类;需通过评分器的str查找结果。key - 评判与Agent使用同一模型——会导致产生偏差;请使用不同的评判模型。
agent_judge
Going deeper
深入学习
- —
website/docs/user-guide/evaluation/,getting-started(catalog + custom + return-type rules),scorers,runspersistence - — leaderboard (
ag2-eval-comparison) + head-to-head (run_variants)run_pairwise
- ——入门指南、评分器(目录+自定义+返回类型规则)、运行记录、持久化
website/docs/user-guide/evaluation/ - ——排行榜(
ag2-eval-comparison)+ 直接对比(run_variants)run_pairwise