Comienza a usar la API de Gemini Live con WebSockets

En este instructivo, se muestra cómo conectarse a la API de Gemini Live con WebSockets. En este instructivo, compilarás una aplicación multimodal en tiempo real con un frontend de JavaScript estándar y un servidor de Python que controla la autenticación y el proxy.

Antes de comenzar

Completa los siguientes pasos para configurar el entorno.

  1. In the Cloud de Confiance console, on the project selector page, select or create a Cloud de Confiance project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  2. Verify that billing is enabled for your Cloud de Confiance project.

  3. Enable the Agent Platform API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  4. Install the Google Cloud CLI.

  5. Configure the gcloud CLI to use your federated identity.

    For more information, see Sign in to the gcloud CLI with your federated identity.

  6. To initialize the gcloud CLI, run the following command:

    gcloud init
  7. Instala Git.
  8. Instala Python 3.

Clona la app de demo

Clona el repositorio de la app de demo y navega a ese directorio:

git clone https://github.com/GoogleCloudPlatform/generative-ai.git &&
cd generative-ai/gemini/multimodal-live-api/native-audio-websocket-demo-apps/plain-js-demo-app

Estructura del proyecto

La aplicación incluye los siguientes archivos:

/
├── server.py            # WebSocket proxy + HTTP server
├── requirements.txt     # Python dependencies
└── frontend/
    ├── index.html       # UI
    ├── geminilive.js    # Gemini API client
    ├── mediaUtils.js    # Audio/video streaming
    ├── tools.js         # Custom tool definitions
    └── script.js        # App logic

Ejecuta el servidor de backend

El backend (server.py) controla la autenticación y actúa como proxy de WebSocket entre el cliente y la API de Gemini Live.

Para ejecutar el servidor de backend, ejecuta los siguientes comandos:

  1. Instala las dependencias:

    pip3 install -r requirements.txt
    
  2. Autentícate con Cloud de Confiance by S3NS:

    gcloud auth application-default login
    
  3. Inicia el servidor. Para esto, sigue los pasos siguientes:

    python3 server.py
    

Abre la IU de frontend y conéctate con Gemini

El frontend administra la captura y reproducción de audio y video. El archivo geminilive.js controla la conexión de WebSocket al backend.

const client = new GeminiLiveAPI(proxyUrl, projectId, model);
client.addFunction(toolInstance); // Add custom tools
client.connect(accessToken); // Connect (token optional with proxy)

Para abrir la IU de frontend y conectarte con Gemini, haz lo siguiente:

  1. Abre tu navegador y ve a http://localhost:8000.
  2. En el campo ID del proyecto, ingresa el ID de tu proyecto Cloud de Confiance .
  3. Haz clic en Conectar.

Interactúa con Gemini

Intenta lo siguiente:

  • Entrada de texto: Puedes escribir un mensaje de texto a Gemini ingresando tu mensaje en el campo de mensajes y haciendo clic en Enviar. Gemini responde el mensaje con audio.
  • Entrada de voz: Para hablar con Gemini, haz clic en Iniciar micrófono. Gemini responde a la instrucción con audio.
  • Entrada de video: Para permitir que Gemini vea a través de tu cámara, haz clic en Iniciar cámara. Puedes hablar con Gemini sobre lo que ve a través de tu cámara.

¿Qué sigue?