Revenir à la leçon

Fichier fonctionnel d’origine

netlify/functions/mini-chat.mjs

Le code et les pages d’exemple fonctionnelles conservent leurs identifiants et leurs textes d’origine. La leçon et les consignes des fichiers les expliquent dans votre langue.

export async function generate(contents, instruction) {
  const { GEMINI_API_KEY, GEMINI_MODEL } = process.env;
  if (!GEMINI_API_KEY || !GEMINI_MODEL || !/^[a-zA-Z0-9._-]+$/.test(GEMINI_MODEL))
    throw Error("Provider not configured");
  const r = await fetch(
    "https://generativelanguage.googleapis.com/v1beta/models/" +
      GEMINI_MODEL +
      ":generateContent",
    {
      method: "POST",
      headers: { "Content-Type": "application/json", "x-goog-api-key": GEMINI_API_KEY },
      body: JSON.stringify({
        contents,
        systemInstruction: { parts: [{ text: instruction }] },
        generationConfig: { maxOutputTokens: 600 },
      }),
      signal: AbortSignal.timeout(20000),
    },
  );
  if (!r.ok) throw Error("Provider request failed: " + r.status);
  const result = await r.json(),
    candidate = result.candidates?.[0];
  const text = (candidate?.content?.parts || [])
    .filter((p) => !p.thought && typeof p.text === "string")
    .map((p) => p.text)
    .join("")
    .trim();
  if (!text || candidate.finishReason !== "STOP") throw Error("No complete answer");
  return text;
}
export const handler = async (event) => {
  if (event.httpMethod !== "POST") return { statusCode: 405, body: "Use POST" };
  const labToken = process.env.LAB_TOKEN;
  if (!labToken || labToken.length < 24)
    return { statusCode: 503, body: "Practice access not configured" };
  if (event.headers?.authorization !== "Bearer " + labToken)
    return { statusCode: 401, body: "Practice access required" };

  if ((event.body || "").length > 16000) return { statusCode: 413, body: "Too large" };
  let body;
  try {
    body = JSON.parse(event.body || "");
  } catch {
    return { statusCode: 400, body: "Invalid JSON" };
  }
  const messages = body?.messages;
  if (
    !Array.isArray(messages) ||
    messages.length < 1 ||
    messages.length > 9 ||
    messages.length % 2 !== 1 ||
    messages.some(
      (m, i) =>
        m.role !== (i % 2 ? "assistant" : "user") ||
        typeof m.text !== "string" ||
        !m.text.trim() ||
        m.text.length > 1500,
    )
  )
    return { statusCode: 400, body: "Invalid conversation" };
  const contents = messages.map((m) => ({
    role: m.role === "assistant" ? "model" : "user",
    parts: [{ text: m.text }],
  }));

  try {
    const answer = await generate(
      contents,
      "You are a concise beginner website tutor. Respond to the latest question using the conversation. Do not claim to inspect a website or perform actions.",
    );
    return {
      statusCode: 200,
      headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
      body: JSON.stringify({ answer }),
    };
  } catch {
    return { statusCode: 502, body: "No complete provider reply" };
  }
};