Skip to main content

AI RAG Common Framework

A lightweight, modular, zero-bloat foundation framework for building RAG systems, Model Context Protocol (MCP) servers, autonomous multi-agent workflows, and production AI microservices.

PyPI Python CI License


AI RAG Common Framework is engineered as a clean, idiomatic, and dependency-light standard library for modern AI engineering. It replaces sprawling, over-engineered stacks with composable, typed primitives that work seamlessly across asynchronous coroutines and synchronous pipelines.

Features

Pillar Highlights
Unified LLM & Resilience Async clients for Gemini, OpenAI, Anthropic, Ollama, DeepSeek, Groq, and vLLM; FallbackLLMClient with circuit breaking; SSE streaming (complete_stream()); SemanticCache; Pydantic structured outputs.
RAG & Vector Storage RAGEngine; PostgresVectorStore (pgvector HNSW/IVFFlat, JSONB @>, FTS); embedded SQLiteVectorStore (SQLite + FTS5); InMemoryVectorStore (NumPy BLAS GEMV); Okapi BM25 + Reciprocal Rank Fusion; MultiQueryStrategy & HyDEStrategy; local & Cohere rerankers.
Agents & Workflows ReActAgent, AgentSupervisor with shared AgentBus, StateGraph cyclic/acyclic workflows with SQLiteCheckpointSaver, ConversationBufferMemory, VectorMemory, and Human-in-the-Loop (HITL) approval hooks.
Tooling & MCP 2.x Universal @tool decorator with Pydantic JSON schema generation, FrameworkMCPServer and FrameworkMCPClient (stdio & SSE), and single-line as_tool() export.
Security & Guardrails Sandboxed CodeInterpreter subprocesses, PromptGuardrail injection detection, PIISanitizer redaction, SSRF URL validation, and path-traversal guards.
Observability & Eval TokenCostTracker, zero-dependency PrometheusRegistry (/metrics), W3C traceparent spans, RAGTriadEvaluator, and HallucinationDetector.
Developer CLI ai-rag / rag-mcp with doctor, interactive repl, init project scaffolding, and run-mcp.

Installation

Install from PyPI:

pip install ai-rag-common-framework

Or install only the optional feature bundles you need:

Extra Command Includes
API Gateway pip install "ai-rag-common-framework[api]" FastAPI & Uvicorn
MCP 2.x pip install "ai-rag-common-framework[mcp]" Model Context Protocol SDK
Vector / Postgres pip install "ai-rag-common-framework[rag]" pgvector, asyncpg, NumPy BLAS
Everything pip install "ai-rag-common-framework[all]" All optional integrations & test tools

Quick Configuration

Create a .env file in your project root (see .env.example):

FRAMEWORK_ENV=development
LOG_LEVEL=INFO

# Default LLM Provider (gemini, openai, anthropic, ollama, deepseek, groq, vllm)
DEFAULT_LLM_PROVIDER=gemini
DEFAULT_LLM_MODEL=gemini-2.5-flash

# API Keys
GEMINI_API_KEY=your_gemini_api_key
OPENAI_API_KEY=your_openai_api_key
ANTHROPIC_API_KEY=your_anthropic_api_key

Usage Examples

1. Unified LLM with Structured Outputs & Fallbacks

import asyncio
from pydantic import BaseModel, Field
from common_framework import (
    LLMFactory,
    FallbackLLMClient,
    ChatMessage,
    Role,
)

class ArticleSummary(BaseModel):
    title: str
    key_points: list[str] = Field(description="3-5 bullet points")
    sentiment: str = Field(description="positive, neutral, or negative")

async def main() -> None:
    primary = LLMFactory.create("openai", model="gpt-4o-mini")
    backup = LLMFactory.create("gemini", model="gemini-2.5-flash")
    client = FallbackLLMClient(clients=[primary, backup])

    messages = [
        ChatMessage(
            role=Role.USER,
            content="Summarize: AI RAG Common Framework delivers modular RAG, MCP tools, and multi-agent workflows.",
        )
    ]

    result: ArticleSummary = await client.structured_complete(
        messages=messages,
        response_model=ArticleSummary,
    )
    print(result.title, result.key_points, result.sentiment)

if __name__ == "__main__":
    asyncio.run(main())
import asyncio
from common_framework import RAGEngine, SQLiteVectorStore

async def main() -> None:
    # Single-file ACID vector store with FTS5 BM25 keyword index
    vector_store = SQLiteVectorStore(db_path="knowledge.db")
    engine = RAGEngine(vector_store=vector_store)

    await engine.ingest_texts([
        "Authentication is handled via Bearer JWT tokens in the HTTP Authorization header.",
        "Rate limits are enforced using an in-memory token bucket algorithm with 60 req/min.",
        "Database backups execute nightly at 03:00 UTC to an isolated S3 bucket.",
    ])

    response = await engine.query(
        "How is user authentication implemented?",
        mode="hybrid",
        top_k=2,
    )
    print(response.answer)

if __name__ == "__main__":
    asyncio.run(main())

3. Stateful Workflow Orchestration (StateGraph)

