使用 Live API 進行互動式對話

Live API 可讓您與 Gemini 進行低延遲的雙向語音和視訊互動。

本指南說明如何設定雙向互動式對話、調整音訊設定、管理工作階段等。

支援的模型

您可以在下列機型上使用 Live API:

模型版本 可用程度
gemini-live-2.5-flash 私人搶先體驗版*
gemini-live-2.5-flash-preview-native-audio 公開預先發布版

* 請與 Google 帳戶團隊代表聯絡,要求存取權。

發起對話

控制台

  1. 開啟 Vertex AI Studio > Stream realtime
  2. 按一下「開始工作階段」即可展開對話。

如要結束工作階段,請按一下「停止工作階段」

Python

如要啟用即時互動式對話,請在可存取麥克風和喇叭的本機電腦上執行下列範例 (不是 Colab 筆記本)。這個範例會設定與 API 的對話,讓您傳送音訊提示並接收音訊回覆:

"""
# Installation
# on linux
sudo apt-get install portaudio19-dev

# on mac
brew install portaudio

python3 -m venv env
source env/bin/activate
pip install google-genai
"""

import asyncio
import pyaudio
from google import genai
from google.genai import types

CHUNK=4200
FORMAT=pyaudio.paInt16
CHANNELS=1
RECORD_SECONDS=5
MODEL = 'gemini-live-2.5-flash'
INPUT_RATE=16000
OUTPUT_RATE=24000

client = genai.Client(
    vertexai=True,
    project=GOOGLE_CLOUD_PROJECT,
    location=GOOGLE_CLOUD_LOCATION,
)
config = {
    "response_modalities": ["AUDIO"],
    "input_audio_transcription": {},  # Configure input transcription
    "output_audio_transcription": {},  # Configure output transcription
}

async def main():
    print(MODEL)
    p = pyaudio.PyAudio()
    async with client.aio.live.connect(model=MODEL, config=config) as session:
        #exit()
        async def send():
            stream = p.open(
                format=FORMAT, channels=CHANNELS, rate=INPUT_RATE, input=True, frames_per_buffer=CHUNK)
            while True:
                frame = stream.read(CHUNK)
                await session.send(input={"data": frame, "mime_type": "audio/pcm"})
                await asyncio.sleep(10**-12)
        async def receive():
            output_stream = p.open(
                format=FORMAT, channels=CHANNELS, rate=OUTPUT_RATE, output=True, frames_per_buffer=CHUNK)
            async for message in session.receive():
                if message.server_content.input_transcription:
                  print(message.server_content.model_dump(mode="json", exclude_none=True))
                if message.server_content.output_transcription:
                  print(message.server_content.model_dump(mode="json", exclude_none=True))
                if message.server_content.model_turn:
                    for part in message.server_content.model_turn.parts:
                        if part.inline_data.data:
                            audio_data=part.inline_data.data
                            output_stream.write(audio_data)
                            await asyncio.sleep(10**-12)
        send_task = asyncio.create_task(send())
        receive_task = asyncio.create_task(receive())
        await asyncio.gather(send_task, receive_task)

asyncio.run(main())
      

Python

與 API 進行對話,傳送文字提示並接收語音回覆:

# Set model generation_config
CONFIG = {"response_modalities": ["AUDIO"]}

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {bearer_token[0]}",
}

async def main() -> None:
    # Connect to the server
    async with connect(SERVICE_URL, additional_headers=headers) as ws:

        # Setup the session
        async def setup() -> None:
            await ws.send(
                json.dumps(
                    {
                        "setup": {
                            "model": "gemini-live-2.5-flash",
                            "generation_config": CONFIG,
                        }
                    }
                )
            )

            # Receive setup response
            raw_response = await ws.recv(decode=False)
            setup_response = json.loads(raw_response.decode("ascii"))
            print(f"Connected: {setup_response}")
            return

        # Send text message
        async def send() -> bool:
            text_input = input("Input > ")
            if text_input.lower() in ("q", "quit", "exit"):
                return False

            msg = {
                "client_content": {
                    "turns": [{"role": "user", "parts": [{"text": text_input}]}],
                    "turn_complete": True,
                }
            }

            await ws.send(json.dumps(msg))
            return True

        # Receive server response
        async def receive() -> None:
            responses = []

            # Receive chucks of server response
            async for raw_response in ws:
                response = json.loads(raw_response.decode())
                server_content = response.pop("serverContent", None)
                if server_content is None:
                    break

                model_turn = server_content.pop("modelTurn", None)
                if model_turn is not None:
                    parts = model_turn.pop("parts", None)
                    if parts is not None:
                        for part in parts:
                            pcm_data = base64.b64decode(part["inlineData"]["data"])
                            responses.append(np.frombuffer(pcm_data, dtype=np.int16))

                # End of turn
                turn_complete = server_content.pop("turnComplete", None)
                if turn_complete:
                    break

            # Play the returned audio message
            display(Markdown("**Response >**"))
            display(Audio(np.concatenate(responses), rate=24000, autoplay=True))
            return

        await setup()

        while True:
            if not await send():
                break
            await receive()
      

