ወደ ትምህርቱ ይመለሱ

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

public/app.js

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

const history = [],
  form = document.querySelector("form"),
  log = document.querySelector("#conversation"),
  status = document.querySelector("[role=status]");
function show(role, text) {
  const p = document.createElement("p");
  p.textContent = role + ": " + text;
  log.append(p);
}
form.addEventListener("submit", async (e) => {
  e.preventDefault();
  const text = form.elements.message.value.trim(),
    button = form.querySelector("button");
  if (!text) return;
  if (history.length >= 8) {
    status.textContent = "Practice limit reached. Reload to start another conversation.";
    return;
  }
  button.disabled = true;
  status.textContent = "Preparing a reply…";
  const pending = [...history, { role: "user", text }];
  try {
    const r = await fetch("/.netlify/functions/mini-chat", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + form.elements.access.value,
      },
      body: JSON.stringify({ messages: pending }),
    });
    if (!r.ok) throw Error();
    const value = await r.json();
    if (typeof value.answer !== "string") throw Error();
    history.push({ role: "user", text }, { role: "assistant", text: value.answer });
    show("You", text);
    show("Assistant", value.answer);
    form.elements.message.value = "";
    status.textContent = "Reply received.";
  } catch {
    status.textContent =
      "No reply received. Your message is still here; try again after checking the service.";
  } finally {
    button.disabled = false;
  }
});
form.elements.message.addEventListener("keydown", (e) => {
  if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {
    e.preventDefault();
    if (!form.querySelector("button").disabled) form.requestSubmit();
  }
});