> 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/api/configuration.md).

# Referencia de configuración

Esta documentación describe todas las opciones de configuración disponibles en Taína, incluyendo variables de entorno, configuraciones de retriever y opciones del agente.

## Variables de entorno

**Implementación**: `src/main.py` - CONFIG dict con variables reales del sistema

### Configuración del sistema

| Variable    | Tipo   | Descripción          | Valor por Defecto | Ejemplo        |
| ----------- | ------ | -------------------- | ----------------- | -------------- |
| `ENV`       | `str`  | Entorno de ejecución | `"development"`   | `"production"` |
| `DEBUG`     | `bool` | Modo debug           | `false`           | `true`         |
| `LOG_LEVEL` | `str`  | Nivel de logging     | `"INFO"`          | `"DEBUG"`      |

### Configuración del Agente (CONFIG dict)

**Implementación**: `src/main.py` - CONFIG dict con configuración real del sistema

```python
CONFIG = {
    "max_memory_mb": int(os.getenv("MAX_MEMORY_MB", "2500")),
    "warning_memory_mb": int(os.getenv("WARNING_MEMORY_MB", "1800")),
    "worker_processes": int(os.getenv("WORKER_PROCESSES", "3")),
    "load_threshold": float(os.getenv("LOAD_THRESHOLD", "0.8")),
    "stt_timeout": int(os.getenv("STT_TIMEOUT", "10")),
    "llm_timeout": int(os.getenv("LLM_TIMEOUT", "15")),
    "tts_timeout": int(os.getenv("TTS_TIMEOUT", "20")),
    "health_check_interval": int(os.getenv("HEALTH_CHECK_INTERVAL", "300")),
    "max_retry_attempts": int(os.getenv("MAX_RETRY_ATTEMPTS", "3")),
    "enable_health_checks": os.getenv("ENABLE_HEALTH_CHECKS", "true").lower() == "true",
    "enable_auto_recovery": os.getenv("ENABLE_AUTO_RECOVERY", "true").lower() == "true",
    "retriever_k": int(os.getenv("RETRIEVER_K", "3")),
    "retriever_fetch_k": int(os.getenv("RETRIEVER_FETCH_K", "9")),
    "chroma_collection": os.getenv("CHROMA_COLLECTION_NAME", "servicios"),
    "chroma_directory": os.getenv("CHROMA_DIRECTORY", "storage/chroma"),    
}
```

| Variable                 | Tipo    | Descripción                            | Valor por Defecto  | Ejemplo                 |
| ------------------------ | ------- | -------------------------------------- | ------------------ | ----------------------- |
| `MAX_MEMORY_MB`          | `int`   | Límite de memoria en MB                | `2500`             | `3000`                  |
| `WARNING_MEMORY_MB`      | `int`   | Umbral de advertencia de memoria       | `1800`             | `2000`                  |
| `WORKER_PROCESSES`       | `int`   | Número de procesos worker              | `3`                | `5`                     |
| `LOAD_THRESHOLD`         | `float` | Umbral de carga del sistema            | `0.8`              | `0.9`                   |
| `STT_TIMEOUT`            | `int`   | Timeout para Speech-to-Text (segundos) | `10`               | `15`                    |
| `LLM_TIMEOUT`            | `int`   | Timeout para LLM (segundos)            | `15`               | `20`                    |
| `TTS_TIMEOUT`            | `int`   | Timeout para Text-to-Speech (segundos) | `20`               | `25`                    |
| `HEALTH_CHECK_INTERVAL`  | `int`   | Intervalo de health checks (segundos)  | `300`              | `600`                   |
| `MAX_RETRY_ATTEMPTS`     | `int`   | Número máximo de reintentos            | `3`                | `5`                     |
| `ENABLE_HEALTH_CHECKS`   | `bool`  | Habilitar health checks                | `true`             | `false`                 |
| `ENABLE_AUTO_RECOVERY`   | `bool`  | Habilitar recuperación automática      | `true`             | `false`                 |
| `RETRIEVER_K`            | `int`   | Número de documentos a recuperar       | `3`                | `5`                     |
| `RETRIEVER_FETCH_K`      | `int`   | Número de documentos a buscar          | `9`                | `15`                    |
| `CHROMA_COLLECTION_NAME` | `str`   | Nombre de la colección ChromaDB        | `"servicios"`      | `"servicios_gob"`       |
| `CHROMA_DIRECTORY`       | `str`   | Directorio de ChromaDB                 | `"storage/chroma"` | `"storage/chroma_prod"` |