發起對話、輸入提示,或輸入 qquitexit 即可結束。

await main()
      

變更語言和語音設定

Live API 使用 Chirp 3,支援以各種 HD 語音和語言合成語音回應。如需完整清單和各語音的試聽,請參閱「Chirp 3:HD 語音」。

如要設定回覆語音和語言,請按照下列步驟操作:

控制台

  1. 開啟 Vertex AI Studio > Stream realtime
  2. 在「輸出」展開器中,從「語音」下拉式選單選取語音。
  3. 在同一個展開器中,從「語言」下拉式選單選取語言。
  4. 按一下「 開始工作階段」即可開始工作階段。

Python

config = LiveConnectConfig(
    response_modalities=["AUDIO"],
    speech_config=SpeechConfig(
        voice_config=VoiceConfig(
            prebuilt_voice_config=PrebuiltVoiceConfig(
                voice_name=voice_name,
            )
        ),
        language_code="en-US",
    ),
)
      

變更語音活動偵測設定

語音活動偵測 (VAD) 可讓模型辨識使用者何時說話。這對建立自然對話至關重要,因為使用者可以隨時中斷模型。

模型會對連續音訊輸入串流自動執行語音活動偵測 (VAD)。您可以使用設定訊息realtimeInputConfig.automaticActivityDetection 欄位設定 VAD。當 VAD 偵測到中斷時,系統會取消並捨棄正在進行的生成作業。工作階段記錄只會保留已傳送給用戶端的資訊。伺服器隨後會傳送訊息,回報中斷情形。

如果音訊串流暫停超過一秒 (例如使用者關閉麥克風),請傳送 audioStreamEnd 事件來清除所有快取的音訊。用戶端隨時可以繼續傳送音訊資料。

或者,您也可以在設定訊息中將 realtimeInputConfig.automaticActivityDetection.disabled 設為 true,停用自動 VAD。完成這項設定後,用戶端就會偵測使用者語音,並在適當時間傳送 activityStartactivityEnd 訊息。系統不會傳送 audioStreamEnd。中斷會以 activityEnd 標示。

Python

config = LiveConnectConfig(
    response_modalities=["TEXT"],
    realtime_input_config=RealtimeInputConfig(
        automatic_activity_detection=AutomaticActivityDetection(
            disabled=False,  # default
            start_of_speech_sensitivity=StartSensitivity.START_SENSITIVITY_LOW, # Either START_SENSITIVITY_LOW or START_SENSITIVITY_HIGH
            end_of_speech_sensitivity=EndSensitivity.END_SENSITIVITY_LOW, # Either END_SENSITIVITY_LOW or END_SENSITIVITY_HIGH
            prefix_padding_ms=20,
            silence_duration_ms=100,
        )
    ),
)

async with client.aio.live.connect(
    model=MODEL_ID,
    config=config,
) as session:
    audio_bytes = Path("sample.pcm").read_bytes()

    await session.send_realtime_input(
        media=Blob(data=audio_bytes, mime_type="audio/pcm;rate=16000")
    )

    # if stream gets paused, send:
    # await session.send_realtime_input(audio_stream_end=True)

    response = []
    async for message in session.receive():
        if message.server_content.interrupted is True:
            # The model generation was interrupted
            response.append("The session was interrupted")

        if message.text:
            response.append(message.text)

    display(Markdown(f"**Response >** {''.join(response)}"))
      

延長工作階段

對話工作階段的預設時間上限為 10 分鐘。工作階段結束前 60 秒,系統會向用戶端傳送goAway 通知 (BidiGenerateContentServerMessage.goAway)。

您可以使用 Gen AI SDK,以 10 分鐘為單位延長工作階段長度。工作階段的延長次數沒有上限。如需範例,請參閱「啟用及停用工作階段續傳功能」。

脈絡窗口

Live API 內容視窗用於儲存即時串流資料 (音訊每秒 25 個符記 (TPS),影片每秒 258 個符記) 和其他內容,包括文字輸入內容和模型輸出內容。

如果脈絡視窗超過長度上限 (在 Vertex AI Studio 中使用「內容大小上限」滑桿設定,或在 API 中使用 trigger_tokens),系統會使用脈絡視窗壓縮功能截斷最舊的輪次,避免工作階段突然終止。當脈絡窗口達到最大長度 (在 Vertex AI Studio 中使用「目標脈絡大小」滑桿設定,或在 API 中使用 target_tokens 設定) 時,系統會觸發脈絡窗口壓縮,並刪除對話中最舊的部分,直到權杖總數降回目標大小為止。

舉例來說,如果您的脈絡長度上限設為 32000 個權杖,目標大小設為 16000 個權杖:

  1. 第 1 輪:對話開始。在本範例中,要求會使用 12,000 個權杖。
    • 脈絡總長度:12,000 個權杖
  2. 第 2 輪:你提出其他要求。這項要求會再使用 12,000 個權杖。
    • 內容大小總計:24,000 個權杖
  3. 第 3 輪:你提出另一項要求。這項要求會使用 14,000 個權杖。
    • 背景資訊大小總計:38,000 個權杖

