frontend/chat.js

파일 다운로드

const form = document.querySelector("#chat-form");
const input = document.querySelector("#question");
const button = document.querySelector("#send");
const log = document.querySelector("#conversation");
const status = document.querySelector("#status");
let history = [];
function addMessage(role, text, usage = null, followup = null) {
  const item = document.createElement("article");
  item.className = role === "고객" ? "message customer" : "message assistant";
  const label = document.createElement("span");
  label.className = "role";
  label.textContent = role;
  const content = document.createElement("p");
  content.textContent = text;
  item.append(label, content);
  if (followup) {
    const extra = document.createElement("p");
    extra.className = "followup";
    extra.textContent = followup;
    item.append(extra);
  }
  if (role === "모아상점") {
    const tokens = document.createElement("div");
    tokens.className = "tokens";
    tokens.textContent = usage ? `입력 ${usage.prompt_tokens ?? "—"} · 출력 ${usage.completion_tokens ?? "—"} 토큰` : "토큰 사용량 없음";
    item.append(tokens);
  }
  log.append(item);
  item.scrollIntoView({ behavior: "smooth", block: "nearest" });
}
fetch("/api/chat").then(r => r.json()).then(data => {
  document.querySelector("#model").textContent = data.mode === "DEMO_MODE" ? "DEMO_MODE · 고정 응답" : data.model;
}).catch(() => { status.textContent = "서버 연결을 확인하세요."; });
form.addEventListener("submit", async event => {
  event.preventDefault();
  const question = input.value.trim();
  if (!question || question.length > 500) return;
  button.disabled = true;
  addMessage("고객", question);
  input.value = "";
  status.textContent = "답변 생성 중…";
  try {
    const response = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ question, history }) });
    const result = await response.json();
    if (!response.ok) throw new Error(result.error || `HTTP ${response.status}`);
    const fields = { answer: result.answer, needs_followup: result.needs_followup, followup_question: result.followup_question };
    addMessage("모아상점", fields.answer, result.usage, fields.needs_followup ? fields.followup_question : null);
    history.push({ role: "user", content: question }, { role: "assistant", content: JSON.stringify(fields) });
    history = history.slice(-6);
    status.textContent = "전송 완료";
  } catch (error) { status.textContent = error.message; }
  finally { button.disabled = false; input.focus(); }
});