Update app/api/ai/route.ts
Browse files1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758591 unmodified lineimport { HfInference } from '@huggingface/inference';import db from '@/lib/db';// FORCE THE NEW ROUTER URLconst hf = new HfInference(process.env.NEXT_PUBLIC_HF_TOKEN, {endpoint: "https://router.huggingface.co/hf-inference/v1"});export async function POST(req: Request) {const body = await req.json();if (body.type === 'IMAGE') {try {const prompt = `Fantasy character portrait, ${body.prompt}, anime style, 8k, detailed`;const blob = await hf.textToImage({model: 'black-forest-labs/FLUX.1-dev',inputs: prompt,});const arrayBuffer = await blob.arrayBuffer();const buffer = Buffer.from(arrayBuffer);const base64 = `data:image/png;base64,${buffer.toString('base64')}`;db.prepare('UPDATE characters SET image_url = ? WHERE user_id = ?').run(base64, body.userId);return NextResponse.json({ success: true, url: base64 });} catch (e) {console.error(e);return NextResponse.json({ error: "AI Failed" }, { status: 500 });}}if (body.type === 'CHAT') {const { userId, message, history } = body;const char = db.prepare('SELECT * FROM characters WHERE user_id = ?').get(userId) as any;const systemPrompt = `You are a helper AI inside the inventory of ${char?.name || 'the adventurer'}. Inventory: ${char?.inventory || 'Empty'}. Class: ${char?.class_type || 'Unknown'}. Keep answers short, helpful, and immersive.`;const stream = await hf.chatCompletionStream({model: "meta-llama/Meta-Llama-3-8B-Instruct",messages: [{ role: "system", content: systemPrompt }, ...history, { role: "user", content: message }],max_tokens: 200});const encoder = new TextEncoder();const customStream = new ReadableStream({async start(controller) {for await (const chunk of stream) {const content = chunk.choices[0]?.delta?.content || "";controller.enqueue(encoder.encode(content));}controller.close();},});return new Response(customStream, { headers: { 'Content-Type': 'text/plain' } });}return NextResponse.json({ error: "Invalid Type" });}1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081821 unmodified lineimport { HfInference } from '@huggingface/inference';import db from '@/lib/db';// We use the standard client now. Make sure your NEXT_PUBLIC_HF_TOKEN is in Settings!const hf = new HfInference(process.env.NEXT_PUBLIC_HF_TOKEN);export async function POST(req: Request) {const body = await req.json();// --- IMAGE GENERATION ---if (body.type === 'IMAGE') {try {const prompt = `Fantasy character portrait, ${body.prompt}, masterpiece, 8k, rpg style`;const blob = await hf.textToImage({model: 'runwayml/stable-diffusion-v1-5', // SWITCHED TO UNLOCKED MODELinputs: prompt,});const arrayBuffer = await blob.arrayBuffer();const buffer = Buffer.from(arrayBuffer);const base64 = `data:image/png;base64,${buffer.toString('base64')}`;// Save to character sheetdb.prepare('UPDATE characters SET image_url = ? WHERE user_id = ?').run(base64, body.userId);return NextResponse.json({ success: true, url: base64 });} catch (e) {console.error("Image Gen Error:", e);return NextResponse.json({ error: "AI Failed: Check Server Logs" }, { status: 500 });}}// --- CHAT COMPANION ---if (body.type === 'CHAT') {const { userId, message, history } = body;// RAG: Get Contextlet charContext = "Unknown Adventurer";try {const char = db.prepare('SELECT * FROM characters WHERE user_id = ?').get(userId) as any;if (char) {charContext = `${char.name} (Class: ${char.class_type}, Inventory: ${char.inventory})`;}} catch (e) { console.error("DB Read Error", e); }const systemPrompt = `You are a magical inventory spirit.User Context: ${charContext}.Keep answers under 50 words. Be helpful and immersive.`;// Convert history to format Zephyr expects// We combine system prompt into the first message for simplicity with this modelconst promptInputs = `<|system|>\n${systemPrompt}</s>\n<|user|>\n${message}</s>\n<|assistant|>\n`;try {const stream = hf.textGenerationStream({model: 'HuggingFaceH4/zephyr-7b-beta', // SWITCHED TO UNLOCKED MODELinputs: promptInputs,parameters: { max_new_tokens: 150, return_full_text: false }});const encoder = new TextEncoder();const customStream = new ReadableStream({async start(controller) {for await (const chunk of stream) {const content = chunk.token.text || "";controller.enqueue(encoder.encode(content));}controller.close();},});return new Response(customStream, { headers: { 'Content-Type': 'text/plain' } });} catch (e) {console.error("Chat Error:", e);return NextResponse.json({ error: "Companion is sleeping (AI Error)" }, { status: 500 });}}return NextResponse.json({ error: "Invalid Type" });}
app/api/ai/route.ts+52-29