Skip to content

robinprashanth/ai-chat-fastapi

Repository files navigation

πŸ€– AI Chat API

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.

✨ Features

  • 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

πŸ—οΈ Project Structure

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

πŸš€ Quick Start

Prerequisites

  • Python 3.11+
  • Docker and Docker Compose
  • PostgreSQL 15+
  • Redis 7+

1. Clone and Setup

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

2. Using Docker (Recommended)

# Start all services
docker-compose up -d

# View logs
docker-compose logs -f

# Stop services
docker-compose down

3. Local Development

# 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.py

πŸ”§ Configuration

Environment Variables

Create 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

Database Setup

# 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.py

πŸ“š API Documentation

Once running, access the interactive API documentation:

πŸ§ͺ Testing

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.

Running Tests

# 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

Test Structure

  • 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

Benefits of Our Testing Approach

βœ… 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

🐳 Docker

Development

# Start with hot reload
docker-compose up

# Build and start
docker-compose up --build

# View logs
docker-compose logs -f ai_chat_api

Production

# Build production image
docker build -t ai-chat-api .

# Run production container
docker run -p 8000:8000 ai-chat-api

Docker Services

The 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.

πŸ” Monitoring

Health Checks

  • Application: /health
  • Database: Automatic health checks in Docker Compose
  • Redis: Automatic health checks in Docker Compose

Logs

# 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 redis

πŸ› οΈ Development

Code Quality

This project uses modern Python development tools:

  • Black: Code formatting
  • isort: Import sorting
  • mypy: Type checking
  • pytest: Testing framework
  • pre-commit: Git hooks

Pre-commit Hooks

# Install pre-commit hooks
pre-commit install

# Run manually
pre-commit run --all-files

Adding New Features

  1. Models: Add to src/app/models/
  2. Schemas: Add to src/app/schemas/
  3. API Endpoints: Add to src/app/api/endpoints/
  4. Services: Add to src/app/services/
  5. Tools: Add to src/app/tools/

Database Migrations

# 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

πŸ“¦ Dependencies

Core Dependencies

  • FastAPI: Modern web framework
  • SQLAlchemy 2.0: Database ORM
  • Pydantic V2: Data validation
  • Alembic: Database migrations
  • Redis: Caching and sessions
  • Uvicorn: ASGI server

LLM Providers

  • OpenAI: GPT models
  • Anthropic: Claude models
  • Google: Gemini models
  • Groq: Fast inference models
  • OpenRouter: Multiple provider access

Development Tools

  • uv: Fast Python package manager
  • pytest: Testing framework
  • black: Code formatting
  • isort: Import sorting
  • mypy: Type checking

πŸ—„οΈ Database Schema

Chat Models

  • 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

E-commerce Models

  • 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

πŸ”‘ Default Users (After Seeding)

After running the seeding script, you'll have these default users:

Admin Users

  • Username: admin | Password: admin123
  • Username: superadmin | Password: super123

Seller Users

  • Username: techstore | Password: seller123
  • Username: fashionhub | Password: seller123
  • Username: homegoods | Password: seller123
  • Username: bookstore | Password: seller123
  • Username: sportsworld | Password: seller123

Customer Users

  • Username: john_doe | Password: customer123
  • Username: jane_smith | Password: customer123
  • And 8 more customer accounts...

πŸš€ Deployment

Production Setup

  1. Environment Variables: Set all required environment variables
  2. Database: Ensure PostgreSQL is running and accessible
  3. Redis: Ensure Redis is running and accessible
  4. Migrations: Run database migrations
  5. Seeding: Run the seeding script for initial data

Docker Production

# 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-api

Environment-Specific Configurations

The application supports different configurations for development, testing, and production environments through environment variables.

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Run the test suite
  6. Submit a pull request

Development Workflow

# 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-name

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

  • Issues: GitHub Issues
  • Documentation: Check the /docs endpoint when running
  • Community: Join our discussions

πŸ”„ Migration from Old Structure

If you're migrating from the old structure:

  1. Backup your data
  2. Update import paths in your code
  3. Test thoroughly before deploying
  4. Update your CI/CD pipelines

The new structure maintains backward compatibility while providing a cleaner, more maintainable codebase.

πŸ“Š Performance

  • 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

πŸ” Security

  • 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

πŸ“ˆ Monitoring and Logging

  • 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

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages