trading-platform/apps/llm-agent/DEPLOYMENT.md

495 lines
10 KiB
Markdown

# OrbiQuant LLM Agent - Deployment Guide
## Overview
El servicio LLM Agent proporciona un copiloto de trading inteligente que se ejecuta localmente en GPU usando Ollama, con soporte para modelos como Llama 3 y Mistral.
## Tabla de Contenidos
1. [Requisitos del Sistema](#requisitos-del-sistema)
2. [Instalación de Ollama](#instalación-de-ollama)
3. [Configuración del Servicio](#configuración-del-servicio)
4. [Instalación de Dependencias](#instalación-de-dependencias)
5. [Iniciar el Servicio](#iniciar-el-servicio)
6. [Verificación](#verificación)
7. [Troubleshooting](#troubleshooting)
---
## Requisitos del Sistema
### Hardware Recomendado
- **GPU:** NVIDIA RTX 5060 Ti (16GB VRAM) o superior
- **RAM:** Mínimo 16GB, recomendado 32GB
- **Storage:** 20GB libres para modelos
### Software
- **OS:** Linux (Ubuntu 20.04+) o WSL2
- **GPU Drivers:** NVIDIA drivers 525.60.13+
- **Docker:** 20.10+ con NVIDIA Container Toolkit
- **Python:** 3.11+
- **Conda:** Miniconda o Anaconda
---
## Instalación de Ollama
### Opción 1: Docker (Recomendado)
```bash
# Navegar al directorio del servicio
cd /home/isem/workspace/projects/trading-platform/apps/llm-agent
# Iniciar Ollama con GPU
docker-compose -f docker-compose.ollama.yml up -d
# Verificar que Ollama está corriendo
curl http://localhost:11434/api/tags
# Pull del modelo Llama 3 8B (recomendado para 16GB VRAM)
docker exec orbiquant-ollama ollama pull llama3:8b
# Alternativas según tu VRAM:
# docker exec orbiquant-ollama ollama pull mistral:7b # Más rápido
# docker exec orbiquant-ollama ollama pull llama3:70b # Requiere 40GB+ VRAM
# docker exec orbiquant-ollama ollama pull mixtral:8x7b # Requiere 32GB+ VRAM
```
**Nota:** La primera descarga del modelo puede tomar 10-30 minutos dependiendo de tu conexión.
### Opción 2: Instalación Nativa
```bash
# Linux
curl -fsSL https://ollama.com/install.sh | sh
# Iniciar Ollama
ollama serve &
# Pull del modelo
ollama pull llama3:8b
```
### Verificar GPU
```bash
# Verificar que Ollama detecta tu GPU
docker exec orbiquant-ollama nvidia-smi
# O en instalación nativa:
nvidia-smi
# Deberías ver tu RTX 5060 Ti listada
```
---
## Configuración del Servicio
### 1. Configurar Variables de Entorno
```bash
cd /home/isem/workspace/projects/trading-platform/apps/llm-agent
# Copiar archivo de ejemplo
cp .env.example .env
# Editar configuración
nano .env
```
Configuración mínima para Ollama:
```bash
# LLM Provider
LLM_PROVIDER=ollama
OLLAMA_BASE_URL=http://localhost:11434
LLM_MODEL=llama3:8b
# Service URLs (ajustar según tu deployment)
BACKEND_URL=http://localhost:8000
DATA_SERVICE_URL=http://localhost:8001
ML_ENGINE_URL=http://localhost:8002
# Database (usar la misma que el backend)
DATABASE_URL=postgresql://orbiquant:orbiquant123@localhost:5432/orbiquant
# Redis
REDIS_URL=redis://localhost:6379/0
```
### 2. Modelos Disponibles
| Modelo | VRAM Requerida | Velocidad | Calidad | Uso Recomendado |
|--------|---------------|-----------|---------|-----------------|
| `llama3:8b` | 8GB | Rápido | Excelente | **Recomendado para RTX 5060 Ti** |
| `mistral:7b` | 6GB | Muy rápido | Buena | Desarrollo/pruebas rápidas |
| `llama3:70b` | 40GB+ | Lento | Excepcional | Servidores de alta gama |
| `mixtral:8x7b` | 32GB+ | Medio | Excelente | GPUs grandes |
| `codellama:7b` | 6GB | Rápido | Buena | Code generation |
---
## Instalación de Dependencias
### Crear Entorno Conda
```bash
cd /home/isem/workspace/projects/trading-platform/apps/llm-agent
# Crear entorno
conda env create -f environment.yml
# Activar entorno
conda activate orbiquant-llm-agent
# O instalar con pip en el entorno
pip install -r requirements.txt
```
### Dependencias Principales
```
fastapi>=0.104.0 # API framework
uvicorn[standard]>=0.24.0 # ASGI server
sse-starlette>=1.6.5 # Streaming support
aiohttp>=3.9.0 # Async HTTP client
loguru>=0.7.0 # Logging
pydantic>=2.0.0 # Data validation
```
---
## Iniciar el Servicio
### Opción 1: Desarrollo (con hot-reload)
```bash
cd /home/isem/workspace/projects/trading-platform/apps/llm-agent
# Activar entorno
conda activate orbiquant-llm-agent
# Iniciar servicio
uvicorn src.main:app --reload --host 0.0.0.0 --port 8003
# El servicio estará disponible en:
# - API: http://localhost:8003
# - Docs: http://localhost:8003/docs
# - Health: http://localhost:8003/api/v1/health
```
### Opción 2: Producción
```bash
# Con más workers (1 por CPU core)
uvicorn src.main:app --host 0.0.0.0 --port 8003 --workers 4
# O usando gunicorn
gunicorn src.main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8003
```
### Opción 3: Docker (futuro)
```bash
# TODO: Crear Dockerfile para el servicio
docker-compose up llm-agent
```
---
## Verificación
### 1. Health Check
```bash
# Check básico
curl http://localhost:8003/
# Health detallado
curl http://localhost:8003/api/v1/health
# Expected response:
{
"status": "healthy",
"llm_provider": "ollama",
"llm_available": true,
"active_contexts": 0,
"available_tools": 12
}
```
### 2. Listar Modelos
```bash
curl http://localhost:8003/api/v1/models
# Expected response:
{
"models": ["llama3:8b"],
"current": "llama3:8b"
}
```
### 3. Listar Tools
```bash
curl "http://localhost:8003/api/v1/tools?user_plan=pro"
# Expected response:
{
"plan": "pro",
"tools": [
"get_signal",
"get_analysis",
"get_news",
"check_portfolio",
"get_positions",
"execute_trade",
...
],
"count": 12
}
```
### 4. Test Chat (básico)
```bash
curl -X POST http://localhost:8003/api/v1/chat \
-H "Content-Type: application/json" \
-d '{
"user_id": "test-user",
"conversation_id": "test-conv",
"message": "¿Qué es el RSI?",
"user_plan": "free",
"stream": false
}'
```
### 5. Test Análisis
```bash
curl -X POST http://localhost:8003/api/v1/analyze \
-H "Content-Type: application/json" \
-d '{
"user_id": "test-user",
"symbol": "AAPL",
"user_plan": "pro"
}'
```
### 6. Interactive API Docs
Abre en tu navegador: http://localhost:8003/docs
Aquí puedes probar todos los endpoints interactivamente.
---
## Troubleshooting
### Ollama no arranca
**Síntoma:** `Connection refused` al hacer curl a Ollama
**Solución:**
```bash
# Verificar que el container está corriendo
docker ps | grep ollama
# Ver logs
docker logs orbiquant-ollama
# Reiniciar container
docker restart orbiquant-ollama
```
### GPU no detectada
**Síntoma:** Modelo corre muy lento, CPU usage al 100%
**Solución:**
```bash
# Verificar NVIDIA Container Toolkit
docker run --rm --gpus all nvidia/cuda:11.8.0-base-ubuntu22.04 nvidia-smi
# Reinstalar nvidia-container-toolkit
sudo apt-get install -y nvidia-container-toolkit
sudo systemctl restart docker
```
### Out of Memory (OOM)
**Síntoma:** `CUDA out of memory` o el modelo no carga
**Solución:**
1. Usar un modelo más pequeño:
```bash
docker exec orbiquant-ollama ollama pull mistral:7b
```
2. Cerrar otras aplicaciones que usen GPU
3. Configurar `.env`:
```
LLM_MODEL=mistral:7b
```
### Modelo muy lento
**Optimizaciones:**
1. **Reducir max_tokens:**
```
MAX_TOKENS=1024 # En lugar de 2048
```
2. **Usar modelo más pequeño:**
```
LLM_MODEL=mistral:7b
```
3. **Verificar que usa GPU:**
```bash
# Durante inferencia, debería mostrar GPU usage
watch -n 0.5 nvidia-smi
```
### Herramientas no funcionan
**Síntoma:** Tools retornan errores de conexión
**Solución:**
```bash
# Verificar que otros servicios están corriendo
curl http://localhost:8000/health # Backend
curl http://localhost:8001/health # Data Service
curl http://localhost:8002/health # ML Engine
# Ajustar URLs en .env si es necesario
```
### Import Errors
**Síntoma:** `ModuleNotFoundError` al iniciar
**Solución:**
```bash
# Asegurarse de estar en el entorno correcto
conda activate orbiquant-llm-agent
# Reinstalar dependencias
pip install -r requirements.txt
# Verificar instalación
python -c "import fastapi; import aiohttp; print('OK')"
```
---
## Monitoreo
### Logs del Servicio
```bash
# Los logs se muestran en la consola
# Usar loguru levels: DEBUG, INFO, WARNING, ERROR
# Cambiar nivel en .env:
LOG_LEVEL=DEBUG
```
### Monitoreo de GPU
```bash
# Uso en tiempo real
watch -n 1 nvidia-smi
# Solo memoria
nvidia-smi --query-gpu=memory.used,memory.total --format=csv
# Temperatura
nvidia-smi --query-gpu=temperature.gpu --format=csv
```
### Ollama Web UI (Opcional)
Si levantaste Ollama con docker-compose, tendrás una UI web en:
http://localhost:3000
Desde ahí puedes:
- Chatear directamente con los modelos
- Gestionar modelos instalados
- Ver logs y métricas
---
## Performance Tips
### 1. Optimizar Temperatura
```python
# En .env, ajustar según el caso de uso:
TEMPERATURE=0.3 # Para análisis técnico (más determinista)
TEMPERATURE=0.7 # Para conversación general (más creativo)
TEMPERATURE=0.9 # Para brainstorming (muy creativo)
```
### 2. Context Window
Los modelos tienen límites de contexto:
- Llama 3 8B: 8K tokens (~6K palabras)
- Mistral 7B: 32K tokens (~24K palabras)
El sistema automáticamente limita el historial a `max_history=20` mensajes.
### 3. Batch Requests
Para múltiples análisis, usa requests paralelos:
```python
import asyncio
import aiohttp
async def analyze_multiple(symbols):
async with aiohttp.ClientSession() as session:
tasks = [
session.post('http://localhost:8003/api/v1/analyze', json={
'user_id': 'user-1',
'symbol': symbol,
'user_plan': 'pro'
})
for symbol in symbols
]
results = await asyncio.gather(*tasks)
return results
# Uso
symbols = ['AAPL', 'GOOGL', 'MSFT']
results = await analyze_multiple(symbols)
```
---
## Siguientes Pasos
1. Integrar con el frontend (WebSocket para streaming)
2. Implementar persistencia de conversaciones en PostgreSQL
3. Añadir RAG con ChromaDB para documentación de trading
4. Implementar rate limiting por usuario
5. Añadir métricas y telemetría
---
## Recursos
- **Ollama Docs:** https://github.com/ollama/ollama
- **Llama 3 Info:** https://ai.meta.com/llama/
- **FastAPI Docs:** https://fastapi.tiangolo.com/
- **Trading Tools API:** Ver `/docs/02-definicion-modulos/OQI-007-llm-agent/`
---
**Estado:** ✅ COMPLETADO
**Versión:** 1.0.0
**Última actualización:** 2025-12-07