MOA / LLM SERVICE / CHAPTER 04

4장 · 한국어 질문을 잘 찾는 검색을 붙인다

시작 ZIP완성 ZIP시작 안내완성 안내

코드 전문은 이 페이지에서 복사하거나 파일로 내려받을 수 있습니다. 복사 권한이 없으면 선택된 코드에 Ctrl+C 또는 ⌘C를 사용합니다.

완성 소스 21개

aliases.py

별도 보기파일 다운로드
코드 펼치기
"""공식 상품 코드의 표기만 정규화한다. 다른 상품을 추측하지 않는다."""
import re
import unicodedata

CATALOG_CODES = {"AB-120", "AB-121", "MG-210", "LT-310", "PC-410", "NT-510"}
CODE_PATTERN = re.compile(r"(?<![A-Z0-9])([A-Z]{2})\s*-?\s*(\d{3})(?![A-Z0-9])", re.I)


def canonicalize(text):
    text = unicodedata.normalize("NFKC", text)

    def replace(match):
        code = f"{match[1].upper()}-{match[2]}"
        return code if code in CATALOG_CODES else match[0]

    return CODE_PATTERN.sub(replace, text)


def product_codes(query):
    return {match[0].upper() for match in re.finditer(
        r"(?<![A-Z0-9])[A-Z]{2}-\d{3}(?![A-Z0-9])", canonicalize(query), re.I
    )} & CATALOG_CODES


def product_pool(chunks, query):
    codes = product_codes(query)
    if not codes:
        return chunks
    return [row for row in chunks if row.get("product_code") in codes | {None}]

build_documents.py

별도 보기파일 다운로드
코드 펼치기
"""원문에서 문서·조각과 분할 비교를 생성합니다."""
import argparse
import hashlib
import json
from pathlib import Path
from documents import load_documents, chunk_documents, write_jsonl


