-
Notifications
You must be signed in to change notification settings - Fork 218
Expand file tree
/
Copy pathreranks_predictionguard.py
More file actions
66 lines (54 loc) · 2.11 KB
/
Copy pathreranks_predictionguard.py
File metadata and controls
66 lines (54 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Copyright (C) 2024 Prediction Guard, Inc.
# SPDX-License-Identified: Apache-2.0
import logging
import time
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from predictionguard import PredictionGuard
from comps import (
GeneratedDoc,
LLMParamsDoc,
RerankedDoc,
SearchedDoc,
ServiceType,
TextDoc,
opea_microservices,
register_microservice,
register_statistics,
statistics_dict,
)
from comps.reranks.predictionguard.src.helpers import process_doc_list
client = PredictionGuard()
app = FastAPI()
@register_microservice(
name="opea_service@reranks_predictionguard",
service_type=ServiceType.LLM,
endpoint="/v1/reranking",
host="0.0.0.0",
port=9000,
input_datatype=SearchedDoc,
output_datatype=RerankedDoc,
)
@register_statistics(names=["opea_service@reranks_predictionguard"])
def reranks_generate(input: SearchedDoc) -> RerankedDoc:
start = time.time()
reranked_docs = []
if input.retrieved_docs:
docs = process_doc_list(input.retrieved_docs)
try:
rerank_result = client.rerank.create(
model="bge-reranker-v2-m3", query=input.initial_query, documents=docs, return_documents=True
)
# based on rerank_result, reorder the retrieved_docs to match the order of the retrieved_docs in the input
reranked_docs = [
TextDoc(id=input.retrieved_docs[doc["index"]].id, text=doc["text"]) for doc in rerank_result["results"]
]
except ValueError as e:
logging.error(f"rerank failed with error: {e}. Inputs: query={input.initial_query}, documents={docs}")
raise HTTPException(status_code=500, detail="An unexpected error occurred.")
else:
logging.info("reranking request input did not contain any documents")
statistics_dict["opea_service@reranks_predictionguard"].append_latency(time.time() - start, None)
return RerankedDoc(initial_query=input.initial_query, reranked_docs=reranked_docs)
if __name__ == "__main__":
opea_microservices["opea_service@reranks_predictionguard"].start()