Gemini の機能を構成する

このドキュメントでは、Gemini Live API を使用する際に Gemini モデルのさまざまな機能を構成する方法について説明します。関数呼び出しやグラウンディングなどのツールの使用、アフェクティブ ダイアログやプロアクティブ音声などのネイティブ音声機能を構成できます。

ツールの使用を構成する

さまざまなツールが Gemini Live API 対応モデルのさまざまなバージョンと互換性があります。次に例を示します。

返されたレスポンスで使用する特定のツールを有効にするには、モデルを初期化するときに tools リストにツールの名前を含めます。以降のセクションでは、コードで各組み込みツールを使用する方法の例を示します。

関数呼び出し

モデルが管理する外部システムまたは API と やり取りする場合は、関数呼び出しを使用します。データベースの確認、メールの送信、カスタム API とのやり取りなどのタスクに使用します。

モデルは関数呼び出しを生成し、アプリケーションはコードを実行して結果をモデルに返します。

すべての関数は、LiveConnectConfig メッセージの一部としてツール定義を送信することで、セッションの開始時に宣言する必要があります。

関数呼び出しを有効にするには、セットアップ メッセージの tools リストに function_declarations を含めます。

Python

import asyncio

from google import genai
from google.genai.types import (
    Content,
    LiveConnectConfig,
    Part,
)

# Initialize the client.
client = genai.Client(
    vertexai=True,
    project="GOOGLE_CLOUD_PROJECT",  # Replace with your project ID
    location="LOCATION",  # Replace with your location
)

MODEL_ID = "gemini-live-2.5-flash-native-audio"


def get_current_weather(location: str) -> str:
    """Example method. Returns the current weather.

    Args:
        location: The city and state, e.g. San Francisco, CA
    """
    weather_map: dict[str, str] = {
        "Boston, MA": "snowing",
        "San Francisco, CA": "foggy",
        "Seattle, WA": "raining",
        "Austin, TX": "hot",
        "Chicago, IL": "windy",
    }
    return weather_map.get(location, "unknown")


async def main():
    config = LiveConnectConfig(
        response_modalities=["AUDIO"],
        tools=[get_current_weather],
    )

    async with client.aio.live.connect(
        model=MODEL_ID,
        config=config,
    ) as session:
        text_input = "Get the current weather in Boston."
        print(f"Input: {text_input}")

        await session.send_client_content(
            turns=Content(role="user", parts=[Part(text=text_input)])
        )

        async for message in session.receive():
            if message.tool_call:
                function_responses = []
                for function_call in message.tool_call.function_calls:
                    print(f"FunctionCall > {function_call}")
                    # Execute the tool and send the response back to the model.
                    result = get_current_weather(**function_call.args)
                    function_responses.append(
                        {
                            "name": function_call.name,
                            "response": {"result": result},
                            "id": function_call.id,
                        }
                    )
                if function_responses:
                    await session.send_tool_response(function_responses=function_responses)


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

システム指示で関数呼び出しを使用する例については、ベスト プラクティスの例をご覧ください。

モデルが検証可能な情報源に回答を固定することで、より正確で事実に基づいた回答を提供できるようにする場合は、Google 検索によるグラウンディングを使用します。ウェブ検索などのタスクに使用します。

関数呼び出しとは異なり、サーバーサイド統合では情報の取得が自動的に処理されます。

Google 検索によるグラウンディングを有効にするには、セットアップ メッセージの tools リストに google_search を含めます。

Python

import asyncio

from google import genai
from google.genai.types import (
    Content,
    LiveConnectConfig,
    Part,
)

# Initialize the client.
client = genai.Client(
    vertexai=True,
    project="GOOGLE_CLOUD_PROJECT",  # Replace with your project ID
    location="LOCATION",  # Replace with your location
)

MODEL_ID = "gemini-live-2.5-flash-native-audio"


async def main():
    config = LiveConnectConfig(
        response_modalities=["AUDIO"],
        tools=[{"google_search": {}}],
    )

    async with client.aio.live.connect(
        model=MODEL_ID,
        config=config,
    ) as session:
        text_input = "What is the current weather in Toronto, Canada?"
        print(f"Input: {text_input}")

        await session.send_client_content(
            turns=Content(role="user", parts=[Part(text=text_input)])
        )

        async for message in session.receive():
            # Consume the messages from the model.
            # In native audio, the model response is in audio format.
            pass


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

Vertex AI RAG Engine によるグラウンディング

Vertex AI RAG Engine を Live API と組み合わせて使用して、コンテキストのグラウンディング、保存、取得を行うことができます。ドキュメント コーパスから情報を取得するなどのタスクに使用します。Google 検索によるグラウンディングと同様に、RAG グラウンディングはサーバーサイドで処理され、指定したコーパスから自動的に情報を取得します。

