🎯 Mục tiêu bài học
Tổng hợp tất cả kiến thức từ course: deploy một AI application production-ready hoàn chỉnh.
Sau bài này, bạn sẽ:
✅ Xây dựng FastAPI backend với AI endpoints hoàn chỉnh ✅ Dockerize toàn bộ stack với Docker Compose ✅ Setup monitoring với Prometheus và Grafana ✅ Implement security với auth, rate limiting, input validation ✅ Viết tests và documentation cho project
🔍 Project Overview
Checkpoint
Bạn đã hiểu kiến trúc tổng thể của capstone project chưa?
📝 Project Requirements
Core Features:
- FastAPI backend với AI endpoints
- Chat endpoint với streaming response
- Document Q and A với RAG
- Response caching với Redis
Infrastructure:
- Dockerized với docker-compose
- Nginx reverse proxy với SSL
- Health checks và auto-restart
Monitoring:
- Prometheus metrics collection
- Grafana dashboard
- LangSmith tracing
- Cost tracking
Security:
- API key authentication
- Rate limiting
- Input validation va sanitization
- CORS configuration
Checkpoint
Bạn đã nắm được đầy đủ requirements cho project chưa?
🛠️ Project Structure
1ai-deployment-capstone/2├── docker-compose.yml3├── .env.example4├── nginx/5│ └── nginx.conf6├── app/7│ ├── Dockerfile8│ ├── requirements.txt9│ ├── main.py10│ ├── config.py11│ ├── auth.py12│ ├── middleware.py13│ ├── routes/14│ │ ├── chat.py15│ │ └── health.py16│ └── services/17│ ├── ai_service.py18│ └── cache_service.py19├── monitoring/20│ ├── prometheus.yml21│ └── grafana/22│ └── dashboard.json23└── tests/24 ├── test_chat.py25 └── test_health.pyCheckpoint
Bạn đã tạo được project structure hoàn chỉnh chưa?
💻 FastAPI Application
1# app/main.py2from fastapi import FastAPI3from fastapi.middleware.cors import CORSMiddleware4from contextlib import asynccontextmanager5from app.middleware import RateLimitMiddleware, MetricsMiddleware6from app.routes import chat, health7from app.config import settings89@asynccontextmanager10async def lifespan(app: FastAPI):11 # Startup12 print("Starting AI service...")13 yield14 # Shutdown15 print("Shutting down...")1617app = FastAPI(18 title="AI Deployment Capstone",19 version="1.0.0",20 lifespan=lifespan21)2223app.add_middleware(24 CORSMiddleware,25 allow_origins=settings.CORS_ORIGINS,26 allow_methods=["*"],27 allow_headers=["*"],28)29app.add_middleware(RateLimitMiddleware, max_requests=60)30app.add_middleware(MetricsMiddleware)3132app.include_router(health.router, tags=["health"])33app.include_router(chat.router, prefix="/api/v1", tags=["chat"])1# app/config.py2from pydantic_settings import BaseSettings34class Settings(BaseSettings):5 OPENAI_API_KEY: str6 REDIS_URL: str = "redis://redis:6379"7 LANGSMITH_API_KEY: str = ""8 API_KEYS: list[str] = []9 CORS_ORIGINS: list[str] = ["http://localhost:3000"]10 RATE_LIMIT: int = 6011 DAILY_BUDGET: float = 10.012 13 class Config:14 env_file = ".env"1516settings = Settings()Checkpoint
Bạn đã setup được FastAPI application với config và middleware chưa?
💻 AI Service
1# app/services/ai_service.py2from langchain_openai import ChatOpenAI3from langchain_core.prompts import ChatPromptTemplate4from langchain_core.output_parsers import StrOutputParser5from app.services.cache_service import CacheService67class AIService:8 def __init__(self):9 self.llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.7)10 self.cache = CacheService()11 12 self.chat_prompt = ChatPromptTemplate.from_messages([13 ("system", "You are a helpful AI assistant."),14 ("human", "{message}")15 ])16 17 self.chain = self.chat_prompt | self.llm | StrOutputParser()18 19 async def chat(self, message: str) -> str:20 # Check cache21 cached = await self.cache.get(message)22 if cached:23 return cached24 25 # Invoke chain26 result = await self.chain.ainvoke({"message": message})27 28 # Cache result29 await self.cache.set(message, result)30 31 return result32 33 async def stream_chat(self, message: str):34 async for chunk in self.chain.astream({"message": message}):35 yield chunkCheckpoint
Bạn đã xây dựng được AI Service với caching và streaming chưa?
🐳 Docker Compose
1# docker-compose.yml2services:3 app:4 build: ./app5 ports:6 - "8000:8000"7 env_file: .env8 depends_on:9 redis:10 condition: service_healthy11 healthcheck:12 test: ["CMD", "curl", "-f", "http://localhost:8000/health"]13 interval: 30s14 timeout: 10s15 retries: 316 restart: unless-stopped17 18 redis:19 image: redis:7-alpine20 ports:21 - "6379:6379"22 healthcheck:23 test: ["CMD", "redis-cli", "ping"]24 interval: 10s25 volumes:26 - redis_data:/data27 28 nginx:29 image: nginx:alpine30 ports:31 - "80:80"32 volumes:33 - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro34 depends_on:35 - app36 37 prometheus:38 image: prom/prometheus39 ports:40 - "9090:9090"41 volumes:42 - ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml43 44 grafana:45 image: grafana/grafana46 ports:47 - "3001:3000"48 environment:49 - GF_SECURITY_ADMIN_PASSWORD=admin50 51volumes:52 redis_data:Checkpoint
Bạn đã viết được Docker Compose file hoàn chỉnh chưa?
💻 Dockerfile
1# app/Dockerfile2FROM python:3.11-slim3 4WORKDIR /app5 6COPY requirements.txt .7RUN pip install --no-cache-dir -r requirements.txt8 9COPY . .10 11EXPOSE 800012 13CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]Checkpoint
Bạn đã viết được Dockerfile cho AI application chưa?
🧪 Testing
1# tests/test_chat.py2import pytest3from httpx import AsyncClient, ASGITransport4from app.main import app56@pytest.mark.asyncio7async def test_chat_endpoint():8 transport = ASGITransport(app=app)9 async with AsyncClient(transport=transport, base_url="http://test") as ac:10 response = await ac.post(11 "/api/v1/chat",12 json={"message": "Hello"},13 headers={"X-API-Key": "test-key"}14 )15 assert response.status_code == 20016 assert "response" in response.json()1718@pytest.mark.asyncio19async def test_health_check():20 transport = ASGITransport(app=app)21 async with AsyncClient(transport=transport, base_url="http://test") as ac:22 response = await ac.get("/health")23 assert response.status_code == 20024 assert response.json()["status"] == "healthy"Checkpoint
Bạn đã viết được tests cho các endpoints chưa?
📊 Evaluation Criteria
| Criteria | Points |
|---|---|
| FastAPI app chạy đúng với endpoints | 20 |
| Docker Compose setup hoàn chỉnh | 20 |
| Caching với Redis | 15 |
| Monitoring (Prometheus + Grafana) | 15 |
| Security (auth, rate limit, validation) | 15 |
| Testing (unit + integration) | 10 |
| Documentation | 5 |
| Total | 100 |
Checkpoint
Bạn đã xem qua evaluation criteria và biết cần hoàn thành những gì chưa?
🎯 Tổng kết
Submission Checklist
- Tất cả services start thành công với
docker compose up - API endpoints trả về responses đúng
- Caching hoạt động (check Redis)
- Grafana dashboard hiển thị metrics
- Rate limiting chặn excessive requests
- Tests pass:
pytest tests/ - README với setup instructions
Câu hỏi tự kiểm tra
- Trong capstone project, làm thế nào để kết hợp FastAPI, Docker Compose, Redis caching và monitoring (Prometheus + Grafana) thành một hệ thống hoàn chỉnh?
- Security checklist cho production AI API bao gồm những gì (auth, rate limiting, input validation)? Tại sao mỗi yếu tố đều quan trọng?
- Giải thích quy trình testing cho AI application: unit tests, integration tests và health checks cần cover những gì?
- Evaluation criteria nào quan trọng nhất khi đánh giá một production-ready AI deployment và tại sao?
🎉 Chúc mừng! Bạn đã hoàn thành bài học Capstone Project và toàn bộ khóa học GenAI Deployment & MLOps!
Bạn cũng đã hoàn thành toàn bộ GenAI Coding Pathway — từ những kiến thức nền tảng về Text Generation, qua LangChain, đến Deployment & MLOps. Bạn giờ đây có đủ kỹ năng để xây dựng, triển khai và vận hành AI applications trong production. Hãy tiếp tục xây dựng các dự án thực tế để củng cố kiến thức! 🚀
Quay lại: Trang khóa học
