☰
semantic-router 全局存储与工具配置指南:深入解析 `global.stores` 与 `global.integrations.tools`
2026/10/14 21:11:03 网站建设 项目流程
  • 后端
  • API网关
  • 模型推理服务
  • AI Agent

【免费下载链接】semantic-router

An open, programmable decision layer for models and compute.

项目地址:https://gitcode.com/gh_mirrors/sem/semantic-router
点击查看免费下载

本文围绕 semantic-router 配置文件中的global:顶层块,系统讲解语义缓存(response cache)、Agentic Memory、向量库(vector store)与共享工具目录(tool catalog)的集中式声明方式。你将掌握这些共享后端的完整 YAML 写法、参数含义与默认值、各后端选型约束,以及"否定守卫"、嵌入身份绑定等底层机制的源码级原理,从而在 v0.3 及当前仓库的 canonical 配置中正确落地共享存储与工具依赖。

为什么需要global:级共享存储与工具块

semantic-router 的路由局部插件(route-local plugins)常常依赖共享存储或工具状态:响应缓存需要向量后端、记忆插件需要记忆库、检索功能需要向量库、工具插件需要工具目录。如果这些依赖在各条路由(decision)内随意重复配置,系统会迅速变得不一致、难以运维——同一份缓存配置在两条路由上漂移,后端地址改了却只改了一半,排查成本随之上升。

global:块正是为此设计:它将共享后端服务定义一次、全局复用。从 config/config.yaml 可以看到,global下通过stores与integrations两个子块统一承载这些基础设施:

global: router: ... services: ... stores: response_cache: ... memory: ... vector_store: ... tool_sessions: ... integrations: kv_transfer: ... tools: ... looper: ...

主要优势

  • 集中共享后端存储:语义缓存、记忆、检索与工具目录只需声明一次,而非在每条路由重复。
  • 保持一致:所有路由插件共享同一份缓存/记忆/向量库实例,行为天然一致。
  • 路由局部插件保持小而专注:插件只需声明"用哪个全局存储",无需自带后端连接细节。
  • 共享基础设施依赖显式:哪些后端属于整台路由器、由谁提供,在配置顶部一目了然。

解决什么问题 / 何时使用

当出现以下任一情况时,应将这些依赖上移到global:块:

  • 多条路由依赖同一个语义缓存或记忆后端;
  • 检索功能需要一个全局共享的向量库;
  • 路由器应对外暴露一个统一的工具目录;
  • 后端存储配置天然属于"整台路由器"而非"单条路由"。

语义缓存(Response Cache):global.stores.response_cache

命名说明:v0.3 版文档(version-v0.3 教程)中的键名为semantic_cache,当前仓库 canonical 配置(config/config.yaml)已统一为response_cache,二者指同一功能。

最简单的语义缓存声明如下:

global: stores: response_cache: enabled: true backend_type: memory similarity_threshold: 0.8

其中similarity_threshold决定语义命中阈值:查询嵌入与缓存条目嵌入的相似度达到该值即视为命中。阈值并非越高越安全——见下文"否定守卫"。当前仓库参考配置(config/config.yaml)给出了更完整的字段:

global: stores: response_cache: backend_type: milvus enabled: true similarity_threshold: 0.86 max_entries: 50000 ttl_seconds: 7200 eviction_policy: lru embedding_model: mmbert

各字段含义:

字段含义参考值/默认
enabled是否启用响应缓存true
backend_type缓存后端类型memory、milvus、redis、valkey、qdrant、hybrid
similarity_threshold语义命中阈值0.8~0.86(需按数据标定)
max_entries缓存条目上限50000
ttl_seconds条目存活时间7200
eviction_policy淘汰策略lru
embedding_model嵌入模型mmbert(Vela Embedding)

否定守卫(Negation guard):cache_negation_reject

为什么单纯提高阈值不可靠?双编码器(bi-encoder)相似度无法区分"打开深色模式"(turnondark mode)与"关闭深色模式"(turnoffdark mode):语义相反的查询往往也能超过similarity_threshold,而真正同义改写有时反而得分更低。因此每个缓存后端在返回语义候选之前,都会施加一层词法守卫(lexical guard):对近似的英文 token 集合捕捉否定信号(negation cues)与已知反义替换(antonym swaps)。

该守卫的特征:

  • 无需模型、无需额外配置,对内存、Redis、Valkey、Milvus、Qdrant 及 hybrid 缓存统一生效;
  • 不覆盖无提示词的、仅词序变化的或非英文的改写;
  • 被拒绝的命中记录为 miss,并输出事件cache_negation_reject,同时仍会在x-vsr-cache-similarity响应头暴露被拒绝的相似度分数;
  • 远程与 hybrid 后端在缺少原始查询时会拒绝候选,并继续检查有界的候选集合;同一检查同样作用于 hybrid 的 Milvus 回退路径。