Python

import asyncio

from google import genai
from google.genai.types import (
    Content,
    LiveConnectConfig,
    Part,
    Retrieval,
    Tool,
    VertexRagStore,
    VertexRagStoreRagResource,
)

# Initialize the client.
client = genai.Client(
    vertexai=True,
    project="GOOGLE_CLOUD_PROJECT",  # Replace with your project ID
    location="LOCATION",  # Replace with your location
)

MODEL_ID = "gemini-live-2.5-flash-native-audio"


async def main():
    rag_store = VertexRagStore(
        rag_resources=[
            VertexRagStoreRagResource(
                rag_corpus="RESOURCE_NAME"  # Replace with your corpus resource name
            )
        ],
        # Set `store_context` to true to allow Live API sink context into your memory corpus.
        store_context=True,
    )

    config = LiveConnectConfig(
        response_modalities=["AUDIO"],
        tools=[Tool(retrieval=Retrieval(vertex_rag_store=rag_store))],
    )

    async with client.aio.live.connect(
        model=MODEL_ID,
        config=config,
    ) as session:
        text_input = "YOUR_TEXT_INPUT"
        print(f"Input: {text_input}")

        await session.send_client_content(
            turns=Content(role="user", parts=[Part(text=text_input)])
        )

        async for message in session.receive():
            # Consume the messages from the model.
            # In native audio, the model response is in audio format.
            pass


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

詳細については、Gemini Live API で Vertex AI RAG Engine を使用するをご覧ください。

ネイティブ オーディオ機能を構成する

ネイティブ オーディオ機能を備えたモデルは、次の機能をサポートしています。

アフェクティブ ダイアログを構成する

アフェクティブ ダイアログが有効になっている場合、モデルはユーザーの口調や感情表現に基づいて理解し、応答しようとします。

アフェクティブ ダイアログを有効にするには、セットアップ メッセージで enable_affective_dialogtrue に設定します。

Python

config = LiveConnectConfig(
    response_modalities=["AUDIO"],
    enable_affective_dialog=True,
)
  

プロアクティブ音声を構成する

プロアクティブ音声を使用すると、モデルが応答するタイミングを制御できます。たとえば、Gemini に、質問されたときや特定のトピックが議論されたときにのみ応答するようリクエストできます。プロアクティブ音声の動画デモについては、Gemini LiveAPI ネイティブ オーディオ プレビューをご覧ください。

プロアクティブ音声を有効にするには、セットアップ メッセージの proactivity フィールドを構成し、proactive_audiotrue に設定します。

Python

config = LiveConnectConfig(
    response_modalities=["AUDIO"],
    proactivity=ProactivityConfig(proactive_audio=True),
)
  

会話の例

たとえば、料理について Gemini と会話する例を次に示します。

Prompt: "You are an AI assistant in Italian cooking; only chime in when the topic is about Italian cooking."

Speaker A: "I really love cooking!" (No response from Gemini.)

Speaker B: "Oh yes, me too! My favorite is French cuisine." (No response from
Gemini.)

Speaker A: "I really like Italian food; do you know how to make a pizza?"

(Italian cooking topic will trigger response from Gemini.)
Gemini Live API: "I'd be happy to help! Here's a recipe for a pizza."

一般的なユースケース

プロアクティブ音声を使用すると、Gemini は次のように動作します。

  • 最小限のレイテンシで応答する: ユーザーが話し終えた後に Gemini が応答するため、中断が減り、中断が発生した場合でも Gemini が文脈を見失わないようにできます。
  • 中断を回避する: プロアクティブ音声を使用すると、Gemini が周囲の雑音や外部の会話で中断されるのを防ぎ、会話中に外部の会話が聞こえてきた場合に Gemini が応答しないようにします。
  • 割り込みを処理する: ユーザーが Gemini の回答中に割り込む必要がある場合、プロアクティブ音声を使用すると、ユーザーが「えー」や「あー」などのつなぎ言葉を使用するよりも、Gemini が適切にバックチャネル(適切な割り込みが処理される)を処理しやすくなります。
  • 音声を一緒に聴く: Gemini は、発言者の音声ではない音声ファイルを一緒に聴き、会話の後半でその音声ファイルに関する質問に後から答えることができます。

課金

Gemini が会話をリッスンしている間は、入力音声トークンが課金されます。

出力音声トークンについては、Gemini が応答した場合にのみ課金されます。Gemini が応答しない場合や無音状態が続く場合、出力音声トークンに対する課金は発生しません。

詳細については、Gemini Enterprise Agent Platform の料金をご覧ください。

次のステップ

Gemini Live API の使用について詳しくは、以下をご覧ください。