미납·환불은 입력한 차량번호로 조회하고 개발서버 임베딩을 운영 벡터에 맞춘다.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Qwen3-Embedding OpenAI(/v1/embeddings) + TEI(/embed) 서버.
|
||||
|
||||
Qwen3-Embedding-8B 문서는 last-token pooling 이다.
|
||||
질의 프리픽스는 챗봇 클라이언트가 붙이므로 여기서는 입력을 그대로 임베딩한다.
|
||||
"""
|
||||
import os
|
||||
from typing import List, Union
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from fastapi import FastAPI
|
||||
from pydantic import BaseModel
|
||||
from transformers import AutoModel, AutoTokenizer
|
||||
|
||||
MODEL_ID = os.getenv("EMBED_MODEL_ID", "Qwen/Qwen3-Embedding-8B")
|
||||
PORT = int(os.getenv("EMBED_PORT", "16021"))
|
||||
|
||||
app = FastAPI()
|
||||
tokenizer = None
|
||||
model = None
|
||||
device = None
|
||||
|
||||
|
||||
class EmbedInputs(BaseModel):
|
||||
inputs: Union[str, List[str]]
|
||||
normalize: bool = True
|
||||
|
||||
|
||||
class OpenAIEmbedRequest(BaseModel):
|
||||
model: str = ""
|
||||
input: Union[str, List[str]]
|
||||
|
||||
|
||||
def load_model() -> None:
|
||||
global tokenizer, model, device
|
||||
if torch.backends.mps.is_available():
|
||||
device = torch.device("mps")
|
||||
elif torch.cuda.is_available():
|
||||
device = torch.device("cuda")
|
||||
else:
|
||||
device = torch.device("cpu")
|
||||
print(f"[Embed] loading {MODEL_ID} on {device}", flush=True)
|
||||
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
|
||||
model = AutoModel.from_pretrained(
|
||||
MODEL_ID, trust_remote_code=True, torch_dtype=torch.float16
|
||||
)
|
||||
model.to(device)
|
||||
model.eval()
|
||||
print("[Embed] ready", flush=True)
|
||||
|
||||
|
||||
@torch.inference_mode()
|
||||
def embed_texts(texts: List[str], normalize: bool) -> List[List[float]]:
|
||||
encoded = tokenizer(texts, padding=True, truncation=True, return_tensors="pt")
|
||||
encoded = {k: v.to(device) for k, v in encoded.items()}
|
||||
hidden = model(**encoded).last_hidden_state
|
||||
last_idx = encoded["attention_mask"].sum(dim=1) - 1
|
||||
rows = torch.arange(hidden.size(0), device=device)
|
||||
embeddings = hidden[rows, last_idx]
|
||||
if normalize:
|
||||
embeddings = F.normalize(embeddings, p=2, dim=1)
|
||||
return embeddings.float().cpu().tolist()
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup() -> None:
|
||||
load_model()
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health():
|
||||
return {"status": "ok", "model": MODEL_ID, "pooling": "lasttoken"}
|
||||
|
||||
|
||||
@app.post("/embed")
|
||||
async def embed(req: EmbedInputs):
|
||||
texts = [req.inputs] if isinstance(req.inputs, str) else req.inputs
|
||||
return embed_texts(texts, req.normalize)
|
||||
|
||||
|
||||
@app.post("/v1/embeddings")
|
||||
async def openai_embeddings(req: OpenAIEmbedRequest):
|
||||
texts = [req.input] if isinstance(req.input, str) else list(req.input)
|
||||
vectors = embed_texts(texts, normalize=True)
|
||||
return {
|
||||
"object": "list",
|
||||
"model": req.model or MODEL_ID,
|
||||
"data": [
|
||||
{"object": "embedding", "index": i, "embedding": vec}
|
||||
for i, vec in enumerate(vectors)
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(app, host="0.0.0.0", port=PORT)
|
||||
Reference in New Issue
Block a user