如何用 Messages API 复现 Claude 的 DeepSearchQA 与 BrowseComp 代理搜索基准分数

原创2026-09-08 19:33:221,967 阅读
文章标签:示例工程人工智能大模型

如何用 Messages API 复现 Claude 的 DeepSearchQA 与 BrowseComp 代理搜索基准分数

Claude 公开发布的代理搜索基准分数(DeepSearchQA、BrowseComp)可以在公开的 Messages API 上复现,前提是把 harness(评测脚手架)配置对。短对话里无关紧要的几个 API 参数——工具调用方式、thinking 模式、输出预算、上下文压缩——在 agent 连续执行 30 次以上工具调用、处理数十万 token 的长任务中会变成决定分数的关键。第三方评测分数偏低,常见原因就是 harness 配置与官方评测不一致。

仓库中的 reproduce_agentic_search_benchmarks.ipynb 完整走了一遍这个过程,配套代码在 utils/agentic_search.py。本文按该 notebook 的章节顺序整理:先搭客户端,再配工具与请求参数,然后跑通回合循环,最后用裁判模型打分验证,并说明如何扩展到完整数据集和适配 BrowseComp。

注意成本与运行时间:notebook 里可运行的 cell 只跑 3 道演示题(约 5–10 分钟、几美元 API 开销);完整复现 900 题的基准需要数百美元和数小时(中等并发下),notebook 本身不会替你重跑全集。

准备条件

按 notebook 的 Prerequisites 一节:

安装依赖:

pip install -U "anthropic>=0.111.0" pandas python-dotenv

客户端配置:长任务下的超时与重试

Server tools 会让一次流式调用在沙箱里先跑很多分钟的工具执行才返回第一个 token,所以默认超时不够用。notebook 把读超时提到 60 分钟;因为使用了流式,这是"每个事件之间"的上限而不是整个响应的上限,真正管用的是首个事件到达前的那段空窗:

import anthropic
from dotenv import load_dotenv

load_dotenv()

MODEL = "claude-sonnet-5"
# Hold the grader model fixed so scores are comparable across the model under test.
GRADER_MODEL = "claude-opus-4-6"

client = anthropic.Anthropic(
    max_retries=20,
    timeout=anthropic.Timeout(5.0, read=3600.0, write=600.0, pool=600.0),
)

max_retries 默认是 2 次,这里设为 20,避免完整基准运行中途因短暂过载把整题记为零分。

工具配置:把搜索放进 code_execution 沙箱

最大的效率杠杆是程序化工具调用(Programmatic Tool Calling,PTC):Claude 不直接调用 web_search / web_fetch 再把每个结果绕回 API,而是在 code_execution 沙箱里写 Python、在代码内部完成搜索和抓取,只有代码打印的摘要回到对话里。深研究类问题单题可能发出 50+ 次 fetch,没有 PTC 时每个网页正文都会进入上下文;有 PTC 后模型在沙箱内读取,只把需要的部分带出来。

TOOLS = [
    {
        "type": "code_execution_20260521",
        "name": "code_execution",
    },
    {
        "type": "web_search_20260318",
        "name": "web_search",
        "max_uses": 10_000,
        "allowed_callers": ["code_execution_20260521"],
        "response_inclusion": "excluded",
    },
    {
        "type": "web_fetch_20260318",
        "name": "web_fetch",
        "max_uses": 10_000,
        "max_content_tokens": 1_000_000,
        "allowed_callers": ["code_execution_20260521"],
        "response_inclusion": "excluded",
    },
]

BETAS = [
    "compact-2026-01-12",
    "task-budgets-2026-03-13",
]

两个细节:

  • code_execution_20260521 的工具 prompt 会披露沙箱的单 cell 墙钟时限,Claude 因此会把长搜索拆成多个短 cell,而不是写一个大循环等到超时。
  • response_inclusion: "excluded" 让 web_search / web_fetch 的结果留在沙箱内;响应里其余部分(thinking、text、server_tool_use、代码执行结果、compaction)随后文回合循环用 model_dump() 回传。

请求级参数:effort、task_budget 与压缩触发器

四个请求级参数决定 Claude"多努力地工作"以及"如何管理自己的上下文":

THINKING = {"type": "adaptive"}

