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

PDF问答AI应用:TypeError错误与消息未入库问题求助

PDF AI问答应用问题排查

问题1:TypeError: messagesRef.current.concat is not a function 错误

原因

useChat 的 initialMessages 参数要求传入数组,但 /api/get-messages 返回的是 { messages: 消息数组 } 对象而非直接数组。ChatComponent 中 useQuery 直接返回 response.data(即该对象),导致 initialMessages: data || [] 传入非数组值,触发内部 concat 函数调用失败。

修复

修改 ChatComponent 中 useQuery 的返回值,正确提取消息数组:

const { data, isLoading } = useQuery({
  queryKey: ["chat", chatId],
  queryFn: async () => {
    const response = await axios.post<{ messages: Message[] }>("/api/get-messages", {
      chatId,
    });
    return response.data.messages; // 提取数组而非整个对象
  },
});

此时 initialMessages: data || [] 即可正常工作,保留 Array.isArray(data) ? data : [] 可进一步增强鲁棒性。


问题2:用户提问与AI回复无法存入NeonDB

原因及修复步骤

1. ChatId 类型不匹配

数据库 schema 中 chatId 定义为 integer,但前端传入的可能是字符串类型,导致插入时静默失败。
修复 /api/chat 中的类型转换:

export async function POST(req: Request) {
  try {
    const { messages, chatId } = await req.json();
    const numericChatId = Number(chatId); // 转为数字类型
    if (isNaN(numericChatId)) {
      return NextResponse.json({ error: "Invalid chat ID" }, { status: 400 });
    }

    const _chats = await db.select().from(chats).where(eq(chats.id, numericChatId));
    // 后续所有使用 chatId 的地方替换为 numericChatId
    await db.insert(_messages).values({
      chatId: numericChatId,
      content: lastMessage.content,
      role: "user",
    });
    // ... 其他代码
  }
  // ...
}

2. AI 消息角色与数据库枚举不一致

数据库枚举 userSystemEnum 仅包含 ["system", "user"],但组件中 AI 消息预期角色为 assistant,当前代码插入 AI 消息时使用 role: "system",存在逻辑不一致。

  • 若希望 AI 消息角色为 assistant,更新 schema:
export const userSystemEnum = pgEnum("user_system_enum", ["system", "user", "assistant"]);

执行数据库迁移后,修改 /api/chat 中 AI 消息的角色:

await db.insert(_messages).values({
  chatId: numericChatId,
  content: completion,
  role: "assistant", // 改为 assistant
});
  • 若保持枚举不变,修改 MessageList 中 AI 消息的判断条件:
"justify-start pr-10": message.role === "system",

3. 未处理错误响应

/api/chat 的 catch 块未返回响应,可能导致请求挂起,补充返回:

catch (error) {
  console.error("Error processing message:", error);
  return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
}

内容的提问来源于stack exchange,提问作者Haroon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:27:03