From 1628588d5a9f8a7a8854a57eb7c2d9bf9e2361a5 Mon Sep 17 00:00:00 2001 From: Mannu Date: Sun, 17 May 2026 13:31:30 +0530 Subject: [PATCH] fix(ai): correct env var names and fresh session per home modal open MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AI route was reading LITELLM_URL/LITELLM_KEY but env vars are named LITELLM_BASE_URL/LITELLM_API_KEY — causing 503 on every request. Home page chat now creates a fresh session each time the modal opens and resets homeSessionId on close, so conversations don't pile into the same old session. Co-Authored-By: Claude Sonnet 4.6 --- src/app/api/ai/route.ts | 4 +-- src/app/page.tsx | 59 +++++++++++++++++++---------------------- 2 files changed, 30 insertions(+), 33 deletions(-) diff --git a/src/app/api/ai/route.ts b/src/app/api/ai/route.ts index 4cdbe72..8e3f10a 100644 --- a/src/app/api/ai/route.ts +++ b/src/app/api/ai/route.ts @@ -3,8 +3,8 @@ import { sql } from "@/db"; import { detectMedicalIntent, ESCALATION_RULES } from "@/lib/ai/medical-triggers"; import { logAudit } from "@/lib/audit"; -const LITELLM_URL = process.env.LITELLM_URL; -const LITELLM_KEY = process.env.LITELLM_KEY; +const LITELLM_URL = process.env.LITELLM_BASE_URL; +const LITELLM_KEY = process.env.LITELLM_API_KEY; export async function POST(request: Request) { try { diff --git a/src/app/page.tsx b/src/app/page.tsx index efd174b..09fa01e 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -142,6 +142,7 @@ export default function HomePage() { const [aiInput, setAiInput] = useState(""); const [aiChats, setAiChats] = useState([]); const [aiLoading, setAiLoading] = useState(false); + const [homeSessionId, setHomeSessionId] = useState(null); const [pendingCount, setPendingCount] = useState(0); const [lastLogs, setLastLogs] = useState([]); const [vaccineReminders, setVaccineReminders] = useState([]); @@ -199,56 +200,52 @@ export default function HomePage() { toggleTheme(); }; - // Unified AI chat that saves to sessions (database) + // Unified AI chat — creates a fresh session per modal open, reuses it for follow-ups const handleAiChat = async (question?: string) => { const q = question || aiInput; if (!q.trim() || aiLoading) return; setAiLoading(true); setAiOpen(true); - const sessions = await getSessions(childId); - let currentSession: ChatSession | null = sessions[0] || null; - - // Create new session if none exists - if (!currentSession) { - currentSession = await createSession(childId); - if (currentSession) { - sessions.unshift(currentSession); - } - } - - if (!currentSession) { - setAiLoading(false); - return; - } - - const userMsg: AIChat = { id: crypto.randomUUID(), role: "user", content: q, createdAt: new Date().toISOString() }; const inputVal = q.trim(); if (!question) setAiInput(""); + // Reuse session within same modal open, or create fresh one + let sessionId = homeSessionId; + if (!sessionId) { + const newSession = await createSession(childId); + if (!newSession) { setAiLoading(false); return; } + sessionId = newSession.id; + setHomeSessionId(sessionId); + setAiChats([]); + } + + // Optimistically show user message + const userMsg: AIChat = { id: "tmp-" + Date.now(), role: "user", content: inputVal, createdAt: new Date().toISOString() }; + setAiChats(prev => [...prev, userMsg]); + try { - // Save user message to DB await fetch("/api/chat", { method: "PATCH", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ sessionId: currentSession.id, role: "user", content: inputVal }), + body: JSON.stringify({ sessionId, role: "user", content: inputVal }), }); - // Get AI response - const res = await fetch("/api/ai", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ messages: [{ role: "user", content: inputVal }] }) }); + const res = await fetch("/api/ai", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ messages: [{ role: "user", content: inputVal }] }), + }); const data = await res.json(); - const reply = data.reply || "Sorry, I couldn't help with that."; + const reply = data.reply || "Sorry, I'm having trouble connecting. Please try again."; - // Save AI response to DB await fetch("/api/chat", { method: "PATCH", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ sessionId: currentSession.id, role: "assistant", content: reply }), + body: JSON.stringify({ sessionId, role: "assistant", content: reply }), }); - // Refresh sessions - const updatedSessions = await getSessions(childId); - setAiChats(updatedSessions[0]?.messages || []); + setAiChats(prev => [...prev, { id: "ai-" + Date.now(), role: "assistant", content: reply, createdAt: new Date().toISOString() }]); } catch (err) { console.error("AI chat error:", err); } @@ -335,10 +332,10 @@ export default function HomePage() { setModalType(null)} /> - {aiOpen && aiChats.length > 0 && ( -
setAiOpen(false)}> + {aiOpen && ( +
{ setAiOpen(false); setHomeSessionId(null); }}>
e.stopPropagation()}> -

Ask AI

+

Ask AI

{aiChats.map((chat) => (
{chat.content}
))} {aiLoading &&
Thinking...
}