Utils
LLM models
llama_utils.utils.models
LLMs and embedding models.
LLMModel
Abstraction layer for different LLM providers: AzureOpenAI, Ollama, and HuggingFace.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_type
|
str
|
Type of the model ('azure', 'ollama', 'huggingface'). |
required |
**kwargs
|
dict
|
Additional parameters for the model initialization. |
{}
|
Examples:
Initialize an Azure OpenAI model: >>> from llama_utils.utils.models import LLMModel >>> from dotenv import load_dotenv >>> load_dotenv() # doctest: +SKIP >>> model = LLMModel(model_type='azure', model_id='gpt-4o', engine='4o') # doctest: +SKIP >>> print(model.base_model.model) # doctest: +SKIP gpt-4o >>> response = model.generate_response("Hello, how are you?") # doctest: +SKIP >>> print(response) # doctest: +SKIP Hello! I'm just a computer program, so I don't have feelings, but I'm here and ready to help you. How can I assist you today?
Initialize an Ollama model: >>> model = LLMModel(model_type='ollama', model_id='llama3.1') >>> response = model.generate_response("Hello, how are you?") # doctest: +SKIP >>> print(response) # doctest: +SKIP I'm just a language model, I don't have emotions or feelings like humans do, so I don't have good or bad days. However, I'm functioning properly and ready to help with any questions or tasks you may have! How about you? How's your day going?
Initialize a HuggingFace model: >>> import os >>> cache_dir = os.getenv("CACHE_DIR") >>> model_kwargs = {} >>> model_kwargs["cache_dir"] = cache_dir >>> model_name = "distilgpt2" >>> model = LLMModel( ... model_type='huggingface', model_name=model_name, tokenizer_name=model_name, model_kwargs=model_kwargs ... ) >>> response = model.generate_response("Hello, how are you?") # doctest: +SKIP >>> print(response) # doctest: +SKIP
Source code in src/llama_utils/utils/models.py
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 |
|
base_model
property
Get the base model.
model_type
property
Get the model type.
__init__(model_type: str, **kwargs)
Initialize the LLM model.
Source code in src/llama_utils/utils/models.py
296 297 298 299 |
|
generate_response(prompt: str, **kwargs)
Generate a response from the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prompt
|
str
|
The input prompt. |
required |
**kwargs
|
dict
|
Additional parameters for generation. |
{}
|
Returns:
Type | Description |
---|---|
str
|
Generated response. |
Examples:
Generate response using Azure OpenAI:
>>> model = LLMModel(model_type='azure', model_id='gpt-4o')
>>> response = model.generate_response("What is AI?")
>>> print(response)
Generate response using Ollama:
>>> model = LLMModel(model_type='ollama', model_id='llama3')
>>> response = model.generate_response("Explain quantum mechanics.")
>>> print(response)
Generate response using HuggingFace:
>>> model = LLMModel(model_type='huggingface', model_name='distilgpt2')
>>> response = model.generate_response("Write a poem about the sea.")
>>> print(response)
Source code in src/llama_utils/utils/models.py
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 |
|
azure_open_ai(model_id: str = 'gpt-4o', engine: str = '4o')
Get the Azure OpenAI model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_id
|
str
|
The model ID. |
'gpt-4o'
|
engine
|
str
|
The engine. |
'4o'
|
Returns:
Type | Description |
---|---|
AzureOpenAI
|
The Azure OpenAI model. |
Raises:
Type | Description |
---|---|
ImportError
|
If the |
Examples:
>>> from llama_utils.utils.models import azure_open_ai
>>> from dotenv import load_dotenv
>>> load_dotenv()
>>> llm = azure_open_ai()
>>> print(llm.model)
gpt-4o
>>> print(llm.metadata)
context_window=128000 num_output=-1 is_chat_model=True is_function_calling_model=True model_name='gpt-4o' system_role=<MessageRole.SYSTEM: 'system'>
Source code in src/llama_utils/utils/models.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 |
|
get_hugging_face_embedding(model_name: str = 'BAAI/bge-small-en-v1.5', cache_folder: str = None)
Get the hugging face embedding model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_name
|
str
|
Name of the hugging face embedding model. |
'BAAI/bge-small-en-v1.5'
|
cache_folder
|
str
|
Folder to cache the model. If not provided the function will search for
- |
None
|
Returns:
Type | Description |
---|---|
HuggingFaceEmbedding
|
The hugging face embedding model. |
Raises:
Type | Description |
---|---|
ImportError
|
If the |
Examples:
>>> from llama_utils.utils.models import get_hugging_face_embedding
>>> embedding = get_hugging_face_embedding()
>>> print(embedding.model_name)
BAAI/bge-small-en-v1.5
>>> print(embedding.max_length)
512
>>> print(embedding.embed_batch_size)
10
Source code in src/llama_utils/utils/models.py
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 |
|
get_huggingface_llm(**kwargs)
Initializes and returns a HuggingFaceLLM instance with specified parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kwargs
|
context_window : int, optional The maximum context window size, by default DEFAULT_CONTEXT_WINDOW. max_new_tokens : int, optional The maximum number of new tokens to generate, by default DEFAULT_NUM_OUTPUTS. generate_kwargs : dict, optional Additional arguments for text generation, by default {"temperature": 0.75, "do_sample": False}. query_wrapper_prompt : str, optional The wrapper prompt for query execution, by default "Answer the following question succinctly and informatively.". tokenizer_name : str, optional The tokenizer model name, by default DEFAULT_HUGGINGFACE_MODEL. model_name : str, optional The model name, by default DEFAULT_HUGGINGFACE_MODEL. device_map : str, optional The device mapping strategy, by default "auto". tokenizer_kwargs : dict, optional Additional tokenizer arguments, by default {"max_length": 2048}. model_kwargs : dict, optional Additional model arguments, by default {"torch_dtype": torch.float16}. |
{}
|
Returns:
Type | Description |
---|---|
HuggingFaceLLM
|
An instance of the HuggingFaceLLM class. |
Source code in src/llama_utils/utils/models.py
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
|
get_ollama_llm(model_id: str = 'llama3', base_url: str = 'http://localhost:11434', temperature: float = 0.75, context_window: int = DEFAULT_CONTEXT_WINDOW, request_timeout: float = 360.0, prompt_key: str = 'prompt', json_mode: bool = False, additional_kwargs: Dict[str, Any] = {}, is_function_calling_model: bool = True, keep_alive: Optional[Union[float, str]] = None)
Get the Ollama LLM with flexible parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_id
|
str
|
The model ID to use. |
'llama3'
|
base_url
|
str
|
The base URL of the Ollama API. |
'http://localhost:11434'
|
temperature
|
float
|
The temperature setting for response randomness. |
0.75
|
context_window
|
int
|
Maximum token window for context. |
DEFAULT_CONTEXT_WINDOW
|
request_timeout
|
float
|
Timeout for requests. |
360.0
|
prompt_key
|
str
|
Key for the prompt in requests. |
'prompt'
|
json_mode
|
bool
|
Whether to return responses in JSON mode. |
False
|
additional_kwargs
|
dict
|
Additional model-specific parameters. |
{}
|
is_function_calling_model
|
bool
|
Whether the model supports function calling. |
True
|
keep_alive
|
Optional[Union[float, str]]
|
Keep-alive duration. |
None
|
Returns:
Type | Description |
---|---|
Ollama
|
An instance of the Ollama LLM. |
Raises:
Type | Description |
---|---|
ImportError
|
If the |
Examples:
>>> from llama_utils.utils.models import get_ollama_llm
>>> llm = get_ollama_llm()
>>> print(llm.model)
llama3
>>> print(llm.base_url)
http://localhost:11434
>>> print(llm.metadata)
context_window=3900 num_output=256 is_chat_model=True is_function_calling_model=True model_name='llama3' system_role=<MessageRole.SYSTEM: 'system'>
Source code in src/llama_utils/utils/models.py
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 |
|
config_loader
llama_utils.utils.config_loader
A class or function to load configuration.
ConfigLoader
A class or function to load configuration.
Source code in src/llama_utils/utils/config_loader.py
11 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 |
|
embedding
property
writable
Get the embedding model.
llm
property
writable
Get the llm model.
settings
property
Get the settings.
__init__(llm: Any = None, embedding: Any = None)
Initialize the ConfigLoader class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
llm
|
Any
|
llm model to use. |
None
|
embedding
|
Any
|
Embedding model to use. |
None
|
Examples:
>>> from llama_utils.utils.config_loader import ConfigLoader
>>> config = ConfigLoader() # doctest: +SKIP
>>> print(config.embedding) # doctest: +SKIP
model_name='BAAI/bge-small-en-v1.5' embed_batch_size=10 callback_manager=<llama_index.core.callbacks.base.CallbackManager object at 0x000002919C16BD40> num_workers=None max_length=512 normalize=True query_instruction=None text_instruction=None cache_folder=None
>>> print(config.llm.model) # doctest: +SKIP
llama3
Source code in src/llama_utils/utils/config_loader.py
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 |
|
helper_functions
llama_utils.utils.helper_functions
A collection of helper functions used across different modules (e.g., text preprocessing, validation).
HelperFunctions
A collection of helper functions used across different modules (e.g., text preprocessing, validation).
Source code in src/llama_utils/utils/helper_functions.py
10 11 12 13 14 15 |
|
__init__()
Initialize the helper functions.
Source code in src/llama_utils/utils/helper_functions.py
13 14 15 |
|
generate_content_hash(content: str)
Generate a hash for the document content using SHA-256.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
content
|
str
|
The content of the document. |
required |
Returns:
Type | Description |
---|---|
str
|
The SHA-256 hash of the content. |
Source code in src/llama_utils/utils/helper_functions.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
is_sha256(string: str) -> bool
Check if a string is a valid SHA-256 hash.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
string
|
str
|
The string to check. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the string is a valid SHA-256 hash, False otherwise. |
Source code in src/llama_utils/utils/helper_functions.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
|
loggers
llama_utils.utils.logger
Logger.
Logger
Logger class.
Source code in src/llama_utils/utils/logger.py
7 8 9 10 11 12 13 14 15 16 17 18 |
|
__init__(name: str, level: int = logging.INFO, file_name: str = None)
Initialize the logger.
Source code in src/llama_utils/utils/logger.py
10 11 12 13 14 15 16 17 18 |
|
errors
llama_utils.utils.errors
Errors module.
StorageNotFoundError
Bases: Exception
ReadOnlyError.
Source code in src/llama_utils/utils/errors.py
4 5 6 7 8 |
|
__init__(error_message: str)
init.
Source code in src/llama_utils/utils/errors.py
7 8 |
|