> 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/arquitectura-y-conceptos/architecture/integration/2.6_api_flows.md).

# Flujos de API

Este documento describe, paso a paso, cómo Taína IA coordina las llamadas a Deepgram (STT), Google Gemini (LLM) y ElevenLabs (TTS) durante una conversación. Sustituye a los antiguos “diagramas de secuencia” y ofrece el mismo contenido en formato narrativo.

## 1. Flujo conversacional detallado

1. El ciudadano inicia la sesión desde la interfaz (botón “Ir al chat”).
2. La UI solicita al backend un token JWT y se conecta a la sala LiveKit asignada.
3. El backend se une a la misma sala y queda a la espera de audio.
4. El ciudadano emite su consulta; la UI captura el audio y lo envía a LiveKit.
5. LiveKit enruta el audio hacia el agente de voz.
6. El agente limpia el audio y lo envía a Deepgram para transcripción.
7. Deepgram devuelve transcripción en español, con resultados parciales cuando es necesario.
8. El agente pasa la transcripción a Google Gemini junto con el contexto de conversación.
9. Gemini analiza la intención y decide si invocar herramientas (`list_services`, `get_service_overview`, etc.).
10. Las herramientas consultan ChromaDB para obtener información oficial y devuelven un JSON estructurado.
11. Gemini sintetiza la respuesta final en texto, incorporando los datos recuperados.
12. El texto se envía a ElevenLabs para generar audio en voz natural dominicana.
13. El agente transmite el audio por LiveKit hacia la UI.
14. La interfaz reproduce la respuesta al ciudadano y muestra la transcripción.
15. El ciclo se repite hasta que el ciudadano finaliza la sesión o solicita apoyo humano.

## 2. Interacción con Deepgram (STT)

* **Endpoint**: `https://api.deepgram.com/v1/listen`
* **Autenticación**: header `Authorization: Token {DEEPGRAM_API_KEY}`
* **Parámetros clave**: `language=es`, `model=nova-2`, `punctuate=true`, `interim_results=true`
* **Respuesta**: JSON con transcripción, palabras y nivel de confianza.
* **Tiempo de uso**: tan pronto como la UI envía audio a LiveKit.

## 3. Interacción con Google Gemini (LLM)

* **Endpoint**: `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent`
* **Autenticación**: query `key={GOOGLE_API_KEY}`
* **Payload**: historial de conversación, transcripción actual y resultados de herramientas.
* **Respuesta**: texto en español y, cuando aplica, instrucciones de llamada a funciones.
* **Uso**: determina la intención, decide qué herramienta emplear y redacta la respuesta final.

## 4. Interacción con ElevenLabs (TTS)

* **Endpoint**: `https://api.elevenlabs.io/v1/text-to-speech/{voice_id}/stream`
* **Autenticación**: header `xi-api-key: {ELEVENLABS_API_KEY}`
* **Payload**: texto en español, modelo `eleven_multilingual_v2`, parámetros de voz (stability, similarity).
* **Respuesta**: flujo de audio MP3 listo para reproducir.
* **Uso**: convierte respuestas textuales en voz natural.

## 5. Consideraciones adicionales

* **Retos de latencia**: la transcripción parcial de Deepgram y el streaming de ElevenLabs permiten dar respuestas ágiles sin esperar a que finalice cada llamada.
* **Monitoreo**: cada integración registra métricas y errores en el subsistema de logging (`log_performance`, `log_system_health`), facilitando el diagnóstico cuando ocurre un fallo.


---

# 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/arquitectura-y-conceptos/architecture/integration/2.6_api_flows.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.
