Semantic Router
LLM Streaming 分层架构中的输出分流层——按已验证的事件类型分流输出;区分 UI 投影、工具执行授权和可对外展示的推理摘要。
#concept
#evergreen
#ai
#architecture
[!info] related notes
- 所属 MOC: LLM Streaming MOC
- 架构位置: LLM Streaming 分层架构
- 上游: Chunk Aggregator
- 下游: Multi-channel Stream
- 相关: Structured Streaming
Semantic Router
一句话定义
Semantic Router 是 LLM Streaming 分层架构中的输出分流层——根据内容类型将流式输出路由到不同的处理通道,让文本、工具调用、思考过程、引用来源等各走各的路径。
这里指流式输出分发器,不是用向量相似度选择模型、工具或意图的 semantic routing;保留旧标题作为本笔记入口。
核心机制
为什么需要这一层
LLM 输出不只有文本。一个完整的 AI 响应可能包含:
- 文本回答(展示给用户)
- 工具调用(需要后端执行)
- 接口明确提供且允许展示的推理摘要(不是所有模型都输出内部思考过程)
- 引用来源(参考面板)
- 结构化数据(专用 UI 组件)
- 错误信息(错误处理)
同一连接可以承载多种事件;需要明确 type 或 channel 才能按契约分别处理。
分流模型
Chunk Aggregator 输出
↓
Semantic Router
↓
┌────┼────┬────┬────┐
↓ ↓ ↓ ↓ ↓
text tool think cite struct
↓ ↓ ↓ ↓ ↓
UI executor hidden ref panel
各通道职责
| 通道 | 内容 | 目标 |
|---|---|---|
text | 面向用户的回答文本 | 主聊天 UI |
tool | 工具调用请求与结果 | 后端执行器 / 工具状态 UI |
thinking | 接口允许公开的推理摘要 | 按展示策略显示;折叠不等于保密 |
citation | 引用来源、参考文献 | 引用面板 |
structured | 结构化提取数据 | 专用 UI 组件 |
status | 流程状态变化 | 状态指示器 |
error | 错误与警告 | 错误提示 UI |
分发伪代码
SemanticChunk 和 eventBus 由应用定义。输入须先经过运行时校验;发往 tool 通道只表示分发请求,执行器仍须检查参数、权限、确认策略与重复调用。未知类型应按兼容策略忽略、记录或拒绝,不能直接执行。
class SemanticRouter {
route(chunk: SemanticChunk) {
switch (chunk.type) {
case "text":
this.eventBus.emit("text", chunk.content)
break
case "tool_call":
this.eventBus.emit("tool", chunk.data)
break
case "thinking":
this.eventBus.emit("thinking", chunk.content)
break
case "citation":
this.eventBus.emit("citation", chunk.data)
break
default:
this.eventBus.emit("unknown", chunk)
}
}
}
最小场景
AI 助手回复中同时包含文本和工具调用:
LLM 输出: "我帮你查一下。" + [调用 search 工具] + "根据搜索结果..."
Semantic Router 分流:
→ text: "我帮你查一下。" → 主 UI
→ tool: search({...}) → 后端执行
→ text: "根据搜索结果..." → 主 UI
与 Multi-channel Stream 的关系
Semantic Router 是后端的分流逻辑,Multi-channel Stream 是协议层的通道标识。Semantic Router 的输出通过带有 channel 字段的事件传输给前端:
{ "type": "message.delta", "channel": "text", "data": { "content": "你好" } }
{ "type": "tool_call.started", "channel": "tool", "data": { "name": "search" } }
{ "type": "thinking.delta", "channel": "reasoning", "data": { "content": "正在核对相关资料。" } }
边界与易混淆点
- Semantic Router 不是 HTTP Router:它路由的是流式输出的内容类型,不是 HTTP 请求。
- 分流规则取决于 LLM 输出格式:不同 LLM Provider 的输出格式不同,Router 需要适配。
- 可以在 Provider 适配层实现:接口可能已区分文本与工具事件,但字段映射、增量累积、完成状态与输入校验仍需按具体接口处理。
- 和 Event Bus 的关系:Semantic Router 负责”分到哪”,Event Bus 负责进程内或服务间事件分发;SSE / WebSocket 是面向客户端的传输方式,可由独立适配器连接。