Files

1 line
15 KiB
JSON

{"repo": "bostanidis/celebchatai", "files": {"app/api/chat/route.js": {"8a5de5d93a67018544a3180d0d016c6dcc7e9532": {"t": 1785745553.6300995, "n": 4955, "h": "5a056db23d0750dc", "c": "import { NextResponse } from 'next/server'\r\nimport supabase from '@/utils/supabase/client'\r\nimport { createClient } from '@supabase/supabase-js'\r\nimport OpenAI from 'openai'\r\n\r\n// Create a Supabase client with the service role key for server-side operations\r\nconst supabaseAdmin = createClient(\r\n process.env.NEXT_PUBLIC_SUPABASE_URL,\r\n process.env.SUPABASE_SERVICE_ROLE_KEY\r\n)\r\n\r\n// Initialize OpenAI client with DeepSeek base URL\r\nconst openai = new OpenAI({\r\n baseURL: 'https://api.deepseek.com/v1',\r\n apiKey: process.env.DEEPSEEK_API_KEY\r\n});\r\n\r\nexport async function GET() {\r\n try {\r\n const { data: { session }, error: sessionError } = await supabase.auth.getSession()\r\n\r\n if (sessionError) {\r\n console.error('Session error:', sessionError)\r\n return NextResponse.json({ error: sessionError.message }, { status: 401 })\r\n }\r\n\r\n if (!session) {\r\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\r\n }\r\n\r\n const { data: chats, error: chatsError } = await supabase\r\n .from('chats')\r\n .select('*')\r\n .eq('user_id', session.user.id)\r\n .order('created_at', { ascending: false })\r\n\r\n if (chatsError) {\r\n console.error('Chats error:', chatsError)\r\n return NextResponse.json({ error: chatsError.message }, { status: 500 })\r\n }\r\n\r\n return NextResponse.json({ chats })\r\n } catch (error) {\r\n console.error('GET error:', error)\r\n return NextResponse.json({ error: error.message }, { status: 500 })\r\n }\r\n}\r\n\r\nexport async function POST(request) {\r\n try {\r\n // Parse request body\r\n const { messages, character, characterId, isGuest } = await request.json();\r\n \r\n if (!messages || !character || !characterId) {\r\n console.error('Missing required fields:', { messages: !!messages, character: !!character, characterId: !!characterId });\r\n return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });\r\n }\r\n\r\n // Skip auth check for guest users\r\n if (!isGuest) {\r\n // Get session from request\r\n const authHeader = request.headers.get('authorization');\r\n if (!authHeader) {\r\n console.error('No authorization header');\r\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });\r\n }\r\n\r\n // Verify session with Supabase\r\n const { data: { user }, error: sessionError } = await supabase.auth.getUser(authHeader.replace('Bearer ', ''));\r\n if (sessionError || !user) {\r\n console.error('Session error:', sessionError);\r\n return NextResponse.json({ error: 'Invalid session' }, { status: 401 });\r\n }\r\n }\r\n\r\n // Create system message based on character data\r\n const systemMessage = character.systemPrompt || `You are ${character.name}. ${character.description || ''} \r\n Your personality: ${character.personality || 'Not specified'}\r\n Your background: ${character.background || 'Not specified'}\r\n \r\n Respond as this character would, maintaining their unique voice, knowledge, and mannerisms.\r\n Keep responses concise but meaningful, showing the character's personality.`;\r\n\r\n // Prepare messages for the AI\r\n const messagesToSend = [\r\n { role: 'system', content: systemMessage },\r\n ...(character.exampleDialogue ? [{ role: 'system', content: `Example dialogue: ${character.exampleDialogue}` }] : []),\r\n ...messages.map(msg => ({\r\n role: msg.role,\r\n content: msg.content\r\n }))\r\n ];\r\n\r\n // Create stream response\r\n const encoder = new TextEncoder();\r\n const stream = new ReadableStream({\r\n async start(controller) {\r\n try {\r\n const completion = await openai.chat.completions.create({\r\n model: 'deepseek-chat',\r\n messages: messagesToSend,\r\n temperature: 0.7,\r\n max_tokens: 500,\r\n stream: true,\r\n });\r\n\r\n let fullResponse = '';\r\n for await (const chunk of completion) {\r\n const content = chunk.choices[0]?.delta?.content || '';\r\n if (content) {\r\n fullResponse += content;\r\n // Send the chunk as a Server-Sent Event\r\n const data = encoder.encode(`data: ${JSON.stringify({ content })}\\n\\n`);\r\n controller.enqueue(data);\r\n }\r\n }\r\n \r\n // Send the [DONE] message\r\n controller.enqueue(encoder.encode('data: [DONE]\\n\\n'));\r\n controller.close();\r\n } catch (error) {\r\n console.error('Error in stream:', error);\r\n controller.error(error);\r\n }\r\n },\r\n });\r\n\r\n return new Response(stream, {\r\n headers: {\r\n 'Content-Type': 'text/event-stream',\r\n 'Cache-Control': 'no-cache',\r\n 'Connection': 'keep-alive',\r\n },\r\n });\r\n } catch (error) {\r\n console.error('Error in POST handler:', error);\r\n return NextResponse.json({ error: 'Internal server error' }, { status: 500 });\r\n }\r\n}"}, "a49c81af7c90134955916653ce52d1e593f17232": {"t": 1785754156.0621126, "n": 4955, "h": "5a056db23d0750dc", "c": "import { NextResponse } from 'next/server'\r\nimport supabase from '@/utils/supabase/client'\r\nimport { createClient } from '@supabase/supabase-js'\r\nimport OpenAI from 'openai'\r\n\r\n// Create a Supabase client with the service role key for server-side operations\r\nconst supabaseAdmin = createClient(\r\n process.env.NEXT_PUBLIC_SUPABASE_URL,\r\n process.env.SUPABASE_SERVICE_ROLE_KEY\r\n)\r\n\r\n// Initialize OpenAI client with DeepSeek base URL\r\nconst openai = new OpenAI({\r\n baseURL: 'https://api.deepseek.com/v1',\r\n apiKey: process.env.DEEPSEEK_API_KEY\r\n});\r\n\r\nexport async function GET() {\r\n try {\r\n const { data: { session }, error: sessionError } = await supabase.auth.getSession()\r\n\r\n if (sessionError) {\r\n console.error('Session error:', sessionError)\r\n return NextResponse.json({ error: sessionError.message }, { status: 401 })\r\n }\r\n\r\n if (!session) {\r\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\r\n }\r\n\r\n const { data: chats, error: chatsError } = await supabase\r\n .from('chats')\r\n .select('*')\r\n .eq('user_id', session.user.id)\r\n .order('created_at', { ascending: false })\r\n\r\n if (chatsError) {\r\n console.error('Chats error:', chatsError)\r\n return NextResponse.json({ error: chatsError.message }, { status: 500 })\r\n }\r\n\r\n return NextResponse.json({ chats })\r\n } catch (error) {\r\n console.error('GET error:', error)\r\n return NextResponse.json({ error: error.message }, { status: 500 })\r\n }\r\n}\r\n\r\nexport async function POST(request) {\r\n try {\r\n // Parse request body\r\n const { messages, character, characterId, isGuest } = await request.json();\r\n \r\n if (!messages || !character || !characterId) {\r\n console.error('Missing required fields:', { messages: !!messages, character: !!character, characterId: !!characterId });\r\n return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });\r\n }\r\n\r\n // Skip auth check for guest users\r\n if (!isGuest) {\r\n // Get session from request\r\n const authHeader = request.headers.get('authorization');\r\n if (!authHeader) {\r\n console.error('No authorization header');\r\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });\r\n }\r\n\r\n // Verify session with Supabase\r\n const { data: { user }, error: sessionError } = await supabase.auth.getUser(authHeader.replace('Bearer ', ''));\r\n if (sessionError || !user) {\r\n console.error('Session error:', sessionError);\r\n return NextResponse.json({ error: 'Invalid session' }, { status: 401 });\r\n }\r\n }\r\n\r\n // Create system message based on character data\r\n const systemMessage = character.systemPrompt || `You are ${character.name}. ${character.description || ''} \r\n Your personality: ${character.personality || 'Not specified'}\r\n Your background: ${character.background || 'Not specified'}\r\n \r\n Respond as this character would, maintaining their unique voice, knowledge, and mannerisms.\r\n Keep responses concise but meaningful, showing the character's personality.`;\r\n\r\n // Prepare messages for the AI\r\n const messagesToSend = [\r\n { role: 'system', content: systemMessage },\r\n ...(character.exampleDialogue ? [{ role: 'system', content: `Example dialogue: ${character.exampleDialogue}` }] : []),\r\n ...messages.map(msg => ({\r\n role: msg.role,\r\n content: msg.content\r\n }))\r\n ];\r\n\r\n // Create stream response\r\n const encoder = new TextEncoder();\r\n const stream = new ReadableStream({\r\n async start(controller) {\r\n try {\r\n const completion = await openai.chat.completions.create({\r\n model: 'deepseek-chat',\r\n messages: messagesToSend,\r\n temperature: 0.7,\r\n max_tokens: 500,\r\n stream: true,\r\n });\r\n\r\n let fullResponse = '';\r\n for await (const chunk of completion) {\r\n const content = chunk.choices[0]?.delta?.content || '';\r\n if (content) {\r\n fullResponse += content;\r\n // Send the chunk as a Server-Sent Event\r\n const data = encoder.encode(`data: ${JSON.stringify({ content })}\\n\\n`);\r\n controller.enqueue(data);\r\n }\r\n }\r\n \r\n // Send the [DONE] message\r\n controller.enqueue(encoder.encode('data: [DONE]\\n\\n'));\r\n controller.close();\r\n } catch (error) {\r\n console.error('Error in stream:', error);\r\n controller.error(error);\r\n }\r\n },\r\n });\r\n\r\n return new Response(stream, {\r\n headers: {\r\n 'Content-Type': 'text/event-stream',\r\n 'Cache-Control': 'no-cache',\r\n 'Connection': 'keep-alive',\r\n },\r\n });\r\n } catch (error) {\r\n console.error('Error in POST handler:', error);\r\n return NextResponse.json({ error: 'Internal server error' }, { status: 500 });\r\n }\r\n}"}, "87cdadc7352b0f875fa66a74e47b377d65fde8ba": {"t": 1785754157.67891, "n": 4817, "h": "81bdfb7baf140c59", "c": "import { NextResponse } from 'next/server'\nimport supabase from '@/utils/supabase/client'\nimport { createClient } from '@supabase/supabase-js'\nimport OpenAI from 'openai'\n\n// Create a Supabase client with the service role key for server-side operations\nconst supabaseAdmin = createClient(\n process.env.NEXT_PUBLIC_SUPABASE_URL,\n process.env.SUPABASE_SERVICE_ROLE_KEY\n)\n\n// Initialize OpenAI client with DeepSeek base URL\nconst openai = new OpenAI({\n baseURL: 'https://api.deepseek.com/v1',\n apiKey: process.env.DEEPSEEK_API_KEY\n});\n\nexport async function GET() {\n try {\n const { data: { session }, error: sessionError } = await supabase.auth.getSession()\n\n if (sessionError) {\n console.error('Session error:', sessionError)\n return NextResponse.json({ error: sessionError.message }, { status: 401 })\n }\n\n if (!session) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const { data: chats, error: chatsError } = await supabase\n .from('chats')\n .select('*')\n .eq('user_id', session.user.id)\n .order('created_at', { ascending: false })\n\n if (chatsError) {\n console.error('Chats error:', chatsError)\n return NextResponse.json({ error: chatsError.message }, { status: 500 })\n }\n\n return NextResponse.json({ chats })\n } catch (error) {\n console.error('GET error:', error)\n return NextResponse.json({ error: error.message }, { status: 500 })\n }\n}\n\nexport async function POST(request) {\n try {\n // Parse request body\n const { messages, character, characterId, isGuest } = await request.json();\n \n if (!messages || !character || !characterId) {\n console.error('Missing required fields:', { messages: !!messages, character: !!character, characterId: !!characterId });\n return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });\n }\n\n // Skip auth check for guest users\n if (!isGuest) {\n // Get session from request\n const authHeader = request.headers.get('authorization');\n if (!authHeader) {\n console.error('No authorization header');\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });\n }\n\n // Verify session with Supabase\n const { data: { user }, error: sessionError } = await supabase.auth.getUser(authHeader.replace('Bearer ', ''));\n if (sessionError || !user) {\n console.error('Session error:', sessionError);\n return NextResponse.json({ error: 'Invalid session' }, { status: 401 });\n }\n }\n\n // Create system message based on character data\n const systemMessage = character.systemPrompt || `You are ${character.name}. ${character.description || ''} \n Your personality: ${character.personality || 'Not specified'}\n Your background: ${character.background || 'Not specified'}\n \n Respond as this character would, maintaining their unique voice, knowledge, and mannerisms.\n Keep responses concise but meaningful, showing the character's personality.`;\n\n // Prepare messages for the AI\n const messagesToSend = [\n { role: 'system', content: systemMessage },\n ...(character.exampleDialogue ? [{ role: 'system', content: `Example dialogue: ${character.exampleDialogue}` }] : []),\n ...messages.map(msg => ({\n role: msg.role,\n content: msg.content\n }))\n ];\n\n // Create stream response\n const encoder = new TextEncoder();\n const stream = new ReadableStream({\n async start(controller) {\n try {\n const completion = await openai.chat.completions.create({\n model: 'deepseek-chat',\n messages: messagesToSend,\n temperature: 0.7,\n max_tokens: 500,\n stream: true,\n });\n\n let fullResponse = '';\n for await (const chunk of completion) {\n const content = chunk.choices[0]?.delta?.content || '';\n if (content) {\n fullResponse += content;\n // Send the chunk as a Server-Sent Event\n const data = encoder.encode(`data: ${JSON.stringify({ content })}\\n\\n`);\n controller.enqueue(data);\n }\n }\n \n // Send the [DONE] message\n controller.enqueue(encoder.encode('data: [DONE]\\n\\n'));\n controller.close();\n } catch (error) {\n console.error('Error in stream:', error);\n controller.error(error);\n }\n },\n });\n\n return new Response(stream, {\n headers: {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n },\n });\n } catch (error) {\n console.error('Error in POST handler:', error);\n return NextResponse.json({ error: 'Internal server error' }, { status: 500 });\n }\n}"}}}}