OUTPUT_CONFIG = {
    "effort": "max",
    "task_budget": {"type": "tokens", "total": 3_000_000},
}

# Match the system-card configuration. To reproduce a different model's score,
# use the effort tier and compaction trigger from that model's model card.
COMPACTION_TRIGGER = 200_000

COMPACT_INSTRUCTIONS = (
    "Your summary MUST begin by restating the user's ORIGINAL QUESTION "
    "verbatim and in full, wrapped in <original_question> and "
    "</original_question> tags. Then summarize the research progress so "
    "far: key sources found, data extracted, partial answers, and what "
    "remains to be done. Do NOT call any tools. Your summary MUST also "
    "include this instruction verbatim: 'Provide your final answer "
    "wrapped in <result> and </result> tags.'"
)

CONTEXT_MANAGEMENT = {
    "edits": [
        {
            "type": "compact_20260112",
            "trigger": {"type": "input_tokens", "value": COMPACTION_TRIGGER},
            "instructions": COMPACT_INSTRUCTIONS,
        }
    ]
}

参数与用途的对应关系(按 notebook 的说明):

参数 作用
thinking: adaptive 让 Claude 在工具结果出乎意料时调用间思考,不意外时跳过
effort 模型卡上的分数是在该模型最高 effort 档位报告的
task_budget.total 告诉 Claude 它跨所有回合与压缩的累计输出预算,让它自我配速而不是过早放弃

为什么 COMPACT_INSTRUCTIONS 不能省

对话到达触发阈值时,API 会用一次独立的模型调用总结历史,agent 从摘要继续。默认的总结 prompt 是任务无关的——它不知道在基准场景下,原始问题和答案格式指令是压缩后必须存活的两样东西。没有自定义 instructions,压缩后的 agent 只知道"找到了什么"而不知道"被问了什么",长问题上它会向用户复述问题,直接记零分。

这个收益随压缩触发频率放大:低触发阈值下(单题可能压缩多次)收益最大,本例 200K 触发下较小,但它是 harness 里最便宜的保险。

notebook 还指出一个 model card 细节:最新 Claude 模型卡的 DeepSearchQA 分数是不带压缩报告的(模型有 1M token 上下文,1M 预算的任务装得进一个窗口),BrowseComp 则是带 3M 总预算压缩报告的。本文采用 3M 预算的 BrowseComp 配置使压缩有意义;在 DeepSearchQA 上多数题目远低于 1M 结束,不会触发压缩。

回合循环:pause_turn、容器持久化与历史裁剪

Server tools 下每次 API 调用内部可以跑很多轮工具迭代,然后以 stop_reason="pause_turn" 检查点返回。客户端职责只有三件:把响应内容作为 assistant 轮次追加、再次调用、直到 stop_reason="end_turn"。

先把压缩之前的历史裁掉。服务器压缩时已经丢弃了那段历史,重发它纯属开销,长任务上还可能超过 32 MB 的请求体上限:

def truncate_to_last_compaction(messages: list[dict]) -> list[dict]:
    """Drop history that precedes the most recent compaction block.

    The server already discarded that history when it compacted; resending it is
    pure overhead and on long runs can exceed the 32 MB request-body limit.
    `messages[0]` (the original user prompt) is always kept so the request still
    starts with a user turn.
    """
    for mi in range(len(messages) - 1, 0, -1):
        content = messages[mi].get("content")
        if not isinstance(content, list):
            continue
        for bi in range(len(content) - 1, -1, -1):
            blk = content[bi]
            if isinstance(blk, dict) and blk.get("type") == "compaction":
                trimmed = {**messages[mi], "content": content[bi:]}
                return [messages[0], trimmed, *messages[mi + 1 :]]
    return messages

主循环 sample() 单题跑到完成,每一行都服务于真实基准运行(用户消息上的 cache_control 让整个请求开启 prompt caching,server-side 工具循环在迭代之间命中缓存):

import time
from utils.agentic_search import (
    USER_PROMPT_TEMPLATE,
    extract_result_tag,
    summarize_response,
)