def build(data_dir, max_chars=360):
    root = Path(data_dir)
    documents = load_documents(root / "source/documents.json")
    chunks = chunk_documents(documents, max_chars)
    write_jsonl(root / "documents.jsonl", documents)
    write_jsonl(root / "chunks.jsonl", chunks)
    comparison = {}
    for size in (180, 360):
        rows = chunk_documents(documents, size)
        comparison[str(size)] = {"chunk_count": len(rows),
                                "longest_chars": max(len(row["text"]) for row in rows),
                                "over_soft_limit": sum(len(row["text"]) > size for row in rows)}
    meta = {"dataset_id": "moa_data_r01", "schema_version": 1,
            "chunk_version": "sections_v1", "max_chars": max_chars,
            "document_count": len(documents), "chunk_count": len(chunks),
            "source_sha256": hashlib.sha256((root / "source/documents.json").read_bytes()).hexdigest(),
            "chunks_sha256": hashlib.sha256((root / "chunks.jsonl").read_bytes()).hexdigest(),
            "comparison": comparison}
    (root / "document_build.json").write_text(json.dumps(meta, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    return meta


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--data", default=str(Path(__file__).parent / "data"))
    parser.add_argument("--max-chars", type=int, default=360)
    args = parser.parse_args()
    print(json.dumps(build(args.data, args.max_chars), ensure_ascii=False, indent=2))

conversation.py

별도 보기파일 다운로드
코드 펼치기
from prompts import build_system_prompt

MAX_HISTORY_MESSAGES = 6
MAX_MESSAGE_CHARS = 1200


class HistoryError(ValueError):
    pass


def build_messages(question, history=None, style="balanced"):
    history = [] if history is None else history
    if not isinstance(history, list) or len(history) > MAX_HISTORY_MESSAGES or len(history) % 2:
        raise HistoryError("대화 기록은 최근 세 턴의 완성된 질문·답변 쌍이어야 합니다.")
    clean = []
    for index, message in enumerate(history):
        expected = "user" if index % 2 == 0 else "assistant"
        if not isinstance(message, dict) or set(message) != {"role", "content"}:
            raise HistoryError("대화 기록의 필드를 확인하세요.")
        if message["role"] != expected:
            raise HistoryError("대화 기록은 user·assistant 순서여야 합니다.")
        text = message["content"]
        if not isinstance(text, str) or not 1 <= len(text.strip()) <= MAX_MESSAGE_CHARS:
            raise HistoryError("이전 메시지는 1~1200자의 문자열이어야 합니다.")
        clean.append({"role": expected, "content": text.strip()})
    return ([{"role": "system", "content": build_system_prompt(style)}] + clean
            + [{"role": "user", "content": question}])

demo_response.py

별도 보기파일 다운로드
코드 펼치기
import json
import re


def demo_result(messages):
    q = messages[-1]["content"]
    normalized = q.upper().replace("-", "").replace(" ", "")
    previous = " ".join(m["content"] for m in messages[1:-1])
    previous = previous.upper().replace("-", "").replace(" ", "")
    explicit_code = re.search(r"[A-Z]{2}\s*-?\s*\d{3}", q.upper())
    refers_back = any(word in q for word in ("그 가방", "그 상품", "이 가방", "이 상품"))
    known_product = "AB120" in normalized or (
        explicit_code is None and refers_back and "AB120" in previous
    )
    if "배송비" in q or "교환" in q:
        data = {"answer": "배송비·교환 규정이 제공되지 않아 현재 안내할 수 없습니다.",
                "needs_followup": False, "followup_question": None}
    elif "주문" in q or "환불" in q or "배송" in q:
        data = {"answer": "조회·처리 기능이 연결되지 않아 처리 결과를 확정할 수 없습니다.",
                "needs_followup": False, "followup_question": None}
    elif known_product:
        if "가격" in q or "얼마" in q:
            answer = "AB-120 데일리 백팩의 판매 가격은 39,000원입니다."
        elif "무게" in q:
            answer = "AB-120 데일리 백팩의 무게는 580g입니다."
        elif "용량" in q:
            answer = "AB-120 데일리 백팩의 용량은 18L입니다."
        elif normalized.rstrip("?.!") in (
            "AB120", "AB120이요", "AB120상품에대해알려주세요", "AB120상품을소개해주세요"
        ):
            answer = "AB-120 데일리 백팩은 판매 가격 39,000원, 용량 18L, 무게 580g입니다."
        else:
            answer = "AB-120의 해당 정보는 참조 사실에 없어 현재 안내할 수 없습니다."
        data = {"answer": answer, "needs_followup": False, "followup_question": None}
    elif explicit_code:
        data = {"answer": "문의하신 상품의 참조 사실이 제공되지 않아 현재 안내할 수 없습니다.",
                "needs_followup": False, "followup_question": None}
    else:
        data = {"answer": "상품 문의를 도와드리겠습니다.",
                "needs_followup": True,
                "followup_question": "상품명이나 상품코드와 궁금한 점을 알려주시겠어요?"}
    return {"answer": json.dumps(data, ensure_ascii=False), "usage": None, "model": "DEMO_MODE"}

document_schema.py

별도 보기파일 다운로드
코드 펼치기
"""문서·조각의 필드와 적용일 검사."""
from datetime import date
import re

FIELDS = ("document_id", "title", "document_type", "product_code",
          "effective_from", "effective_to", "revision", "body")
CODE = re.compile(r"([A-Z]{2})[- ]?(\d{3})", re.I)


def normalize_product_code(value):
    match = CODE.fullmatch(value.strip())
    return f"{match[1].upper()}-{match[2]}" if match else None


def validate_document(document):
    if set(document) != set(FIELDS):
        raise ValueError("document fields mismatch")
    for key in ("document_id", "title", "document_type", "revision", "body"):
        if not isinstance(document[key], str) or not document[key].strip():
            raise ValueError(f"invalid field: {key}")
    code = document["product_code"]
    if code is not None and (not isinstance(code, str) or normalize_product_code(code) != code):
        raise ValueError("invalid product_code")
    start = date.fromisoformat(document["effective_from"])
    end = document["effective_to"]
    if end is not None and date.fromisoformat(end) < start:
        raise ValueError("effective_to precedes effective_from")
    return document


def is_effective(record, as_of):
    day = date.fromisoformat(as_of)
    start = date.fromisoformat(record["effective_from"])
    end = record["effective_to"]
    return start <= day and (end is None or day <= date.fromisoformat(end))

documents.py

별도 보기파일 다운로드
코드 펼치기
"""제목과 문단을 보존하는 문서 파이프라인."""
import json
from pathlib import Path
from document_schema import validate_document, is_effective


def load_documents(path):
    records = json.loads(Path(path).read_text(encoding="utf-8"))
    seen = set()
    for record in records:
        validate_document(record)
        if record["document_id"] in seen:
            raise ValueError("duplicate document_id")
        seen.add(record["document_id"])
    return records


def sections(body):
    heading, paragraphs, buffer = "본문", [], []
    for line in body.splitlines() + [""]:
        if line.startswith("## "):
            if buffer:
                paragraphs.append(" ".join(buffer)); buffer = []
            if paragraphs:
                yield heading, paragraphs
            heading, paragraphs = line[3:].strip(), []
        elif line.strip():
            buffer.append(line.strip())
        elif buffer:
            paragraphs.append(" ".join(buffer)); buffer = []
    if paragraphs:
        yield heading, paragraphs


def chunk_documents(documents, max_chars=360):
    if max_chars < 1:
        raise ValueError("max_chars must be positive")
    chunks = []
    for document in documents:
        number = 0
        for heading, paragraphs in sections(document["body"]):
            prefix = f"{document['title']}\n{heading}\n"
            groups, current = [], ""
            for paragraph in paragraphs:
                trial = current + ("\n\n" if current else "") + paragraph
                if current and len(prefix + trial) > max_chars:
                    groups.append(current); current = paragraph
                else:
                    current = trial
            if current:
                groups.append(current)
            for group in groups:
                number += 1
                chunk = {key: value for key, value in document.items() if key != "body"}
                chunk.update(chunk_id=f"{document['document_id']}__c{number:02d}",
                             heading=heading, text=prefix + group)
                chunks.append(chunk)
    return chunks


def write_jsonl(path, records):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("".join(json.dumps(row, ensure_ascii=False) + "\n" for row in records), encoding="utf-8")

embedding_client.py

별도 보기파일 다운로드
코드 펼치기
"""임베딩 API 전용 클라이언트. 생성 모델 설정과 독립적이다."""
import json
import math
import os
import urllib.error
import urllib.request


def embedding_config():
    return {
        "base_url": os.getenv("EMBEDDING_BASE_URL", "https://api.openai.com/v1").rstrip("/"),
        "model": os.getenv("EMBEDDING_MODEL", "text-embedding-3-small"),
        "dimensions": int(os.getenv("EMBEDDING_DIMENSIONS", "512")),
    }


def embed_texts(texts, config=None):
    config = config or embedding_config()
    if not texts or any(not isinstance(text, str) or not text.strip() for text in texts):
        raise ValueError("임베딩 입력에는 빈 문자열을 넣을 수 없습니다.")
    key = os.getenv("EMBEDDING_API_KEY") or os.getenv("LLM_API_KEY", "")
    if not key:
        raise RuntimeError("EMBEDDING_API_KEY 또는 LLM_API_KEY를 설정하세요.")
    body = {"model": config["model"], "input": texts,
            "dimensions": config["dimensions"], "encoding_format": "float"}
    request = urllib.request.Request(
        config["base_url"] + "/embeddings",
        data=json.dumps(body, ensure_ascii=False).encode("utf-8"),
        headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            result = json.load(response)
    except urllib.error.HTTPError as error:
        raise RuntimeError(f"임베딩 API HTTP {error.code}") from None
    except (urllib.error.URLError, TimeoutError, json.JSONDecodeError):
        raise RuntimeError("임베딩 API 연결 또는 JSON 응답을 확인하세요.") from None
    rows = sorted(result.get("data", []), key=lambda row: row["index"])
    if [row["index"] for row in rows] != list(range(len(texts))):
        raise RuntimeError("임베딩 응답의 입력 순서 또는 개수가 맞지 않습니다.")
    vectors = [row["embedding"] for row in rows]
    for vector in vectors:
        if len(vector) != config["dimensions"] or any(
            isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x)
            for x in vector
        ):
            raise RuntimeError("임베딩 응답의 차원 또는 숫자 값이 올바르지 않습니다.")
    return {"vectors": vectors, "model": result.get("model"), "usage": result.get("usage")}

first_call.py

별도 보기파일 다운로드
코드 펼치기
from request_options import chat_options
import json
from urllib.request import Request, urlopen
from settings import API_KEY, BASE_URL, MAX_TOKENS, MODEL, TIMEOUT

if not API_KEY:
    raise ValueError("LLM_API_KEY 환경변수를 설정하세요.")
payload = {
    "model": MODEL,
    "messages": [{"role": "user", "content": "배송비가 얼마인가요?"}],
    **chat_options(MODEL, MAX_TOKENS, 0.2),
}
request = Request(BASE_URL + "/chat/completions",
                  data=json.dumps(payload).encode("utf-8"),
                  headers={"Authorization": "Bearer " + API_KEY,
                           "Content-Type": "application/json"})
with urlopen(request, timeout=TIMEOUT) as response:
    result = json.load(response)
print(json.dumps(result, ensure_ascii=False, indent=2))

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(); }
});

