DeepSearch 搜索智能体:openJiuwen 多步探索式状态机的架构与实现解析
DeepSearch 搜索智能体:openJiuwen 多步探索式状态机的架构与实现解析
导读
openJiuwen DeepSearch 的搜索智能体(Search Agent)是其深度搜索与研究能力的核心引擎:它以「状态初始化 → 候选 action 生成 → action 加权采样与执行 → 状态校验」的循环反复探索信息空间,逐步收敛证据并最终产出带片段级引用的研究答案。本文基于 deepsearch/docs/feature/algorithm/search-agent.md 及其四个子文档,结合 openjiuwen_deepsearch/algorithm/search_agent/、search_nodes/、search_tools/、search_index/ 的源码实现,完整讲解搜索智能体的可见行为、节点状态机、Action Pool 采样算法、工具白名单与错误处理,并给出可直接复用的测试验证命令与关键配置参数,帮助你从「会用」深入到「读懂并二次开发」。
一、搜索智能体在 DeepSearch 中的定位与维护范围
1.1 功能目的
DeepSearch 搜索智能体解决的核心问题是:如何通过多轮工具调用自主收集证据,逐步逼近研究问题的答案。它采用循环式探索:
状态初始化 -> 候选 action 生成 -> action 采样与执行 -> 状态校验
- 初始化:把用户问题解析为结构化
State(未知变量列表)。 - 生成:基于 query、当前 state 和已有 result,让 LLM 产出带置信度的候选
ActionProposal。 - 采样与执行:由
ActionPool按评分加权挑选下一步 action,暴露工具给 LLM 调用并执行。 - 校验:判断新状态是否有效、答案是否可信、循环是否应继续。
它支持两种工具模式:web search / fetch(联网探索)与 retrieve-only(固定语料检索),后者用于在预构建索引上做受限的证据检索。
1.2 维护范围(本文档边界)
本文档覆盖以下目录中的搜索智能体能力:
| 目录 | 职责 |
|---|---|
openjiuwen_deepsearch/algorithm/search_agent/ |
搜索 agent 结果解析与 Action Pool |
openjiuwen_deepsearch/algorithm/search_nodes/ |
初始化、find action、run action、tool node、校验等节点状态机 |
openjiuwen_deepsearch/algorithm/search_tools/ |
web search / web fetch / retrieve 工具封装 |
openjiuwen_deepsearch/algorithm/search_index/ |
固定语料索引创建与切分 |
本文档不覆盖上层 workflow 节点编排,也不覆盖报告生成阶段的资料分类与正文写作。相关子能力细节见:
二、可见行为与关键代码路径
2.1 对外可见行为
- 初始状态会被解析为
State,id 固定为0,depth 为0(源码见 initialize_state.py)。 - find action 会生成多个带 score 的
ActionProposal,并绑定当前 state、query 和上下文消息。 - action pool 按 proposal score、candidate strength、depth 和配置权重采样待执行 action。
- run action 会根据模式暴露
web_search/web_fetch或retrieve原生工具,并把 LLM 工具调用结果解析为新状态或答案。 - 工具名会先归一化到白名单,未允许的工具名不会执行(防止 prompt injection)。
2.2 关键代码路径一览
| 功能 | 文件 |
|---|---|
| 搜索 agent 结果解析 | deepsearch_agent.py |
| Action Pool | action_pool.py |
| 初始状态 | initialize_state.py |
| Action 发现 | find_action.py |
| Action 执行 | run_action.py |
| 状态校验 | validate_new_state.py |
| 工具节点 | tool_node.py |
| Web search/fetch 工具 | web_search_tool.py、web_fetch_tool.py |
| Retriever 工具 | retriever_tool.py |
| 检索索引 | search_index/ |
相关 Prompt(均位于 openjiuwen_deepsearch/algorithm/prompts/):
deepsearch_initialize_state.mddeepsearch_find_action_space.mddeepsearch_run_action.mddeepsearch_validator.mddeepsearch_verify.mdsimple_react_search.md
主要测试(位于 deepsearch/tests/):
tests/search_agent/test_initialize_state.pytests/search_agent/test_find_action_space.pytests/search_agent/test_action_pool.pytests/search_agent/test_run_action.pytests/search_agent/test_run_action_node.pytests/search_agent/test_deep_search_agent_smoke.pytests/search_agent/test_integration_search_loop.pytests/search_agent/test_termination.pytests/tools/test_web_search.py
三、核心流程:搜索循环如何运转
整体流程(对应 search-agent.md 与 workflow.py 中的主循环实现):
run_initialize_state调用初始化 Prompt,解析并校验State。run_find_action_space基于 query、state 和已有 result 生成候选 action。ActionPool接收候选 action,按配置进行加权采样、记录运行中和已完成 action。run_action暴露允许的原生工具定义,并把工具调用结果写回消息上下文。- LLM 输出被解析为新
Result或新状态。 - 校验节点判断新状态是否有效、是否已完成、是否需要继续探索。
- 搜索循环把最终结果交给上层 workflow 和报告生成阶段。
3.1 主循环的并发与终止控制
主循环位于 workflow.py 的 DeepSearchAgent 中(run_search_loop 区域):
- 通过
max_workers(PerQuestionParams中默认 5)限制并发执行的 action 协程数,available_slots = max_workers - len(running_tasks),有空闲槽位且 pool 非空时调用action_pool.sample(available_slots)采样。 - 每个 action 通过
asyncio.create_task(run_state_creation_workflow(...))提交,并用asyncio.wait(..., return_when=asyncio.FIRST_COMPLETED)等待完成。 - 单个 action 完成后调用
record_completed;若结果含found_answer则进入答案收敛逻辑(见下)。 - 若 pool 耗尽且无运行任务,会按
retry_count_on_empty_action_space(默认 3)重跑 find_action;当启用dependent_retry策略时,会把已完成的 action direction 与摘要一起注入 prompt(deepsearch_dependent_retry_find_action),避免重复探索。
终止条件(Termination 枚举)包括:
ACTION_POOL_DEPLETED:action pool 耗尽且重试次数用尽。TIME_LIMIT:超过time_limit(默认 4800 秒)。ACTIONS_EXPLORED_LIMIT:超过actions_explored_limit(默认 200,200 即无限制语义需注意配置说明)。FAIL_LIMIT:连续失败次数超过fail_limit(默认 0,即无限制)。
答案收敛策略:answer_mode_top_k 默认 1,即首个找到答案即返回;当大于 1 时进入 top-k 模式,收集够 k 个答案后用 action_pool.get_best_answer() 按 answer_variable 的 candidate_strength 选最优;超时且启用 provide_best_guess 时,用 get_best_guess() 从已完成 action 中挑选 candidate_strength 最高的候选作为兜底答案(termination 为 timeout_guess)。
四、初始状态生成(Initialize State)
4.1 实现与解析
run_initialize_state(initialize_state.py)把 query 包装成 user 消息,调用 deepsearch_initialize_state Prompt(agent_name=AgentLlmName.INITIAL_STATE),随后 parse_and_validate_init_state 完成解析:
- 剥离 thinking 标签:用正则
<think|reasoning|thinking>...</\1>删除推理痕迹,再json.loads。 - 兼容
variables别名:若 JSON 顶层是variables而非state,自动改名为state。 - 用
State(**init_state_dict)构造模型,空状态视为失败(INIT_STATE_FAILED)。 - 强制设置
id="0"、depth=0,作为搜索起点。
4.2 初始化 Prompt 的输出契约
deepsearch_initialize_state.md 要求 LLM 输出如下 JSON(出自 deepsearch_initialize_state.md):
{
"reasoning": "<step-by-step analysis of the question>",
"state": [
{
"id": 1,
"type": "Person",
"question_clues": ["<clue or relationship derived from the question>"],
"discovered_clues": [],
"candidate": null,
"candidate_strength": null
}
],
"answer_variable": 1
}
规则要点:变量必须来自问题中显式提到的未知实体;初始化阶段不得猜测 candidate;candidate_strength 必须是 null 而非空串;answer_variable 必须与某个变量 id 对应——它正是后续验证与答案选择所锚定的变量。
五、候选 Action 发现(Find Action Space)
5.1 实现与重试
run_find_action_space(find_action.py)基于 query、state 和已有 result 生成候选 action,默认 max_tries=4:
- 若 LLM 输出为空或解析失败,重试并追加「修复错误后重试」的 user 消息,两次尝试间
await asyncio.sleep(1)。 - 重试耗尽后返回空 actions 和错误信息(success=False),绝不抛出未包装异常——这与文档「find action 多次解析失败后返回空 actions」的边界要求一致。
- 每次解析使用
json_repair.loads容忍格式瑕疵,并再次剥离<think>标签。
5.2 Action 与 ActionProposal 的组装
parse_and_build_actions 遍历 action_proposals 列表,逐项构建 Action:
- score 缺失兜底:若 proposal 缺
score,会尝试从direction文本中用正则<a href="https://link.gitcode.com/i/da2aa786e34b537557e04c4331669a82" target="_blank">Ss]core[:\s]+([0-9.]+)提取分数并 clamp 到[0, 1];提取不到则按解析错误处理(对应 [find_action.py)。 - action id 使用
f"{state.id}_{secrets.token_hex(3)}"生成,保证稳定唯一(这也是 ActionPool score cache 以 action id 为 key 的前提)。 - 每个
Action绑定state、proposal、question和完整messages上下文。
对应 Prompt 的输出 schema(出自 deepsearch_find_action_space.md):
{
"reasoning": "<strategy analysis>",
"action_proposals": [
{"direction": "<concise, self-contained research action>", "score": 0.8}
]
}
LLM 被要求:不超过 action_proposals_limit(默认 5)个提案;每个 direction 要么聚焦不同变量、要么采用不同方法;鼓励跳出常规思维提出非常规研究角度。
六、Action Pool:加权采样与状态记录
ActionPool(action_pool.py)是搜索循环的「任务调度中枢」,负责候选 action 的入池、评分、采样、状态记录与快照输出。
6.1 评分模型(核心算法)
- 入池预热缓存:
add()时先逐个_get_score(action)计算并缓存 base score,再self._pool.extend(actions);add异常时 pool 保持不变并记录日志。 - base score 计算(
_compute_base_score):
score = action.proposal.score
+ Σ(candidate_strength of each variable with candidate)
- 深度权重(受
depth_weight配置控制,默认 True):- 深度惩罚:
depth > DEPTH_PENALTY_THRESHOLD(5)时score *= (MAX_STATE_DEPTH(12) - depth) / DEPTH_PENALTY_DENOMINATOR(8),即过深状态被降权,且深度超过 12 时趋近于 0。 - 浅层加成:
depth < SHALLOW_DEPTH_THRESHOLD(2)时score += SHALLOW_DEPTH_BONUS(100),即浅层状态获得强加成。
- 深度惩罚:
- pool 相对调整:
promote_unique_states配置开启时(默认 False),对出现次数超过MULTIPLE_STATES_DIVISOR_THRESHOLD(1)的相同状态 hash(由各变量 candidate 小写拼接而成)做score /= count,抑制同一状态被过度重复探索。该因子被刻意排除在 base score 之外,因为它属于采样权重而非 action 固有属性。
6.2 采样逻辑(sample)
sample(k) 调用 _sample_impl:
- immediate queue 优先:若
immediate_queue中有 action,按 FIFO 直接取出(绕过评分逻辑),直到填满 k 或队列清空。 - 随机采样:若
random_sample配置开启(默认 False),直接用random.sample从 pool 抽取。 - 加权采样(默认路径):逐轮按归一化权重
score/total用random.choices抽取,抽到即从_pool.pop移出。 - 采样成功后把结果加入
running_actions并触发快照;sample内任何异常都只记录日志并返回空列表,不阻塞循环。
6.3 状态记录
record_completed(action, result):把 action 从running_actions移除并记入completed_actions;若 running 列表中找不到该 id(可能重复完成或 pool 失同步),仍会记录完成状态并输出 warning。record_successful_answer(action, result)/successful_answer_count():top-k 模式下的成功答案收集。get_best_answer():返回 answer_variable 的candidate_strength最高的(action, result)。get_best_guess():扫描全部已完成 action,返回 answer_variable 有候选且candidate_strength最高者的(action, result, candidate),用于超时兜底。
6.4 快照输出(可观测性)
- 配置了
log_dir时,add/sample/record_completed都会触发_save_pool_json():异步写出action_pool.json(pending/running/completed 三类快照),写入失败只记录日志,绝不影响搜索主流程。 - 写文件采用「临时文件 +
os.replace原子替换」策略,避免读到半截快照;同时通过emit("action_pool_snapshot", ...)发送遥测事件。 - 同一事件循环内多次更新会被合并为一次 flush(
_snapshot_dirty标志 + 单例 flush task),flush_snapshot()可显式等待持久化完成。 - 线程安全边界:ActionPool 只在单个 asyncio 协程上下文中使用,不提供线程安全保证(源码类注释明确说明)。
对应测试:test_action_pool.py 覆盖 immediate queue 优先、record_completed 缺失 running、best guess 选取、快照原子写、flush 失败不阻塞、并发 flush 合并等场景;test_termination.py 覆盖终止逻辑。
七、Action 执行与工具系统(Run Action + Tool Node)
7.1 工具定义:两种模式
get_tool_definitions(retrieval_tool_only)(run_action.py)按模式返回 OpenAI 格式的 function 定义:
- search_fetch 模式(默认,
tool_map="search_fetch"):暴露web_search与web_fetch。 - retrieve 模式(
tool_map="retrieve"):只暴露retrieve,且query支持 1~3 个自然语言 query 一次调用返回合并结果。
7.2 工具名白名单与归一化(安全边界)
resolve_native_tool_call_name(run_action.py):
- 把模型提供的工具名做
strip().lower(),并将空格/连字符替换为下划线,映射到 canonical name:web_search/websearch→web_search,web_fetch/webfetch→web_fetch,retrieve→retrieve。 - 只有命中别名表且属于当前模式允许集合(由
get_tool_definitions决定)的 canonical name 才会返回,否则返回None。 execute_tool(tool_node.py)进一步校验 canonical 是否在tool_map中,非法工具名抛TOOL_EXEC_ERROR并列出允许的工具名——这是防止 prompt injection 调用未授权工具的关键防线。
7.3 工具参数注入
execute_tool 会根据工具类型注入运行参数:
web_fetch:注入log_fetch(默认取配置,StateCreationAgentConfig.log_fetch默认 False)和fetch_tool_model(取自llm_config.general.model_name),并记录new_found_evidence_ids(url+goal)。web_search:注入log_search(默认 True)。retrieve:注入top_k(默认 5)、add_instruction(默认 True)、mode(默认dense,注意RetrievalSettingsConfig.mode默认hybrid)、top_k_multiply_factor(默认 10),并把检索返回的id_list中新增的证据 id 追加到new_found_evidence_ids(去重:排除已存在于 action state 的 id)。
7.4 LLM 结果解析:state / answer / tool_calls 三种模式
parse_run_action_result 与 parse_and_apply_llm_result(run_action.py):
- tool_calls 模式:LLM 返回原生
tool_calls,逐个归一化为{name, arguments, tool_call_id};query/url字段经normalize_str_or_list处理,并调用sanitize_search_query清洗引号与多余空白。 - state 模式:识别
<state>...</state>标签(未闭合时自动补</state>尝试恢复),用json_repair解析;要求顶层含new_states列表,每个分支包含state变量补丁列表。对 LLM 常见错误(扁平变量 dict 未包state包装器)做了自动纠正(_normalize_new_states)。随后apply_patch将补丁合并到 base state 生成新State:只允许修改已存在变量(必须有不可变的id)、depth 自动 +1、新 id 用f"{depth:03x}_{int(time.time()*100):08x}{secrets.token_hex(1)}"生成、discovered_clues按discovered_clues_mode(report/blacklist/none)处理。 - answer 模式:识别
<answer>...</answer>,要求同时含answer与new_state,构造含found_answer的Result。 - 无输出:返回
no_output解析错误,作为 user 消息追加进上下文,让 LLM 下一轮修正(每次失败都会把错误写回 messages)。
7.5 上下文超限策略(context limit)
run_action 调用 LLM 若命中上下文长度错误,按 context_limit_reached_strategy(StateCreationAgentConfig,默认 reduced_retrieval_request)处理(run_action.py):
| 策略 | 行为 |
|---|---|
fail |
立即终止 action(next_node=END_NODE),返回错误 |
reduced_retrieval_request |
将 top_k 与 top_k_multiply_factor 减半后重试(仅 retrieve 模式有效) |
delete_tool_responses |
剥离全部 role=tool 消息后重试 |
delete_tool_input_and_responses |
同时剥离 assistant 的 tool_calls 与 tool 消息后重试 |
上下文超限的判定由 llm_utils.py 的 _is_context_limit_error 完成:匹配 _CONTEXT_LIMIT_PHRASES(context_length_exceeded、too many tokens、prompt is too long 等 19 个短语),并沿 __cause__ 异常链向下检查,兼容「OpenJiuwen 将失败包装成 status 400」的情况。
八、搜索工具封装:web_search / web_fetch / retrieve
8.1 WebSearch:多 query 合并与缓存
WebSearch(web_search_tool.py):
- 接收单个 query 或 query 数组;数组场景用
asyncio.gather并发执行并用\n=======\n合并输出,单个 query 失败不影响其余结果。 - provider 选择:调用 framework 层
get_web_search_api_wrapper()获取「已注册的活动搜索引擎」——即由web_search_engine_config初始化并注册的 wrapper,而不是单独构造 Serper 专用客户端(对应 search-tools.md 的说明)。未初始化活动引擎时返回受控错误文本。 - 结果归一化:把 wrapper 返回的标准化搜索结果的字段(title/name、url/link/source_url、content/snippet/summary 等)统一映射为
title/link/snippet/source/date,格式化为历史兼容的 markdown 文本(编号条目 + Published/Origin/摘要)。 - 缓存与日志:以 query 为 key 从
web_search_log.jsonl读取缓存命中结果;写入时使用跨进程文件锁(Windows 用msvcrt、类 Unix 用fcntl),避免并发写坏日志。
8.2 WebFetch:provider 显式选择与摘要提取
WebFetch(web_fetch_tool.py):
- 构造函数通过
resolve_web_fetch_provider(provider_config)解析web_fetch_provider_config.provider_name,当前只支持jina;未配置或配置非法时,_provider_config_error()返回明确的受控工具错误,不会静默回退到其他 provider。 - 接收
url(单个或数组)+goal;批量场景并发抓取并合并输出。 - 抓取成功后调用 LLM(
AgentLlmName.TOOL)把网页内容按 goal 提炼为evidence+summary(web_fetch_extractorprompt),最多重试 4 次;遇到上下文超限会按 0.8 比例截断正文重试(最长不超过 400_000 字符)。结构化提取失败时走_fallback,返回前 2000 字符的 raw 页面文本并标注「无法结构化提取」。 - provider 只负责单页获取/抽取,goal 相关的 LLM 摘要由共享 facade 生成;
log_fetch开启时把 provider 原始输出与摘要写入web_fetch_log.jsonl(jina 输出单独存jina_output字段)。
8.3 RetrieveTool:固定语料检索
RetrieveTool(retriever_tool.py)封装 retrieve 工具:
- 默认使用
KnowledgeBaseRetriever(BrowsecompPlusMilvusRetriever,可经MilvusConfig.retriever_class替换)。 - Milvus 连接参数默认值:host
localhost、port19530、databasedeepsearch_benchmarks、collectionbrowsecompplus_with_bm25。 - Embedder 使用
OpenJiuwenAPIEmbedder,配置项包括embedder_model_name、embedder_api_key、embedder_base_url、embedder_timeout。 - 工具输入:
query(List[str])、top_k、add_instruction、mode、top_k_multiply_factor、save_as;输出为(results, id_list),由 tool_node 维护new_found_evidence_ids溯源链。
BrowsecompPlusMilvusRetriever(retriever.py)会把来自同一 docid 的多个命中片段按 chunk_idx 排序合并成单个 snippet(必要时补查 docid__0 首块),并记录 start_idx 处理重叠,为片段级溯源提供证据 id。
对应测试:test_web_search.py、tests/tools/search_api/test_jina.py、test_local_search.py、test_native_local_search.py、test_web_fetch_provider_registry.py、test_web_search_tool_adapter.py、test_jina_reader_endpoints.py。
九、状态校验(Validate New State)
validate_new_state(validate_new_state.py)对新状态中每个有候选的变量执行证据校验:
- 对含 candidate 的变量,先调用
find_relative_info基于discovered_clues收集相对证据。 - 构造
Verify工具输入(entities + candidates + problem_text + options),mode 支持isolated/linked/set(非法值回退isolated)。 - 校验产出
VerifiedVariableResult(含CandidateVerifiedClues:每条 clue 的 statuspass|fail|pending、overall 与 evidence)。 - 数值型线索可通过
defer_numeric延迟校验;含 placeholder 的线索pass会被转pending并提升 overall 判定(promote_flag)。
run_validations 批量校验 new_states,任一状态校验异常都会包装为 VALIDATE_NEW_STATE_ERROR 抛出。是否执行校验由 ValidatorAgentConfig 控制:validate_new_states(默认 False)与 validate_answer(默认 False);对应 workflow 层 validator_agent 子配置。
十、固定语料检索索引(Search Index)
当运行在 retrieve-only 模式时,需要预构建固定语料索引。相关实现位于 search_index/:
- 切分:
TokenizerChunker(tokenizer_chunker.py)基于IndexSentenceSplitter按 token 数切分,默认chunk_size=2048、chunk_overlap=50(见 create_browsecompplus_index.py 的BrowseCompChunker);另有splitter.py/text_splitter.py提供句级切分。 - 建索引:
create_browsecompplus_index.py读取语料 → chunk → 用OpenJiuwenAPIEmbedder转向量 → 写入 Milvus collection(schema 含docid、title、content、embedding等字段,setup_milvus_collection自动创建)。 - 消费:retrieve 工具按 query 做 dense/sparse/hybrid 检索(
RetrievalSettingsConfig.mode默认hybrid),返回相关片段与证据 id 供 run action 推理。
边界要求:chunk 过长会影响嵌入与上下文长度,应通过 splitter 控制;retrieve-only 模式不应暴露 web search/fetch;索引不存在或加载失败时应在工具层返回明确错误(而非崩溃)。
十一、数据契约与依赖
11.1 核心模型
关键模型来自 search_context.py:
Variable:id(int)、type(如 Person/City/Book/University)、question_clues(问题派生线索,初始化后不可变)、discovered_clues(研究中增量发现)、candidate(候选值,可空)、candidate_strength(0~1 置信度)。State:state(Variable 列表)、depth(默认 0)、id(默认'0')、retrieved_evidence_ids、answer_variable、verify_result。ActionProposal:direction+score(0~1)。Action:id、question、state、proposal、messages。Result:messages、previous_action_id、new_states、found_answer、summary、retrieved_evidence_ids;get_summary()返回最后一条消息内容(截断 500 字符)或 summary 字段。
11.2 运行依赖
- LLM 配置与
AgentLlmName(INITIAL_STATE / FIND_ACTION_SPACE / RUN_ACTION / TOOL 等,定义于 node_constants.py)。 - web search/fetch 配置(
web_search_engine_config、web_fetch_provider_config)。 - retrieve 模式的本地或固定语料索引(Milvus + Embedder 配置)。
- action sampling 配置(
ActionSamplingConfig)。
11.3 关键配置一览(均出自 config.py)
| 配置类 | 关键字段与默认值 |
|---|---|
ActionSamplingConfig |
depth_weight=True、promote_unique_states=False、random_sample=False |
PerQuestionParams |
max_workers=5、retry_count_on_empty_action_space=3、time_limit=4800、tool_map="search_fetch"、actions_explored_limit=200、fail_limit=0、answer_mode_top_k=1、provide_best_guess=False |
FindActionAgentConfig |
action_proposals_limit=5、action_pool_depleted_strategy="dependent_retry" |
RetrievalSettingsConfig |
top_k=3、top_k_multiply_factor=5、add_instruction=True、mode="hybrid" |
StateCreationAgentConfig |
use_candidate_strength=True、discovered_clues_mode="blacklist"、context_limit_reached_strategy="reduced_retrieval_request"、log_fetch=False、log_search=False、web_fetch_log_file="gnosis/tool_log/web_fetch_log.jsonl"、web_search_log_file="gnosis/tool_log/web_search_log.jsonl" |
ValidatorAgentConfig |
validate_new_states=False、validate_answer=False |
MilvusConfig |
milvus_host="localhost"、milvus_port=19530、database_name="deepsearch_benchmarks"、collection_name="browsecompplus_with_bm25" |
十二、边界与错误处理汇总
- thinking 剥离:LLM 输出会先剥离
<think>/<reasoning>/<thinking>标签再解析。 - score 兜底:action proposal 缺 score 时从 direction 文本解析,失败按解析错误处理。
- 解析失败不抛裸异常:find action 多次失败后返回空 actions 与错误信息;run action 解析失败把错误写回 messages 进入下一轮修正。
- 工具白名单:native tool 名称必须命中白名单,防止 prompt injection 调用未授权工具;非法工具名返回受控错误并列出允许集。
- 快照失败隔离:action pool 快照写入失败只记录日志,不阻塞搜索循环。
- 上下文超限:按
context_limit_reached_strategy决定 fail / 减半检索 / 剥离工具消息重试。 - 并发安全:ActionPool 仅限单 asyncio 协程上下文使用,无线程安全保证。
十三、测试与验证
推荐命令(对应 search-agent.md):
uv run pytest tests/search_agent
uv run pytest tests/tools/test_web_search.py
如果只改 action pool,可运行:
uv run pytest tests/search_agent/test_action_pool.py
针对各节点的最小验证集:
uv run pytest tests/search_agent/test_initialize_state.py
uv run pytest tests/search_agent/test_find_action_space.py
uv run pytest tests/search_agent/test_run_action.py
uv run pytest tests/search_agent/test_run_action_node.py
uv run pytest tests/search_agent/test_web_fetch_provider_registry.py
uv run pytest tests/search_agent/test_web_search_tool_adapter.py
如果改动搜索 API 适配(如新增搜索引擎 wrapper),可运行:
uv run pytest tests/tools/search_api
新增能力建议同步补充测试:test_action_pool.py 已覆盖采样与快照;test_run_action.py 覆盖成功路径、重试耗尽与上下文超限降级(reduced_retrieval 策略);test_deep_search_agent_smoke.py 覆盖 agent 构建与日志目录初始化。