Chat → Agent 迁移指南
Chat(useChat / ChatMixin / ChatBehavior)在 v2.0 中已不推荐使用。需要多轮对话、工具调用、状态管理时,请迁移到 Agent。
如果只是单次生成,请使用 Stream。
快速对比
| 对比项 | Chat(旧) | Agent(新) |
|---|---|---|
| React / Vue3 | useChat | useAgent |
| Vue2 | ChatMixin | AgentMixin |
| 小程序 | ChatBehavior | AgentBehavior |
| 状态命名空间 | chat.* | agent.* |
| 发送方法 | chat(params) | send(params, options) |
| 消息内容 | message.content / message.reason | message.parts |
| 工具调用 | 不推荐 | setTools() / toolExecuted |
| 状态管理 | 无 | agentState |
迁移步骤
1. 替换接入 API
ts
// 之前
import { useChat } from '@tencent/ssv-ai-sdk-react';
const { messages, chat, stop } = useChat({ /* ... */ });
// 之后
import { useAgent } from '@tencent/ssv-ai-sdk-react';
const { messages, send, stop, setTools, setMessages, on, off } = useAgent({ /* ... */ });
ts
// 之前
import { useChat } from '@tencent/ssv-ai-sdk-vue';
const { messages, chat, stop } = useChat({ /* ... */ });
// 之后
import { useAgent } from '@tencent/ssv-ai-sdk-vue';
const { messages, send, stop, setTools, setMessages, on, off } = useAgent({ /* ... */ });
ts
// 之前
import { ChatMixin } from '@tencent/ssv-ai-sdk-vue2';
mixins: [ChatMixin({ /* ... */ })]
// 之后
import { AgentMixin } from '@tencent/ssv-ai-sdk-vue2';
mixins: [AgentMixin({ /* ... */ })]
ts
// 之前
import { ChatBehavior } from '@tencent/ssv-ai-sdk-miniprogram';
behaviors: [ChatBehavior({ /* ... */ })]
// 之后
import { AgentBehavior } from '@tencent/ssv-ai-sdk-miniprogram';
behaviors: [AgentBehavior({ /* ... */ })]
2. 替换发送方法
ts
// 之前
await chat({ input });
// 之后
await send({ input });
Vue2 / 小程序:
js
// Vue2
await this.agent.send({ input: this.inputValue });
// 小程序
await this.agent.send({ input: this.data.inputValue });
3. 替换消息渲染
Agent 的 assistant 消息不再依赖顶层 content / reason,需要按 parts 顺序渲染。
tsx
{messages.map((message) => (
<div key={message.id}>
{message.role === 'user' && <div>{message.content}</div>}
{message.role === 'assistant' && message.parts?.map((part, index) => {
if (part.type === 'reasoning') return <div key={index}>{part.reason}</div>;
if (part.type === 'text') return <p key={index}>{part.text}</p>;
if (part.type === 'tool_call') return <ToolCard key={part.id} part={part} />;
return null;
})}
</div>
))}
4. 迁移工具调用
Frontend 工具执行完成后,SDK 会触发 toolExecuted。业务侧需要构造 tool 消息并调用 send({}, { type: 'tools' })。
ts
on('toolExecuted', ({ toolCallId, toolCallName, result }) => {
if (UI_ONLY_TOOLS.includes(toolCallName)) return;
const toolMessage = {
id: `tool-${Date.now()}`,
role: 'tool',
content: typeof result === 'string' ? result : JSON.stringify(result),
toolCallId,
extraInfo: {},
};
setMessages([...messages, toolMessage]);
send({}, { type: 'tools' });
});
5. Vue2 / 小程序状态命名空间替换
html
<!-- 之前 -->
<view>{{chat.messages}}</view>
<view>{{chat.assistantStatus}}</view>
<!-- 之后 -->
<view>{{agent.messages}}</view>
<view>{{agent.assistantStatus}}</view>
@ssv-lab