동의 게이트와 런타임 안정화

This commit is contained in:
Yun Chan 2026-06-27 17:22:38 +09:00
parent 0eb7d925ed
commit 0ec266a761
34 changed files with 1186 additions and 158 deletions

View file

@ -23,6 +23,7 @@ from __future__ import annotations
import asyncio
import json
import threading
import time
from dataclasses import dataclass, field
from enum import Enum
@ -159,6 +160,7 @@ CRAG_TOP1_THRESHOLD = 0.35
# ════════════════════════════════════════════════════════════════════════════
_EMBEDDER: Any = None # FlagEmbedding.BGEM3FlagModel 인스턴스(지연 로딩 캐시)
_EMBEDDER_FAILED = False # 모델 로드 실패 1회 기록(반복 시도 방지)
_EMBEDDER_LOCK = threading.RLock()
BGE_M3_MODEL = "BAAI/bge-m3"
EMBED_DIM = 1024 # kb.chunk.embedding vector(1024) 와 정합 — 어기면 DB 캐스트 실패
@ -171,22 +173,25 @@ def _get_embedder() -> Any:
global _EMBEDDER, _EMBEDDER_FAILED
if _EMBEDDER is not None:
return _EMBEDDER
if _EMBEDDER_FAILED:
raise NotConfigured("BGE-M3 embedder unavailable (prior load failure)")
try:
from FlagEmbedding import BGEM3FlagModel # 무거운 의존성 — 지연 import
except Exception as e: # ImportError 포함(미설치 환경)
_EMBEDDER_FAILED = True
raise NotConfigured(
"FlagEmbedding(BGE-M3) not installed — requirements-rag.txt 필요"
) from e
try:
# use_fp16: GPU 시 절반정밀(속도). CPU 면 무시됨.
_EMBEDDER = BGEM3FlagModel(BGE_M3_MODEL, use_fp16=True)
except Exception as e:
_EMBEDDER_FAILED = True
raise NotConfigured(f"BGE-M3 model load failed: {e}") from e
return _EMBEDDER
with _EMBEDDER_LOCK:
if _EMBEDDER is not None:
return _EMBEDDER
if _EMBEDDER_FAILED:
raise NotConfigured("BGE-M3 embedder unavailable (prior load failure)")
try:
from FlagEmbedding import BGEM3FlagModel # 무거운 의존성 — 지연 import
except Exception as e: # ImportError 포함(미설치 환경)
_EMBEDDER_FAILED = True
raise NotConfigured(
"FlagEmbedding(BGE-M3) not installed — requirements-rag.txt 필요"
) from e
try:
# use_fp16: GPU 시 절반정밀(속도). CPU 면 무시됨.
_EMBEDDER = BGEM3FlagModel(BGE_M3_MODEL, use_fp16=True)
except Exception as e:
_EMBEDDER_FAILED = True
raise NotConfigured(f"BGE-M3 model load failed: {e}") from e
return _EMBEDDER
@dataclass(slots=True)
@ -202,13 +207,14 @@ def embed_query(text: str) -> EmbeddedQuery:
인덱싱 시점(오프라인 배치)에도 같은 함수로 청크 임베딩을 산출한다(동일 모델 재사용).
"""
model = _get_embedder()
out = model.encode(
[text],
return_dense=True,
return_sparse=True,
return_colbert_vecs=False, # 멀티벡터는 런타임 회수에 미사용(인덱싱만)
)
with _EMBEDDER_LOCK:
model = _get_embedder()
out = model.encode(
[text],
return_dense=True,
return_sparse=True,
return_colbert_vecs=False, # 멀티벡터는 런타임 회수에 미사용(인덱싱만)
)
dense_vec = out["dense_vecs"][0]
# numpy → list[float] (asyncpg pgvector 텍스트 캐스트 호환). tolist() 있으면 사용.
dense = dense_vec.tolist() if hasattr(dense_vec, "tolist") else list(dense_vec)