export async function onRequestPost({ request, env }) { try { if (!env.GROQ_API_KEY) { return Response.json( { error: "GROQ_API_KEY is missing." }, { status: 500 } ); } const body = await request.json(); const messages = Array.isArray(body.messages) ? body.messages .filter(m => m && ["user", "assistant"].includes(m.role) && typeof m.content === "string" && m.content.trim() ) .map(m => ({ role: m.role, content: m.content.trim() })) : typeof body.message === "string" && body.message.trim() ? [{ role: "user", content: body.message.trim() }] : []; if (!messages.length) { return Response.json( { error: "Please enter a message." }, { status: 400 } ); } const totalLength = messages.reduce( (sum, item) => sum + item.content.length, 0 ); if (totalLength > 20000) { return Response.json( { error: "Conversation is too long." }, { status: 400 } ); } const upstream = await fetch( "https://api.groq.com/openai/v1/chat/completions", { method: "POST", headers: { "Authorization": `Bearer ${env.GROQ_API_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ model: "openai/gpt-oss-120b", messages: [ { role: "system", content: "You are NE7IFY AI, an expert assistant and web developer. Follow the user's requirements carefully. When generating code, return complete runnable code and do not omit requested features." }, ...messages ], max_completion_tokens: 8000, stream: body.stream === true }) } ); if (!upstream.ok) { const data = await upstream.json().catch(() => ({})); return Response.json( { error: data.error?.message || "Groq rejected the request." }, { status: 502 } ); } if (body.stream === true) { return new Response(upstream.body, { headers: { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache, no-transform", "Connection": "keep-alive" } }); } const data = await upstream.json(); return Response.json({ reply: data.choices?.[0]?.message?.content || "", finish_reason: data.choices?.[0]?.finish_reason || null }); } catch (error) { return Response.json( { error: "Server error: " + error.message }, { status: 500 } ); } }