A comprehensive FastAPI-based multi-agent AI system designed to handle complex tasks across different life domains. The system features specialized agents for food assistance, travel planning, shopping optimization, and payment processing, all coordinated by a central MasterAgent.
- Meal Planning: Create personalized meal plans based on dietary preferences and calorie goals
- Recipe Generation: Discover and generate recipes using available ingredients
- Grocery List Creation: Automatically generate shopping lists from meal plans
- Dietary Analysis: Analyze nutritional content and provide health recommendations
- Trip Planning: Plan complete trips with budget breakdowns and recommendations
- Flight Search: Find and compare flights across multiple airlines
- Hotel Search: Discover accommodations with detailed amenities and pricing
- Itinerary Generation: Create detailed day-by-day travel itineraries
- Booking Assistance: Help with booking confirmations and next steps
- Product Discovery: Find products based on search criteria and preferences
- Price Comparison: Compare prices across multiple vendors
- Order Optimization: Optimize orders for best value and delivery
- Deal Finding: Discover current deals and discounts
- Shopping Lists: Create organized shopping lists with budget tracking
- Quick Commerce Integration: Compare prices across Zepto, Blinkit, Swiggy Instamart, BigBasket
- Automated Ordering: Place orders automatically via headless browser automation
- Real-time Tracking: Track order status and delivery progress
- Order Creation: Create payment orders using Razorpay
- Payment Verification: Verify payment signatures for security
- Payment Links: Generate shareable payment links
- Refund Processing: Handle payment refunds
- Transaction History: Track payment history and methods
- Audio Transcription: Convert speech to text using Groq's Whisper API
- Multi-language Support: Support for 99+ languages
- Timestamp Support: Get word-level timestamps for audio
- Format Validation: Validate audio file formats
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β FastAPI App β β MasterAgent β β Domain Agents β
β β β β β β
β /assistant βββββΆβ Intent AnalysisβββββΆβ FoodAgent β
β /speech-to-textβ β Task Routing β β TravelAgent β
β /payment/* β β Response Synth β β ShoppingAgent β
β /quick-order β β β β QuickCommerce β
β /status β β β β PaymentAgent β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β
βΌ
βββββββββββββββββββ
β MCP Clients β
β β
β FoodAPIClient β
β GroqWhisper β
β RazorpayAPI β
β QuickCommerce β
βββββββββββββββββββ
- Python 3.10+
- Node.js 18+ (for frontend)
- uv (recommended) or pip
-
Clone the repository
git clone <repository-url> cd Order_Agent
-
Install dependencies
uv sync # or with pip pip install -e .
-
Set up environment variables
# API Keys for external services export SPOONACULAR_API_KEY="your_spoonacular_key" export GROQ_API_KEY="your_groq_key" export RAZORPAY_API_KEY="your_razorpay_key" export RAZORPAY_API_SECRET="your_razorpay_secret" export RAZORPAY_CALLBACK_URL="https://your-domain.com/callback" # Optional: Redis configuration export REDIS_URL="redis://localhost:6379" # Logging export LOG_LEVEL="INFO"
-
Run the application
Option 1: Automated startup (Recommended)
./start_dev.sh
Option 2: Manual startup
# Backend python main.py # Frontend (in another terminal) cd quickpick_frontend npm install npm run dev
-
Access the application
- Frontend: http://localhost:5173
- Backend API: http://localhost:8000
- API Documentation: http://localhost:8000/docs
- Health Check: http://localhost:8000/health
- System Status: http://localhost:8000/status
POST /assistant
Content-Type: application/json
{
"message": "Plan a healthy dinner for tonight",
"user_id": "user123",
"context": {}
}POST /speech-to-text
Content-Type: multipart/form-data
file: [audio file]
language: enPOST /payment/create-order
POST /payment/verify
POST /payment/create-link
GET /payment/methodsPOST /quick-order
POST /quick-order/approve
GET /quick-order/status/{order_id}
POST /test/quick-commerce{
"message": "Plan a 500-calorie dinner using chicken and vegetables"
}{
"message": "Find recipes for vegetarian pasta dishes"
}{
"message": "Create a grocery list for a week of healthy meals"
}{
"message": "Find flights from New York to Los Angeles for next week"
}{
"message": "Plan a 5-day trip to Paris with $2000 budget"
}{
"message": "Find hotels in downtown Tokyo for 3 people"
}{
"message": "Compare prices for wireless headphones under $100"
}{
"message": "Find deals on running shoes this week"
}{
"message": "Create a payment order for 500 rupees"
}{
"message": "Verify payment with ID pay_1234567890"
}{
"message": "Order tomatoes and milk"
}{
"message": "Find cheapest rice delivery"
}{
"message": "Compare prices for groceries across platforms"
}# API Keys for external services
SPOONACULAR_API_KEY=your_spoonacular_key
GROQ_API_KEY=your_groq_key
RAZORPAY_API_KEY=your_razorpay_key
RAZORPAY_API_SECRET=your_razorpay_secret
RAZORPAY_CALLBACK_URL=https://your-domain.com/callback
# Redis configuration (for future use)
REDIS_URL=redis://localhost:6379
# Logging
LOG_LEVEL=INFOEach agent can be configured with user preferences:
# Food preferences
food_agent.update_dietary_preferences(
restrictions=["vegetarian"],
allergies=["nuts"],
cuisine_preferences=["Italian", "Mediterranean"]
)
# Travel preferences
travel_agent.update_travel_preferences(
preferred_airlines=["Delta", "American"],
preferred_hotels=["Marriott", "Hilton"],
budget_preferences={"flights": 500, "hotels": 200},
travel_style="luxury"
)
# Shopping preferences
shopping_agent.update_shopping_preferences(
preferred_vendors=["Amazon", "Walmart"],
budget_constraints={"electronics": 1000, "clothing": 200},
product_preferences={"brands": ["Apple", "Nike"]}
)
# Payment preferences
payment_agent.update_payment_preferences(
preferred_currencies=["INR", "USD"],
payment_methods=["card", "upi", "netbanking"]
)Order_Agent/
βββ agents/ # Agent implementations
β βββ __init__.py
β βββ base_agent.py # Base agent class with common functionality
β βββ food_agent.py # Food domain agent
β βββ travel_agent.py # Travel domain agent
β βββ shopping_agent.py # Shopping domain agent (includes QuickCommerceAgent)
β βββ payment_agent.py # Payment processing agent
βββ master/ # Master agent coordination
β βββ __init__.py
β βββ master_agent.py # Central coordinator and router
βββ mcp/ # Model Context Protocol clients
β βββ __init__.py
β βββ food_api_client.py # Food API integrations (Spoonacular)
β βββ speech_to_text_client.py # Groq Whisper API client
β βββ razorpay_api_client.py # Razorpay payment gateway client
β βββ quick_commerce_scrapper.py # Quick commerce web scraping
βββ config/ # Configuration management
β βββ __init__.py
β βββ settings.py # Application settings and configuration
βββ utils/ # Utility functions
β βββ __init__.py
β βββ logger.py # Logging utilities
β βββ helpers.py # Helper functions
βββ tests/ # Test suite
β βββ __init__.py
β βββ conftest.py # Pytest configuration and fixtures
β βββ unit/ # Unit tests
β βββ integration/ # Integration tests
β βββ e2e/ # End-to-end tests
β βββ fixtures/ # Test data and fixtures
β βββ mocks/ # Mock objects
βββ quickpick_frontend/ # React frontend application
β βββ src/
β β βββ components/ # React components
β β βββ hooks/ # Custom React hooks
β β βββ lib/ # Utility libraries
β β βββ config/ # Frontend configuration
β β βββ pages/ # Page components
β βββ package.json
β βββ README.md
βββ main.py # FastAPI application entry point
βββ pyproject.toml # Project dependencies and configuration
βββ pytest.ini # Pytest configuration
βββ run_tests.py # Test runner script
βββ start_dev.sh # Development startup script
βββ .gitignore # Git ignore rules
βββ TESTING.md # Testing documentation
βββ INTEGRATION_GUIDE.md # Frontend-backend integration guide
βββ catalog.json # Product catalog data
βββ restaurant.json # Restaurant data sample
βββ sample.json # Sample API request data
βββ full_response.json # Sample response data
βββ sample_result.json # Sample result data
βββ text_to_speech.py # Text-to-speech functionality
βββ foodagent.py # Standalone food agent (legacy)
βββ menu-brows.py # Menu browsing functionality
βββ res-api-test.py # Restaurant API testing
βββ resapi2.py # Restaurant API implementation
βββ README.md # This file
- User Request: User sends natural language request to
/assistant - Intent Analysis: MasterAgent analyzes intent and determines required agents
- Task Routing: Request is routed to appropriate domain agents
- Agent Processing: Domain agents process requests using their specialized logic
- Response Synthesis: MasterAgent combines responses from multiple agents
- Unified Response: Single, coherent response is returned to user
The project includes a comprehensive test suite with unit, integration, and end-to-end tests.
# Install test dependencies
python run_tests.py --install-deps
# Run all tests
python run_tests.py --all
# Run with coverage
python run_tests.py --all --coverage
# Run CI pipeline
python run_tests.py --ci# Unit tests
python run_tests.py --unit
# Integration tests
python run_tests.py --integration
# End-to-end tests
python run_tests.py --e2e
# Specific test file
python run_tests.py --test tests/unit/test_food_agent.py# Run linting
python run_tests.py --lint
# Format code
python run_tests.py --format
# Type checking
python run_tests.py --typesFor detailed testing information, see TESTING.md.
# Test food agent
curl -X POST "http://localhost:8000/test/food"
# Test travel agent
curl -X POST "http://localhost:8000/test/travel"
# Test shopping agent
curl -X POST "http://localhost:8000/test/shopping"
# Test payment agent
curl -X POST "http://localhost:8000/test/payment"
# Test quick commerce
curl -X POST "http://localhost:8000/test/quick-commerce"# Test main assistant endpoint
curl -X POST "http://localhost:8000/assistant" \
-H "Content-Type: application/json" \
-d '{
"message": "Plan a healthy dinner for tonight",
"user_id": "test_user"
}'
# Test speech-to-text
curl -X POST "http://localhost:8000/speech-to-text" \
-F "[email protected]" \
-F "language=en"
# Test payment order creation
curl -X POST "http://localhost:8000/payment/create-order" \
-H "Content-Type: application/json" \
-d '{
"amount": 500.0,
"currency": "INR",
"receipt": "test_receipt_001"
}'
# Test quick commerce order
curl -X POST "http://localhost:8000/quick-order" \
-H "Content-Type: application/json" \
-d '{
"items": ["tomatoes", "milk", "bread"],
"delivery_preference": "fastest",
"auto_approve": false
}'
# Test quick commerce approval
curl -X POST "http://localhost:8000/quick-order/approve" \
-H "Content-Type: application/json" \
-d '{
"order_id": "order_123",
"approved": true,
"user_id": "user_123"
}'
# Test order status
curl -X GET "http://localhost:8000/quick-order/status/order_123?user_id=user_123"Main entry point for processing user requests. Analyzes intent, routes to appropriate agents, and synthesizes responses.
Parameters:
request_data: Dictionary containing message, user_id, and context
Returns:
- Unified response with primary response, additional suggestions, and recommendations
Analyzes user intent using pattern matching to determine which agents should handle the request.
Parameters:
user_message: The user's natural language input
Returns:
- Intent analysis with primary intent, involved agents, task type, and extracted data
Routes the request to appropriate agents based on intent analysis.
Parameters:
intent_analysis: Result from intent analysiscontext: Request context including user information
Returns:
- Dictionary of agent responses
Combines responses from multiple agents into a unified response.
Parameters:
agent_responses: Responses from individual agentscontext: Request context
Returns:
- Unified response with primary response and additional suggestions
Processes food-related requests including meal planning, recipe generation, and grocery lists.
Supported Request Types:
meal_planning: Create meal plans based on calories and preferencesrecipe_generation: Generate recipes from ingredientsgrocery_list: Create shopping lists from meal plansdietary_analysis: Analyze nutritional content
update_dietary_preferences(restrictions: List[str], allergies: List[str], cuisine_preferences: List[str])
Updates dietary preferences and restrictions for personalized recommendations.
Processes travel-related requests including trip planning, flight searches, and hotel bookings.
Supported Request Types:
trip_planning: Plan complete trips with budget breakdownsflight_search: Search and compare flightshotel_search: Find accommodations with amenitiesitinerary_generation: Create detailed travel itinerariesbooking_assistance: Help with booking confirmations
update_travel_preferences(preferred_airlines: List[str], preferred_hotels: List[str], budget_preferences: Dict[str, Any], travel_style: str)
Updates travel preferences for personalized recommendations.
Processes shopping-related requests including product discovery, price comparison, and deal finding.
Supported Request Types:
product_discovery: Find products based on search criteriaprice_comparison: Compare prices across vendorsorder_optimization: Optimize orders for best valuedeal_finding: Discover current deals and discountsshopping_list: Create organized shopping lists
update_shopping_preferences(preferred_vendors: List[str], budget_constraints: Dict[str, Any], product_preferences: Dict[str, Any])
Updates shopping preferences for personalized recommendations.
Processes quick commerce requests including price comparison, order placement, and tracking.
Supported Request Types:
quick_order: Compare prices and place orders across quick commerce platformscompare_prices_quick_commerce: Compare prices without placing ordersplace_order: Place orders on specific platformsorder_status: Check order status and tracking information
Handles quick order requests by comparing prices across platforms and placing orders.
Parameters:
items: List of items to orderpreferences: User preferences for delivery and platform selection
Returns:
- Order response with recommendations and order details
Compares prices for items across all supported quick commerce platforms.
Parameters:
items: List of items to compare
Returns:
- Price comparison data with best options for each platform
Automates order placement using headless browser automation.
Parameters:
platform: Target platform (zepto, blinkit, swiggy_instamart, bigbasket)items: List of items with quantities and detailsuser_id: User identifier
Returns:
- Order placement result with order ID and tracking information
update_quick_commerce_preferences(delivery_priority: str, max_delivery_time: int, preferred_platforms: List[str], auto_approve_threshold: float, quality_threshold: float)
Updates quick commerce preferences for personalized recommendations.
Parameters:
delivery_priority: Priority preference (fastest, cheapest, best_rated)max_delivery_time: Maximum acceptable delivery time in minutespreferred_platforms: List of preferred platformsauto_approve_threshold: Minimum savings threshold for auto-approvalquality_threshold: Minimum quality rating threshold
Processes payment-related requests using Razorpay integration.
Supported Request Types:
create_order: Create payment ordersverify_payment: Verify payment signaturescreate_payment_link: Generate shareable payment linksrefund_payment: Process payment refundsget_payment_methods: Retrieve available payment methodsget_transaction_history: Get payment history
Updates payment preferences for personalized recommendations.
create_order(amount: float, currency: str = "INR", receipt: Optional[str] = None, notes: Optional[Dict[str, str]] = None) -> Dict[str, Any]
Creates a new payment order using Razorpay API.
Parameters:
amount: Payment amountcurrency: Currency code (default: INR)receipt: Receipt identifiernotes: Additional notes
Returns:
- Order creation response with order ID and details
Verifies payment signature for security.
Parameters:
params_dict: Dictionary containing payment_id, order_id, and signature
Returns:
- Verification result with success/error status
create_payment_link(amount: float, currency: str = "INR", description: str = "", reference_id: Optional[str] = None) -> Dict[str, Any]
Creates a shareable payment link.
Parameters:
amount: Payment amountcurrency: Currency codedescription: Payment descriptionreference_id: Reference identifier
Returns:
- Payment link creation response with link URL
Transcribes audio file using Groq's Whisper API.
Parameters:
audio_file_path: Path to audio filelanguage: Language code (default: en)
Returns:
- Transcription result with text, language, and duration
transcribe_audio_bytes(audio_bytes: bytes, filename: str = "audio.wav", language: str = "en") -> Dict[str, Any]
Transcribes audio from bytes data.
Parameters:
audio_bytes: Audio data as bytesfilename: Original filenamelanguage: Language code
Returns:
- Transcription result
Returns list of supported languages for transcription.
Returns:
- Dictionary with supported languages and their codes
Searches for products on a specific quick commerce platform.
Parameters:
platform: Platform name (zepto, blinkit, swiggy_instamart, bigbasket)query: Search query for products
Returns:
- List of product dictionaries with name, price, rating, and availability
Places an order on a specific platform using headless browser automation.
Parameters:
platform: Target platform for order placementitems: List of items with quantities and detailsuser_id: User identifier for order tracking
Returns:
- Order placement result with order ID, status, and tracking information
Private method to handle Selenium-based web scraping for product data.
Parameters:
platform: Platform to scrapequery: Search query
Returns:
- Scraped product data
Finds the best deals across all platforms for given items.
Parameters:
items: List of items to find deals forpreferences: User preferences for optimization
Returns:
- Optimization result with best platform recommendations and savings
Selects the best product from a list based on preferences.
Parameters:
products: List of products to choose frompreferences: User preferences for selection
Returns:
- Best product based on price, rating, and availability
Optimizes the entire order across platforms.
Parameters:
all_results: Results from all platformspreferences: User preferences
Returns:
- Optimized order recommendation with platform selection and savings
search_recipes(query: str, max_results: int = 10, diet: Optional[str] = None, cuisine: Optional[str] = None) -> List[Dict[str, Any]]
Searches for recipes based on query and filters.
Parameters:
query: Search querymax_results: Maximum number of resultsdiet: Dietary restrictionscuisine: Cuisine type
Returns:
- List of recipe dictionaries
Gets detailed recipe information by ID.
Parameters:
recipe_id: Recipe identifier
Returns:
- Detailed recipe information or None if not found
Generates a meal plan based on calories and diet preferences.
Parameters:
calories: Target calorie countdiet: Diet typetime_frame: Planning timeframe
Returns:
- Meal plan with meals and shopping list
- Redis integration for message queuing and caching
- Vector database for preference learning and recommendations
- Real API integrations (Spoonacular, Skyscanner, etc.)
- WebSocket support for real-time updates
- User authentication and session management
- Advanced conversation memory and context
- Multi-language support for all agents
- Mobile app integration
- Voice response capabilities
- Advanced analytics and reporting
- FinanceAgent for budgeting and expense tracking
- HealthAgent for fitness and wellness
- EntertainmentAgent for movies, books, and events
- ProductivityAgent for task management and scheduling
- WeatherAgent for weather information and alerts
- NewsAgent for personalized news delivery
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
For support and questions:
- Create an issue in the GitHub repository
- Check the API documentation at
/docs - Review the test endpoints for examples
- Check the logs for debugging information
- Missing API Keys: Ensure all required environment variables are set
- Import Errors: Check that all dependencies are installed correctly
- Payment Failures: Verify Razorpay credentials and callback URLs
- Audio Transcription Issues: Check audio file format and size limits
- Agent Routing Problems: Review intent analysis patterns and agent configurations
Enable debug logging by setting LOG_LEVEL=DEBUG in your environment variables.
Happy coding! π