Semantic Router
LLM Streaming 分层架构中的输出分流层——根据内容类型将流式输出路由到不同处理通道(text→UI、tool→executor、thinking→hidden、citation→reference)。
#type / concept
#status / evergreen
#tech / ai
#tech / architecture
[!info] related notes
- 所属 MOC: LLM Streaming MOC
- 架构位置: LLM Streaming 分层架构
- 上游: Chunk Aggregator
- 下游: Multi-channel Stream
- 相关: Structured Streaming
Semantic Router
一句话定义
Semantic Router 是 LLM Streaming 分层架构中的输出分流层——根据内容类型将流式输出路由到不同的处理通道,让文本、工具调用、思考过程、引用来源等各走各的路径。
核心机制
为什么需要这一层
LLM 输出不只有文本。一个完整的 AI 响应可能包含:
- 文本回答(展示给用户)
- 工具调用(需要后端执行)
- 思考过程(可选展示)
- 引用来源(参考面板)
- 结构化数据(专用 UI 组件)
- 错误信息(错误处理)
如果所有内容混在一起通过同一个通道传输,前端无法区分和分别处理。
分流模型
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 |
实现示例
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 层实现:有些 LLM Provider(如 OpenAI)的 streaming response 已经区分了
content和tool_calls,Router 只需要透传。 - 和 Event Bus 的关系:Semantic Router 负责”分到哪”,Event Bus 负责”怎么传”(SSE / WebSocket)。