import asyncio
from common_framework import END, START, StateGraph

def fetch_data(state: dict) -> dict:
    return {"raw_data": f"Processed: {state['query']}"}

def analyze_risk(state: dict) -> dict:
    return {"risk_score": 85}

def router(state: dict) -> str:
    return "high_risk" if state["risk_score"] > 50 else "low_risk"

def flag_review(state: dict) -> dict:
    return {"status": "Escalated for manual compliance review"}

def auto_approve(state: dict) -> dict:
    return {"status": "Auto-approved"}

async def main() -> None:
    graph = (
        StateGraph()
        .add_node("fetch", fetch_data)
        .add_node("analyze", analyze_risk)
        .add_node("flag_review", flag_review)
        .add_node("auto_approve", auto_approve)
        .add_edge(START, "fetch")
        .add_edge("fetch", "analyze")
        .add_conditional_edges("analyze", router, {
            "high_risk": "flag_review",
            "low_risk": "auto_approve",
        })
        .add_edge("flag_review", END)
        .add_edge("auto_approve", END)
    )

    result = await graph.run({"query": "Audit Q3 numbers"})
    print(result.state)

if __name__ == "__main__":
    asyncio.run(main())

4. Sandboxed Python Code Interpreter

import asyncio
from common_framework import CodeInterpreter

async def main() -> None:
    interpreter = CodeInterpreter(timeout=5.0)
    result = await interpreter.run(
        "import statistics\n"
        "data = [10.2, 14.5, 18.9, 22.1, 35.6]\n"
        "print(f'Mean: {statistics.mean(data):.2f}, Stdev: {statistics.stdev(data):.2f}')"
    )
    print(result.stdout)

if __name__ == "__main__":
    asyncio.run(main())

5. FastAPI Microservice with RAG & Authenticated MCP

from common_framework import RAGEngine, create_app, create_mcp_server

rag = RAGEngine()
mcp = create_mcp_server(name="gateway-mcp")

@mcp.tool(name="status", description="Get cluster health status")
def get_status() -> dict[str, str]:
    return {"cluster": "us-east-1", "health": "green"}

app = create_app(
    title="AI Knowledge Gateway",
    enable_rag_routes=True,
    rag_engine=rag,
    mcp_server=mcp,
    mcp_prefix="/mcp",
    mcp_api_key="secret-token",
)

# Run with: uvicorn main:app --host 0.0.0.0 --port 8000

6. Command-Line Interface (ai-rag)

ai-rag doctor                          # Check environment, API keys, and services
ai-rag doctor --json                   # Machine-readable diagnostics for CI/CD
ai-rag repl                            # Launch interactive playground
ai-rag init --dir ./my_ai_service      # Scaffold a starter microservice
ai-rag run-mcp --transport stdio       # Run standalone MCP server (stdio or sse)
ai-rag version                         # Print installed package version

Development & Testing

git clone https://github.com/buhozurdo/ai-rag-common-framework.git
cd ai-rag-common-framework
pip install -e ".[dev]"

# Run tests
python -m pytest tests/ -v

# Run tests with coverage
python -m pytest tests/ --cov=common_framework

Documentation

  • Changelog — Release history and upgrade notes.
  • Roadmap — Release train model and upcoming milestones.
  • GitHub Wiki — Architecture guides, API cheatsheet, and production runbooks.

License

This project is licensed under the MIT License.

Metadata

Release files for ai-rag-common-framework 0.22.0

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

Source distribution (sdist)

Source distribution for ai-rag-common-framework 0.22.0
File Size Uploaded Provenance Actions
ai_rag_common_framework-0.22.0.tar.gz 262.3 kB With provenance Details for ai_rag_common_framework-0.22.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ai-rag-common-framework 0.22.0
File Interpreter ABI Platform Actions
ai_rag_common_framework-0.22.0-py3-none-any.whl Python 3 none any Details for ai_rag_common_framework-0.22.0-py3-none-any.whl

Total release size: 419.6 kB

Release files / ai_rag_common_framework-0.22.0.tar.gz

Download URL ai_rag_common_framework-0.22.0.tar.gz
Size 262.3 kB
Tags Source
SHA-256 checksum
How to use checksums
c6d663e55b248dc53fe33d70450c3738fb043d451488151ffb106053c69028ee
BLAKE2b-256 checksum
How to use checksums
ebe6cc1bc034c9ab0ada27c8f397e06fceb1b4b5625d15ff11a521963b3633c3
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 29, 2026.

Transparency log

Release files / ai_rag_common_framework-0.22.0-py3-none-any.whl

Download URL ai_rag_common_framework-0.22.0-py3-none-any.whl
Size 157.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e72798d8ad0794e52dbd45199cb442621a066626dbecbc1df93c6a5c08634109
BLAKE2b-256 checksum
How to use checksums
b4b4a51d73727aa424dda5ecc4ee2cc90a9d9bda32b32345da6631fa195569e7
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 29, 2026.

Transparency log

Security for ai-rag-common-framework 0.22.0

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 ai_rag_common_framework-0.22.0.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 29, 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