A modern Python learning platform for experimenting with Large Language Models (LLMs), Model Context Protocol (MCP) servers/clients, and Retrieval Augmented Generation (RAG) systems. Built with uv for fast dependency management, FastAPI for the backend, and LangChain for LLM integration.
Agent Lab is designed for learning and experimentation with:
- LLM Integration: Using LangChain to interact with OpenAI, Anthropic, and other providers
- MCP Protocol: Implementing Anthropic's Model Context Protocol for server/client communication
- RAG Systems: Building Retrieval Augmented Generation with vector embeddings and MySQL
- Memory Systems: Multi-level conversation memory (short-term, semantic, episodic, profile, procedural)
- API Development: Creating production-ready FastAPI applications
- API Reference: Complete API documentation and endpoints.
- Configuration Guide: Dynamic configuration system for Memory and RAG.
- LLM Integration: Guide to using the LangChain LLM wrapper.
- MCP Protocol: Model Context Protocol implementation details.
- Memory System: Comprehensive guide to the multi-level memory system.
- RAG System: Guide to Retrieval Augmented Generation with Pinecone.
agentlab/
βββ frontend/ # Frontend application (React/Vue)
β βββ src/
β β βββ components/
β β βββ Chat.jsx # Chat interface
β β βββ MPCManager.jsx # MPC instance management
β β βββ RAGViewer.jsx # RAG visualization
β βββ README.md
β
βββ src/agentlab/ # Python backend package
β βββ database/ # Database layer
β β βββ config.py # MySQL connection config
β β βββ models.py # Table schemas
β β βββ crud.py # CRUD operations
β β
β βββ core/ # Core business logic
β β βββ rag_service.py # RAG implementation
β β βββ mpc_manager.py # MPC instance manager
β β βββ llm_interface.py # LangChain LLM wrapper
β β βββ memory_service.py # Memory management (NEW)
β β
β βββ agents/ # Low-level implementations
β β βββ rag_processor.py # Embedding & retrieval
β β βββ mpc_client_base.py # MPC client base class
β β βββ mpc_server_base.py # MPC server base class
β β βββ memory_processor.py # Long-term memory (NEW)
β β
β βββ api/ # FastAPI application
β β βββ main.py # FastAPI app entry point
β β βββ routes/
β β βββ chat_routes.py # Chat & RAG endpoints
β β βββ mpc_routes.py # MPC management endpoints
β β
β βββ models.py # Data models & Protocols
β βββ main.py # CLI entry point
β
βββ data/ # Static data & configurations
β βββ initial_knowledge/ # RAG knowledge base documents
β βββ examples/ # Example queries
β βββ configs/ # Config files
β
βββ tests/
β βββ unit/ # Unit tests with mocks
β βββ integration/ # Integration tests
β
βββ pyproject.toml # Dependencies & configuration
βββ Makefile # Development automation
βββ AGENTS.md # AI coding assistant guidelines
βββ README.md # This file
- Fast Package Management: Uses
uvfor lightning-fast dependency resolution - Modern Python: Python 3.12+ with type hints and Protocols
- FastAPI Backend: Production-ready REST API with automatic documentation
- LangChain Integration: Unified interface for multiple LLM providers
- MCP Tools: Extensible tool system with autonomous agent execution
- RAG System: Vector embeddings with Pinecone storage
- Memory System: Multi-level conversation memory (short-term, semantic, episodic, profile, procedural)
- Testing Ready: Pre-configured pytest with unit and integration tests
- Code Quality: Ruff for formatting and linting
- SOLID Principles: Clean architecture with dependency injection
- Python 3.12+
- uv package manager
- MySQL 8.0+ (for database)
- Node.js 18+ (for frontend, optional)
Windows:
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"Linux/macOS:
curl -LsSf https://astral.sh/uv/install.sh | sh# Clone the repository
git clone https://github.com/theviderlab/ia-bootcamp-2005
cd ia-bootcamp-2005
# Sync dependencies (creates .venv and installs packages)
uv sync
# Or use Make
make install
# OPCIONAL: Instalar el paquete en modo editable para importarlo sin uv run
uv pip install -e .# Copy environment template
cp .env.example .env
# Edit .env and add your credentials
# - Database configuration (MySQL)
# - OpenAI API key
# - Anthropic API key (optional)Required environment variables:
# Database
DB_HOST=localhost
DB_PORT=3306
DB_USER=your_db_user
DB_PASSWORD=your_db_password
DB_NAME=agent_lab
# LLM APIs
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
# Pinecone (for RAG)
PINECONE_API_KEY=pcsk_...
PINECONE_INDEX_NAME=agent-lab-index
PINECONE_CLOUD=aws
PINECONE_REGION=us-east-1# Initialize MySQL database and tables
make setup-dbCon el layout src/, hay dos formas de ejecutar cΓ³digo:
OpciΓ³n 1: Usando uv run (Recomendado)
# uv run configura automΓ‘ticamente el entorno
uv run python script.py
uv run python -m agentlab.mainOpciΓ³n 2: Instalar en modo editable
# Instalar una vez
uv pip install -e .
# Luego ejecutar normalmente
python script.py# Start the API server (with auto-reload)
make api
# Or directly with uvicorn
uv run uvicorn agentlab.api.main:app --reloadThe API will be available at:
- API: http://localhost:8000
- Interactive Docs: http://localhost:8000/docs
- Alternative Docs: http://localhost:8000/redoc
Chat & LLM:
POST /llm/generate- Generate text from promptPOST /llm/chat- Chat with conversation history, memory, RAG, and tools
RAG (Retrieval Augmented Generation):
POST /llm/rag/query- Query knowledge base with RAGPOST /llm/rag/documents- Add documents to knowledge basePOST /llm/rag/directory- Add directory of documents
MCP Tools:
GET /mpc/tools- List all available tools with metadataGET /mpc/tools/names- Get tool names onlyGET /mpc/tools/{tool_name}- Get detailed tool information
Memory:
GET /llm/memory/context- Get enriched memory contextGET /llm/memory/history- Get conversation historyGET /llm/memory/stats- Get memory statisticsPOST /llm/memory/search- Semantic search across memoriesDELETE /llm/memory/session/{session_id}- Clear session memory
Configuration:
GET /config/status- System configuration statusGET /config/session/{session_id}- Get session configurationPOST /config/session- Create/Update session configurationDELETE /config/session/{session_id}- Reset session configuration
# Run the main CLI application
make main
# Or directly
uv run python -m agentlab.mainmake help # Show all available commands
make install # Install/sync dependencies
make api # Start FastAPI server
make setup-db # Initialize database
make test # Run all tests
make test-unit # Run unit tests only
make test-integration # Run integration tests only
make format # Format code with Ruff
make lint # Lint code with Ruff
make pre-commit # Run pre-commit checks
make clean # Clean cache filesThe project uses pytest with separation between unit and integration tests:
- Unit Tests (tests/unit/): Fast, isolated tests using mocks
- Integration Tests (tests/integration/): Tests with real APIs/services
# All tests
make test
# Unit tests only
make test-unit
# Integration tests only
make test-integration
# With verbose output
uv run pytest -v
# With coverage
uv run pytest --cov=src/agentlab
# Specific test file
uv run pytest tests/unit/test_specific.pyThe project includes a fully implemented LLM interface using LangChain for interacting with OpenAI models.
Quick Start:
from agentlab.core.llm_interface import LangChainLLM
from agentlab.models import ChatMessage
from datetime import datetime
# Initialize LLM
llm = LangChainLLM(model_name="gpt-3.5-turbo")
# Simple text generation
response = llm.generate(
prompt="Explain machine learning in one sentence",
temperature=0.7,
max_tokens=100
)
# Chat with conversation history
messages = [
ChatMessage(
role="system",
content="You are a helpful assistant",
timestamp=datetime.now()
),
ChatMessage(
role="user",
content="What is Python?",
timestamp=datetime.now()
),
]
response = llm.chat(messages)Features:
- β Text generation with customizable parameters
- β Chat conversations with history
- β Support for system, user, and assistant roles
- β Error handling and validation
- β Multiple model support (GPT-3.5, GPT-4)
Run the example:
# Make sure OPENAI_API_KEY is set
export OPENAI_API_KEY="your-api-key"
# Run example script
uv run python -m agentlab.examples.llm_example
# Or run basic tests
uv run python test_llm_basic.pyFull documentation: docs/llm_interface_guide.md
The project includes a fully implemented RAG (Retrieval Augmented Generation) system using Pinecone vector database and LangChain.
Quick Start:
from agentlab.core.llm_interface import LangChainLLM
from agentlab.core.rag_service import RAGServiceImpl
# Initialize RAG service
llm = LangChainLLM()
rag_service = RAGServiceImpl(llm=llm)
# Add documents to knowledge base
rag_service.add_documents_from_directory(
directory="data/initial_knowledge",
namespace="my-project"
)
# Query the knowledge base
result = rag_service.query(
query="What is Agent Lab?",
top_k=5,
namespace="my-project"
)
print(f"Answer: {result.response}")
print(f"Sources: {len(result.sources)}")Features:
- β Pinecone vector database integration
- β Automatic document chunking with metadata
- β Multi-tenant support via namespaces
- β Extensible document loaders (txt, md, log)
- β Stable document IDs for upsert behavior
- β Source attribution and citation
- β REST API endpoints
Quick Test:
# Make sure environment is configured
# OPENAI_API_KEY, PINECONE_API_KEY, etc.
# Start API server
make api
# Add sample documents
curl -X POST "http://localhost:8000/llm/rag/directory" \
-H "Content-Type: application/json" \
-d '{"directory": "data/initial_knowledge", "recursive": true}'
# Query the system
curl -X POST "http://localhost:8000/llm/rag/query" \
-H "Content-Type: application/json" \
-d '{"query": "What is Agent Lab?", "top_k": 5}'Full documentation: docs/rag_guide.md
The project includes a fully implemented multi-level memory system with short-term and long-term memory capabilities using LangChain and hybrid storage (MySQL + Pinecone).
Memory Types:
- Short-term Memory: Recent conversation buffer (buffer/window/summary strategies)
- Semantic Memory: Facts and knowledge extracted from conversations
- Episodic Memory: Temporal summaries of conversation episodes
- Profile Memory: Aggregated user characteristics and preferences
- Procedural Memory: Identified interaction patterns and workflows
Quick Start:
from agentlab.core.memory_service import IntegratedMemoryService
from agentlab.models import ChatMessage
from datetime import datetime
# Initialize memory service
memory_service = IntegratedMemoryService()
# Add messages
memory_service.add_message(
session_id="user-123",
message=ChatMessage(
role="user",
content="I love programming in Python",
timestamp=datetime.now()
)
)
# Get enriched context (includes all memory types)
context = memory_service.get_context("user-123")
print(f"Short-term: {context.short_term_context}")
print(f"Semantic facts: {context.semantic_facts}")
print(f"User profile: {context.user_profile}")
print(f"Patterns: {context.procedural_patterns}")
# Search semantic memory
results = memory_service.search_semantic(
query="Python programming",
top_k=5
)Features:
- β LangChain memory integration (Buffer, Window, Summary)
- β MySQL persistence for structured data
- β Pinecone for semantic embeddings (optional)
- β Configurable retention policies
- β Multi-session support
- β REST API endpoints
Configuration:
# Database (required)
DB_HOST=localhost
DB_USER=your_user
DB_PASSWORD=your_password
DB_NAME=agent_lab
# Memory strategy
MEMORY_TYPE=buffer # buffer, summary, or window
ENABLE_LONG_TERM=true # Enable semantic/episodic/profile memory
SEMANTIC_STORAGE=hybrid # mysql, pinecone, or hybrid
# Optional: Pinecone for semantic search
PINECONE_API_KEY=pcsk_...
PINECONE_INDEX_NAME=agent-lab-memoryQuick Test:
# Run example script
uv run python -m agentlab.examples.memory_example
# Test via API
curl -X POST "http://localhost:8000/llm/memory/context" \
-H "Content-Type: application/json" \
-d '{"session_id": "user-123", "max_tokens": 2000}'Full documentation: docs/memory_guide.md
# Add runtime dependency
uv add <package-name>
# Add development dependency
uv add --dev <package-name>
# Examples:
uv add langchain-anthropic # Add Anthropic support
uv add --dev pytest-asyncio # Add async test support# Update specific package
uv lock --upgrade-package langchain
# Update all packages
uv lock --upgrade
# Sync after updating
uv syncuv remove <package-name>This project follows SOLID principles and enforces:
- 150-line maximum per file (refactor if exceeded)
- Protocol-based interfaces for dependency injection
- Type hints for all function signatures
- Docstrings for all public APIs (Google style)
- Composition over inheritance
See AGENTS.md for complete coding guidelines.
# Auto-format all code
make format
# Check formatting without changes
uv run ruff format --check# Run linter
make lint
# Auto-fix issues
uv run ruff check --fix# Run before committing (unit tests + format + lint)
make pre-commitknowledge_base: Stores documents and embeddings for RAG
- id: INT (primary key)
- doc_id: VARCHAR(255) (unique)
- content: TEXT
- embedding: JSON
- metadata: JSON
- created_at: TIMESTAMPchat_history: Stores conversation history
- id: INT (primary key)
- session_id: VARCHAR(255)
- role: ENUM('user', 'assistant', 'system')
- content: TEXT
- metadata: JSON
- created_at: TIMESTAMPmpc_instances: Tracks MPC server instances
- id: INT (primary key)
- instance_id: VARCHAR(255) (unique)
- status: ENUM('running', 'stopped', 'error')
- host: VARCHAR(255)
- port: INT
- metadata: JSON
- created_at: TIMESTAMP- Implement llm_interface.py
- Add support for multiple providers (OpenAI, Anthropic, etc.)
- Experiment with different prompting strategies
- Implement rag_service.py
- Add document embedding generation
- Build similarity search functionality
- Implement mpc_client_base.py
- Implement mpc_server_base.py
- Follow Anthropic's MCP specification
- Complete FastAPI routes in chat_routes.py
- Add authentication and rate limiting
- Build comprehensive test suite
- Choose React or Vue.js
- Implement chat interface
- Build MPC instance manager UI
models.py: Protocol definitions and data models
LLMInterface: Abstract interface for LLM implementationsRAGService: Protocol for RAG operationsMemoryService: Protocol for memory operations β¨ShortTermMemory&LongTermMemory: Memory sub-protocols β¨MPCClient/MPCServer: MPC protocol interfaces- Data models:
ChatMessage,RAGResult,MemoryContext,MemoryStatsβ¨
database/: Database layer
- config.py: MySQL connection configuration
- models.py: Table schemas and SQL definitions
- crud.py: CRUD operations
core/: Business logic
- rag_service.py: RAG implementation
- mpc_manager.py: MPC instance manager
- llm_interface.py: LangChain LLM wrapper
- memory_service.py: Memory management β¨
agents/: Low-level implementations
- rag_processor.py: Embedding generation, chunking
- mpc_client_base.py: MPC client base class
- mpc_server_base.py: MPC server base class
- memory_processor.py: Long-term memory processor β¨
api/: FastAPI application
- main.py: FastAPI app entry point
- routes/chat_routes.py: Chat & RAG endpoints
- routes/mpc_routes.py: MPC management endpoints
- Project structure and organization
- Protocol definitions and interfaces
- Database schema design
- FastAPI application with routes
- Development tooling (Makefile, testing setup)
- LangChain LLM integration β¨
- RAG service with Pinecone β¨
- Memory system (short-term & long-term) β¨
- Document chunking and embedding
- Multi-tenant namespace support
- Unit tests for RAG and memory modules
- Database CRUD operations (MySQL)
- MCP client/server implementations
- Integration tests for memory module
- Frontend application
- Additional document loaders (PDF, HTML, DOCX)
- Authentication and rate limiting
- Docker composition
- Automatic retention policy enforcement
This is a learning project. To contribute:
- Follow the coding guidelines in AGENTS.md
- Maintain 150-line limit per file
- Use Protocol-based interfaces for new features
- Add unit tests for all new code
- Run
make pre-commitbefore committing - Add docstrings with Args, Returns, and Raises sections
- AGENTS.md - Comprehensive coding guidelines
- LLM Interface Guide - LLM integration
- RAG Guide - Retrieval Augmented Generation
- Memory Guide - Conversation memory system β¨
- Frontend README - Frontend structure
- Data README - Data directory usage
# Check MySQL is running
mysql -u root -p
# Verify credentials in .env
cat .env | grep DB_# Ensure dependencies are synced
uv sync
# Verify package is installed
uv pip list | grep agentlab# Change API port in .env
API_PORT=8001
# Or specify when running
uv run uvicorn agentlab.api.main:app --port 8001- Built for IA Bootcamp 2025
- Based on Python template by Alejandro FernΓ‘ndez Camello
This project is for educational purposes.