I just want to use a pre-trained open source embedding model from SentenceTransformer for encoding plain text.
The goal is to use swagger as GUI - put in a sentence and get out embeddings.
from fastapi import Depends, FastAPI
from pydantic import BaseModel
from sentence_transformers import SentenceTransformer
embedding_model = SentenceTransformer("./assets/BAAI/bge-small-en")
app = FastAPI()
class EmbeddingRequest(BaseModel):
text: str
class EmbeddingResponse(BaseModel):
embeddings: float
@app.post("/embeddings", response_model=EmbeddingResponse)
async def get_embeddings(request: EmbeddingRequest, model: embedding_model):
embeddings_result = model.encode(request.text)
return EmbeddingResponse(embeddings=embeddings_result)
Note that I don't have access to your
"./assets/BAAI/bge-small-enmodel, so I usedall-mpnet-base-v2instead.That said, there are two issues with your implementation:
modelas an input parameter which is not necessary. Just use the globalembedding_modeldirectly.embeddingsis wrong. (Unless your model really outputs a singlefloat). The output ofembedding_model.encodeisnp.ndarray, which you can convert to a list usingembeddings_result.tolist().The following works for me: