A modern, production-ready FastAPI-based AI chat application with agent capabilities, built with best practices and a clean architecture. This project provides a complete e-commerce platform with AI-powered chat functionality, user management, and comprehensive testing.
- AI Agents: Powered by OpenAI, Anthropic, Google Gemini, and Groq with tool usage capabilities
- E-commerce Platform: Complete marketplace with products, orders, reviews, and seller management
- User Management: Multi-role system (admin, seller, customer) with JWT authentication
- Memory: Persistent conversation history with Redis
- Tools: Weather, web search, calculation, and custom tool capabilities
- Real-time Chat: WebSocket support for live conversations
- Modern Architecture: Clean separation of concerns with src/ layout
- Production Ready: Docker support, health checks, and monitoring
- Comprehensive Testing: Fast unit tests with mocked dependencies
ai-chat-api/
βββ src/ # Source code
β βββ app/ # Application package
β βββ api/ # API endpoints and routing
β β βββ endpoints/ # Individual endpoint modules
β βββ core/ # Core configuration and utilities
β βββ models/ # Database models (chat + ecommerce)
β βββ schemas/ # Pydantic schemas
β βββ services/ # Business logic services
β βββ tools/ # AI agent tools
β βββ agents/ # AI agent implementations
β βββ llm/ # LLM provider integrations
βββ tests/ # Test suite
βββ src/alembic/ # Database migrations
βββ src/scripts/ # Utility scripts (seeding, etc.)
βββ docker-compose.yml # Docker services configuration
βββ Dockerfile # Application container
βββ pyproject.toml # Project configuration and dependencies
βββ alembic.ini # Alembic configuration
βββ README.md # This file
- Python 3.11+
- Docker and Docker Compose
- PostgreSQL 15+
- Redis 7+
git clone <your-repo-url>
cd ai-chat-api
# Copy environment file
cp env.example .env
# Edit .env with your configuration
# Required: OPENAI_API_KEY, DATABASE_URL, REDIS_URL, SECRET_KEY# Start all services
docker-compose up -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down# Install dependencies using uv (recommended)
uv sync
# Start the application
uv run python start.py
# Or for development with auto-reload
uv run python run_local.pyCreate a .env file based on env.example:
# API Keys
OPENAI_API_KEY=your_openai_api_key
ANTHROPIC_API_KEY=your_anthropic_api_key
GOOGLE_API_KEY=your_google_api_key
GROQ_API_KEY=your_groq_api_key
# Database
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/ai_chat_db
# Redis
REDIS_URL=redis://localhost:6379
# Security
SECRET_KEY=your_secret_key_here
DEBUG=True# Run migrations
alembic -c alembic.ini upgrade head
# or
uv run alembic -c alembic.ini upgrade head
# Or from the src directory
cd src && alembic upgrade head
# Seed initial data (creates users, products, orders, etc.)
uv run python src/scripts/seed_data.pyOnce running, access the interactive API documentation:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- Health Check: http://localhost:8000/health
This project uses fast unit tests that don't require external services like databases or Redis. Tests are isolated using mocks and run in milliseconds.
# Run all tests
uv run pytest
# Run with verbose output
uv run pytest -v
# Run specific test file
uv run pytest tests/test_user_unit.py
# Run specific test
uv run pytest tests/test_user_unit.py::TestWriteUser::test_create_user_success
# Run with coverage
uv run pytest --cov=src- Unit Tests (
test_*_unit.py): Fast, isolated tests with mocked dependencies - Fixtures (
conftest.py): Shared test fixtures and mock setups - Helpers (
tests/helpers/): Utilities for generating test data and mocks
β
Fast: Tests run in ~0.04 seconds
β
Reliable: No external dependencies required
β
Isolated: Each test focuses on one piece of functionality
β
Maintainable: Easy to understand and modify
β
CI/CD Ready: Run anywhere without infrastructure setup
# Start with hot reload
docker-compose up
# Build and start
docker-compose up --build
# View logs
docker-compose logs -f ai_chat_api# Build production image
docker build -t ai-chat-api .
# Run production container
docker run -p 8000:8000 ai-chat-apiThe docker-compose.yml includes:
- ai_chat_api: Main FastAPI application
- postgres: PostgreSQL database
- redis: Redis for caching and sessions
All services include health checks and proper networking.
- Application:
/health - Database: Automatic health checks in Docker Compose
- Redis: Automatic health checks in Docker Compose
# View application logs
docker-compose logs -f ai_chat_api
# View database logs
docker-compose logs -f postgres
# View Redis logs
docker-compose logs -f redisThis project uses modern Python development tools:
- Black: Code formatting
- isort: Import sorting
- mypy: Type checking
- pytest: Testing framework
- pre-commit: Git hooks
# Install pre-commit hooks
pre-commit install
# Run manually
pre-commit run --all-files- Models: Add to
src/app/models/ - Schemas: Add to
src/app/schemas/ - API Endpoints: Add to
src/app/api/endpoints/ - Services: Add to
src/app/services/ - Tools: Add to
src/app/tools/
# Create a new migration
alembic -c alembic.ini revision --autogenerate -m "description"
# Apply migrations
alembic -c alembic.ini upgrade head
# Check current migration
alembic -c alembic.ini current- FastAPI: Modern web framework
- SQLAlchemy 2.0: Database ORM
- Pydantic V2: Data validation
- Alembic: Database migrations
- Redis: Caching and sessions
- Uvicorn: ASGI server
- OpenAI: GPT models
- Anthropic: Claude models
- Google: Gemini models
- Groq: Fast inference models
- OpenRouter: Multiple provider access
- uv: Fast Python package manager
- pytest: Testing framework
- black: Code formatting
- isort: Import sorting
- mypy: Type checking
- User: User accounts with roles (admin, seller, customer)
- Conversation: Chat conversations with metadata
- Message: Individual messages with AI metadata
- TokenUsage: Token consumption tracking
- ConversationAnalytics: Analytics and insights
- Customer: Customer profiles and preferences
- Seller: Seller accounts and business info
- Product: Products with variants and images
- Order: Orders with items and status
- Review: Product reviews and ratings
- Cart/Wishlist: Shopping cart and wishlist items
- Coupon: Discount codes and promotions
After running the seeding script, you'll have these default users:
- Username:
admin| Password:admin123 - Username:
superadmin| Password:super123
- Username:
techstore| Password:seller123 - Username:
fashionhub| Password:seller123 - Username:
homegoods| Password:seller123 - Username:
bookstore| Password:seller123 - Username:
sportsworld| Password:seller123
- Username:
john_doe| Password:customer123 - Username:
jane_smith| Password:customer123 - And 8 more customer accounts...
- Environment Variables: Set all required environment variables
- Database: Ensure PostgreSQL is running and accessible
- Redis: Ensure Redis is running and accessible
- Migrations: Run database migrations
- Seeding: Run the seeding script for initial data
# Build and run with Docker Compose
docker-compose -f docker-compose.yml up -d
# Or build and run individual container
docker build -t ai-chat-api .
docker run -p 8000:8000 --env-file .env ai-chat-apiThe application supports different configurations for development, testing, and production environments through environment variables.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Run the test suite
- Submit a pull request
# Clone and setup
git clone <your-fork-url>
cd ai-chat-api
uv sync
# Create feature branch
git checkout -b feature/your-feature-name
# Make changes and test
uv run pytest
uv run python src/scripts/seed_data.py
uv run python start.py
# Commit and push
git add .
git commit -m "Add your feature"
git push origin feature/your-feature-nameThis project is licensed under the MIT License - see the LICENSE file for details.
- Issues: GitHub Issues
- Documentation: Check the
/docsendpoint when running - Community: Join our discussions
If you're migrating from the old structure:
- Backup your data
- Update import paths in your code
- Test thoroughly before deploying
- Update your CI/CD pipelines
The new structure maintains backward compatibility while providing a cleaner, more maintainable codebase.
- Fast Startup: Application starts in under 2 seconds
- Efficient Testing: Test suite runs in ~0.04 seconds
- Scalable: Designed for horizontal scaling
- Production Ready: Includes health checks and monitoring
- JWT Authentication: Secure token-based authentication
- Password Hashing: Bcrypt for password security
- Input Validation: Pydantic V2 for robust data validation
- SQL Injection Protection: SQLAlchemy ORM prevents SQL injection
- CORS Configuration: Configurable CORS settings
- Health Checks: Built-in health check endpoints
- Structured Logging: Comprehensive logging throughout the application
- Error Tracking: Detailed error reporting and handling
- Performance Metrics: Token usage and response time tracking
Built with β€οΈ using FastAPI, SQLAlchemy 2.0, and Pydantic V2