A production-ready asynchronous Python boilerplate for building a Multi-Agent Telegram AI Chatbot using FastAPI, aiogram, SQLAlchemy (PostgreSQL/Supabase), and Docker.
It features an intelligent Router Agent that dynamically directs user questions to specialized agents (Support Agent & Analytics Agent) based on the query type.
graph TD
User([👤 User via Telegram]) -->|Sends Message| TelegramBot[🤖 Telegram Bot API]
TelegramBot -->|Webhooks / Polling| FastAPI[⚡ FastAPI Webhook Server]
FastAPI -->|Invokes Router| RouterAgent[🧭 Router Agent]
RouterAgent -->|Analyzes query| Decision{Category?}
Decision -->|General Chat / Q&A| SupportAgent[💬 Support Agent]
Decision -->|Math / Calculations| AnalyticsAgent[📊 Analytics Agent]
SupportAgent -->|Call LLM API| LLM[🧠 OpenAI GPT / Gemini API]
AnalyticsAgent -->|Call LLM API| LLM
SupportAgent -->|Formulate Answer| Response[✉️ Response]
AnalyticsAgent -->|Formulate Answer| Response
Response -->|Log Message| Postgres[(🗄️ PostgreSQL / Supabase)]
Response -->|Send Message| TelegramBot
TelegramBot -->|Delivered Response| User
- ⚡ FastAPI Integration: High-performance asynchronous routing, exposing webhook and health-check endpoints.
- 🧭 Multi-Agent Orchestration: Dynamic semantic routing between specialized agents (
RouterAgent,SupportAgent,AnalyticsAgent). - 🗄️ Database Session Logs: Automatically records user data, commands, messages, and which agent handled the request into PostgreSQL using SQLAlchemy 2.0.
- 🐳 Containerized with Docker: Comes with ready-to-use multi-stage
Dockerfileanddocker-compose.ymlconfiguration. - 🛡️ Robust Fallbacks: Fully operational locally even without OpenAI/Gemini API keys using integrated keyword-based routers and mock fallbacks.
- Docker & Docker Compose
- Python 3.11+ (if running bare metal)
- Telegram Bot Token (Get it from @BotFather)
Copy the .env.example file and customize it with your credentials:
cp .env.example .envFill out the variables inside .env:
TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
OPENAI_API_KEY=your_openai_api_key
GEMINI_API_KEY=your_gemini_api_keyStart the database and the chatbot container with a single command:
docker-compose up -bin --buildThis starts:
- A PostgreSQL database on port
5432with persistent storage. - The FastAPI chatbot application on port
8000(which connects to the database and automatically starts polling Telegram for messages).
If you want to run the python script directly without Docker:
# Create and activate virtual environment
python -m venv venv
source venv/bin/activate # On Windows use: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Run database setup and launch the app
python main.py├── Dockerfile # Docker build file
├── docker-compose.yml # Orchestrates FastAPI & PostgreSQL containers
├── requirements.txt # Python library dependencies
├── .env.example # Environment variables template
├── config.py # Settings and configuration validation
├── database.py # SQLAlchemy models, sessions, and DB initializer
├── agents.py # Multi-Agent logic (Router, Support, Analytics)
├── bot_handlers.py # Telegram commands and message handlers
├── main.py # FastAPI application & lifecycle entry point
└── README.md # Project documentation
/start- Welcomes user and initializes session inside the database./help- Shows help documentation./history- Fetches and prints the last 10 messages stored in the database for the current user.
To add a new specialist agent (e.g., a "Code Expert Agent" or "Image Creator Agent"):
- Inherit from
BaseAgentinagents.pyand implement therunmethod. - Register the agent inside the
specialistsdictionary ofRouterAgentinsideagents.py. - Update the routing instructions string in
RouterAgentso the LLM knows when to pick your new agent.