frontend/index.html

별도 보기파일 다운로드
코드 펼치기
<!doctype html>
<html lang="ko">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>모아상점 · 고객지원</title>
  <link rel="stylesheet" href="/style.css">
  <script src="/chat.js" defer></script>
</head>
<body>
  <main class="shell">
    <header class="masthead">
      <a class="brand" href="/" aria-label="모아상점 홈"><span class="mark">m.</span> 모아상점</a>
      <span class="chapter">CHAPTER 02 · RESPONSE CONTRACT</span>
    </header>
    <section class="hero">
      <div><p class="eyebrow">모아상점 고객지원</p><h1>무엇을 도와드릴까요?</h1><p class="intro">배송과 교환에 대해 궁금한 점을 남겨주세요.</p></div>
      <div class="connection"><span class="signal"></span><div><small>연결 모델</small><span id="model">연결 확인 중…</span></div></div>
    </section>
    <section class="chat-panel" aria-label="고객지원 대화">
      <div class="panel-top"><span>고객과 모아상점</span><span class="live">CONVERSATION</span></div>
      <div id="conversation" aria-live="polite"></div>
      <form id="chat-form">
        <label for="question">질문</label>
        <div class="input-row"><input id="question" name="question" placeholder="예: 배송비가 얼마인가요?" maxlength="500" autocomplete="off" required><button id="send" type="submit">전송 <span aria-hidden="true">↗</span></button></div>
        <div class="form-foot"><span>한 번에 500자까지</span><span id="status" role="status">질문을 입력하세요.</span></div>
      </form>
    </section>
    <footer>MOA STORE <span>고객지원 · 상담 규칙과 대화 기록</span></footer>
  </main>
