《AI Agent 开发入门》16.2 评测集与打分

本节提供完整 Case、Score、Report 和 evaluate。修订示例使用两条固定用例:检索用例与已知失败用例,不再引用旧六条统计。权重非负且和为一,评测集不能空,case id 不能重复。AgentLoopError 保留部分失败轨迹;脚本耗尽属于运行失败,其他配置错误继续向上暴露。

16.2 固定用例评分与轨迹覆盖

本节提供完整 Case、Score、Report 和 evaluate。修订示例使用两条固定用例:检索用例与已知失败用例,不再引用旧六条统计。

实现选择

工具分是请求覆盖率,答案分是关键字符串覆盖率;引用分要求精确标记与成功 read 结果。模型请求失败或 read 返回 error 不应拿到引用分,仍不能据此证明论断被来源支持。

权重非负且和为一,评测集不能空,case id 不能重复。AgentLoopError 保留部分失败轨迹;脚本耗尽属于运行失败,其他配置错误继续向上暴露。

minagent/evaluate.py

# file: minagent/evaluate.py | write
from __future__ import annotations
from minagent.fake import FakeModel
from minagent.types import Message, ModelResponse, ToolCall
from minagent.tools import Tool, ToolRegistry
from minagent.loop import run, AgentLoopError

from dataclasses import dataclass, field
from typing import Any

@dataclass
class Case:
    id: str
    input: str
    script: list[Any]                       # 脚本化这条的正确/错误行为
    expected_tools: list[str] = field(default_factory=list)
    expected_answer_contains: list[str] = field(default_factory=list)
    expected_citations: list[str] = field(default_factory=list)
    system: str = "你是一个严谨的助手。"

@dataclass
class Score:
    case_id: str
    converged: bool          # 是否成功收敛
    tool_hit: float          # 工具请求覆盖率
    answer_rate: float       # 答案关键点命中率
    citation_rate: float     # 引用标记与成功读取覆盖率
    steps: int               # 步数(过程指标)
    tokens: int              # 估算 token
    cost: float              # 估算成本
    score: float             # 加权综合分
    ok: bool                 # 是否严格全过

import json

PRICE_PER_1K = 0.05  # 元 / 千 token,估算口径


def estimate_tokens(messages) -> int:
    """无真实 usage 时的字符数估算:约 4 字符 1 token。"""
    chars = 0
    for m in messages:
        chars += len(m.content)
        for tc in m.tool_calls:
            chars += len(tc.name) + len(json.dumps(tc.arguments, ensure_ascii=False))
    from .budget import count_messages
    return count_messages(messages)


class Scorer:
    """把一次运行的轨迹折成一个 0~1 的分数,外加过程指标。"""

    def __init__(self, w_tool: float = 0.4, w_answer: float = 0.4, w_cite: float = 0.2) -> None:
        if min(w_tool,w_answer,w_cite)<0 or abs(w_tool+w_answer+w_cite-1)>1e-9: raise ValueError("weights must sum to one")
        self.w_tool, self.w_answer, self.w_cite = w_tool, w_answer, w_cite

    def score(self, case, result, converged: bool):
        actual = [tc.name for m in result.messages for tc in m.tool_calls]
        hit = (len(set(case.expected_tools) & set(actual)) / len(set(case.expected_tools))
               if case.expected_tools else 1.0)
        ans = (sum(k in result.final for k in case.expected_answer_contains)
               / len(case.expected_answer_contains) if case.expected_answer_contains else 1.0)
        from .loop import is_tool_error
        successful={m.tool_call_id for m in result.messages if m.role=="tool" and not is_tool_error(m.content)}
        reads=set()
        for m in result.messages:
            for tc in m.tool_calls:
                if tc.name=="read" and tc.id in successful:
                    doc=tc.arguments.get("doc_id")
                    reads.add(doc)
                    if "chunk_id" in tc.arguments: reads.add(f"{doc}#{tc.arguments['chunk_id']}")
        cite = (sum(f"[{c}]" in result.final and c in reads for c in case.expected_citations)
                / len(case.expected_citations) if case.expected_citations else 1.0)
        tokens = estimate_tokens(result.messages)
        cost = tokens / 1000 * PRICE_PER_1K
        score = self.w_tool * hit + self.w_answer * ans + self.w_cite * cite
        ok = converged and hit == 1.0 and ans == 1.0 and cite == 1.0
        return Score(case.id, converged, round(hit, 3), round(ans, 3), round(cite, 3),
                     len(result.steps), tokens, round(cost, 5), round(score, 3), ok)

@dataclass
class Report:
    scores: list
    pass_rate: float
    avg_score: float
    avg_steps: float
    avg_cost: float

def evaluate(cases,registry,scorer,model_factory=None,max_steps=8):
    if not cases: raise ValueError("empty evaluation set")
    if len({c.id for c in cases})!=len(cases): raise ValueError("duplicate case ids")
    factory=model_factory or (lambda c:FakeModel(c.script)); scores=[]
    for case in cases:
        try:
            result=run(factory(case),registry,case.input,system=case.system,max_steps=max_steps)
            converged=True
        except AgentLoopError as exc:
            result=exc.result; converged=False
        except RuntimeError:
            result=RunResult([],[],""); converged=False
        scores.append(scorer.score(case,result,converged))
    n=len(scores)
    return Report(scores,sum(s.ok for s in scores)/n,sum(s.score for s in scores)/n,
                  sum(s.steps for s in scores)/n,sum(s.cost for s in scores)/n)

def build_cases(cite=False):
    script=[[ToolCall("a","read",{"doc_id":"doc1"})],"检索增强生成 [doc1]"] if cite else ["检索增强生成"]
    return [Case("retrieval","RAG",script,expected_tools=["read"],expected_answer_contains=["检索增强生成"],expected_citations=["doc1"]),
            Case("wrong","加法",["6"],expected_tools=["add"],expected_answer_contains=["5"])]
def build_registry():
    reg=ToolRegistry()
    reg.add(Tool("read","读取",{"type":"object","properties":{"doc_id":{"type":"string"}},"required":["doc_id"]},lambda doc_id:"检索增强生成" if doc_id=="doc1" else '{"error":"missing"}'))
    reg.add(Tool("add","相加",{"type":"object","properties":{"a":{"type":"integer"},"b":{"type":"integer"}},"required":["a","b"]},lambda a,b:a+b))
    return reg

demo_eval.py

# file: demo_eval.py | write
from minagent.evaluate import *
for cite in (False,True):
    report=evaluate(build_cases(cite),build_registry(),Scorer())
    print(cite,report.pass_rate,report.avg_score)
assert evaluate(build_cases(True),build_registry(),Scorer()).pass_rate==0.5

运行与练习

tokens 是最终历史的粗估大小,cost 是示例费率指标;这不是累计 billing usage,也不能把平均历史大小当真实降本证据。真实计费使用第 15.3 节 tracker。

下载全卷项目 。在项目根运行本节 demo 文件;练习检查与故障用例见 tests/test_book.py、tests/test_extensions.py 和附录 B。

阅读导航:上一节:16.1 确定性测试 · 下一节:16.3 对比实验 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「agent」更多文章

  1. 《AI Agent 高级编程》目录
  2. 《AI Agent 高级编程》11.3 全景回顾:从零到框架的完整路径与展望
  3. 《AI Agent 高级编程》11.2 真实 API 冒烟:假模型 vs 真模型量化差距