字段 | 类型 | 描述 | 是否必传 | 示例 |
|---|---|---|---|---|
| msg | string | 用户输入的消息内容,通常为 JSON 字符串格式 | 是 | '{"msg": "你好,请帮我写一首诗"}' |
| history | Array<Message> | 历史对话消息数组,用于维护多轮对话上下文 | 是(可传空数组 [] ) | [{"role": "user", "content": "之前的问题"}, {"role": "assistant", "content": "之前的回答"}] |
{
"msg": "请帮我分析一下这个数据",
"type": "text"
}
// 通过 this.sseSender 发送流式数据
for await (const chunk of modelResponse) {
this.sseSender.send({ data: chunk });
}
this.sseSender.end(); // 结束流式输出
// 解析用户输入
const messageText = JSON.parse(input.msg).msg || '';
// 构建消息数组
const messages = [
{ role: 'system', content: systemPrompt },
...input.history, // 添加历史消息
{ role: 'user', content: messageText }
];
// 创建模型实例
const model = this.createModel('qwen-turbo');
// 流式调用
const modelResponse = await model.streamText({ messages });
⚠️ 重要提醒:
class MyAgent extends AgentRuntime {
async sendMessage(input) {
try {
// 1. 解析用户输入
const messageText = JSON.parse(input.msg).msg || '';
const model = this.createModel('qwen-turbo');
// 2. 构建消息数组
const messages = [
{
role: 'system',
content: '你是一个有用的AI助手,请用中文回答问题。'
}
];
// 3. 添加历史消息
if (input.history && input.history.length) {
messages.push(...input.history);
}
// 4. 添加当前用户消息
messages.push({
role: 'user',
content: messageText
});
// 5. 调用模型生成响应
const modelResponse = await model.streamText({
messages
});
// 6. 流式输出响应
for await (const chunk of modelResponse) {
this.sseSender.send({ data: chunk });
}
} catch (error) {
// 7. 错误处理
console.error('sendMessage error:', error);
this.sseSender.send({
data: {
error: '处理消息时发生错误,请稍后重试'
}
});
} finally {
// 8. 结束连接
this.sseSender.end();
}
}
}
class AdvancedAgent extends AgentRuntime {
async sendMessage(input) {
try {
const parsedInput = JSON.parse(input.msg);
const messageText = parsedInput.msg || '';
const hasImage = parsedInput.image; // 检查是否包含图片
const model = this.createModel('qwen-vl-plus'); // 多模态模型
const messages = [
{
role: 'system',
content: '你是一个智能助手,可以处理文本和图片。'
}
];
// 添加历史消息
if (input.history && input.history.length) {
messages.push(...input.history);
}
// 构建当前消息
const currentMessage = {
role: 'user',
content: hasImage ? [
{ type: 'text', text: messageText },
{ type: 'image_url', image_url: { url: hasImage } }
] : messageText
};
messages.push(currentMessage);
// 流式调用模型
const modelResponse = await model.streamText({ messages });
// 处理流式响应
for await (const chunk of modelResponse) {
// 可以在这里对响应进行额外处理
const processedChunk = {
...chunk,
timestamp: new Date().toISOString()
};
this.sseSender.send({ data: processedChunk });
}
} catch (error) {
console.error('Advanced sendMessage error:', error);
this.sseSender.send({
data: {
error: 'AI 服务暂时不可用,请稍后重试',
code: 'MODEL_ERROR'
}
});
} finally {
this.sseSender.end();
}
}
}
SSE 发送的数据格式示例(不同模型回复格式不同,这里以deepseek-r1为例):
{
"choices": [
{
"message": {
"role": "assistant",
"content": "这是AI生成的回复内容",
"type": "text"
}
}
],
"usage": {
"prompt_tokens": 100,
"completion_tokens": 50,
"total_tokens": 150
}
}