|
1 | | -# AI Base Template - Development Guide |
| 1 | +# AI Base Template - Production-First Development Guide |
2 | 2 |
|
3 | | -A Python template for ML/AI projects with FastAPI, designed for rapid prototyping and clean architecture. |
| 3 | +A production-ready Python template for AI/ML systems, designed for reliability, observability, and cost management from day one. |
| 4 | + |
| 5 | +## Project Philosophy |
| 6 | + |
| 7 | +This template embodies **production-first AI engineering**, where we optimize for reliability over research metrics: |
| 8 | + |
| 9 | +- **90% Infrastructure, 10% AI Logic** - Most code is defensive engineering, not model development |
| 10 | +- **Engineering Discipline** - Comprehensive testing, monitoring, and error handling |
| 11 | +- **Cost Management** - Real-time budget tracking and resource controls |
| 12 | +- **Observable Systems** - AI-specific metrics and monitoring patterns |
4 | 13 |
|
5 | 14 | ## Project Structure |
6 | 15 |
|
7 | 16 | ``` |
8 | 17 | ai-base-template/ |
9 | | -├── ai_base_template/ # Main application code |
| 18 | +├── ai_base_template/ # Production AI service code |
10 | 19 | │ ├── __init__.py |
11 | | -│ └── main.py # FastAPI entry point |
12 | | -├── tests/ # Test suite |
13 | | -│ └── test_main.py |
14 | | -├── research/ # Notebooks and experiments |
15 | | -│ └── EDA.ipynb # Exploratory data analysis |
16 | | -├── testing/ # API testing utilities |
17 | | -├── Makefile # Development automation |
18 | | -└── pyproject.toml # Project config & dependencies |
| 20 | +│ ├── main.py # AI service with defensive patterns |
| 21 | +│ ├── config.py # Environment-driven configuration |
| 22 | +│ └── monitoring.py # AI-specific observability |
| 23 | +├── tests/ # Defensive testing strategy |
| 24 | +│ ├── test_main.py # Basic functionality tests |
| 25 | +│ └── test_ai_service.py # AI-specific defensive tests |
| 26 | +├── research/ # Experimental AI development |
| 27 | +│ └── EDA.ipynb # Exploratory data analysis |
| 28 | +├── ARCHITECTURE.md # Production system design docs |
| 29 | +├── Makefile # Development automation |
| 30 | +└── pyproject.toml # Project config & dependencies |
19 | 31 | ``` |
20 | 32 |
|
21 | 33 | ## Quick Start |
22 | 34 |
|
23 | | -### Setup |
| 35 | +### Environment Setup |
24 | 36 | ```bash |
25 | | -make environment-create # Creates Python 3.12 env with uv |
26 | | -make environment-sync # Updates dependencies |
| 37 | +make init # Complete development environment setup |
| 38 | +make sync # Update dependencies |
27 | 39 | ``` |
28 | 40 |
|
29 | 41 | ### Development Commands |
30 | 42 | ```bash |
31 | | -make format # Auto-format with Ruff |
32 | | -make lint # Lint and auto-fix issues |
33 | | -make type-check # Type check with MyPy |
34 | | -make validate-branch # Run all checks before PR |
| 43 | +# Code quality (production-ready standards) |
| 44 | +make format # Auto-format with Ruff |
| 45 | +make lint # Lint and auto-fix issues |
| 46 | +make type-check # Static type validation |
| 47 | +make validate-branch # Full pre-commit validation |
| 48 | + |
| 49 | +# Testing (AI-focused test strategy) |
| 50 | +make test # Standard test suite (excludes integration) |
| 51 | +make test-unit # Fast, isolated component tests |
| 52 | +make test-functional # AI workflow tests |
| 53 | +make test-integration # Service-level integration tests |
| 54 | +make test-all # Complete suite including cost/load tests |
| 55 | + |
| 56 | +# Environment management |
| 57 | +make clean-project # Clean Python caches |
| 58 | +make clean-env # Remove virtual environment |
| 59 | +``` |
| 60 | + |
| 61 | +## Production-First Development Workflow |
| 62 | + |
| 63 | +### 1. Configuration-Driven Development |
| 64 | +All production concerns are configured, not hardcoded: |
| 65 | + |
| 66 | +```python |
| 67 | +# ai_base_template/config.py |
| 68 | +class AIServiceConfig(BaseSettings): |
| 69 | + # Cost management |
| 70 | + monthly_budget_limit: float = 10000.0 |
| 71 | + cost_alert_threshold: float = 100.0 |
| 72 | + |
| 73 | + # Reliability |
| 74 | + model_timeout: float = 5.0 |
| 75 | + enable_fallback: bool = True |
| 76 | + |
| 77 | + # Observability |
| 78 | + log_level: str = "INFO" |
| 79 | + enable_tracing: bool = True |
| 80 | +``` |
| 81 | + |
| 82 | +### 2. Defensive Testing Strategy |
| 83 | +Test for AI-specific failure modes: |
| 84 | + |
| 85 | +```bash |
| 86 | +# Run defensive AI tests |
| 87 | +make test-unit # Input validation, cost controls |
| 88 | +make test-integration # Service-level AI workflows |
| 89 | +make test-all # Include load and cost validation |
| 90 | +``` |
| 91 | + |
| 92 | +Test categories: |
| 93 | +- **Unit tests**: `@pytest.mark.unit` - Fast, isolated AI component tests |
| 94 | +- **Functional tests**: `@pytest.mark.functional` - Feature workflow tests |
| 95 | +- **Integration tests**: `@pytest.mark.integration` - Service-level tests with dependencies |
| 96 | +- **Performance tests**: `@pytest.mark.performance` - Cost and latency validation |
| 97 | + |
| 98 | +### 3. Cost-Aware Development |
| 99 | +Every AI operation is cost-tracked: |
| 100 | + |
| 101 | +```python |
| 102 | +# Cost tracking in all AI operations |
| 103 | +with cost_tracker.track_cost(estimated_cost=0.01): |
| 104 | + result = await model.predict(data) |
| 105 | + |
| 106 | +# Monitor budget status |
| 107 | +budget_status = cost_tracker.get_budget_status() |
35 | 108 | ``` |
36 | 109 |
|
37 | | -### Testing |
| 110 | +### 4. Comprehensive Validation |
| 111 | +Before any commit: |
| 112 | + |
38 | 113 | ```bash |
39 | | -make test-unit # Run unit tests |
40 | | -make test-functional # Run functional tests |
41 | | -make test # Run standard tests with coverage |
42 | | -make test-all # Run all tests with coverage |
| 114 | +make validate-branch # Runs: lint → type-check → test |
43 | 115 | ``` |
44 | 116 |
|
45 | | -## Development Workflow |
| 117 | +This ensures: |
| 118 | +- ✅ Code formatting and linting compliance |
| 119 | +- ✅ Static type checking passes |
| 120 | +- ✅ All defensive tests pass |
| 121 | +- ✅ Cost controls are validated |
| 122 | +- ✅ Performance requirements met |
46 | 123 |
|
47 | | -1. **Write code** following Python conventions: |
48 | | - - Classes: `PascalCase` |
49 | | - - Functions/variables: `snake_case` |
50 | | - - Constants: `UPPER_SNAKE_CASE` |
51 | | - - Max line length: 120 characters |
| 124 | +## Key Technologies & Production Patterns |
52 | 125 |
|
53 | | -2. **Validate before committing**: |
| 126 | +### Core Infrastructure |
| 127 | +- **FastAPI**: Production-grade async web framework |
| 128 | +- **Pydantic**: Runtime data validation and type safety |
| 129 | +- **loguru**: Structured logging for observability |
| 130 | +- **uv**: Fast, reliable Python package management |
| 131 | + |
| 132 | +### AI-Specific Engineering |
| 133 | +- **Cost Tracking**: Real-time budget monitoring and alerts |
| 134 | +- **Circuit Breakers**: Prevent cascading AI model failures |
| 135 | +- **Graceful Degradation**: Fallback strategies for AI failures |
| 136 | +- **Input Sanitization**: Prevent adversarial input attacks |
| 137 | +- **Timeout Management**: Prevent hanging AI operations |
| 138 | + |
| 139 | +### Monitoring & Observability |
| 140 | +- **AI Metrics**: Confidence distributions, fallback rates |
| 141 | +- **Cost Metrics**: Per-request costs, budget utilization |
| 142 | +- **Performance Metrics**: Latency percentiles, throughput |
| 143 | +- **Error Categorization**: Input validation vs. model failures |
| 144 | + |
| 145 | +## Production Deployment Patterns |
| 146 | + |
| 147 | +### Environment Configuration |
| 148 | +```bash |
| 149 | +# .env.production |
| 150 | +MODEL_VERSION=v2.1.0 |
| 151 | +MODEL_TIMEOUT=3.0 |
| 152 | +CONFIDENCE_THRESHOLD=0.90 |
| 153 | +MAX_REQUESTS_PER_USER=500 |
| 154 | +COST_ALERT_THRESHOLD=1000.0 |
| 155 | +ENABLE_FALLBACK=true |
| 156 | +``` |
| 157 | + |
| 158 | +### Health Checks |
| 159 | +```python |
| 160 | +# Built-in health check endpoint |
| 161 | +def get_service_health() -> dict: |
| 162 | + return { |
| 163 | + "status": "healthy", |
| 164 | + "model_version": config.model_version, |
| 165 | + "cost_summary": cost_tracker.get_budget_status(), |
| 166 | + "performance_summary": metrics.get_performance_summary() |
| 167 | + } |
| 168 | +``` |
| 169 | + |
| 170 | +## Best Practices for Production AI |
| 171 | + |
| 172 | +### Code Quality Standards |
| 173 | +- **Type hints on all functions** - Prevent runtime AI failures |
| 174 | +- **Comprehensive error handling** - AI systems fail uniquely |
| 175 | +- **Input validation** - Sanitize adversarial inputs |
| 176 | +- **Cost awareness** - Track and limit expensive operations |
| 177 | +- **Fallback strategies** - Graceful degradation for AI failures |
| 178 | + |
| 179 | +### Testing Standards |
| 180 | +- **Test coverage > 80%** - Include AI-specific edge cases |
| 181 | +- **Defensive testing** - Validate against malicious inputs |
| 182 | +- **Cost validation** - Ensure budget controls work |
| 183 | +- **Performance testing** - Validate latency requirements |
| 184 | +- **Failure scenario testing** - Test circuit breakers and fallbacks |
| 185 | + |
| 186 | +### Monitoring Standards |
| 187 | +- **Real-time cost tracking** - Prevent budget overruns |
| 188 | +- **Confidence monitoring** - Detect model drift early |
| 189 | +- **Latency monitoring** - Maintain SLA compliance |
| 190 | +- **Error categorization** - Distinguish AI vs. infrastructure failures |
| 191 | +- **Capacity planning** - Monitor resource utilization trends |
| 192 | + |
| 193 | +## Common Production AI Challenges |
| 194 | + |
| 195 | +### 1. Cost Control |
| 196 | +```python |
| 197 | +# Rate limiting to prevent cost spirals |
| 198 | +@rate_limit(max_requests_per_user=1000) |
| 199 | +async def predict(request): |
| 200 | + with cost_tracker.track_cost(): |
| 201 | + return await ai_model.predict(request) |
| 202 | +``` |
| 203 | + |
| 204 | +### 2. Input Validation |
| 205 | +```python |
| 206 | +# Sanitize adversarial inputs |
| 207 | +def validate_ai_input(data: str) -> str: |
| 208 | + if len(data) > MAX_INPUT_LENGTH: |
| 209 | + raise ValueError("Input too large") |
| 210 | + return sanitize_adversarial_patterns(data) |
| 211 | +``` |
| 212 | + |
| 213 | +### 3. Timeout Management |
| 214 | +```python |
| 215 | +# Prevent hanging AI operations |
| 216 | +result = await asyncio.wait_for( |
| 217 | + ai_model.predict(data), |
| 218 | + timeout=config.model_timeout |
| 219 | +) |
| 220 | +``` |
| 221 | + |
| 222 | +### 4. Graceful Degradation |
| 223 | +```python |
| 224 | +# Fallback strategies for AI failures |
| 225 | +try: |
| 226 | + return await primary_ai_model.predict(data) |
| 227 | +except Exception: |
| 228 | + return await fallback_model.predict(data) |
| 229 | +``` |
| 230 | + |
| 231 | +## Getting Started with Production AI |
| 232 | + |
| 233 | +1. **Clone and initialize**: |
54 | 234 | ```bash |
55 | | - make validate-branch # Runs linting and tests |
| 235 | + git clone <repo> my-ai-service |
| 236 | + cd my-ai-service |
| 237 | + make init |
56 | 238 | ``` |
57 | 239 |
|
58 | | -3. **Test thoroughly**: |
59 | | - - Unit tests: `@pytest.mark.unit` |
60 | | - - Functional tests: `@pytest.mark.functional` |
61 | | - - Integration tests: `@pytest.mark.integration` |
| 240 | +2. **Understand the architecture**: |
| 241 | + ```bash |
| 242 | + # Read the production patterns |
| 243 | + cat ARCHITECTURE.md |
| 244 | + |
| 245 | + # Examine the defensive code |
| 246 | + cat ai_base_template/main.py |
| 247 | + ``` |
62 | 248 |
|
63 | | -## Key Technologies |
| 249 | +3. **Run defensive tests**: |
| 250 | + ```bash |
| 251 | + # Validate the foundation |
| 252 | + make validate-branch |
| 253 | + |
| 254 | + # Run AI-specific tests |
| 255 | + make test-all |
| 256 | + ``` |
64 | 257 |
|
65 | | -- **FastAPI**: Modern Python web framework |
66 | | -- **Pydantic**: Data validation using Python type annotations |
67 | | -- **MyPy**: Static type checking |
68 | | -- **Ruff**: Fast Python linter and formatter |
69 | | -- **pytest**: Testing framework |
70 | | -- **uv**: Fast Python package manager |
| 258 | +4. **Implement your AI logic**: |
| 259 | + - Replace the mock `_make_prediction()` method with your model |
| 260 | + - Keep all the defensive infrastructure intact |
| 261 | + - Add AI-specific configuration in `config.py` |
| 262 | + - Extend monitoring in `monitoring.py` |
71 | 263 |
|
72 | | -## ML/Data Science Stack |
| 264 | +5. **Deploy with confidence**: |
| 265 | + ```bash |
| 266 | + # Final validation |
| 267 | + make validate-branch |
| 268 | + |
| 269 | + # Deploy knowing you have production safeguards |
| 270 | + ``` |
73 | 271 |
|
74 | | -- **scikit-learn**: Machine learning library |
75 | | -- **XGBoost/LightGBM**: Gradient boosting frameworks |
76 | | -- **PyTorch**: Deep learning framework |
77 | | -- **pandas/numpy**: Data manipulation |
78 | | -- **SHAP**: Model interpretability |
| 272 | +## Remember: Production AI is Infrastructure Engineering |
79 | 273 |
|
80 | | -## Best Practices |
| 274 | +> "The best AI is the AI that works." |
81 | 275 |
|
82 | | -- Type hints on all functions |
83 | | -- Pydantic models for data validation |
84 | | -- Structured logging with loguru |
85 | | -- Environment-based configuration |
86 | | -- No hardcoded secrets |
87 | | -- Test coverage > 80% |
| 276 | +This template prioritizes **reliability over research metrics**. Most of your code will be infrastructure—cost controls, error handling, monitoring, and fallbacks—not AI/ML logic. |
88 | 277 |
|
89 | | -## Getting Started |
| 278 | +That's exactly how production AI systems should be built. |
90 | 279 |
|
91 | | -1. Clone the template |
92 | | -2. Run `make environment-create` |
93 | | -3. Start coding in `ai_base_template/` |
94 | | -4. Add tests in `tests/` |
95 | | -5. Use `make validate-branch` before commits |
| 280 | +--- |
96 | 281 |
|
97 | | -This template provides a solid foundation for ML/AI projects with all the modern Python tooling pre-configured. |
| 282 | +For detailed architecture patterns and production deployment strategies, see [ARCHITECTURE.md](ARCHITECTURE.md). |
0 commit comments