### LiveKit Configuration

| Variable             | Tipo  | Descripción              | Valor por Defecto | Ejemplo                   |
| -------------------- | ----- | ------------------------ | ----------------- | ------------------------- |
| `LIVEKIT_URL`        | `str` | URL del servidor LiveKit | -                 | `"wss://your-server.com"` |
| `LIVEKIT_API_KEY`    | `str` | Clave API de LiveKit     | -                 | `"your_api_key"`          |
| `LIVEKIT_API_SECRET` | `str` | Secreto API de LiveKit   | -                 | `"your_api_secret"`       |

### Google Gemini

| Variable         | Tipo  | Descripción                | Valor por Defecto | Ejemplo                 |
| ---------------- | ----- | -------------------------- | ----------------- | ----------------------- |
| `GOOGLE_API_KEY` | `str` | Clave API de Google Gemini | -                 | `"your_google_api_key"` |

### Speech-to-Text (Deepgram)

| Variable           | Tipo  | Descripción           | Valor por Defecto | Ejemplo                   |
| ------------------ | ----- | --------------------- | ----------------- | ------------------------- |
| `DEEPGRAM_API_KEY` | `str` | Clave API de Deepgram | -                 | `"your_deepgram_api_key"` |

### Text-to-Speech (ElevenLabs)

| Variable              | Tipo  | Descripción             | Valor por Defecto | Ejemplo                     |
| --------------------- | ----- | ----------------------- | ----------------- | --------------------------- |
| `ELEVENLABS_API_KEY`  | `str` | Clave API de ElevenLabs | -                 | `"your_elevenlabs_api_key"` |
| `ELEVENLABS_VOICE_ID` | `str` | ID de voz de ElevenLabs | -                 | `"your_voice_id"`           |

### Configuración de Memoria

| Variable            | Tipo  | Descripción                           | Valor por Defecto | Ejemplo |
| ------------------- | ----- | ------------------------------------- | ----------------- | ------- |
| `MAX_MEMORY_MB`     | `int` | Límite máximo de memoria (MB)         | `4000`            | `8000`  |
| `WARNING_MEMORY_MB` | `int` | Umbral de advertencia de memoria (MB) | `3000`            | `6000`  |

### Configuración de Workers

| Variable           | Tipo    | Descripción                 | Valor por Defecto | Ejemplo |
| ------------------ | ------- | --------------------------- | ----------------- | ------- |
| `WORKER_PROCESSES` | `int`   | Número de procesos worker   | `4`               | `8`     |
| `LOAD_THRESHOLD`   | `float` | Umbral de carga del sistema | `0.8`             | `0.9`   |

### Timeouts

| Variable      | Tipo  | Descripción                 | Valor por Defecto | Ejemplo |
| ------------- | ----- | --------------------------- | ----------------- | ------- |
| `STT_TIMEOUT` | `int` | Timeout para STT (segundos) | `15`              | `20`    |
| `LLM_TIMEOUT` | `int` | Timeout para LLM (segundos) | `20`              | `30`    |
| `TTS_TIMEOUT` | `int` | Timeout para TTS (segundos) | `25`              | `35`    |

### Health Checks

| Variable                | Tipo   | Descripción                           | Valor por Defecto | Ejemplo |
| ----------------------- | ------ | ------------------------------------- | ----------------- | ------- |
| `ENABLE_HEALTH_CHECKS`  | `bool` | Habilitar health checks               | `true`            | `false` |
| `HEALTH_CHECK_INTERVAL` | `int`  | Intervalo de health checks (segundos) | `300`             | `600`   |
| `ENABLE_AUTO_RECOVERY`  | `bool` | Habilitar recuperación automática     | `true`            | `false` |

### Retry Configuration

