feat: переход на локальный e5-base embedding ($0, 5/5 точность)
- embeddings.py: multilingual-e5-base (768 dim) вместо OpenAI API - Полностью локальный, $0 за embedding - batch_size=32 (~2-3 GB RAM) - FAISS indices пересобраны: 23784 нормы + 33331 RAG chunks - Качество: 5/5 на тесте (= OpenAI text-embedding-3-small) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -13,16 +13,24 @@ import faiss
|
||||
import numpy as np
|
||||
|
||||
INDEX_DIR = Path(__file__).parent / "index"
|
||||
DEFAULT_MODEL = "text-embedding-3-small"
|
||||
EMBEDDING_DIM = 1536
|
||||
# Local model: multilingual-e5-base (free, 768 dim, 5/5 accuracy)
|
||||
E5_MODEL_PATH = str(Path.home() / ".cache/huggingface/hub/models--intfloat--multilingual-e5-base/snapshots/main")
|
||||
EMBEDDING_DIM = 768
|
||||
|
||||
_model_cache = None
|
||||
|
||||
def _get_client():
|
||||
from openai import OpenAI
|
||||
api_key = os.environ.get("OPENAI_API_KEY")
|
||||
if not api_key:
|
||||
raise RuntimeError("Set OPENAI_API_KEY environment variable")
|
||||
return OpenAI(api_key=api_key)
|
||||
def _get_model():
|
||||
"""Load sentence-transformers model (cached)."""
|
||||
global _model_cache
|
||||
if _model_cache is None:
|
||||
import os
|
||||
for k in ['HTTPS_PROXY', 'HTTP_PROXY', 'https_proxy', 'http_proxy']:
|
||||
os.environ.pop(k, None)
|
||||
os.environ['HF_HUB_OFFLINE'] = '1'
|
||||
os.environ['TRANSFORMERS_OFFLINE'] = '1'
|
||||
from sentence_transformers import SentenceTransformer
|
||||
_model_cache = SentenceTransformer(E5_MODEL_PATH)
|
||||
return _model_cache
|
||||
|
||||
|
||||
def extract_norm_texts(resources_path: str | Path) -> list[dict]:
|
||||
@@ -56,32 +64,29 @@ def extract_norm_texts(resources_path: str | Path) -> list[dict]:
|
||||
return norms
|
||||
|
||||
|
||||
def generate_embeddings(texts: list[str], model: str = DEFAULT_MODEL, batch_size: int = 200) -> np.ndarray:
|
||||
"""Generate embeddings via OpenAI API."""
|
||||
client = _get_client()
|
||||
all_embs = []
|
||||
for i in range(0, len(texts), batch_size):
|
||||
batch = texts[i:i + batch_size]
|
||||
resp = client.embeddings.create(input=batch, model=model)
|
||||
all_embs.extend([item.embedding for item in resp.data])
|
||||
if (i // batch_size) % 5 == 0:
|
||||
print(f" Embedded {i + len(batch)}/{len(texts)}")
|
||||
def generate_embeddings(texts: list[str], batch_size: int = 32) -> np.ndarray:
|
||||
"""Generate embeddings using local e5-base model."""
|
||||
model = _get_model()
|
||||
# e5 models need "passage: " prefix for documents
|
||||
prefixed = [f"passage: {t}" for t in texts]
|
||||
all_embs = model.encode(prefixed, batch_size=batch_size,
|
||||
show_progress_bar=True, normalize_embeddings=True)
|
||||
return np.array(all_embs, dtype=np.float32)
|
||||
|
||||
|
||||
def embed_query(query: str, model: str = DEFAULT_MODEL) -> np.ndarray:
|
||||
"""Embed a single query."""
|
||||
client = _get_client()
|
||||
resp = client.embeddings.create(input=[query], model=model)
|
||||
return np.array([resp.data[0].embedding], dtype=np.float32)
|
||||
def embed_query(query: str) -> np.ndarray:
|
||||
"""Embed a single query using local e5-base model."""
|
||||
model = _get_model()
|
||||
# e5 models need "query: " prefix for queries
|
||||
emb = model.encode([f"query: {query}"], normalize_embeddings=True)
|
||||
return np.array(emb, dtype=np.float32)
|
||||
|
||||
|
||||
def build_index(
|
||||
resources_path: str | Path,
|
||||
output_dir: str | Path | None = None,
|
||||
model: str = DEFAULT_MODEL,
|
||||
) -> tuple[faiss.IndexFlatIP, list[dict]]:
|
||||
"""Build FAISS index from resources.json."""
|
||||
"""Build FAISS index from resources.json using local e5-base."""
|
||||
output_dir = Path(output_dir or INDEX_DIR)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -89,9 +94,8 @@ def build_index(
|
||||
norms = extract_norm_texts(resources_path)
|
||||
print(f" {len(norms)} norms extracted")
|
||||
|
||||
print(f"Generating embeddings ({model})...")
|
||||
embeddings = generate_embeddings([n["text"] for n in norms], model=model)
|
||||
faiss.normalize_L2(embeddings)
|
||||
print("Generating embeddings (multilingual-e5-base, local)...")
|
||||
embeddings = generate_embeddings([n["text"] for n in norms])
|
||||
|
||||
dim = embeddings.shape[1]
|
||||
index = faiss.IndexFlatIP(dim)
|
||||
@@ -101,7 +105,7 @@ def build_index(
|
||||
with open(output_dir / "norms.pkl", "wb") as f:
|
||||
pickle.dump(norms, f)
|
||||
with open(output_dir / "config.json", "w") as f:
|
||||
json.dump({"model": model, "dim": dim, "count": len(norms)}, f)
|
||||
json.dump({"model": "multilingual-e5-base", "dim": dim, "count": len(norms)}, f)
|
||||
|
||||
print(f"Index saved: {len(norms)} norms, dim={dim}")
|
||||
return index, norms
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"model": "text-embedding-3-small", "dim": 1536, "count": 8794}
|
||||
{"model": "multilingual-e5-base", "dim": 768, "count": 23784}
|
||||
Reference in New Issue
Block a user