ወደ ትምህርቱ ይመለሱ

የመጀመሪያው የሚሠራ ፋይል

netlify/functions/mini-explain.mjs

ኮዱ እና የሚሠሩ ምሳሌ ገጾች የመጀመሪያ መለያዎቻቸውንና የምሳሌ ጽሑፋቸውን ይይዛሉ። ትምህርቱ እና የፋይል መመሪያዎች በእርስዎ ቋንቋ ያብራሯቸዋል።

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 > 1000) return { statusCode: 413, body: "Too large" };
  try {
    const answer = await generate(
      [
        {
          role: "user",
          parts: [{ text: "Explain what a website server does in two sentences." }],
        },
      ],
      "Explain clearly to a beginner.",
    );
    return {
      statusCode: 200,
      headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
      body: JSON.stringify({ answer }),
    };
  } catch {
    return {
      statusCode: 502,
      body: "Provider unavailable; check server configuration and provider status",
    };
  }
};