A comprehensive Python framework for building and serving conversational AI agents with FastAPI
pip install agent-framework-lib==0.8.19 Copy PIP instructions
# Install with LlamaIndex support (recommended) uv add agent-framework-lib[llamaindex] # Install with MCP support uv add agent-framework-lib[llamaindex,mcp] # Install with all features uv add agent-framework-lib[all] Available extras: llamaindex, mcp, gitnexus, mongodb, elasticsearch, postgresql, s3, minio, gcp, multimodal, memory, memori, graphiti, graphiti-falkordb, graphiti-neo4j, graphiti-all, observability, monitoring, websearch, dev, all
The framework automatically detects and configures system libraries. Manual installation is only needed if you encounter issues:
# macOS brew install pango gdk-pixbuf libffi cairo # Ubuntu/Debian sudo apt-get install libpango-1.0-0 libpangoft2-1.0-0 libgdk-pixbuf2.0-0 libffi-dev libcairo2 # Fedora/RHEL sudo dnf install pango gdk-pixbuf2 libffi-devel cairo For Chart/Mermaid Image Generation (Playwright):
# Install Playwright and browser uv add playwright playwright install chromium For MCP Python Server (Deno):
# macOS/Linux curl -fsSL https://deno.land/install.sh | sh # Windows (PowerShell) irm https://deno.land/install.ps1 | iex Post-Installation Script (Recommended) The framework includes a CLI script that automatically installs all optional dependencies (Playwright browsers and Deno runtime):
# Run after installing the package agent-framework-post-install This script:
Note: The framework also attempts lazy auto-installation when tools are first used, but running the post-install script ensures everything is ready upfront.
The framework handles library path configuration automatically on startup.
The framework includes a built-in AI assistant that helps you create agents! Access it at /helper when running any agent server.
For the best experience, install and run GitNexus to enable semantic code search:
# 1. Install and index the codebase ./scripts/setup_gitnexus.sh # 2. Start the GitNexus server ./scripts/start_gitnexus_server.sh # 3. Verify it's running curl http://localhost:4747/health The helper agent will automatically use GitNexus if available, with graceful fallback to text search if not running.
📖 User Guide - Complete guide for using GitNexus features with the Helper Agent
# Install GitNexus support uv add agent-framework-lib[gitnexus] The helper agent indexes:
Re-indexing: If you update documentation or examples, trigger a re-index:
# Re-index knowledge base curl -X POST http://localhost:8000/helper/reindex # Re-index GitNexus (after code changes) npx gitnexus analyze --embeddings Model Configuration:
By default, the helper agent uses Claude (if ANTHROPIC_API_KEY is set) or GPT-5.4 (if OPENAI_API_KEY is set). You can override this with:
# Force a specific model (useful if your Anthropic key has reached its limit) HELPER_AGENT_MODEL=gpt-6-astra Example questions:
Pour déployer un agent, partez de l'image officielle — Chromium Playwright, Deno, git, root, sandbox locale déjà en place (sinon l'agent ne peut ni rendre un PNG ni installer quoi que ce soit) :
FROM ghcr.io/komus-ai/agent-framework-runtime:0.8.19 Détails, publication et visibilité GHCR : docs/AGENT_RUNTIME_IMAGE.md.
For local development, use Docker Compose to run all external services (Elasticsearch, MongoDB, PostgreSQL, FalkorDB, MinIO):
# Start all services docker-compose --profile all up -d # Copy environment template cp .env.docker .env # Edit .env to add your LLM API keys # Stop services docker-compose down Use profiles to start only what you need:
docker-compose --profile storage up -d # Elasticsearch, MongoDB, MinIO docker-compose --profile memory up -d # PostgreSQL, FalkorDB Full documentation: See Docker Setup Guide for service details, ports, credentials, and troubleshooting.
Here's a complete, working agent with LlamaIndex:
from typing import List from agent_framework import LlamaIndexAgent, create_basic_agent_server class MyAgent(LlamaIndexAgent): def __init__(self): super().__init__( agent_id="my_calculator_agent", name="Calculator Agent", description="A helpful calculator assistant that can perform basic math operations." ) def get_agent_prompt(self) -> str: """Define your agent's behavior and personality.""" return "You are a helpful calculator assistant." def get_agent_tools(self) -> List[callable]: """Define the tools your agent can use. Tools are automatically converted to LlamaIndex FunctionTool instances. The function name becomes the tool name, and the docstring becomes the description. """ def add(a: float, b: float) -> float: """Add two numbers together.""" return a + b def multiply(a: float, b: float) -> float: """Multiply two numbers together.""" return a * b # Just return the functions - automatic conversion to FunctionTool return [add, multiply] # Start server - includes streaming, session management, web UI create_basic_agent_server(MyAgent, port=8000) Required Methods:
Optional Methods (have default implementations):
That's it! The framework provides default implementations for context management (state persistence), so you only need to implement the three core methods above.
# Set your API key export OPENAI_API_KEY=sk-your-key-here # Run the agent uv run python my_agent.py # Open http://localhost:8000/ui ⚙️ Configure Your Agent Environment Setup Create a .env file:
# Required: At least one API key OPENAI_API_KEY=sk-your-openai-key ANTHROPIC_API_KEY=sk-ant-your-anthropic-key GEMINI_API_KEY=your-gemini-key # Model Configuration DEFAULT_MODEL=claude-haiku-5-5 # Multi-Model Routing (Auto Mode) DEFAULT_MODEL_MODE=auto # "auto" or specific model name AUTO_CLASSIFIER_MODEL=gpt-6-luna # Model for complexity classification PREFERRED_LIGHT_MODELS=gpt-6-luna,claude-haiku-5-5 PREFERRED_STANDARD_MODELS=gpt-6.1-sol PREFERRED_ADVANCED_MODELS=gpt-6-astra,claude-opus-5-5 # Session Storage (optional) SESSION_STORAGE_TYPE=memory # or "mongodb" or "elasticsearch" MONGODB_CONNECTION_STRING=mongodb://localhost:27017 MONGODB_DATABASE_NAME=agent_sessions # File Storage (optional) LOCAL_STORAGE_PATH=./file_storage AWS_S3_BUCKET=my-bucket S3_AS_DEFAULT=false Remote Configuration (Elasticsearch-Managed Agents) For production deployments, you can configure agents to be managed entirely via Elasticsearch, allowing ops teams to modify prompts and models at runtime without code deployments.
from agent_framework import LlamaIndexAgent class OpsMangedAgent(LlamaIndexAgent): def __init__(self): super().__init__( agent_id="ops_managed_agent", name="Ops Managed Agent", description="An agent configured via Elasticsearch." ) @classmethod def get_use_remote_config(cls) -> bool: """Enable Elasticsearch-only configuration.""" return True def get_agent_prompt(self) -> str: # Fallback prompt if ES config not available return "You are a helpful assistant." def get_agent_tools(self) -> list: return [] Behavior:
Fallback: If use_remote_config=True but no ES config exists, the system falls back to hardcoded config and pushes it to ES with a warning.
The framework includes intelligent model routing that automatically selects the best model based on query complexity.
When DEFAULT_MODEL_MODE=auto, the system analyzes each query and routes it to the appropriate tier:
Users can also select a specific model from the UI dropdown:
# Default mode when no user preference DEFAULT_MODEL_MODE=auto # Model used for complexity classification (should be fast and cheap) AUTO_CLASSIFIER_MODEL=gpt-6-luna # Preferred models per tier (comma-separated, in order of preference) PREFERRED_LIGHT_MODELS=gpt-6-luna,claude-haiku-5-5,gemini-3.5-flash-lite PREFERRED_STANDARD_MODELS=gpt-6.1-sol,gemini-3.8-flash PREFERRED_ADVANCED_MODELS=gpt-6-astra,claude-opus-5-5,gemini-3.1-pro-preview API Endpoint # Get available models curl http://localhost:8000/api/models # Response { "models_by_tier": { "light": [{"id": "gpt-6-luna", "provider": "openai", "available": true}, ...], "standard": [...], "advanced": [...] }, "default_mode": "auto", "classifier_model": "gpt-6-luna" } Backward Compatibility Agents with hardcoded models continue to work without changes:
class MyAgent(LlamaIndexAgent): def __init__(self): super().__init__(...) self._default_model = "gpt-6-astra" # This model will always be used LlamaIndex Agent Configuration Control model behavior in your agent:
Users can override settings per session via the API or web UI:
Custom tools extend your agent's capabilities. The tool name and docstring are crucial - they tell the agent when and how to use the tool.
def get_weather(city: str) -> str: """Get the current weather for a specific city. Args: city: The name of the city to get weather for Returns: A description of the current weather """ # Your implementation here return f"The weather in {city} is sunny, 22°C" # Add to your agent class MyAgent(LlamaIndexAgent): def get_agent_tools(self): # Just return the function - automatic conversion to FunctionTool # Function name = tool name, docstring = tool description return [get_weather] Important:
For tools that need file storage or other dependencies, use closures to capture context:
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec class MyAgent(LlamaIndexAgent): def __init__(self): super().__init__( agent_id="my_agent", name="MCP Agent", description="An assistant with access to external tools via MCP servers." ) self.mcp_tools = [] self._mcp_initialized = False async def _initialize_mcp_tools(self): """Load tools from MCP servers.""" if self._mcp_initialized: return # Configure your MCP server mcp_configs = [ { "command": "uvx", "args": ["mcp-server-filesystem"], "env": {"FILESYSTEM_ROOT": "/path/to/workspace"} } ] for config in mcp_configs: client = BasicMCPClient( config["command"], args=config["args"], env=config.get("env", {}) ) # Load tools from the MCP server mcp_tool_spec = McpToolSpec(client=client) tools = await mcp_tool_spec.to_tool_list_async() self.mcp_tools.extend(tools) self._mcp_initialized = True async def initialize_agent(self, model_name, system_prompt, tools, **kwargs): # Load MCP tools before initializing agent await self._initialize_mcp_tools() # Combine with other tools all_tools = self.get_agent_tools() await super().initialize_agent(model_name, system_prompt, all_tools, **kwargs) def get_agent_tools(self): # Return built-in tools + MCP tools return self.mcp_tools Multiple MCP Servers def _get_mcp_configs(self): """Configure multiple MCP servers.""" return [ { "name": "filesystem", "command": "uvx", "args": ["mcp-server-filesystem"], "env": {"FILESYSTEM_ROOT": "/workspace"} }, { "name": "github", "command": "uvx", "args": ["mcp-server-github"], "env": { "GITHUB_TOKEN": os.getenv("GITHUB_TOKEN") } }, { "name": "python", "command": "uvx", "args": ["mcp-run-python", "stdio"] } ] Popular MCP Servers # Filesystem operations uvx mcp-server-filesystem # GitHub integration uvx mcp-server-github # Python code execution uvx mcp-run-python # Database access uvx mcp-neo4j-cypher uvx mcp-server-postgres Installation:
# Install with MCP support uv add agent-framework-lib[llamaindex,mcp] # Or add MCP to existing installation uv add agent-framework-lib[mcp] # MCP servers are run via uvx (no separate install needed) Using Deno-based MCP servers:
If you need to use Deno-based MCP servers (like TypeScript MCP servers), the framework provides a helper function to ensure Deno works correctly even if it's not in your PATH:
from agent_framework import get_deno_command # Configure a Deno-based MCP server mcp_config = { "command": get_deno_command(), # Automatically uses correct Deno path "args": ["run", "-N", "jsr:@pydantic/mcp-run-python", "stdio"] } This helper function:
Add long-term semantic memory to your agents, enabling them to remember information across conversations and provide personalized responses.
The Skills System provides modular, on-demand capability loading that reduces token consumption by ~80%. Instead of loading all instructions into every system prompt, skills deliver detailed instructions only when needed.
Skills are exclusively defined as SKILL.md markdown files with YAML frontmatter, loaded by MarkdownSkillLoader. Each skill uses ShellTool to execute standalone CLI scripts and WebFetchTool for web content retrieval.
BEFORE: System Prompt = Base (~500) + Rich Content (~3000) = ~3500 tokens/message AFTER: System Prompt = Base (~500) + Skills Discovery (~200) = ~700 tokens/message + On-demand skill loading (~500 tokens, one-time per skill) Quick Start Skills are automatically available in all agents via BaseAgent. No need to explicitly inherit from SkillsMixin:
Each skill is a SKILL.md file in agent_framework/skills/builtin/skills/ with an associated CLI script executed via ShellTool.
More info: See Custom Skills Guide, Creating Agents Guide and skills_demo_agent.py
All agents automatically support rich content generation including:
This is automatic! The framework injects rich content instructions into all agent system prompts by default. You don't need to add anything to your get_agent_prompt().
If you need to disable automatic rich content injection for a specific agent or session:
# When initializing a session session_config = { "user_id": "user123", "session_id": "session456", "enable_rich_content": False # Disable rich content } Via Web UI: Uncheck the "Enable rich content capabilities" checkbox when creating a session.
```chart { "type": "chartjs", "chartConfig": { "type": "bar", "data": { "labels": ["Mon", "Tue", "Wed"], "datasets": [{ "label": "Sales", "data": [120, 150, 100] }] } } } ``` Options Block:
```optionsblock { "question": "What would you like to do?", "options": [ {"text": "Continue", "value": "continue"}, {"text": "Cancel", "value": "cancel"} ] } ``` Table:
```tabledata { "caption": "Sales Data", "headers": ["Month", "Revenue"], "rows": [["Jan", "$1000"], ["Feb", "$1200"]] } ``` 🌐 Web Interface The framework includes a built-in web UI for testing and interacting with your agent.
# Start your agent uv run python my_agent.py # Open in browser open http://localhost:8000/ui The UI automatically detects and renders:
API Documentation: http://localhost:8000/docs (Swagger UI)
# API Key Authentication REQUIRE_AUTH=true API_KEYS=sk-key-1,sk-key-2 curl -H "Authorization: Bearer sk-key-1" \ http://localhost:8000/message \ -H "Content-Type: application/json" \ -d '{"query": "Hello!"}' Quick Links:
security llamaindex langgraph mcp websearch microsoft excel drawio gitnexus dev mongodb elasticsearch s3 minio gcp multimodal memory memori graphiti graphiti-falkordb graphiti-neo4j graphiti-all postgresql observability monitoring all
ai agents fastapi llamaindex framework conversational-ai multi-agent llm openai>=2.45 =1.5 <2 gemini chatbot session-management framework-agnostic
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.




