Skip to content

API Reranker

The API Reranker provides integration with external reranking APIs including Cohere, Jina, Voyage, and MixedBread.ai.

Supported Providers

Provider API Key Required Model
Cohere Yes rerank-english-v3.0
Jina Yes jina-reranker-v1-base-en
Voyage Yes rerank-lite-1
MixedBread.ai Yes mxbai-rerank-large-v1

Usage

from rankify.models.reranking import Reranking

reranker = Reranking(
    method="apiranker",
    model_name="cohere",
    api_key="your-cohere-api-key"
)
reranked_docs = reranker.rank([document])

API Reference

rankify.models.apiranker

URL = {'default': {'url': 'https://api.openai.com/v1', 'model_name': 'gpt-3.5-turbo-0125', 'class': OpenaiClient}, 'gpt-3.5': {'url': 'https://api.openai.com/v1', 'model_name': 'gpt-3.5-turbo-0125', 'class': OpenaiClient}, 'gpt-4': {'url': 'https://api.openai.com/v1', 'model_name': 'gpt-4o', 'class': OpenaiClient}, 'gpt-4-mini': {'url': 'https://api.openai.com/v1', 'model_name': 'gpt-4o-mini', 'class': OpenaiClient}, 'llamav3.1-8b': {'url': 'https://api.together.xyz/v1', 'model_name': 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo', 'class': OpenaiClient}, 'llamav3.1-70b': {'url': 'https://api.together.xyz/v1', 'model_name': 'meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo', 'class': OpenaiClient}, 'claude-3-5': {'url': 'https://api.anthropic.com', 'model_name': 'claude-3-5-sonnet-20241022', 'class': ClaudeClient}, 'cohere': {'url': 'https://api.cohere.ai/v2/rerank', 'model_name': 'rerank-english-v3.0'}, 'jina': {'url': 'https://api.jina.ai/v1/rerank', 'model_name': 'jina-reranker-v1-base-en'}, 'voyage': {'url': 'https://api.voyageai.com/v1/rerank', 'model_name': 'rerank-lite-1'}, 'mixedbread.ai': {'url': 'https://api.mixedbread.ai/v1/reranking', 'model_name': 'mixedbread-ai/mxbai-rerank-large-v1'}} module-attribute

API_DOCUMENT_KEY_MAPPING = {'mixedbread.ai': 'input', 'text-embeddings-inference': 'texts'} module-attribute

API_RETURN_DOCUMENTS_KEY_MAPPING = {'mixedbread.ai': 'return_input', 'text-embeddings-inference': 'return_text'} module-attribute

API_RESULTS_KEY_MAPPING = {'voyage': 'data', 'mixedbread.ai': 'data', 'text-embeddings-inference': None} module-attribute

API_SCORE_KEY_MAPPING = {'mixedbread.ai': 'score', 'text-embeddings-inference': 'score'} module-attribute

BaseRanking

Bases: ABC

An abstract base class for implementing different ranking models.

This class defines the interface for all ranking models, ensuring that all subclasses implement the required methods.

Attributes:

Name Type Description
method str

The name of the ranking method.

model_name str

The name of the model being used for ranking.

api_key str

An optional API key for accessing remote models or services.

Source code in rankify/models/base.py
class BaseRanking(ABC):
    """
    An abstract base class for implementing different ranking models.

    This class defines the interface for all ranking models, ensuring that all subclasses implement the required methods.

    Attributes:
        method (str): The name of the ranking method.
        model_name (str): The name of the model being used for ranking.
        api_key (str, optional): An optional API key for accessing remote models or services.
    """

    @abstractmethod
    def __init__(self, method: str= None, model_name: str= None, api_key: str= None, **kwargs) ->None:
        """
        Initializes the base ranking model.

        Args:
            method (str, optional): The name of the ranking method. Defaults to None.
            model_name (str, optional): The name of the model being used for ranking. Defaults to None.
            api_key (str, optional): An optional API key for accessing remote models or services. Defaults to None.

        Example:
            ```python
            class MyRanking(BaseRanking):
                def __init__(self, method, model_name):
                    super().__init__(method, model_name)
            ```
        """
        pass

    @abstractmethod
    def rank(self, documents: list[Document] ):
        """
        Abstract method to rank a list of documents.

        Args:
            documents (list[Document]): A list of Document instances that need to be ranked.

        Raises:
            NotImplementedError: This method must be implemented by subclasses.

        Example:
            ```python
            class MyRanking(BaseRanking):
                def __init__(self, method, model_name):
                    super().__init__(method, model_name)

                def rank(self, documents):
                    # Ranking implementation here
                    pass
            ```
        """
        pass

__init__(method=None, model_name=None, api_key=None, **kwargs) abstractmethod

Initializes the base ranking model.

Parameters:

Name Type Description Default
method str

The name of the ranking method. Defaults to None.

None
model_name str

The name of the model being used for ranking. Defaults to None.

None
api_key str

An optional API key for accessing remote models or services. Defaults to None.

None
Example
class MyRanking(BaseRanking):
    def __init__(self, method, model_name):
        super().__init__(method, model_name)
Source code in rankify/models/base.py
@abstractmethod
def __init__(self, method: str= None, model_name: str= None, api_key: str= None, **kwargs) ->None:
    """
    Initializes the base ranking model.

    Args:
        method (str, optional): The name of the ranking method. Defaults to None.
        model_name (str, optional): The name of the model being used for ranking. Defaults to None.
        api_key (str, optional): An optional API key for accessing remote models or services. Defaults to None.

    Example:
        ```python
        class MyRanking(BaseRanking):
            def __init__(self, method, model_name):
                super().__init__(method, model_name)
        ```
    """
    pass

rank(documents) abstractmethod

Abstract method to rank a list of documents.

Parameters:

Name Type Description Default
documents list[Document]

A list of Document instances that need to be ranked.

required

Raises:

Type Description
NotImplementedError

This method must be implemented by subclasses.

Example
class MyRanking(BaseRanking):
    def __init__(self, method, model_name):
        super().__init__(method, model_name)

    def rank(self, documents):
        # Ranking implementation here
        pass
Source code in rankify/models/base.py
@abstractmethod
def rank(self, documents: list[Document] ):
    """
    Abstract method to rank a list of documents.

    Args:
        documents (list[Document]): A list of Document instances that need to be ranked.

    Raises:
        NotImplementedError: This method must be implemented by subclasses.

    Example:
        ```python
        class MyRanking(BaseRanking):
            def __init__(self, method, model_name):
                super().__init__(method, model_name)

            def rank(self, documents):
                # Ranking implementation here
                pass
        ```
    """
    pass

Document

Represents a document consisting of a question, answers, and contexts.

Attributes:

Name Type Description
question Question

The question associated with the document.

answers Answer

The answers to the question.

contexts list[Context]

A list of related contexts.

reorder_contexts list[Context] or None

A reordered list of contexts based on relevance.

Source code in rankify/dataset/dataset.py
class Document:
    """
    Represents a document consisting of a question, answers, and contexts.

    Attributes:
        question (Question): The question associated with the document.
        answers (Answer): The answers to the question.
        contexts (list[Context]): A list of related contexts.
        reorder_contexts (list[Context] or None): A reordered list of contexts based on relevance.
    """
    def __init__(self, question: Question, answers: Answer, contexts: list = None , id: int = None) -> None:
        """
        Initializes a Document instance.

        Args:
            question (Question): The question associated with the document.
            answers (Answer): The answers to the question.
            contexts (list[Context], optional): A list of contexts related to the question.

        Example:
            ```python
            q = Question("What is the capital of France?")
            a = Answer(["Paris"])
            c1 = Context(score=0.9, has_answer=True, id=1, title="Paris", text="The capital of France is Paris.")
            c2 = Context(score=0.5, has_answer=False, id=2, title="Berlin", text="Berlin is the capital of Germany.")
            d = Document(question=q, answers=a, contexts=[c1, c2])
            print(d)
            ```
        """
        self.question: Question = question
        self.answers: Answer = answers
        self.contexts: List[Context] = contexts
        self.reorder_contexts: List[Context] = None
        self.id = str(id) 

    @classmethod
    def from_dict(cls, data: dict,n_docs:int=100) -> 'Document':
        """
        Creates a Document instance from a dictionary.

        Args:
            data (dict): A dictionary containing the question, answers, and contexts.
            n_docs (int, optional): The number of contexts to include. Defaults to 100.

        Returns:
            Document: A new Document instance.

        Example:
            ```python
            data = {
                "question": "What is the capital of France?",
                "answers": ["Paris"],
                "ctxs": [
                    {"score": 0.9, "has_answer": True, "id": 1, "title": "Paris", "text": "The capital of France is Paris."},
                    {"score": 0.5, "has_answer": False, "id": 2, "title": "Berlin", "text": "Berlin is the capital of Germany."}
                ]
            }
            d = Document.from_dict(data)
            print(d.question)
            ```
        """
        question = Question(data["question"])
        if "answers" in data:
            answers = Answer(data["answers"])
        else:
            answers =Answer('')

        if "query_id" in data:
            id = data["query_id"]
        else:
            id = None
        contexts = [Context(**ctx) for ctx in data["ctxs"][:n_docs]]
        return cls(question, answers, contexts, id=id)

    def to_dict(self) -> Dict[str, Optional[object]]:
        """
        Converts the document into a dictionary representation.

        Returns:
            dict: A dictionary containing the question, answers, and contexts.
        """
        return {
            "question": self.question.question,
            "answers": self.answers.answers,
            "contexts": [ctx.to_dict() for ctx in self.contexts]
        }
    def to_dict_reoreder(self) -> Dict[str,Optional[object]]:
        return {
            "question" : self.question.question,
            "answers" : self.answers.answers,
            "contexts" : [ctx.to_dict() for ctx in self.reorder_contexts]
        }
    def __str__(self) -> str:
        """
        Returns a string representation of the Document instance.

        Returns:
            str: The formatted document information.

        Example:
            ```python
            d = Document(Question("What is the capital of France?"), Answer(["Paris"]))
            print(d)
            ```
        """
        contexts_str = "\n\n".join([str(ctx) for ctx in self.contexts])
        reorder_contexts_str= ''
        if self.reorder_contexts is not None:
            reorder_contexts_str = "\n\n".join([str(ctx) for ctx in self.reorder_contexts])
        return f"{self.question}\n\n{self.answers}\n\nContext: \n\n{contexts_str}\nReorder contexts: \n\n{reorder_contexts_str}"

__init__(question, answers, contexts=None, id=None)

Initializes a Document instance.

Parameters:

Name Type Description Default
question Question

The question associated with the document.

required
answers Answer

The answers to the question.

required
contexts list[Context]

A list of contexts related to the question.

None
Example
q = Question("What is the capital of France?")
a = Answer(["Paris"])
c1 = Context(score=0.9, has_answer=True, id=1, title="Paris", text="The capital of France is Paris.")
c2 = Context(score=0.5, has_answer=False, id=2, title="Berlin", text="Berlin is the capital of Germany.")
d = Document(question=q, answers=a, contexts=[c1, c2])
print(d)
Source code in rankify/dataset/dataset.py
def __init__(self, question: Question, answers: Answer, contexts: list = None , id: int = None) -> None:
    """
    Initializes a Document instance.

    Args:
        question (Question): The question associated with the document.
        answers (Answer): The answers to the question.
        contexts (list[Context], optional): A list of contexts related to the question.

    Example:
        ```python
        q = Question("What is the capital of France?")
        a = Answer(["Paris"])
        c1 = Context(score=0.9, has_answer=True, id=1, title="Paris", text="The capital of France is Paris.")
        c2 = Context(score=0.5, has_answer=False, id=2, title="Berlin", text="Berlin is the capital of Germany.")
        d = Document(question=q, answers=a, contexts=[c1, c2])
        print(d)
        ```
    """
    self.question: Question = question
    self.answers: Answer = answers
    self.contexts: List[Context] = contexts
    self.reorder_contexts: List[Context] = None
    self.id = str(id) 

from_dict(data, n_docs=100) classmethod

Creates a Document instance from a dictionary.

Parameters:

Name Type Description Default
data dict

A dictionary containing the question, answers, and contexts.

required
n_docs int

The number of contexts to include. Defaults to 100.

100

Returns:

Name Type Description
Document Document

A new Document instance.

Example
data = {
    "question": "What is the capital of France?",
    "answers": ["Paris"],
    "ctxs": [
        {"score": 0.9, "has_answer": True, "id": 1, "title": "Paris", "text": "The capital of France is Paris."},
        {"score": 0.5, "has_answer": False, "id": 2, "title": "Berlin", "text": "Berlin is the capital of Germany."}
    ]
}
d = Document.from_dict(data)
print(d.question)
Source code in rankify/dataset/dataset.py
@classmethod
def from_dict(cls, data: dict,n_docs:int=100) -> 'Document':
    """
    Creates a Document instance from a dictionary.

    Args:
        data (dict): A dictionary containing the question, answers, and contexts.
        n_docs (int, optional): The number of contexts to include. Defaults to 100.

    Returns:
        Document: A new Document instance.

    Example:
        ```python
        data = {
            "question": "What is the capital of France?",
            "answers": ["Paris"],
            "ctxs": [
                {"score": 0.9, "has_answer": True, "id": 1, "title": "Paris", "text": "The capital of France is Paris."},
                {"score": 0.5, "has_answer": False, "id": 2, "title": "Berlin", "text": "Berlin is the capital of Germany."}
            ]
        }
        d = Document.from_dict(data)
        print(d.question)
        ```
    """
    question = Question(data["question"])
    if "answers" in data:
        answers = Answer(data["answers"])
    else:
        answers =Answer('')

    if "query_id" in data:
        id = data["query_id"]
    else:
        id = None
    contexts = [Context(**ctx) for ctx in data["ctxs"][:n_docs]]
    return cls(question, answers, contexts, id=id)

to_dict()

Converts the document into a dictionary representation.

Returns:

Name Type Description
dict Dict[str, Optional[object]]

A dictionary containing the question, answers, and contexts.

Source code in rankify/dataset/dataset.py
def to_dict(self) -> Dict[str, Optional[object]]:
    """
    Converts the document into a dictionary representation.

    Returns:
        dict: A dictionary containing the question, answers, and contexts.
    """
    return {
        "question": self.question.question,
        "answers": self.answers.answers,
        "contexts": [ctx.to_dict() for ctx in self.contexts]
    }

__str__()

Returns a string representation of the Document instance.

Returns:

Name Type Description
str str

The formatted document information.

Example
d = Document(Question("What is the capital of France?"), Answer(["Paris"]))
print(d)
Source code in rankify/dataset/dataset.py
def __str__(self) -> str:
    """
    Returns a string representation of the Document instance.

    Returns:
        str: The formatted document information.

    Example:
        ```python
        d = Document(Question("What is the capital of France?"), Answer(["Paris"]))
        print(d)
        ```
    """
    contexts_str = "\n\n".join([str(ctx) for ctx in self.contexts])
    reorder_contexts_str= ''
    if self.reorder_contexts is not None:
        reorder_contexts_str = "\n\n".join([str(ctx) for ctx in self.reorder_contexts])
    return f"{self.question}\n\n{self.answers}\n\nContext: \n\n{contexts_str}\nReorder contexts: \n\n{reorder_contexts_str}"

Context

Represents a context with metadata such as score and title.

Attributes:

Name Type Description
score float

The relevance score of the context.

has_answer bool

Whether the context contains an answer.

id int

The identifier of the context.

title str

The title of the context.

text str

The text of the context.

Source code in rankify/dataset/dataset.py
class Context:
    """
    Represents a context with metadata such as score and title.

    Attributes:
        score (float, optional): The relevance score of the context.
        has_answer (bool, optional): Whether the context contains an answer.
        id (int, optional): The identifier of the context.
        title (str, optional): The title of the context.
        text (str, optional): The text of the context.
    """
    def __init__(self, score: float=None, has_answer: bool=None, id: str=None, title: str=None, text: str=None)-> None:
        """
        Initializes a Context instance.

        Args:
            score (float, optional): The relevance score.
            has_answer (bool, optional): Whether the context contains an answer.
            id (int, optional): The identifier of the context.
            title (str, optional): The title of the context.
            text (str, optional): The text of the context.

        Example:
            ```python
            c = Context(score=0.9, has_answer=True, id=1, title="Paris", text="The capital of France is Paris.")
            print(c)
            ```
        """
        self.score: Optional[float] = score
        self.has_answer: Optional[bool] = has_answer
        self.id: Optional[str] = id
        self.title: Optional[str] = title
        self.text: Optional[str] = text

    def to_dict(self, save_text: bool=False) -> Dict[str, Optional[object]]:

        """
        Converts the Context instance to a dictionary.

        Args:
            save_text (bool): Whether to include text in the output dictionary.

        Returns:
            dict: The context data.

        Example:
            ```python
            c = Context(score=0.9, has_answer=True, id=1, title="Paris", text="The capital of France is Paris.")
            print(c.to_dict())
            ```
        """
        context_dict = {
            "score": float(self.score) if self.score is not None else None,
            "has_answer": self.has_answer,
            "id": self.id,
            }

        # Include 'text' only if save_text is True
        if save_text:
            context_dict["text"] = self.text
            context_dict["title"] =  self.title

        return context_dict
    def __str__(self) -> str:
        """
        Returns a string representation of the Context instance.

        Returns:
            str: The formatted context.

        Example:
            ```python
            c = Context(score=0.9, has_answer=True, id=1, title="Paris", text="The capital of France is Paris.")
            print(str(c))
            ```
        """
        return f"ID: {self.id}\nHas Answer: {self.has_answer}\nTitle: {self.title}\nText: {self.text}\nScore: {self.score}"

__init__(score=None, has_answer=None, id=None, title=None, text=None)

Initializes a Context instance.

Parameters:

Name Type Description Default
score float

The relevance score.

None
has_answer bool

Whether the context contains an answer.

None
id int

The identifier of the context.

None
title str

The title of the context.

None
text str

The text of the context.

None
Example
c = Context(score=0.9, has_answer=True, id=1, title="Paris", text="The capital of France is Paris.")
print(c)
Source code in rankify/dataset/dataset.py
def __init__(self, score: float=None, has_answer: bool=None, id: str=None, title: str=None, text: str=None)-> None:
    """
    Initializes a Context instance.

    Args:
        score (float, optional): The relevance score.
        has_answer (bool, optional): Whether the context contains an answer.
        id (int, optional): The identifier of the context.
        title (str, optional): The title of the context.
        text (str, optional): The text of the context.

    Example:
        ```python
        c = Context(score=0.9, has_answer=True, id=1, title="Paris", text="The capital of France is Paris.")
        print(c)
        ```
    """
    self.score: Optional[float] = score
    self.has_answer: Optional[bool] = has_answer
    self.id: Optional[str] = id
    self.title: Optional[str] = title
    self.text: Optional[str] = text

to_dict(save_text=False)

Converts the Context instance to a dictionary.

Parameters:

Name Type Description Default
save_text bool

Whether to include text in the output dictionary.

False

Returns:

Name Type Description
dict Dict[str, Optional[object]]

The context data.

Example
c = Context(score=0.9, has_answer=True, id=1, title="Paris", text="The capital of France is Paris.")
print(c.to_dict())
Source code in rankify/dataset/dataset.py
def to_dict(self, save_text: bool=False) -> Dict[str, Optional[object]]:

    """
    Converts the Context instance to a dictionary.

    Args:
        save_text (bool): Whether to include text in the output dictionary.

    Returns:
        dict: The context data.

    Example:
        ```python
        c = Context(score=0.9, has_answer=True, id=1, title="Paris", text="The capital of France is Paris.")
        print(c.to_dict())
        ```
    """
    context_dict = {
        "score": float(self.score) if self.score is not None else None,
        "has_answer": self.has_answer,
        "id": self.id,
        }

    # Include 'text' only if save_text is True
    if save_text:
        context_dict["text"] = self.text
        context_dict["title"] =  self.title

    return context_dict

__str__()

Returns a string representation of the Context instance.

Returns:

Name Type Description
str str

The formatted context.

Example
c = Context(score=0.9, has_answer=True, id=1, title="Paris", text="The capital of France is Paris.")
print(str(c))
Source code in rankify/dataset/dataset.py
def __str__(self) -> str:
    """
    Returns a string representation of the Context instance.

    Returns:
        str: The formatted context.

    Example:
        ```python
        c = Context(score=0.9, has_answer=True, id=1, title="Paris", text="The capital of France is Paris.")
        print(str(c))
        ```
    """
    return f"ID: {self.id}\nHas Answer: {self.has_answer}\nTitle: {self.title}\nText: {self.text}\nScore: {self.score}"

APIRanker

Bases: BaseRanking

A ranking model that leverages external API-based ranking services.

This class interacts with various API providers (e.g., cohere, jina, voyage, mixedbread.ai) to perform re-ranking of retrieved passages based on query relevance.

Attributes:

Name Type Description
model_name str

The model used for ranking by the API provider.

api_key str

The API key to access the ranking service.

api_provider str

The name of the API provider (e.g., "cohere", "jina", "voyage").

url str

The API endpoint URL.

headers dict

The headers required for making API requests.

Raises:

Type Description
ValueError

If the specified API provider is not supported.

References
Source code in rankify/models/apiranker.py
class APIRanker(BaseRanking):
    """
    A ranking model that leverages external API-based ranking services.

    This class interacts with various API providers (e.g., `cohere`, `jina`, `voyage`, `mixedbread.ai`)
    to perform re-ranking of retrieved passages based on query relevance.

    Attributes:
        model_name (str): The model used for ranking by the API provider.
        api_key (str): The API key to access the ranking service.
        api_provider (str): The name of the API provider (e.g., `"cohere"`, `"jina"`, `"voyage"`).
        url (str): The API endpoint URL.
        headers (dict): The headers required for making API requests.

    Raises:
        ValueError: If the specified API provider is not supported.

    References:
        - API Providers: [`Cohere`](https://cohere.com), [`Jina`](https://jina.ai), [`Voyage`](https://voyage.ai)
    """

    def __init__(self, method: str, model_name: str, api_key: str, **kwargs):
        """
        Initializes an APIRanker instance.

        Args:
            method (str): The ranking method.
            model_name (str): The model name for the API provider.
            api_key (str): The API key for the service.

        Raises:
            ValueError: If the specified API provider is not supported.

        Example:
            ```python
            from rankify.models.reranking import Reranking
            question = Question("Who discovered gravity?")
            contexts = [
                Context(text="Gravity was discovered by Newton", id=1),
                Context(text="Newton was a physicist", id=2)
            ]
            document = Document(question=question, contexts=contexts)

            model = Reranking(method="apiranker", model_name="cohere", api_key="your-api-key")
            ranked_docs = model.rank([document])
            ```
        """
        if model_name in URL:
            self.model_name = URL[model_name]['model_name']
            self.url = URL[model_name]['url']
        else:
            self.model_name = model_name
            self.url = kwargs.get("endpoint", None)

        self.api_key = api_key
        self.api_provider = model_name.lower()


        if not self.url:
            raise ValueError(f"Unsupported API provider: {self.api_provider}")

        self.headers = {
            "accept": "application/json",
            "content-type": "application/json",
            "Authorization": f"Bearer {self.api_key}",
        }

    def rank(self, documents: List[Document]) -> List[Document]:
        """
        Reranks the contexts within each document based on their relevance to the document's query.

        Args:
            documents (List[Document]): The documents whose contexts need to be ranked.

        Returns:
            List[Document]: The documents with reordered contexts.

        Example:
            ```python
            from rankify.models.reranking import Reranking
            question = Question("When was the light bulb invented?")
            contexts = [
                Context(text="Thomas Edison invented the light bulb in 1879", id=1),
                Context(text="Electricity was discovered earlier", id=2)
            ]
            document = Document(question=question, contexts=contexts)

            model = Reranking(method="apiranker", model_name="voyage", api_key="your-api-key")
            ranked_docs = model.rank([document])
            ```
        """
        for doc in tqdm(documents, desc="Reranking Documents"):
            query = doc.question.question
            payload = self._format_payload(query, doc.contexts)
            response = requests.post(self.url, headers=self.headers, data=payload)
            response_data = response.json()
            self._parse_response(response_data, doc)

        return documents

    def _format_payload(self, query: str, contexts: List[Context]) -> str:
        """
        Prepares the payload for the API request for a single document.

        Args:
            query (str): The query string.
            contexts (List[Context]): The contexts of a single document.

        Returns:
            str: The JSON payload.

        Example:
            ```python
            payload = model._format_payload("What is AI?", [Context("AI is artificial intelligence.", id=1)])
            print(payload)  # {"model": ..., "query": ..., "documents": ...}
            ```
        """
        top_key = "top_n" if self.api_provider not in ["voyage", "mixedbread.ai"] else "top_k"
        documents_key = API_DOCUMENT_KEY_MAPPING.get(self.api_provider, "documents")
        return_documents_key = API_RETURN_DOCUMENTS_KEY_MAPPING.get(self.api_provider, "return_documents")
        payload = {
            "model": self.model_name,
            "query": query,
            documents_key: [context.text for context in contexts],
            top_key: len(contexts),
            return_documents_key: True,
        }
        return json.dumps(payload)

    def _parse_response(self, response: dict, document: Document) -> None:
        """
        Parses the API response and assigns scores to each context in the document.

        Args:
            response (dict): The API response data.
            document (Document): The document whose contexts are being ranked.

        Returns:
            None

        Example:
            ```python
            response = {
                "results": [
                    {"document": {"text": "Newton discovered gravity."}, "relevance_score": 0.98},
                    {"document": {"text": "Einstein developed relativity."}, "relevance_score": 0.75}
                ]
            }
            model._parse_response(response, document)
            ```
        """
        results_key = API_RESULTS_KEY_MAPPING.get(self.api_provider, "results")
        score_key = API_SCORE_KEY_MAPPING.get(self.api_provider, "relevance_score")

        results = response.get(results_key, response)

        # Create a list to hold the reordered contexts
        reordered_contexts = []

        # Map each result to a context
        for result in results:
            # Extract text and score

            if self.api_provider == "voyage":
                text = result.get("document", {})
            else:
                text = result.get("document", {}).get("text", "")

            score = result.get(score_key, 0.0)

            # Find the matching context in the original list
            matching_context = next((context for context in document.contexts if context.text == text), None)
            if matching_context:
                # Update score and add to reordered list
                matching_context.score = score
                reordered_contexts.append(matching_context)

        # Assign reordered contexts directly from the API response order
        document.reorder_contexts = reordered_contexts

__init__(method, model_name, api_key, **kwargs)

Initializes an APIRanker instance.

Parameters:

Name Type Description Default
method str

The ranking method.

required
model_name str

The model name for the API provider.

required
api_key str

The API key for the service.

required

Raises:

Type Description
ValueError

If the specified API provider is not supported.

Example
from rankify.models.reranking import Reranking
question = Question("Who discovered gravity?")
contexts = [
    Context(text="Gravity was discovered by Newton", id=1),
    Context(text="Newton was a physicist", id=2)
]
document = Document(question=question, contexts=contexts)

model = Reranking(method="apiranker", model_name="cohere", api_key="your-api-key")
ranked_docs = model.rank([document])
Source code in rankify/models/apiranker.py
def __init__(self, method: str, model_name: str, api_key: str, **kwargs):
    """
    Initializes an APIRanker instance.

    Args:
        method (str): The ranking method.
        model_name (str): The model name for the API provider.
        api_key (str): The API key for the service.

    Raises:
        ValueError: If the specified API provider is not supported.

    Example:
        ```python
        from rankify.models.reranking import Reranking
        question = Question("Who discovered gravity?")
        contexts = [
            Context(text="Gravity was discovered by Newton", id=1),
            Context(text="Newton was a physicist", id=2)
        ]
        document = Document(question=question, contexts=contexts)

        model = Reranking(method="apiranker", model_name="cohere", api_key="your-api-key")
        ranked_docs = model.rank([document])
        ```
    """
    if model_name in URL:
        self.model_name = URL[model_name]['model_name']
        self.url = URL[model_name]['url']
    else:
        self.model_name = model_name
        self.url = kwargs.get("endpoint", None)

    self.api_key = api_key
    self.api_provider = model_name.lower()


    if not self.url:
        raise ValueError(f"Unsupported API provider: {self.api_provider}")

    self.headers = {
        "accept": "application/json",
        "content-type": "application/json",
        "Authorization": f"Bearer {self.api_key}",
    }

rank(documents)

Reranks the contexts within each document based on their relevance to the document's query.

Parameters:

Name Type Description Default
documents List[Document]

The documents whose contexts need to be ranked.

required

Returns:

Type Description
List[Document]

List[Document]: The documents with reordered contexts.

Example
from rankify.models.reranking import Reranking
question = Question("When was the light bulb invented?")
contexts = [
    Context(text="Thomas Edison invented the light bulb in 1879", id=1),
    Context(text="Electricity was discovered earlier", id=2)
]
document = Document(question=question, contexts=contexts)

model = Reranking(method="apiranker", model_name="voyage", api_key="your-api-key")
ranked_docs = model.rank([document])
Source code in rankify/models/apiranker.py
def rank(self, documents: List[Document]) -> List[Document]:
    """
    Reranks the contexts within each document based on their relevance to the document's query.

    Args:
        documents (List[Document]): The documents whose contexts need to be ranked.

    Returns:
        List[Document]: The documents with reordered contexts.

    Example:
        ```python
        from rankify.models.reranking import Reranking
        question = Question("When was the light bulb invented?")
        contexts = [
            Context(text="Thomas Edison invented the light bulb in 1879", id=1),
            Context(text="Electricity was discovered earlier", id=2)
        ]
        document = Document(question=question, contexts=contexts)

        model = Reranking(method="apiranker", model_name="voyage", api_key="your-api-key")
        ranked_docs = model.rank([document])
        ```
    """
    for doc in tqdm(documents, desc="Reranking Documents"):
        query = doc.question.question
        payload = self._format_payload(query, doc.contexts)
        response = requests.post(self.url, headers=self.headers, data=payload)
        response_data = response.json()
        self._parse_response(response_data, doc)

    return documents