Spaces:
Runtime error
Runtime error
[Delta-02] Ollama에서 OpenAI로 LLM/임베딩 전환
Browse files- .deepeval/.deepeval_telemetry.txt +0 -4
- .deepeval/.temp_test_run_data.json +0 -1
- Pipfile +2 -1
- app/config.py +9 -30
- app/embedding_utils.py +14 -33
- app/main.py +20 -69
- eval_rag.py +82 -80
.deepeval/.deepeval_telemetry.txt
DELETED
|
@@ -1,4 +0,0 @@
|
|
| 1 |
-
DEEPEVAL_ID=13f97a53-31fd-4207-b2b5-d7669bbc5ee6
|
| 2 |
-
DEEPEVAL_STATUS=old
|
| 3 |
-
DEEPEVAL_LAST_FEATURE=evaluation
|
| 4 |
-
DEEPEVAL_EVALUATION_STATUS=old
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.deepeval/.temp_test_run_data.json
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
{"testCases": [], "conversationalTestCases": [], "metricsScores": [], "runDuration": 0.0}
|
|
|
|
|
|
Pipfile
CHANGED
|
@@ -18,7 +18,8 @@ requests = "*"
|
|
| 18 |
nltk = "*"
|
| 19 |
numpy = "*"
|
| 20 |
sentence-transformers = "*"
|
| 21 |
-
|
|
|
|
| 22 |
|
| 23 |
[dev-packages]
|
| 24 |
pre-commit = "*"
|
|
|
|
| 18 |
nltk = "*"
|
| 19 |
numpy = "*"
|
| 20 |
sentence-transformers = "*"
|
| 21 |
+
ragnarok-ai = {extras = ["ollama"], version = "*"}
|
| 22 |
+
openai = "*"
|
| 23 |
|
| 24 |
[dev-packages]
|
| 25 |
pre-commit = "*"
|
app/config.py
CHANGED
|
@@ -3,37 +3,16 @@ from dotenv import load_dotenv
|
|
| 3 |
|
| 4 |
load_dotenv()
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
#
|
| 15 |
-
# OpenAI를 사용하려면 .env에서 PROVIDER=openai로 설정하고 아래 주석을 해제하세요.
|
| 16 |
-
# OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 17 |
-
# OPENAI_EMBEDDING_MODEL = os.getenv("OPENAI_EMBEDDING_MODEL", "text-embedding-3-small")
|
| 18 |
-
# OPENAI_CHAT_MODEL = os.getenv("OPENAI_CHAT_MODEL", "gpt-3.5-turbo")
|
| 19 |
-
|
| 20 |
-
# OpenAI 사용 시 필수 키 검증
|
| 21 |
-
if PROVIDER == "openai":
|
| 22 |
-
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 23 |
-
OPENAI_EMBEDDING_MODEL = os.getenv(
|
| 24 |
-
"OPENAI_EMBEDDING_MODEL", "text-embedding-3-small"
|
| 25 |
-
)
|
| 26 |
-
OPENAI_CHAT_MODEL = os.getenv("OPENAI_CHAT_MODEL", "gpt-3.5-turbo")
|
| 27 |
-
if not OPENAI_API_KEY:
|
| 28 |
-
raise ValueError(
|
| 29 |
-
"PROVIDER=openai로 설정했지만 OPENAI_API_KEY가 설정되지 않았습니다."
|
| 30 |
-
)
|
| 31 |
-
|
| 32 |
-
# 성능 설정 — 머신 사양에 따라 .env에서 조정
|
| 33 |
-
# M1 Pro 32GB: EMBED_WORKERS=5, OLLAMA_TIMEOUT=120 (기본값)
|
| 34 |
-
# M1 Air 16GB: EMBED_WORKERS=2, OLLAMA_TIMEOUT=300
|
| 35 |
EMBED_WORKERS = int(os.getenv("EMBED_WORKERS", "5"))
|
| 36 |
-
OLLAMA_TIMEOUT = int(os.getenv("OLLAMA_TIMEOUT", "120"))
|
| 37 |
|
| 38 |
UPLOAD_DIR = "app/uploads"
|
| 39 |
|
|
|
|
| 3 |
|
| 4 |
load_dotenv()
|
| 5 |
|
| 6 |
+
# OpenAI 설정
|
| 7 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 8 |
+
OPENAI_EMBEDDING_MODEL = os.getenv("OPENAI_EMBEDDING_MODEL", "text-embedding-3-small")
|
| 9 |
+
OPENAI_CHAT_MODEL = os.getenv("OPENAI_CHAT_MODEL", "gpt-4o-mini")
|
| 10 |
+
|
| 11 |
+
if not OPENAI_API_KEY:
|
| 12 |
+
raise ValueError("OPENAI_API_KEY가 설정되지 않았습니다.")
|
| 13 |
+
|
| 14 |
+
# 성능 설정
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
EMBED_WORKERS = int(os.getenv("EMBED_WORKERS", "5"))
|
|
|
|
| 16 |
|
| 17 |
UPLOAD_DIR = "app/uploads"
|
| 18 |
|
app/embedding_utils.py
CHANGED
|
@@ -1,15 +1,16 @@
|
|
| 1 |
from typing import List
|
| 2 |
import nltk
|
| 3 |
import numpy as np
|
| 4 |
-
import
|
| 5 |
from sentence_transformers import CrossEncoder
|
| 6 |
-
from app.config import
|
|
|
|
|
|
|
| 7 |
|
| 8 |
# Cross-encoder 리랭커 (첫 호출 시 모델 다운로드)
|
| 9 |
reranker = CrossEncoder("BAAI/bge-reranker-v2-m3")
|
| 10 |
|
| 11 |
# 문장 수가 이 값을 초과하면 의미 기반 분할 대신 글자 수 기반 분할 사용
|
| 12 |
-
# (대용량 PDF에서 문장당 임베딩 호출 시 Ollama 500 에러 방지)
|
| 13 |
SENTENCE_LIMIT_FOR_SEMANTIC_CHUNKING = 500
|
| 14 |
|
| 15 |
|
|
@@ -39,14 +40,12 @@ def _simple_split_by_chars(
|
|
| 39 |
return chunks
|
| 40 |
|
| 41 |
|
| 42 |
-
def
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
timeout=OLLAMA_TIMEOUT,
|
| 47 |
)
|
| 48 |
-
|
| 49 |
-
return resp.json()["embedding"]
|
| 50 |
|
| 51 |
|
| 52 |
def _cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
|
|
@@ -64,7 +63,7 @@ def _semantic_chunk(
|
|
| 64 |
text = " ".join(sentences).strip()
|
| 65 |
return [text] if text else []
|
| 66 |
|
| 67 |
-
embeddings = [np.array(
|
| 68 |
|
| 69 |
similarities = [
|
| 70 |
_cosine_similarity(embeddings[i], embeddings[i + 1])
|
|
@@ -129,18 +128,10 @@ def split_text(
|
|
| 129 |
긴 텍스트를 의미 기반으로 청크로 분할하는 함수.
|
| 130 |
|
| 131 |
1. nltk 문장 분리
|
| 132 |
-
2.
|
| 133 |
3. 적응적 threshold(평균 - 1σ)로 의미 경계 분할
|
| 134 |
4. chunk_size 적용 (작은 그룹 병합, 큰 그룹 강제 분할)
|
| 135 |
5. chunk_overlap 적용
|
| 136 |
-
|
| 137 |
-
Args:
|
| 138 |
-
text: 분할할 전체 텍스트
|
| 139 |
-
chunk_size: 청크 당 최대 글자 수
|
| 140 |
-
chunk_overlap: 청크 간 중복 글자 수
|
| 141 |
-
|
| 142 |
-
Returns:
|
| 143 |
-
분할된 텍스트 청크 리스트
|
| 144 |
"""
|
| 145 |
sentences = nltk.sent_tokenize(text)
|
| 146 |
if len(sentences) <= 1:
|
|
@@ -170,18 +161,8 @@ def split_text(
|
|
| 170 |
|
| 171 |
def get_embedding(text: str) -> List[float]:
|
| 172 |
"""
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
요구사항:
|
| 176 |
-
1. 로컬에서 실행 중인 Ollama 서버를 통해 임베딩 벡터를 생성하세요.
|
| 177 |
-
- Ollama API 스펙을 직접 조사하세요: https://github.com/ollama/ollama/blob/main/docs/api.md
|
| 178 |
-
- 사용할 모델과 반환 벡터 차원은 README.md의 환경 설정 섹션을 참고하세요.
|
| 179 |
-
2. 반환값은 float 숫자로 구성된 리스트여야 합니다.
|
| 180 |
-
3. Ollama 서버가 응답하지 않는 경우를 적절히 처리하세요.
|
| 181 |
-
|
| 182 |
-
(선택사항) OpenAI 사용:
|
| 183 |
-
- .env에서 PROVIDER=openai로 설정한 경우에만 사용됩니다.
|
| 184 |
-
- OpenAI Embeddings API 스펙을 직접 조사하세요.
|
| 185 |
|
| 186 |
Args:
|
| 187 |
text (str): 임베딩할 텍스트
|
|
@@ -189,7 +170,7 @@ def get_embedding(text: str) -> List[float]:
|
|
| 189 |
Returns:
|
| 190 |
List[float]: 임베딩 벡터
|
| 191 |
"""
|
| 192 |
-
return
|
| 193 |
|
| 194 |
|
| 195 |
def rerank(query: str, chunks: List[str], top_k: int = 5) -> List[str]:
|
|
|
|
| 1 |
from typing import List
|
| 2 |
import nltk
|
| 3 |
import numpy as np
|
| 4 |
+
from openai import OpenAI
|
| 5 |
from sentence_transformers import CrossEncoder
|
| 6 |
+
from app.config import OPENAI_API_KEY, OPENAI_EMBEDDING_MODEL
|
| 7 |
+
|
| 8 |
+
client = OpenAI(api_key=OPENAI_API_KEY)
|
| 9 |
|
| 10 |
# Cross-encoder 리랭커 (첫 호출 시 모델 다운로드)
|
| 11 |
reranker = CrossEncoder("BAAI/bge-reranker-v2-m3")
|
| 12 |
|
| 13 |
# 문장 수가 이 값을 초과하면 의미 기반 분할 대신 글자 수 기반 분할 사용
|
|
|
|
| 14 |
SENTENCE_LIMIT_FOR_SEMANTIC_CHUNKING = 500
|
| 15 |
|
| 16 |
|
|
|
|
| 40 |
return chunks
|
| 41 |
|
| 42 |
|
| 43 |
+
def _openai_embed(text: str) -> List[float]:
|
| 44 |
+
response = client.embeddings.create(
|
| 45 |
+
model=OPENAI_EMBEDDING_MODEL,
|
| 46 |
+
input=text,
|
|
|
|
| 47 |
)
|
| 48 |
+
return response.data[0].embedding
|
|
|
|
| 49 |
|
| 50 |
|
| 51 |
def _cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
|
|
|
|
| 63 |
text = " ".join(sentences).strip()
|
| 64 |
return [text] if text else []
|
| 65 |
|
| 66 |
+
embeddings = [np.array(_openai_embed(s)) for s in sentences]
|
| 67 |
|
| 68 |
similarities = [
|
| 69 |
_cosine_similarity(embeddings[i], embeddings[i + 1])
|
|
|
|
| 128 |
긴 텍스트를 의미 기반으로 청크로 분할하는 함수.
|
| 129 |
|
| 130 |
1. nltk 문장 분리
|
| 131 |
+
2. OpenAI 임베딩으로 인접 문장 유사도 계산
|
| 132 |
3. 적응적 threshold(평균 - 1σ)로 의미 경계 분할
|
| 133 |
4. chunk_size 적용 (작은 그룹 병합, 큰 그룹 강제 분할)
|
| 134 |
5. chunk_overlap 적용
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
"""
|
| 136 |
sentences = nltk.sent_tokenize(text)
|
| 137 |
if len(sentences) <= 1:
|
|
|
|
| 161 |
|
| 162 |
def get_embedding(text: str) -> List[float]:
|
| 163 |
"""
|
| 164 |
+
텍스트의 벡터 임베딩을 생성하는 함수.
|
| 165 |
+
OpenAI Embeddings API를 사용한다.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
Args:
|
| 168 |
text (str): 임베딩할 텍스트
|
|
|
|
| 170 |
Returns:
|
| 171 |
List[float]: 임베딩 벡터
|
| 172 |
"""
|
| 173 |
+
return _openai_embed(text)
|
| 174 |
|
| 175 |
|
| 176 |
def rerank(query: str, chunks: List[str], top_k: int = 5) -> List[str]:
|
app/main.py
CHANGED
|
@@ -19,20 +19,21 @@ from .supabase_utils import (
|
|
| 19 |
from .config import (
|
| 20 |
UPLOAD_DIR,
|
| 21 |
ALLOWED_EXTENSIONS,
|
| 22 |
-
|
| 23 |
-
|
| 24 |
EMBED_WORKERS,
|
| 25 |
-
OLLAMA_TIMEOUT,
|
| 26 |
)
|
| 27 |
|
| 28 |
import pdfplumber
|
| 29 |
-
import
|
| 30 |
import hashlib
|
| 31 |
import time
|
| 32 |
from concurrent.futures import ThreadPoolExecutor
|
| 33 |
|
| 34 |
app = FastAPI(title="DocuFlow AI Agent")
|
| 35 |
|
|
|
|
|
|
|
| 36 |
# 템플릿 및 정적 파일 설정
|
| 37 |
templates = Jinja2Templates(directory="app/templates")
|
| 38 |
app.mount("/static", StaticFiles(directory="app/static"), name="static")
|
|
@@ -149,15 +150,13 @@ async def root_page(request: Request):
|
|
| 149 |
@app.post("/documents/")
|
| 150 |
async def upload_document(file: UploadFile = File(...)):
|
| 151 |
"""
|
| 152 |
-
|
| 153 |
|
| 154 |
프로세스:
|
| 155 |
1. 업로드된 파일을 로컬(UPLOAD_DIR)에 저장
|
| 156 |
2. PDF에서 텍스트 추출
|
| 157 |
3. 텍스트를 청크로 분할
|
| 158 |
4. 각 청크를 임베딩하고 DB에 저장
|
| 159 |
-
5. (Deep Dive) 대량의 청크를 처리할 때 속도 저하를 막기 위한 방법을 조사해보세요.
|
| 160 |
-
힌트: Python의 비동기 처리 방식을 검토해보세요.
|
| 161 |
"""
|
| 162 |
document_id = str(uuid4())
|
| 163 |
|
|
@@ -165,14 +164,6 @@ async def upload_document(file: UploadFile = File(...)):
|
|
| 165 |
raise HTTPException(status_code=400, detail="허용되지 않는 파일 형식입니다.")
|
| 166 |
|
| 167 |
try:
|
| 168 |
-
# ---------------------------------------------------------
|
| 169 |
-
# [Day 1 & 2] 과제: 파이프라인 구현
|
| 170 |
-
# 1. 파일 저장
|
| 171 |
-
# 2. 텍스트 추출
|
| 172 |
-
# 3. 청크 분할
|
| 173 |
-
# 4. 임베딩 및 저장
|
| 174 |
-
# ---------------------------------------------------------
|
| 175 |
-
|
| 176 |
content = await file.read()
|
| 177 |
file_hash = hashlib.sha256(content).hexdigest()
|
| 178 |
existing_id = get_document_id_by_hash(file_hash)
|
|
@@ -221,31 +212,20 @@ async def upload_document(file: UploadFile = File(...)):
|
|
| 221 |
print(f"오류 발생: {str(e)}")
|
| 222 |
raise HTTPException(status_code=500, detail=str(e))
|
| 223 |
finally:
|
| 224 |
-
# 임시 파일 삭제
|
| 225 |
-
# if os.path.exists(file_path):
|
| 226 |
-
# os.remove(file_path)
|
| 227 |
pass
|
| 228 |
|
| 229 |
|
| 230 |
@app.post("/qa")
|
| 231 |
async def question_answering(question: Dict[str, str] = Body(...)):
|
| 232 |
"""
|
| 233 |
-
|
| 234 |
|
| 235 |
프로세스:
|
| 236 |
-
1.
|
| 237 |
-
2.
|
| 238 |
-
3. 검색
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
4. LLM에게 답변 요청
|
| 242 |
-
- 어떤 LLM API를 어떻게 호출해야 하는지 직접 조사하세요.
|
| 243 |
-
- 사용할 API 스펙: README.md의 외부 참고 자료에서 Ollama API 문서를 확인하세요.
|
| 244 |
-
5. (Deep Dive) 이전 대화 내용을 기억하도록 messages 리스트를 관리해보세요.
|
| 245 |
-
REFERENCE.md의 Query Rewriting 섹션을 참고하세요.
|
| 246 |
-
|
| 247 |
-
(선택사항) OpenAI 사용:
|
| 248 |
-
- env에서 PROVIDER=openai로 설정한 경우에만 사용됩니다.
|
| 249 |
"""
|
| 250 |
try:
|
| 251 |
if "document_id" not in question:
|
|
@@ -254,16 +234,6 @@ async def question_answering(question: Dict[str, str] = Body(...)):
|
|
| 254 |
user_question = question["query"]
|
| 255 |
document_id = question["document_id"]
|
| 256 |
|
| 257 |
-
# System Prompt + Context + Question 조합
|
| 258 |
-
|
| 259 |
-
# ---------------------------------------------------------
|
| 260 |
-
# [Day 3] 과제: RAG 로직 구현
|
| 261 |
-
# 1. 질문 임베딩
|
| 262 |
-
# 2. 벡터 검색
|
| 263 |
-
# 3. 프롬프트 구성 (System Prompt + Context + Question)
|
| 264 |
-
# 4. LLM 응답 생성
|
| 265 |
-
# ---------------------------------------------------------
|
| 266 |
-
|
| 267 |
# 1. 쿼리 리라이팅: LLM으로 검색 최적화 쿼리 생성
|
| 268 |
rewrite_prompt = (
|
| 269 |
"당신은 문서 검색 쿼리 최적화 전문가입니다.\n"
|
|
@@ -276,22 +246,11 @@ async def question_answering(question: Dict[str, str] = Body(...)):
|
|
| 276 |
"5. 변환된 키워드/구문만 출력하세요 (설명 없이)\n\n"
|
| 277 |
f"질문: {user_question}"
|
| 278 |
)
|
| 279 |
-
rewrite_response =
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
"model": OLLAMA_CHAT_MODEL,
|
| 283 |
-
"messages": [{"role": "user", "content": rewrite_prompt}],
|
| 284 |
-
"stream": False,
|
| 285 |
-
},
|
| 286 |
-
timeout=OLLAMA_TIMEOUT,
|
| 287 |
-
)
|
| 288 |
-
rewrite_response.raise_for_status()
|
| 289 |
-
rewritten_query = (
|
| 290 |
-
rewrite_response.json()
|
| 291 |
-
.get("message", {})
|
| 292 |
-
.get("content", user_question)
|
| 293 |
-
.strip()
|
| 294 |
)
|
|
|
|
| 295 |
print(f"\n{'='*60}")
|
| 296 |
print(f" [QA] 원본 질문: {user_question}")
|
| 297 |
print(f" [QA] 리라이팅: {rewritten_query}")
|
|
@@ -372,26 +331,18 @@ async def question_answering(question: Dict[str, str] = Body(...)):
|
|
| 372 |
{"role": "user", "content": user_question},
|
| 373 |
]
|
| 374 |
|
| 375 |
-
response =
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
timeout=OLLAMA_TIMEOUT,
|
| 379 |
)
|
| 380 |
|
| 381 |
-
response.
|
| 382 |
-
|
| 383 |
-
data = response.json()
|
| 384 |
-
answer = data.get("message", {}).get("content", "답변을 생성할 수 없습니다.")
|
| 385 |
|
| 386 |
return {
|
| 387 |
"answer": answer,
|
| 388 |
"sources": reranked_chunks,
|
| 389 |
}
|
| 390 |
|
| 391 |
-
except requests.exceptions.ConnectionError:
|
| 392 |
-
raise HTTPException(status_code=503, detail="Ollama 서버에 연결할 수 없습니다.")
|
| 393 |
-
except requests.exceptions.Timeout:
|
| 394 |
-
raise HTTPException(status_code=504, detail="Ollama 서버 응답 시간 초과.")
|
| 395 |
except Exception as e:
|
| 396 |
print(f"오류 발생: {str(e)}")
|
| 397 |
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
| 19 |
from .config import (
|
| 20 |
UPLOAD_DIR,
|
| 21 |
ALLOWED_EXTENSIONS,
|
| 22 |
+
OPENAI_API_KEY,
|
| 23 |
+
OPENAI_CHAT_MODEL,
|
| 24 |
EMBED_WORKERS,
|
|
|
|
| 25 |
)
|
| 26 |
|
| 27 |
import pdfplumber
|
| 28 |
+
from openai import OpenAI
|
| 29 |
import hashlib
|
| 30 |
import time
|
| 31 |
from concurrent.futures import ThreadPoolExecutor
|
| 32 |
|
| 33 |
app = FastAPI(title="DocuFlow AI Agent")
|
| 34 |
|
| 35 |
+
client = OpenAI(api_key=OPENAI_API_KEY)
|
| 36 |
+
|
| 37 |
# 템플릿 및 정적 파일 설정
|
| 38 |
templates = Jinja2Templates(directory="app/templates")
|
| 39 |
app.mount("/static", StaticFiles(directory="app/static"), name="static")
|
|
|
|
| 150 |
@app.post("/documents/")
|
| 151 |
async def upload_document(file: UploadFile = File(...)):
|
| 152 |
"""
|
| 153 |
+
문서 업로드 및 임베딩 처리 엔드포인트
|
| 154 |
|
| 155 |
프로세스:
|
| 156 |
1. 업로드된 파일을 로컬(UPLOAD_DIR)에 저장
|
| 157 |
2. PDF에서 텍스트 추출
|
| 158 |
3. 텍스트를 청크로 분할
|
| 159 |
4. 각 청크를 임베딩하고 DB에 저장
|
|
|
|
|
|
|
| 160 |
"""
|
| 161 |
document_id = str(uuid4())
|
| 162 |
|
|
|
|
| 164 |
raise HTTPException(status_code=400, detail="허용되지 않는 파일 형식입니다.")
|
| 165 |
|
| 166 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
content = await file.read()
|
| 168 |
file_hash = hashlib.sha256(content).hexdigest()
|
| 169 |
existing_id = get_document_id_by_hash(file_hash)
|
|
|
|
| 212 |
print(f"오류 발생: {str(e)}")
|
| 213 |
raise HTTPException(status_code=500, detail=str(e))
|
| 214 |
finally:
|
|
|
|
|
|
|
|
|
|
| 215 |
pass
|
| 216 |
|
| 217 |
|
| 218 |
@app.post("/qa")
|
| 219 |
async def question_answering(question: Dict[str, str] = Body(...)):
|
| 220 |
"""
|
| 221 |
+
RAG 기반 질의응답 엔드포인트
|
| 222 |
|
| 223 |
프로세스:
|
| 224 |
+
1. 쿼리 리라이팅
|
| 225 |
+
2. 질문 임베딩
|
| 226 |
+
3. 하이브리드 검색 (벡터 + 키워드)
|
| 227 |
+
4. 리랭킹
|
| 228 |
+
5. LLM 응답 생성
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
"""
|
| 230 |
try:
|
| 231 |
if "document_id" not in question:
|
|
|
|
| 234 |
user_question = question["query"]
|
| 235 |
document_id = question["document_id"]
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
# 1. 쿼리 리라이팅: LLM으로 검색 최적화 쿼리 생성
|
| 238 |
rewrite_prompt = (
|
| 239 |
"당신은 문서 검색 쿼리 최적화 전문가입니다.\n"
|
|
|
|
| 246 |
"5. 변환된 키워드/구문만 출력하세요 (설명 없이)\n\n"
|
| 247 |
f"질문: {user_question}"
|
| 248 |
)
|
| 249 |
+
rewrite_response = client.chat.completions.create(
|
| 250 |
+
model=OPENAI_CHAT_MODEL,
|
| 251 |
+
messages=[{"role": "user", "content": rewrite_prompt}],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
)
|
| 253 |
+
rewritten_query = rewrite_response.choices[0].message.content.strip()
|
| 254 |
print(f"\n{'='*60}")
|
| 255 |
print(f" [QA] 원본 질문: {user_question}")
|
| 256 |
print(f" [QA] 리라이팅: {rewritten_query}")
|
|
|
|
| 331 |
{"role": "user", "content": user_question},
|
| 332 |
]
|
| 333 |
|
| 334 |
+
response = client.chat.completions.create(
|
| 335 |
+
model=OPENAI_CHAT_MODEL,
|
| 336 |
+
messages=messages,
|
|
|
|
| 337 |
)
|
| 338 |
|
| 339 |
+
answer = response.choices[0].message.content
|
|
|
|
|
|
|
|
|
|
| 340 |
|
| 341 |
return {
|
| 342 |
"answer": answer,
|
| 343 |
"sources": reranked_chunks,
|
| 344 |
}
|
| 345 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
except Exception as e:
|
| 347 |
print(f"오류 발생: {str(e)}")
|
| 348 |
raise HTTPException(status_code=500, detail=str(e))
|
eval_rag.py
CHANGED
|
@@ -1,70 +1,25 @@
|
|
| 1 |
"""
|
| 2 |
-
RAG 파이프라인 평가 스크립트 (
|
| 3 |
|
| 4 |
사용법:
|
| 5 |
1. 서버 실행: pipenv run uvicorn app.main:app --reload
|
| 6 |
2. 평가 실행: pipenv run python eval_rag.py
|
| 7 |
"""
|
| 8 |
|
| 9 |
-
import
|
| 10 |
import requests as http_requests
|
| 11 |
-
from
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
ContextualPrecisionMetric,
|
| 18 |
-
ContextualRecallMetric,
|
| 19 |
)
|
| 20 |
-
from deepeval import evaluate
|
| 21 |
|
| 22 |
# ── 설정 ──────────────────────────────────────────────
|
| 23 |
API_BASE = "http://127.0.0.1:8000"
|
| 24 |
OLLAMA_BASE = "http://localhost:11434"
|
| 25 |
|
| 26 |
-
|
| 27 |
-
# ── Ollama 커스텀 래퍼 (ollama 패키지 불필요) ──────────
|
| 28 |
-
class OllamaLLM(DeepEvalBaseLLM):
|
| 29 |
-
"""requests로 Ollama API를 직접 호출하는 DeepEval 커스텀 모델"""
|
| 30 |
-
|
| 31 |
-
def __init__(self, model="llama3.1", base_url="http://localhost:11434"):
|
| 32 |
-
self._model_name = model
|
| 33 |
-
self.base_url = base_url
|
| 34 |
-
super().__init__(model)
|
| 35 |
-
|
| 36 |
-
def load_model(self):
|
| 37 |
-
return self._model_name
|
| 38 |
-
|
| 39 |
-
def generate(self, prompt: str, schema: BaseModel = None) -> str:
|
| 40 |
-
payload = {
|
| 41 |
-
"model": self._model_name,
|
| 42 |
-
"messages": [{"role": "user", "content": prompt}],
|
| 43 |
-
"stream": False,
|
| 44 |
-
}
|
| 45 |
-
if schema:
|
| 46 |
-
payload["format"] = schema.model_json_schema()
|
| 47 |
-
|
| 48 |
-
resp = http_requests.post(
|
| 49 |
-
f"{self.base_url}/api/chat", json=payload, timeout=120
|
| 50 |
-
)
|
| 51 |
-
resp.raise_for_status()
|
| 52 |
-
content = resp.json()["message"]["content"]
|
| 53 |
-
|
| 54 |
-
if schema:
|
| 55 |
-
return schema(**json.loads(content))
|
| 56 |
-
return content
|
| 57 |
-
|
| 58 |
-
async def a_generate(self, prompt: str, schema: BaseModel = None) -> str:
|
| 59 |
-
return self.generate(prompt, schema)
|
| 60 |
-
|
| 61 |
-
def get_model_name(self):
|
| 62 |
-
return self._model_name
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
# 평가용 모델 초기화
|
| 66 |
-
eval_model = OllamaLLM(model="llama3.1", base_url=OLLAMA_BASE)
|
| 67 |
-
|
| 68 |
# ── 테스트 케이스 정의 ─────────────────────────────────
|
| 69 |
TEST_CASES = [
|
| 70 |
{
|
|
@@ -102,15 +57,18 @@ def get_document_id() -> str:
|
|
| 102 |
return doc_id
|
| 103 |
|
| 104 |
|
| 105 |
-
def main():
|
| 106 |
document_id = get_document_id()
|
| 107 |
|
| 108 |
print(f"\n{'='*60}")
|
| 109 |
print(f" RAG 평가 시작 (총 {len(TEST_CASES)}건)")
|
| 110 |
print(f"{'='*60}\n")
|
| 111 |
|
| 112 |
-
#
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
| 114 |
for i, tc in enumerate(TEST_CASES, 1):
|
| 115 |
question = tc["question"]
|
| 116 |
expected = tc["expected"]
|
|
@@ -120,38 +78,82 @@ def main():
|
|
| 120 |
|
| 121 |
answer = result["answer"]
|
| 122 |
sources = result["sources"]
|
|
|
|
| 123 |
|
| 124 |
print(f" 답변: {answer[:80]}...")
|
| 125 |
-
print(f" 소스: {len(sources)}건
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
| 143 |
|
|
|
|
| 144 |
print(f"{'='*60}")
|
| 145 |
-
print(f"
|
| 146 |
print(f"{'='*60}\n")
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
print(f" 평
|
| 153 |
-
print(f"{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
|
| 156 |
if __name__ == "__main__":
|
| 157 |
-
main()
|
|
|
|
| 1 |
"""
|
| 2 |
+
RAG 파이프라인 평가 스크립트 (RAGnarok-AI + Ollama)
|
| 3 |
|
| 4 |
사용법:
|
| 5 |
1. 서버 실행: pipenv run uvicorn app.main:app --reload
|
| 6 |
2. 평가 실행: pipenv run python eval_rag.py
|
| 7 |
"""
|
| 8 |
|
| 9 |
+
import asyncio
|
| 10 |
import requests as http_requests
|
| 11 |
+
from ragnarok_ai.evaluators import (
|
| 12 |
+
precision_at_k,
|
| 13 |
+
recall_at_k,
|
| 14 |
+
mrr,
|
| 15 |
+
ndcg_at_k,
|
| 16 |
+
LLMJudge,
|
|
|
|
|
|
|
| 17 |
)
|
|
|
|
| 18 |
|
| 19 |
# ── 설정 ──────────────────────────────────────────────
|
| 20 |
API_BASE = "http://127.0.0.1:8000"
|
| 21 |
OLLAMA_BASE = "http://localhost:11434"
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
# ── 테스트 케이스 정의 ─────────────────────────────────
|
| 24 |
TEST_CASES = [
|
| 25 |
{
|
|
|
|
| 57 |
return doc_id
|
| 58 |
|
| 59 |
|
| 60 |
+
async def main():
|
| 61 |
document_id = get_document_id()
|
| 62 |
|
| 63 |
print(f"\n{'='*60}")
|
| 64 |
print(f" RAG 평가 시작 (총 {len(TEST_CASES)}건)")
|
| 65 |
print(f"{'='*60}\n")
|
| 66 |
|
| 67 |
+
# LLM-as-Judge 초기화 (Ollama llama3.1)
|
| 68 |
+
judge = LLMJudge(model="llama3.1", base_url=OLLAMA_BASE)
|
| 69 |
+
|
| 70 |
+
# 각 테스트 케이스에 대해 RAG API 호출 및 평가
|
| 71 |
+
all_results = []
|
| 72 |
for i, tc in enumerate(TEST_CASES, 1):
|
| 73 |
question = tc["question"]
|
| 74 |
expected = tc["expected"]
|
|
|
|
| 78 |
|
| 79 |
answer = result["answer"]
|
| 80 |
sources = result["sources"]
|
| 81 |
+
context = "\n".join(sources)
|
| 82 |
|
| 83 |
print(f" 답변: {answer[:80]}...")
|
| 84 |
+
print(f" 소스: {len(sources)}건")
|
| 85 |
+
|
| 86 |
+
# Retrieval 지표 (sources를 문서 ID로 사용)
|
| 87 |
+
retrieved_ids = [f"doc_{j}" for j in range(len(sources))]
|
| 88 |
+
relevant_ids = [f"doc_0"] # 최소 첫 번째 문서가 관련 있다고 가정
|
| 89 |
+
p = precision_at_k(retrieved_ids, relevant_ids, k=len(sources))
|
| 90 |
+
r = recall_at_k(retrieved_ids, relevant_ids, k=len(sources))
|
| 91 |
+
m = mrr(retrieved_ids, relevant_ids)
|
| 92 |
+
|
| 93 |
+
# LLM-as-Judge 평가 (faithfulness, relevance, hallucination)
|
| 94 |
+
print(f" 평가 중... (Ollama llama3.1, 시간이 걸릴 수 있습니다)")
|
| 95 |
+
faithfulness = await judge.evaluate_faithfulness(
|
| 96 |
+
context=context, question=question, answer=answer
|
| 97 |
)
|
| 98 |
+
relevance = await judge.evaluate_relevance(question=question, answer=answer)
|
| 99 |
+
hallucination = await judge.detect_hallucination(context=context, answer=answer)
|
| 100 |
+
|
| 101 |
+
case_result = {
|
| 102 |
+
"question": question,
|
| 103 |
+
"answer": answer,
|
| 104 |
+
"expected": expected,
|
| 105 |
+
"retrieval": {"precision": p, "recall": r, "mrr": m},
|
| 106 |
+
"faithfulness": {
|
| 107 |
+
"verdict": faithfulness.verdict,
|
| 108 |
+
"score": faithfulness.score,
|
| 109 |
+
"explanation": faithfulness.explanation,
|
| 110 |
+
},
|
| 111 |
+
"relevance": {
|
| 112 |
+
"verdict": relevance.verdict,
|
| 113 |
+
"score": relevance.score,
|
| 114 |
+
"explanation": relevance.explanation,
|
| 115 |
+
},
|
| 116 |
+
"hallucination": {
|
| 117 |
+
"verdict": hallucination.verdict,
|
| 118 |
+
"score": hallucination.score,
|
| 119 |
+
"explanation": hallucination.explanation,
|
| 120 |
+
},
|
| 121 |
+
}
|
| 122 |
+
all_results.append(case_result)
|
| 123 |
|
| 124 |
+
print(
|
| 125 |
+
f" Faithfulness: {faithfulness.verdict} ({faithfulness.score:.2f})"
|
| 126 |
+
)
|
| 127 |
+
print(f" Relevance: {relevance.verdict} ({relevance.score:.2f})")
|
| 128 |
+
print(
|
| 129 |
+
f" Hallucination: {hallucination.verdict} ({hallucination.score:.2f})"
|
| 130 |
+
)
|
| 131 |
+
print()
|
| 132 |
|
| 133 |
+
# 요약 출력
|
| 134 |
print(f"{'='*60}")
|
| 135 |
+
print(f" 평가 완료! 결과 요약")
|
| 136 |
print(f"{'='*60}\n")
|
| 137 |
|
| 138 |
+
avg_faith = sum(r["faithfulness"]["score"] for r in all_results) / len(all_results)
|
| 139 |
+
avg_rel = sum(r["relevance"]["score"] for r in all_results) / len(all_results)
|
| 140 |
+
avg_hall = sum(r["hallucination"]["score"] for r in all_results) / len(all_results)
|
| 141 |
+
|
| 142 |
+
print(f" 평균 Faithfulness : {avg_faith:.2f}")
|
| 143 |
+
print(f" 평균 Relevance : {avg_rel:.2f}")
|
| 144 |
+
print(f" 평균 Hallucination: {avg_hall:.2f}")
|
| 145 |
+
print()
|
| 146 |
+
|
| 147 |
+
for i, r in enumerate(all_results, 1):
|
| 148 |
+
print(f" [{i}] {r['question']}")
|
| 149 |
+
print(f" 답변: {r['answer'][:60]}...")
|
| 150 |
+
print(
|
| 151 |
+
f" Faithfulness={r['faithfulness']['score']:.2f} "
|
| 152 |
+
f"Relevance={r['relevance']['score']:.2f} "
|
| 153 |
+
f"Hallucination={r['hallucination']['score']:.2f}"
|
| 154 |
+
)
|
| 155 |
+
print()
|
| 156 |
|
| 157 |
|
| 158 |
if __name__ == "__main__":
|
| 159 |
+
asyncio.run(main())
|