Semantic Router `tools` 路由局部插件:工具过滤与语义工具选择实战指南
Semantic Router tools 路由局部插件:工具过滤与语义工具选择实战指南
semantic-router 是一个开放、可编程的"模型与算力决策层"。在 Agent 场景中,如何为不同路由配备不同工具策略,是决定系统安全与体验的关键。本文围绕 v0.3 版本文档中 tools 路由局部插件展开,结合仓库源码与真实配置,讲解其解决的问题、三种 mode 的语义、allow_tools/block_tools 过滤机制、基于全局工具库的语义工具选择(semantic_selection)、隐私场景的 strip_tool_history 用法、动态检索(dynamic_retrieval)扩展,以及可落地的完整配置示例。读完本文,你将掌握在 routing.decisions[].plugins 下声明式地"按路由配工具"的完整方法,并能参照源码与测试独立排查配置问题。
核心导读
工具策略应当属于路由策略的一部分:有的路由应完全剥离工具、有的应原样透传、有的应约束语义工具候选池。
tools插件将这一"路由局部约定"显式化,并与全局工具库组合使用,而不是把配置堆进routing.decisions[]里。
主要优势
- 策略挂在匹配路由上:工具策略随路由命中而生效,而不是全局一刀切。
- 路由间互相独立:一条路由禁用工具,另一条路由过滤工具,第三条路由做语义选择,互不干扰。
- 与全局工具库组合:语义选择的候选集来自全局工具库(global tools database),插件只需声明策略,无需重复维护工具目录。
- 声明式、可验证:配置即契约,配错会直接被校验拦截(详见下文"校验规则")。
它解决什么问题?
工具行为是路由策略的一部分。典型诉求包括:
- 部分路由应完全剥离工具(如安全隔离路由、隐私路由);
- 部分路由应原样透传请求自带的工具;
- 部分路由应从全局工具库中按语义选择最匹配的少量工具;
- 部分路由应通过显式允许/阻止列表限制工具访问范围。
如果这些依赖被零散地配置在每条路由里,系统会变得不一致、难以运维。tools 插件把"这条路由对工具做什么"变成一个独立、可校验、可观测的声明。
何时使用
当出现以下任一需求时,就应该启用 tools 插件:
- 路由应禁用所有工具;
- 路由应从全局工具库语义选择工具;
- 路由应用显式 allow/block 列表限制工具访问;
- 隐私路由应保留工具历史用于路由判定,但不向所选模型透传之前的工具/函数调用与结果消息。
最后一条正是 v0.3 文档英文版补充并强调的使用场景,与隐私/安全类路由强相关。
配置:在 routing.decisions[].plugins 下使用
在匹配决策(decision)的 plugins 数组中挂载 tools 插件:
plugin:
type: tools
configuration:
enabled: true
mode: filtered
semantic_selection: true
allow_tools:
- docs.search
- tickets.lookup
block_tools:
- admin.delete
仓库中的标准片段 config/fragments/plugin/tools/semantic-select.yaml 即为该配置的规范示例,并附有一条重要注释:
# Privacy routes should instead use mode: none together with
# strip_tool_history: true so prior calls/results are not provider-bound.
即:隐私路由应改用 mode: none 并配合 strip_tool_history: true,让先前的工具调用/结果不再随请求进入所选后端模型。
配置字段速查
| 字段 | 类型 | 默认值 | 说明 |
|---|---|---|---|
enabled |
bool | false |
是否启用本插件。关闭时其余字段一律不生效(校验也跳过) |
mode |
string | passthrough |
工具处理模式:none / passthrough / filtered |
semantic_selection |
bool | true(有值即按值) |
是否在过滤后继续执行语义工具选择;mode: none 下强制视为关闭 |
allow_tools |
[]string | 空 | 白名单,仅保留名字命中的工具(仅 filtered 模式合法) |
block_tools |
[]string | 空 | 黑名单,命中即移除,优先级高于 allow(仅 filtered 模式合法) |
strip_tool_history |
bool | false |
剥离历史工具调用/结果消息;仅 mode: none 下合法 |
strategy |
string | default |
语义工具选择的检索策略名,须在 router 的 tools Registry 中注册 |
dynamic_retrieval |
对象 | 无 | 历史感知的工具检索扩展,启用后按 semantic_only/hybrid_history 策略工作 |
这些字段与默认值的定义见 src/semantic-router/pkg/config/tools_plugin.go:
ToolsPluginModeNone/Passthrough/Filtered三个模式常量(L6-L8);EffectiveMode()(L93-L98):mode为空时默认passthrough;EffectiveStrategy()(L102-L107):strategy为空时默认default(即 embedding 相似度检索);SelectionEnabled()(L110-L118):enabled=false或mode=none时返回 false,semantic_selection未设置时默认视为 true。
三种 mode 的执行语义
mode 的执行逻辑在 src/semantic-router/pkg/extproc/req_filter_tools.go 的 handleEarlyToolModes(L74-L116)中实现:
mode: none —— 剥离全部工具
case config.ToolsPluginModeNone:
changed, removed := stripSemanticToolPolicy(request, toolsCfg.StripToolHistory)
if changed { request.Generation++ }
- 请求中的所有工具被移除,
tool_choice被清空(clearSemanticToolChoiceWhenNoTools); - 若同时设置
strip_tool_history: true,路由在完成信号与决策评估之后、向所选后端发送之前,删除对话历史中的 assistant tool/function 调用消息与 tool/function 结果消息(实现见 src/semantic-router/pkg/extproc/req_filter_tools_history.go 的stripSemanticToolPolicy与llmprotocol.StripTools); - 关键性质:这一剥离发生在路由判定之后,因此不会改变路由匹配结果,只改变发往提供商的请求体。这正是隐私路由"用历史做路由判定、但不把历史交给模型"的实现基础。
mode: passthrough —— 原样透传
case config.ToolsPluginModePassthrough:
return request.ToolChoice.Mode == llmprotocol.ToolChoiceAuto, nil
- 不修改请求携带的工具;当请求的
tool_choice为 auto 时继续进入语义选择流程,否则直接透传。
mode: filtered —— 显式 allow/block 过滤
case config.ToolsPluginModeFiltered:
filtered := filterToolsByDecisionPolicy(request.Tools, toolsCfg.AllowTools, toolsCfg.BlockTools)
if len(filtered) != len(request.Tools) { request.Generation++ }
request.Tools = filtered
...
return true, nil
filterToolsByDecisionPolicy(L582-L603)按工具函数名精确匹配:blockTools命中即剔除;allowTools非空时,不在白名单内的工具一律剔除;- 过滤后若
tool_choice不是 auto,则直接提交(不再做语义选择);是 auto 则继续进入语义工具选择阶段。
过滤规则实测(源码测试佐证)
src/semantic-router/pkg/extproc/tools_plugin_test.go 用 read_file、write_file、search_web、exec_cmd 四个工具验证了三种组合:
- 仅白名单
allow=["read_file","search_web"]:只保留这两个,write_file/exec_cmd被剔除(TestFilterToolsByDecisionPolicy_AllowList); - 仅黑名单
block=["exec_cmd","write_file"]:只保留read_file/search_web(TestFilterToolsByDecisionPolicy_BlockList); - 黑白名单同时存在且冲突时,block 优先:
allow=["read_file","write_file"]且block=["write_file"]时,最终只剩read_file(TestFilterToolsByDecisionPolicy_AllowAndBlock)。
全局与路由级过滤的合并策略
路由级插件过滤会与全局 advanced_filtering 合并(mergeToolFilters,L519-L529):
- allow 列表取交集:全局白名单与路由白名单都允许的工具才保留(
intersectToolAllowLists); - block 列表取并集:任一侧列入黑名单的工具都会被剔除(
unionToolBlockLists); - 匹配时忽略大小写并去除首尾空格。
也就是说,路由插件无法"放大"全局白名单,但可以进一步收紧。
语义工具选择:从全局工具库检索候选
当 mode 为 filtered 或 passthrough、且 semantic_selection 允许时,路由器会对用户内容做 embedding 相似度检索,从全局工具库中挑选最相关的工具替换请求的工具列表。
全局工具库的配置
语义选择依赖全局工具库,配置在 global.integrations.tools 下(见 config/config.yaml L2529-L2533 的示例):
global:
integrations:
tools:
enabled: true
top_k: 5
similarity_threshold: 0.35
tools_db_path: config/runtime/tools/tools_db.json
fallback_to_empty: true
工具库文件是一份 JSON 数组,每个条目包含完整的工具定义(tool)、用于相似度匹配的 description、以及可选的 category 与 tags。以 config/runtime/tools/tools_db.json 中的 get_weather 为例:
{
"tool": {
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather information for a location",
"parameters": { "type": "object", "properties": { "location": { "type": "string" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] }
}
},
"description": "Get current weather information, temperature, conditions, forecast for any location, city, or place. Check weather today, now, current conditions, temperature, rain, sun, cloudy, hot, cold, storm, snow",
"category": "weather",
"tags": ["weather", "temperature", "forecast", "climate"]
}
注意:用于相似度匹配的是 description(以及 category/tags),而不是工具自身的函数 description 字段。description 写的越是自然语言化、覆盖越多用户问法,检索命中率越高。
检索实现原理
- 工具库加载时会对每条
description生成 embedding 并缓存(AddTool,见 src/semantic-router/pkg/tools/tools.go L70-L93); - 请求到来时,对用户内容生成查询 embedding,与全部工具做点积相似度计算(
FindSimilarToolsWithScoresMinSimilarity,L124-L191),仅保留相似度 ≥similarity_threshold的候选; - 结果按相似度降序、同名按名称升序(确定性排序),取
top_k个; top_k <= 0时按 3 兜底(findToolsForQuery,L326-L338),并受全局advanced_filtering.candidate_pool_size影响候选池大小;- 若检索结果为空:
fallback_to_empty: true时工具列表置空,否则置为[](空但非 nil),并递增Generation通知下游重新序列化(applySelectedTools,L35-L69)。
检索策略与降级
executeRetrieval(L283-L321)的降级顺序为:
- 若配置了
strategy,先从 router 的ToolsRegistry取对应 retriever;未找到时回退到default策略(结果标记为-fallback),再未找到则直接用ToolsDatabase检索; - 检索失败时按
fallback_to_empty决定是空工具集(继续请求)还是返回错误; - 每次检索都会记录
tools-retrieval指标,并在请求了 debug 头(x-vsr-debug)时通过x-vsr-tools-strategy/x-vsr-tools-confidence/x-vsr-tools-latency-ms响应头暴露观测信息(emitToolObservability,L410-L427)。
一个关键安全边界
需要强调:语义工具选择只决定"哪些工具定义被发给模型",它本身不授权工具执行。工具真正的权限必须在工具服务侧强制执行,工具 schema 与调用结果都应视为随提供商的绑定内容处理(官方文档原文:"Tool selection controls what reaches the model; it does not authorize tool execution")。路由层能缩小暴露面,但不能替代工具侧的鉴权。
隐私与安全场景:mode: none + strip_tool_history
config/recipes/privacy/config.yaml 给出了一个非常完整的生产级示例,四种决策演示了三种模式在隐私/安全策略下的典型用法:
local_security_containment(L626-L648):可疑/jailbreak 请求落入本地安全通道,插件配置mode: none—— 完全禁用工具;omni(L650-L673):含图片的隐私请求路由到本地多模态模型,mode: filtered+allow_tools: [local_search, local_read]—— 只允许本地工具;local_privacy_policy(L675-L709):PII、私有代码、内部文档走本地模型,同样是mode: filtered+ 本地工具白名单;cloud_frontier_reasoning(L711-L746):非敏感、非可疑的深度推理才允许上云,mode: passthrough—— 原样透传工具。
这套配置直观说明了"一条路由禁用、另一条过滤、第三条透传"的设计意图。若需"路由判定仍可用历史、但模型看不到历史",则在隐私路由上设置:
- type: tools
configuration:
enabled: true
mode: none
strip_tool_history: true
该策略在路由完成信号评估与决策选择后、最终向提供商序列化前生效(applyPreDispatchToolsPolicy),因此不影响路由命中,只影响 provider-bound 的请求体。
校验规则:配错会被直接拒绝
src/semantic-router/pkg/config/tools_plugin_validation.go 定义了完整的配置校验,任何一条违反都会导致配置加载失败:
mode必须是none/passthrough/filtered三者之一(L24-L31);mode: filtered必须提供allow_tools或block_tools(L33-L46);- 其他模式不得携带
allow_tools/block_tools(L40-L44); strip_tool_history: true必须搭配mode: none,否则报错strip_tool_history requires mode="none"(L17-L19);dynamic_retrieval.strategy只能是semantic_only或hybrid_history(L57-L62);hybrid_history策略下history_window必须 ≥ 1(L64-L67);min_history_confidence必须在[0.0, 1.0](L69-L71);- 所有
weights必须非负(L84-L98),零权重表示忽略对应信号。
对应的行为测试覆盖见 src/semantic-router/pkg/config/tools_plugin_test.go,例如"未知策略名被拒""history_window=0 在 hybrid 策略下被拒""负权重被拒",以及完整的 YAML 反序列化与往返测试。
进阶扩展:dynamic_retrieval 历史感知检索
v0.3 配置契约中,tools 插件还支持按决策粒度的历史感知检索扩展:
- type: tools
configuration:
enabled: true
mode: passthrough
dynamic_retrieval:
enabled: true
strategy: hybrid_history # 或 semantic_only
history_window: 8
min_history_confidence: 0.4
fallback_on_low_confidence: true
weights:
semantic: 1.0
history: 0.7
decision_prior: 0.2
repetition_penalty: 0.1
strategy: semantic_only:纯语义检索(默认);strategy: hybrid_history:在语义相似度基础上,综合最近history_window条工具调用观测、决策先验(decision prior)与重复惩罚进行排序;weights缺省时采用semantic 1.0 / history 1.0 / decision_prior 0.0 / repetition_penalty 0.0的默认值;fallback_on_low_confidence: true时,历史证据未达到min_history_confidence则回退到纯语义排序;- 该块是完全增量的设计:不配置或
enabled: false时路由器行为与旧版完全一致(DynamicRetrievalEnabled的判断见 tools_plugin.go L123-L128)。
完整可运行示例:一份带注释的决策配置
结合仓库示例,一份覆盖三种模式与语义选择的决策片段如下:
routing:
decisions:
- name: tool_free_safety_lane
description: 安全通道:完全剥离工具,不给模型任何调用入口
priority: 300
plugins:
- type: tools
configuration:
enabled: true
mode: none
- name: docs_agent
description: 文档助手:白名单过滤 + 语义选择
priority: 200
plugins:
- type: tools
configuration:
enabled: true
mode: filtered
semantic_selection: true
allow_tools:
- docs.search
- tickets.lookup
block_tools:
- admin.delete
- name: cloud_default
description: 默认云路由:原样透传请求自带工具
priority: 100
plugins:
- type: tools
configuration:
enabled: true
mode: passthrough
配合全局工具库(global.integrations.tools)启用语义选择所需的 embedding 提供方即可运行。若想了解工具库条目的语义化编写方式与全局存储配置,可继续阅读 website/docs/tutorials/global/stores-and-tools.md。
小结
tools是路由局部的工具策略插件,把"禁用 / 透传 / 过滤 / 语义选择"四种行为挂到决策上;mode: none适合安全隔离与隐私路由,配合strip_tool_history: true可在保留历史用于路由判定的同时阻止历史流向提供商;mode: filtered的 allow/block 列表与全局过滤合并(allow 取交集、block 取并集),block 优先;- 语义选择从全局工具库按 embedding 相似度取 top_k 候选,工具库条目的自然语言
description决定检索质量; - 配置有严格校验,非法组合会被直接拒绝;源码与测试提供了逐条的验证依据。
相关仓库路径速查
- 配置片段:config/fragments/plugin/tools/semantic-select.yaml
- 完整配置示例:config/config.yaml、config/recipes/privacy/config.yaml
- 全局工具库:config/runtime/tools/tools_db.json
- 配置结构与默认值:src/semantic-router/pkg/config/tools_plugin.go
- 校验规则:src/semantic-router/pkg/config/tools_plugin_validation.go
- 请求处理与语义选择:src/semantic-router/pkg/extproc/req_filter_tools.go
- 历史剥离:src/semantic-router/pkg/extproc/req_filter_tools_history.go
- 工具库检索实现:src/semantic-router/pkg/tools/tools.go
- 测试佐证:src/semantic-router/pkg/config/tools_plugin_test.go、src/semantic-router/pkg/extproc/tools_plugin_test.go