MOA / LLM SERVICE / CHAPTER 01
1장 · 첫 번째 고객지원 봇과 모델 호출
코드 전문은 이 페이지에서 복사하거나 파일로 내려받을 수 있습니다. 복사 권한이 없으면 선택된 코드에 Ctrl+C 또는 ⌘C를 사용합니다.
완성 소스 8개
코드 펼치기
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))
코드 펼치기
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");
function addMessage(role, text, usage = 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 (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 }) });
const result = await response.json();
if (!response.ok) throw new Error(result.error || `HTTP ${response.status}`);
addMessage("모아상점", result.answer, result.usage);
status.textContent = "전송 완료";
} catch (error) { status.textContent = error.message; }
finally { button.disabled = false; input.focus(); }
});
코드 펼치기
<!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 01 · FIRST CONVERSATION</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>
코드 펼치기
: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}}
코드 펼치기
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
코드 펼치기
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import model_client
import settings
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")}
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 <= 16384:
self.close_connection = True
return self.send_json(413, {"error": "본문은 16KB 이하여야 합니다."})
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을 확인하세요."})
messages = [{"role": "system", "content": settings.SYSTEM},
{"role": "user", "content": question.strip()}]
try:
self.send_json(200, model_client.generate(messages))
except model_client.ModelError as error:
print(str(error), flush=True)
self.send_json(502, {"error": str(error)})
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()
코드 펼치기
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 = "당신은 모아상점 고객지원 담당입니다. 한국어로 간결하게 답하세요."
추가 안내
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}