You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js + ChatGroq:无法返回正确AIMessage内容的问题排查

问题分析与解决方案

核心问题是流式调用时未传入角色设定和历史对话上下文:

  • 你在model.invoke中正确传入了包含system角色设定、用户prompt和历史对话的消息数组,因此能生成符合Melon角色的回复;
  • 但在创建stream时,仅传入了prompt字符串,没有带上system指令和历史记录,导致模型无法获取角色上下文,返回默认AI回复。

此外,当前代码存在重复调用模型的问题:先通过model.invoke获取内容,再通过model.pipe(parser).stream(prompt)发起第二次请求,既浪费资源又导致结果不一致。

修改后的route.js核心代码

// 移除原有的model.invoke相关代码,替换为以下流式处理逻辑
const messages = [
  ["system", `${companion.instructions} Try to give responses that are straight to the point. 
    Generate sentences without a prefix of who is speaking. Don't use ${companion.name} prefix.
    Below are relevant details about ${companion.name}'s past and the conversation you are in.
    ${companion.description}`],
  ["human", `${prompt}\n${recentChatHistory}`]
];

const parser = new StringOutputParser();
const stream = await model.pipe(parser).stream(messages);

// 收集流式输出的完整内容,用于写入数据库和内存
let fullContent = "";
const asyncIterable = stream[Symbol.asyncIterator]();
for await (const chunk of asyncIterable) {
  fullContent += chunk;
}

// 写入历史记录和数据库
await memoryManager.writeToHistory(fullContent, companionKey);
await prismadb.companion.update({
  where: { id: params.chatId },
  data: {
    messages: {
      create: {
        role: 'system',
        userId: user.id,
        content: fullContent,
      },
    },
  },
});

return LangChainAdapter.toDataStreamResponse(stream);

关键修改说明

  1. 统一消息上下文:流式调用时传入与model.invoke完全一致的消息数组,确保模型能获取角色设定和历史对话;
  2. 避免重复调用:移除多余的model.invoke,仅通过流式调用获取结果,同时收集完整内容用于后续的数据库和内存写入;
  3. 保持原有业务逻辑:保留历史记录写入、数据库更新等操作,确保功能完整性。

额外优化建议

  • 可以考虑使用streamText替代LangChainAdapter,更贴合Vercel AI SDK的使用习惯;
  • 流式输出时可实时写入内存(如果业务允许),无需等待完整内容生成。

内容的提问来源于stack exchange,提问作者A-Makeyev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:55:05