Revenir à la leçon

Fichier fonctionnel d’origine

practice/app.js

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.

// Account-free evidence exercise. It does not call a model or send any data.
const copy = {
  "en": [
    "Local practice · scripted, no AI request",
    "Try the café notes before setup",
    "Choose a question. See which supplied note is selected, then compare the quoted fact. This page uses fixed rules, not a language model. The live chatbot comes in the next step.",
    "Your question",
    "Try it",
    "Selected evidence",
    "Scripted response",
    "Show the original notes",
    "No matching note. The practice cannot answer from this dataset.",
    "Ready. Nothing was sent to an external service.",
    "Back to the lesson",
    "What are the opening hours?",
    "Can I reserve a table?",
    "What is the owner’s phone number?",
  ],
  "tr": [
    "Yerel alıştırma · hazır kurallar, AI isteği yok",
    "Kurulumdan önce kafe notlarını deneyin",
    "Bir soru seçin. Hangi hazır notun bulunduğunu görün ve gösterilen bilgiyle karşılaştırın. Bu sayfa dil modeli değil, sabit kurallar kullanır. Gerçek sohbet uygulamasını sonraki adımda çalıştıracağız.",
    "Sorunuz",
    "Dene",
    "Seçilen bilgi",
    "Kurallı örnek yanıt",
    "Asıl notları göster",
    "Eşleşen not yok. Bu bilgilerle soruya yanıt verilemiyor.",
    "Hazır. Harici bir servise hiçbir şey gönderilmedi.",
    "Derse dön",
    "Çalışma saatleri nedir?",
    "Masa rezervasyonu yapabilir miyim?",
    "Sahibinin telefon numarası nedir?",
  ],
  "es": [
    "Práctica local · reglas fijas, sin petición de IA",
    "Prueba las notas antes de configurar",
    "Elige una pregunta. Mira qué nota se selecciona y compárala con el dato mostrado. Esta página usa reglas fijas, no un modelo de lenguaje. El chatbot real viene después.",
    "Tu pregunta",
    "Probar",
    "Información seleccionada",
    "Respuesta de ejemplo con reglas",
    "Ver las notas originales",
    "No hay una nota coincidente. Estos datos no permiten responder.",
    "Listo. No se envió nada a un servicio externo.",
    "Volver a la lección",
    "¿Cuál es el horario de apertura?",
    "¿Puedo reservar una mesa?",
    "¿Cuál es el teléfono del propietario?",
  ],
  "fr": [
    "Exercice local · règles fixes, aucun appel IA",
    "Essayez les notes avant la configuration",
    "Choisissez une question. Observez la note sélectionnée et comparez-la au fait affiché. Cette page utilise des règles fixes, pas un modèle de langage. Le vrai chatbot vient ensuite.",
    "Votre question",
    "Essayer",
    "Information sélectionnée",
    "Réponse d’exemple par règles",
    "Voir les notes originales",
    "Aucune note correspondante. Ces données ne permettent pas de répondre.",
    "Prêt. Rien n’a été envoyé à un service externe.",
    "Retour à la leçon",
    "Quels sont les horaires d’ouverture ?",
    "Puis-je réserver une table ?",
    "Quel est le téléphone du propriétaire ?",
  ],
  "de": [
    "Lokale Übung · feste Regeln, keine KI-Anfrage",
    "Teste die Notizen vor der Einrichtung",
    "Wähle eine Frage. Sieh dir die ausgewählte Notiz an und vergleiche den gezeigten Fakt. Diese Seite verwendet feste Regeln, kein Sprachmodell. Der echte Chatbot folgt im nächsten Schritt.",
    "Deine Frage",
    "Testen",
    "Ausgewählte Information",
    "Regelbasierte Beispielantwort",
    "Originalnotizen anzeigen",
    "Keine passende Notiz. Mit diesen Daten ist keine Antwort möglich.",
    "Bereit. Es wurde nichts an einen externen Dienst gesendet.",
    "Zurück zur Lektion",
    "Wie sind die Öffnungszeiten?",
    "Kann ich einen Tisch reservieren?",
    "Wie lautet die Telefonnummer des Besitzers?",
  ],
  "pt": [
    "Prática local · regras fixas, sem chamada de IA",
    "Experimente as notas antes de configurar",
    "Escolha uma pergunta. Veja a nota selecionada e compare com o fato mostrado. Esta página usa regras fixas, não um modelo de linguagem. O chatbot real vem depois.",
    "Sua pergunta",
    "Testar",
    "Informação selecionada",
    "Resposta de exemplo por regras",
    "Mostrar notas originais",
    "Nenhuma nota correspondente. Estes dados não permitem responder.",
    "Pronto. Nada foi enviado a um serviço externo.",
    "Voltar à aula",
    "Qual é o horário de funcionamento?",
    "Posso reservar uma mesa?",
    "Qual é o telefone do proprietário?",
  ],
  "sw": [
    "Zoezi la ndani · kanuni maalumu, hakuna ombi la AI",
    "Jaribu taarifa za kahawa kabla ya kusanidi",
    "Chagua swali. Angalia taarifa iliyochaguliwa na uilinganishe na ukweli ulioonyeshwa. Ukurasa huu hutumia kanuni, si modeli ya lugha. Chatbot halisi itafuata.",
    "Swali lako",
    "Jaribu",
    "Taarifa iliyochaguliwa",
    "Jibu la mfano kwa kanuni",
    "Onyesha taarifa asili",
    "Hakuna taarifa inayolingana. Data hii haiwezi kujibu swali.",
    "Tayari. Hakuna kilichotumwa kwa huduma ya nje.",
    "Rudi kwenye somo",
    "Saa za kufungua ni zipi?",
    "Ninaweza kuhifadhi meza?",
    "Namba ya simu ya mmiliki ni ipi?",
  ],
  "rw": [
    "Umwitozo wo kuri mudasobwa · amategeko, nta AI ihamagazwa",
    "Gerageza amakuru mbere yo gutegura porogaramu",
    "Hitamo ikibazo. Reba amakuru yatoranyijwe uyagereranye n’ibyerekanywe. Uru rupapuro rukoresha amategeko, si modeli y’ururimi. Chatbot nyayo iraza mu ntambwe ikurikira.",
    "Ikibazo cyawe",
    "Gerageza",
    "Amakuru yatoranyijwe",
    "Igisubizo cy’urugero gishingiye ku mategeko",
    "Erekana amakuru y’umwimerere",
    "Nta makuru ahuye abonetse. Iyi dosiye ntishobora gusubiza icyo kibazo.",
    "Biriteguye. Nta kintu cyoherejwe kuri serivisi yo hanze.",
    "Subira mu isomo",
    "Amasaha yo gufungura ni ayahe?",
    "Nshobora kubika ameza?",
    "Nimero ya telefone ya nyiraho ni iyihe?",
  ],
  "ar": [
    "تدريب محلي · قواعد ثابتة، دون طلب إلى الذكاء الاصطناعي",
    "جرّب معلومات المقهى قبل الإعداد",
    "اختر سؤالًا. شاهد الملاحظة المختارة وقارنها بالمعلومة المعروضة. تستخدم هذه الصفحة قواعد ثابتة لا نموذج لغة. ستشغّل روبوت المحادثة الحقيقي في الخطوة التالية.",
    "سؤالك",
    "جرّب",
    "المعلومات المختارة",
    "إجابة توضيحية بقواعد ثابتة",
    "عرض الملاحظات الأصلية",
    "لا توجد ملاحظة مطابقة. لا تسمح هذه البيانات بالإجابة.",
    "جاهز. لم يُرسل شيء إلى خدمة خارجية.",
    "العودة إلى الدرس",
    "ما ساعات العمل؟",
    "هل يمكنني حجز طاولة؟",
    "ما رقم هاتف المالك؟",
  ],
  "am": [
    "የአካባቢ ልምምድ · ቋሚ ደንቦች፣ የAI ጥያቄ የለም",
    "ከማዘጋጀትዎ በፊት የካፌውን መረጃ ይሞክሩ",
    "ጥያቄ ይምረጡ። የትኛው መረጃ እንደተመረጠ ይመልከቱና ከታየው እውነታ ጋር ያወዳድሩ። ይህ ገጽ ቋሚ ደንብ እንጂ የቋንቋ ሞዴል አይጠቀምም። ትክክለኛውን ቻትቦት በሚቀጥለው ደረጃ ያስነሳሉ።",
    "ጥያቄዎ",
    "ይሞክሩ",
    "የተመረጠ መረጃ",
    "በደንብ የተዘጋጀ ምሳሌ መልስ",
    "ዋናውን መረጃ አሳይ",
    "የሚዛመድ መረጃ የለም። በዚህ መረጃ ጥያቄው አይመለስም።",
    "ዝግጁ ነው። ወደ ውጭ አገልግሎት ምንም አልተላከም።",
    "ወደ ትምህርቱ ተመለስ",
    "የመክፈቻ ሰዓቱ ስንት ነው?",
    "ጠረጴዛ ማስያዝ እችላለሁ?",
    "የባለቤቱ ስልክ ቁጥር ምንድን ነው?",
  ],
};
const keys = [
  "mode",
  "title",
  "intro",
  "question-label",
  "send",
  "selected-title",
  "reply-title",
  "notes-title",
];
const params = new URLSearchParams(location.search);
const lang = Object.hasOwn(copy, params.get("lang")) ? params.get("lang") : "en";
const text = copy[lang];
document.documentElement.lang = lang;
document.documentElement.dir = lang === "ar" ? "rtl" : "ltr";
keys.forEach((key, i) => (document.getElementById(key).textContent = text[i]));
const back = document.querySelector("#back");
back.textContent = text[10];
back.hidden = location.protocol === "file:";
back.href = "/lesson-assets/mini-lessons/content-chatbot/" + lang + ".html#1";
const records = window.PracticeCafeNotes;
if (!Array.isArray(records)) throw Error("Local practice notes are missing.");
document.querySelector("#notes").textContent = JSON.stringify(records, null, 2);
document.querySelector("#status").textContent = text[9];
const questions = [
  { label: text[11], query: text[11] },
  { label: text[12], query: text[12] },
  { label: text[13], query: text[13] },
];
for (const item of questions) {
  const button = document.createElement("button");
  button.type = "button";
  button.textContent = item.label;
  button.addEventListener("click", () => {
    document.querySelector("#question").value = item.query;
    show(item.query);
  });
  document.querySelector("#questions").append(button);
}
function show(question) {
  const words = new Set(
    question
      .toLowerCase()
      .normalize("NFKC")
      .match(/[\p{L}\p{M}\p{N}]+/gu) || [],
  );
  const chosen = records
    .map((record) => ({
      record,
      score: record.keywords.filter((k) => words.has(k)).length,
    }))
    .filter((row) => row.score > 0)
    .sort((a, b) => b.score - a.score)
    .slice(0, 2)
    .map((row) => row.record);
  const selected = document.querySelector("#selected");
  selected.replaceChildren();
  for (const record of chosen) {
    const p = document.createElement("p");
    p.textContent = record.id + " · " + record.title;
    selected.append(p);
  }
  document.querySelector("#reply").textContent = chosen.length
    ? chosen.map((r) => r.text).join(" ")
    : text[8];
  document.querySelector("#status").textContent = text[9];
}
document.querySelector("#ask").addEventListener("submit", (event) => {
  event.preventDefault();
  show(document.querySelector("#question").value);
});