File size: 15,455 Bytes
1e570c8
 
 
 
 
 
 
 
 
 
afc8097
0bbd198
 
1990560
0bbd198
afc8097
0bbd198
 
1c747b0
 
 
0c6fd3a
 
1c747b0
 
1e570c8
74b444e
37c1245
 
 
 
 
 
 
7ed0ad9
0bbd198
1990560
 
74b444e
1e570c8
 
7ed0ad9
0c6fd3a
2c18c5e
f5c1673
 
 
 
 
 
37c1245
 
 
 
2c18c5e
 
 
 
 
 
37c1245
2c18c5e
37c1245
2c18c5e
 
 
 
 
 
1e570c8
 
 
 
 
 
 
 
 
afc8097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e570c8
 
afc8097
 
1e570c8
afc8097
 
74b444e
 
afc8097
8fd1042
afc8097
 
 
 
 
f537bfd
afc8097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74b444e
f537bfd
afc8097
 
1e570c8
 
 
 
 
 
 
 
 
 
0c6fd3a
1e570c8
 
 
 
 
 
 
 
 
74b444e
 
 
1e570c8
0bbd198
 
 
 
 
 
 
 
 
74b444e
 
 
 
 
 
1990560
74b444e
1990560
74b444e
aea0bb5
 
1990560
aea0bb5
 
1990560
 
 
1c747b0
1990560
 
 
aea0bb5
1e570c8
 
 
aea0bb5
1990560
 
 
 
 
 
1e570c8
 
bdbc970
 
 
 
 
 
37c1245
 
 
 
 
 
1e570c8
 
 
 
 
 
 
 
 
 
0c6fd3a
1e570c8
 
0c6fd3a
 
 
 
 
1e570c8
 
 
 
 
 
 
 
afc8097
 
f537bfd
 
 
 
 
 
 
 
 
afc8097
2c18c5e
0c6fd3a
2c18c5e
 
79a0126
 
 
 
afc8097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79a0126
 
 
 
2c0a524
afc8097
 
79a0126
afc8097
2c0a524
afc8097
 
79a0126
 
 
 
 
afc8097
 
f537bfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c0a524
afc8097
2c0a524
f537bfd
 
2c0a524
 
2c18c5e
1e570c8
74b444e
2c0a524
afc8097
74b444e
1e570c8
bdbc970
 
 
 
 
 
37c1245
 
 
 
 
 
2c18c5e
 
 
 
 
 
 
 
 
 
1e570c8
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
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))