78 lines
2.8 KiB
TypeScript
78 lines
2.8 KiB
TypeScript
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
|
|
|
|
const corsHeaders = {
|
|
"Access-Control-Allow-Origin": "*",
|
|
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type, x-supabase-client-platform, x-supabase-client-platform-version, x-supabase-client-runtime, x-supabase-client-runtime-version",
|
|
};
|
|
|
|
serve(async (req) => {
|
|
if (req.method === "OPTIONS") {
|
|
return new Response(null, { headers: corsHeaders });
|
|
}
|
|
|
|
try {
|
|
const { query } = await req.json();
|
|
|
|
if (!query || typeof query !== "string" || query.trim().length === 0 || query.length > 200) {
|
|
return new Response(JSON.stringify({ error: "Invalid query" }), {
|
|
status: 400,
|
|
headers: { ...corsHeaders, "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
|
|
const LOVABLE_API_KEY = Deno.env.get("LOVABLE_API_KEY");
|
|
if (!LOVABLE_API_KEY) {
|
|
return new Response(JSON.stringify({ error: "AI not configured" }), {
|
|
status: 500,
|
|
headers: { ...corsHeaders, "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
|
|
const response = await fetch("https://ai.gateway.lovable.dev/v1/chat/completions", {
|
|
method: "POST",
|
|
headers: {
|
|
Authorization: `Bearer ${LOVABLE_API_KEY}`,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
model: "google/gemini-2.5-flash-lite",
|
|
messages: [
|
|
{
|
|
role: "system",
|
|
content: "You are a translator. Translate the user's Minecraft-related search query to English. Return ONLY the translated text, nothing else. If it's already in English, return it as-is. Keep Minecraft mod names unchanged.",
|
|
},
|
|
{ role: "user", content: query.trim() },
|
|
],
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
if (response.status === 429) {
|
|
return new Response(JSON.stringify({ error: "Rate limited" }), {
|
|
status: 429,
|
|
headers: { ...corsHeaders, "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
const t = await response.text();
|
|
console.error("AI error:", response.status, t);
|
|
return new Response(JSON.stringify({ error: "Translation failed" }), {
|
|
status: 500,
|
|
headers: { ...corsHeaders, "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
|
|
const data = await response.json();
|
|
const translated = data.choices?.[0]?.message?.content?.trim() || query;
|
|
|
|
return new Response(JSON.stringify({ translated, original: query.trim() }), {
|
|
headers: { ...corsHeaders, "Content-Type": "application/json" },
|
|
});
|
|
} catch (error) {
|
|
console.error("translate error:", error);
|
|
return new Response(JSON.stringify({ error: "Translation failed" }), {
|
|
status: 500,
|
|
headers: { ...corsHeaders, "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
});
|