Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from fastapi import FastAPI, HTTPException
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from sentence_transformers import SentenceTransformer
|
| 5 |
+
|
| 6 |
+
# Optimize for the 2 vCPU limit on the free tier
|
| 7 |
+
os.environ["OMP_NUM_THREADS"] = "2"
|
| 8 |
+
os.environ["MKL_NUM_THREADS"] = "2"
|
| 9 |
+
|
| 10 |
+
app = FastAPI(title="Embedding API", description="Production-grade text embedding endpoint.")
|
| 11 |
+
|
| 12 |
+
# Initialize the model at startup
|
| 13 |
+
MODEL_ID = "Snowflake/snowflake-arctic-embed-l"
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
print(f"Loading {MODEL_ID} into memory...")
|
| 17 |
+
model = SentenceTransformer(MODEL_ID, device="cpu")
|
| 18 |
+
print("Model loaded successfully.")
|
| 19 |
+
except Exception as e:
|
| 20 |
+
print(f"Failed to load model: {e}")
|
| 21 |
+
model = None
|
| 22 |
+
|
| 23 |
+
class EmbeddingRequest(BaseModel):
|
| 24 |
+
texts: list[str]
|
| 25 |
+
is_query: bool = False
|
| 26 |
+
|
| 27 |
+
@app.get("/health")
|
| 28 |
+
def health_check():
|
| 29 |
+
if model is None:
|
| 30 |
+
raise HTTPException(status_code=503, detail="Model not loaded")
|
| 31 |
+
return {"status": "healthy", "model": MODEL_ID}
|
| 32 |
+
|
| 33 |
+
@app.post("/embed")
|
| 34 |
+
def generate_embeddings(request: EmbeddingRequest):
|
| 35 |
+
if model is None:
|
| 36 |
+
raise HTTPException(status_code=503, detail="Model initialization failed.")
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
# Snowflake architecture requires a specific prefix for search queries
|
| 40 |
+
if request.is_query:
|
| 41 |
+
inputs = [f"Represent this sentence for searching relevant passages: {text}" for text in request.texts]
|
| 42 |
+
else:
|
| 43 |
+
inputs = request.texts
|
| 44 |
+
|
| 45 |
+
embeddings = model.encode(inputs, normalize_embeddings=True)
|
| 46 |
+
return {"embeddings": embeddings.tolist()}
|
| 47 |
+
except Exception as e:
|
| 48 |
+
raise HTTPException(status_code=500, detail=str(e))
|