Metadata-Version: 2.4
Name: ai_factory_model
Version: 0.0.11
Summary: AI Library to authenticate and manage LLM models and vector databases RAGs
License-Expression: MIT
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: Developers
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.12
Description-Content-Type: text/markdown
Requires-Dist: openai>=2.31.0
Requires-Dist: azure-core>=1.39.0
Requires-Dist: azure-identity>=1.25.3
Requires-Dist: azure-keyvault-secrets>=4.10.0
Requires-Dist: langchain>=1.2.15
Requires-Dist: langchain-openai>=1.1.12
Requires-Dist: azure-search-documents>=11.6.0
Requires-Dist: langchain-azure-ai>=1.2.1
Requires-Dist: jinja2>=3.1.6
Requires-Dist: python-decouple==3.8
Requires-Dist: pyyaml>=6.0.3
Provides-Extra: google-genai
Requires-Dist: langchain-google-genai>=4.2.1; extra == "google-genai"
Provides-Extra: community
Requires-Dist: langchain-community>=0.4.1; extra == "community"
Provides-Extra: ollama
Requires-Dist: langchain-ollama>=1.1.0; extra == "ollama"
Provides-Extra: cohere
Requires-Dist: langchain-cohere>=0.5.0; extra == "cohere"
Provides-Extra: pgvector
Requires-Dist: psycopg[binary]>=3.2.6; extra == "pgvector"
Provides-Extra: test
Requires-Dist: pytest>=8.3.5; extra == "test"
Requires-Dist: pytest-env>=1.1.5; extra == "test"
Requires-Dist: coverage>=7.8.0; extra == "test"
Provides-Extra: dev
Requires-Dist: build>=1.2.2; extra == "dev"
Requires-Dist: setuptools>=78.1.0; extra == "dev"
Requires-Dist: wheel>=0.45.1; extra == "dev"
Requires-Dist: flake8>=7.2.0; extra == "dev"
Requires-Dist: tox>=4.23.2; extra == "dev"
Requires-Dist: flake8>=4.0; extra == "dev"

# ai-factory-model