该机制的源码实现在 inmemory_cache_search.go:recordLexicalPolarityReject将拒绝计数为 miss、输出 Debug 日志与cache_negation_reject事件,并记录find_similar的 miss 指标;当 HNSW 近似检索出现极性拒绝且没有更低排名的有效命中时,还会回退到线性全扫描(同上文件 L220-L232),避免近似索引掩盖合法命中。

历史配置迁移:早期版本通过polarity_guard配置该守卫,内存后端还包含 NLI 层级(nli、lexical+nli)。NLI 模型现已退役,路由器拒绝polarity_guard字段,运行vllm-sr config migrate可自动移除该配置。

外部缓存后端的连接配置示例

仓库在 config/runtime/response-cache/ 下提供了可直接参考并内联到global.stores.response_cache的后端示例文件:

  • milvus.yaml:Milvus 连接(host/port/database/timeout/auth/tls)、collection(vector_field.dimension、metric_type: IP、HNSW 索引 M=16、efConstruction=64)、搜索参数(ef、topk、consistency_level)与开发开关(drop_collection_on_startup、auto_create_collection)。
  • valkey.yaml:Valkey 连接、索引设置(index.name、prefix、vector_field、metric_type: COSINE、index_type: HNSW)、搜索 topk 与开发开关。
  • qdrant.yaml:Qdrant host/port(gRPC 6334)、api_key、use_tls、collection_name、connect_timeout。
  • redis.yaml:Redis 后端连接。

注意:Milvus 后端需要以go build -tags=milvus构建(见 milvus.yaml),Valkey 后端要求启用 valkey-search 模块。

Agentic Memory:global.stores.memory

记忆存储为会话提供跨轮次检索与持久化。支持三种后端:milvus(默认)、valkey、qdrant。enabled: true为最小启用方式:

global: stores: memory: enabled: true

Milvus 后端(默认)

global: stores: memory: enabled: true milvus: address: milvus:19530 collection: agentic_memory dimension: 256

Valkey 后端(需启用 Search 模块)

global: stores: memory: enabled: true backend: valkey valkey: host: valkey port: 6379 dimension: 256 collection_prefix: "mem:" index_name: mem_idx metric_type: COSINE

Valkey 后端要求使用带 valkey-search 模块的服务端(FT.CREATE/FT.SEARCH向量操作),可使用valkey/valkey-bundle镜像或编译期--enable-search。更完整的字段(HNSW 调参、TLS、超时)参见 config/runtime/memory/valkey.yaml 及 config/config.yaml 中的 memory 块。

Qdrant 后端

global: stores: memory: enabled: true backend: qdrant qdrant: host: qdrant port: 6334 collection: agentic_memory dimension: 256 embedding_model: mmbert default_retrieval_limit: 5 default_similarity_threshold: 0.30

维度约束与启动失败行为

三种后端默认均以mmbert(Vela Embedding)嵌入,因此dimension必须是其支持的尺寸之一:64、128、256、512 或 768。使用任何其他尺寸,路由器会在启动时输出警告Failed to create memory store: … Memory will be disabled并以无记忆模式运行——该行为在 router_memory.go 中实现,同时将MemoryStatus.Reason置为BackendUnavailable。

Qdrant 示例中的default_similarity_threshold: 0.30是基于原始余弦分数的起点值而非标定值,在使用你的数据前,应先用无关查询与纠错后的事实验证。

混合检索与反思(Hybrid search and reflection)

hybrid_mode与reflection.algorithm可在global.stores.memory全局设置,也可在 decision 的memory插件中覆盖。路由器会拒绝任何其他取值(包括 recipe 的 decisions 中设置的值):

字段可接受取值(精确、小写)默认值
hybrid_modeweighted、rrfweighted
reflection.algorithmheuristic、noopheuristic
  • hybrid_mode仅在hybrid_search: true时生效;
  • 旧配置中的hybrid_mode: rerank或algorithm: recency_semantic会导致启动失败,应替换为weighted与heuristic(这两个值正是旧值实际运行方式)。

参考配置中的示例(config/config.yaml):

embedding_model: mmbert default_retrieval_limit: 10 default_similarity_threshold: 0.40 hybrid_search: true hybrid_mode: weighted adaptive_threshold: true reflection: enabled: true algorithm: heuristic max_inject_tokens: 512 recency_decay_days: 14 dedup_threshold: 0.9 block_patterns: - api key - password

reflection.block_patterns可用于在注入记忆时屏蔽api key、password等敏感模式。

写入路径的容量约束(Write path bounds)

自动持久化首先受 Memory 启用状态、保留策略及所选 decision 的 memory 插件中显式auto_store: false约束。Responses 请求可以自行选择退出,但不能覆盖这些服务器级限制。当策略允许持久化时,优先级为:Responses 请求的auto_store> decision 的值 >global.stores.memory的默认值;只有省略时才逐级回退。

