feat: add rag by codex

This commit is contained in:
2026-11-27 20:46:29 +03:30
parent 302d06b44f
commit 8a1e61b0f7
52 changed files with 3772 additions and 59 deletions
+4
View File
@@ -0,0 +1,4 @@
.venv/
__pycache__/
.pytest_cache/
test_main.py
+14
View File
@@ -0,0 +1,14 @@
FROM python:3.12-slim
WORKDIR /app
ENV HF_HOME=/cache PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
COPY requirements.txt .
RUN pip install --no-cache-dir torch==2.9.1 --index-url https://download.pytorch.org/whl/cpu \
&& pip install --no-cache-dir -r requirements.txt \
&& mkdir -p /cache && chown 65532:65532 /cache
COPY main.py .
USER 65532:65532
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--limit-concurrency", "32", "--timeout-graceful-shutdown", "30", "--no-access-log"]
+143
View File
@@ -0,0 +1,143 @@
import logging
import os
from contextlib import asynccontextmanager
from threading import Lock
from typing import Annotated, Literal
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field, StringConstraints
MODEL = os.getenv("RAG_EMBEDDING_MODEL", "intfloat/multilingual-e5-small")
REVISION = os.getenv("RAG_EMBEDDING_REVISION", "62ff60abe92eb88c1b297fabaad28f7ac77b5875")
MODEL_ID = f"{MODEL}@{REVISION}"
MAX_BATCH = 32
MAX_TOKENS = 512
logger = logging.getLogger("embedding")
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False
inference_lock = Lock()
def load_model():
import torch
from sentence_transformers import SentenceTransformer
torch.set_num_threads(2)
return SentenceTransformer(
MODEL, revision=REVISION, device="cpu", trust_remote_code=False,
model_kwargs={"use_safetensors": True},
)
@asynccontextmanager
async def lifespan(app: FastAPI):
model = load_model()
if model.get_sentence_embedding_dimension() != 384 or not model.tokenizer.is_fast:
raise RuntimeError("Expected 384 dimensions and a fast tokenizer")
model.max_seq_length = min(MAX_TOKENS, model.max_seq_length)
app.state.model = model
logger.info('{"event":"embedding_model_ready","device":"cpu"}')
try:
yield
finally:
del app.state.model
logger.info('{"event":"embedding_model_stopped"}')
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
Text = Annotated[str, StringConstraints(strict=True, strip_whitespace=True, min_length=1)]
class EmbedInput(BaseModel):
input_type: Literal["query", "passage"]
texts: list[Annotated[Text, Field(max_length=8192)]] = Field(min_length=1, max_length=MAX_BATCH)
class ChunkInput(BaseModel):
text: Annotated[Text, Field(max_length=32000)]
size: int = Field(ge=64, le=480, strict=True)
overlap: int = Field(ge=0, le=160, strict=True)
@app.exception_handler(RequestValidationError)
async def validation_error(_request: Request, exc: RequestValidationError):
return JSONResponse(status_code=422, content={
"detail": [{"loc": item["loc"], "type": item["type"]} for item in exc.errors()]
})
@app.get("/health")
def health():
return {"status": "ready"}
@app.get("/model")
def model_info(request: Request):
return {"model": MODEL_ID, "dimensions": 384, "max_batch": MAX_BATCH,
"max_tokens": request.app.state.model.max_seq_length, "device": "cpu"}
@app.post("/embed")
def embed(body: EmbedInput, request: Request):
model = request.app.state.model
texts = [f"{body.input_type}: {text}" for text in body.texts]
try:
with inference_lock:
if any(len(ids) > model.max_seq_length for ids in model.tokenizer(texts, verbose=False)["input_ids"]):
raise HTTPException(422, "Input exceeds the tokenizer limit")
vectors = model.encode(texts, batch_size=min(8, len(texts)),
normalize_embeddings=True, show_progress_bar=False)
except HTTPException:
raise
except Exception:
logger.error('{"event":"embedding_inference_failed"}')
raise HTTPException(503, "Embedding inference failed") from None
if vectors.shape != (len(texts), 384):
raise HTTPException(503, "Unexpected model output")
return {"model": MODEL_ID, "embeddings": vectors.tolist()}
def split_text(text, tokenizer, size, overlap, max_tokens):
offsets = tokenizer(text, add_special_tokens=False, verbose=False,
return_offsets_mapping=True)["offset_mapping"]
start = 0
while start < len(offsets):
end = min(start + size, len(offsets))
floor = start + max(overlap + 1, size * 3 // 4)
if end < len(offsets):
for boundary in range(end, floor - 1, -1):
if text[offsets[boundary - 1][1]:offsets[boundary][0]].strip(" \n\t") == "" and (
text[offsets[boundary - 1][1]:offsets[boundary][0]].count("\n")
or text[offsets[boundary - 1][1] - 1:offsets[boundary - 1][1]] in ".؟!?؛"
):
end = boundary
break
while end > start:
content = text[offsets[start][0]:offsets[end - 1][1]].strip()
if 0 < len(content) <= 4096 and len(tokenizer(f"passage: {content}", verbose=False)["input_ids"]) <= max_tokens:
yield content
break
end -= 1
if end == len(offsets):
break
start = max(start + 1, end - overlap)
@app.post("/chunks")
def chunks(body: ChunkInput, request: Request):
if body.overlap >= body.size:
raise HTTPException(422, "Overlap must be smaller than size")
model = request.app.state.model
try:
with inference_lock:
parts = list(split_text(body.text, model.tokenizer, body.size, body.overlap, model.max_seq_length))
except Exception:
logger.error('{"event":"embedding_tokenization_failed"}')
raise HTTPException(503, "Embedding tokenization failed") from None
return {"model": MODEL_ID, "chunks": parts}
+5
View File
@@ -0,0 +1,5 @@
fastapi==0.121.3
uvicorn==0.38.0
sentence-transformers==5.1.2
transformers==4.57.6
+104
View File
@@ -0,0 +1,104 @@
import math
import os
import re
from unittest.mock import Mock
import pytest
from fastapi.testclient import TestClient
import main
class Tokenizer:
is_fast = True
def __call__(self, texts, add_special_tokens=True, **_kwargs):
if isinstance(texts, list):
return {"input_ids": [self(text)["input_ids"] for text in texts]}
offsets = [match.span() for match in re.finditer(r"\S+", texts)]
return {"input_ids": [1] * (len(offsets) + 2 * add_special_tokens),
"offset_mapping": offsets}
@pytest.fixture
def model(monkeypatch):
model = Mock(max_seq_length=512, tokenizer=Tokenizer())
model.get_sentence_embedding_dimension.return_value = 384
def encode(texts, **_kwargs):
array = Mock(shape=(len(texts), 384))
array.tolist.return_value = [[1.0] + [0.0] * 383 for _ in texts]
return array
model.encode.side_effect = encode
monkeypatch.setattr(main, "load_model", lambda: model)
return model
def test_prefixes_batch_and_metadata(model):
with TestClient(main.app) as client:
assert client.get("/health").status_code == 200
assert client.get("/model").json()["dimensions"] == 384
for kind in ("query", "passage"):
result = client.post("/embed", json={"input_type": kind, "texts": ["سلام", "text"]})
assert result.status_code == 200
assert len(result.json()["embeddings"]) == 2
assert len(result.json()["embeddings"][0]) == 384
assert model.encode.call_args.args[0] == [f"{kind}: سلام", f"{kind}: text"]
assert model.encode.call_args.kwargs["normalize_embeddings"]
def test_limits_and_validation_does_not_echo_content(model):
with TestClient(main.app) as client:
for payload in (
{"input_type": "secret-invalid", "texts": ["hello"]},
{"input_type": "query", "texts": []},
{"input_type": "query", "texts": [" "]},
{"input_type": "query", "texts": [123]},
{"input_type": "query", "texts": ["x"] * 33},
{"input_type": "query", "texts": ["x " * 513]},
{"input_type": "query", "texts": ["x" * 8193]},
):
response = client.post("/embed", json=payload)
assert response.status_code == 422
assert "secret-invalid" not in response.text
model.encode.assert_not_called()
def test_token_chunks_overlap_and_fit(model):
words = [f"واژه{i}" for i in range(150)]
with TestClient(main.app) as client:
response = client.post("/chunks", json={"text": " ".join(words), "size": 64, "overlap": 12})
assert response.status_code == 200
first, second, last = [chunk.split() for chunk in response.json()["chunks"]]
assert len(first) == 64
assert first[-12:] == second[:12]
assert last[-1] == words[-1]
assert client.post("/chunks", json={"text": "سلام", "size": 64, "overlap": 64}).status_code == 422
@pytest.mark.skipif(os.getenv("RAG_REAL_MODEL_TEST") != "1", reason="requires CPU model weights")
def test_real_model_contract():
with TestClient(main.app) as client:
assert main.app.state.model.device.type == "cpu"
response = client.post("/embed", json={
"input_type": "query",
"texts": ["فشار خون چیست؟", "What is blood pressure?"],
})
assert response.status_code == 200
assert response.json()["model"] == main.MODEL_ID
embeddings = response.json()["embeddings"]
assert len(embeddings) == 2
for embedding in embeddings:
assert len(embedding) == 384
assert math.isclose(sum(value * value for value in embedding), 1, abs_tol=1e-3)
text = "این بخش درباره فشار خون است. " * 240
chunk_response = client.post("/chunks", json={"text": text, "size": 440, "overlap": 88})
assert chunk_response.status_code == 200
passages = chunk_response.json()["chunks"]
assert 1 < len(passages) <= main.MAX_BATCH
passage_response = client.post("/embed", json={"input_type": "passage", "texts": passages})
assert passage_response.status_code == 200
assert len(passage_response.json()["embeddings"]) == len(passages)