A sophisticated AI-powered task routing system where a central Peer Agent intelligently delegates user tasks to specialized AI agents. Built with FastAPI, LangChain, MongoDB, and Docker.
- π§ Intelligent Task Routing: Keyword-based analysis routes tasks to appropriate AI agents
- π Content Generation: Research, blog posts, articles with web search integration
- π» Code Generation: Multi-language code generation, debugging, and optimization
- π Web Search Integration: Real-time information gathering with DuckDuckGo
- π Session Management: Track user interactions across multiple requests
- ποΈ MongoDB Logging: Persistent storage of all interactions and analytics
- π³ Docker Ready: Fully containerized for easy deployment
- π§ͺ Comprehensive Testing: 30+ tests ensuring reliability
User Request β Peer Agent β Task Analysis β Specialized Agent β Response
β
MongoDB Logging
- ContentAgent: Blog posts, articles, research with web search
- CodeAgent: Code generation in 20+ programming languages
- PeerAgent: Central router with keyword-based task classification
- Python 3.9+
- OpenAI API Key (Get one here)
- MongoDB (optional - runs without it)
- Docker (optional - for containerized deployment)
# Clone the repository
git clone <your-repo-url>
cd peer-agent
# Create virtual environment
python -m venv venv
# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
# Install dependencies
pip install -r requirements.txtQuick Setup (Recommended):
# Run the setup script to create configuration files
python setup.pyManual Setup:
Create a .env file in the project root with your API keys:
# Required - OpenAI API Configuration
OPENAI_API_KEY=your_openai_api_key_here
OPENAI_MODEL=gpt-3.5-turbo
OPENAI_MAX_TOKENS=1500
# Optional - MongoDB Configuration
MONGODB_URI=mongodb://localhost:27017/peer_agent
MONGODB_DATABASE=peer_agent
# Optional - API Configuration
API_HOST=0.0.0.0
API_PORT=8000
API_DEBUG=True
# Optional - Agent Configuration
CONTENT_AGENT_ENABLED=True
CODE_AGENT_ENABLED=True
MAX_SEARCH_RESULTS=5
# Optional - Search Engine Configuration
# SerpAPI key for enhanced search results (leave empty to use DuckDuckGo)
# Get one from: https://serpapi.com/
SERPAPI_KEY=your_serpapi_key_here
β οΈ Important: Never commit your.envfile with real API keys!
Run the comprehensive test suite to verify everything works:
# Run all tests
python -m pytest tests/ -v
# Run specific test categories
python -m pytest tests/test_peer_agent.py -v # Core routing tests
python -m pytest -m "unit" -v # Unit tests only
python -m pytest -m "not slow" -v # Exclude slow tests
# Check test coverage
python -m pytest --cov=. --cov-report=htmlExpected Result: Core functionality tests should pass, validating the system works correctly.
# Method 1: Using uvicorn directly
uvicorn api.main:app --host 0.0.0.0 --port 8000 --reload
# Method 2: Using Python module
python -m uvicorn api.main:app --host 0.0.0.0 --port 8000 --reloadThe API will be available at:
- API Docs: http://localhost:8000/docs
- Health Check: http://localhost:8000/health
- Main Endpoint: http://localhost:8000/v1/agent/execute
If you want persistent logging:
# Install MongoDB locally, or use Docker:
docker run -d -p 27017:27017 --name mongodb mongo:latest# Build and start all services
docker-compose up --build
# Or run in background
docker-compose up -d --build
# View logs
docker-compose logs -f
# Stop services
docker-compose downCreate .env.docker for container-specific settings:
# Docker Environment Configuration
OPENAI_API_KEY=your_openai_api_key_here
MONGODB_URI=mongodb://mongo:27017/peer_agent
API_HOST=0.0.0.0
API_PORT=8000- API: FastAPI application on port 8000
- MongoDB: Database on port 27017 with persistent volume
- Health Checks: Automatic service health monitoring
POST /v1/agent/execute
{
"task": "Your task description here",
"session_id": "optional-session-uuid"
}curl -X POST "http://localhost:8000/v1/agent/execute" \
-H "Content-Type: application/json" \
-d '{
"task": "Write a blog post about artificial intelligence trends"
}'curl -X POST "http://localhost:8000/v1/agent/execute" \
-H "Content-Type: application/json" \
-d '{
"task": "Write a Python function to calculate fibonacci numbers"
}'curl -X POST "http://localhost:8000/v1/agent/execute" \
-H "Content-Type: application/json" \
-d '{
"task": "Research latest developments in quantum computing"
}'{
"success": true,
"agent_type": "content",
"session_id": "550e8400-e29b-41d4-a716-446655440000",
"timestamp": "2024-01-01T12:00:00",
"request_id": "req_123456",
"result": {
"agent": "content",
"task": "Write a blog post about AI",
"content": "# AI Blog Post\n\nContent here...",
"processing_time_seconds": 2.5,
"success": true
}
}GET /healthGET /v1/agent/capabilitiesGET /v1/agent/routing-infoGET /v1/agent/sessions/{session_id}/historyGET /v1/agent/stats- "Write a blog post about..."
- "Create an article about..."
- "Research information on..."
- "Generate content about..."
- "Write a Python function to..."
- "Debug this JavaScript code..."
- "Create a REST API in..."
- "Implement a sorting algorithm..."
Python, JavaScript, TypeScript, Java, C++, C#, C, Go, Rust, PHP, Ruby, Swift, Kotlin, Scala, HTML, CSS, SQL, Bash, PowerShell, R, MATLAB
β STATUS: FULLY OPERATIONAL with SerpAPI
The system features intelligent web search integration that automatically detects when tasks require current information and performs searches accordingly.
User Task β PeerAgent β ContentAgent or CodeAgent
β
ContentAgent analyzes task for search keywords
β
π Search Required? β Web Search + Content Generation
π No Search? β Direct Content Generation
The ContentAgent automatically triggers web search when tasks contain these keywords:
Search Keywords: research, information, current, latest, news, facts, data
# β
TRIGGERS SEARCH - These will search the web:
"Research latest developments in AI"
"Find information about State College weather"
"What's the current status of climate change?"
"Latest news about cryptocurrency"
"Get facts about renewable energy"
"Provide data on population growth"
# β NO SEARCH - These generate content directly:
"Write a creative blog about happiness"
"Create a story about dragons"
"Draft an email template"
"Write a poem about nature"The system intelligently selects the best available search engine:
-
β SerpAPI (Premium) - CURRENTLY ACTIVE
- Structured JSON results with rich metadata
- High-quality, relevant search results
- Requires API key:
SERPAPI_KEY=your_serpapi_key
-
π DuckDuckGo (Fallback)
- Free search, no API key required
- Plain text results
- Automatically used if SerpAPI unavailable
When search is performed:
- Results Found: Web data is integrated into AI-generated content with citations
- No Results: AI generates content based on training data (with disclaimer)
- Sources Added: Automatic citation section with links
# Search API Configuration
SERPAPI_KEY=your_serpapi_key_here # Optional but recommended
MAX_SEARCH_RESULTS=5 # Number of results to include
# Search Engine Selection (automatic based on available keys)
SEARCH_ENGINE=serpapi # serpapi or duckduckgo| Task Type | Example | Search Triggered? | Output Includes |
|---|---|---|---|
| Research | "Research quantum computing trends" | β Yes | Current web data + citations |
| Current Info | "Latest information about Tesla stock" | β Yes | Real-time data + sources |
| Creative | "Write a story about space travel" | β No | AI-generated creative content |
| Educational | "Explain machine learning concepts" | β No | AI knowledge without web search |
| News | "What's the latest news in tech?" | β Yes | Current news articles + links |
When search is triggered, responses include:
{
"result": {
"content": "Generated content with web search data...",
"search_performed": true,
"search_results_count": 5,
"sources": [
{
"title": "Article Title",
"url": "https://example.com",
"source": "SerpAPI"
}
]
}
}- Search not triggering: Ensure task contains search keywords
- No results found: SerpAPI/DuckDuckGo may have rate limits
- JSON parsing errors: Check SerpAPI key validity
- Fallback to DuckDuckGo: SerpAPI key missing/invalid
# Check search tool selection in logs:
python -m api.main
# Look for: "Search tool: SerpAPI selected" or "Search tool: DuckDuckGo"
# Test search functionality:
curl -X POST "http://localhost:8000/v1/agent/execute" \
-H "Content-Type: application/json" \
-d '{"task": "research current AI trends"}'peer-agent/
βββ agents/ # AI Agent implementations
β βββ peer_agent.py # Central task router
β βββ content_agent.py # Content generation
β βββ code_agent.py # Code generation
βββ api/ # FastAPI application
β βββ main.py # API endpoints
βββ models/ # Data models
β βββ schemas.py # Pydantic schemas
βββ database/ # Database integration
β βββ mongo.py # MongoDB operations
βββ tests/ # Test suite
β βββ test_peer_agent.py
β βββ test_agents.py
β βββ test_api.py
β βββ test_integration.py
βββ docker-compose.yml # Docker orchestration
βββ Dockerfile # Container definition
βββ requirements.txt # Python dependencies
βββ README.md # This file
1. OpenAI API Key Issues
# Error: "No API key provided"
# Solution: Check your .env file has OPENAI_API_KEY set2. MongoDB Connection Issues
# Error: "Database connection failed"
# Solution: The app works without MongoDB, but check connection string3. Port Already in Use
# Error: "Port 8000 is already in use"
# Solution: Change port in .env or stop other services
uvicorn api.main:app --port 80014. Import Errors
# Error: "Module not found"
# Solution: Ensure virtual environment is activated and dependencies installed
pip install -r requirements.txt5. Search Functionality Issues
# Error: "SerpAPI module not found"
# Solution: Install optional search dependencies
pip install google-search-results
# Warning: "Falling back to DuckDuckGo"
# This is normal if no SerpAPI key is provided - DuckDuckGo works fine
# Error: "Failed to parse SerpAPI results: Expecting property name..."
# Solution: This is handled automatically - system falls back to DuckDuckGo parsing
# Issue: "Search not triggering when expected"
# Solution: Include search keywords: research, information, current, latest, news, facts, data
# Issue: "OpenAI API error with placeholder key"
# Solution: Replace placeholder OPENAI_API_KEY with actual API key from platform.openai.com- API Documentation: Visit
/docsfor interactive Swagger UI - Debug Mode: Set
API_DEBUG=Truein.envfor detailed logs - Testing: Run tests before making changes to ensure stability
- Logs: Check application logs for detailed error information
- Fork the repository
- Create a feature branch:
git checkout -b feature-name - Make your changes
- Run tests:
python -m pytest tests/ -v - Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
- LangChain for AI agent framework
- FastAPI for high-performance API framework
- OpenAI for language model capabilities
- MongoDB for document storage
- Docker for containerization
π Ready to delegate your tasks to AI agents? Get started now!