Neste tutorial, mostramos como se conectar à API Gemini Live usando WebSockets. Neste tutorial, você vai criar um aplicativo multimodal em tempo real com um front-end JavaScript simples e um servidor Python que processa a autenticação e o proxy.
Antes de começar
Conclua as etapas a seguir para configurar seu ambiente.
- Faça login na sua conta do Google Cloud . Se você começou a usar o Google Cloudagora, crie uma conta para avaliar o desempenho dos nossos produtos em situações reais. Clientes novos também recebem US $300 em créditos para executar, testar e implantar cargas de trabalho.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud 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 theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Gemini Enterprise Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. 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.-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init -
In the Google Cloud console, on the project selector page, select or create a Google Cloud 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 theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Gemini Enterprise Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. 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.-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init - Instale o Git.
- Instale o Python 3.
Clonar o app de demonstração
Clone o repositório do app de demonstração e navegue até esse diretório:
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
Estrutura do projeto
O aplicativo inclui os seguintes arquivos:
/
├── 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
Executar o servidor de back-end
O back-end (server.py) processa a autenticação e atua como um proxy
WebSocket entre o cliente e a API Gemini Live.
Para executar o servidor de back-end, execute os seguintes comandos:
Instale as dependências:
pip3 install -r requirements.txtAutenticar com Google Cloud:
gcloud auth application-default loginInicie o servidor:
python3 server.py
Abra a UI de front-end e conecte-se ao Gemini
O front-end gerencia a captura e a reprodução de áudio e vídeo. O arquivo
geminilive.js processa a conexão WebSocket com o back-end.
const client = new GeminiLiveAPI(proxyUrl, projectId, model);
client.addFunction(toolInstance); // Add custom tools
client.connect(accessToken); // Connect (token optional with proxy)
Para abrir a UI do usuário de front-end e se conectar ao Gemini, faça o seguinte:
- Abra o navegador e acesse http://localhost:8000.
- No campo ID do projeto, insira o ID do projeto Google Cloud .
- Clique em Conectar.
Interagir com o Gemini
Tente fazer o seguinte:
- Entrada de texto: você pode escrever uma mensagem de texto para o Gemini digitando sua mensagem no campo de mensagem e clicando em Enviar. O Gemini responde à mensagem usando áudio.
- Entrada de texto por voz: para falar com o Gemini, clique em Iniciar microfone. O Gemini responde ao comando usando áudio.
- Entrada de vídeo: para permitir que o Gemini veja pela sua câmera, clique em Iniciar câmera. Você pode conversar com o Gemini sobre o que ele vê pela sua câmera.
A seguir
- Saiba como configurar idioma e voz.
- Saiba como configurar os recursos do Gemini.
- Saiba mais sobre as práticas recomendadas da API Gemini Live.