def sample(question: str, *, max_turns: int = 100) -> dict:
    """Run one question to completion through the agentic search loop."""
    messages = [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": USER_PROMPT_TEMPLATE.format(question=question),
                    "cache_control": {"type": "ephemeral"},
                }
            ],
        }
    ]
    request = {
        "model": MODEL,
        "max_tokens": 64_000,
        "tools": TOOLS,
        "betas": BETAS,
        "thinking": THINKING,
        "output_config": OUTPUT_CONFIG,
        "context_management": CONTEXT_MANAGEMENT,
        "messages": messages,
    }

    usage = {"input_tokens": 0, "output_tokens": 0, "cache_read_input_tokens": 0}
    transcript: list[str] = []
    tool_calls = 0
    start = time.time()

    for turn in range(max_turns):
        # Stream so the per-event read-timeout applies, not a per-response one.
        with client.beta.messages.stream(**request) as stream:
            response = stream.get_final_message()

        usage["input_tokens"] += response.usage.input_tokens
        usage["output_tokens"] += response.usage.output_tokens
        usage["cache_read_input_tokens"] += (
            getattr(response.usage, "cache_read_input_tokens", 0) or 0
        )
        tool_calls += sum(
            1 for b in response.content if getattr(b, "type", "") == "server_tool_use"
        )
        transcript.append(f"--- turn {turn} ---\n" + summarize_response(response))

        # Persist the code-execution container so state survives across turns.
        if getattr(response, "container", None) is not None:
            request["container"] = response.container.id

        # Round-trip: append assistant content, drop pre-compaction history.
        messages.append(
            {
                "role": "assistant",
                "content": [b.model_dump(exclude_none=True) for b in response.content],
            }
        )
        messages[:] = truncate_to_last_compaction(messages)

        if response.stop_reason == "end_turn":
            final_text = "".join(
                b.text for b in response.content if getattr(b, "type", "") == "text"
            )
            return {
                "text": final_text,
                "result": extract_result_tag(final_text),
                "turns": turn + 1,
                "tool_calls": tool_calls,
                "elapsed_s": time.time() - start,
                "usage": usage,
                "transcript": transcript,
            }
        if response.stop_reason not in ("pause_turn", "max_tokens"):
            raise RuntimeError(f"unexpected stop_reason={response.stop_reason}")

    raise RuntimeError(f"did not finish within {max_turns} turns")

循环里容易漏掉的三处:container id 必须在轮次间回传,沙箱状态(变量、文件)才能跨回合存活;assistant 内容要 model_dump(exclude_none=True) 完整回传;每一轮结束都要重新裁剪压缩前历史。

重试策略与静默限流的排查

SDK 对连接错误、408、409、429 和 >=500 响应自动指数退避重试,并遵守限流响应里的 Retry-After 头。客户端侧重试默认 2 次,上文已设为 20 次。

文档特别指出一个不报错的失败模式:server tools 的速率限制与模型 token 限额是分开的。工具限流耗尽时不会抛 API 错误,too_many_requests 会以工具结果错误的形式出现在响应内部,Claude 通常会在沙箱内自行重试。判断方法:如果完整基准跑完分数异常偏低且全程没有异常,就检查 result["transcript"] 里是否有打印 rate_limit_error 或 too_many_requests 的代码执行 cell。客户端侧重试帮不上忙(API 调用本身返回了 200),正确动作是降低并发,或联系 Anthropic 支持提高工具限流。

另外文档建议把每题的 sample() 调用包在 try/except 里,让单次 stop_reason="refusal" 或不可恢复错误只把该题记为零分,而不是中断整个运行。

评分:固定裁判模型的 F1 打分

基准打分用 model-as-judge 的 F1 裁判:裁判看到问题、标准答案和从响应中提取的 <result> 文本,报告哪些标准答案项被命中、哪些是多余项,据此计算 precision、recall 和 F1。解析与 F1 计算在 utils/agentic_search.py 中。

两点必须做对:

  • 只评 <result> 标签内的文本,不评整个响应。 完整响应包含规划过程和搜索摘要,喂给裁判会同时抬高误报和漏报。extract_result_tag() 只取最后一个 <result>...</result> 内容。
  • 裁判模型固定为 claude-opus-4-6,与待测模型无关。用待测模型自己打分会让跨模型分数失去可比性。
from utils.agentic_search import grade_response

