export async function onRequestGet({ env }) { return Response.json({ status: "Backend is running", aiBinding: Boolean(env.AI) }); } export async function onRequestPost({ request, env }) { try { if (!env.AI) { throw new Error("Workers AI binding named AI is missing."); } const body = await request.json(); const messages = Array.isArray(body.messages) ? body.messages .filter(m => ["user", "assistant"].includes(m.role) && typeof m.content === "string" ) .slice(-12) .map(m => ({ role: m.role, content: m.content.slice(0, 2000) })) : []; if (!messages.length) { return Response.json( { error: "Please send a message." }, { status: 400 } ); } const result = await env.AI.run( "@cf/meta/llama-3.1-8b-instruct", { messages: [ { role: "system", content: `You are the haus&haus Property Concierge, assisting people interested in Dubai real estate. Be professional, warm, concise and helpful. Understand whether visitors want to buy, rent, explore off-plan or find commercial property. Ask relevant follow-up questions naturally, one at a time. Clarify property type, preferred Dubai area, budget and bedrooms when relevant. Do not ask questions already answered. Never invent property listings, prices, availability, agent details or company policies. If information is not verified, say so. Never claim an enquiry has been sent. Help visitors understand their needs and take the next step.` }, ...messages ] } ); if (!result || typeof result.response !== "string") { console.error("Unexpected AI response:", result); throw new Error("AI returned no usable response."); } return Response.json({ reply: result.response }); } catch (error) { console.error("AI CHAT ERROR:", error); return Response.json( { error: "AI request failed. Check Cloudflare Function logs." }, { status: 500 } ); } }