> For the complete documentation index, see [llms.txt](https://public-intelligence.gitbook.io/taina-agente-ia-ogtic/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://public-intelligence.gitbook.io/taina-agente-ia-ogtic/referencias-tecnicas/integrations/livekit.md).

# LiveKit

Esta guía explica cómo Taína se integra con LiveKit para proporcionar comunicación en tiempo real con agentes de voz.

LiveKit es la plataforma de comunicación en tiempo real que permite a Taína:

* **Comunicación WebRTC**: Conexión de audio/video en tiempo real
* **Gestión de Sesiones**: Manejo automático de conexiones de usuarios
* **Escalabilidad**: Soporte para múltiples usuarios simultáneos

## Configuración de LiveKit

### 1. Obtener credenciales

#### LiveKit Cloud (Recomendado)

```bash
# Registrarse en LiveKit Cloud
# https://cloud.livekit.io/

# Obtener credenciales del dashboard
LIVEKIT_URL=wss://your-project.livekit.cloud
LIVEKIT_API_KEY=your_api_key
LIVEKIT_API_SECRET=your_api_secret
```

#### LiveKit Self-Hosted

```bash
# Instalar LiveKit Server
docker run --rm -p 7880:7880 -p 7881:7881/udp livekit/livekit-server

# Configurar variables
LIVEKIT_URL=ws://localhost:7880
LIVEKIT_API_KEY=your_api_key
LIVEKIT_API_SECRET=your_api_secret
```

### 2. Configuración en Taína

```python
# src/main.py - Configuración del agente LiveKit
from livekit.agents import Agent, JobContext
from livekit.plugins.deepgram import STT
from livekit.plugins.elevenlabs import TTS
from livekit.plugins.google import GeminiLLM

class ProductionAssistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions=COMBINED_PROMPT,
            tools=[
                list_services,
                get_service_overview,
                list_service_variations,
                get_service_locations,
                get_service_digital_channel,
                get_service_contact,
                ask_knowledge_base,
                get_current_date,
            ],
        )
```

### 3. Variables de entorno

```ini
# LiveKit Configuration
LIVEKIT_URL=wss://your-project.livekit.cloud
LIVEKIT_API_KEY=your_api_key
LIVEKIT_API_SECRET=your_api_secret

# Opcional: Configuración avanzada
LIVEKIT_REGION=us-east-1
LIVEKIT_REDIS_URL=redis://localhost:6379
```

## Arquitectura de sesión

### Flujo de conexión

1. El cliente solicita un token y se conecta a LiveKit.
2. El agente se une a la sala, prepara STT/TTS y valida credenciales.
3. La sesión se mantiene activa hasta que el usuario o el backend cierran la conexión.

### Ciclo de vida de sesión

```python
# src/main.py - Manejo de sesiones
async def entrypoint(ctx: JobContext):
    """Entrypoint principal del agente LiveKit"""
    
    # 1. Inicialización
    await ctx.wait_for_room()
    room = ctx.room
    
    # 2. Configuración de audio
    stt = STT.create(
        provider="deepgram",
        model="nova-2",
        language="es"
    )
    
    tts = TTS.create(
        provider="elevenlabs",
        voice_id=os.getenv("ELEVENLABS_VOICE_ID")
    )
    
    # 3. Creación del agente
    agent = ProductionAssistant()
    
    # 4. Manejo de sesión
    await agent.start(ctx, stt=stt, tts=tts)
```

## Configuración de audio

### Speech-to-Text (STT)

```python
# Configuración de Deepgram STT
stt = STT.create(
    provider="deepgram",
    model="nova-2",           # Modelo optimizado para español
    language="es",             # Idioma español
    sample_rate=16000,        # Frecuencia de muestreo
    channels=1,               # Mono
    interim_results=True,     # Resultados parciales
    punctuation=True,        # Puntuación automática
    profanity_filter=False    # Sin filtro de palabras
)
```

### Text-to-Speech (TTS)

```python
# Configuración de ElevenLabs TTS
tts = TTS.create(
    provider="elevenlabs",
    voice_id=os.getenv("ELEVENLABS_VOICE_ID"),
    model="eleven_multilingual_v2",
    language="es",
    stability=0.5,           # Estabilidad de voz
    similarity_boost=0.8,    # Similitud con voz original
    style=0.0,               # Estilo de voz
    use_speaker_boost=True   # Mejora de voz
)
```

## Monitoreo y health checks

### Health Check de LiveKit

```python
# src/tools.py - Health check para LiveKit
@function_tool()
async def health_check() -> str:
    """Verifica el estado del sistema incluyendo LiveKit"""
    
    status = {
        "timestamp": datetime.now().isoformat(),
        "livekit": "unknown",
        "knowledge_base": "unknown",
        "memory_usage": "unknown"
    }
    
    # Verificar conexión LiveKit
    try:
        # Test de conectividad
        import aiohttp
        async with aiohttp.ClientSession() as session:
            async with session.get(f"{LIVEKIT_URL}/health") as response:
                if response.status == 200:
                    status["livekit"] = "healthy"
                else:
                    status["livekit"] = "unhealthy"
    except Exception as e:
        status["livekit"] = f"error: {str(e)}"
    
    return json.dumps(status)
```

### Métricas de sesión

```python
# Métricas que se pueden monitorear
session_metrics = {
    "active_sessions": len(active_rooms),
    "total_sessions_today": daily_count,
    "average_session_duration": avg_duration,
    "audio_quality_score": quality_score
}
```

## Troubleshooting

### Problemas comunes

#### Error: "LiveKit connection failed"

```bash
# Verificar URL y credenciales
curl -I $LIVEKIT_URL

# Verificar claves API
python3 -c "
import os
print('URL:', os.getenv('LIVEKIT_URL'))
print('API Key:', os.getenv('LIVEKIT_API_KEY')[:10] + '...')
"
```

#### Error: "Room not found"

```bash
# Verificar que la sala existe
# En el frontend, verificar que se crea correctamente
const room = new Room();
await room.connect(livekitUrl, token);
```

#### Error: "Audio quality issues"

```bash
# Verificar configuración de audio
# Ajustar parámetros de STT/TTS
export AUDIO_SAMPLE_RATE=16000
export AUDIO_CHANNELS=1
```

### Logs de LiveKit

```bash
# Ver logs del agente
tail -f logs/taina.log | grep -i livekit

# Ver logs de LiveKit Server (si es self-hosted)
docker logs livekit-server
```

## Configuración avanzada

### Escalabilidad

```python
# Configuración para múltiples workers
worker_config = {
    "max_workers": int(os.getenv("WORKER_PROCESSES", 4)),
    "load_balancing": True,
    "health_check_interval": 30,
    "auto_scaling": True
}
```

### Seguridad

```python
# Configuración de seguridad
security_config = {
    "jwt_expiry": 3600,           # 1 hora
    "room_encryption": True,      # Encriptación de sala
    "access_control": True        # Control de acceso
}
```

## Recursos adicionales

* [LiveKit Documentation](https://docs.livekit.io/)
* [LiveKit Agents Guide](https://docs.livekit.io/agents/)
* [LiveKit Cloud](https://cloud.livekit.io/)
* [WebRTC Best Practices](https://webrtc.org/getting-started/)

## Próximos pasos

1. **Integración Google Gemini**: [Integración Google Gemini](/taina-agente-ia-ogtic/referencias-tecnicas/integrations/google-gemini.md)
2. **Integración Deepgram**: [Deepgram Integration](/taina-agente-ia-ogtic/referencias-tecnicas/integrations/deepgram.md)
3. **Integración ElevenLabs**: [ElevenLabs Integration](/taina-agente-ia-ogtic/referencias-tecnicas/integrations/elevenlabs.md)
4. **Arquitectura de la Base de Conocimiento**: [Arquitectura de la base de conocimiento](/taina-agente-ia-ogtic/arquitectura-y-conceptos/architecture/knowledge-base.md)

***

¿Necesitas ayuda? Consulta la [guía de solución de problemas](https://github.com/public-intelligence/taina_ogtic/blob/master/taina-gitbook-ogtic/taina-asistente-ia/index/how-to/troubleshoot.md) o la [documentación de configuración](/taina-agente-ia-ogtic/referencias-tecnicas/api/configuration.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://public-intelligence.gitbook.io/taina-agente-ia-ogtic/referencias-tecnicas/integrations/livekit.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
