An educational project demonstrating how to build a production-ready SQL query chatbot using AWS serverless architecture and Claude 3 Haiku.
This chatbot allows users to query a MySQL database using natural language in both French and English. It leverages:
- Claude 3 Haiku for natural language understanding
- LangChain for agent orchestration
- AWS Serverless for scalable, cost-effective infrastructure
- SQL Query Agent: Natural language to SQL conversion using Claude 3 Haiku
- French Language Support: Full bilingual support (French/English)
- AWS Serverless: Lambda, API Gateway, DynamoDB, S3/CloudFront architecture
- Security First:
- Read-only database access
- AWS Secrets Manager for credentials
- Cognito authentication
- VPC isolation (envisioned for company context) π
- Production Ready:
- CloudWatch structured logging with AWS Lambda Powertools
- X-Ray tracing support π
- Comprehensive error handling
- Chain-of-thought logging for debugging
- CloudWatch dashboards and alarms β
- ~90% test coverage
- Developer Experience:
- Modern Python tooling with
uv - Pre-configured linting and formatting
- Automated CI/CD pipeline
- Rich local development logging
- Modern Python tooling with
- Compute: Lambda (Python 3.12)
- API: API Gateway REST API
- AI/ML: Bedrock (Claude 3 Haiku)
- Database: RDS MySQL + DynamoDB
- Security: Secrets Manager, IAM, Cognito
- Monitoring: CloudWatch, X-Ray π
- Storage: S3 + CloudFront
- Auth: Cognito
- Framework: FastAPI + AWS Lambda Powertools
- AI/ML: LangChain, LangChain-AWS
- Database: PyMySQL, SQLAlchemy, boto3
- Configuration: pydantic-settings
- Testing: pytest, coverage
- Code Quality: ruff
- Package Management: uv
- IaC: AWS SAM/CloudFormation
- CI/CD: GitHub Actions
- Secrets: AWS Secrets Manager
- Monitoring: CloudWatch Dashboards & Alarms
βββ src/ # Lambda function code
β βββ app.py # Lambda handler with async detection
β βββ agent/ # SQL agent implementation
β β βββ callbacks.py # Chain-of-thought & metrics handlers
β β βββ prompts.py # LangChain prompts
β β βββ sql_agent.py # Main agent logic
β β βββ tools.py # SQL tools
β β βββ translation_data.py # French translations
β β βββ translation_utils.py # Translation helpers
β βββ api/ # FastAPI application
β β βββ main.py # FastAPI app configuration
β β βββ models.py # Pydantic models
β β βββ dependencies/ # FastAPI dependencies
β β β βββ auth.py # Authentication dependency
β β βββ routers/ # API endpoints
β β βββ auth.py # OAuth endpoints
β β βββ chat.py # Sync chat endpoint
β β βββ chat_async.py # Async chat endpoint
β β βββ feedback.py # Feedback endpoint
β β βββ health.py # Health check
β βββ utils/ # Shared utilities
β βββ auth.py # JWT validation utilities
β βββ bedrock.py # Bedrock LLM config & token tracking
β βββ correlation.py # Request tracking
β βββ db.py # Database connection
β βββ dynamodb.py # DynamoDB operations with metrics
β βββ logger.py # Centralized logging
β βββ metrics.py # CloudWatch metrics
β βββ settings.py # Configuration
βββ frontend/ # Static web assets
β βββ index.html # Main page
β βββ css/
β β βββ styles.css # Styling
β βββ js/
β βββ config.js # Environment detection
β βββ auth.js # Cognito OAuth2 flow
β βββ app.js # Main app with async polling
βββ tests/ # Test suite
β βββ unit/ # Unit tests (comprehensive)
β βββ integration/ # Integration tests
β βββ conftest.py # Pytest configuration
βββ docs/ # Documentation
β βββ 01-setup.md # Development setup
β βββ 02-infrastructure.md # AWS architecture
β βββ 03-development.md # Workflow guide
β βββ 04-database-security.md # Phase 2 implementation
β βββ 05-sql-agent.md # Phase 3 implementation
β βββ 06-api-layer.md # Phase 4 implementation
β βββ 07-authentication.md # Phase 5 implementation
β βββ 08-frontend.md # Phase 6 implementation
β βββ 09-monitoring.md # Phase 7 implementation
β βββ README.md # Documentation index
- Python 3.12+
- AWS CLI configured
- SAM CLI installed
- Docker Desktop running
- AWS Account with appropriate permissions
- MySQL/MariaDB database (local or RDS)
-
Clone the repository
git clone https://github.com/GMartin-Data/sql-agent-chatbot cd sql-agent-chatbot -
Set up the project
Choose between standard pip or modern uv:
Option A: Using pip (universal)
make setup-pip source .venv/bin/activate # On Windows: .venv\Scripts\activate
Option B: Using uv (faster, auto-installs if needed on Linux/Mac)
make setup-uv source .venv/bin/activate # On Windows: .venv\Scripts\activate
-
Configure Environment
# Edit the generated .env file with your database credentials # The setup commands already created it from .env.example nano .env # or your preferred editor
-
Test Database Connection
make db-test
-
Run Tests
make test # Run all tests with coverage make cov # Generate HTML coverage report
-
Start Local API
make dev # Starts SAM local API on http://localhost:3000OR
make api # Starts FastAPI directly on http://localhost:8000
Once running locally:
# Test health endpoint
curl http://localhost:3000/health
# Test SQL query (French)
curl -X POST http://localhost:3000/chat \
-H "Content-Type: application/json" \
-d '{"question": "Montre-moi toutes les tables"}'
# Test SQL query (English)
curl -X POST http://localhost:3000/chat \
-H "Content-Type: application/json" \
-d '{"question": "Show me all tables"}'For production testing, replace the URL with your API Gateway endpoint:
# Find your API endpoint
aws cloudformation describe-stacks \
--stack-name sql-agent-chatbot \
--query "Stacks[0].Outputs[?OutputKey=='ApiUrl'].OutputValue" \
--output textπ§ Examples with actual database tables and columns coming soon
π§ Examples with real data filters coming soon
π§ Examples based on actual database schema coming soon
π§ Examples using real table relationships coming soon
π§ Real response examples will be added based on actual database content
The project includes a complete CI/CD pipeline:
- Development: Push to any branch triggers tests
- Production: Merge to
maindeploys to AWS
To deploy manually:
make build
make deploy-backendFor frontend deployment:
make deploy-frontendRequired Parameters:
DBHost: Your RDS MySQL endpointDBPassword: Database password for read-only userBedrockModelId: Claude model to use (default: claude-3-haiku)
See Infrastructure Documentation for details.
- Project structure with SAM
- CI/CD pipeline with GitHub Actions
- Basic Lambda function with health check
- Development environment setup
- Documentation structure
- RDS MySQL integration with read-only user
- AWS Secrets Manager for credentials
- Database connection utilities
- CloudWatch structured logging with Powertools
- 100% test coverage maintained
- LangChain SQL agent implementation
- Claude 3 Haiku integration via Bedrock
- Query safety and validation (markdown SQL patch)
- Chain-of-thought logging
- French language support
- Lambda integration with connection reuse
- Comprehensive error handling
- ~100% test coverage maintained
- FastAPI integration with Lambda
- Request/response validation with Pydantic
- Comprehensive error handling
- API documentation (OpenAPI/Swagger)
- Maintained ~100% test coverage
- Cognito user pools setup (SAM template)
- JWT token validation utilities
- FastAPI auth dependency integration
- Chat endpoint auth protection
- User session management integration (DynamoDB)
- Integration tests for auth flow
- ~95% test coverage maintained
- Static site infrastructure (S3/CloudFront)
- Q&A chat interface with character counters
- OAuth2 integration with Cognito
- Backend auth endpoints (/auth/callback, /auth/config)
- User feedback system with DynamoDB storage
- Frontend deployment via CloudFront
- 3-environment configuration system
- ~95% test coverage maintained
- CloudWatch dashboards (AI Performance & Application Health)
- CloudWatch alarms with email notifications
- Custom metrics for AI performance
- Token usage tracking per LLM call
- Chain-of-thought step metrics
- DynamoDB operation metrics
- Comprehensive monitoring documentation
- Operational runbook (in progress)
- X-Ray tracing integration (future)
- ~90% test coverage
- Polishing and minor debugging (fix known issues first)
- Enhancing security (critical for production)
- Improving coverage (safety net before refactoring)
- Refactoring (with confidence from tests)
- Updating documentation (continuous process)
Comprehensive guides are available in the docs/ directory:
- Development Setup - Get your environment ready
- Infrastructure Guide - Understand the AWS architecture
- Development Workflow - Git workflow, 3-environment system, and CI/CD
- Database & Security - RDS, Secrets Manager, and logging
- SQL Agent Implementation - LangChain and Claude 3 integration
- API Layer - FastAPI integration and REST API
- Authentication - JWT auth with AWS Cognito
- Frontend - SPA architecture, OAuth2 flow, and deployment
- Monitoring & Observability - CloudWatch dashboards, metrics, and alarms
The project maintains test coverage as close as possible to 100%:
make test # Run all tests
make cov # Generate coverage report
make db-test # Test database connection
make agent-test # Interactive agent testingThe application includes comprehensive monitoring:
- AI Performance Dashboard: Token usage, response times, reasoning complexity
- Application Health Dashboard: Success rates, latencies, database performance
- High error rate (>5%)
- High response time (>60s)
- No traffic detection
- High token usage (>100k/hour)
Access dashboards:
# Get dashboard URLs
make dashboard-urls
# Or find them manually
aws cloudwatch list-dashboards \
--query "DashboardEntries[?contains(DashboardName, 'sql-agent-chatbot')].DashboardName"This is an educational project, but contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Follow the commit conventions
- Ensure tests pass
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
- AWS for the serverless platform
- Anthropic for Claude 3 Haiku
- The Python and AWS communities
Note: This is an educational project demonstrating best practices for building production-ready serverless applications. Always follow your organization's security and compliance requirements when building production systems.