响应处理不等待记忆持久化完成:身份检查与容量预留先于有界历史快照,协议编码与写入在后台执行;响应路径上的其他 Replay 操作保持同步。通过global.stores.memory.persistence配置:

字段含义默认值
timeout_seconds从预留到超时的秒数(含准备、队列等待与写入),范围 0–9,223,372,03630
concurrencyWorker 槽位数(含准备与写入),范围 0–648
queue等待 worker 的预留尝试数,范围 0–102464
shutdown_grace_seconds重载/关闭时排空写入的秒数,范围 0–9,223,372,0365

省略字段或设为0即取默认值。负值与超过上限的值会在配置校验阶段被拒绝(在启动或重载分配 worker/队列存储之前),且同样适用于config_source: kubernetes的初始文档——全局资源边界不会被推迟到 CRD 加载之后。

每次持久化尝试共享1 MiB载荷预算(请求历史 + 保留的 Responses 历史 + 当前助手响应;助手文本在去除 think 标签前计数)。历史另有 256 条消息/条目与 32 层嵌套内容限制,历史与当前响应共享 4096 节点结构限制。超过任一限制会以skipped/history_too_large跳过持久化并保持fail_open=true,不占用持久化容量、不截断模型响应;缺少用户身份以skipped/memory_info_unavailable跳过;被 jailbreak 或幻觉策略拦截的响应以policy_blocked报告。持久化容量或回执容量耗尽时分别以queue_full/receipt_queue_full拒绝新写入(退役池使用shutting_down),均保持 fail-open 并按请求 ID 记录日志。可监控指标:llm_plugin_execution_total{plugin_type="memory_persistence", status="rejected"}。

另外,当配置了model_role: memory_rewrite的外部模型时,其max_response_bytes会限制每次查询改写响应的字节数;省略或非正值使用1 MiB默认值。

完整的部署说明可参见仓库文档 valkey-memory.md(Docker、Kubernetes、配置参考、调参与排障)与 qdrant.md,以及 config/runtime/memory/ 下的后端专项配置参考。

向量库:global.stores.vector_store

最小配置:

global: stores: vector_store: enabled: true backend_type: milvus metadata_store: postgres

支持的后端:memory、milvus、llama_stack、valkey、qdrant(与源码 vectorstore.go 的校验枚举一致)。

metadata_store:元数据注册表选型

metadata_store控制向量库与上传文件的元数据注册表:

  • postgres:适合需要重启安全的本地或类生产环境。设置metadata_store: postgres后,CLI 本地运行会自动拉起 Postgres 并补齐metadata_postgres连接默认值(host/port/database/user/password/ssl_mode/max_open_conns 等,参见 config/config.yaml);
  • memory:只适合临时本地实验,路由器重启后会丢失库和文件元数据。

源码校验(vectorstore.go)明确要求:metadata_store只能取值memory或postgres,且为postgres时metadata_postgres配置必填。

嵌入身份绑定与409 EMBEDDING_REINDEX_REQUIRED

当使用 model runtime 的嵌入(包括 Vela Embedding)时,每个新建向量库都会记录创建其向量的表示(representation)身份。已有库保持可见、已上传文件保留;但向不兼容或未标记的库执行搜索或附加文件时,会返回409 EMBEDDING_REINDEX_REQUIRED。处理方式:新建向量库并重新附加原始上传文件 ID,以生成兼容向量。客户端元数据无法覆盖路由器所有的_router_embedding_identity字段。

同样的检查适用于请求时的 RAG 与缓存检索结果。llama_stack后端在远程执行查询嵌入,因此目前不能与身份绑定的运行时文档嵌入组合使用;此类配置应改用memory、milvus、valkey或qdrant。

完整字段与文件上传参数

参考配置(config/config.yaml)中的向量库块还包含:

global: stores: vector_store: enabled: true backend_type: llama_stack file_storage_dir: /var/lib/vsr/data max_file_size_mb: 100 embedding_model: multimodal embedding_dimension: 384 ingestion_workers: 4 ingestion_drain_timeout_seconds: 25 supported_formats: [.txt, .md, .json, .csv, .html, .pdf] metadata_store: memory metadata_postgres: host: postgres port: 5432 database: vsr user: router ...

字段含义(依据 vectorstore.go 的结构定义):

  • file_storage_dir:上传文件的基础目录(默认/var/lib/vsr/data);
  • max_file_size_mb:单文件上传大小上限(默认 50);
  • embedding_model:文档嵌入模型,可选mmbert(默认)、qwen3、multimodal;
  • embedding_dimension:嵌入维度,默认 0 表示采用模型原生输出维度;
  • ingestion_workers/ingestion_drain_timeout_seconds:摄取管线的并发 worker 数与关闭时排空等待秒数(默认 2/25);drain 超时应大于单任务典型延迟、小于平台关闭宽限期(如 Kubernetes 默认 30s 的 terminationGracePeriodSeconds);
  • supported_formats:允许上传的扩展名列表。

