通过 Google Gen AI SDK 开始使用 Gemini Live API

本教程介绍了如何使用 Google Gen AI SDK for Python 连接到 Gemini Live API。在本教程中,您将构建一个实时多模态应用,该应用使用强大的 Python 后端来处理 API 连接。

准备工作

完成以下步骤以设置您的环境。

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Install the Google Cloud CLI.

  5. 如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI

  6. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  7. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  8. Verify that billing is enabled for your Google Cloud project.

  9. Install the Google Cloud CLI.

  10. 如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI

  11. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  12. 安装 Git
  13. 安装 Python 3
  14. 克隆演示应用

    克隆演示应用代码库并前往该目录:

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

    项目结构

    该应用包含以下文件:

    /
    ├── main.py                 # FastAPI server and WebSocket endpoint
    ├── gemini_live.py          # Gemini Live API wrapper using Gen AI SDK
    ├── requirements.txt        # Python dependencies
    └── frontend/
        ├── index.html          # User Interface
        ├── main.js             # Application logic
        ├── gemini-client.js    # WebSocket client for backend communication
        ├── media-handler.js    # Audio/Video capture and playback
        └── pcm-processor.js    # AudioWorklet for PCM processing
    

    配置环境变量

    为了便于本次演示,我们需要配置的唯一环境变量是用于定义 Google Cloud 项目 ID 的环境变量。以下命令会创建一个 .env 文件,用于设置环境变量 PROJECT_ID。将 PROJECT_ID 替换为您的 Google Cloud 项目的项目 ID。

    echo "PROJECT_ID=PROJECT_ID" > .env
    

    运行后端服务器

    后端 (main.py) 处理客户端与 Gemini Live API 之间的连接。入口点是一个公开 WebSocket 端点的 FastAPI 服务器。它接受来自前端的音频和视频块,并将它们转发到 GeminiLive 会话。gemini_live.py 中的 GeminiLive 类封装了 genai.Client 以管理会话。

    # Connects using the SDK
    async with self.client.aio.live.connect(model=self.model, config=config) as session:
        # Manages input/output queues
        await asyncio.gather(
            send_audio(),
            send_video(),
            receive_responses()
        )
    

    如要运行后端服务器,请运行以下命令:

    1. 安装依赖项:

      pip3 install -r requirements.txt
      
    2. 向 Google Cloud进行身份验证:

      gcloud auth application-default login
      
    3. 启动服务器:

      python3 main.py
      

    打开前端界面并与 Gemini 连接

    前端管理音频和视频的捕获与播放。gemini-client.js 文件处理与后端的 WebSocket 连接。它将 base64 编码的媒体块发送到后端,并从 Gemini Live API 接收音频响应,然后将这些响应播放给用户。

    如需打开前端界面并与 Gemini 连接,请执行以下操作:

    1. 打开浏览器并前往 http://localhost:8000
    2. 点击连接

    与 Gemini 互动

    请尝试执行以下操作:

    • 文字输入:您可以在消息字段中输入消息,然后点击发送,从而撰写消息发送给 Gemini。Gemini 会使用音频回复消息。
    • 语音输入:如需与 Gemini 对话,请点击启动麦克风。 Gemini 会使用音频回答提示。
    • 视频输入:如需让 Gemini 通过摄像头查看,请点击启动摄像头。你可以与 Gemini 聊聊它通过摄像头看到的内容。

    后续步骤