// Dummy streaming chat endpoint for local testing // POST /api/chat { content: string, sessionId?: string } import { NextRequest } from 'next/server'; import { streamText } from 'ai'; import { createOpenAI } from '@ai-sdk/openai'; import { getHistory, putMessage } from './chat-store'; import { aggregateUserData, cleanDeveloperProfile, buildAllContextPrompt, getReportGraphData, getBadgeUserId } from './context'; import { checkAndConsumeToken } from './rate-limit'; import { createSession } from './chat-store'; export const runtime = 'nodejs'; export async function chatStreamRoute(req: NextRequest, userId: string, companyId?: string) { try { const { sessionId, content, badgeId } = await req.json(); if (!content || !sessionId) { return Response.json({ error: 'Missing sessionId or content' }, { status: 400 }); } const allowed = await checkAndConsumeToken(userId, 20); if (!allowed) { return Response.json({ error: 'Rate limit exceeded' }, { status: 429 }); } await putMessage({ sessionId, role: 'user', content }); const badgeUserId = await getBadgeUserId(badgeId); const aggregated = await aggregateUserData(badgeUserId, !!companyId, companyId); const cleaned = cleanDeveloperProfile(aggregated); const graphData = await getReportGraphData(badgeId); const system = buildAllContextPrompt(cleaned, graphData, { concise: true }); const history = await getHistory(sessionId, 20); const apiKey = process.env.OPENAI_API_KEY; if (!apiKey) { return Response.json({ error: 'Server misconfigured: missing OPENAI_API_KEY' }, { status: 500 }); } const chatMessages = [ { role: 'system', content: system }, ...history.map((m: any) => ({ role: m.role, content: m.content })), { role: 'user', content }, ]; const openai = createOpenAI({ apiKey }); const result = await streamText({ model: openai('gpt-4o-mini'), messages: chatMessages as any, maxTokens: 1024, onFinish: async ({ text }: { text: string }) => { try { if (text) await putMessage({ sessionId, role: 'assistant', content: text }); } catch {} }, }); return result.toTextStreamResponse({ headers: { 'X-Accel-Buffering': 'no', }, }); } catch (e) { console.error('chat error', e); return new Response('An error occurred. Please try again.', { status: 500 }); } } export async function createSessionRoute(req: NextRequest, userId: string, companyId?: string) { try { const body = await req.json().catch(() => ({})); const sessionId = await createSession({ userId: userId, companyId: companyId, model: body?.model, promptId: body?.promptId, promptVersion: body?.promptVersion, }); return Response.json({ sessionId }); } catch (e) { console.error(e); if (e instanceof Response) return e; return Response.json({ error: 'Failed to create session' }, { status: 500 }); } }