| Variable             | Tipo  | Descripción                 | Valor por Defecto | Ejemplo |
| -------------------- | ----- | --------------------------- | ----------------- | ------- |
| `MAX_RETRY_ATTEMPTS` | `int` | Número máximo de reintentos | `3`               | `5`     |

### ChromaDB Configuration

| Variable                 | Tipo  | Descripción                      | Valor por Defecto  | Ejemplo            |
| ------------------------ | ----- | -------------------------------- | ------------------ | ------------------ |
| `CHROMA_COLLECTION_NAME` | `str` | Nombre de la colección ChromaDB  | `"servicios"`      | `"servicios_prod"` |
| `CHROMA_DIRECTORY`       | `str` | Directorio de ChromaDB           | `"storage/chroma"` | `"/data/chroma"`   |
| `RETRIEVER_K`            | `int` | Número de documentos a recuperar | `3`                | `5`                |
| `RETRIEVER_FETCH_K`      | `int` | Número de documentos a buscar    | `9`                | `15`               |

## Configuración de Retriever

### Estructura de configuración

```python
_RETRIEVER_CONFIG = {
    "chunks": {
        "directory": Path("storage/chroma"),
        "collection": "servicios",
        "retriever_k": 3,
    },
    "qa": {
        "directory": Path("storage/chroma_qa"),
        "collection": "servicios_qa",
        "retriever_k": 3,
    },
}
```

### Parámetros de retriever

| Parámetro     | Tipo   | Descripción                      | Valor por Defecto  |
| ------------- | ------ | -------------------------------- | ------------------ |
| `directory`   | `Path` | Directorio de ChromaDB           | `"storage/chroma"` |
| `collection`  | `str`  | Nombre de la colección           | `"servicios"`      |
| `retriever_k` | `int`  | Número de documentos a recuperar | `3`                |
| `fetch_k`     | `int`  | Número de documentos a buscar    | `9`                |

## Configuración del Agente

### Opciones del Agente

```python
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,
            ],
        )
```

### Configuración de STT

```python
# Configuración de Deepgram STT
stt = STT.create(
    provider="deepgram",
    model="nova-2",
    language="es",
    sample_rate=16000,
    channels=1,
)
```

### Configuración de 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",
)
```

### Configuración de LLM

```python
# Configuración de Google Gemini
llm = GeminiLLM(
    model="gemini-1.5-flash",
    temperature=0.7,
    max_tokens=1000,
)
```

## Configuración de Logging

### Niveles de Log

| Nivel      | Descripción           | Uso        |
| ---------- | --------------------- | ---------- |
| `DEBUG`    | Información detallada | Desarrollo |
| `INFO`     | Información general   | Producción |
| `WARNING`  | Advertencias          | Producción |
| `ERROR`    | Errores               | Producción |
| `CRITICAL` | Errores críticos      | Producción |

### Configuración de Logger

```python
import logging

# Configurar logger
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('logs/taina.log'),
        logging.StreamHandler()
    ]
)
```

## Configuración de Monitoreo

### Health Check Configuration

```python
# Configuración de health checks
HEALTH_CHECK_CONFIG = {
    "interval": int(os.getenv("HEALTH_CHECK_INTERVAL", 300)),
    "enabled": os.getenv("ENABLE_HEALTH_CHECKS", "true").lower() == "true",
    "auto_recovery": os.getenv("ENABLE_AUTO_RECOVERY", "true").lower() == "true",
}
```

### Memory Monitoring

```python
# Configuración de monitoreo de memoria
MEMORY_CONFIG = {
    "max_memory_mb": int(os.getenv("MAX_MEMORY_MB", 4000)),
    "warning_memory_mb": int(os.getenv("WARNING_MEMORY_MB", 3000)),
    "check_interval": 60,  # segundos
}
```

## Configuración de desarrollo

### Variables para desarrollo

```ini
# Desarrollo
ENV=development
DEBUG=true
LOG_LEVEL=DEBUG

# Configuración de desarrollo
MAX_MEMORY_MB=2000
WARNING_MEMORY_MB=1500
WORKER_PROCESSES=1
ENABLE_HEALTH_CHECKS=true
ENABLE_AUTO_RECOVERY=false

# Timeouts más cortos para desarrollo
STT_TIMEOUT=10
LLM_TIMEOUT=15
TTS_TIMEOUT=20