由於總脈絡大小現在超過 32,000 個權杖的上限,因此系統會觸發脈絡窗口壓縮。系統會回到對話開頭,開始刪除舊的對話輪次,直到權杖總大小小於 16,000 個權杖目標為止:

  • 系統會刪除「Turn 1」 (12,000 個權杖)。現在總共是 26,000 個權杖,仍高於 16,000 個權杖的目標。
  • 這會刪除「Turn 2」 (12,000 個權杖)。現在總共是 14,000 個權杖。

最終結果是只有「回合 3」會保留在有效記憶體中,對話會從該處繼續。

背景資訊長度和目標大小的長度下限和上限如下:

設定 (API 標記) 最小值 最大值
背景資訊長度上限 (trigger_tokens) 5,000 128,000
脈絡長度目標 (target_tokens) 0 128,000

如何設定脈絡窗口:

控制台

  1. 開啟 Vertex AI Studio > Stream realtime
  2. 按一下開啟「進階」選單。
  3. 在「工作階段內容」部分,使用「內容大小上限」滑桿,將內容大小設為介於 5,000 到 128,000 之間的值。
  4. (選用) 在同一區段中,使用「目標內容大小」滑桿,將目標大小設為介於 0 到 128,000 之間的值。

Python

在設定訊息中設定 context_window_compression.trigger_tokenscontext_window_compression.sliding_window.target_tokens 欄位:

config = types.LiveConnectConfig(
      temperature=0.7,
      response_modalities=['TEXT'],
      system_instruction=types.Content(
          parts=[types.Part(text='test instruction')], role='user'
      ),
      context_window_compression=types.ContextWindowCompressionConfig(
          trigger_tokens=1000,
          sliding_window=types.SlidingWindow(target_tokens=10),
      ),
  )
      

並行工作階段

每個專案最多可有 5,000 個並行工作階段。

在工作階段期間更新系統指示

透過 Live API,您可以在工作階段進行期間更新系統指令。你可以使用這項功能調整模型的回覆內容,例如變更回覆語言或修改語氣。

如要在工作階段中更新系統指令,可以傳送 system 角色的文字內容。更新後的系統指令會在剩餘的工作階段中生效。

Python

session.send_client_content(
      turns=types.Content(
          role="system", parts=[types.Part(text="new system instruction")]
      ),
      turn_complete=False
  )
      

啟用及停用工作階段續傳功能

工作階段續傳功能可讓您在 24 小時內重新連線至先前的工作階段。 具體做法是儲存快取資料,包括文字、影片、音訊提示和模型輸出內容。系統會對這項快取資料強制執行專案層級的隱私權設定。

工作階段續傳功能預設為停用。

如要啟用繼續工作階段功能,請設定 BidiGenerateContentSetup 訊息的 sessionResumption 欄位。啟用後,伺服器會定期擷取目前快取工作階段內容的快照,並儲存在內部儲存空間。

成功擷取快照後,系統會傳回 resumptionUpdate,其中包含可記錄的控制代碼 ID,供您日後從快照繼續工作階段。

以下範例說明如何啟用工作階段恢復功能及擷取控制代碼 ID:

Python

import asyncio
from google import genai
from google.genai import types

client = genai.Client(
    vertexai=True,
    project=GOOGLE_CLOUD_PROJECT,
    location=GOOGLE_CLOUD_LOCATION,
)
model = "gemini-live-2.5-flash"

async def main():
    print(f"Connecting to the service with handle {previous_session_handle}...")
    async with client.aio.live.connect(
        model=model,
        config=types.LiveConnectConfig(
            response_modalities=["AUDIO"],
            session_resumption=types.SessionResumptionConfig(
                # The handle of the session to resume is passed here,
                # or else None to start a new session.
                handle=previous_session_handle
            ),
        ),
    ) as session:
        while True:
            await session.send_client_content(
                turns=types.Content(
                    role="user", parts=[types.Part(text="Hello world!")]
                )
            )
            async for message in session.receive():
                # Periodically, the server will send update messages that may
                # contain a handle for the current state of the session.
                if message.session_resumption_update:
                    update = message.session_resumption_update
                    if update.resumable and update.new_handle:
                        # The handle should be retained and linked to the session.
                        return update.new_handle

                # For the purposes of this example, placeholder input is continually fed
                # to the model. In non-sample code, the model inputs would come from
                # the user.
                if message.server_content and message.server_content.turn_complete:
                    break

if __name__ == "__main__":
    asyncio.run(main())
      

如要順暢地繼續工作階段,請啟用透明模式

Python

types.LiveConnectConfig(
            response_modalities=["AUDIO"],
            session_resumption=types.SessionResumptionConfig(
                transparent=True,
    ),
)
      

啟用透明模式後,系統會明確傳回與內容快照相應的用戶端訊息索引。這有助於識別從續傳控制代碼恢復工作階段時,需要再次傳送的用戶端訊息。

更多資訊

如要進一步瞭解如何使用 Live API,請參閱: