Skip to main content
ai4rag icon

ai4rag

RAG Templates Optimization Engine

AI4RAG Python Python

RAG Builder HPO AutoML

Initializes RAG Templates with optimal parameters

Getting StartedUser GuideAPI ReferenceDevelopment


🎯 What is ai4RAG?

ai4RAG is an optimization engine for RAG Templates that is LLM and vector database provider-agnostic. It accepts a variety of RAG Templates and a search space definition, then returns an initialized RAG Template with optimal parameter values (called a RAG Pattern).

[!IMPORTANT] ai4rag is designed to be provider-agnostic: user may provide his own implementation for foundation model, embedding model or vector store and use them for the experiment. Out of the box ai4rag is designed to work with OGX. To use the full capabilities of ai4rag, you'll need access to an OGX server configured with at least one foundation model, one embedding model, and a vector database.

OGX

ai4RAG can run experiments using an OGX server for embeddings, vector storage, and text generation. Use the official client and API docs to connect and extend:

  • Client: ogx-client >= 1.1.0 (Python package used by ai4RAG; installs with this project).
  • Server: OGX >= 1.1.0.
  • API reference: OGX API docs — HTTP API used by the client.

Features used by ai4rag

When using the OGX backend, ai4rag relies on:

  • Embeddings — Text embeddings via the client (e.g. for indexing and query encoding). See Embeddings API in the docs.
  • Vector stores — Create, retrieve, and delete vector store instances (e.g. Milvus) with a chosen embedding model and dimension. See Vector stores in the API docs.
  • Vector IO — Insert document chunks (with embeddings) into a store and run similarity search (query) for retrieval. See Vector IO and insert/query endpoints.
  • Chat / responses — Foundation model integration for answer generation (e.g. chat completions or responses API) when evaluating RAG patterns.

Document processing

ai4RAG uses docling-core for document representation and chunking. Documents are represented as DoclingDocument instances, and the DoclingChunker leverages docling's HybridChunker for structure-aware, token-aware chunking. Both docling-core and ogx-client are installed automatically with ai4rag.

Quick start

  1. Provide an instance of ogx-client to integrate with OGX.
  2. Prepare your knowledge base documents for the experiment.
  3. Prepare benchmark_data.json with evaluation questions and answers.
  4. Define and constrain your search space.
  5. Configure the optimizer.
  6. Create and run the experiment.

Prepare ogx-client

To enable full integration with OGX, instantiate an OgxClient. This allows ai4rag to use the models and vector stores available on your OGX server.

[!tip] Store your credentials securely in a .env file.

import os
from dotenv import load_dotenv, find_dotenv
from ogx_client import OgxClient

client = OgxClient(base_url=os.getenv("BASE_URL"), api_key=os.getenv("API_KEY"))

Prepare knowledge base documents

Prepare a set of documents to serve as the knowledge base for retrieval. Documents are represented as DoclingDocument instances (from the docling-core library) and should be stored in a local directory.

[!note] If you are using the project locally, you can load documents using the FileStore class from the dev_utils module. Supported document formats can be found in the FileStore implementation.

from pathlib import Path
from dev_utils.file_store import FileStore

documents_path = Path("<path to the documents folder>")
documents = FileStore(documents_path).load_as_documents()

Prepare benchmark_data.json

Create a benchmark_data.json file following this schema:

[
	{
		"question": "<question_1>",
		"correct_answers": [
			"<answer 1 for question 1>",
			"<answer 2 for question 1>"
		],
		"correct_answer_document_ids": ["<list of documents ids based on which correct answers were generated>"]
	},
	{
		"question": "<question_2>",
		"correct_answers": [
			"<answer 1 for question 2>",
			"<answer 2 for question 2>"
		],
		"correct_answer_document_ids": ["<list of documents ids based on which correct answers were generated>"]
	}
]

All benchmark questions and answers must be derived from your knowledge base documents.

from dev_utils.utils import read_benchmark_from_json

benchmark_data_path = Path("<path to benchmark_data.json>")
benchmark_data = read_benchmark_from_json(benchmark_data_path)

Define and constrain search space

The search space defines all possible parameter combinations, where each combination creates a unique RAG Pattern. During the experiment, the engine will optimize the RAG Pattern for the selected metric over the given search space, using an objective function to evaluate each configuration.

from ai4rag.search_space.src.parameter import Parameter
from ai4rag.search_space.src.search_space import AI4RAGSearchSpace
from ai4rag.rag.foundation_models.ogx import OGXFoundationModel
from ai4rag.rag.embedding.ogx import OGXEmbeddingModel


search_space = AI4RAGSearchSpace(
    params=[
        Parameter(
            name="foundation_model",
            param_type="C",
            values=[OGXFoundationModel(model_id="ollama/llama3.2:3b", client=client)],
        ),
        Parameter(
            name="embedding_model",
            param_type="C",
            values=[
                OGXEmbeddingModel(
                    model_id="ollama/nomic-embed-text:latest",
                    client=client,
                    params={"embedding_dimension": 768, "context_length": 8192},
                )
            ],
        ),
        Parameter(
            name="chunking_method",
            param_type="C",
            values=["recursive", "hybrid"],
        ),
        Parameter(
            name="chunk_size",
            param_type="C",
            values=[512, 1024, 2048],
        ),
        Parameter(
            name="chunk_overlap",
            param_type="C",
            values=[0, 128, 256],
        ),
    ]
)