# Retry Configuration
MAX_RETRY_ATTEMPTS=1
```

## Configuración de producción

### Variables para producción

```ini
# Producción
ENV=production
DEBUG=false
LOG_LEVEL=INFO

# Configuración de producción
MAX_MEMORY_MB=8000
WARNING_MEMORY_MB=6000
WORKER_PROCESSES=8
LOAD_THRESHOLD=0.9
ENABLE_HEALTH_CHECKS=true
ENABLE_AUTO_RECOVERY=true

# Timeouts de producción
STT_TIMEOUT=20
LLM_TIMEOUT=30
TTS_TIMEOUT=35

# Retry Configuration
MAX_RETRY_ATTEMPTS=5

# Health Checks
HEALTH_CHECK_INTERVAL=600
```

## Validación de configuración

### Script de validación

```python
#!/usr/bin/env python3
"""
validate_config.py - Validar configuración de TAINA
"""

import os
from typing import Dict, List, Any

def validate_required_vars() -> List[str]:
    """Valida variables de entorno requeridas"""
    required_vars = [
        "LIVEKIT_URL",
        "LIVEKIT_API_KEY", 
        "LIVEKIT_API_SECRET",
        "GOOGLE_API_KEY",
        "DEEPGRAM_API_KEY",
        "ELEVENLABS_API_KEY",
        "ELEVENLABS_VOICE_ID"
    ]
    
    missing_vars = []
    for var in required_vars:
        if not os.getenv(var):
            missing_vars.append(var)
    
    return missing_vars

def validate_optional_vars() -> Dict[str, Any]:
    """Valida variables de entorno opcionales"""
    config = {}
    
    # Configuración de memoria
    config["MAX_MEMORY_MB"] = int(os.getenv("MAX_MEMORY_MB", 4000))
    config["WARNING_MEMORY_MB"] = int(os.getenv("WARNING_MEMORY_MB", 3000))
    
    # Configuración de workers
    config["WORKER_PROCESSES"] = int(os.getenv("WORKER_PROCESSES", 4))
    config["LOAD_THRESHOLD"] = float(os.getenv("LOAD_THRESHOLD", 0.8))
    
    # Timeouts
    config["STT_TIMEOUT"] = int(os.getenv("STT_TIMEOUT", 15))
    config["LLM_TIMEOUT"] = int(os.getenv("LLM_TIMEOUT", 20))
    config["TTS_TIMEOUT"] = int(os.getenv("TTS_TIMEOUT", 25))
    
    # Health checks
    config["ENABLE_HEALTH_CHECKS"] = os.getenv("ENABLE_HEALTH_CHECKS", "true").lower() == "true"
    config["HEALTH_CHECK_INTERVAL"] = int(os.getenv("HEALTH_CHECK_INTERVAL", 300))
    config["ENABLE_AUTO_RECOVERY"] = os.getenv("ENABLE_AUTO_RECOVERY", "true").lower() == "true"
    
    # Retry
    config["MAX_RETRY_ATTEMPTS"] = int(os.getenv("MAX_RETRY_ATTEMPTS", 3))
    
    # ChromaDB
    config["CHROMA_COLLECTION_NAME"] = os.getenv("CHROMA_COLLECTION_NAME", "servicios")
    config["CHROMA_DIRECTORY"] = os.getenv("CHROMA_DIRECTORY", "storage/chroma")
    config["RETRIEVER_K"] = int(os.getenv("RETRIEVER_K", 3))
    config["RETRIEVER_FETCH_K"] = int(os.getenv("RETRIEVER_FETCH_K", 9))
    
    return config

def main():
    print("🔍 Validando configuración de TAINA...")
    
    # Validar variables requeridas
    missing_vars = validate_required_vars()
    if missing_vars:
        print("❌ Variables de entorno faltantes:")
        for var in missing_vars:
            print(f"  - {var}")
        return False
    
    # Validar variables opcionales
    config = validate_optional_vars()
    
    print("✅ Configuración válida")
    print("📊 Configuración actual:")
    for key, value in config.items():
        print(f"  {key}: {value}")
    
    return True

