Model Factory
rankify.generator.models.model_factory
FiDModel
Bases: BaseRAGModel
FiD (Fusion-in-Decoder) Generator for Open-Domain Question Answering.
Fusion-in-Decoder (FiD) is a retrieval-augmented generation (RAG) model that
aggregates information from multiple retrieved passages to generate context-aware answers.
Inside Rankifys architecture, this model is an exception, it subclasses BaseRAGModel but also includes the logic
of the FiD RAG method, since this RAG technique relies on the full transformer architecture.
Attributes:
| Name | Type | Description |
|---|---|---|
device |
str
|
Device used for inference ( |
model_path |
str
|
Path to the downloaded and extracted model. |
tokenizer |
T5Tokenizer
|
T5 tokenizer for text encoding. |
model |
FiDT5
|
Pretrained FiD model for text generation. |
max_length |
int
|
Maximum length of the generated output (default: 50 tokens). |
References
- Izacard & Grave Leveraging Passage Retrieval with Generative Models for Open-Domain QA
Paper
See Also
BaseRAGModel: Parent class for FiDModel.RAG-based QA Models: FiD falls under retrieval-augmented generation.
Example
from rankify.dataset.dataset import Document, Question, Answer, Context
from rankify.generator.generator import Generator
# Define question and answer
question = Question("What is the capital of France?")
answers = Answer([""])
contexts = [
Context(id=1, title="France", text="The capital of France is Paris.", score=0.9),
Context(id=2, title="Germany", text="Berlin is the capital of Germany.", score=0.5)
]
# Construct document
doc = Document(question=question, answers=answers, contexts=contexts)
# Initialize Generator (e.g., Meta Llama)
generator = Generator(method="fid", model_name='nq_reader_base', backend="fid")
# Generate answer
generated_answers = generator.generate([doc])
print(generated_answers) # Output: ["Paris"]
Notes
- FiD combines multiple passages to generate better responses.
- It integrates seamlessly with the
Generatorclass. - Uses retrieval-augmented generation (RAG) techniques for QA.
Source code in rankify/generator/models/fid_model.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | |
__init__(method='fid', model_name='nq_reader_base', **kwargs)
Initializes the FiDModel for retrieval-augmented generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
The generator type (default: |
'fid'
|
model_name
|
str
|
The specific FiD model to use (e.g., |
'nq_reader_base'
|
max_length
|
int
|
Maximum length of generated answers (default: 50). |
required |
device
|
str
|
Device for inference ( |
required |
**kwargs
|
Additional parameters for model configuration. |
{}
|
Sets up device, downloads and loads the model and tokenizer, and configures generation parameters.
Example
Source code in rankify/generator/models/fid_model.py
generate(documents)
Generates answers for a list of documents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
documents
|
List[Document]
|
A list of documents with queries and retrieved contexts. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List[str]: A list of generated answers. |
Example
Source code in rankify/generator/models/fid_model.py
LitellmModel
Bases: BaseRAGModel
LiteLLM Model for Retrieval-Augmented Generation (RAG).
This class integrates LiteLLM's API for text generation in a RAG pipeline. It uses the LiteLLM API to generate responses based on input prompts.
Attributes:
| Name | Type | Description |
|---|---|---|
model_name |
str
|
Name of the LiteLLM model. |
prompt_generator |
PromptGenerator
|
Instance for generating prompts. |
client |
LitellmClient
|
Client for interacting with the LiteLLM API. |
Notes
- This model uses LiteLLM's API for text generation.
- It supports additional parameters like
max_tokensandtemperature.
Source code in rankify/generator/models/litellm_model.py
__init__(model_name, api_key, prompt_generator)
Initialize the LitellmModel with the LitellmClient.
:param model_name: Name of the LiteLLM model. :param api_key: API key for LiteLLM. :param prompt_generator: Instance of PromptGenerator for generating prompts.
Source code in rankify/generator/models/litellm_model.py
generate(prompt, **kwargs)
Generate a response using LiteLLM's API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
The input prompt for the model. |
required |
**kwargs
|
Additional parameters for the LiteLLM API call, such as: - model (str): Model name to use (default: self.model_name). - max_tokens (int): Maximum number of tokens to generate (default: 128). - temperature (float): Sampling temperature (default: 0.7). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The generated response as a string. |
Notes
- Default parameters: model=self.model_name, max_tokens=128, temperature=0.7.
- All generation parameters can be overridden via
kwargs.
Source code in rankify/generator/models/litellm_model.py
OpenAIModel
Bases: BaseRAGModel
OpenAI Model for Retrieval-Augmented Generation (RAG).
This class integrates OpenAI's GPT models for text generation in a RAG pipeline. It uses the OpenAI API to generate responses based on input prompts.
Attributes:
| Name | Type | Description |
|---|---|---|
model_name |
str
|
Name of the OpenAI model (e.g., "gpt-3.5-turbo"). |
prompt_generator |
PromptGenerator
|
Instance for generating prompts. |
client |
OpenaiClient
|
Client for interacting with the OpenAI API. |
Notes
- This model uses OpenAI's GPT models for text generation.
- It supports additional parameters like
max_tokensandtemperature.
Source code in rankify/generator/models/openai_model.py
__init__(model_name, api_keys, prompt_generator, base_url=None)
Initialize the OpenAIModel with the OpenaiClient.
:param model_name: Name of the OpenAI model (e.g., "gpt-3.5-turbo"). :param api_keys: List of API keys for OpenAI. :param prompt_generator: Instance of PromptGenerator for generating prompts. :param base_url: Optional base URL for the OpenAI API.
Source code in rankify/generator/models/openai_model.py
generate(prompt, **kwargs)
Generate a response using OpenAI's API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
The input prompt for the model. |
required |
**kwargs
|
Additional parameters for the OpenAI API call, such as: - model (str): Model name to use (default: self.model_name). - max_tokens (int): Maximum number of tokens to generate (default: 128). - temperature (float): Sampling temperature (default: 0.7). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The generated response as a string. |
Notes
- Default parameters: model=self.model_name, max_tokens=128, temperature=0.7.
- All generation parameters can be overridden via
kwargs.
Source code in rankify/generator/models/openai_model.py
BaseRAGModel
Bases: ABC
Base RAG Model for Retrieval-Augmented Generation (RAG).
This is an abstract base class for implementing LLM endpoints in rankify. It defines the interface for generating responses and optional embedding generation.
Methods:
| Name | Description |
|---|---|
generate |
str, **kwargs) -> str: Abstract method to generate a response based on the given prompt. |
embed |
str, **kwargs) -> List[float]: Optional method to generate embeddings for the given text. |
Notes
- This class serves as a blueprint for RAG models like
OpenAIModelandHuggingFaceModel. - The
embedmethod is optional and can be implemented if needed. - This class needs to be extended to include new LLM endpoints in Rankify.
Source code in rankify/generator/models/base_rag_model.py
generate(prompt, **kwargs)
abstractmethod
embed(text, **kwargs)
Optional: Generate embeddings for the given text.
HuggingFaceModel
Bases: BaseRAGModel
Hugging Face Model for Retrieval-Augmented Generation (RAG).
This class integrates Hugging Face's pretrained models for text generation in a RAG pipeline. It uses the Hugging Face Transformers library for tokenization and model inference.
Attributes:
| Name | Type | Description |
|---|---|---|
model_name |
str
|
Name of the Hugging Face model. |
tokenizer |
Tokenizer instance for encoding input text. |
|
model |
Pretrained Hugging Face model for text generation. |
|
prompt_generator |
PromptGenerator
|
Instance for generating prompts. |
stop_at_period |
bool
|
If True, cuts generated answer at the first period. |
Notes
- This model uses Hugging Face's Transformers library for text generation.
- Default generation parameters like
max_lengthandtemperaturecan be overridden.
Source code in rankify/generator/models/huggingface_model.py
generate(prompt, **kwargs)
Generates a response using the Hugging Face model and returns the answer(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
The input prompt for generation. |
required |
**kwargs
|
Optional generation parameters, such as: - max_new_tokens (int): Maximum number of new tokens to generate (default: 64). - do_sample (bool): Whether to use sampling (default: True). - num_return_sequences (int): Number of answers to generate (default: 1). - eos_token_id (int): End-of-sequence token ID (default: tokenizer.eos_token_id). - pad_token_id (int): Padding token ID (default: tokenizer.eos_token_id). - temperature (float): Sampling temperature (default: 0.1). - top_p (float): Nucleus sampling parameter (default: 1.0). |
{}
|
Returns:
| Type | Description |
|---|---|
|
str or List[str]: The generated answer(s). If |
Notes
- The answer is post-processed to remove the prompt and extra whitespace.
- If
stop_at_periodis True, the answer is truncated at the first period. - All generation parameters can be overridden via
kwargs.
Source code in rankify/generator/models/huggingface_model.py
VLLMModel
Bases: BaseRAGModel
vLLM Model for Retrieval-Augmented Generation (RAG).
This class integrates vLLM's API for text generation in a RAG pipeline. It uses the vLLM library to generate responses based on input prompts.
Attributes:
| Name | Type | Description |
|---|---|---|
model_name |
str
|
Name of the vLLM model. |
prompt_generator |
PromptGenerator
|
Instance for generating prompts. |
client |
LLM
|
Client for interacting with the vLLM library. |
Notes
- This model uses vLLM's library for text generation.
- It supports additional parameters like
max_tokensandtemperature. - Specialty: vLLM requires a
sampling_paramsdictionary to control decoding and sampling behavior, allowing fine-grained control over generation (e.g.,max_tokens,temperature,top_p, etc.).
Source code in rankify/generator/models/vllm_model.py
__init__(model_name, prompt_generator, **kwargs)
Initialize the VLLMModel with the vLLM client.
:param model_name: Name of the vLLM model. :param prompt_generator: Instance of PromptGenerator for generating prompts. :param device: Device to run the model on (default: "cuda").
Source code in rankify/generator/models/vllm_model.py
generate(prompt, **kwargs)
Generate a response using vLLM's API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
The input prompt for the model. |
required |
sampling_params
|
(dict, required in kwargs)
|
Dictionary of sampling parameters for vLLM generation, such as: - max_tokens (int): Maximum number of tokens to generate. - temperature (float): Sampling temperature. - top_p (float): Nucleus sampling parameter. - other vLLM-supported generation options. |
required |
**kwargs
|
Additional parameters for the vLLM API call. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The generated response as a string. |
Notes
sampling_paramscontrols the decoding and sampling behavior of the vLLM model.- Typical keys include
max_tokens,temperature,top_p, etc. - See vLLM documentation for all supported sampling parameters.
Example
```python answer = model.generate( "What is the capital of France?", sampling_params={"max_tokens": 64, "temperature": 0.7, "top_p": 0.9} )
```
Source code in rankify/generator/models/vllm_model.py
PromptGenerator
PromptGenerator for Retrieval-Augmented Generation (RAG).
This class manages prompt construction for different RAG methods and model types in Rankify. It selects and formats prompt templates based on the specified method and model, enabling flexible and consistent prompt generation.
Attributes:
| Name | Type | Description |
|---|---|---|
method |
str
|
The RAG method or strategy (e.g., "basic-rag", "chain-of-thought-rag"). |
prompt_template |
PromptTemplate
|
The prompt template used for formatting prompts. |
model_type |
str
|
The type of model (e.g., "huggingface", "openai"). |
Methods:
| Name | Description |
|---|---|
generate_user_prompt |
Generates a user prompt by formatting the question and contexts with the selected template. |
_select_template |
Selects the appropriate prompt template for the given method. |
Notes
- Supports custom prompt templates via the
custom_promptargument. - If no contexts are provided, generates prompts with only the question.
- Ensures consistent prompt formatting across different RAG methods and models.
- Automatically selects a default template if none is specified.
Source code in rankify/generator/prompt_generator.py
__init__(method, model_type, prompt_template=None)
Initialize the PromptGenerator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
The RAG method or strategy (e.g., "basic-rag", "chain-of-thought-rag"). |
required |
model_type
|
str
|
The type of model (e.g., "huggingface", "openai"). |
required |
prompt_template
|
PromptTemplate
|
Custom prompt template to use. If None, selects based on method. |
None
|
Notes
- If no custom template is provided, selects a default template for the specified method.
- Stores the method, model type, and selected prompt template for prompt generation.
Source code in rankify/generator/prompt_generator.py
generate_user_prompt(question, contexts, custom_prompt=None)
Generates a user prompt by formatting the question and contexts with the selected template.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
str
|
The question to be answered. |
required |
contexts
|
List[str]
|
List of context passages to include in the prompt. |
required |
custom_prompt
|
str
|
Custom prompt template string. If provided, overrides the default template. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted prompt string. |
Notes
- If no contexts are provided, generates a prompt with only the question.
- Custom prompt templates can use
{question}and{contexts}placeholders. - Ensures consistent prompt formatting for all RAG methods and models.
Source code in rankify/generator/prompt_generator.py
load_model(model_name, **kwargs)
Source code in rankify/utils/generator/huggingface_models/model_utils.py
load_tokenizer(model_name)
model_factory(model_name, backend, method, stop_at_period=False, **kwargs)
Factory function to instantiate and return the appropriate RAG model based on the backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
Name of the model to use (e.g., 'meta-llama/Meta-Llama-3.1-8B', 'nq_reader_base'). |
required |
backend
|
str
|
Backend type ('openai', 'huggingface', 'fid', 'litellm', 'vllm'). |
required |
method
|
str
|
RAG method or prompt strategy (e.g., 'zero-shot', 'fid'). |
required |
stop_at_period
|
bool
|
If True, truncate output at first period (default: False). |
False
|
**kwargs
|
Additional model-specific parameters, such as API keys or generation settings. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
BaseRAGModel |
BaseRAGModel
|
An instance of the selected model class, ready for text generation. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unsupported backend is specified. |
Notes
- Automatically initializes the required prompt generator.
- For 'openai', expects 'api_keys' in kwargs.
- For 'huggingface', loads tokenizer and model locally.
- For 'fid', instantiates Fusion-in-Decoder model.
- For 'litellm', expects 'api_key' in kwargs.
- For 'vllm', passes all kwargs to VLLMModel.