[![PyPI version](https://img.shields.io/pypi/v/ai-factory-model.svg)](https://pypi.org/project/ai-factory-model/)
![Supported Python Versions](https://img.shields.io/pypi/pyversions/ai-factory-model)
![Build Status](https://github.com/jorgegilramos/ai-factory-model/workflows/Python%20package/badge.svg)
![PyPI - Downloads](https://img.shields.io/pypi/dm/ai-factory-model)
[![License](https://img.shields.io/badge/License-Apache%202.0-lightgrey.svg)](https://opensource.org/licenses/Apache-2.0)


**ai-factory-model** is a modular Python library aimed at integrating with multiple language models (LLMs), cloud providers, and auxiliary utilities for development and infrastructure.

This library is designed to facilitate interaction with LLMs from OpenAI, Azure, Google, and Ollama, also integrating authentication, external configuration, Jinja2 templates, and reusable components.

## Features

- Support for multiple LLM models:
  - OpenAI (chat and embeddings)
  - Azure OpenAI
  - Google Generative AI
  - Ollama
  - LangChain and variants
- Configuration modules (`decouple`, `YAML`)
- Authentication via Azure Identity
- Content generation via Jinja2 templates
- Clear separation of responsibilities with modules such as:
  - `logger`
  - `security`
  - `auth_clients`
  - `model_*`  (interfaces for different LLMs)

## Installation

From PyPI:

```bash
pip install ai-factory-model
```

Optional modules:
```bash
pip install ai-factory-model[google_genai]
pip install ai-factory-model[community]
pip install ai-factory-model[ollama]
pip install ai-factory-model[cohere]
pip install ai-factory-model[pgvector]
```

## Setup
To use the model factory, you need to define a series of environment variables that allow connection to the various model hosting services:

```python
AZURE_TENANT_ID = <id_tenant_azure>
AZURE_CLIENT_ID = <id_client_azure>
AZURE_CLIENT_SECRET = <secret_passphrase_azure_client>
AZURE_TOKEN_URL = <azure_url_token>
```

For enhanced security, there is a connection to KeyVault. To define the connection to the corresponding key store, use:
```python
KV_NAME = <kv_name>
KV_TENANT_ID = <id_kv_tenant>
KV_CLIENT_ID = <id_kv_client>
KV_SECRET = <secret_passphrase_kv>
```

With the KeyVault connection established, the values to be retrieved from the key store should be specified using the following nomenclature:

> VARIABLE_SECRET = kv{name-of-secret-at-kv}

For example:
```python
# Transition from having the secret in raw form
AZURE_CLIENT_SECRET = <secret_passphrase_azure_client>

# To retrieving it from the KV
AZURE_CLIENT_SECRET = kv{<name_secret_azure_client>}
```

Additionally, if you have a file containing the various model configurations you wish to use, you should specify it with the corresponding variable.

> MODELS_CONFIG_FILE = <path_to_models_declarations_file>

## Basic usage

Using prompt:
```python
from ai_factory_model import ModelFactory

model = ModelFactory.get_model("azai_gtp4o")
params = ["Eres un guía turístico", "¿Dónde está Plasencia?"]

response = model.prompt(params=params)

print(type(response))
# Output:
# <class 'str'>

print(response)
# Output:
# Plasencia es una ciudad situada en la comunidad autónoma de Extremadura, en el oeste de España. Se encuentra en la provincia de Cáceres, a orillas del río Jerte. Plasencia está aproximadamente a unos 80 kilómetros al norte de la ciudad de Cáceres y a unos 250 kilómetros al oeste de Madrid. Es conocida por su casco histórico, que incluye la Catedral de Plasencia, y por su cercanía al Valle del Jerte, famoso por sus cerezos en flor.

```


Using langchain instance:
```python
from ai_factory_model import ModelFactory

model = ModelFactory.get_model("azai_gtp4o")
params = ["Eres un guía turístico", "¿Cuál es la capital de España?"]

response = model.get_client.invoke([
    {"role": "system", "content": params[0]},
    {"role": "user", "content": params[1]}
])

print(type(response))
# Output:
# <class 'langchain_core.messages.ai.AIMessage'>

print(f"{response.content}")
# Output:
# La capital de España es Madrid. Es una ciudad vibrante y llena de historia, conocida por su rica cultura, su arquitectura impresionante y su animada vida nocturna. Además, Madrid alberga importantes museos como el Museo del Prado y el Museo Reina Sofía, así como el Palacio Real y el Parque del Retiro.
```

Render a template:
```python
from ai_factory_model import ModelFactory, SEP_PATTERN

model = ModelFactory.get_model("azai_gtp4o")
params = {"system": "Eres un guía turístico", "user": "¿Qué visitar en Mérida de Extremadura?"}

template_content = (
    f"{{{{ system }}}}"
    f"{SEP_PATTERN}"
    f"{{{{ user }}}}"
)
prompt_template = Template(template_content)

response = model.prompt_render(
    template=prompt_template,
    params=params,
    sep_pattern=SEP_PATTERN
)

print(type(response))
# Output:
# <class 'str'>

print(f"{response}")
# Output:
# ¡Mérida es una ciudad fascinante llena de historia y patrimonio! Es conocida por su impresionante legado romano, ya que fue una de las ciudades más importantes de la antigua Hispania. Aquí tienes una lista de los lugares imprescindibles que deberías visitar en Mérida: [...]
```



## Project structure

```
ai_factory_model/
├── ai_factory_model/
│   ├── __init__.py
│   ├── config/
│   ├── llm/
│   ├── logger/
│   ├── security/
│   ├── vectordb/
├── pyproject.toml
├── requirements.txt
└── README.md
```

## Dependencies

This package requires the followind external libraries:

- `python-decouple`
- `PyYAML`
- `openai`
- `jinja2`
- `azure-core`
- `azure-identity`
- `azure-keyvault-secrets`
- `langchain`
- `langchain-openai`
- `langchain-azure-ai`
- `azure-search-documents`

With optional extra libraries 

```bash
pip install ai-factory-model[google_genai]
```
- `langchain-google-genai`

```bash
pip install ai-factory-model[community]
```
- `langchain-community`
```bash
pip install ai-factory-model[ollama]
```
- `langchain-ollama`
```bash
pip install ai-factory-model[cohere]
```
- `langchain-cohere`
```bash
pip install ai-factory-model[pgvector]
```
- `psycopg[binary]`


## Requirements
- Python 3.12 o superior
- Credential access/API keys to your needed providers (OpenAI, Azure, etc.)
