Agno Accuracy Eval 实战指南:用 LLM-as-Judge 量化 Agent 回答准确率
【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agno
本文围绕 agno 的 accuracy 评估能力展开,聚焦 cookbook/09_evals/accuracy 目录下 8 个可运行示例,结合 agno/eval/accuracy.py 源码,系统讲解 AccuracyEval 的评分机制、同步/异步执行、给定答案评分、工具型 Agent 与 Team 路由评估、自定义评判 Agent、PostgreSQL 结果落库,以及 eval 模型指标如何并入 Agent 的 run_output。读完即可照抄示例搭建自己的准确率回归评估流水线。
一、AccuracyEval 是什么:从“跑没跑通”到“答得对不对”
在把 Agent 或 Team 投入生产之前,除了验证「代码能运行」,更需要回答「回答是否正确」。agno 的 accuracy 评估正是为此设计:给定一条输入和一个期望输出,让一个独立的评判模型(evaluator / judge)对 Agent 的实际输出与期望输出进行比对,输出 1–10 的准确率评分与详细理由。
- 这是 LLM-as-Judge 思路在 agno 中的落地实现。核心接口是
AccuracyEval数据类,定义在 libs/agno/agno/eval/accuracy.py; - 评估对象可以是单个
Agent(通过agent=参数),也可以是Team(通过team=参数); - 评估结果汇总为
AccuracyResult,自动计算平均分、均值、最小/最大分和标准差,便于多轮迭代后观察稳定性。
从 cookbook/09_evals/accuracy 的目录组织看,这一专题覆盖了从最简同步评估到团队路由、数据库落库、自定义评判 Agent 的完整场景,是 cookbook/09_evals 中 accuracy 板块的全部可运行示例。
二、核心 API 速览
AccuracyEval的关键字段(见 libs/agno/agno/eval/accuracy.py#L155-L202):
| 字段 | 类型 | 默认值 | 说明 |
|---|---|---|---|
input | Union[str, Callable] | 必填 | 传给 Agent/Team 的评测问题;也可传 callable,运行时调用取返回值 |
expected_output | Union[str, Callable] | 必填 | 期望答案,被评判模型视为“正确基准”,同样支持 callable |
agent | Optional[Agent] | None | 待评估的 Agent(与team二选一) |
team | Optional[Team] | None | 待评估的 Team(与agent二选一) |
name | Optional[str] | None | 评估名称,用于展示与落库标识 |
num_iterations | int | 1 | 重复执行的轮数,多轮可得到分数分布与标准差 |
model | Optional[Model] | 默认OpenAIChat("o4-mini") | 评判 Agent 使用的模型 |
evaluator_agent | Optional[Agent] | None | 自定义评判 Agent(覆盖默认评判逻辑) |
additional_guidelines | Optional[Union[str, List[str]]] | None | 追加到评判 prompt 的额外准则 |
additional_context | Optional[str] | None | 追加到评判 prompt 的额外上下文 |
print_summary/print_results | bool | False | 是否打印汇总/逐条结果 |
file_path_to_save_results | Optional[str] | None | 结果落盘路径,支持{name}、{run_id}占位符 |
db | Optional[Union[BaseDb, AsyncBaseDb]] | None | 结果写入数据库(如 PostgreSQL) |
telemetry | bool | True | 匿名遥测上报开关 |
debug_mode | bool | 读取AGNO_DEBUG环境变量 | 打开 debug 日志 |
需要注意的参数约束:
agent与team必须且只能提供一个。源码在run()与arun()中均做了双重校验:两者都为空时记录错误并返回None,两者同时提供同样报错(见 libs/agno/agno/eval/accuracy.py#L368-L374);get_eval_input()与get_eval_expected_output()会在执行前解析 callable,若 callable 返回值不是字符串会抛出EvalError(见 libs/agno/agno/eval/accuracy.py#L273-L291);- 若
model与evaluator_agent均未提供,默认使用OpenAIChat(id="o4-mini")作为评判模型,并需要环境已安装openai包(见 libs/agno/agno/eval/accuracy.py#L209-L219)。
评分结果对象:AccuracyEvaluation 与 AccuracyResult
- 单次评估结果
AccuracyEvaluation包含input、output、expected_output、score、reason五个字段,可用print_eval()以 Rich 表格渲染(见 libs/agno/agno/eval/accuracy.py#L36-L66); - 汇总结果
AccuracyResult持有run_id与结果列表,并在__post_init__中通过compute_stats()自动计算avg_score、mean_score、min_score、max_score、std_dev_score五个统计量(见 libs/agno/agno/eval/accuracy.py#L69-L97)。因此示例中常见的断言写法result.avg_score >= 8可直接验证平均分是否达标。
三、评判模型如何打分:从 prompt 到结构化输出
在get_evaluator_agent()中(libs/agno/agno/eval/accuracy.py#L204-L271),agno 内置了一套完整的评判指令,核心规则包括:
- 只对比,不评判基准:必须假设
expected_output是正确的,即使评判者个人不同意,也只比较agent_output与expected_output的接近程度; - 两个评分维度:Accuracy(与期望输出的接近度)与 Completeness(是否覆盖期望输出的全部关键要素);
- 输出结构化:评判 Agent 使用
output_schema=AccuracyAgentResponse且开启structured_outputs=True,强制返回accuracy_score(1–10 整数)与accuracy_reason(详细理由)两个字段(见 libs/agno/agno/eval/accuracy.py#L31-L33); - 分数档位:1–2 完全错误/无关;3–4 重大错误或缺失关键信息;5–6 部分正确但有明显问题;7–8 基本准确完整、有轻微问题;9–10 高度准确完整,与期望答案和给定准则高度一致。
在每次迭代中,evaluate_answer()(libs/agno/agno/eval/accuracy.py#L293-L324)会把输入构造成<agent_input>、<expected_output>、<agent_output>三段的拼接 prompt,交给评判 Agent 执行,再校验返回内容是否为AccuracyAgentResponse类型,最后组装成AccuracyEvaluation。异常时记录日志并返回None,外层循环会跳过该次迭代。
additional_guidelines与additional_context会以## Additional Guidelines/## Additional Context小节拼入评判 prompt(见 libs/agno/agno/eval/accuracy.py#L221-L234),这是让评判标准贴合业务语义的主要手段,例如“Agent output should include the steps and the final answer”。
四、实战示例一:同步与异步的基础评估
accuracy_basic.py 演示了最典型的用法——评估一个带CalculatorTools的计算 Agent:
import asyncio from typing import Optional from agno.agent import Agent from agno.eval.accuracy import AccuracyEval, AccuracyResult from agno.models.openai import OpenAIChat from agno.tools.calculator import CalculatorTools # 同步评估 evaluation = AccuracyEval( name="Calculator Evaluation", model=OpenAIChat(id="o4-mini"), # 评判模型 agent=Agent( model=OpenAIChat(id="gpt-5.6-luna"), # 被评估 Agent tools=[CalculatorTools()], ), input="What is 10*5 then to the power of 2? do it step by step", expected_output="2500", additional_guidelines="Agent output should include the steps and the final answer.", num_iterations=1, ) # 异步评估 async_evaluation = AccuracyEval( model=OpenAIChat(id="o4-mini"), agent=Agent( model=OpenAIChat(id="gpt-5.6-luna"), tools=[CalculatorTools()], ), input="What is 10*5 then to the power of 2? do it step by step", expected_output="2500", additional_guidelines="Agent output should include the steps and the final answer.", num_iterations=3, # 跑 3 轮以获得分数分布 ) if __name__ == "__main__": result: Optional[AccuracyResult] = evaluation.run(print_results=True) assert result is not None and result.avg_score >= 8 async_result: Optional[AccuracyResult] = asyncio.run( async_evaluation.arun(print_results=True) ) assert async_result is not None and async_result.avg_score >= 8关键点:
run()与arun()对称存在。两者内部逻辑完全一致,只是分别调用agent.run/team.run与agent.arun/team.arun,异步版本还对应aevaluate_answer()(见 libs/agno/agno/eval/accuracy.py#L504-L646);- 被评估 Agent 每次迭代使用独立 session id
eval_{run_id}_{i+1},避免多轮之间记忆串扰; num_iterations=3时AccuracyResult会自动统计出 3 个分数的均值与标准差,assert avg_score >= 8是示例自带的通过门槛;- 若某次迭代 Agent 未产出有效输出(
output为空),该轮会被跳过并记录 error 日志(见 libs/agno/agno/eval/accuracy.py#L409-L411)。
五、实战示例二:数值比较陷阱——9.11 与 9.9 谁更大
accuracy_9_11_bigger_or_9_99.py 是一个经典的“小数比较”陷阱题,很多模型会因十进制直觉误判 9.11 > 9.9:
evaluation = AccuracyEval( name="Comparison Evaluation", model=OpenAIChat(id="o4-mini"), agent=Agent( model=OpenAIChat(id="gpt-5.6-luna"), tools=[CalculatorTools()], instructions="You must use the calculator tools for comparisons.", ), input="9.11 and 9.9 -- which is bigger?", expected_output="9.9", additional_guidelines="Its ok for the output to include additional text or information relevant to the comparison.", )这个示例展示了 accuracy 评估的两点价值:
- 用
instructions约束被评估 Agent 的行为:强制其使用计算器工具做比较,避免纯文本推理出错; - 用
additional_guidelines放宽评判口径:允许输出附带额外说明文字,只要核心结论9.9正确即可得高分——这说明评判标准的松紧完全由评估者定义,是评估设计中最需要斟酌的部分。
六、实战示例三:不跑 Agent,直接给答案打分
有些场景下输出已经存在(例如人工撰写、缓存结果、其他系统返回),无需再调用被评估 Agent。accuracy_with_given_answer.py 演示了run_with_output()的用法:
evaluation = AccuracyEval( name="Given Answer Evaluation", model=OpenAIChat(id="o4-mini"), input="What is 10*5 then to the power of 2? do it step by step", expected_output="2500", ) if __name__ == "__main__": result_with_given_answer: Optional[AccuracyResult] = evaluation.run_with_output( output="2500", print_results=True ) assert ( result_with_given_answer is not None and result_with_given_answer.avg_score >= 8 )注意此时AccuracyEval甚至可以不提供agent/team,因为不会真正执行被评估对象。run_with_output()(libs/agno/agno/eval/accuracy.py#L648-L762)直接把output作为<agent_output>参与评判,其余流程与run()一致;异步对应arun_with_output()(libs/agno/agno/eval/accuracy.py#L764-L876)。这一能力非常适合用来做「给定答案的快速回归」或「评测集本身的合理性抽检」。
七、实战示例四:评估带工具的 Agent——阶乘计算
accuracy_with_tools.py 与基础示例结构几乎一致,区别在于问题更依赖工具调用,用于验证「工具型 Agent」的答案正确性:
evaluation = AccuracyEval( name="Tools Evaluation", model=OpenAIChat(id="o4-mini"), agent=Agent( model=OpenAIChat(id="gpt-5.2"), tools=[CalculatorTools()], ), input="What is 10!?", expected_output="3628800", )流程上,被评估 Agent 在执行10!时会调用CalculatorTools,其最终输出再交由评判模型评分。这验证了 accuracy 评估对被评估对象内部行为(工具调用与否)不敏感——评判只看最终输出与期望输出的匹配度,因此它可以统一覆盖普通问答 Agent 与工具型 Agent。
八、实战示例五:Team 的语言路由准确率
Accuracy 评估的对象并不局限于单个 Agent。accuracy_team.py 演示了对一个多语言Team的路由行为进行评估:
english_agent = Agent( name="English Agent", role="You only answer in English", model=OpenAIChat(id="gpt-5.6-luna"), ) spanish_agent = Agent( name="Spanish Agent", role="You can only answer in Spanish", model=OpenAIChat(id="gpt-5.6-luna"), ) multi_language_team = Team( name="Multi Language Team", model=OpenAIChat("gpt-5.6-luna"), members=[english_agent, spanish_agent], respond_directly=True, markdown=True, instructions=[ "You are a language router that directs questions to the appropriate language agent.", "If the user asks in a language whose agent is not a team member, respond in English with:", "'I can only answer in the following languages: English and Spanish.", "Always check the language of the user's input before routing to an agent.", ], ) evaluation = AccuracyEval( name="Multi Language Team", model=OpenAIChat(id="o4-mini"), team=multi_language_team, input="Comment allez-vous?", expected_output="I can only answer in the following languages: English and Spanish.", num_iterations=1, )- 团队内两个成员分别只负责英文和西班牙文,Team 充当“语言路由器”;
- 输入是法语
Comment allez-vous?,期望输出是拒绝语——从而验证路由是否把不支持的语种正确地挡在门外; - 通过
AccuracyEval(team=...),底层run()会自动改用team.run()并记录team_id(见 libs/agno/agno/eval/accuracy.py#L405-L407),DB 落库与遥测也会区分agent_id与team_id(见 libs/agno/agno/eval/accuracy.py#L461-L472)。
这类评估特别适合路由型/编排型 Agent:你不关心具体答案,只关心系统是否正确地把请求分派给了预期的处理路径。
九、实战示例六:自定义评判 Agent
内置评判指令不一定满足所有业务,evaluator_agent.py 演示了完全自定义评判者的方式:
from agno.eval.accuracy import AccuracyAgentResponse, AccuracyEval, AccuracyResult evaluator_agent = Agent( model=OpenAIChat(id="gpt-5"), output_schema=AccuracyAgentResponse, # 复用官方 schema,保证返回结构一致 ) evaluation = AccuracyEval( model=OpenAIChat(id="o4-mini"), agent=Agent(model=OpenAIChat(id="gpt-5.2"), tools=[CalculatorTools()]), input="What is 10*5 then to the power of 2? do it step by step", expected_output="2500", evaluator_agent=evaluator_agent, additional_guidelines="Agent output should include the steps and the final answer.", )关键点:get_evaluator_agent()在evaluator_agent非空时直接返回用户提供的评判 Agent(见 libs/agno/agno/eval/accuracy.py#L204-L207)。此时你可以:
- 换用更强或更便宜的模型作为评判者;
- 通过自己的
output_schema自定义返回字段(但官方evaluate_answer会校验返回类型是否为AccuracyAgentResponse,见 libs/agno/agno/eval/accuracy.py#L312-L314,自定义 schema 需与之一致才能被消费); - 在自定义 Agent 的 system prompt 中植入更细粒度的领域评判规则。
十、实战示例七:结果落库 PostgreSQL 与指标并入 run_output
10.1 将评估结果写入 PostgreSQL
db_logging.py 演示了评估完成后把结果持久化:
from agno.db.postgres.postgres import PostgresDb db_url = "postgresql+psycopg://ai:ai@localhost:5432/ai" db = PostgresDb(db_url=db_url, eval_table="eval_runs_cookbook") evaluation = AccuracyEval( db=db, name="Calculator Evaluation", model=OpenAIChat(id="o4-mini"), agent=Agent( model=OpenAIChat(id="gpt-5.6-luna"), tools=[CalculatorTools()], ), input="What is 10*5 then to the power of 2? do it step by step", expected_output="2500", additional_guidelines="Agent output should include the steps and the final answer.", num_iterations=1, )在run()的收尾阶段,若db非空,会调用log_eval_run()把run_id、完整结果、EvalType.ACCURACY、agent_id/team_id、model_id/model_provider、评估名称以及eval_input(含 guidelines、context、iterations、期望输出与输入)一并写入指定的eval_table(见 libs/agno/agno/eval/accuracy.py#L474-L495)。异步场景使用async_log_eval()(见 libs/agno/agno/eval/accuracy.py#L616-L637)。
需要留意:run()遇到AsyncBaseDb会直接抛ValueError并提示改用arun()(见 libs/agno/agno/eval/accuracy.py#L365-L366),同步/异步 DB 需与同步/异步执行方式配对。此外,所有执行路径在telemetry=True时会上报匿名遥测,可在评估器中关闭。
10.2 Eval 指标并入 Agent 的 run_output
accuracy_eval_metrics.py(TEST_LOG 中标记为 PASS)演示了一个更精细的能力:把评判模型的 token 指标累积进被评估 Agent 的run_output.metrics,从而在同一份指标对象里同时看到「agent 模型」与「eval 模型」的用量明细:
from rich.pretty import pprint agent = Agent( model=OpenAIChat(id="gpt-5.6-luna"), instructions="Answer factual questions concisely.", ) evaluation = AccuracyEval( name="Capital Cities", model=OpenAIChat(id="gpt-5.6-luna"), agent=agent, input="What is the capital of Japan?", expected_output="Tokyo", num_iterations=1, ) if __name__ == "__main__": run_output = agent.run("What is the capital of Japan?") agent_output = str(run_output.content) evaluator_agent = evaluation.get_evaluator_agent() eval_input = evaluation.get_eval_input() eval_expected = evaluation.get_eval_expected_output() evaluation_input = ( f"<agent_input>\n{eval_input}\n</agent_input>\n\n" f"<expected_output>\n{eval_expected}\n</expected_output>\n\n" f"<agent_output>\n{agent_output}\n</agent_output>" ) result = evaluation.evaluate_answer( input=eval_input, evaluator_agent=evaluator_agent, evaluation_input=evaluation_input, evaluator_expected_output=eval_expected, agent_output=agent_output, run_metrics=run_output.metrics, # 关键:传入父 run 的 metrics ) if result: print(f"Score: {result.score}/10") print(f"Reason: {result.reason[:200]}") if run_output.metrics: print("\nTotal tokens (agent + eval):", run_output.metrics.total_tokens) if run_output.metrics.details: if "model" in run_output.metrics.details: agent_tokens = sum(m.total_tokens for m in run_output.metrics.details["model"]) print("Agent model tokens:", agent_tokens) if "eval_model" in run_output.metrics.details: eval_tokens = sum(m.total_tokens for m in run_output.metrics.details["eval_model"]) print("Eval model tokens:", eval_tokens) print("\nFull metrics breakdown:") pprint(run_output.metrics.to_dict())其原理在evaluate_answer()/aevaluate_answer()中:当传入run_metrics时,调用agno.metrics.accumulate_eval_metrics(response.metrics, run_metrics)把评判模型的指标累积进去(见 libs/agno/agno/eval/accuracy.py#L306-L310),评判模型在metrics.details中挂到"eval_model"键下,与 Agent 自身的"model"键并列。这样做的收益是:评估成本与主链路成本可以在同一指标对象中对账,方便观测评判环节的开销占比。
十一、如何运行与验证
以上示例均位于 cookbook/09_evals/accuracy,直接以 Python 脚本方式运行:
# 基础同步/异步评估 python cookbook/09_evals/accuracy/accuracy_basic.py # 数值比较评估 python cookbook/09_evals/accuracy/accuracy_9_11_bigger_or_9_99.py # 给定答案评分 python cookbook/09_evals/accuracy/accuracy_with_given_answer.py # 工具型 Agent 评估 python cookbook/09_evals/accuracy/accuracy_with_tools.py # Team 路由评估 python cookbook/09_evals/accuracy/accuracy_team.py # 自定义评判 Agent python cookbook/09_evals/accuracy/evaluator_agent.py # 指标并入 run_output 演示 python cookbook/09_evals/accuracy/accuracy_eval_metrics.py # PostgreSQL 落库(需先启动本地 Postgres) python cookbook/09_evals/accuracy/db_logging.py运行前提与限制:
- 模型依赖:示例使用 OpenAI 系模型(
gpt-5.6-luna、gpt-5.2、o4-mini等),需要有效的OPENAI_API_KEY,并按需pip install openai;db_logging.py还需要postgresql+psycopg连接串对应的数据库可用(示例默认postgresql+psycopg://ai:ai@localhost:5432/ai); - 示例自带断言门槛:多数脚本以
assert result.avg_score >= 8收尾,分数不达标会抛 AssertionError,这本身就是一种「评估驱动回归」的最小 CI 形态; - 环境变量:设置
AGNO_DEBUG=true可打开 debug 日志观察每次迭代的 Agent 输出与评分细节(见 libs/agno/agno/eval/accuracy.py#L195); - 结果落盘:需要持久化 JSON 报告时,可设置
file_path_to_save_results(支持{name}、{run_id}占位符,见 libs/agno/agno/eval/accuracy.py#L191-L193)。
十二、小结:一条可复用的准确率评估流水线
结合 cookbook/09_evals/accuracy 的 8 个示例与 agno/eval/accuracy.py 的实现,可以沉淀出如下评估套路:
- 准备评测集:
input+expected_output成对组织,两者均支持 callable 动态生成; - 选定被评估对象:单 Agent 传
agent=,路由/编排类场景传team=; - 定制评判口径:默认评判 Agent 已内置 1–10 分制与 Accuracy/Completeness 双维度;业务差异通过
additional_guidelines、additional_context或完全自定义evaluator_agent注入; - 决定执行方式:同步
run()/ 异步arun();已有答案时用run_with_output()/arun_with_output(); - 多轮取统计:
num_iterations > 1时可获得avg_score、min/max与std_dev_score,观察模型稳定性; - 结果治理:通过
db=落库 PostgreSQL,通过file_path_to_save_results落盘 JSON,通过run_metrics把评判成本并入主链路指标,配合assert avg_score >= 8即可接入回归门禁。
这套能力让「回答准确率」从主观感受变成可度量、可复现、可追踪的工程指标,是 agno 评估体系中成本最低、上手最快的切入模块。
【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agno
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考