File size: 9,011 Bytes
92d464e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 |
# 🚀 Guia de Deployment - Cidadão.AI Backend
**Autor**: Anderson Henrique da Silva
**Última Atualização**: 2025-09-25 18:30:00 -03:00 (São Paulo, Brasil)
[English version below](#-deployment-guide---cidadãoai-backend-english)
## 📊 Estado Atual
O sistema está **atualmente em produção** no HuggingFace Spaces com configuração simplificada (sem PostgreSQL/Redis).
## 🎯 Opções de Deploy
### 1. HuggingFace Spaces (Atual) ✅
**Prós**: Gratuito, fácil, CI/CD automático
**Contras**: Sem banco de dados persistente, recursos limitados
```bash
# Deploy automático via push
git remote add hf https://huggingface.co/spaces/SEU_USUARIO/cidadao-ai
git push hf main
```
**Configuração no HuggingFace**:
1. Crie um Space com SDK Docker
2. Configure as secrets:
- `GROQ_API_KEY`
- `JWT_SECRET_KEY`
- `TRANSPARENCY_API_KEY` (opcional)
### 2. Docker Local 🐳
**Para desenvolvimento e testes**:
```bash
# Build e execução básica
docker build -t cidadao-ai .
docker run -p 8000:8000 --env-file .env cidadao-ai
# Com docker-compose (inclui Redis)
docker-compose up -d
# Com monitoramento completo
docker-compose -f docker-compose.yml -f docker-compose.monitoring.yml up -d
```
### 3. VPS com Docker 🖥️
**Para produção completa com banco de dados**:
```bash
# 1. Configure o servidor (Ubuntu 22.04)
ssh usuario@seu-servidor
sudo apt update && sudo apt install docker.io docker-compose
# 2. Clone o projeto
git clone https://github.com/seu-usuario/cidadao.ai-backend
cd cidadao.ai-backend
# 3. Configure variáveis
cp .env.example .env
nano .env # Configure todas as variáveis
# 4. Execute
docker-compose -f docker-compose.production.yml up -d
```
### 4. Kubernetes ☸️
**Para alta disponibilidade**:
```bash
# Apply configurações
kubectl apply -f k8s/
# Verificar pods
kubectl get pods -n cidadao-ai
# Expor serviço
kubectl expose deployment cidadao-api --type=LoadBalancer --port=80
```
## 🔑 Variáveis de Ambiente
### Essenciais (Obrigatórias)
```bash
# Autenticação
JWT_SECRET_KEY=gere-com-openssl-rand-hex-32
SECRET_KEY=outra-chave-aleatoria
# LLM Provider
GROQ_API_KEY=sua-chave-groq
```
### Opcionais (Recursos Extras)
```bash
# Portal da Transparência (sem isso usa dados demo)
TRANSPARENCY_API_KEY=sua-chave-api
# Banco de Dados (sem isso usa memória)
DATABASE_URL=postgresql+asyncpg://user:pass@localhost/cidadao
# Cache Redis (sem isso usa memória)
REDIS_URL=redis://localhost:6379
# Configurações de Performance
WORKERS=4
MAX_AGENTS=10
CACHE_TTL=3600
```
## 📋 Checklist de Deploy
### Produção Mínima (HuggingFace)
- [ ] Configurar secrets no HF Spaces
- [ ] Verificar app.py está usando configuração minimal
- [ ] Push para branch hf-fastapi
- [ ] Testar endpoints básicos
### Produção Completa (VPS/Cloud)
- [ ] Servidor com mínimo 2GB RAM
- [ ] Docker e docker-compose instalados
- [ ] PostgreSQL configurado
- [ ] Redis configurado (opcional)
- [ ] SSL/TLS configurado (Nginx + Certbot)
- [ ] Backup configurado
- [ ] Monitoramento ativo
## 📊 Monitoramento
### Endpoints de Health Check
```bash
# Básico
curl https://seu-dominio/health
# Detalhado (requer auth)
curl -H "Authorization: Bearer $TOKEN" https://seu-dominio/health/detailed
# Métricas Prometheus
curl https://seu-dominio/metrics
```
### Grafana Dashboards
Se usando docker-compose com monitoramento:
- **URL**: http://localhost:3000
- **User**: admin
- **Pass**: cidadao123
Dashboards disponíveis:
- System Overview
- Agent Performance
- API Metrics
- Cache Analytics
## 🚨 Troubleshooting
### Erro: "No module named 'src'"
```bash
# Adicione ao Dockerfile ou startup
export PYTHONPATH=/app:$PYTHONPATH
```
### Erro: Redis connection failed
O sistema funciona sem Redis, mas se quiser ativar:
```bash
docker run -d --name redis -p 6379:6379 redis:alpine
```
### Erro: Database connection failed
O sistema usa memória se não encontrar PostgreSQL. Para ativar:
```bash
docker run -d --name postgres \
-e POSTGRES_DB=cidadao \
-e POSTGRES_USER=cidadao \
-e POSTGRES_PASSWORD=senha \
-p 5432:5432 \
postgres:15-alpine
```
### Performance Lenta
1. Verifique CPU/RAM: `docker stats`
2. Aumente workers: `WORKERS=8`
3. Ative cache Redis
4. Use agent pooling
## 🔒 Segurança
### Configurações Essenciais
1. **Sempre** gere novas chaves secretas
2. **Nunca** commite .env no git
3. Use HTTPS em produção
4. Configure rate limiting
5. Mantenha dependências atualizadas
### Gerar Chaves Seguras
```bash
# JWT Secret
openssl rand -hex 32
# Secret Key
python -c "import secrets; print(secrets.token_urlsafe(32))"
```
---
# 🚀 Deployment Guide - Cidadão.AI Backend (English)
**Author**: Anderson Henrique da Silva
**Last Updated**: 2025-09-25 18:30:00 -03:00 (São Paulo, Brazil)
## 📊 Current Status
The system is **currently in production** on HuggingFace Spaces with simplified configuration (no PostgreSQL/Redis).
## 🎯 Deployment Options
### 1. HuggingFace Spaces (Current) ✅
**Pros**: Free, easy, automatic CI/CD
**Cons**: No persistent database, limited resources
```bash
# Automatic deployment via push
git remote add hf https://huggingface.co/spaces/YOUR_USER/cidadao-ai
git push hf main
```
**HuggingFace Configuration**:
1. Create a Space with Docker SDK
2. Configure secrets:
- `GROQ_API_KEY`
- `JWT_SECRET_KEY`
- `TRANSPARENCY_API_KEY` (optional)
### 2. Local Docker 🐳
**For development and testing**:
```bash
# Basic build and run
docker build -t cidadao-ai .
docker run -p 8000:8000 --env-file .env cidadao-ai
# With docker-compose (includes Redis)
docker-compose up -d
# With complete monitoring
docker-compose -f docker-compose.yml -f docker-compose.monitoring.yml up -d
```
### 3. VPS with Docker 🖥️
**For complete production with database**:
```bash
# 1. Configure server (Ubuntu 22.04)
ssh user@your-server
sudo apt update && sudo apt install docker.io docker-compose
# 2. Clone project
git clone https://github.com/your-user/cidadao.ai-backend
cd cidadao.ai-backend
# 3. Configure variables
cp .env.example .env
nano .env # Configure all variables
# 4. Run
docker-compose -f docker-compose.production.yml up -d
```
### 4. Kubernetes ☸️
**For high availability**:
```bash
# Apply configurations
kubectl apply -f k8s/
# Check pods
kubectl get pods -n cidadao-ai
# Expose service
kubectl expose deployment cidadao-api --type=LoadBalancer --port=80
```
## 🔑 Environment Variables
### Essential (Required)
```bash
# Authentication
JWT_SECRET_KEY=generate-with-openssl-rand-hex-32
SECRET_KEY=another-random-key
# LLM Provider
GROQ_API_KEY=your-groq-key
```
### Optional (Extra Features)
```bash
# Portal da Transparência (without this uses demo data)
TRANSPARENCY_API_KEY=your-api-key
# Database (without this uses memory)
DATABASE_URL=postgresql+asyncpg://user:pass@localhost/cidadao
# Redis Cache (without this uses memory)
REDIS_URL=redis://localhost:6379
# Performance Settings
WORKERS=4
MAX_AGENTS=10
CACHE_TTL=3600
```
## 📋 Deployment Checklist
### Minimum Production (HuggingFace)
- [ ] Configure secrets in HF Spaces
- [ ] Verify app.py is using minimal configuration
- [ ] Push to hf-fastapi branch
- [ ] Test basic endpoints
### Complete Production (VPS/Cloud)
- [ ] Server with minimum 2GB RAM
- [ ] Docker and docker-compose installed
- [ ] PostgreSQL configured
- [ ] Redis configured (optional)
- [ ] SSL/TLS configured (Nginx + Certbot)
- [ ] Backup configured
- [ ] Active monitoring
## 📊 Monitoring
### Health Check Endpoints
```bash
# Basic
curl https://your-domain/health
# Detailed (requires auth)
curl -H "Authorization: Bearer $TOKEN" https://your-domain/health/detailed
# Prometheus metrics
curl https://your-domain/metrics
```
### Grafana Dashboards
If using docker-compose with monitoring:
- **URL**: http://localhost:3000
- **User**: admin
- **Pass**: cidadao123
Available dashboards:
- System Overview
- Agent Performance
- API Metrics
- Cache Analytics
## 🚨 Troubleshooting
### Error: "No module named 'src'"
```bash
# Add to Dockerfile or startup
export PYTHONPATH=/app:$PYTHONPATH
```
### Error: Redis connection failed
System works without Redis, but to enable:
```bash
docker run -d --name redis -p 6379:6379 redis:alpine
```
### Error: Database connection failed
System uses memory if PostgreSQL not found. To enable:
```bash
docker run -d --name postgres \
-e POSTGRES_DB=cidadao \
-e POSTGRES_USER=cidadao \
-e POSTGRES_PASSWORD=password \
-p 5432:5432 \
postgres:15-alpine
```
### Slow Performance
1. Check CPU/RAM: `docker stats`
2. Increase workers: `WORKERS=8`
3. Enable Redis cache
4. Use agent pooling
## 🔒 Security
### Essential Settings
1. **Always** generate new secret keys
2. **Never** commit .env to git
3. Use HTTPS in production
4. Configure rate limiting
5. Keep dependencies updated
### Generate Secure Keys
```bash
# JWT Secret
openssl rand -hex 32
# Secret Key
python -c "import secrets; print(secrets.token_urlsafe(32))"
``` |