</body>
</html>

frontend/style.css

별도 보기파일 다운로드
코드 펼치기
:root{color-scheme:light;--ink:#162536;--muted:#637283;--line:#dce5e9;--teal:#007f7a;--pale:#edf8f5;--navy:#163146}
*{box-sizing:border-box}body{margin:0;background:#f4f7f8;color:var(--ink);font-family:Arial,"Apple SD Gothic Neo","Malgun Gothic",sans-serif;-webkit-font-smoothing:antialiased}
.shell{max-width:1060px;margin:auto;padding:0 40px}.masthead{height:98px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}.brand{color:var(--ink);text-decoration:none;font-size:23px;font-weight:700;display:flex;align-items:center;gap:11px}.mark{background:var(--navy);color:white;width:39px;height:39px;border-radius:11px;display:grid;place-items:center;font-size:24px}.chapter{font-size:10px;letter-spacing:1.8px;color:var(--muted)}
.hero{display:flex;align-items:center;justify-content:space-between;gap:24px;padding:45px 0 35px}.eyebrow{margin:0 0 12px;color:var(--teal);font-size:12px;font-weight:700;letter-spacing:1px}h1{font-size:33px;line-height:1.3;letter-spacing:-1px;margin:0 0 12px}.intro{font-size:14px;color:var(--muted);margin:0}.connection{display:flex;align-items:flex-start;gap:10px;max-width:280px;background:#fff;padding:15px 18px;border:1px solid var(--line);border-radius:12px}.signal{width:7px;height:7px;flex:none;border-radius:50%;background:var(--teal);margin-top:4px}.connection small{display:block;color:var(--muted);font-size:10px;margin-bottom:7px}.connection #model{font-size:12px;font-weight:700;overflow-wrap:anywhere}
.chat-panel{background:#fff;border:1px solid var(--line);border-radius:16px;overflow:hidden;box-shadow:0 12px 35px #16314608}.panel-top{height:49px;padding:0 25px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);font-size:12px;font-weight:700}.live{font-size:9px;letter-spacing:1.7px;color:var(--muted)}#conversation{padding:25px 28px;min-height:150px;display:flex;flex-direction:column;gap:18px}.message{max-width:88%;padding:17px 21px;border-radius:12px}.message.customer{align-self:flex-end;background:var(--navy);color:#fff;max-width:82%}.message.assistant{align-self:flex-start;background:var(--pale);border:1px solid #d9ece6}.role{font-size:10px;font-weight:700;letter-spacing:.7px;opacity:.8}.message p{font-size:15px;line-height:1.75;white-space:pre-wrap;overflow-wrap:anywhere;margin:7px 0 0}.tokens{font-size:10px;color:var(--muted);border-top:1px solid #d5e7e1;padding-top:10px;margin-top:12px}
#chat-form{padding:21px 27px 19px;border-top:1px solid var(--line);background:#fcfdfd}label{display:block;font-size:11px;font-weight:700;margin-bottom:9px}.input-row{display:flex;gap:10px}input{min-width:0;flex:1;border:1px solid #cdd8de;border-radius:9px;padding:14px 15px;font-size:14px;font-family:inherit;outline:none}input:focus{border-color:var(--teal);box-shadow:0 0 0 2px #007f7a14}input::placeholder{color:#97a2ac}button{border:0;border-radius:9px;background:var(--teal);color:#fff;font-size:13px;font-weight:700;padding:0 20px;cursor:pointer}button span{margin-left:12px}button:disabled{opacity:.5;cursor:wait}.form-foot{display:flex;justify-content:space-between;gap:16px;margin-top:11px;font-size:10px;color:var(--muted)}#status{text-align:right}footer{padding:27px 0 30px;font-size:10px;font-weight:700;letter-spacing:1.2px;color:#8a97a1}footer span{float:right;letter-spacing:0;font-weight:400}
@media(max-width:680px){.shell{padding:0 18px}.masthead{height:77px}.chapter{display:none}.hero{display:block;padding:30px 0 24px}h1{font-size:27px}.connection{margin-top:22px;max-width:100%}#conversation{padding:20px 15px}.message{max-width:97%;padding:14px 16px}#chat-form{padding:19px 16px}.panel-top{padding:0 17px}.message p{font-size:14px}button{padding:0 15px}}

.followup{border-left:3px solid #087f83;padding-left:14px;color:#087f83;font-weight:600}

hybrid_search.py

별도 보기파일 다운로드
코드 펼치기
"""RRF: 서로 다른 점수를 더하지 않고 순위를 결합한다."""


def hybrid_search(keyword_rows, vector_rows, top_k=3, rank_constant=60):
    if not isinstance(top_k, int) or not 1 <= top_k <= 20 or rank_constant < 0:
        raise ValueError("top_k는 1~20, rank_constant는 0 이상입니다.")
    combined = {}
    for ranking in (keyword_rows, vector_rows):
        seen = set()
        for row in ranking:
            key = row["chunk_id"]
            if key in seen:
                continue
            seen.add(key)
            item = combined.setdefault(key, {"chunk_id": key, "document_id": row["document_id"],
                                             "score": 0.0, "method": "hybrid"})
            item["score"] += 1 / (rank_constant + row["rank"])
    ordered = sorted(combined.values(), key=lambda row: (-row["score"], row["chunk_id"]))
    return [dict(row, rank=rank) for rank, row in enumerate(ordered[:top_k], 1)]

keyword_search.py

별도 보기파일 다운로드
코드 펼치기
"""작은 한국어 자료의 부분 문자열 일치 기준선."""
import re
import unicodedata
from aliases import canonicalize

ENDINGS = ("해주세요", "되나요", "인가요", "알려주세요", "은", "는", "이", "가", "을", "를", "의")
TERM_ALIASES = {"출근용": "출근"}
STOPWORDS = {"얼마", "무엇", "어떻게", "있나요", "되나요", "찾아주세요", "알려주세요"}


def terms(text, use_aliases=True):
    normalized = canonicalize(text) if use_aliases else unicodedata.normalize("NFKC", text)
    values = re.findall(r"[a-z]{2}-\d{3}|[가-힣a-z0-9]+", normalized.lower())
    result = set()
    for word in values:
        if word in STOPWORDS:
            continue
        for ending in ENDINGS:
            if word.endswith(ending) and len(word) - len(ending) >= 2:
                word = word[:-len(ending)]
                break
        word = TERM_ALIASES.get(word, word)
        if len(word) >= 2:
            result.add(word)
    return result


def keyword_search(query, chunks, top_k=3, use_aliases=True):
    if not isinstance(top_k, int) or not 1 <= top_k <= 20:
        raise ValueError("top_k는 1~20의 정수입니다.")
    query_terms = terms(query, use_aliases)
    candidates = []
    for row in chunks:
        text = "\n".join(str(row.get(key, "")) for key in ("title", "heading", "text"))
        text = canonicalize(text) if use_aliases else text
        compact = re.sub(r"\s+", "", unicodedata.normalize("NFKC", text).lower())
        matched = [word for word in query_terms if word in compact]
        if matched:
            score = len(matched) / len(query_terms)
            candidates.append({"chunk_id": row["chunk_id"], "document_id": row["document_id"],
                               "score": score, "method": "keyword"})
    candidates.sort(key=lambda row: (-row["score"], row["chunk_id"]))
    return [dict(row, rank=rank) for rank, row in enumerate(candidates[:top_k], 1)]

model_client.py

별도 보기파일 다운로드
코드 펼치기
from request_options import chat_options
import json
import re
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
import settings


class ModelError(Exception):
    pass


def generate(messages, temperature=0.2):
    if settings.DEMO_MODE:
        return {"answer": "배송비와 교환 가능 여부는 상점 규정을 확인해야 합니다.",
                "usage": None, "model": "DEMO_MODE"}
    if not settings.API_KEY:
        raise ModelError("LLM_API_KEY 환경변수를 설정하세요.")
    payload = {"model": settings.MODEL, "messages": messages,
               **chat_options(settings.MODEL, settings.MAX_TOKENS, temperature)}
    request = Request(settings.BASE_URL + "/chat/completions",
                      data=json.dumps(payload).encode("utf-8"),
                      headers={"Authorization": "Bearer " + settings.API_KEY,
                               "Content-Type": "application/json"})
    try:
        with urlopen(request, timeout=settings.TIMEOUT) as response:
            result = json.load(response)
    except HTTPError as error:
        code = "unknown"
        try:
            value = json.loads(error.read(16384))["error"]["code"]
            if (isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_.-]{1,80}", value)
                    and settings.API_KEY not in value):
                code = value
        except (ValueError, KeyError, TypeError):
            pass
        raise ModelError(f"모델 API 오류: HTTP {error.code} ({code})") from None
    except (URLError, TimeoutError, OSError):
        raise ModelError("모델 API 연결 실패 또는 응답 시간 초과") from None
    except (ValueError, UnicodeError):
        raise ModelError("모델 API 응답을 JSON으로 해석할 수 없습니다.") from None
    try:
        answer = result["choices"][0]["message"]["content"]
        if not isinstance(answer, str) or not answer.strip():
            raise ValueError
        return {"answer": answer, "usage": result.get("usage"),
                "model": result.get("model", settings.MODEL)}
    except (KeyError, IndexError, TypeError, ValueError):
        raise ModelError("모델 API 응답에 텍스트 content가 없습니다.") from None

prompts.py

별도 보기파일 다운로드
코드 펼치기
def build_system_prompt(style="balanced"):
    tone = ("아주 짧게 답하세요." if style == "brief" else
            "먼저 문의 대상을 짚고, 현재 안내할 수 있는 범위를 한 문장으로 설명하세요.")
    return (
        "당신은 모아상점 고객지원 담당입니다. 한국어 존댓말로 답하세요. "
        + tone +
        " 참조 사실: AB-120 데일리 백팩의 판매 가격은 39,000원, 용량은 18L, 무게는 580g입니다. "
        "AB120도 AB-120과 같은 상품코드입니다. "
        "상품과 문의 항목을 현재 질문이나 이전 대화에서 알 수 있으면 해당 참조 사실을 답하세요. "
        "포괄적인 AB-120 상품 문의에는 제공된 세 사실을 안내하세요. "
        "이전 대화에서 상품이 명확하면 '그 가방' 같은 표현을 같은 상품에 연결하세요. "
        "질문에 없는 상품을 AB-120으로 가정하지 마세요. "
        "참조 사실에 없는 상품 정보·배송 및 교환 규정·주문 조회 결과는 제공되지 않았습니다. "
        "알려 주지 않은 사실과 주문 상태·환불 완료를 추측하지 마세요. "
        "상품이나 문의 항목이 빠져 제공된 사실 중 답할 내용을 정할 수 없을 때만 추가 질문 하나를 만드세요. "
        "규정이나 조회 도구가 없어 처리할 수 없는 일에는 금액이나 주문번호를 더 요구하지 마세요. "
        "배송비·주문 상태·환불 완료 문의에는 현재 확인할 자료나 실행 도구가 없다고 답하고, "
        "needs_followup은 false, followup_question은 null로 쓰세요. "
        "'확인 중입니다', '기다려 주세요', '주문번호를 주시면 조회하겠습니다'라고 말하지 마세요. "
        "예: 주문은 어디까지 왔나요? → "
        '{"answer":"주문 조회 도구가 연결되지 않아 현재 배송 상태를 확인할 수 없습니다.",'
        '"needs_followup":false,"followup_question":null}. '
        "다음 세 필드의 JSON 객체만 반환하세요. "
        "answer: 비어 있지 않은 답변 문자열, 200자 이내. "
        "needs_followup: 추가 질문이 있으면 true, 없으면 false. "
        "followup_question: true이면 100자 이내 질문 문자열, false이면 null."
    )

response_schema.py

별도 보기파일 다운로드
코드 펼치기
import json


class SchemaError(ValueError):
    pass


def parse_response(raw):
    try:
        data = json.loads(raw)
    except (TypeError, ValueError):
        raise SchemaError("응답이 JSON 객체 형식이어야 합니다.") from None
    fields = {"answer", "needs_followup", "followup_question"}
    if not isinstance(data, dict) or set(data) != fields:
        raise SchemaError("응답에는 약속한 세 필드가 필요합니다.")
    answer = data["answer"]
    if not isinstance(answer, str) or not 1 <= len(answer.strip()) <= 500:
        raise SchemaError("답변은 1~500자의 문자열이어야 합니다.")
    if type(data["needs_followup"]) is not bool:
        raise SchemaError("needs_followup은 참·거짓이어야 합니다.")
    question = data["followup_question"]
    if data["needs_followup"]:
        if not isinstance(question, str) or not 1 <= len(question.strip()) <= 200:
            raise SchemaError("추가 질문은 1~200자의 문자열이어야 합니다.")
        question = question.strip()
    elif question is not None:
        raise SchemaError("추가 질문이 없으면 null이어야 합니다.")
    return {"answer": answer.strip(), "needs_followup": data["needs_followup"],
            "followup_question": question}

search_cli.py

별도 보기파일 다운로드
코드 펼치기
"""인덱스 생성·저장된 질문 비교·새 질문 검색 명령."""
import argparse
import json
from pathlib import Path
from aliases import canonicalize, product_pool
from embedding_client import embed_texts, embedding_config
from hybrid_search import hybrid_search
from keyword_search import keyword_search
from vector_search import embedding_text, metadata, validate_index, vector_search

DATA = Path(__file__).resolve().parent / "data"


def load_rows(path):
    return [json.loads(line) for line in Path(path).read_text(encoding="utf-8").splitlines() if line.strip()]


def save_json(path, value):
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    Path(path).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def build_index(chunks, config, chunk_profile):
    result = embed_texts([embedding_text(row) for row in chunks], config)
    return {"metadata": metadata(chunks, config, chunk_profile),
            "returned_model": result["model"], "usage": result["usage"],
            "rows": [{"chunk_id": row["chunk_id"], "embedding": vector}
                     for row, vector in zip(chunks, result["vectors"])]}


def build_query_cache(questions, config):
    queries = [canonicalize(row["question"]) for row in questions]
    result = embed_texts(queries, config)
    return {"model": config["model"], "dimensions": config["dimensions"],
            "base_url": config["base_url"], "usage": result["usage"],
            "rows": [{"question_id": row["question_id"], "query": query, "embedding": vector}
                     for row, query, vector in zip(questions, queries, result["vectors"])]}


def current_chunks(chunks, as_of):
    return [row for row in chunks if row["effective_from"] <= as_of
            and (row.get("effective_to") is None or as_of <= row["effective_to"])]


def search(query, chunks, index, query_vector, top_k=3, as_of="2026-06-15", exact_product=True):
    pool = current_chunks(chunks, as_of)
    if exact_product:
        pool = product_pool(pool, query)
    candidate_k = min(20, max(top_k, 6))
    keyword = keyword_search(query, pool, candidate_k)
    vector = vector_search(query_vector, index, pool, candidate_k)
    return {"keyword": keyword[:top_k], "vector": vector[:top_k],
            "hybrid": hybrid_search(keyword, vector, top_k)}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("command", choices=["build", "compare", "search"])
    parser.add_argument("--data", type=Path, default=DATA)
    parser.add_argument("--query")
    parser.add_argument("--top-k", type=int, default=3)
    parser.add_argument("--as-of", default="2026-06-15")
    args = parser.parse_args()
    if not 1 <= args.top_k <= 20:
        parser.error("--top-k는 1~20입니다.")
    config = embedding_config()
    chunks = load_rows(args.data / "chunks.jsonl")
    manifest = json.loads((args.data / "document_build.json").read_text(encoding="utf-8"))
    profile = {key: manifest[key] for key in ("chunk_version", "max_chars")}
    index_path = args.data / "search_index.json"
    if args.command == "build":
        save_json(index_path, build_index(chunks, config, profile))
        questions = load_rows(args.data / "search_questions.jsonl")
        save_json(args.data / "query_embeddings.json", build_query_cache(questions, config))
        print("저장: search_index.json, query_embeddings.json")
        return
    index = json.loads(index_path.read_text(encoding="utf-8"))
    validate_index(index, chunks, config, profile)
    if args.command == "search":
        if not args.query or not args.query.strip():
            parser.error("--query에 질문을 지정하세요.")
        vector = embed_texts([canonicalize(args.query)], config)["vectors"][0]
        result = search(args.query, chunks, index, vector, args.top_k, args.as_of)
    else:
        questions = load_rows(args.data / "search_questions.jsonl")
        cache = json.loads((args.data / "query_embeddings.json").read_text(encoding="utf-8"))
        if any(cache.get(key) != config[key] for key in ("model", "dimensions", "base_url")):
            raise ValueError("질문 임베딩을 재생성하세요.")
        saved = {row["question_id"]: row for row in cache["rows"]}
        result = []
        for row in questions:
            vector_row = saved[row["question_id"]]
            if vector_row["query"] != canonicalize(row["question"]):
                raise ValueError("질문이 바뀌었습니다. 질문 임베딩을 재생성하세요.")
            rankings = search(row["question"], chunks, index, vector_row["embedding"],
                              args.top_k, args.as_of, exact_product=False)
            filtered = search(row["question"], chunks, index, vector_row["embedding"],
                              args.top_k, args.as_of, exact_product=True)
            result.append(dict(row, rankings=rankings, product_filtered=filtered))
        save_json(args.data / "search_results.json", result)
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()

server.py

별도 보기파일 다운로드
코드 펼치기
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import model_client
import settings
from conversation import build_messages, HistoryError
from response_schema import parse_response, SchemaError
from demo_response import demo_result

FRONTEND = Path(__file__).parent / "frontend"
FILES = {"/": ("index.html", "text/html; charset=utf-8"),
         "/chat.js": ("chat.js", "text/javascript; charset=utf-8"),
         "/style.css": ("style.css", "text/css; charset=utf-8")}


def reply(question, history):
    messages = build_messages(question, history)
    result = demo_result(messages) if settings.DEMO_MODE else model_client.generate(messages)
    response = parse_response(result["answer"])
    return {**response, "usage": result.get("usage"), "model": result.get("model")}


class Handler(BaseHTTPRequestHandler):
    def send_json(self, status, data):
        body = json.dumps(data, ensure_ascii=False).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if self.path == "/api/chat":
            return self.send_json(200, {"model": settings.MODEL,
                                       "mode": "DEMO_MODE" if settings.DEMO_MODE else "API"})
        if self.path not in FILES:
            return self.send_json(404, {"error": "경로를 찾을 수 없습니다."})
        name, content_type = FILES[self.path]
        body = (FRONTEND / name).read_bytes()
        self.send_response(200)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_POST(self):
        if self.path != "/api/chat":
            return self.send_json(404, {"error": "경로를 찾을 수 없습니다."})
        try:
            length = int(self.headers.get("Content-Length", "0"))
            if not 0 < length <= 65536:
                self.close_connection = True
                return self.send_json(413, {"error": "본문은 64KB 이하여야 합니다."})
            data = json.loads(self.rfile.read(length))
            question = data.get("question") if isinstance(data, dict) else None
            if not isinstance(question, str) or not question.strip() or len(question) > 500:
                return self.send_json(400, {"error": "질문은 1~500자의 문자열이어야 합니다."})
        except (ValueError, UnicodeError):
            return self.send_json(400, {"error": "요청 JSON을 확인하세요."})
        try:
            result = reply(question.strip(), data.get("history", []))
        except HistoryError as error:
            return self.send_json(400, {"error": str(error)})
        except SchemaError as error:
            print(str(error), flush=True)
            return self.send_json(502, {"error": "답변 형식을 처리하지 못했습니다. 다시 시도해 주세요."})
        except model_client.ModelError as error:
            print(str(error), flush=True)
            return self.send_json(502, {"error": str(error)})
        self.send_json(200, result)


if __name__ == "__main__":
    server = ThreadingHTTPServer(("127.0.0.1", 8765), Handler)
    print("모아상점: http://127.0.0.1:8765", flush=True)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.server_close()

settings.py

별도 보기파일 다운로드
코드 펼치기
import os

BASE_URL = os.getenv("LLM_BASE_URL", "https://api.openai.com/v1").rstrip("/")
API_KEY = os.getenv("LLM_API_KEY", "")
MODEL = os.getenv("LLM_MODEL", "gpt-6-luna")
DEMO_MODE = os.getenv("DEMO_MODE", "0") == "1"
TIMEOUT = 30
MAX_TOKENS = 512
SYSTEM = "당신은 모아상점 고객지원 담당입니다. 한국어로 간결하게 답하세요."

vector_search.py

별도 보기파일 다운로드
코드 펼치기
"""저장된 임베딩에서 코사인 유사도로 후보를 반환한다."""
import hashlib
import json
import math


def content_hash(value):
    data = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(data.encode("utf-8")).hexdigest()


def embedding_text(row):
    return row["text"]


def metadata(chunks, config, chunk_profile):
    versions = sorted({(row["document_id"], row["revision"]) for row in chunks})
    return {"schema_version": 1, "model": config["model"],
            "dimensions": config["dimensions"], "base_url": config["base_url"],
            "chunks_sha256": content_hash(chunks), "document_revisions": versions,
            "chunk_profile": chunk_profile, "input_format": "text_with_title_and_heading"}


def validate_index(index, chunks, config, chunk_profile):
    expected = metadata(chunks, config, chunk_profile)
    actual = index.get("metadata", {})
    changed = [key for key in expected if content_hash(actual.get(key)) != content_hash(expected[key])]
    if changed:
        raise ValueError("인덱스 재생성 필요: " + ", ".join(changed))
    rows = index.get("rows", [])
    if len(rows) != len(chunks) or [row.get("chunk_id") for row in rows] != [row["chunk_id"] for row in chunks]:
        raise ValueError("인덱스 재생성 필요: chunk_id")
    for row in rows:
        vector = row.get("embedding", [])
        if len(vector) != config["dimensions"] or any(
            isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x)
            for x in vector
        ):
            raise ValueError("인덱스 재생성 필요: embedding")


def cosine(left, right):
    if len(left) != len(right) or not left:
        raise ValueError("두 벡터의 차원이 같아야 합니다.")
    denominator = math.sqrt(sum(x*x for x in left) * sum(x*x for x in right))
    if denominator == 0:
        raise ValueError("영벡터의 코사인 유사도를 계산할 수 없습니다.")
    return sum(a*b for a, b in zip(left, right)) / denominator


def vector_search(query_vector, index, chunks, top_k=3):
    if not isinstance(top_k, int) or not 1 <= top_k <= 20:
        raise ValueError("top_k는 1~20의 정수입니다.")
    allowed = {row["chunk_id"]: row for row in chunks}
    candidates = []
    for row in index["rows"]:
        if row["chunk_id"] in allowed:
            chunk = allowed[row["chunk_id"]]
            candidates.append({"chunk_id": row["chunk_id"], "document_id": chunk["document_id"],
                               "score": cosine(query_vector, row["embedding"]), "method": "vector"})
    candidates.sort(key=lambda row: (-row["score"], row["chunk_id"]))
    return [dict(row, rank=rank) for rank, row in enumerate(candidates[:top_k], 1)]

데이터 파일

데이터 전체 ZIP

추가 안내

request_options.py

파일 다운로드 · 별도 보기

"""모델별 Chat Completions 요청 옵션.

GPT-6 Luna는 max_completion_tokens와 reasoning_effort="none"을 사용한다.
다른 모델에는 기존 max_tokens와 temperature를 보낸다.
공식 사양: https://developers.openai.com/api/docs/models/gpt-6-luna
"""


def chat_options(model, max_tokens, temperature=0.2):
    """양의 정수 출력 한도만 받는다. 작업별 기존 32~2048 검증은 호출자 소관."""
    if type(max_tokens) is not int or max_tokens <= 0:
        raise ValueError("출력 토큰 한도는 양의 정수여야 합니다.")
    if model == "gpt-6-luna":
        return {"max_completion_tokens": max_tokens, "reasoning_effort": "none"}
    return {"temperature": temperature, "max_tokens": max_tokens}