if __name__ == "__main__":
    main()
```

## Configuración de archivos

### Archivo .env de ejemplo

```ini
# Configuración del Sistema
ENV=production
DEBUG=false
LOG_LEVEL=INFO

# LiveKit Configuration
LIVEKIT_URL=wss://your-livekit-server.com
LIVEKIT_API_KEY=your_livekit_api_key
LIVEKIT_API_SECRET=your_livekit_api_secret

# Google Gemini
GOOGLE_API_KEY=your_google_api_key

# Speech-to-Text
DEEPGRAM_API_KEY=your_deepgram_api_key

# Text-to-Speech
ELEVENLABS_API_KEY=your_elevenlabs_api_key
ELEVENLABS_VOICE_ID=your_voice_id

# Configuración de Producción
MAX_MEMORY_MB=8000
WARNING_MEMORY_MB=6000
WORKER_PROCESSES=8
LOAD_THRESHOLD=0.9

# Timeouts de Producción
STT_TIMEOUT=20
LLM_TIMEOUT=30
TTS_TIMEOUT=35

# Health Checks
HEALTH_CHECK_INTERVAL=600
ENABLE_HEALTH_CHECKS=true
ENABLE_AUTO_RECOVERY=true

# Retry Configuration
MAX_RETRY_ATTEMPTS=5

# ChromaDB
CHROMA_COLLECTION_NAME=servicios
CHROMA_DIRECTORY=storage/chroma
RETRIEVER_K=3
RETRIEVER_FETCH_K=9
```

## Configuración de Docker

### Dockerfile

```dockerfile
FROM python:3.12-slim

WORKDIR /app

# Instalar dependencias del sistema
RUN apt-get update && apt-get install -y \
    jq \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Copiar archivos de configuración
COPY requirements.txt .
COPY pyproject.toml .

# Instalar dependencias Python
RUN pip install --no-cache-dir -r requirements.txt

# Copiar código fuente
COPY src/ ./src/
COPY data/ ./data/

# Crear directorios necesarios
RUN mkdir -p storage/chroma storage/chroma_qa logs

# Variables de entorno por defecto
ENV ENV=production
ENV MAX_MEMORY_MB=4000
ENV WORKER_PROCESSES=4

# Exponer puerto
EXPOSE 3000

# Comando por defecto
CMD ["python", "-m", "src.main"]
```

### docker-compose.yml

```yaml
version: '3.8'

services:
  taina-backend:
    build: .
    ports:
      - "3000:3000"
    environment:
      - ENV=production
      - LIVEKIT_URL=${LIVEKIT_URL}
      - LIVEKIT_API_KEY=${LIVEKIT_API_KEY}
      - LIVEKIT_API_SECRET=${LIVEKIT_API_SECRET}
      - GOOGLE_API_KEY=${GOOGLE_API_KEY}
      - DEEPGRAM_API_KEY=${DEEPGRAM_API_KEY}
      - ELEVENLABS_API_KEY=${ELEVENLABS_API_KEY}
      - ELEVENLABS_VOICE_ID=${ELEVENLABS_VOICE_ID}
    volumes:
      - ./storage:/app/storage
      - ./logs:/app/logs
    restart: unless-stopped
```

## Próximos pasos

1. **Herramientas**: [Herramientas](/taina-agente-ia-ogtic/referencias-tecnicas/api/tools.md)
2. **Catálogo de Herramientas**: [Catálogo de herramientas](https://github.com/public-intelligence/taina_ogtic/blob/master/taina-gitbook-ogtic/taina-asistente-ia/index/scripts/service-catalog.md)
3. **Pipeline de Datos**: [Pipeline de datos](https://github.com/public-intelligence/taina_ogtic/blob/master/taina-gitbook-ogtic/general/development/data-pipeline.md)

## Recursos adicionales

* [LiveKit Configuration](https://docs.livekit.io/guides/production/)
* [Google Gemini API](https://ai.google.dev/docs)
* [Deepgram API](https://developers.deepgram.com/)
* [ElevenLabs API](https://docs.elevenlabs.io/)

***

¿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 herramientas](/taina-agente-ia-ogtic/referencias-tecnicas/api/tools.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/api/configuration.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.
