Spaces:
Configuration error
Configuration error
| import { NextRequest, NextResponse } from "next/server" | |
| import prisma from "@/lib/prisma" | |
| import { stackServerApp } from "@/lib/stack-server" | |
| import { generateText } from "ai" | |
| import { openai } from "@ai-sdk/openai" | |
| // GET - Get memory for a character | |
| export async function GET(request: NextRequest) { | |
| try { | |
| const user = await stackServerApp.getUser() | |
| if (!user) { | |
| return NextResponse.json( | |
| { error: "Authentication required" }, | |
| { status: 401 } | |
| ) | |
| } | |
| const { searchParams } = new URL(request.url) | |
| const characterId = searchParams.get("characterId") | |
| if (!characterId) { | |
| return NextResponse.json( | |
| { error: "characterId is required" }, | |
| { status: 400 } | |
| ) | |
| } | |
| const memory = await prisma.characterMemory.findUnique({ | |
| where: { | |
| characterId_userId: { | |
| characterId, | |
| userId: user.id, | |
| }, | |
| }, | |
| }) | |
| return NextResponse.json({ memory }) | |
| } catch (error) { | |
| console.error("Error fetching character memory:", error) | |
| return NextResponse.json( | |
| { error: "Failed to fetch memory" }, | |
| { status: 500 } | |
| ) | |
| } | |
| } | |
| // POST - Update memory with new messages | |
| export async function POST(request: NextRequest) { | |
| try { | |
| const user = await stackServerApp.getUser() | |
| if (!user) { | |
| return NextResponse.json( | |
| { error: "Authentication required" }, | |
| { status: 401 } | |
| ) | |
| } | |
| const { characterId, messages, newMessage, characterResponse } = await request.json() | |
| if (!characterId) { | |
| return NextResponse.json( | |
| { error: "characterId is required" }, | |
| { status: 400 } | |
| ) | |
| } | |
| // Get or create memory | |
| let memory = await prisma.characterMemory.findUnique({ | |
| where: { | |
| characterId_userId: { | |
| characterId, | |
| userId: user.id, | |
| }, | |
| }, | |
| }) | |
| if (!memory) { | |
| memory = await prisma.characterMemory.create({ | |
| data: { | |
| characterId, | |
| userId: user.id, | |
| recentMessages: [], | |
| userFacts: [], | |
| messageCount: 0, | |
| }, | |
| }) | |
| } | |
| // Update recent messages | |
| const recentMessages = memory.recentMessages as Array<{ role: string; content: string }> | |
| const updatedMessages = [ | |
| ...recentMessages, | |
| { role: "user", content: newMessage }, | |
| { role: "assistant", content: characterResponse }, | |
| ].slice(-20) // Keep last 20 messages | |
| // If we have enough messages, summarize the context | |
| let contextSummary = memory.contextSummary | |
| if (updatedMessages.length >= 10 && (!contextSummary || memory.messageCount % 10 === 0)) { | |
| try { | |
| const { text } = await generateText({ | |
| model: openai("gpt-4o-mini"), | |
| prompt: `Summarize the key points from this conversation for context retention. Focus on: | |
| 1. User preferences and interests | |
| 2. Important facts mentioned | |
| 3. Ongoing topics or tasks | |
| Conversation: | |
| ${updatedMessages.map(m => `${m.role}: ${m.content}`).join("\n")} | |
| Provide a brief summary (2-3 sentences):`, | |
| }) | |
| contextSummary = text | |
| } catch (error) { | |
| console.error("Failed to summarize context:", error) | |
| } | |
| } | |
| // Extract user facts (simple keyword extraction) | |
| const userFacts = memory.userFacts as string[] | |
| // This could be enhanced with AI extraction | |
| // Update memory | |
| const updatedMemory = await prisma.characterMemory.update({ | |
| where: { | |
| characterId_userId: { | |
| characterId, | |
| userId: user.id, | |
| }, | |
| }, | |
| data: { | |
| recentMessages: updatedMessages, | |
| contextSummary, | |
| userFacts, | |
| messageCount: { increment: 2 }, | |
| }, | |
| }) | |
| return NextResponse.json({ memory: updatedMemory }) | |
| } catch (error) { | |
| console.error("Error updating character memory:", error) | |
| return NextResponse.json( | |
| { error: "Failed to update memory" }, | |
| { status: 500 } | |
| ) | |
| } | |
| } | |
| // DELETE - Clear memory for a character | |
| export async function DELETE(request: NextRequest) { | |
| try { | |
| const user = await stackServerApp.getUser() | |
| if (!user) { | |
| return NextResponse.json( | |
| { error: "Authentication required" }, | |
| { status: 401 } | |
| ) | |
| } | |
| const { searchParams } = new URL(request.url) | |
| const characterId = searchParams.get("characterId") | |
| if (!characterId) { | |
| return NextResponse.json( | |
| { error: "characterId is required" }, | |
| { status: 400 } | |
| ) | |
| } | |
| await prisma.characterMemory.deleteMany({ | |
| where: { | |
| characterId, | |
| userId: user.id, | |
| }, | |
| }) | |
| return NextResponse.json({ success: true }) | |
| } catch (error) { | |
| console.error("Error clearing character memory:", error) | |
| return NextResponse.json( | |
| { error: "Failed to clear memory" }, | |
| { status: 500 } | |
| ) | |
| } | |
| } | |