|
| 1 | +# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. ========= |
| 14 | +from typing import List, Optional, Tuple |
| 15 | + |
| 16 | +import torch |
| 17 | +from transformers import AutoModel |
| 18 | + |
| 19 | +from camel.toolkits import FunctionTool |
| 20 | +from camel.toolkits.base import BaseToolkit |
| 21 | +from camel.utils import MCPServer |
| 22 | + |
| 23 | + |
| 24 | +@MCPServer() |
| 25 | +class JinaRerankerToolkit(BaseToolkit): |
| 26 | + r"""A class representing a toolkit for reranking documents |
| 27 | + using Jina Reranker. |
| 28 | +
|
| 29 | + This class provides methods for reranking documents (text or images) |
| 30 | + based on their relevance to a given query using the Jina Reranker model. |
| 31 | + """ |
| 32 | + |
| 33 | + def __init__( |
| 34 | + self, |
| 35 | + timeout: Optional[float] = None, |
| 36 | + device: Optional[str] = None, |
| 37 | + ) -> None: |
| 38 | + r"""Initializes a new instance of the JinaRerankerToolkit class. |
| 39 | +
|
| 40 | + Args: |
| 41 | + timeout (Optional[float]): The timeout value for API requests |
| 42 | + in seconds. If None, no timeout is applied. |
| 43 | + (default: :obj:`None`) |
| 44 | + device (Optional[str]): Device to load the model on. If None, |
| 45 | + will use CUDA if available, otherwise CPU. |
| 46 | + (default: :obj:`None`) |
| 47 | + """ |
| 48 | + super().__init__(timeout=timeout) |
| 49 | + |
| 50 | + self.model = AutoModel.from_pretrained( |
| 51 | + 'jinaai/jina-reranker-m0', |
| 52 | + torch_dtype="auto", |
| 53 | + trust_remote_code=True, |
| 54 | + ) |
| 55 | + DEVICE = ( |
| 56 | + device |
| 57 | + if device is not None |
| 58 | + else ("cuda" if torch.cuda.is_available() else "cpu") |
| 59 | + ) |
| 60 | + self.model.to(DEVICE) |
| 61 | + self.model.eval() |
| 62 | + |
| 63 | + def _sort_documents( |
| 64 | + self, documents: List[str], scores: List[float] |
| 65 | + ) -> List[Tuple[str, float]]: |
| 66 | + r"""Sort documents by their scores in descending order. |
| 67 | +
|
| 68 | + Args: |
| 69 | + documents (List[str]): List of documents to sort. |
| 70 | + scores (List[float]): Corresponding scores for each document. |
| 71 | +
|
| 72 | + Returns: |
| 73 | + List[Tuple[str, float]]: Sorted list of (document, score) pairs. |
| 74 | +
|
| 75 | + Raises: |
| 76 | + ValueError: If documents and scores have different lengths. |
| 77 | + """ |
| 78 | + if len(documents) != len(scores): |
| 79 | + raise ValueError("Number of documents must match number of scores") |
| 80 | + doc_score_pairs = list(zip(documents, scores)) |
| 81 | + doc_score_pairs.sort(key=lambda x: x[1], reverse=True) |
| 82 | + |
| 83 | + return doc_score_pairs |
| 84 | + |
| 85 | + def rerank_text_documents( |
| 86 | + self, |
| 87 | + query: str, |
| 88 | + documents: List[str], |
| 89 | + max_length: int = 1024, |
| 90 | + ) -> List[Tuple[str, float]]: |
| 91 | + r"""Reranks text documents based on their relevance to a text query. |
| 92 | +
|
| 93 | + Args: |
| 94 | + query (str): The text query for reranking. |
| 95 | + documents (List[str]): List of text documents to be reranked. |
| 96 | + max_length (int): Maximum token length for processing. |
| 97 | + (default: :obj:`1024`) |
| 98 | +
|
| 99 | + Returns: |
| 100 | + List[Tuple[str, float]]: A list of tuples containing |
| 101 | + the reranked documents and their relevance scores. |
| 102 | + """ |
| 103 | + if self.model is None: |
| 104 | + raise ValueError( |
| 105 | + "Model has not been initialized or failed to initialize." |
| 106 | + ) |
| 107 | + |
| 108 | + with torch.inference_mode(): |
| 109 | + text_pairs = [[query, doc] for doc in documents] |
| 110 | + scores = self.model.compute_score( |
| 111 | + text_pairs, max_length=max_length, doc_type="text" |
| 112 | + ) |
| 113 | + |
| 114 | + return self._sort_documents(documents, scores) |
| 115 | + |
| 116 | + def rerank_image_documents( |
| 117 | + self, |
| 118 | + query: str, |
| 119 | + documents: List[str], |
| 120 | + max_length: int = 2048, |
| 121 | + ) -> List[Tuple[str, float]]: |
| 122 | + r"""Reranks image documents based on their relevance to a text query. |
| 123 | +
|
| 124 | + Args: |
| 125 | + query (str): The text query for reranking. |
| 126 | + documents (List[str]): List of image URLs or paths to be reranked. |
| 127 | + max_length (int): Maximum token length for processing. |
| 128 | + (default: :obj:`2048`) |
| 129 | +
|
| 130 | + Returns: |
| 131 | + List[Tuple[str, float]]: A list of tuples containing |
| 132 | + the reranked image URLs/paths and their relevance scores. |
| 133 | + """ |
| 134 | + if self.model is None: |
| 135 | + raise ValueError( |
| 136 | + "Model has not been initialized or failed to initialize." |
| 137 | + ) |
| 138 | + |
| 139 | + with torch.inference_mode(): |
| 140 | + image_pairs = [[query, doc] for doc in documents] |
| 141 | + scores = self.model.compute_score( |
| 142 | + image_pairs, max_length=max_length, doc_type="image" |
| 143 | + ) |
| 144 | + |
| 145 | + return self._sort_documents(documents, scores) |
| 146 | + |
| 147 | + def image_query_text_documents( |
| 148 | + self, |
| 149 | + image_query: str, |
| 150 | + documents: List[str], |
| 151 | + max_length: int = 2048, |
| 152 | + ) -> List[Tuple[str, float]]: |
| 153 | + r"""Reranks text documents based on their relevance to an image query. |
| 154 | +
|
| 155 | + Args: |
| 156 | + image_query (str): The image URL or path used as query. |
| 157 | + documents (List[str]): List of text documents to be reranked. |
| 158 | + max_length (int): Maximum token length for processing. |
| 159 | + (default: :obj:`2048`) |
| 160 | +
|
| 161 | + Returns: |
| 162 | + List[Tuple[str, float]]: A list of tuples containing |
| 163 | + the reranked documents and their relevance scores. |
| 164 | + """ |
| 165 | + if self.model is None: |
| 166 | + raise ValueError("Model has not been initialized.") |
| 167 | + with torch.inference_mode(): |
| 168 | + image_pairs = [[image_query, doc] for doc in documents] |
| 169 | + scores = self.model.compute_score( |
| 170 | + image_pairs, |
| 171 | + max_length=max_length, |
| 172 | + query_type="image", |
| 173 | + doc_type="text", |
| 174 | + ) |
| 175 | + |
| 176 | + return self._sort_documents(documents, scores) |
| 177 | + |
| 178 | + def image_query_image_documents( |
| 179 | + self, |
| 180 | + image_query: str, |
| 181 | + documents: List[str], |
| 182 | + max_length: int = 2048, |
| 183 | + ) -> List[Tuple[str, float]]: |
| 184 | + r"""Reranks image documents based on their relevance to an image query. |
| 185 | +
|
| 186 | + Args: |
| 187 | + image_query (str): The image URL or path used as query. |
| 188 | + documents (List[str]): List of image URLs or paths to be reranked. |
| 189 | + max_length (int): Maximum token length for processing. |
| 190 | + (default: :obj:`2048`) |
| 191 | +
|
| 192 | + Returns: |
| 193 | + List[Tuple[str, float]]: A list of tuples containing |
| 194 | + the reranked image URLs/paths and their relevance scores. |
| 195 | + """ |
| 196 | + if self.model is None: |
| 197 | + raise ValueError("Model has not been initialized.") |
| 198 | + |
| 199 | + with torch.inference_mode(): |
| 200 | + image_pairs = [[image_query, doc] for doc in documents] |
| 201 | + scores = self.model.compute_score( |
| 202 | + image_pairs, |
| 203 | + max_length=max_length, |
| 204 | + query_type="image", |
| 205 | + doc_type="image", |
| 206 | + ) |
| 207 | + |
| 208 | + return self._sort_documents(documents, scores) |
| 209 | + |
| 210 | + def get_tools(self) -> List[FunctionTool]: |
| 211 | + r"""Returns a list of FunctionTool objects representing the |
| 212 | + functions in the toolkit. |
| 213 | +
|
| 214 | + Returns: |
| 215 | + List[FunctionTool]: A list of FunctionTool objects |
| 216 | + representing the functions in the toolkit. |
| 217 | + """ |
| 218 | + return [ |
| 219 | + FunctionTool(self.rerank_text_documents), |
| 220 | + FunctionTool(self.rerank_image_documents), |
| 221 | + FunctionTool(self.image_query_text_documents), |
| 222 | + FunctionTool(self.image_query_image_documents), |
| 223 | + ] |
0 commit comments