feat: add rag by codex
This commit is contained in:
@@ -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}
|
||||
|
||||
Reference in New Issue
Block a user