grade = grade_response(client, GRADER_MODEL, SAMPLE_QUESTIONS[0], result["text"])
print(f"precision : {grade['precision']:.2f}")
print(f"recall    : {grade['recall']:.2f}")
print(f"F1        : {grade['f1']:.2f}")

验证:先跑通 3 道演示题

演示用的 3 道题是本 cookbook 自写的(不是取自 DeepSearchQA-900),目的是让可运行 cell 保持快速、低成本。问题会被包进 USER_PROMPT_TEMPLATE,要求 Claude 自由规划、把最终答案放进 <result> 标签。

单题运行(notebook 中的文档示例输出,实际耗时与 token 数会不同):

tool_calls=4  elapsed=56s
tokens: in=130  out=3,842  cache_read=39,703

Final <result>: **Jamie Dimon**, CEO of **JPMorgan Chase**, ...

然后跑完 3 道题并汇总(文档示例输出):

rows = []
for q in SAMPLE_QUESTIONS:
    r = sample(q["problem"])
    g = grade_response(client, GRADER_MODEL, q, r["text"])
    rows.append({
        "id": q["example_id"],
        "tool_calls": r["tool_calls"],
        "in_tokens": r["usage"]["input_tokens"],
        "out_tokens": r["usage"]["output_tokens"],
        "f1": g["f1"],
        "answer": g["extracted_answer"][:60],
    })

df = pd.DataFrame(rows)
print(df.to_string(index=False))
print(f"\nMean F1: {df['f1'].mean():.2f}")
print(f"Total tokens: {df['in_tokens'].sum():,} in / {df['out_tokens'].sum():,} out")
    id  tool_calls  in_tokens  out_tokens  f1  answer
demo-0          11        312       10503 1.0  **Jamie Dimon**, CEO of **JPMorgan Chase** ...
demo-1           7        208        9768 1.0  The three countries with the largest ...
demo-2           3        104        1592 1.0  - **2021**: *Titane* — directed by Julia ...

Mean F1: 1.00
Total tokens: 624 in / 21,863 out

注意 in_tokens 是未命中缓存的计费输入;开启缓存后大部分实际上下文是 cache read(单独记录在 usage.cache_read_input_tokens)。transcript 里每个回合都是一次 pause_turn 检查点后的沙箱内工具调用批次,可以用它核对循环形态是否符合预期。

扩展到完整基准:数据集与并发

按 notebook 的说法,用同一配置跑完整的 DeepSearchQA-900 与 BrowseComp-1266 可以复现已发布的模型卡分数。数据集的获取入口(notebook 的 Datasets 表格):

基准 规模 来源
BrowseComp 1,266 题 Wei et al., 2025(OpenAI)
DeepSearchQA 900 题 Kaggle Benchmarks(Google DSQA)

harness 要求每行有 problem、answer、answer_type 三个字段;加载自己的数据源时按此映射 schema。

并发扩展按 notebook 的 Next steps:把 sample() 包进 concurrent.futures.ThreadPoolExecutor(客户端是线程安全的),SDK 内置重试已覆盖 429/529;并发 50 时 DeepSearchQA-900 大约 2 小时跑完。若分数整体偏低又没有任何异常,先按上一节检查 transcript 里的工具限流信号再谈其他原因。

适配 BrowseComp

BrowseComp 的题目是单答案型("Which 1995 film…")而非集合型,所以 harness 唯一的变化是裁判函数——工具、betas 和 sample() 循环原样不变:

from utils.agentic_search import grade_browsecomp

# Grading: a single-letter judge (A=correct, B=incorrect, C=abstain).
# accuracy = fraction of "A" verdicts.
bc_grade = grade_browsecomp(client, GRADER_MODEL, SAMPLE_QUESTIONS[0], result["text"])
print(bc_grade)

裁判返回单个字母:A 表示与标准答案匹配,B 不匹配,C 表示拒答;accuracy 就是判为 A 的比例。

如果要严格复现 BrowseComp 的已发布分数,notebook 提示:effort 档位和压缩触发值以模型卡为准,本文 §请求级参数 中的值(effort: max、200K 触发、3M 总预算)是一个可用的默认。这就是这套 harness 的设计意图:循环配对了之后,换基准只是换数据集、改几行配置和换一个裁判函数。

登录后查看全文
claude-cookbooks