Skip to main content

ALIRA

PyPI version Python 3.11+ License: MIT

Active Learning Iterative Retrieval Agent

ALIRA classifies a large text corpus according to a natural-language query when exhaustive LLM evaluation is impractical. It iteratively discovers relevant documents using active learning, LLM validation, and classifier refinement.

Overview

Given a text corpus and a natural-language query, ALIRA bootstraps a binary classifier using LLM-generated synthetic examples (HyDE), then iteratively:

  1. Evaluates candidate documents via an LLM (up to 5 concurrent calls)
  2. Trains a Logistic Regression classifier on the accumulated labels
  3. Predicts relevance scores for the full corpus
  4. Selects the next batch of candidates via stratified sampling across confidence zones
  5. Stops early when the positive-zone prediction drift (RMSE) falls below a threshold

The result is a ranked list of documents predicted to match the query, requiring far fewer LLM calls than exhaustive evaluation.

Quick Start

Requirements

  • Python >= 3.11
  • LLM provider supporting the OpenAI API format (for both chat and embedding endpoints)

Installation

Install from PyPI:

pip install alira

Or clone the repository and install the development version locally:

git clone git@github.com:epfl-p-data/alira.git
cd alira
pip install -e .

Configuration

Set the following environment variables (or use a .env file loaded by your entrypoint script):

Variable Description
ALIRA_LLM_BASE_URL Base URL of the LLM API
ALIRA_LLM_API_KEY API key for authentication
ALIRA_LLM_EMBEDDING_MODEL Model name for embedding requests
ALIRA_LLM_BASE_MODEL Model name for chat/evaluation requests
ALIRA_LLM_DISABLE_THINKING Optional, defaults to true. Sends chat_template_kwargs: {"enable_thinking": false} to turn off the thinking mode of reasoning models (e.g. Qwen3 on vLLM). Set to false if your provider rejects this parameter (e.g. the OpenAI API).

Example

import pandas as pd
from alira import ActiveLearner

# Load corpus
df = pd.read_csv("data/movies.csv")

# Fit active learner
learner = ActiveLearner(corpus=df["text"])
learner.fit(query="sports")

# Get ranked results
df["score"] = learner.predict_proba()
results = df[df["score"] >= 0.5].sort_values("score", ascending=False)

See examples/demo.py for a complete runnable script with logging and result persistence.

API

ActiveLearner

Main entrypoint exported by the alira package.

ActiveLearner(
    corpus: list[str] | pd.Series | np.ndarray,
    embeddings: np.ndarray | pd.Series | None = None,
    n_synthetic: int = 10,
    min_iterations: int = 3,
    max_iterations: int = 20,
    n_eval_per_iteration: int = 30,
    c_value: float = 1.0,
    positive_zone_rmse_threshold: float = 0.01,
    cluster_candidates: bool = False,
    generation_prompt: str | None = None,
    evaluation_prompt: str | None = None,
)
Parameter Description
corpus Collection of texts to search
embeddings Optional pre-computed embeddings aligned 1-to-1 with corpus
n_synthetic Number of synthetic texts to generate for bootstrapping (HyDE)
min_iterations Minimum iterations before early stopping is evaluated
max_iterations Maximum active learning iterations
n_eval_per_iteration Number of texts evaluated per iteration
c_value Inverse regularization strength for LogisticRegression
positive_zone_rmse_threshold Early-stopping threshold for prediction drift in the positive zone
cluster_candidates Whether to cluster candidates within each stratum for diversity
generation_prompt Custom prompt for synthetic text generation
evaluation_prompt Custom prompt for LLM evaluation

Methods

  • fit(query: str) -> Self — Run the active-learning loop and train the classifier.
  • predict_proba(corpus=None, embeddings=None) -> pd.Series — Return predicted probabilities of relevance.
  • predict(corpus=None, embeddings=None) -> pd.Series — Return binary predictions.

Project Structure

.
├── src/
│   └── alira/
│       ├── __init__.py           # Package entrypoint, exports ActiveLearner
│       ├── active_learner.py     # Core ActiveLearner implementation
│       ├── classifiers.py        # LogisticRegressionClassifier
│       ├── evaluation.py         # LLM-based binary evaluation (async, max 5 concurrent)
│       ├── llms.py               # OpenAI API client for chat and embeddings
│       ├── synthetic.py          # Synthetic text generation via LLM (HyDE)
│       └── config.py             # Environment-based configuration
├── examples/
│   ├── demo.py                   # Example script with logging and CSV output
│   ├── lab_explorer.py           # Example using external data source
│   ├── compare.py                # Utility to compare result sets
│   ├── aists.py                  # Batch runner for AISTS themes
│   ├── embeddings.py             # Generate and cache embeddings
│   └── utils.py                  # Shared example utilities
├── pyproject.toml
└── README.md

Dependencies

Core dependencies (see pyproject.toml):

  • numpy
  • openai
  • pandas
  • pydantic
  • scikit-learn

Optional dependencies for the example scripts (install with pip install -e ".[demo]"):

  • python-dotenv
  • epfl-data-index

Metadata

Release files for alira 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for alira 0.1.2
File Size Uploaded Provenance Actions
alira-0.1.2.tar.gz 890.6 kB With provenance Details for alira-0.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for alira 0.1.2
File Interpreter ABI Platform Actions
alira-0.1.2-py3-none-any.whl Python 3 none any Details for alira-0.1.2-py3-none-any.whl

Total release size: 903.8 kB

Release files / alira-0.1.2.tar.gz

Download URL alira-0.1.2.tar.gz
Size 890.6 kB
Tags Source
SHA-256 checksum
How to use checksums
b2702b2cc362f7ae53eef95cff149d11f31eddab32726fbf0765193f0675fdeb
BLAKE2b-256 checksum
How to use checksums
c3037fbe2a01c9a3b52731dba0e601ea8c80289f8583c409cde384ba32686fd0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Release files / alira-0.1.2-py3-none-any.whl

Download URL alira-0.1.2-py3-none-any.whl
Size 13.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7948c8345c07542fd838ea0ee551abe0e32dfe039fc006c1bebf76c959422529
BLAKE2b-256 checksum
How to use checksums
d777376bc7845c2f9ab8cfc8573160b79b07dbdc4cb43ea1f9e8a9cb6901ca4c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Security for alira 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for alira-0.1.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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