diff --git a/app/(chat)/api/chat/route.ts b/app/(chat)/api/chat/route.ts index d483b01..5f5f3d1 100644 --- a/app/(chat)/api/chat/route.ts +++ b/app/(chat)/api/chat/route.ts @@ -343,6 +343,10 @@ export async function POST(request: Request) { console.log("[Smart Auto Mode] 🚀 Starting intelligent analysis..."); try { + // 🆕 首先获取历史消息(在 Smart Auto Mode 内部单独获取,避免依赖后面的 messagesFromDb) + const smartAutoHistoryMessagesFromDb = await getMessagesByChatId({ id }); + console.log("[Smart Auto Mode] Loaded", smartAutoHistoryMessagesFromDb.length, "messages from DB"); + // 1. 提取用户消息内容 const lastUserMessage = message; const textContent = lastUserMessage.parts @@ -362,13 +366,13 @@ export async function POST(request: Request) { // 🆕 历史图片上下文感知:如果用户没有发送新图片,自动使用历史中最近的图片(支持多张) // 逻辑:只要用户在对话中没有附上新图片,就默认继续处理之前的图片 - if (!hasImage && messagesFromDb.length > 0) { + if (!hasImage && smartAutoHistoryMessagesFromDb.length > 0) { console.log("[Smart Auto Mode] 🔍 No image in current message, auto-searching history..."); // 从历史消息中倒序查找最近一轮包含图片的消息 // 收集该消息中的所有图片(支持多图融合编辑) - for (let i = messagesFromDb.length - 1; i >= 0; i--) { - const msg = messagesFromDb[i]; + for (let i = smartAutoHistoryMessagesFromDb.length - 1; i >= 0; i--) { + const msg = smartAutoHistoryMessagesFromDb[i]; const parts = msg.parts as any[]; if (!parts) continue; @@ -424,7 +428,7 @@ export async function POST(request: Request) { // 🆕 从历史消息中提取对话文本(用于上下文理解) const historyMessages: { role: "user" | "assistant"; content: string }[] = []; - for (const msg of messagesFromDb.slice(-10)) { // 最多取最近10条 + for (const msg of smartAutoHistoryMessagesFromDb.slice(-10)) { // 最多取最近10条 const parts = msg.parts as any[]; if (parts && parts.length > 0) { // 提取文本内容