[!tip] chunking_method controls the chunking strategy: "recursive" uses LangChain's RecursiveCharacterTextSplitter, while "hybrid" uses docling's structure-aware HybridChunker (requires chunk_overlap=0). When omitted, both methods are included by default.

[!tip] To run automatic models discovery with OGX you may use prepare_search_space_with_ogx() from ai4rag.search_space.prepare_search_space.

Configure optimizer

You have full control over the optimization algorithm. Configure the GAMOptimizer by adjusting GAMOptSettings.

from ai4rag.core.hpo.gam_opt import GAMOptSettings

optimizer_settings = GAMOptSettings(
    max_evals=10, n_random_nodes=4
)

Run the experiment

Using the information from the previous steps, create an experiment and run the ai4rag optimization engine.

[!note] For OGX vector stores, use vector_store_type="ogx" and specify the provider with ogx_vector_io_provider_id (e.g., ogx_vector_io_provider_id="milvus", ogx_vector_io_provider_id="qdrant"). To use ChromaDB in-memory, specify vector_store_type="chroma".

from ai4rag.core.experiment.experiment import AI4RAGExperiment
from ai4rag.utils.event_handler import LocalEventHandler

experiment = AI4RAGExperiment(
    client=client,
    documents=documents,
    benchmark_data=benchmark_data,
    search_space=search_space,
    vector_store_type="ogx",
    ogx_vector_io_provider_id="milvus",
    optimizer_settings=optimizer_settings,
    event_handler=LocalEventHandler(output_path="<local-path-to-store-your-output-files>"),
)

experiment.search()
best_eval = experiment.results.get_best_evaluations(k=1)[0]
print(best_eval)

print(best_eval.rag_pattern.generate("What ai4rag can be used for?"))

[!tip] For production use, implement your own custom EventHandler to handle status changes and artifacts produced during the experiment. See the BaseEventHandler implementation for reference.

Contribution

Pull requests are very welcome! Make sure your patches are well tested. Ideally create a topic branch for every separate change you make.

Development setup

This project uses uv for dependency management.

# Clone the repository
git clone https://github.com/IBM/ai4rag.git
cd ai4rag

# Install all development dependencies
uv sync --extra dev

# Run tests
uv run pytest tests/unit/

# Check code style
uv run black --check ai4rag/
uv run pylint ai4rag/

# Build and serve documentation locally
uv run mkdocs serve

Pull request workflow

  1. Fork the repo
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -s -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

See more details in contributing section.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ai4rag-0.10.1.tar.gz (126.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ai4rag-0.10.1-py3-none-any.whl (164.2 kB view details)

Uploaded Python 3

File details

Details for the file ai4rag-0.10.1.tar.gz.

File metadata

  • Download URL: ai4rag-0.10.1.tar.gz
  • Upload date:
  • Size: 126.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for ai4rag-0.10.1.tar.gz
Algorithm Hash digest
SHA256 b1b370c8b657e1b44860d6443258a72446c3a03007be1b9bb1ada22040a0aaf3
MD5 cbe91c7a9ef2d4dc62fc20e51159a9ae
BLAKE2b-256 87f42ac70812ae7d22c94644817727d981e201e44e218a35e9076552a831c6c8

See more details on using hashes here.

Provenance

The following attestation bundles were made for ai4rag-0.10.1.tar.gz:

Publisher: publish-pypi.yml on IBM/ai4rag

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ai4rag-0.10.1-py3-none-any.whl.

File metadata

  • Download URL: ai4rag-0.10.1-py3-none-any.whl
  • Upload date:
  • Size: 164.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for ai4rag-0.10.1-py3-none-any.whl
Algorithm Hash digest
SHA256 56a5bc592ef408c8174b17f5f3d93c7fcc9a9c20308377faf8d21ffd620001d9
MD5 21a6f0907802abfdfa5656e7498ee948
BLAKE2b-256 9632de5a1a1d7321bf6b07c77502a6eeeb3b2b230a9fa5f9455d8885a0f6958c

See more details on using hashes here.

Provenance

The following attestation bundles were made for ai4rag-0.10.1-py3-none-any.whl:

Publisher: publish-pypi.yml on IBM/ai4rag

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.16.0

2 files

0.15.0

2 files

0.14.0

2 files

0.13.0

2 files

0.12.0

2 files

0.11.1

2 files

0.11.0

2 files

0.10.4

2 files

0.10.3

2 files

0.10.2

2 files

This release

0.10.1 This release

2 files

0.10.0

2 files

0.9.3

2 files

0.9.2

2 files

0.9.1

2 files

0.9.0

2 files

0.8.1

2 files

0.8.0

2 files

0.7.0

2 files

0.6.4

2 files

0.6.3

2 files

0.6.2

2 files

0.6.1

2 files

0.6.0

2 files

0.5.6

2 files

0.5.5

2 files

0.5.4

2 files

0.5.3

2 files

0.5.2

2 files

0.5.1

2 files

0.5.0

2 files

0.4.0

2 files

0.2.1

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page