WebSocket 协议扩展
在 Step 9 中,我们扩展了 WebSocket 消息协议以支持多模态内容。
消息内容类型定义
1 | // src/server/protocol.ts |
客户端消息格式
1 | /** |
消息示例:
纯文本(向后兼容):
1
2
3
4{
"type": "chat.send",
"content": "你好"
}文本对象:
1
2
3
4
5
6
7{
"type": "chat.send",
"content": {
"type": "text",
"text": "你好"
}
}纯图像:
1
2
3
4
5
6
7
8{
"type": "chat.send",
"content": {
"type": "image",
"mediaType": "image/png",
"data": "iVBORw0KGgo..."
}
}文本+图像混合:
1
2
3
4
5
6
7
8
9
10
11
12
13
14{
"type": "chat.send",
"content": [
{
"type": "text",
"text": "描述这张图片"
},
{
"type": "image",
"mediaType": "image/jpeg",
"data": "/9j/4AAQSkZJRg..."
}
]
}
消息验证
协议层提供了完整的消息验证逻辑:
1 | // src/server/protocol.ts |
服务器端处理
AgentService 多模态处理
1 | // src/server/agent-service.ts |
消息路由
1 | // src/server/server.ts |
协议兼容性
向后兼容
协议设计保持了向后兼容性:
1 | // 旧的纯文本消息仍然有效 |
内容规范化
服务器端将所有格式统一转换为标准格式:
1 | /** |
错误处理
常见错误情况
无效的媒体类型:
1
2
3
4{
"type": "error",
"error": "不支持的图像格式: image/tiff"
}Base64 格式错误:
1
2
3
4{
"type": "error",
"error": "无效的 base64 编码"
}文件过大:
1
2
3
4{
"type": "error",
"error": "图像文件过大 (12.5MB),最大支持 10MB"
}消息格式错误:
1
2
3
4{
"type": "error",
"error": "无效的消息格式"
}
错误处理实现
1 | // src/server/agent-service.ts |
协议版本控制
为了未来扩展,协议支持版本标识:
1 | /** |
版本化消息示例:
1 | { |
小结
本节介绍了多模态消息协议的设计和实现:
- WebSocket 协议扩展
- 消息内容类型定义
- 消息验证逻辑
- 服务器端处理流程
- 向后兼容性设计
- 错误处理机制
导航
上一篇: 11.3 图像处理与传输
下一篇: 11.5 Web UI 图像功能