| 1 | from typing import List |
| 2 | import aiohttp |
| 3 | import asyncio |
| 4 | from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential |
| 5 | import logging |
| 6 | |
| 7 | |
| 8 | class RerankerBgeSiliconapi: |
| 9 | def __init__( |
| 10 | self, |
| 11 | api_key: str, |
| 12 | base_url: str, |
| 13 | model: str = "BAAI/bge-reranker-v2-m3", |
| 14 | ): |
| 15 | self.api_key = api_key |
| 16 | self.base_url = base_url |
| 17 | self.model = model |
| 18 | # return_documents: bool = True, |
| 19 | |
| 20 | |
| 21 | @retry( |
| 22 | stop=stop_after_attempt(3), |
| 23 | wait=wait_exponential(multiplier=1, max=30), |
| 24 | retry=retry_if_exception_type((aiohttp.ClientError, asyncio.TimeoutError)), |
| 25 | reraise=True, |
| 26 | after=lambda retry_state: logging.warning(f"Retrying SiliconReranker due to error: {retry_state.outcome.exception()}"), |
| 27 | ) |
| 28 | async def __call__( |
| 29 | self, |
| 30 | documents: List[str], |
| 31 | query: str, |
| 32 | top_n: int, |
| 33 | ) -> List[str]: |
| 34 | |
| 35 | url = f"{self.base_url}/rerank" |
| 36 | |
| 37 | payload = { |
| 38 | "model": self.model, |
| 39 | "query": query, |
| 40 | "documents": documents, |
| 41 | "top_n": top_n, |
| 42 | "return_documents": True, |
| 43 | } |
| 44 | |
| 45 | |
| 46 | headers = { |
| 47 | 'Accept': 'application/json', |
| 48 | 'Authorization': f'Bearer {self.api_key}', |
| 49 | 'Content-Type': 'application/json' |
| 50 | } |
| 51 | |
| 52 | async with aiohttp.ClientSession() as session: |
| 53 | async with session.post(url, json=payload, headers=headers) as resp: |
| 54 | response = await resp.json() |
| 55 | if resp.status >= 400: |
| 56 | raise RuntimeError(f"Rerank request failed with HTTP {resp.status}: {response}") |
| 57 | |
| 58 | |
| 59 | """ |
| 60 | { |
| 61 | "id": "<string>", |
| 62 | "results": [ |
| 63 | { |
| 64 | "document": { |
| 65 | "text": "<string>" |
| 66 | }, |
| 67 | "index": 123, |
| 68 | "relevance_score": 123 |
| 69 | } |
| 70 | ], |
| 71 | "tokens": { |
| 72 | "input_tokens": 123, |
| 73 | "output_tokens": 123 |
| 74 | } |
| 75 | } |
| 76 | """ |
| 77 | |
| 78 | results = [] |
| 79 | |
| 80 | for result in response["results"]: |
| 81 | results.append((result["document"]["text"], result["relevance_score"])) |
| 82 | |
| 83 | return results |