docuflow / app /main.py
woongmin's picture
[Delta-02] Drill C retry/backoff ๋˜๋Š” graceful fallback ๋™์ž‘ ํ™•์ธ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ ์ œ๊ฑฐ ver.2
7ed0ad9
Raw History Blame Contribute Delete
15.5 kB
from fastapi import FastAPI, UploadFile, File, HTTPException, Body
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi import Request
import os
from uuid import uuid4
from typing import Dict, List
# ํ•„์š”ํ•œ ๋ชจ๋“ˆ ์ž„ํฌํŠธ (์—ฌ๋Ÿฌ๋ถ„์ด ๊ตฌํ˜„ํ•œ ๋ชจ๋“ˆ)
from .embedding_utils import split_text, get_embedding, rerank
from .supabase_utils import (
save_embedding,
save_embeddings_batch,
search_similar_embeddings,
search_by_keyword,
get_document_id_by_hash,
)
from .config import (
UPLOAD_DIR,
ALLOWED_EXTENSIONS,
OPENAI_API_KEY,
OPENAI_CHAT_MODEL,
EMBED_WORKERS,
)
import pdfplumber
from openai import (
OpenAI,
RateLimitError,
AuthenticationError,
APITimeoutError,
APIConnectionError,
)
from tenacity import retry, wait_exponential, stop_after_attempt, retry_if_exception
import hashlib
import time
from concurrent.futures import ThreadPoolExecutor
app = FastAPI(title="DocuFlow AI Agent")
client = OpenAI(api_key=OPENAI_API_KEY)
@app.get("/health")
async def health_check():
"""ํ—ฌ์Šค์ฒดํฌ ์—”๋“œํฌ์ธํŠธ - ๋ฐฐํฌ ์ƒํƒœ ํ™•์ธ์šฉ"""
return {"status": "healthy"}
def _is_transient_error(e: Exception) -> bool:
"""ํƒ€์ž„์•„์›ƒยท์—ฐ๊ฒฐ ์˜ค๋ฅ˜ยทrate limit(quota ๋ถ€์กฑ ์ œ์™ธ)์„ ์žฌ์‹œ๋„ ๋Œ€์ƒ์œผ๋กœ ํŒ๋‹จ"""
if isinstance(e, (APITimeoutError, APIConnectionError)):
return True
if isinstance(e, RateLimitError):
return e.code != "insufficient_quota"
return False
@retry(
retry=retry_if_exception(_is_transient_error),
wait=wait_exponential(multiplier=1, min=2, max=30),
stop=stop_after_attempt(3),
)
def _call_llm(messages: list, model: str) -> str:
response = client.chat.completions.create(model=model, messages=messages)
return response.choices[0].message.content
# ํ…œํ”Œ๋ฆฟ ๋ฐ ์ •์  ํŒŒ์ผ ์„ค์ •
templates = Jinja2Templates(directory="app/templates")
app.mount("/static", StaticFiles(directory="app/static"), name="static")
def allowed_file(filename: str) -> bool:
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
def _table_to_markdown(table: list[list]) -> str:
"""pdfplumber ํ…Œ์ด๋ธ”(๋ฆฌ์ŠคํŠธ์˜ ๋ฆฌ์ŠคํŠธ)์„ ๋งˆํฌ๋‹ค์šด ํ…Œ์ด๋ธ” ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค."""
if not table:
return ""
# None โ†’ ๋นˆ ๋ฌธ์ž์—ด, ์…€ ๋‚ด ์ค„๋ฐ”๊ฟˆ โ†’ ๊ณต๋ฐฑ
cleaned = []
for row in table:
cleaned.append([(cell or "").replace("\n", " ").strip() for cell in row])
# ๋ชจ๋“  ์…€์ด ๋น„์–ด์žˆ์œผ๋ฉด ๋นˆ ๋ฌธ์ž์—ด ๋ฐ˜ํ™˜
if all(cell == "" for row in cleaned for cell in row):
return ""
header = cleaned[0]
col_count = len(header)
lines = [
"| " + " | ".join(header) + " |",
"| " + " | ".join(["---"] * col_count) + " |",
]
for row in cleaned[1:]:
# ์—ด ์ˆ˜๊ฐ€ ๋งž์ง€ ์•Š์œผ๋ฉด ํŒจ๋”ฉ
padded = (
row + [""] * (col_count - len(row))
if len(row) < col_count
else row[:col_count]
)
lines.append("| " + " | ".join(padded) + " |")
return "\n".join(lines)
def extract_text_from_pdf(file_path: str) -> str:
"""
PDF ํŒŒ์ผ์—์„œ ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜.
ํ‘œ(table)๊ฐ€ ์žˆ๋Š” ํŽ˜์ด์ง€๋Š” ๋งˆํฌ๋‹ค์šด ํ…Œ์ด๋ธ”๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ๊ตฌ์กฐ๋ฅผ ๋ณด์กดํ•œ๋‹ค.
"""
all_pages_text = []
with pdfplumber.open(file_path) as pdf:
for page in pdf.pages:
tables = page.find_tables()
print(f"[DEBUG] page {page.page_number}: {len(tables)} tables found")
# ํ…Œ์ด๋ธ”์ด ์—†์œผ๋ฉด ๊ธฐ์กด ๋น ๋ฅธ ๊ฒฝ๋กœ
if not tables:
page_text = page.extract_text()
if page_text:
all_pages_text.append(f"[p.{page.page_number}] {page_text}")
continue
# ํ…Œ์ด๋ธ”์ด ์žˆ๋Š” ํŽ˜์ด์ง€: ํ…Œ์ด๋ธ”๊ณผ ๋น„-ํ…Œ์ด๋ธ” ์˜์—ญ์„ ๋ถ„๋ฆฌํ•˜์—ฌ ์ถ”์ถœ
segments = [] # (y์ขŒํ‘œ, ํ…์ŠคํŠธ) ํŠœํ”Œ ๋ฆฌ์ŠคํŠธ
# ํ…Œ์ด๋ธ” bbox ์ˆ˜์ง‘
table_bboxes = []
for table in tables:
bbox = table.bbox # (x0, top, x1, bottom)
table_bboxes.append(bbox)
md = _table_to_markdown(table.extract())
if md:
segments.append((bbox[1], md)) # top y์ขŒํ‘œ ๊ธฐ์ค€
# ๋น„-ํ…Œ์ด๋ธ” ์˜์—ญ ํ…์ŠคํŠธ ์ถ”์ถœ
# ํŽ˜์ด์ง€๋ฅผ ํ…Œ์ด๋ธ” ์˜์—ญ ๊ธฐ์ค€์œผ๋กœ cropํ•˜์—ฌ ๋‚˜๋จธ์ง€ ํ…์ŠคํŠธ ์ถ”์ถœ
page_height = page.height
page_width = page.width
# ํ…Œ์ด๋ธ” ์˜์—ญ์„ y์ขŒํ‘œ ์ˆœ์œผ๋กœ ์ •๋ ฌ
sorted_bboxes = sorted(table_bboxes, key=lambda b: b[1])
# ๋น„-ํ…Œ์ด๋ธ” ์˜์—ญ ๊ตฌ๊ฐ„ ๊ณ„์‚ฐ
non_table_regions = []
current_top = 0
for bbox in sorted_bboxes:
if bbox[1] > current_top:
non_table_regions.append((0, current_top, page_width, bbox[1]))
current_top = max(current_top, bbox[3])
if current_top < page_height:
non_table_regions.append((0, current_top, page_width, page_height))
for region in non_table_regions:
try:
cropped = page.crop(region)
region_text = cropped.extract_text()
if region_text:
segments.append((region[1], region_text))
except Exception:
pass
# y์ขŒํ‘œ ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜์—ฌ ์ฝ๊ธฐ ์ˆœ์„œ ์œ ์ง€
segments.sort(key=lambda s: s[0])
page_text = "\n".join(seg[1] for seg in segments)
if page_text:
all_pages_text.append(f"[p.{page.page_number}] {page_text}")
return "\n".join(all_pages_text)
@app.get("/", response_class=HTMLResponse)
async def root_page(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.post("/documents/")
async def upload_document(file: UploadFile = File(...)):
"""
๋ฌธ์„œ ์—…๋กœ๋“œ ๋ฐ ์ž„๋ฒ ๋”ฉ ์ฒ˜๋ฆฌ ์—”๋“œํฌ์ธํŠธ
ํ”„๋กœ์„ธ์Šค:
1. ์—…๋กœ๋“œ๋œ ํŒŒ์ผ์„ ๋กœ์ปฌ(UPLOAD_DIR)์— ์ €์žฅ
2. PDF์—์„œ ํ…์ŠคํŠธ ์ถ”์ถœ
3. ํ…์ŠคํŠธ๋ฅผ ์ฒญํฌ๋กœ ๋ถ„ํ• 
4. ๊ฐ ์ฒญํฌ๋ฅผ ์ž„๋ฒ ๋”ฉํ•˜๊ณ  DB์— ์ €์žฅ
"""
document_id = str(uuid4())
if not allowed_file(file.filename):
raise HTTPException(status_code=400, detail="ํ—ˆ์šฉ๋˜์ง€ ์•Š๋Š” ํŒŒ์ผ ํ˜•์‹์ž…๋‹ˆ๋‹ค.")
try:
content = await file.read()
file_hash = hashlib.sha256(content).hexdigest()
existing_id = get_document_id_by_hash(file_hash)
if existing_id:
return {
"message": "์ด๋ฏธ ๋™์ผํ•œ ๋ฌธ์„œ๊ฐ€ ์—…๋กœ๋“œ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.",
"document_id": existing_id,
}
# 1. ํŒŒ์ผ ์ €์žฅ
file_path = os.path.join(UPLOAD_DIR, f"{document_id}_{file.filename}")
with open(file_path, "wb") as f:
f.write(content)
# 2. ํ…์ŠคํŠธ ์ถ”์ถœ
t0 = time.perf_counter()
text = extract_text_from_pdf(file_path)
t1 = time.perf_counter()
# 3. ์ฒญํฌ ๋ถ„ํ• 
chunks = split_text(text)
t2 = time.perf_counter()
# 4. ์ž„๋ฒ ๋”ฉ ๋ฐ ์ €์žฅ
def _embed_chunk(chunk: str):
return get_embedding(chunk)
with ThreadPoolExecutor(max_workers=EMBED_WORKERS) as executor:
embeddings = list(executor.map(_embed_chunk, chunks))
save_embeddings_batch(document_id, chunks, embeddings, file_hash=file_hash)
t3 = time.perf_counter()
return {
"message": "๋ฌธ์„œ ์ฒ˜๋ฆฌ๊ฐ€ ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.",
"document_id": document_id,
"chunks_count": len(chunks),
"timing": {
"extract_text_sec": round(t1 - t0, 2),
"split_text_sec": round(t2 - t1, 2),
"embed_and_save_sec": round(t3 - t2, 2),
"total_sec": round(t3 - t0, 2),
},
}
except AuthenticationError:
print("์˜ค๋ฅ˜ ๋ฐœ์ƒ: OpenAI API ํ‚ค๊ฐ€ ์œ ํšจํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.")
raise HTTPException(
status_code=500,
detail="์„œ๋ฒ„ ์„ค์ • ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ด€๋ฆฌ์ž์—๊ฒŒ ๋ฌธ์˜ํ•ด์ฃผ์„ธ์š”.",
)
except APITimeoutError:
print("์˜ค๋ฅ˜ ๋ฐœ์ƒ: OpenAI API ์š”์ฒญ ์‹œ๊ฐ„ ์ดˆ๊ณผ")
raise HTTPException(
status_code=504,
detail="์š”์ฒญ ์ฒ˜๋ฆฌ ์‹œ๊ฐ„์ด ์ดˆ๊ณผ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ž ์‹œ ํ›„ ๋‹ค์‹œ ์‹œ๋„ํ•ด์ฃผ์„ธ์š”.",
)
except Exception as e:
print(f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
finally:
pass
@app.post("/qa")
async def question_answering(question: Dict[str, str] = Body(...)):
"""
RAG ๊ธฐ๋ฐ˜ ์งˆ์˜์‘๋‹ต ์—”๋“œํฌ์ธํŠธ
ํ”„๋กœ์„ธ์Šค:
1. ์ฟผ๋ฆฌ ๋ฆฌ๋ผ์ดํŒ…
2. ์งˆ๋ฌธ ์ž„๋ฒ ๋”ฉ
3. ํ•˜์ด๋ธŒ๋ฆฌ๋“œ ๊ฒ€์ƒ‰ (๋ฒกํ„ฐ + ํ‚ค์›Œ๋“œ)
4. ๋ฆฌ๋žญํ‚น
5. LLM ์‘๋‹ต ์ƒ์„ฑ
"""
try:
if "document_id" not in question:
raise HTTPException(status_code=400, detail="document_id is required")
user_question = question["query"]
document_id = question["document_id"]
# 1. ์ฟผ๋ฆฌ ๋ฆฌ๋ผ์ดํŒ…: LLM์œผ๋กœ ๊ฒ€์ƒ‰ ์ตœ์ ํ™” ์ฟผ๋ฆฌ ์ƒ์„ฑ
rewrite_prompt = (
"๋‹น์‹ ์€ ๋ฌธ์„œ ๊ฒ€์ƒ‰ ์ฟผ๋ฆฌ ์ตœ์ ํ™” ์ „๋ฌธ๊ฐ€์ž…๋‹ˆ๋‹ค.\n"
"๋‹ค์Œ ์‚ฌ์šฉ์ž ์งˆ๋ฌธ์„ ๋ฌธ์„œ ๊ฒ€์ƒ‰์— ์ ํ•ฉํ•œ ํ˜•ํƒœ๋กœ ๋ณ€ํ™˜ํ•˜์„ธ์š”.\n\n"
"๊ทœ์น™:\n"
"1. ํ•ต์‹ฌ ๋ช…์‚ฌ์™€ ๊ณ ์œ ๋ช…์‚ฌ๋ฅผ ๋ณด์กดํ•˜์„ธ์š”\n"
"2. ํ•œ๊ตญ์–ด ์กฐ์‚ฌ(์€/๋Š”/์ด/๊ฐ€/์„/๋ฅผ/์˜)๋ฅผ ์ œ๊ฑฐํ•˜์„ธ์š”\n"
"3. ๊ฒ€์ƒ‰์— ๋ถˆํ•„์š”ํ•œ ํ‘œํ˜„(์•Œ๋ ค์ฃผ์„ธ์š”, ๋ฌด์—‡์ธ๊ฐ€์š” ๋“ฑ)์„ ์ œ๊ฑฐํ•˜์„ธ์š”\n"
"4. ๋™์˜์–ด๋‚˜ ๊ด€๋ จ ์šฉ์–ด๊ฐ€ ์žˆ๋‹ค๋ฉด ์ถ”๊ฐ€ํ•˜์„ธ์š”\n"
"5. ๋ณ€ํ™˜๋œ ํ‚ค์›Œ๋“œ/๊ตฌ๋ฌธ๋งŒ ์ถœ๋ ฅํ•˜์„ธ์š” (์„ค๋ช… ์—†์ด)\n\n"
f"์งˆ๋ฌธ: {user_question}"
)
rewritten_query = _call_llm(
messages=[{"role": "user", "content": rewrite_prompt}],
model=OPENAI_CHAT_MODEL,
).strip()
print(f"\n{'='*60}")
print(f" [QA] ์›๋ณธ ์งˆ๋ฌธ: {user_question}")
print(f" [QA] ๋ฆฌ๋ผ์ดํŒ…: {rewritten_query}")
print(f"{'='*60}")
# 2. ์งˆ๋ฌธ ์ž„๋ฒ ๋”ฉ (๋ฆฌ๋ผ์ดํŒ…๋œ ์ฟผ๋ฆฌ ์‚ฌ์šฉ)
question_embedding = get_embedding(rewritten_query)
# 3. ํ•˜์ด๋ธŒ๋ฆฌ๋“œ ๊ฒ€์ƒ‰: ๋ฒกํ„ฐ ๊ฒ€์ƒ‰ + ํ‚ค์›Œ๋“œ ๊ฒ€์ƒ‰
vector_chunks = search_similar_embeddings(question_embedding, document_id)
keyword_chunks = search_by_keyword(user_question, document_id)
# ์ค‘๋ณต ์ œ๊ฑฐ ํ›„ ํ•ฉ์นจ
seen_contents = set()
all_chunks_content = []
for chunk in vector_chunks:
content = chunk["content"]
if content not in seen_contents:
seen_contents.add(content)
all_chunks_content.append(content)
for chunk in keyword_chunks:
content = chunk["content"]
if content not in seen_contents:
seen_contents.add(content)
all_chunks_content.append(content)
print(f"\n ํ•˜์ด๋ธŒ๋ฆฌ๋“œ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ:")
print(f" ๋ฒกํ„ฐ ๊ฒ€์ƒ‰: {len(vector_chunks)}๊ฑด")
print(f" ํ‚ค์›Œ๋“œ ๊ฒ€์ƒ‰: {len(keyword_chunks)}๊ฑด")
print(f" ์ค‘๋ณต ์ œ๊ฑฐ ํ›„: {len(all_chunks_content)}๊ฑด")
# 4. ๋นˆ ๊ฒฐ๊ณผ ๋ฐฉ์–ด: ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๊ฐ€ ์—†์œผ๋ฉด ์ฆ‰์‹œ ๋ฐ˜ํ™˜
if not all_chunks_content:
print(f" โš  ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ์—†์Œ โ†’ ๋นˆ ์‘๋‹ต ๋ฐ˜ํ™˜")
return {"answer": "๋ฌธ์„œ์—์„œ ํ•ด๋‹น ์ •๋ณด๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.", "sources": []}
# 5. ๋ฆฌ๋žญํ‚น: Cross-encoder๋กœ ์ƒ์œ„ 5๊ฐœ ์„ ๋ณ„
reranked_chunks = rerank(user_question, all_chunks_content, top_k=5)
print(f"\n ๋ฆฌ๋žญํ‚น ํ›„ ์ตœ์ข… {len(reranked_chunks)}๊ฑด ์„ ๋ณ„:")
for i, chunk in enumerate(reranked_chunks, 1):
preview = chunk[:60].replace("\n", " ")
print(f" [{i}] {preview}...")
print(f"{'='*60}\n")
# 6. ํ”„๋กฌํ”„ํŠธ ๊ตฌ์„ฑ
context = "\n\n".join(
f"[์ฐธ๊ณ ์ž๋ฃŒ {i}]\n{chunk}" for i, chunk in enumerate(reranked_chunks, 1)
)
system_prompt = (
"[์—ญํ• ]\n"
"- ๋„ˆ๋Š” ์—…๋กœ๋“œ๋œ ๋ฌธ์„œ๋ฅผ ๊ทผ๊ฑฐ๋กœ๋งŒ ๋‹ต๋ณ€ํ•˜๋Š” RAG ์–ด์‹œ์Šคํ„ดํŠธ๋‹ค.\n"
"[ํ–‰๋™ ์›์น™]\n"
"- ์ œ๊ณต๋œ ์ฐธ๊ณ  ๋ฌธ์„œ์— ๊ทผ๊ฑฐ๊ฐ€ ์žˆ๋Š” ๋‚ด์šฉ๋งŒ ๋‹ต๋ณ€ํ•œ๋‹ค.\n"
"- ์ฐธ๊ณ  ๋ฌธ์„œ์— ์—†๋Š” ์‚ฌ์‹ค์€ ์ถ”์ •ํ•˜์ง€ ์•Š๋Š”๋‹ค.\n"
"- ์งˆ๋ฌธ์ด ๋ชจํ˜ธํ•˜๋ฉด ํ•„์š”ํ•œ ์ •๋ณด๋ฅผ ๋จผ์ € ๋ฌผ์–ด๋ณธ๋‹ค.\n"
"- ๋ฌธ์„œ ์™ธ ์งˆ๋ฌธ์ด๋ฉด '๋ฌธ์„œ์—์„œ ํ™•์ธํ•  ์ˆ˜ ์—†๋‹ค'๋ผ๊ณ  ๋ช…์‹œํ•œ๋‹ค.\n"
"[๊ธˆ์ง€ ์‚ฌํ•ญ]\n"
"- ์ฐธ๊ณ  ๋ฌธ์„œ์— ์—†๋Š” ์ •๋ณด๋ฅผ ์ถ”์ •, ์ถ”๋ก , ์ง€์–ด๋‚ด์ง€ ์•Š๋Š”๋‹ค.\n"
"- ํ™•์‹ ์ด ์—†์œผ๋ฉด 'ํ™•์ธํ•  ์ˆ˜ ์—†๋‹ค'๋ผ๊ณ ๋งŒ ๋‹ตํ•œ๋‹ค.\n"
"[๋‹ต๋ณ€ ์ „ ๊ฒ€์ฆ]\n"
"- ๋‹ต๋ณ€์˜ ๊ฐ ๋ฌธ์žฅ์ด ์ฐธ๊ณ  ๋ฌธ์„œ์— ๊ทผ๊ฑฐ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•œ๋‹ค.\n"
"- ๊ทผ๊ฑฐ๊ฐ€ ์—†๋Š” ๋ฌธ์žฅ์€ ์‚ญ์ œํ•˜๊ฑฐ๋‚˜ '๋ฌธ์„œ์— ๋ช…์‹œ๋˜์ง€ ์•Š์Œ'์œผ๋กœ ํ‘œ์‹œํ•œ๋‹ค.\n"
"[๋ถˆํ™•์‹ค์„ฑ ์ฒ˜๋ฆฌ]\n"
"- ์ฐธ๊ณ  ๋ฌธ์„œ์— ๋ถ€๋ถ„์ ์œผ๋กœ๋งŒ ์–ธ๊ธ‰๋œ ๋‚ด์šฉ์€ '์ œํ•œ์ ์œผ๋กœ ํ™•์ธ๋จ' ๋“ฑ์œผ๋กœ ํ‘œํ˜„ํ•œ๋‹ค.\n"
"- ๊ด€๋ จ ๋‚ด์šฉ์ด ์ „ํ˜€ ์—†์œผ๋ฉด ์ถ”์ธกํ•˜์ง€ ์•Š๊ณ  'ํ•ด๋‹น ์ •๋ณด๋Š” ๋ฌธ์„œ์— ์—†์Šต๋‹ˆ๋‹ค'๋ผ๊ณ ๋งŒ ๋‹ตํ•œ๋‹ค.\n"
"[๊ทผ๊ฑฐ ์ œ์‹œ]\n"
"- ๊ทผ๊ฑฐ ์ œ์‹œ ์‹œ ํŽ˜์ด์ง€ ๋ฒˆํ˜ธ([p.N])๊ฐ€ ์žˆ์œผ๋ฉด ํฌํ•จํ•˜์„ธ์š”.\n"
"[์‘๋‹ต ํ˜•์‹]\n"
"- ๋‹ต๋ณ€:\n"
"- ๊ทผ๊ฑฐ:\n"
"- ํ•œ๊ณ„/์ถ”๊ฐ€ ํ™•์ธ ํ•„์š”์‚ฌํ•ญ:"
)
# 7. LLM ์‘๋‹ต ์ƒ์„ฑ
messages = [
{"role": "system", "content": f"{system_prompt}\n\n[์ฐธ๊ณ  ๋ฌธ์„œ]\n{context}"},
{"role": "user", "content": user_question},
]
answer = _call_llm(messages=messages, model=OPENAI_CHAT_MODEL)
return {
"answer": answer,
"sources": reranked_chunks,
}
except AuthenticationError:
print("์˜ค๋ฅ˜ ๋ฐœ์ƒ: OpenAI API ํ‚ค๊ฐ€ ์œ ํšจํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.")
raise HTTPException(
status_code=500,
detail="์„œ๋ฒ„ ์„ค์ • ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ด€๋ฆฌ์ž์—๊ฒŒ ๋ฌธ์˜ํ•ด์ฃผ์„ธ์š”.",
)
except APITimeoutError:
print("์˜ค๋ฅ˜ ๋ฐœ์ƒ: OpenAI API ์š”์ฒญ ์‹œ๊ฐ„ ์ดˆ๊ณผ")
raise HTTPException(
status_code=504,
detail="์š”์ฒญ ์ฒ˜๋ฆฌ ์‹œ๊ฐ„์ด ์ดˆ๊ณผ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ž ์‹œ ํ›„ ๋‹ค์‹œ ์‹œ๋„ํ•ด์ฃผ์„ธ์š”.",
)
except RateLimitError as e:
if e.code == "insufficient_quota":
raise HTTPException(
status_code=402,
detail="OpenAI API ํฌ๋ ˆ๋”ง์ด ๋ถ€์กฑํ•ฉ๋‹ˆ๋‹ค. ํ”Œ๋žœ์„ ํ™•์ธํ•ด์ฃผ์„ธ์š”.",
)
raise HTTPException(
status_code=429,
detail="OpenAI API ์š”์ฒญ ํ•œ๋„๋ฅผ ์ดˆ๊ณผํ–ˆ์Šต๋‹ˆ๋‹ค. ์ž ์‹œ ํ›„ ๋‹ค์‹œ ์‹œ๋„ํ•ด์ฃผ์„ธ์š”.",
)
except Exception as e:
print(f"์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))