File size: 10,788 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 |
# ποΈ Arquitetura - CidadΓ£o.AI Backend
**Autor**: Anderson Henrique da Silva
**Γltima AtualizaΓ§Γ£o**: 2025-09-25 18:15:00 -03:00 (SΓ£o Paulo, Brasil)
[English version below](#-architecture---cidadΓ£oai-backend-english)
## π VisΓ£o Geral
O CidadΓ£o.AI Γ© um sistema multi-agente de IA para anΓ‘lise de transparΓͺncia governamental brasileira, construΓdo com arquitetura modular e escalΓ‘vel.
## π§ Sistema Multi-Agente
### Hierarquia de Agentes
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β UsuΓ‘rio / Frontend β
βββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β API Gateway (FastAPI) β
β Rate Limiting | Auth | CORS β
βββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ποΈ Ayrton Senna (Router) β
β DetecΓ§Γ£o de IntenΓ§Γ£o | Roteamento β
βββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββ
β
βββββββββββββββββββ΄ββββββββββββββββββ
βΌ βΌ
βββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββ
β π― Abaporu (Master) β β Agentes Diretos β
β OrquestraΓ§Γ£o Complexa β β (Para tarefas simples) β
βββββββββββββββββ¬ββββββββββββββββ βββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Pool de Agentes β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β π Zumbi β π Anita β π Tiradentes β π§ NanΓ£ β
β Anomalias β PadrΓ΅es β RelatΓ³rios β MemΓ³ria β
βββββββββββββββββΌβββββββββββββββΌβββββββββββββββΌβββββββββββββββ€
β βοΈ BonifΓ‘cio β π Machado β π‘οΈ Dandara β π LampiΓ£o β
β PolΓticas β Textos β JustiΓ§a β Regional β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### Classes Base
1. **BaseAgent**
- Retry logic com backoff exponencial
- Monitoramento integrado (Prometheus)
- Lifecycle management
- Error handling
2. **ReflectiveAgent**
- Auto-reflexΓ£o com threshold de qualidade (0.8)
- MΓ‘ximo 3 iteraΓ§Γ΅es de melhoria
- Self-improvement loop
### Estados dos Agentes
```python
class AgentState(Enum):
IDLE = "idle"
THINKING = "thinking"
ACTING = "acting"
WAITING = "waiting"
ERROR = "error"
COMPLETED = "completed"
```
## πΎ EstratΓ©gia de Cache
### Multi-Layer Cache
```
βββββββββββββββββββ
β Request β
ββββββββββ¬βββββββββ
βΌ
βββββββββββββββββββ
β L1: Memory β β 5ms latency
β (LRU Cache) β TTL: 5 min
ββββββββββ¬βββββββββ
βΌ miss
βββββββββββββββββββ
β L2: Redis β β 20ms latency
β (Distributed) β TTL: 1 hour
ββββββββββ¬βββββββββ
βΌ miss
βββββββββββββββββββ
β L3: Database β β 100ms latency
β (PostgreSQL) β TTL: 24 hours
βββββββββββββββββββ
```
### Cache Keys Strategy
```
chat:session:{session_id}:messages
investigation:{id}:results
agent:{agent_name}:state
portal:contracts:{org_code}:{page}
```
## π OtimizaΓ§Γ΅es de Performance
### 1. Agent Pool
- PrΓ©-inicializaΓ§Γ£o de instΓ’ncias
- Warm-up automΓ‘tico
- Lifecycle management
- Health checks
### 2. Parallel Processing
```python
# EstratΓ©gias disponΓveis
- SEQUENTIAL: ExecuΓ§Γ£o em ordem
- PARALLEL: Todos ao mesmo tempo
- ADAPTIVE: Baseado em dependΓͺncias
- PRIORITY: Por prioridade
```
### 3. JSON Optimization
- orjson para serializaΓ§Γ£o 3x mais rΓ‘pida
- Streaming responses
- Compression (Brotli/Gzip)
## π AnΓ‘lise Espectral (FFT)
### DetecΓ§Γ£o de PadrΓ΅es PeriΓ³dicos
```python
# Pipeline de anΓ‘lise
1. Preprocessamento dos dados
2. AplicaΓ§Γ£o de FFT/RFFT
3. DetecΓ§Γ£o de picos no domΓnio da frequΓͺncia
4. ClassificaΓ§Γ£o de componentes sazonais
5. CΓ‘lculo de entropia espectral
```
### Thresholds de Anomalia
- **PreΓ§o**: 2.5 desvios padrΓ£o
- **ConcentraΓ§Γ£o de fornecedor**: > 70%
- **Contratos duplicados**: > 85% similaridade
- **FrequΓͺncia anΓ΄mala**: > 3 desvios no espectro
## π SeguranΓ§a
### AutenticaΓ§Γ£o e AutorizaΓ§Γ£o
```
βββββββββββββββ βββββββββββββββ βββββββββββββββ
β Client ββββββΆβ JWT Auth ββββββΆβ API β
βββββββββββββββ βββββββββββββββ βββββββββββββββ
β
βΌ
βββββββββββββββ
β Rate Limit β
β by Tier β
βββββββββββββββ
```
### Rate Limiting Tiers
```python
RATE_LIMIT_TIERS = {
"anonymous": "10/minute",
"authenticated": "60/minute",
"premium": "300/minute",
"admin": "unlimited"
}
```
## π Monitoramento
### MΓ©tricas Prometheus
```python
# MΓ©tricas de agentes
agent_task_duration_seconds
agent_task_total
agent_errors_total
agent_reflection_iterations
# MΓ©tricas de API
http_request_duration_seconds
http_requests_total
active_websocket_connections
# MΓ©tricas de cache
cache_hits_total
cache_misses_total
cache_hit_rate
```
### Dashboards Grafana
1. **System Overview**: VisΓ£o geral do sistema
2. **Agent Performance**: Performance por agente
3. **API Metrics**: LatΓͺncia e throughput
4. **Cache Analytics**: Hit rate e eficiΓͺncia
## π IntegraΓ§Γ£o Portal da TransparΓͺncia
### Endpoints Funcionais (22%)
```
/contracts β GET com codigoOrgao obrigatΓ³rio
/servants β GET por CPF apenas
/agencies β GET informaΓ§Γ΅es de Γ³rgΓ£os
```
### LimitaΓ§Γ΅es Descobertas
- 78% dos endpoints retornam 403 Forbidden
- Sem documentaΓ§Γ£o oficial sobre nΓveis de acesso
- Dados de salΓ‘rio nΓ£o disponΓveis
## π Fluxo de Dados
```
1. Request β API Gateway
2. Auth/Rate Limit Check
3. Intent Detection (Senna)
4. Cache Check (L1 β L2 β L3)
5. Agent Selection/Orchestration
6. External API Calls (if needed)
7. Result Processing
8. Cache Update
9. Response β Client
```
---
# ποΈ Architecture - CidadΓ£o.AI Backend (English)
**Author**: Anderson Henrique da Silva
**Last Updated**: 2025-09-25 18:15:00 -03:00 (SΓ£o Paulo, Brazil)
## π Overview
CidadΓ£o.AI is a multi-agent AI system for Brazilian government transparency analysis, built with modular and scalable architecture.
## π§ Multi-Agent System
### Agent Hierarchy
[Same diagram as above]
### Base Classes
1. **BaseAgent**
- Retry logic with exponential backoff
- Integrated monitoring (Prometheus)
- Lifecycle management
- Error handling
2. **ReflectiveAgent**
- Self-reflection with quality threshold (0.8)
- Maximum 3 improvement iterations
- Self-improvement loop
### Agent States
[Same states as above]
## πΎ Cache Strategy
### Multi-Layer Cache
[Same diagram as above]
### Cache Keys Strategy
[Same keys as above]
## π Performance Optimizations
### 1. Agent Pool
- Pre-initialized instances
- Automatic warm-up
- Lifecycle management
- Health checks
### 2. Parallel Processing
[Same strategies as above]
### 3. JSON Optimization
- orjson for 3x faster serialization
- Streaming responses
- Compression (Brotli/Gzip)
## π Spectral Analysis (FFT)
### Periodic Pattern Detection
[Same pipeline as above]
### Anomaly Thresholds
- **Price**: 2.5 standard deviations
- **Supplier concentration**: > 70%
- **Duplicate contracts**: > 85% similarity
- **Anomalous frequency**: > 3 deviations in spectrum
## π Security
### Authentication and Authorization
[Same diagram as above]
### Rate Limiting Tiers
[Same tiers as above]
## π Monitoring
### Prometheus Metrics
[Same metrics as above]
### Grafana Dashboards
1. **System Overview**: System overview
2. **Agent Performance**: Performance by agent
3. **API Metrics**: Latency and throughput
4. **Cache Analytics**: Hit rate and efficiency
## π Portal da TransparΓͺncia Integration
### Functional Endpoints (22%)
[Same endpoints as above]
### Discovered Limitations
- 78% of endpoints return 403 Forbidden
- No official documentation about access levels
- Salary data not available
## π Data Flow
[Same flow as above] |