ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Agno Accuracy Eval 实战指南:用 LLM-as-Judge 量化 Agent 回答准确率

Agno Accuracy Eval 实战指南:用 LLM-as-Judge 量化 Agent 回答准确率 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字段类型默认值说明inputUnion[str, Callable]必填传给 Agent/Team 的评测问题也可传 callable运行时调用取返回值expected_outputUnion[str, Callable]必填期望答案被评判模型视为“正确基准”同样支持 callableagentOptional[Agent]None待评估的 Agent与team二选一teamOptional[Team]None待评估的 Team与agent二选一nameOptional[str]None评估名称用于展示与落库标识num_iterationsint1重复执行的轮数多轮可得到分数分布与标准差modelOptional[Model]默认OpenAIChat(o4-mini)评判 Agent 使用的模型evaluator_agentOptional[Agent]None自定义评判 Agent覆盖默认评判逻辑additional_guidelinesOptional[Union[str, List[str]]]None追加到评判 prompt 的额外准则additional_contextOptional[str]None追加到评判 prompt 的额外上下文print_summary/print_resultsboolFalse是否打印汇总/逐条结果file_path_to_save_resultsOptional[str]None结果落盘路径支持{name}、{run_id}占位符dbOptional[Union[BaseDb, AsyncBaseDb]]None结果写入数据库如 PostgreSQLtelemetryboolTrue匿名遥测上报开关debug_modebool读取AGNO_DEBUG环境变量打开 debug 日志需要注意的参数约束agent与team必须且只能提供一个。源码在run()与arun()中均做了双重校验两者都为空时记录错误并返回None两者同时提供同样报错见 libs/agno/agno/eval/accuracy.py#L368-L374get_eval_input()与get_eval_expected_output()会在执行前解析 callable若 callable 返回值不是字符串会抛出EvalError见 libs/agno/agno/eval/accuracy.py#L273-L291若model与evaluator_agent均未提供默认使用OpenAIChat(ido4-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-L271agno 内置了一套完整的评判指令核心规则包括只对比不评判基准必须假设expected_output是正确的即使评判者个人不同意也只比较agent_output与expected_output的接近程度两个评分维度Accuracy与期望输出的接近度与 Completeness是否覆盖期望输出的全部关键要素输出结构化评判 Agent 使用output_schemaAccuracyAgentResponse且开启structured_outputsTrue强制返回accuracy_score1–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的计算 Agentimport 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( nameCalculator Evaluation, modelOpenAIChat(ido4-mini), # 评判模型 agentAgent( modelOpenAIChat(idgpt-5.6-luna), # 被评估 Agent tools[CalculatorTools()], ), inputWhat is 10*5 then to the power of 2? do it step by step, expected_output2500, additional_guidelinesAgent output should include the steps and the final answer., num_iterations1, ) # 异步评估 async_evaluation AccuracyEval( modelOpenAIChat(ido4-mini), agentAgent( modelOpenAIChat(idgpt-5.6-luna), tools[CalculatorTools()], ), inputWhat is 10*5 then to the power of 2? do it step by step, expected_output2500, additional_guidelinesAgent output should include the steps and the final answer., num_iterations3, # 跑 3 轮以获得分数分布 ) if __name__ __main__: result: Optional[AccuracyResult] evaluation.run(print_resultsTrue) assert result is not None and result.avg_score 8 async_result: Optional[AccuracyResult] asyncio.run( async_evaluation.arun(print_resultsTrue) ) 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 ideval_{run_id}_{i1}避免多轮之间记忆串扰num_iterations3时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.9evaluation AccuracyEval( nameComparison Evaluation, modelOpenAIChat(ido4-mini), agentAgent( modelOpenAIChat(idgpt-5.6-luna), tools[CalculatorTools()], instructionsYou must use the calculator tools for comparisons., ), input9.11 and 9.9 -- which is bigger?, expected_output9.9, additional_guidelinesIts 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( nameGiven Answer Evaluation, modelOpenAIChat(ido4-mini), inputWhat is 10*5 then to the power of 2? do it step by step, expected_output2500, ) if __name__ __main__: result_with_given_answer: Optional[AccuracyResult] evaluation.run_with_output( output2500, print_resultsTrue ) 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( nameTools Evaluation, modelOpenAIChat(ido4-mini), agentAgent( modelOpenAIChat(idgpt-5.2), tools[CalculatorTools()], ), inputWhat is 10!?, expected_output3628800, )流程上被评估 Agent 在执行10!时会调用CalculatorTools其最终输出再交由评判模型评分。这验证了 accuracy 评估对被评估对象内部行为工具调用与否不敏感——评判只看最终输出与期望输出的匹配度因此它可以统一覆盖普通问答 Agent 与工具型 Agent。八、实战示例五Team 的语言路由准确率Accuracy 评估的对象并不局限于单个 Agent。accuracy_team.py 演示了对一个多语言Team的路由行为进行评估english_agent Agent( nameEnglish Agent, roleYou only answer in English, modelOpenAIChat(idgpt-5.6-luna), ) spanish_agent Agent( nameSpanish Agent, roleYou can only answer in Spanish, modelOpenAIChat(idgpt-5.6-luna), ) multi_language_team Team( nameMulti Language Team, modelOpenAIChat(gpt-5.6-luna), members[english_agent, spanish_agent], respond_directlyTrue, markdownTrue, 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 users input before routing to an agent., ], ) evaluation AccuracyEval( nameMulti Language Team, modelOpenAIChat(ido4-mini), teammulti_language_team, inputComment allez-vous?, expected_outputI can only answer in the following languages: English and Spanish., num_iterations1, )团队内两个成员分别只负责英文和西班牙文Team 充当“语言路由器”输入是法语Comment allez-vous?期望输出是拒绝语——从而验证路由是否把不支持的语种正确地挡在门外通过AccuracyEval(team...)底层run()会自动改用team.run()并记录team_id见 libs/agno/agno/eval/accuracy.py#L405-L407DB 落库与遥测也会区分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( modelOpenAIChat(idgpt-5), output_schemaAccuracyAgentResponse, # 复用官方 schema保证返回结构一致 ) evaluation AccuracyEval( modelOpenAIChat(ido4-mini), agentAgent(modelOpenAIChat(idgpt-5.2), tools[CalculatorTools()]), inputWhat is 10*5 then to the power of 2? do it step by step, expected_output2500, evaluator_agentevaluator_agent, additional_guidelinesAgent 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_output10.1 将评估结果写入 PostgreSQLdb_logging.py 演示了评估完成后把结果持久化from agno.db.postgres.postgres import PostgresDb db_url postgresqlpsycopg://ai:ailocalhost:5432/ai db PostgresDb(db_urldb_url, eval_tableeval_runs_cookbook) evaluation AccuracyEval( dbdb, nameCalculator Evaluation, modelOpenAIChat(ido4-mini), agentAgent( modelOpenAIChat(idgpt-5.6-luna), tools[CalculatorTools()], ), inputWhat is 10*5 then to the power of 2? do it step by step, expected_output2500, additional_guidelinesAgent output should include the steps and the final answer., num_iterations1, )在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 需与同步/异步执行方式配对。此外所有执行路径在telemetryTrue时会上报匿名遥测可在评估器中关闭。10.2 Eval 指标并入 Agent 的 run_outputaccuracy_eval_metrics.pyTEST_LOG 中标记为 PASS演示了一个更精细的能力把评判模型的 token 指标累积进被评估 Agent 的run_output.metrics从而在同一份指标对象里同时看到「agent 模型」与「eval 模型」的用量明细from rich.pretty import pprint agent Agent( modelOpenAIChat(idgpt-5.6-luna), instructionsAnswer factual questions concisely., ) evaluation AccuracyEval( nameCapital Cities, modelOpenAIChat(idgpt-5.6-luna), agentagent, inputWhat is the capital of Japan?, expected_outputTokyo, num_iterations1, ) 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 ( fagent_input\n{eval_input}\n/agent_input\n\n fexpected_output\n{eval_expected}\n/expected_output\n\n fagent_output\n{agent_output}\n/agent_output ) result evaluation.evaluate_answer( inputeval_input, evaluator_agentevaluator_agent, evaluation_inputevaluation_input, evaluator_expected_outputeval_expected, agent_outputagent_output, run_metricsrun_output.metrics, # 关键传入父 run 的 metrics ) if result: print(fScore: {result.score}/10) print(fReason: {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 openaidb_logging.py还需要postgresqlpsycopg连接串对应的数据库可用示例默认postgresqlpsycopg://ai:ailocalhost:5432/ai示例自带断言门槛多数脚本以assert result.avg_score 8收尾分数不达标会抛 AssertionError这本身就是一种「评估驱动回归」的最小 CI 形态环境变量设置AGNO_DEBUGtrue可打开 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 的实现可以沉淀出如下评估套路准备评测集inputexpected_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),仅供参考
返回列表