|
| 1 | +import json |
| 2 | + |
| 3 | +import requests |
| 4 | +from typing import Any, Dict, List, Optional |
| 5 | + |
| 6 | +from ..version import __version__ |
| 7 | + |
| 8 | + |
| 9 | +class Rerank: |
| 10 | + """Rerank sorts text inputs by semantic relevance to a specified query. |
| 11 | +
|
| 12 | + Usage:: |
| 13 | +
|
| 14 | + import os |
| 15 | + import json |
| 16 | +
|
| 17 | + from predictionguard import PredictionGuard |
| 18 | +
|
| 19 | + # Set your Prediction Guard token as an environmental variable. |
| 20 | + os.environ["PREDICTIONGUARD_API_KEY"] = "<api key>" |
| 21 | +
|
| 22 | + client = PredictionGuard() |
| 23 | +
|
| 24 | + response = client.rerank.create( |
| 25 | + model="bge-reranker-v2-m3", |
| 26 | + query="What is Deep Learning?", |
| 27 | + documents=[ |
| 28 | + "Deep Learning is pizza.", |
| 29 | + "Deep Learning is not pizza." |
| 30 | + ], |
| 31 | + return_documents=True |
| 32 | + ) |
| 33 | +
|
| 34 | + print(json.dumps(response, sort_keys=True, indent=4, separators=(",", ": "))) |
| 35 | + """ |
| 36 | + |
| 37 | + |
| 38 | + def __init__(self, api_key, url): |
| 39 | + self.api_key = api_key |
| 40 | + self.url = url |
| 41 | + |
| 42 | + def create( |
| 43 | + self, |
| 44 | + model: str, |
| 45 | + query: str, |
| 46 | + documents: List[str], |
| 47 | + return_documents: Optional[bool] = True |
| 48 | + ) -> Dict[str, Any]: |
| 49 | + """ |
| 50 | + Creates a rerank request in the Prediction Guard /rerank API. |
| 51 | +
|
| 52 | + :param model: The model to use for reranking. |
| 53 | + :param query: The query to rank against. |
| 54 | + :param documents: The documents to rank. |
| 55 | + :param return_documents: Whether to return documents with score. |
| 56 | + :return: A dictionary containing the tokens and token metadata. |
| 57 | + """ |
| 58 | + |
| 59 | + # Run _create_rerank |
| 60 | + choices = self._create_rerank(model, query, documents, return_documents) |
| 61 | + return choices |
| 62 | + |
| 63 | + def _create_rerank(self, model, query, documents, return_documents): |
| 64 | + """ |
| 65 | + Function to rank text. |
| 66 | + """ |
| 67 | + |
| 68 | + headers = { |
| 69 | + "Content-Type": "application/json", |
| 70 | + "Authorization": "Bearer " + self.api_key, |
| 71 | + "User-Agent": "Prediction Guard Python Client: " + __version__, |
| 72 | + } |
| 73 | + |
| 74 | + payload = { |
| 75 | + "model": model, |
| 76 | + "query": query, |
| 77 | + "documents": documents, |
| 78 | + "return_documents": return_documents |
| 79 | + } |
| 80 | + |
| 81 | + payload = json.dumps(payload) |
| 82 | + |
| 83 | + response = requests.request( |
| 84 | + "POST", self.url + "/rerank", headers=headers, data=payload |
| 85 | + ) |
| 86 | + |
| 87 | + if response.status_code == 200: |
| 88 | + ret = response.json() |
| 89 | + return ret |
| 90 | + elif response.status_code == 429: |
| 91 | + raise ValueError( |
| 92 | + "Could not connect to Prediction Guard API. " |
| 93 | + "Too many requests, rate limit or quota exceeded." |
| 94 | + ) |
| 95 | + else: |
| 96 | + # Check if there is a json body in the response. Read that in, |
| 97 | + # print out the error field in the json body, and raise an exception. |
| 98 | + err = "" |
| 99 | + try: |
| 100 | + err = response.json()["error"] |
| 101 | + except Exception: |
| 102 | + pass |
| 103 | + raise ValueError("Could not rank documents. " + err) |
| 104 | + |
| 105 | + def list_models(self): |
| 106 | + # Get the list of current models. |
| 107 | + headers = { |
| 108 | + "Content-Type": "application/json", |
| 109 | + "Authorization": "Bearer " + self.api_key, |
| 110 | + "User-Agent": "Prediction Guard Python Client: " + __version__ |
| 111 | + } |
| 112 | + |
| 113 | + response = requests.request("GET", self.url + "/models/rerank", headers=headers) |
| 114 | + |
| 115 | + response_list = [] |
| 116 | + for model in response.json()["data"]: |
| 117 | + response_list.append(model["id"]) |
| 118 | + |
| 119 | + return response_list |
0 commit comments