|
| 1 | +# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. ========= |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +# See the License for the specific language governing permissions and |
| 12 | +# limitations under the License. |
| 13 | +# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. ========= |
| 14 | +import os |
| 15 | +from typing import Any, Dict, List, Union |
| 16 | + |
| 17 | +import requests |
| 18 | + |
| 19 | +from camel.retrievers import BaseRetriever |
| 20 | +from camel.types.enums import JinaRerankerModelType |
| 21 | + |
| 22 | +DEFAULT_TOP_K_RESULTS = 1 |
| 23 | +JINA_RERANK_API_URL = "https://api.jina.ai/v1/rerank" |
| 24 | + |
| 25 | + |
| 26 | +class JinaRerankRetriever(BaseRetriever): |
| 27 | + r"""An implementation of the `BaseRetriever` using the `Jina AI Reranker` |
| 28 | + model. |
| 29 | +
|
| 30 | + This retriever uses Jina AI's reranking API to re-order retrieved documents |
| 31 | + based on their relevance to the query. It supports multilingual retrieval |
| 32 | + across 100+ languages. |
| 33 | +
|
| 34 | + Attributes: |
| 35 | + model_name (Union[JinaRerankerModelType, str]): The model name to use |
| 36 | + for re-ranking. |
| 37 | + api_key (str, optional): The API key for authenticating with the |
| 38 | + Jina AI service. |
| 39 | +
|
| 40 | + References: |
| 41 | + https://jina.ai/reranker/ |
| 42 | + """ |
| 43 | + |
| 44 | + def __init__( |
| 45 | + self, |
| 46 | + model_name: Union[JinaRerankerModelType, str] = ( |
| 47 | + JinaRerankerModelType.JINA_RERANKER_V2_BASE_MULTILINGUAL |
| 48 | + ), |
| 49 | + api_key: str | None = None, |
| 50 | + ) -> None: |
| 51 | + r"""Initializes an instance of the JinaRerankRetriever. This |
| 52 | + constructor sets up the API key for interacting with the Jina AI |
| 53 | + Reranker API. |
| 54 | +
|
| 55 | + Args: |
| 56 | + model_name (Union[JinaRerankerModelType, str]): The name of the |
| 57 | + model to be used for re-ranking. Can be a JinaRerankerModelType |
| 58 | + enum value or a string. Defaults to |
| 59 | + `JinaRerankerModelType.JINA_RERANKER_V2_BASE_MULTILINGUAL`. |
| 60 | + api_key (Optional[str]): The API key for authenticating requests |
| 61 | + to the Jina AI API. If not provided, the method will attempt to |
| 62 | + retrieve the key from the environment variable 'JINA_API_KEY'. |
| 63 | +
|
| 64 | + Raises: |
| 65 | + ValueError: If the API key is neither passed as an argument nor |
| 66 | + set in the environment variable. |
| 67 | + """ |
| 68 | + self.api_key = api_key or os.environ.get("JINA_API_KEY") |
| 69 | + if not self.api_key: |
| 70 | + raise ValueError( |
| 71 | + "Must pass in Jina API key or specify via JINA_API_KEY" |
| 72 | + " environment variable." |
| 73 | + ) |
| 74 | + # Handle both enum and string values for model_name |
| 75 | + if isinstance(model_name, JinaRerankerModelType): |
| 76 | + self.model_name = model_name.value |
| 77 | + else: |
| 78 | + self.model_name = model_name |
| 79 | + |
| 80 | + def query( |
| 81 | + self, |
| 82 | + query: str, |
| 83 | + retrieved_result: list[dict[str, Any]], |
| 84 | + top_k: int = DEFAULT_TOP_K_RESULTS, |
| 85 | + ) -> List[Dict[str, Any]]: |
| 86 | + r"""Queries and compiles results using the Jina AI re-ranking model. |
| 87 | +
|
| 88 | + Args: |
| 89 | + query (str): Query string for information retriever. |
| 90 | + retrieved_result (List[Dict[str, Any]]): The content to be |
| 91 | + re-ranked, should be the output from `BaseRetriever` like |
| 92 | + `VectorRetriever`. Each dict should have a 'text' key |
| 93 | + containing the document text. |
| 94 | + top_k (int, optional): The number of top results to return during |
| 95 | + retrieval. Must be a positive integer. Defaults to |
| 96 | + `DEFAULT_TOP_K_RESULTS`. |
| 97 | +
|
| 98 | + Returns: |
| 99 | + List[Dict[str, Any]]: Concatenated list of the query results, |
| 100 | + each containing the original data plus a 'similarity score'. |
| 101 | +
|
| 102 | + Raises: |
| 103 | + requests.exceptions.RequestException: If the API request fails. |
| 104 | + """ |
| 105 | + # Extract text content for reranking |
| 106 | + documents = [] |
| 107 | + for item in retrieved_result: |
| 108 | + if isinstance(item, dict): |
| 109 | + # Try common keys for text content |
| 110 | + text = item.get('text') or item.get('content') or str(item) |
| 111 | + else: |
| 112 | + text = str(item) |
| 113 | + documents.append(text) |
| 114 | + |
| 115 | + headers = { |
| 116 | + "Authorization": f"Bearer {self.api_key}", |
| 117 | + "Content-Type": "application/json", |
| 118 | + } |
| 119 | + |
| 120 | + payload = { |
| 121 | + "model": self.model_name, |
| 122 | + "query": query, |
| 123 | + "documents": documents, |
| 124 | + "top_n": top_k, |
| 125 | + } |
| 126 | + |
| 127 | + response = requests.post( |
| 128 | + JINA_RERANK_API_URL, |
| 129 | + headers=headers, |
| 130 | + json=payload, |
| 131 | + timeout=30, |
| 132 | + ) |
| 133 | + response.raise_for_status() |
| 134 | + |
| 135 | + rerank_response = response.json() |
| 136 | + |
| 137 | + formatted_results = [] |
| 138 | + for result in rerank_response.get("results", []): |
| 139 | + index = result.get("index", 0) |
| 140 | + relevance_score = result.get("relevance_score", 0.0) |
| 141 | + |
| 142 | + selected_chunk = retrieved_result[index].copy() |
| 143 | + selected_chunk['similarity score'] = relevance_score |
| 144 | + formatted_results.append(selected_chunk) |
| 145 | + |
| 146 | + return formatted_results |
0 commit comments