Valkey 向量库后端的完整示例见 config/runtime/vector-store/valkey.yaml(含collection_prefix: "vsr_vs_"、metric_type: COSINE、index_m、index_ef_construction等平铺字段)。

工具目录:global.integrations.tools

路由器通过共享工具目录对外暴露统一的工具集合,供模型调用。配置示例:

global: integrations: tools: enabled: true top_k: 3 tools_db_path: config/runtime/tools/tools_db.json

参考配置(config/config.yaml)提供了更完整的生产级参数:

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 advanced_filtering: enabled: true retrieval_strategy: weighted candidate_pool_size: 50 min_lexical_overlap: 1 min_combined_score: 0.42 weights: embed: 0.5 lexical: 0.2 tag: 0.1 name: 0.1 category: 0.1 use_category_filter: true category_confidence_threshold: 0.7 allow_tools: [docs.search, tickets.lookup] block_tools: [admin.delete] hybrid_history: history_horizon: 8 min_history_steps: 1 history_confidence_threshold: 0 weight_semantic: 1 weight_history_transition: 1 weight_decision_prior: 1 repetition_penalty_strength: 0

参数说明(对应源码结构 tool_selection_plugin.go):

  • enabled:是否启用共享工具目录;
  • top_k:语义检索返回给模型的工具数量上限;
  • similarity_threshold:工具语义召回的相似度门槛;
  • tools_db_path:本地工具数据库 JSON 文件路径;
  • fallback_to_empty:检索失败时是否回退为空工具集(避免误暴露不相关工具);
  • advanced_filtering:进阶过滤配置——retrieval_strategy(如weighted)、candidate_pool_size、min_lexical_overlap、min_combined_score,以及 embed/lexical/tag/name/category 五路加权分数、类别过滤阈值(use_category_filter、category_confidence_threshold)、allow_tools/block_tools白/黑名单与基于会话历史(hybrid_history)的混合决策。

工具数据库格式(tools_db.json)

工具数据库是 JSON 数组,每项包含 OpenAI 风格的工具定义(tool.type、tool.function.name/description/parameters)以及检索辅助字段description(自然语言语义描述)、category与tags。仓库示例 config/runtime/tools/tools_db.json 收录了get_weather、search_web、calculate、send_email、create_calendar_event五个工具,其结构如下:

[ { "tool": { "type": "function", "function": { "name": "get_weather", "description": "Get current weather information for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "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字段是语义检索的关键——它用自然语言覆盖工具的各种触发说法(如同义词与使用场景),确保 embedding 能正确召回。实践中应为每个工具编写多角度的检索描述,并借助category、tags参与advanced_filtering的加权打分。

数据与安全注意事项

缓存、记忆与向量库中可能包含提示词、响应、嵌入向量、检索文档或提取的记忆,配置时需注意:

  • 后端安全:为所选后端配置认证(auth)、加密(TLS/SSL)、保留策略(retention)与租户/用户作用域(tenant/user scope);
  • 维度一致性:嵌入维度必须与已有 collection 匹配;更换嵌入模型或维度时,需重建或迁移索引;
  • 工具检索 ≠ 授权:工具检索只决定"把哪些工具展示给模型",不授权工具执行;工具服务端必须自行强制权限(例如通过block_tools屏蔽高危工具,但最终安全边界在工具服务本身);
  • 身份绑定:向量库的嵌入身份由路由器记录,客户端不得伪造_router_embedding_identity。

参考配置资源

  • 完整 canonical 配置契约与全局示例:config/config.yaml(global.router、global.services、global.stores、global.integrations全量字段);
  • 各后端专项示例:config/runtime/(memory、response-cache、response-api、tools、vector-store);
  • 记忆后端部署手册:valkey-memory.md、qdrant.md;
  • 模型运行时嵌入指南:website/docs/model-runtime/guides/embeddings.md;
  • 本主题的中文版本地文档:stores-and-tools.md(v0.3 翻译版) 与 stores-and-tools.md(英文原版)。

小贴士:若你的配置基于 v0.3 中文文档快照(使用semantic_cache键名),迁移到当前版本时请将其重命名为response_cache,并运行vllm-sr config migrate自动清理已退役的polarity_guard等字段,再对照 config/config.yaml 核对新字段默认值。

  • 后端
  • API网关
  • 模型推理服务
  • AI Agent

【免费下载链接】semantic-router

An open, programmable decision layer for models and compute.

项目地址:https://gitcode.com/gh_mirrors/sem/semantic-router
点击查看免费下载

相关推荐

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询