使用 ADK 開始使用 Gemini Live API

本教學課程說明如何建立代理程式,並使用 Agent Development Kit (ADK) 串流功能啟用語音和視訊通訊。您將安裝 ADK、設定使用 Google 搜尋的基本代理,並使用 adk web 工具執行代理。

事前準備

本指南假設您有在 Windows、macOS 或 Linux 環境中使用終端機的經驗。

設定環境並安裝 ADK

本節說明如何準備本機環境。

  1. 建立並啟用虛擬環境。建議使用虛擬環境。

    # Create the environment
    python -m venv .venv
    
    # Activate the environment in each new terminal
    # For macOS or Linux:
    source .venv/bin/activate
    # For Windows CMD:
    .venv\Scripts\activate.bat
    # For Windows PowerShell:
    .venv\Scripts\Activate.ps1
    
  2. 安裝 ADK。

    pip install google-adk
    

建立專案結構

為代理程式建立必要的目錄和檔案。

  1. 建立下列資料夾結構,並加入空白檔案:

    專案結構圖:adk-streaming 資料夾包含 app 資料夾,其中包含 .env 檔案和 google_search_agent 資料夾,而 google_search_agent 資料夾包含 __init__.py 和 agent.py 檔案。

  2. app/google_search_agent/agent.py 檔案中新增下列程式碼。這個檔案會定義代理程式的邏輯。您必須定義 root_agent。在下列程式碼中,請使用支援的模型名稱更新 model 欄位。

    from google.adk.agents import Agent
    from google.adk.tools import google_search  # Import the tool
    
    root_agent = Agent(
      # A unique name for the agent.
      name="basic_search_agent",
      # The Large Language Model (LLM) that agent will use.
      # Please fill in the latest model id that supports live from
      # https://google.github.io/adk-docs/get-started/streaming/quickstart-streaming/#supported-models
      model="...",  # for example: model="gemini-live-2.5-flash-native-audio"
      # A short description of the agent's purpose.
      description="Agent to answer questions using Google Search.",
      # Instructions to set the agent's behavior.
      instruction="You are an expert researcher. You always stick to the facts.",
      # Add google_search tool to perform grounding with Google search.
      tools=[google_search]
    )
    
  3. app/google_search_agent/__init__.py 檔案中新增下列程式碼:

    from . import agent
    

設定平台

如要執行代理程式,請將其設定為使用 Google Cloud Gemini Enterprise Agent Platform。

  1. 開啟 app/ 目錄中的 .env 檔案。

  2. 在檔案中新增下列內容。將 PROJECT_ID 替換為 Google Cloud 專案 ID,並將 LOCATION 替換為 Google Cloud 位置。

    GOOGLE_CLOUD_PROJECT=PROJECT_ID
    GOOGLE_CLOUD_LOCATION=LOCATION
    GOOGLE_GENAI_USE_ENTERPRISE=True
    

使用開發 UI 執行代理

啟動開發使用者介面,與代理互動。

  1. 將目前目錄變更為 app

    cd app
    
  2. 設定 SSL_CERT_FILE 環境變數。語音和視訊測試需要執行這個步驟。

    macOS/Linux

    export SSL_CERT_FILE=$(python -m certifi)
        

    Windows

    $env:SSL_CERT_FILE = (python -m certifi)
        
  3. 執行開發人員 UI。

    adk web
    
  4. 開啟終端機中提供的網址,通常是 http://localhost:8000http://127.0.0.1:8000

  5. 選取「google_search_agent」。

下圖說明使用者輸入內容如何傳送至代理程式、代理程式如何使用 Google 搜尋工具,以及代理程式如何傳回回覆:

這張圖表顯示使用者輸入內容傳送至代理程式,代理程式使用 Google 搜尋工具取得資訊,然後將回應傳回給使用者。

與代理程式互動

啟動開發人員 UI 後,即可透過文字、語音或影片與代理互動。

使用文字輸入

在 UI 中輸入下列提示,測試代理的文字回覆。 代理會使用 google_search 工具取得最新資訊,以回答這些問題。

  • 紐約的天氣如何?
  • 紐約現在幾點?
  • 巴黎的天氣如何?
  • 巴黎現在幾點?

使用語音和視訊輸入

如要使用語音輸入功能,請重新載入網頁瀏覽器,然後按一下麥克風按鈕。提出問題,即時獲得解答。

如要使用視訊輸入,請重新載入網路瀏覽器,然後按一下攝影機按鈕。提出問題,例如「你看到什麼?」,代理程式會根據影片輸入內容描述所見內容。

停止開發人員 UI

如要停止 adk web 工具,請在執行該工具的終端機中按下 Ctrl+C

後續步驟