Ultravox Pipeline
Plataforma de comunicação em tempo real com IA conversacional (STT + LLM + TTS)
🎯 O que é?
Pipeline completo de conversação por voz usando:
Speech-to-Text (Whisper)
LLM (Ultravox multimodal ou Groq/OpenAI)
Text-to-Speech (Kokoro PT-BR/EN)
WebRTC para streaming de áudio
✨ Novidades V2.0:
⚡ Arquitetura Híbrida : Main process unificado + serviços isolados com venvs separados
🔗 Communication Service : Hub centralizado com gRPC (primary) + HTTP Binary (fallback) + JSON (last resort)
🔒 Isolated Services : STT, TTS, LLM rodando em subprocessos gerenciados com ambientes Python isolados
🤖 Auto-Management : Health monitoring, auto-restart, graceful shutdown
📊 Métricas Completas : Performance tracking por serviço e protocolo
🏗️ Arquitetura V2.0
Arquitetura Híbrida
┌──────────────────────────────────────────────────────────┐
│ MAIN PROCESS (Port 8080) │
│ ├─ API Gateway (REST) - in-process │
│ ├─ HTTP Polling - in-process │
│ ├─ WebRTC Server - in-process │
│ ├─ WebSocket Server - in-process │
│ ├─ Orchestrator Engine - in-process │
│ └─ Session Manager - in-process │
│ │
│ IsolatedServiceManager (gerencia subprocessos): │
│ ├─ spawns → STT Service (Port 8120, venv isolado) │
│ ├─ spawns → TTS Service (Port 8130, venv isolado) │
│ └─ spawns → LLM Service (Port 8110, venv isolado) │
└──────────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────────┐
│ COMMUNICATION SERVICE (Port 8888 HTTP, 50888 gRPC) │
│ Hub centralizado para inter-service communication │
│ ├─ gRPC Server (PRIMARY) - ~2ms latency │
│ ├─ HTTP Binary (FALLBACK) - ~8ms latency │
│ └─ HTTP JSON (LAST RESORT) - ~22ms latency │
└──────────────────────────────────────────────────────────┘
3 Modos de Execução
1. LOCAL (Sem GPU)
└─> APIs Externas (Groq/OpenAI)
└─> Latência: ~800-1500ms
└─> Custo: Paga por uso
2. GPU LOCAL (24GB VRAM)
└─> Modelos carregados localmente
└─> Latência: ~150-300ms
└─> Custo: Apenas hardware
3. RUNPOD (Serverless)
└─> Auto-scaling em RunPod
└─> Latência: ~400-700ms
└─> Custo: Paga por uso + idle shutdown
4 Camadas de Context (Dependency Injection)
┌────────────────────────────────────────┐
│ 1. GlobalContext │
│ └─> GPU Manager │
│ └─> Metrics Collector │
│ └─> Profile Config │
├────────────────────────────────────────┤
│ 2. ProcessContext │
│ └─> GlobalContext (herda) │
│ └─> Communication Manager │
├────────────────────────────────────────┤
│ 3. ServiceContext (Service Manager) │
│ └─> ProcessContext (herda tudo) │
│ └─> Logger │
│ └─> Config │
├────────────────────────────────────────┤
│ 4. StandaloneContext (Standalone) │
│ └─> Logger apenas │
│ └─> Config apenas │
│ └─> SEM GPU/Metrics/Communication │
└────────────────────────────────────────┘
SERVICE MANAGER MODE:
└─> ServiceContext (completo com GPU, Metrics, Communication)
STANDALONE MODE:
└─> StandaloneContext (minimalista: só logger + config)
Fluxo de Conversação
Cliente (WebRTC/WebSocket/REST)
↓
Entry Point (4 opções: API Gateway, WebRTC, WebSocket, REST Polling)
↓
ConversationController (unified)
↓
OrchestratorClient
↓
Orchestrator Service
├─> External LLM → Groq/OpenAI API
├─> TTS Service
└─> STT Service
↓
Conversation Store
↓
Response → Cliente
🚀 Quick Start
1. Instalação
1 git clone https://github.com/your-org/ultravox-pipeline.git
2 cd ultravox-pipeline
3 pip install -r requirements.txt
4 cp .env.example .env
5 # Edite .env com suas API keys
2. Escolha o Modo
Sem GPU (APIs externas):
1 export PROFILE = local-pc
2 export GROQ_API_KEY = your_key
3 ./start_service_manager.sh start
Com GPU local:
1 export PROFILE = gpu-machine
2 export CUDA_VISIBLE_DEVICES = 0
3 ./start_service_manager.sh start
Com RunPod:
1 export PROFILE = main-server
2 export RUNPOD_API_KEY = your_key
3 ./start_service_manager.sh start
3. Testar
1 # Health check
2 curl http://localhost:8888/health
3
4 # Conversação
5 curl -X POST http://localhost:8900/api/orchestrator/conversation \
6 -H "Content-Type: application/json" \
7 -d '{
8 "session_id": "test",
9 "message": "Olá, como você está?",
10 "voice_id": "pf_dora"
11 }'
Testes Automatizados (Níveis)
Sistema de testes com 5 níveis para controlar custo e velocidade:
1 # Testes rápidos e gratuitos (padrão)
2 ./main.sh test < service > # Standard: unit + integration
3 ./main.sh test --all # Todos os serviços (paralelo)
4
5 # Níveis específicos
6 ./main.sh test < service > --level unit # Só unit tests (super rápido)
7 ./main.sh test < service > --level real # Validação com APIs reais (dry-run)
8 ./main.sh test < service > --level expensive --confirm-real # Lança clusters reais ($$)
Nível Descrição Custo Tempo unitTestes isolados Grátis <1min integrationMocks de serviços Grátis ~2min standardUnit + integration (padrão) Grátis ~3-5min realDry-run com APIs reais Grátis ~5-10min expensiveClusters/GPUs reais PAGO ~10-30min
Exemplo - SkyPilot:
1 ./main.sh test skypilot # Testes padrão (grátis)
2 ./main.sh test skypilot --level real # Valida RunPod/VastAI (grátis)
3 ./main.sh test skypilot --level expensive --confirm-real # Lança cluster (~$0.02)
4. Quick Start V2.0 (Novo)
Método simplificado com arquitetura híbrida:
1 # 1. Iniciar tudo (Main + Isolated Services)
2 ./start_ultravox_v2.sh
3
4 # 2. Verificar status
5 curl http://localhost:8080/health
6
7 # 3. Testar conversação
8 curl -X POST http://localhost:8080/api/orchestrator/conversation \
9 -H "Content-Type: application/json" \
10 -d '{
11 "session_id": "test",
12 "message": "Hello",
13 "voice_id": "pf_dora"
14 }'
15
16 # 4. Parar tudo
17 ./stop_ultravox_v2.sh
🔗 Communication Service (Novo)
Hub centralizado que gerencia TODA comunicação entre serviços:
Protocol Priority
gRPC (Primary) - Latência ~2ms, binary protocol
HTTP Binary (Fallback) - Latência ~8ms, msgpack/protobuf
HTTP JSON (Last Resort) - Latência ~22ms, human-readable
Endpoints
1 # Health Check
2 curl http://localhost:8888/health
3
4 # Call Service via Communication Hub
5 curl -X POST http://localhost:8888/call \
6 -H "Content-Type: application/json" \
7 -d '{
8 "service_name": "stt",
9 "endpoint": "/transcribe",
10 "method": "POST",
11 "data": {"audio": "base64..."}
12 }'
13
14 # Proxy Request
15 curl -X POST http://localhost:8888/proxy/stt/transcribe \
16 -d '{"audio": "base64..."}'
17
18 # Metrics
19 curl http://localhost:8888/metrics
20 curl http://localhost:8888/metrics/stt
Uso Programático
1 from src . core . managers . communication_manager import get_communication_manager
2
3 comm_manager = get_communication_manager ( )
4
5 # Automatic protocol selection (gRPC → HTTP Binary → JSON)
6 result = await comm_manager . call_service (
7 service_name = "stt" ,
8 endpoint = "/transcribe" ,
9 method = "POST" ,
10 json_data = { "audio" : audio_bytes }
11 )
🔒 Isolated Services (Novo)
O que são?
Serviços (STT, TTS, LLM) que rodam em subprocessos separados com venvs Python isolados , gerenciados pelo IsolatedServiceManager .
Benefícios
✅ Isolamento de Dependências : Cada serviço tem seu próprio venv
✅ Auto-Restart : Falhas são detectadas e serviço reinicia automaticamente
✅ Health Monitoring : Check automático a cada 10 segundos
✅ Graceful Shutdown : SIGTERM → 5s → SIGKILL
Como funciona
1 from src . core . managers . isolated_service_manager import IsolatedServiceManager
2
3 manager = IsolatedServiceManager ( project_root )
4
5 # Registrar serviços
6 manager . register_service ( ServiceConfig (
7 name = "stt" ,
8 script_path = "stt_server.py" ,
9 venv_path = ".venvs/stt_service" ,
10 port = 8120 ,
11 restart_on_failure = True
12 ) )
13
14 # Iniciar todos
15 await manager . start_all ( )
16
17 # Restart individual
18 await manager . restart_service ( "stt" )
19
20 # Status
21 status = manager . get_all_status ( )
📦 Serviços Principais
Core IA
LLM (:8100) - Ultravox local ou Groq/OpenAI externo
STT (:8099) - Whisper local ou Groq externo
TTS (:8101) - Kokoro local
Orquestração
Service Manager (:8888) - Orquestração central
Orchestrator (:8900) - Coordenação de conversação
API Gateway (:8010) - Entry point REST
Comunicação
WebRTC (:8020) - Streaming de áudio
WebSocket (:8022) - Comunicação bidirecional
REST Polling (:8106) - Long polling
Dados
Database (:8102) - Vector store (FAISS + SQLite)
Conversation Store (:8101) - Histórico
Session (:8800) - Gerenciamento de sessões
🔧 Configuração
Variáveis de Ambiente Principais
1 # APIs Externas
2 GROQ_API_KEY = gsk_your_key
3 OPENAI_API_KEY = sk_your_key
4 RUNPOD_API_KEY = your_key
5
6 # Service Manager
7 SERVICE_MANAGER_PORT = 8888
8 PROFILE = local-pc # ou gpu-machine, main-server
9
10 # Redis (opcional)
11 REDIS_URL = redis://localhost:6379
12
13 # GPU (se disponível)
14 CUDA_VISIBLE_DEVICES = 0
15 LLM_GPU_MEMORY_UTILIZATION = 0.9
Trocar Perfil
1 # Via CLI
2 sm profile activate gpu-machine
3
4 # Via API
5 curl -X POST http://localhost:8888/profiles/gpu-machine/activate
📊 Monitoramento
1 # Stack: Prometheus + Grafana + Loki
2 cd monitoring
3 ./start_monitoring.sh
4
5 # Acessar
6 open http://localhost:3000 # Grafana (admin/admin)
7 open http://localhost:9090 # Prometheus
Métricas expostas: Cada serviço expõe em 9200+ (ex: LLM em :9210)
🛠️ CLI Tool
1 sm list # Lista serviços
2 sm describe llm # Detalhes do serviço
3 sm health --all # Health de todos
4 sm start llm # Iniciar serviço
5 sm stop llm # Parar serviço
6 sm call llm /health # Chamar endpoint
📁 Estrutura do Projeto
⚠️ Virtual Environments: Para evitar problemas de file watchers (ENOSPC) e reduzir tamanho do workspace, os virtual environments estão localizados em ~/.cache/ultravox-venvs/ com symlinks no projeto:
.venv → ~/.cache/ultravox-venvs/.venv (main venv - Python 3.13)
.venvs → ~/.cache/ultravox-venvs/.venvs (service venvs - Python 3.11/3.13)
ultravox-pipeline/
├── 🎯 Servidores Standalone (Entry Points)
│ ├── api_gateway_server.py # REST API (:8010)
│ ├── webrtc_server.py # WebRTC (:8020)
│ ├── websocket_server.py # WebSocket (:8022)
│ ├── orchestrator_server.py # Orchestrator (:8900) ✨ Updated
│ ├── external_llm_server.py # External LLM (:8110) ✨ Updated
│ └── session_server.py # Session (:8800)
│
├── 📁 src/
│ ├── core/ # Components core
│ │ ├── base_service.py # Base para serviços
│ │ ├── context/ # Dependency Injection
│ │ │ ├── service_context.py # ServiceContext (Service Manager)
│ │ │ └── standalone_context.py # StandaloneContext (Standalone)
│ │ ├── controllers/ # ConversationController
│ │ ├── managers/ # Communication, Metrics
│ │ ├── service_manager/ # Service Manager core
│ │ │
│ │ ├── resilience/ # 🆕 Resilience Patterns
│ │ │ ├── circuit_breaker.py # Circuit Breaker Pattern
│ │ │ └── retry_policy.py # Retry com Exponential Backoff
│ │ │
│ │ ├── middleware/ # 🆕 FastAPI Middleware
│ │ │ ├── rate_limiting.py # Rate Limiting
│ │ │ ├── input_validation.py # Input Validation
│ │ │ └── authentication.py # JWT Authentication
│ │ │
│ │ └── logging/ # 🆕 Structured Logging
│ │ └── structured_logger.py # JSON Logs
│ │
│ └── services/ # 20+ Microserviços
│ ├── orchestrator/ # Coordenação
│ ├── external_llm/ # LLM externo
│ ├── llm/ # LLM local
│ ├── tts/ # TTS local
│ ├── database/ # Vector store
│ ├── conversation_store/ # Histórico
│ ├── session/ # Sessions
│ └── ...
│
├── 🔌 modules/ # Módulos reutilizáveis
│ ├── providers/ # LLM/STT/TTS providers
│ ├── pipeline/ # Circuit breaker
│ └── ultravox/ # Ultravox implementation
│
├── 📊 config/ # Configs YAML
│ ├── profiles.yaml # 4 perfis de execução
│ └── services.yaml # Config de serviços
│
├── 📈 monitoring/ # Stack de monitoramento
│ ├── prometheus.yml
│ └── grafana/dashboards/
│
├── 🎓 examples/ # 🆕 Exemplos
│ └── full_middleware_integration.py # Exemplo completo de middleware
│
├── IMPROVEMENTS_SUMMARY.md # 🆕 Documentação v2.0
└── README.md # ✨ Updated
🔄 Comparação de Modos
Característica Local (sem GPU) GPU Local RunPod GPU ❌ ✅ 24GB 🚀 Serverless Latência 800-1500ms 150-300ms 400-700ms Custo $ API $ Hardware $$ Uso Ideal para Dev local Produção Auto-scaling
📊 Comparação V1 vs V2
Aspecto V1 (Anterior) V2 (Atual) Processos 5+ processos separados 1 Main + 3 subprocessos gerenciados Startup Scripts múltiplos ./start_ultravox_v2.shLatência (entry points) HTTP (~5ms) In-memory (<1ms) Isolamento de venv ❌ Compartilhado ✅ Isolado (STT/TTS/LLM) Auto-restart ❌ Manual ✅ Automático Communication HTTP direto Communication Service (gRPC/HTTP) Monitoring ❌ Manual ✅ Automático (health checks)
🛡️ Features Enterprise (v2.0)
Resilience & Fault Tolerance
Circuit Breaker Pattern
Previne cascading failures em serviços distribuídos.
1 from src . core . resilience import get_circuit_breaker_registry , CircuitBreakerConfig
2
3 # Configurar circuit breaker
4 registry = get_circuit_breaker_registry ( )
5 circuit = registry . get (
6 "groq_api" ,
7 config = CircuitBreakerConfig (
8 failure_threshold = 5 , # Abrir após 5 falhas
9 recovery_timeout = 60.0 , # Testar recovery após 60s
10 success_threshold = 2 # Fechar após 2 sucessos
11 )
12 )
13
14 # Usar circuit breaker
15 result = await circuit . call ( external_api_function , * args )
Estados :
🟢 CLOSED : Normal operation
🔴 OPEN : Service down, requests fail fast
🟡 HALF_OPEN : Testing recovery
Retry Policy com Exponential Backoff
Recuperação automática de falhas temporárias.
1 from src . core . resilience import get_retry_policy_registry , RetryPolicyConfig , RetryStrategy
2
3 # Configurar retry policy
4 registry = get_retry_policy_registry ( )
5 retry = registry . get (
6 "groq_api" ,
7 config = RetryPolicyConfig (
8 max_attempts = 5 ,
9 initial_delay = 1.0 ,
10 max_delay = 60.0 ,
11 strategy = RetryStrategy . EXPONENTIAL , # 1s, 2s, 4s, 8s, ...
12 jitter = True # Adiciona variação aleatória
13 )
14 )
15
16 # Usar retry policy
17 result = await retry . execute ( flaky_operation , * args )
Estratégias :
FIXED : Delay constante (1s, 1s, 1s, ...)
LINEAR : Delay linear (1s, 2s, 3s, ...)
EXPONENTIAL : Delay exponencial (1s, 2s, 4s, 8s, ...)
Integração Automática no Communication Manager 🆕
Resilience patterns já integrados automaticamente em TODAS as chamadas entre serviços!
1 from src . core . managers . communication_manager import ServiceCommunicationManager
2
3 comm = ServiceCommunicationManager ( )
4
5 # Circuit Breaker + Retry AUTOMÁTICOS em todas as chamadas
6 result = await comm . call_service (
7 service_name = "llm" ,
8 endpoint_path = "/chat/completions" ,
9 method = "POST" ,
10 json_data = { "messages" : [ . . . ] }
11 # enable_resilience=True (padrão)
12 )
Configuração padrão por serviço :
Circuit Breaker: 5 falhas → OPEN por 60s
Retry Policy: 3 tentativas, exponential backoff (1s, 2s, 4s)
Jitter: 10% de variação aleatória
Controle global :
1 # Desabilitar resilience patterns
2 export ENABLE_RESILIENCE = false
3
4 # Desabilitar por chamada individual
5 result = await comm.call_service ( .. ., enable_resilience = False )
Endpoints de Monitoring de Resilience 🆕
API Gateway expõe endpoints REST para monitorar e controlar resilience patterns.
1 # Ver estatísticas completas
2 curl http://localhost:8010/resilience/stats
3
4 # Ver todos os circuit breakers
5 curl http://localhost:8010/resilience/circuit-breakers
6
7 # Ver circuit breaker específico
8 curl http://localhost:8010/resilience/circuit-breakers/llm
9
10 # Resetar circuit breaker manualmente
11 curl -X POST http://localhost:8010/resilience/circuit-breakers/llm/reset
12
13 # Resetar todos os circuit breakers
14 curl -X POST http://localhost:8010/resilience/circuit-breakers/reset-all
15
16 # Ver políticas de retry
17 curl http://localhost:8010/resilience/retry-policies
18
19 # Ver política de retry específica
20 curl http://localhost:8010/resilience/retry-policies/llm
21
22 # Resetar estatísticas de retry
23 curl -X POST http://localhost:8010/resilience/retry-policies/reset-stats
Response de stats :
1 {
2 "circuit_breakers" : {
3 "llm" : {
4 "state" : "closed" ,
5 "total_calls" : 150 ,
6 "total_failures" : 2 ,
7 "total_successes" : 148 ,
8 "failure_rate" : 0.013 ,
9 "last_failure_time" : "2025-10-11T14:30:00Z"
10 }
11 } ,
12 "retry_policies" : {
13 "llm" : {
14 "total_attempts" : 152 ,
15 "successful_attempts" : 148 ,
16 "failed_attempts" : 4 ,
17 "total_retries" : 4 ,
18 "avg_attempts" : 1.03
19 }
20 }
21 }
22
23 ---
24
25 ### **Security & Protection**
26
27 #### **JWT Authentication**
28 Autenticação enterprise-grade com tokens JWT.
29
30 ```python
31 from src.core.middleware import AuthenticationMiddleware , AuthConfig , UserRole
32
33 app.add_middleware(
34 AuthenticationMiddleware ,
35 config=AuthConfig(
36 secret_key= "your-secret-key-change-in-production" ,
37 access_token_expire_minutes= 30 ,
38 refresh_token_expire_days= 7 ,
39 public_paths= [ "/health" , "/docs" , "/auth/login" ] ,
40 api_keys= { "service-key-123" } # API key alternativo
41 )
42 )
Features :
✅ Access + Refresh tokens
✅ Role-based access control (RBAC)
✅ Token blacklist (revocation)
✅ API Key authentication
✅ Public paths whitelist
Uso :
1 # Login
2 curl -X POST http://localhost:8900/auth/login \
3 -d '{"username":"user@example.com","password":"pass"}'
4
5 # Response: {"access_token": "eyJ...", "token_type": "bearer"}
6
7 # Chamar endpoint protegido
8 curl -H "Authorization: Bearer <token>" http://localhost:8900/protected
Input Validation
Validação e sanitização automática de requests.
1 from src . core . middleware import InputValidationMiddleware , ValidationConfig , ValidationLevel
2
3 app . add_middleware (
4 InputValidationMiddleware ,
5 config = ValidationConfig (
6 max_content_length = 50 * 1024 * 1024 , # 50 MB
7 level = ValidationLevel . MODERATE ,
8 sanitize_html = True , # Remove XSS
9 sanitize_sql = True , # Detecta SQL injection
10 validate_base64 = True
11 )
12 )
Protege contra :
✅ XSS (Cross-Site Scripting)
✅ SQL Injection
✅ JSON bombs (deep nesting)
✅ Oversized payloads
✅ Invalid Content-Type
Rate Limiting
Proteção contra abuso de API.
1 from src . core . middleware import RateLimitMiddleware , RateLimitConfig , RateLimitStrategy
2
3 app . add_middleware (
4 RateLimitMiddleware ,
5 config = RateLimitConfig (
6 requests_per_minute = 60 ,
7 requests_per_hour = 1000 ,
8 strategy = RateLimitStrategy . SLIDING_WINDOW , # Mais preciso
9 whitelist = [ "127.0.0.1" ] # IPs permitidos
10 )
11 )
Estratégias :
FIXED_WINDOW : Contador simples por janela de tempo
SLIDING_WINDOW : Janela deslizante (mais preciso)
TOKEN_BUCKET : Permite burst traffic
Response em caso de limite :
1 {
2 "error" : "Rate limit exceeded" ,
3 "retry_after" : 45.2 ,
4 "message" : "Too many requests. Please retry after 45.2 seconds."
5 }
Observability
Structured Logging (JSON)
Logs estruturados para fácil parsing e análise.
1 from src . core . logging import get_structured_logger , LogLevel
2
3 logger = get_structured_logger ( "my_service" , level = LogLevel . INFO )
4
5 # Log simples
6 logger . info ( "Request processed" , endpoint = "/api/chat" , duration_ms = 125.5 )
7
8 # Com contexto (request tracking)
9 with logger . context ( request_id = "req-123" , user_id = "user-456" ) :
10 logger . info ( "Processing request" )
11 # ... processar
12 logger . info ( "Request completed" )
13
14 # Performance timing
15 with logger . timer ( "database_query" ) :
16 # ... query
17 pass # Logs automaticamente: "Operation completed (duration_ms: 45.2)"
Output (JSON) :
1 {
2 "timestamp" : "2025-10-11T14:05:00.123Z" ,
3 "level" : "INFO" ,
4 "service" : "orchestrator" ,
5 "message" : "Request processed" ,
6 "request_id" : "req-123" ,
7 "user_id" : "user-456" ,
8 "endpoint" : "/api/chat" ,
9 "duration_ms" : 125.5 ,
10 "file" : "app.py:42"
11 }
Benefícios :
✅ Fácil integração com Elasticsearch, Loki, CloudWatch
✅ Correlação de logs entre serviços
✅ Métricas de performance embebidas
✅ Rastreamento de erros com contexto completo
🚀 Exemplo de Integração Completa
Veja examples/full_middleware_integration.py para um exemplo completo usando TODOS os componentes.
1 from fastapi import FastAPI
2 from src . core . middleware import (
3 RateLimitMiddleware , RateLimitConfig ,
4 InputValidationMiddleware , ValidationConfig ,
5 AuthenticationMiddleware , AuthConfig
6 )
7 from src . core . logging import get_structured_logger
8 from src . core . resilience import get_circuit_breaker_registry
9
10 app = FastAPI ( )
11
12 # 1. Authentication (outermost)
13 app . add_middleware ( AuthenticationMiddleware , config = AuthConfig ( . . . ) )
14
15 # 2. Input Validation
16 app . add_middleware ( InputValidationMiddleware , config = ValidationConfig ( . . . ) )
17
18 # 3. Rate Limiting (innermost)
19 app . add_middleware ( RateLimitMiddleware , config = RateLimitConfig ( . . . ) )
20
21 # 4. Structured Logging
22 logger = get_structured_logger ( "my_service" )
23
24 # 5. Circuit Breaker
25 circuit = get_circuit_breaker_registry ( ) . get ( "external_api" )
26
27 @app . post ( "/api/process" )
28 async def process ( data : dict , request : Request ) :
29 with logger . context ( user_id = request . state . user_id ) :
30 logger . info ( "Processing request" )
31 result = await circuit . call ( external_api , data )
32 return { "result" : result }
Executar exemplo :
1 cd examples
2 python full_middleware_integration.py
3
4 # Open: http://localhost:8000/docs
📚 Documentação
CLAUDE.md - Regras do projeto
IMPROVEMENTS_SUMMARY.md - 🆕 Novas features v2.0
ARCHITECTURE_V2.md - 🆕 Arquitetura híbrida detalhada
COMMUNICATION_SERVICE.md - 🆕 Communication Service completo
MONITORING_COMPLETE.md - Monitoramento completo
Database Status - Vector store
🆘 Troubleshooting
1 # Service Manager não inicia
2 rm /tmp/service-manager-8888.pid
3 ./start_service_manager.sh start
4
5 # Ver logs
6 ./start_service_manager.sh logs
7 tail -f src/services/llm/tmp/logs/llm.log
8
9 # Health check
10 sm health --all
11 curl http://localhost:8888/health
📄 Licença
MIT License - Veja
LICENSE
Feito com ❤️ pela equipe Ultravox