Content
# 🎫 Smart Flight Booking System
[](https://python.org)
[](https://fastapi.tiangolo.com)
[](https://sqlite.org)
[](https://azure.microsoft.com/en-us/products/ai-services/openai-service)
This is a smart flight booking system based on a **multi-agent collaboration** architecture and **MCP (Model Context Protocol)**. The system implements complete flight inquiry, booking, and management functions through two collaborating AI Agents, showcasing best practices for communication and collaboration among modern AI Agents.
## 📖 Table of Contents
- [🏗️ System Architecture](#️-system-architecture)
- [✨ Core Features](#-core-features)
- [🛠️ Tech Stack](#-tech-stack)
- [🚀 Quick Start](#-quick-start)
- [⚙️ Configuration Instructions](#-configuration-instructions)
- [🎮 User Guide](#-user-guide)
- [📚 API Documentation](#-api-documentation)
- [🔧 Development Guide](#-development-guide)
- [🌟 Project Highlights](#-project-highlights)
- [🔧 Troubleshooting](#-troubleshooting)
## 🏗️ System Architecture
```
┌─────────────────────────────────────────────────────────────────┐
│ Smart Flight Booking System Architecture │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────┐ ┌─────────────────┐
│ Smart Agent 1 │◄────────────►│ Smart Agent 2 │
│ Booking Manager │ MCP Protocol Communication │ Flight Inquiry Assistant │
│ │ │ │
│ ✓ Create Booking │ │ ✓ Query Flights │
│ ✓ Query Booking │ │ ✓ Search Routes │
│ ✓ Modify Booking │ │ ✓ Price Inquiry │
│ ✓ Delete Booking │ │ ✓ Seat Inquiry │
│ ✓ AI Conversation │ │ ✓ Smart Recommendations │
└─────────┬───────┘ └─────────┬───────┘
│ │
│ MCP Protocol │
│ │
┌─────▼────────────────────────────────▼─────┐
│ MCP HTTP Server │
│ │
│ FastAPI + RESTful APIs │
│ ┌─────────────────────────────────────┐ │
│ │ Booking APIs │ Flight APIs │ │
│ │ POST /bookings │ GET /flights │ │
│ │ GET /bookings │ GET /flights/{id} │ │
│ │ PUT /bookings │ POST /flights │ │
│ │ DELETE /booking │ DELETE /flights │ │
│ └─────────────────────────────────────┘ │
└─────────────────┬─────────────────────────┘
│
┌─────▼─────┐ ┌─────────────┐
│ SQLite │ │ Azure OpenAI│
│ Database │ │ GPT-4.1 │
│ │ │ │
│📋 bookings│ │🤖 Smart Conversation │
│✈️ flights │ │💬 Natural Language │
└───────────┘ └─────────────┘
```
### Core Component Description
| Component | Responsibility | Technical Implementation |
|-----------|----------------|--------------------------|
| **Booking Management Agent** | Handles all booking-related operations and provides an intelligent conversation interface | Python + Azure OpenAI |
| **Flight Inquiry Agent** | Manages flight information and provides inquiry and recommendation services | Python + Intelligent Algorithms |
| **MCP HTTP Server** | Provides standardized API interfaces and handles communication between agents | FastAPI + Pydantic |
| **SQLite Database** | Lightweight data persistence storage | Local file database |
| **Azure OpenAI** | Provides GPT-4.1 intelligent conversation capabilities | Azure Cognitive Services |
## ✨ Core Features
### 🎫 Smart Agent 1: Booking Management Assistant
- **🆕 Create Booking**: Complete booking information entry and validation
- **🔍 Query Booking**: Search bookings by ID or passenger name
- **✏️ Modify Booking**: Update seat, status, and other information
- **🗑️ Delete Booking**: Safe booking cancellation feature
- **🤖 Intelligent Conversation**: Natural language understanding based on Azure OpenAI
### ✈️ Smart Agent 2: Flight Inquiry Assistant
- **🔍 Flight Inquiry**: Real-time flight information retrieval
- **🗺️ Route Search**: Inquiry from departure to destination
- **🏢 Airline Filtering**: Query by airline classification
- **💺 Seat Inquiry**: Real-time seat availability check
- **🎯 Smart Recommendations**: AI-based personalized recommendations
### 🔄 Multi-Agent Collaboration Features
- **Intelligent Workflow Orchestration**: Automatic task allocation and result aggregation
- **Data Consistency Assurance**: Transaction management across agents
- **Real-time Status Synchronization**: Sharing of status information between agents
- **Fault Tolerance Mechanism**: Failure retry and degradation handling
## 🛠️ Tech Stack
### Backend Technologies
| Technology | Version | Purpose |
|------------|---------|---------|
| **Python** | 3.13+ | Main programming language |
| **FastAPI** | 0.115.14 | Web framework and API service |
| **SQLAlchemy** | 2.0.41 | ORM and database operations |
| **Pydantic** | 2.11.7 | Data validation and serialization |
| **Uvicorn** | 0.34.3 | ASGI server |
### Data Storage
| Technology | Version | Purpose |
|------------|---------|---------|
| **SQLite** | 3 | Lightweight local database |
### AI and External Services
| Service | Model | Purpose |
|---------|-------|---------|
| **Azure OpenAI** | GPT-4.1 | Intelligent conversation and natural language processing |
## 🚀 Quick Start
### Prerequisites
- **Python 3.13+**: To run the application
- **Azure OpenAI Account**: To obtain API key
### One-Click Start
```bash
# Clone the project
git clone <your-repo-url>
cd A2A-ticketbooking
# One-click start of the entire system (recommended)
./start_system.sh
```
### Manual Start
If one-click start fails, you can execute manually:
```bash
# 1. Create and activate a virtual environment
python3 -m venv venv
source venv/bin/activate
# 2. Install dependencies
pip install fastapi uvicorn pydantic openai requests python-dotenv sqlalchemy alembic
# 3. Configure environment variables
cp .env.example .env
# Edit the .env file to set your Azure OpenAI configuration
# 4. Initialize the database
python init_db.py
# 5. Start the MCP server
python mcp_server.py
```
Once the system starts successfully, you will see:
```
🚀 Starting MCP server...
📍 Address: http://localhost:8000
📖 API Documentation: http://localhost:8000/docs
```
## ⚙️ Configuration Instructions
### Environment Configuration
Edit the `.env` file to set configurations:
```env
# Azure OpenAI Configuration
AZURE_OPENAI_ENDPOINT=https://your-endpoint.openai.azure.com/openai/deployments/gpt-4.1/chat/completions?api-version=2025-01-01-preview
AZURE_OPENAI_API_KEY=your-api-key-here
# Database Configuration
DATABASE_URL=sqlite:///./smart_flight_booking.db
# MCP Server Configuration
MCP_SERVER_HOST=localhost
MCP_SERVER_PORT=8000
```
### Azure OpenAI Configuration Steps
1. Log in to [Azure Portal](https://portal.azure.com)
2. Create or select an Azure OpenAI resource
3. Deploy the GPT-4.1 model
4. Obtain the API key and endpoint address
5. Update the configuration in the `.env` file
## 🎮 User Guide
### Quick Demo
```bash
# Activate the virtual environment
source venv/bin/activate
# Run the quick demo script
python quick_demo.py
```
### Running the Smart Assistants
#### 1. Booking Management Assistant
```bash
source venv/bin/activate
python booking_agent.py
```
**Interaction Example:**
```
🎫 Smart Booking Management Assistant
============================================================
Please enter a command or ask: create
📝 Creating a new booking
------------------------------
Booking Title: Zhang San's Business Trip
Passenger Name: Zhang San
Flight Number: CA1001
...
✅ Booking created successfully! Booking ID: 1
Please enter a command or ask: Help me find all bookings for Zhang San
🤖 AI Assistant: I will help you find all booking records for Zhang San...
```
#### 2. Flight Inquiry Assistant
```bash
source venv/bin/activate
python airline_agent.py
```
**Interaction Example:**
```
✈️ Smart Flight Inquiry Assistant
============================================================
Please enter a command or ask: search PEK SHA
🔍 Searching for flights: PEK → SHA
------------------------------------------------------------
Flight Number Airline Departure Time Arrival Time Price Available Seats
------------------------------------------------------------
CA1001 Air China 08:30:00 10:45:00 ¥680 120
Please enter a command or ask: Recommend some cheap flights from Beijing to Shanghai
🤖 AI Assistant: Based on your needs, I recommend the following flights...
```
#### 3. Multi-Agent Collaboration Demo
```bash
source venv/bin/activate
python agent_communication_demo.py
```
### System Status Check
```bash
source venv/bin/activate
python check_status.py
```
## 📚 API Documentation
After starting the server, you can access the API documentation at the following addresses:
- **Swagger UI**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc
### Main API Endpoints
#### Booking Management API
- `POST /bookings` - Create a booking
- `GET /bookings` - Get all bookings
- `GET /bookings/{id}` - Get a single booking
- `PUT /bookings/{id}` - Update a booking
- `DELETE /bookings/{id}` - Delete a booking
- `GET /bookings/search/{passenger_name}` - Search by passenger name
#### Flight Inquiry API
- `GET /flights` - Get all flights
- `GET /flights/{id}` - Get a single flight
- `GET /flights/search/{from}/{to}` - Search flights
- `GET /flights/number/{flight_number}` - Query by flight number
#### System API
- `GET /health` - Health check
- `GET /stats` - System statistics
### API Testing Examples
```bash
# Health check
curl http://localhost:8000/health
# Get all flights
curl http://localhost:8000/flights
# Search flights
curl http://localhost:8000/flights/search/PEK/SHA
# Create a booking
curl -X POST "http://localhost:8000/bookings" \
-H "Content-Type: application/json" \
-d '{
"title": "Test Booking",
"passenger_name": "Test User",
"flight_number": "CA1001",
"departure_date": "2024-08-15",
"departure_time": "08:30:00",
"arrival_date": "2024-08-15",
"arrival_time": "10:45:00",
"departure_airport": "PEK",
"arrival_airport": "SHA",
"price": "680.00"
}'
```
## 🔧 Development Guide
### Project Structure
```
A2A-ticketbooking/
├── 📄 README.md # Project documentation
├── 📄 requirements.txt # Python dependencies
├── 📄 .env # Environment configuration
├── 📄 .env.example # Environment configuration template
├── 📄 .gitignore # Git ignore file
├── 📄 start_system.sh # One-click start script
├── 🗄️ database.py # Database model definitions
├── 🔧 init_db.py # Database initialization script
├── 🌐 mcp_server.py # MCP HTTP server
├── 🤖 booking_agent.py # Booking management assistant
├── ✈️ airline_agent.py # Flight inquiry assistant
├── 🔄 agent_communication_demo.py # Multi-Agent collaboration demo
├── 🧠 azure_openai_client.py # Azure OpenAI client
├── 🧪 test_mcp_server.py # MCP server tests
├── ⚡ quick_demo.py # Quick demo script
├── 🔍 check_status.py # System status check
├── 🗃️ smart_flight_booking.db # SQLite database file
└── 📁 venv/ # Python virtual environment
```
### Database Schema
The system uses an SQLite database with two main tables:
```sql
-- Flights Table
CREATE TABLE flights (
id INTEGER PRIMARY KEY,
flight_number VARCHAR(20) UNIQUE NOT NULL,
airline VARCHAR(50) NOT NULL,
departure_airport VARCHAR(10) NOT NULL,
arrival_airport VARCHAR(10) NOT NULL,
departure_time TIME NOT NULL,
arrival_time TIME NOT NULL,
price DECIMAL(10,2) NOT NULL,
available_seats INTEGER DEFAULT 0,
aircraft_type VARCHAR(50),
status VARCHAR(20) DEFAULT 'active',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Bookings Table
CREATE TABLE bookings (
id INTEGER PRIMARY KEY,
title VARCHAR(200) NOT NULL,
passenger_name VARCHAR(100) NOT NULL,
flight_number VARCHAR(20) NOT NULL,
departure_date DATE NOT NULL,
departure_time TIME NOT NULL,
arrival_date DATE NOT NULL,
arrival_time TIME NOT NULL,
departure_airport VARCHAR(10) NOT NULL,
arrival_airport VARCHAR(10) NOT NULL,
seat_number VARCHAR(10),
price DECIMAL(10,2) NOT NULL,
status VARCHAR(20) DEFAULT 'confirmed',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
### Airport Code Reference
| Code | Airport Name | City |
|------|--------------|------|
| PEK | Beijing Capital International Airport | Beijing |
| SHA | Shanghai Hongqiao International Airport | Shanghai |
| PVG | Shanghai Pudong International Airport | Shanghai |
| CAN | Guangzhou Baiyun International Airport | Guangzhou |
| CTU | Chengdu Shuangliu International Airport | Chengdu |
| KMG | Kunming Changshui International Airport | Kunming |
| XIY | Xi'an Xianyang International Airport | Xi'an |
| HGH | Hangzhou Xiaoshan International Airport | Hangzhou |
## 🌟 Project Highlights
### 1. 🤝 True Multi-Agent Collaboration
- **Intelligent Task Division**: Two AI assistants perform their respective roles, communicating via the MCP protocol
- **Dynamic Workflow**: Automatically orchestrates workflows based on business needs
- **Status Synchronization**: Maintains data consistency between agents in real-time
### 2. 🔗 MCP Protocol Implementation
- **Standardized Communication**: Follows MCP protocol specifications for agent communication
- **Extensibility Design**: Easy to add new agents and functional modules
- **Interoperability**: Supports seamless integration of agents with different tech stacks
### 3. 🧠 AI-Driven Interaction
- **Natural Language Understanding**: Supports Chinese natural language queries and commands
- **Context Awareness**: Maintains context continuity in multi-turn conversations
- **Smart Recommendations**: Personalized recommendations based on user preferences and historical data
### 4. 🏗️ Lightweight Architecture
- **Simple Deployment**: Uses SQLite, no complex database configuration required
- **Modular Design**: Easy to maintain and extend code structure
- **Comprehensive Testing**: Test cases covering major functionalities
### 5. 🚀 Excellent Development Experience
- **One-Click Deployment**: Automated deployment and configuration scripts
- **Detailed Documentation**: Comprehensive usage and development documentation
- **Rich Demonstrations**: Various demonstration scenarios and use cases
## 🔧 Troubleshooting
### Common Issues
#### Q: MCP Server Fails to Start
**Solution:**
```bash
# Check port usage
lsof -i :8000
# Check virtual environment
source venv/bin/activate
# Reinstall dependencies
pip install -r requirements.txt
# Manually start the server
python mcp_server.py
```
#### Q: Azure OpenAI API Call Fails
**Solution:**
1. Check the API key and endpoint in the `.env` file
2. Verify Azure subscription status
3. Check API quota limits
4. Confirm model deployment status
#### Q: Database Initialization Fails
**Solution:**
```bash
# Delete existing database file
rm smart_flight_booking.db
# Reinitialize the database
python init_db.py
```
#### Q: Dependency Installation Issues
**Solution:**
```bash
# Recreate the virtual environment
rm -rf venv
python3 -m venv venv
source venv/bin/activate
# Manually install core dependencies
pip install fastapi uvicorn pydantic openai requests python-dotenv sqlalchemy
```
### System Monitoring
Use the system status check tool:
```bash
python check_status.py
```
This tool will check:
- Python environment and dependencies
- Database status
- MCP server running status
- Azure OpenAI configuration
- API endpoint availability
---
## 📞 Support and Contribution
### Technical Support
If you encounter issues during use:
1. Check the troubleshooting section of this README
2. Run `python check_status.py` to check system status
3. Review server log files
### Contribution Guidelines
Contributions are welcome! Please follow these steps:
1. Fork the project
2. Create a feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push the branch (`git push origin feature/AmazingFeature`)
5. Create a Pull Request
---
## 📄 License
This project is licensed under the MIT License.
---
## 🎉 Acknowledgments
Thanks to the following technologies and communities for their support:
- [FastAPI](https://fastapi.tiangolo.com/) - Modern high-performance web framework
- [SQLite](https://sqlite.org/) - Lightweight database
- [Azure OpenAI](https://azure.microsoft.com/products/ai-services/openai-service) - Enterprise-level AI services
- [Python](https://python.org/) - Elegant programming language
---
**🚀 Congratulations! You have successfully deployed a complete Smart Flight Booking System!**
*If this project has been helpful to you, please give us a ⭐ Star to support us!*