コンピュータの使用

Gemini 2.5 Computer Use Preview モデルとツールを使用すると、ブラウザ制御エージェントを構築して、タスクの操作と自動化を行うことができます。スクリーンショットを使用して、コンピュータ使用モデルはコンピュータ画面を「認識」し、マウスのクリックやキーボード入力などの特定の UI アクションを生成して「操作」できます。関数呼び出しと同様に、クライアントサイドのアプリケーション コードを記述して、コンピュータの使用アクションを受信して実行する必要があります。

パソコンの使用では、次のエージェントを構築できます。

  • ウェブサイトでのデータ入力やフォームへの記入など、繰り返し発生する作業を自動化します。
  • ウェブ アプリケーションとユーザーフローの自動テストを実行する
  • さまざまなウェブサイトで調査を行う(e コマース サイトから商品情報、価格、レビューを収集して購入の判断に役立てるなど)

Gemini Computer Use モデルをテストする最も簡単な方法は、リファレンス実装または Browserbase デモ環境を使用することです。

コンピュータ使用の仕組み

コンピュータの使用モデルを使用してブラウザ制御エージェントを構築するには、次の処理を行うエージェント ループを実装します。

  1. モデルにリクエストを送信する

    • API リクエストに、Computer Use ツールと、必要に応じてカスタムのユーザー定義関数または除外関数を追加します。
    • ユーザーのリクエストと、GUI の現在の状態を表すスクリーンショットを使用して、Computer Use モデルにプロンプトを表示します。
  2. モデル レスポンスを受信する

    • コンピュータ使用モデルは、ユーザーのリクエストとスクリーンショットを分析し、UI アクションを表す function_call(「click at coordinate (x,y)」または「type 'text'」)。コンピュータ使用モデルでサポートされているすべての UI アクションの説明については、サポートされているアクションをご覧ください。
    • API レスポンスには、モデルの提案されたアクションをチェックする内部安全システムからの safety_decision が含まれる場合もあります。この safety_decision は、アクションを次のように分類します。
      • Regular / allowed: アクションは安全であると見なされます。これは、safety_decision が存在しないことでも表されます。
      • 確認が必要(require_confirmation): モデルが、リスクを伴う可能性のあるアクション(「Cookie バナーに同意する」をクリックするなど)を実行しようとしています。
  3. 受信したアクションを実行する

    • クライアントサイド コードは function_call と、付随する safety_decision を受け取ります。
      • 通常 / 許可: safety_decision が通常 / 許可を示している場合(または safety_decision が存在しない場合)、クライアントサイド コードはターゲット環境(ウェブブラウザなど)で指定された function_call を実行できます。
      • 確認が必要: safety_decision が確認が必要であることを示している場合、アプリケーションは function_call を実行する前に、エンドユーザーに確認を求める必要があります。お客様が確認した場合は、アクションの実行に進みます。ユーザーが拒否した場合は、アクションを実行しないでください。
  4. 新しい環境の状態をキャプチャする

    • アクションが実行されると、クライアントは GUI の新しいスクリーンショットと現在の URL をキャプチャし、function_response の一部としてコンピュータ使用モデルに送信します。
    • アクションが安全性システムによってブロックされた場合や、ユーザーによって確認が拒否された場合、アプリはモデルに別の形式のフィードバックを送信するか、インタラクションを終了することがあります。

このプロセスは、新しいスクリーンショットと進行中の目標を使用して次のアクションを提案する Computer Use モデルで、ステップ 2 から繰り返されます。このループは、タスクが完了するか、エラーが発生するか、プロセスが終了する(「ブロック」の安全応答やユーザーの決定などによる)まで続きます。

コンピュータ使用の概要

コンピュータの使用状況を実装する方法

コンピュータの使用モデルとツールを使用してビルドする前に、次の設定を行う必要があります。

  • 安全な実行環境: 安全上の理由から、安全で制御された環境(サンドボックス化された仮想マシン、コンテナ、権限が制限された専用のブラウザ プロファイルなど)で Computer Use エージェントを実行する必要があります。
  • クライアントサイドのアクション ハンドラ: モデルによって生成されたアクションを実行し、各アクションの後に環境のスクリーンショットをキャプチャするクライアントサイド ロジックを実装する必要があります。

このセクションの例では、実行環境としてブラウザを使用し、クライアントサイドのアクション ハンドラとして Playwright を使用します。これらのサンプルを実行するには、必要な依存関係をインストールして、Playwright ブラウザ インスタンスを初期化する必要があります。

Playwright をインストールする

    pip install google-genai playwright
    playwright install chromium
    

Playwright ブラウザ インスタンスを初期化する

    from playwright.sync_api import sync_playwright

    # 1. Configure screen dimensions for the target environment
    SCREEN_WIDTH = 1440
    SCREEN_HEIGHT = 900

    # 2. Start the Playwright browser
    # In production, utilize a sandboxed environment.
    playwright = sync_playwright().start()
    # Set headless=False to see the actions performed on your screen
    browser = playwright.chromium.launch(headless=False)

    # 3. Create a context and page with the specified dimensions
    context = browser.new_context(
        viewport={"width": SCREEN_WIDTH, "height": SCREEN_HEIGHT}
    )
    page = context.new_page()

    # 4. Navigate to an initial page to start the task
    page.goto("https://www.google.com")

    # The 'page', 'SCREEN_WIDTH', and 'SCREEN_HEIGHT' variables
    # will be used in the steps below.
    

Android 環境に拡張するためのサンプルコードは、カスタム ユーザー定義関数の使用セクションに記載されています。

1. モデルにリクエストを送信する

API リクエストに Computer Use ツールを追加し、ユーザーの目標と GUI の最初のスクリーンショットを含むプロンプトを Computer Use モデルに送信します。Gemini Computer Use モデル gemini-2.5-computer-use-preview-10-2025 を使用する必要があります。別のモデルで Computer Use ツールを使用しようとすると、エラーが発生します。

必要に応じて、次のパラメータを追加することもできます。

  • 除外するアクション: モデルに実行させたくないアクションがサポートされている UI アクションのリストにある場合は、これらのアクションを excluded_predefined_functions として指定します。
  • ユーザー定義関数: コンピュータの使用状況ツールに加えて、カスタムのユーザー定義関数を含めることもできます。

リクエストを発行する際に表示サイズを指定する必要はありません。モデルは、画面の高さと幅に合わせてスケーリングされたピクセル座標を予測します。

Python

from google import genai
from google.genai import types
from google.genai.types import Content, Part

client = genai.Client()

# Specify predefined functions to exclude (optional)
excluded_functions = ["drag_and_drop"]

generate_content_config = genai.types.GenerateContentConfig(
    tools=[
        # 1. Computer Use tool with browser environment
        types.Tool(
            computer_use=types.ComputerUse(
                environment=types.Environment.ENVIRONMENT_BROWSER,
                # Optional: Exclude specific predefined functions
                excluded_predefined_functions=excluded_functions
                )
              ),
        # 2. Optional: Custom user-defined functions
        #types.Tool(
          # function_declarations=custom_functions
          #   )
          ],
  )

# Create the content with user message
contents=[
    Content(
        role="user",
        parts=[
            Part(text="Search for highly rated smart fridges with touchscreen, 2 doors, around 25 cu ft, priced below 4000 dollars on Google Shopping. Create a bulleted list of the 3 cheapest options in the format of name, description, price in an easy-to-read layout."),
            # Optional: include a screenshot of the initial state
            #Part.from_bytes(
                #data=screenshot_image_bytes,
                #mime_type='image/png',
            #),
        ],
    )
]

# Generate content with the configured settings
response = client.models.generate_content(
    model='gemini-2.5-computer-use-preview-10-2025',
    contents=contents,
    config=generate_content_config,
)

# Print the response output
print(response)

カスタム関数の例については、カスタムのユーザー定義関数を使用するをご覧ください。

2. モデルのレスポンスを受信する

タスクを完了するために UI アクションが必要であると判断した場合、コンピュータ使用モデルは 1 つ以上の FunctionCalls で応答します。コンピュータの使用は並列関数呼び出しをサポートしています。つまり、モデルは 1 回のターンで複数のアクションを返すことができます。

モデル レスポンスの例を次に示します。

{
  "content": {
    "parts": [
      {
        "text": "I will type the search query into the search bar. The search bar is in the center of the page."
      },
      {
        "function_call": {
          "name": "type_text_at",
          "args": {
            "x": 371,
            "y": 470,
            "text": "highly rated smart fridges with touchscreen, 2 doors, around 25 cu ft, priced below 4000 dollars on Google Shopping",
            "press_enter": true
          }
        }
      }
    ]
  }
}

3. 受信したアクションを実行する

アプリケーション コードは、モデルのレスポンスを解析し、アクションを実行して、結果を収集する必要があります。

次のコード例では、Computer Use モデルのレスポンスから関数呼び出しを抽出し、Playwright で実行できるアクションに変換します。モデルは入力画像のサイズに関係なく正規化された座標(0 ~ 999)を出力するため、変換ステップの一部として、これらの正規化された座標を実際のピクセル値に戻します。

パソコンの使用モデルで使用する推奨画面サイズは(1440, 900)です。モデルは任意の解像度で動作しますが、結果の品質に影響する可能性があります。

この例には、最も一般的な 3 つの UI アクション(open_web_browserclick_attype_text_at)の実装のみが含まれています。本番環境のユースケースでは、excluded_predefined_functions として明示的に追加しない限り、サポートされているアクション リストの他のすべての UI アクションを実装する必要があります。

Python

from typing import Any, List, Tuple
import time

def denormalize_x(x: int, screen_width: int) -> int:
    """Convert normalized x coordinate (0-1000) to actual pixel coordinate."""
    return int(x / 1000 * screen_width)

def denormalize_y(y: int, screen_height: int) -> int:
    """Convert normalized y coordinate (0-1000) to actual pixel coordinate."""
    return int(y / 1000 * screen_height)

def execute_function_calls(candidate, page, screen_width, screen_height):
    results = []
    function_calls = []
    for part in candidate.content.parts:
        if part.function_call:
            function_calls.append(part.function_call)

    for function_call in function_calls:
        action_result = {}
        fname = function_call.name
        args = function_call.args
        print(f"  -> Executing: {fname}")

        try:
            if fname == "open_web_browser":
                pass # Already open
            elif fname == "click_at":
                actual_x = denormalize_x(args["x"], screen_width)
                actual_y = denormalize_y(args["y"], screen_height)
                page.mouse.click(actual_x, actual_y)
            elif fname == "type_text_at":
                actual_x = denormalize_x(args["x"], screen_width)
                actual_y = denormalize_y(args["y"], screen_height)
                text = args["text"]
                press_enter = args.get("press_enter", False)

                page.mouse.click(actual_x, actual_y)
                # Simple clear (Command+A, Backspace for Mac)
                page.keyboard.press("Meta+A")
                page.keyboard.press("Backspace")
                page.keyboard.type(text)
                if press_enter:
                    page.keyboard.press("Enter")
            else:
                print(f"Warning: Unimplemented or custom function {fname}")

            # Wait for potential navigations/renders
            page.wait_for_load_state(timeout=5000)
            time.sleep(1)

        except Exception as e:
            print(f"Error executing {fname}: {e}")
            action_result = {"error": str(e)}

        results.append((fname, action_result))

    return results

# Execute function calls
candidate = response.candidates[0]
results = execute_function_calls(response.candidates[0], page, SCREEN_WIDTH, SCREEN_HEIGHT)

4. 新しい環境の状態をキャプチャする

アクションを実行したら、関数実行の結果をモデルに送り返します。モデルはこの情報を使用して次のアクションを生成します。複数のアクション(並列呼び出し)が実行された場合は、後続のユーザー ターンでそれぞれに対して FunctionResponse を送信する必要があります。

Python


def get_function_responses(page, results):
    screenshot_bytes = page.screenshot(type="png")
    current_url = page.url
    function_responses = []
    for name, result in results:
        response_data = {"url": current_url}
        response_data.update(result)
        function_responses.append(
            types.FunctionResponse(
                name=name,
                response=response_data,
                parts=[types.FunctionResponsePart(
                        inline_data=types.FunctionResponseBlob(
                            mime_type="image/png",
                            data=screenshot_bytes))
                ]
            )
        )
    return function_responses

# Capture state and return to model
function_responses = get_function_responses(page, results)
user_feedback_content = Content(
    role="user",
    parts=[Part(function_response=fr) for fr in function_responses])

# Append this feedback to the 'contents' history list for the next API call.
contents.append(user_feedback_content)

エージェント ループを構築する

複数ステップのインタラクションを有効にするには、コンピュータの使用を実装する方法のセクションの 4 つのステップをループにまとめます。モデルのレスポンスと関数レスポンスの両方を追加して、会話履歴を正しく管理してください。

このコードサンプルを実行するには、次の操作を行う必要があります。

Python


import time
from typing import Any, List, Tuple
from playwright.sync_api import sync_playwright

from google import genai
from google.genai import types
from google.genai.types import Content, Part

client = genai.Client()

# Constants for screen dimensions
SCREEN_WIDTH = 1440
SCREEN_HEIGHT = 900

# Setup Playwright
print("Initializing browser...")
playwright = sync_playwright().start()
browser = playwright.chromium.launch(headless=False)
context = browser.new_context(viewport={"width": SCREEN_WIDTH, "height": SCREEN_HEIGHT})
page = context.new_page()

# Define helper functions. Copy/paste from steps 3 and 4
# def denormalize_x(...)
# def denormalize_y(...)
# def execute_function_calls(...)
# def get_function_responses(...)

try:
    # Go to initial page
    page.goto("https://ai.google.dev/gemini-api/docs")

    # Configure the model (From Step 1)
    config = types.GenerateContentConfig(
        tools=[types.Tool(computer_use=types.ComputerUse(
            environment=types.Environment.ENVIRONMENT_BROWSER
        ))],
        thinking_config=types.ThinkingConfig(include_thoughts=True),
    )

    # Initialize history
    initial_screenshot = page.screenshot(type="png")
    USER_PROMPT = "Go to ai.google.dev/gemini-api/docs and search for pricing."
    print(f"Goal: {USER_PROMPT}")

    contents = [
        Content(role="user", parts=[
            Part(text=USER_PROMPT),
            Part.from_bytes(data=initial_screenshot, mime_type='image/png')
        ])
    ]

    # Agent Loop
    turn_limit = 5
    for i in range(turn_limit):
        print(f"\n--- Turn {i+1} ---")
        print("Thinking...")
        response = client.models.generate_content(
            model='gemini-2.5-computer-use-preview-10-2025',
            contents=contents,
            config=config,
        )

        candidate = response.candidates[0]
        contents.append(candidate.content)

        has_function_calls = any(part.function_call for part in candidate.content.parts)
        if not has_function_calls:
            text_response = " ".join([part.text for part in candidate.content.parts if part.text])
            print("Agent finished:", text_response)
            break

        print("Executing actions...")
        results = execute_function_calls(candidate, page, SCREEN_WIDTH, SCREEN_HEIGHT)

        print("Capturing state...")
        function_responses = get_function_responses(page, results)

        contents.append(
            Content(role="user", parts=[Part(function_response=fr) for fr in function_responses])
        )

finally:
    # Cleanup
    print("\nClosing browser...")
    browser.close()
    playwright.stop()

カスタムのユーザー定義関数を使用する

必要に応じて、リクエストにカスタム ユーザー定義関数を含めて、モデルの機能を拡張できます。次の例では、ブラウザ固有のアクションを除外しながら、open_applong_press_atgo_home などのカスタム ユーザー定義アクションを含めることで、モバイル ユースケース向けにコンピュータ使用モデルとツールを適応させています。このモデルは、標準の UI アクションとともにこれらのカスタム関数をインテリジェントに呼び出し、ブラウザ以外の環境でタスクを完了できます。

Python

from typing import Optional, Dict, Any

from google import genai
from google.genai import types
from google.genai.types import Content, Part

client = genai.Client()

SYSTEM_PROMPT = """You are operating an Android phone. Today's date is October 15, 2023, so ignore any other date provided.
* To provide an answer to the user, *do not use any tools* and output your answer on a separate line. IMPORTANT: Do not add any formatting or additional punctuation/text, just output the answer by itself after two empty lines.
* Make sure you scroll down to see everything before deciding something isn't available.
* You can open an app from anywhere. The icon doesn't have to currently be on screen.
* Unless explicitly told otherwise, make sure to save any changes you make.
* If text is cut off or incomplete, scroll or click into the element to get the full text before providing an answer.
* IMPORTANT: Complete the given task EXACTLY as stated. DO NOT make any assumptions that completing a similar task is correct.  If you can't find what you're looking for, SCROLL to find it.
* If you want to edit some text, ONLY USE THE `type` tool. Do not use the onscreen keyboard.
* Quick settings shouldn't be used to change settings. Use the Settings app instead.
* The given task may already be completed. If so, there is no need to do anything.
"""

def open_app(app_name: str, intent: Optional[str] = None) -> Dict[str, Any]:
    """Opens an app by name.

    Args:
        app_name: Name of the app to open (any string).
        intent: Optional deep-link or action to pass when launching, if the app supports it.

    Returns:
        JSON payload acknowledging the request (app name and optional intent).
    """
    return {"status": "requested_open", "app_name": app_name, "intent": intent}

def long_press_at(x: int, y: int) -> Dict[str, int]:
    """Long-press at a specific screen coordinate.

    Args:
        x: X coordinate (absolute), scaled to the device screen width (pixels).
        y: Y coordinate (absolute), scaled to the device screen height (pixels).

    Returns:
        Object with the coordinates pressed and the duration used.
    """
    return {"x": x, "y": y}

def go_home() -> Dict[str, str]:
    """Navigates to the device home screen.

    Returns:
        A small acknowledgment payload.
    """
    return {"status": "home_requested"}

#  Build function declarations
CUSTOM_FUNCTION_DECLARATIONS = [
    types.FunctionDeclaration.from_callable(client=client, callable=open_app),
    types.FunctionDeclaration.from_callable(client=client, callable=long_press_at),
    types.FunctionDeclaration.from_callable(client=client, callable=go_home),
]

#Exclude browser functions
EXCLUDED_PREDEFINED_FUNCTIONS = [
    "open_web_browser",
    "search",
    "navigate",
    "hover_at",
    "scroll_document",
    "go_forward",
    "key_combination",
    "drag_and_drop",
]

#Utility function to construct a GenerateContentConfig
def make_generate_content_config() -> genai.types.GenerateContentConfig:
    """Return a fixed GenerateContentConfig with Computer Use + custom functions."""
    return genai.types.GenerateContentConfig(
        system_instruction=SYSTEM_PROMPT,
        tools=[
            types.Tool(
                computer_use=types.ComputerUse(
                    environment=types.Environment.ENVIRONMENT_BROWSER,
                    excluded_predefined_functions=EXCLUDED_PREDEFINED_FUNCTIONS,
                )
            ),
            types.Tool(function_declarations=CUSTOM_FUNCTION_DECLARATIONS),
        ],
    )

# Create the content with user message
contents: list[Content] = [
    Content(
        role="user",
        parts=[
            # text instruction
            Part(text="Open Chrome, then long-press at 200,400."),
            # optional screenshot attachment
            Part.from_bytes(
                data=screenshot_image_bytes,
                mime_type="image/png",
            ),
        ],
    )
]

# Build your fixed config (from helper)
config = make_generate_content_config()

# Generate content with the configured settings
response = client.models.generate_content(
        model='gemini-2.5-computer-use-preview-10-2025',
        contents=contents,
        config=config,
    )

print(response)

サポートされている UI アクション

コンピュータの使用モデルは、FunctionCall を介して次の UI アクションをリクエストできます。クライアントサイド コードで、これらのアクションの実行ロジックを実装する必要があります。例については、リファレンス実装をご覧ください。

コマンド名 説明 引数(関数呼び出し内) 関数呼び出しの例
open_web_browser ウェブブラウザが開きます。 なし {"name": "open_web_browser", "args": {}}
wait_5_seconds 動的コンテンツの読み込みやアニメーションの完了を待つため、実行を 5 秒間一時停止します。 なし {"name": "wait_5_seconds", "args": {}}
go_back ブラウザの履歴の前のページに移動します。 なし {"name": "go_back", "args": {}}
go_forward ブラウザの履歴の次のページに移動します。 なし {"name": "go_forward", "args": {}}
search デフォルトの検索エンジンのホームページ(Google など)を検索してください。新しい検索タスクを開始するのに便利です。 なし {"name": "search", "args": {}}
navigate ブラウザを指定された URL に直接移動します。 url: str {"name": "navigate", "args": {"url": "https://www.wikipedia.org"}}
click_at ウェブページの特定の座標をクリックします。x 値と y 値は 1000x1000 のグリッドに基づいており、画面の寸法に合わせてスケーリングされます。 y: int(0 ~ 999)、x: int(0 ~ 999) {"name": "click_at", "args": {"y": 300, "x": 500}}
hover_at ウェブページの特定の座標にマウスを移動します。サブメニューを表示するのに役立ちます。x と y は 1000x1000 のグリッドに基づいています。 y: int(0 ~ 999)x: int(0 ~ 999) {"name": "hover_at", "args": {"y": 150, "x": 250}}
type_text_at 特定の座標にテキストを入力します。デフォルトでは、まずフィールドをクリアしてから入力後に Enter キーを押しますが、これらの動作は無効にできます。x と y は 1000x1000 のグリッドに基づいています。 y: int(0 ~ 999)、x: int(0 ~ 999)、text: str、press_enter: bool(省略可、デフォルトは True)、clear_before_typing: bool(省略可、デフォルトは True) {"name": "type_text_at", "args": {"y": 250, "x": 400, "text": "search query", "press_enter": false}}
key_combination 「Ctrl+C」や「Enter」などのキーまたはキーの組み合わせを押します。アクション(「Enter」キーによるフォームの送信など)やクリップボード操作のトリガーに役立ちます。 keys: str(例: 'enter'、'control+c')。 {"name": "key_combination", "args": {"keys": "Control+A"}}
scroll_document ウェブページ全体を「上」、「下」、「左」、「右」にスクロールします。 direction: str(「up」、「down」、「left」、「right」) {"name": "scroll_document", "args": {"direction": "down"}}
scroll_at 指定された要素または領域の座標(x, y)を、指定された方向に一定の大きさだけスクロールします。座標と大きさ(デフォルトは 800)は 1000x1000 のグリッドに基づいています。 y: int(0 ~ 999)、x: int(0 ~ 999)、direction: str("up"、"down"、"left"、"right")、magnitude: int(0 ~ 999、省略可、デフォルトは 800) {"name": "scroll_at", "args": {"y": 500, "x": 500, "direction": "down", "magnitude": 400}}
drag_and_drop 要素を開始座標(x, y)からドラッグし、宛先座標(destination_x, destination_y)にドロップします。すべての座標は 1000x1000 のグリッドに基づいています。 y: int(0 ~ 999)、x: int(0 ~ 999)、destination_y: int(0 ~ 999)、destination_x: int(0 ~ 999) {"name": "drag_and_drop", "args": {"y": 100, "x": 100, "destination_y": 500, "destination_x": 500}}

安全性とセキュリティ

安全性の判断を確認する

アクションによっては、モデルのレスポンスに、モデルの提案されたアクションをチェックする内部安全システムの safety_decision が含まれることもあります。

{
  "content": {
    "parts": [
      {
        "text": "I have evaluated step 2. It seems Google detected unusual traffic and is asking me to verify I'm not a robot. I need to click the 'I'm not a robot' checkbox located near the top left (y=98, x=95).",
      },
      {
        "function_call": {
          "name": "click_at",
          "args": {
            "x": 60,
            "y": 100,
            "safety_decision": {
              "explanation": "I have encountered a CAPTCHA challenge that requires interaction. I need you to complete the challenge by clicking the 'I'm not a robot' checkbox and any subsequent verification steps.",
              "decision": "require_confirmation"
            }
          }
        }
      }
    ]
  }
}

safety_decisionrequire_confirmation の場合は、アクションの実行に進む前に、エンドユーザーに確認を求める必要があります。利用規約に基づき、人間による確認のリクエストを回避することは許可されていません。

このコードサンプルでは、アクションを実行する前にエンドユーザーに確認を求めます。ユーザーがアクションを確認しない場合、ループは終了します。ユーザーがアクションを確認すると、アクションが実行され、safety_acknowledgement フィールドが True としてマークされます。

Python

import termcolor

def get_safety_confirmation(safety_decision):
    """Prompt user for confirmation when safety check is triggered."""
    termcolor.cprint("Safety service requires explicit confirmation!", color="red")
    print(safety_decision["explanation"])

    decision = ""
    while decision.lower() not in ("y", "n", "ye", "yes", "no"):
        decision = input("Do you wish to proceed? [Y]es/[N]o\n")

    if decision.lower() in ("n", "no"):
        return "TERMINATE"
    return "CONTINUE"

def execute_function_calls(candidate, page, screen_width, screen_height):

    # ... Extract function calls from response ...

    for function_call in function_calls:
        extra_fr_fields = {}

        # Check for safety decision
        if 'safety_decision' in function_call.args:
            decision = get_safety_confirmation(function_call.args['safety_decision'])
            if decision == "TERMINATE":
                print("Terminating agent loop")
                break
            extra_fr_fields["safety_acknowledgement"] = "true" # Safety acknowledgement

        # ... Execute function call and append to results ...

お客様が確認した場合は、FunctionResponse に安全に関する確認を含める必要があります。

Python

function_response_parts.append(
    FunctionResponse(
        name=name,
        response={"url": current_url,
                  **extra_fr_fields},  # Include safety acknowledgement
        parts=[
            types.FunctionResponsePart(
                inline_data=types.FunctionResponseBlob(
                    mime_type="image/png", data=screenshot
                )
             )
           ]
         )
       )

安全に使用するためのベスト プラクティス

Computer Use API は新しい API であり、デベロッパーが注意すべき新しいリスクがあります。

  • 信頼できないコンテンツと詐欺: モデルがユーザーの目標を達成しようとする際に、信頼できない情報源や画面上の指示に依存する可能性があります。たとえば、ユーザーの目標が Google Pixel を購入することであり、モデルが「アンケートに回答すると Google Pixel が無料」という詐欺に遭遇した場合、モデルがアンケートに回答する可能性があります。
  • 意図しないアクションがたまに発生する: モデルがユーザーの目標やウェブページの内容を誤って解釈し、間違ったボタンをクリックしたり、間違ったフォームに記入したりするなどの誤ったアクションを実行する可能性があります。これにより、タスクの失敗やデータ漏洩が発生する可能性があります。
  • ポリシー違反: API の機能が、Google のポリシー(生成 AI の使用禁止に関するポリシーGemini API 追加利用規約)に違反するアクティビティに意図的または意図せず向けられる可能性があります。これには、システムの完全性を損なう可能性のある行為、セキュリティを侵害する行為、セキュリティ対策を回避する行為、医療機器を制御する行為などが含まれます。

これらのリスクに対処するには、次の安全対策とベスト プラクティスを実装します。

  1. 人間参加型(HITL):

    • ユーザー確認を実装する: 安全性応答が require_confirmation を示している場合は、実行前にユーザー確認を実装する必要があります。コード例については、安全性の判断を確認するをご覧ください。
    • カスタムの安全性に関する指示を提供する: デベロッパーは、組み込みのユーザー確認チェックに加えて、独自の安全性ポリシーを適用するカスタムのシステム指示を任意で追加できます。これにより、特定のモデル アクションをブロックしたり、モデルが特定の不可逆的なアクションを実行する前にユーザーの確認を求めたりできます。モデルとやり取りする際に含めることができるカスタムの安全システム指示の例を次に示します。

      安全性に関する指示の例

      カスタムの安全性ルールをシステム指示として設定します。

          ## **RULE 1: Seek User Confirmation (USER_CONFIRMATION)**
      
          This is your first and most important check. If the next required action falls
          into any of the following categories, you MUST stop immediately, and seek the
          user's explicit permission.
      
          **Procedure for Seeking Confirmation:**  * **For Consequential Actions:**
          Perform all preparatory steps (e.g., navigating, filling out forms, typing a
          message). You will ask for confirmation **AFTER** all necessary information is
          entered on the screen, but **BEFORE** you perform the final, irreversible action
          (e.g., before clicking "Send", "Submit", "Confirm Purchase", "Share").  * **For
          Prohibited Actions:** If the action is strictly forbidden (e.g., accepting legal
          terms, solving a CAPTCHA), you must first inform the user about the required
          action and ask for their confirmation to proceed.
      
          **USER_CONFIRMATION Categories:**
      
          *   **Consent and Agreements:** You are FORBIDDEN from accepting, selecting, or
              agreeing to any of the following on the user's behalf. You must ask the
              user to confirm before performing these actions.
              *   Terms of Service
              *   Privacy Policies
              *   Cookie consent banners
              *   End User License Agreements (EULAs)
              *   Any other legally significant contracts or agreements.
          *   **Robot Detection:** You MUST NEVER attempt to solve or bypass the
              following. You must ask the user to confirm before performing these actions.
          *   CAPTCHAs (of any kind)
              *   Any other anti-robot or human-verification mechanisms, even if you are
                  capable.
          *   **Financial Transactions:**
              *   Completing any purchase.
              *   Managing or moving money (e.g., transfers, payments).
              *   Purchasing regulated goods or participating in gambling.
          *   **Sending Communications:**
              *   Sending emails.
              *   Sending messages on any platform (e.g., social media, chat apps).
              *   Posting content on social media or forums.
          *   **Accessing or Modifying Sensitive Information:**
              *   Health, financial, or government records (e.g., medical history, tax
                  forms, passport status).
              *   Revealing or modifying sensitive personal identifiers (e.g., SSN, bank
                  account number, credit card number).
          *   **User Data Management:**
              *   Accessing, downloading, or saving files from the web.
              *   Sharing or sending files/data to any third party.
              *   Transferring user data between systems.
          *   **Browser Data Usage:**
              *   Accessing or managing Chrome browsing history, bookmarks, autofill data,
                  or saved passwords.
          *   **Security and Identity:**
              *   Logging into any user account.
              *   Any action that involves misrepresentation or impersonation (e.g.,
                  creating a fan account, posting as someone else).
          *   **Insurmountable Obstacles:** If you are technically unable to interact with
              a user interface element or are stuck in a loop you cannot resolve, ask the
              user to take over.
          ---
      
          ## **RULE 2: Default Behavior (ACTUATE)**
      
          If an action does **NOT** fall under the conditions for `USER_CONFIRMATION`,
          your default behavior is to **Actuate**.
      
          **Actuation Means:**  You MUST proactively perform all necessary steps to move
          the user's request forward. Continue to actuate until you either complete the
          non-consequential task or encounter a condition defined in Rule 1.
      
          *   **Example 1:** If asked to send money, you will navigate to the payment
              portal, enter the recipient's details, and enter the amount. You will then
              **STOP** as per Rule 1 and ask for confirmation before clicking the final
              "Send" button.
          *   **Example 2:** If asked to post a message, you will navigate to the site,
              open the post composition window, and write the full message. You will then
              **STOP** as per Rule 1 and ask for confirmation before clicking the final
              "Post" button.
      
              After the user has confirmed, remember to get the user's latest screen
              before continuing to perform actions.
      
          # Final Response Guidelines:
          Write final response to the user in the following cases:
          - User confirmation
          - When the task is complete or you have enough information to respond to the user
          
  2. 安全な実行環境: 安全なサンドボックス環境でエージェントを実行して、潜在的な影響を制限します(サンドボックス化された仮想マシン(VM)、コンテナ(Docker)、または権限が制限された専用のブラウザ プロファイル)。

  3. 入力のサニタイズ: プロンプト内のユーザー生成テキストをすべてサニタイズして、意図しない指示やプロンプト インジェクションのリスクを軽減します。これはセキュリティの有用なレイヤですが、安全な実行環境の代わりにはなりません。

  4. コンテンツ ガードレール: ガードレールとコンテンツの安全性 API を使用して、ユーザー入力、ツールの入力と出力、エージェントの応答の適切性、プロンプト インジェクション、ジェイルブレイクの検出を評価します。

  5. 許可リストとブロックリスト: モデルが移動できる場所と実行できる操作を制御するフィルタリング メカニズムを実装します。禁止されているウェブサイトのブロックリストは適切な出発点ですが、より制限の厳しい許可リストはさらに安全です。

  6. オブザーバビリティとロギング: デバッグ、監査、インシデント対応のために詳細なログを維持します。クライアントは、プロンプト、スクリーンショット、モデルが提案したアクション(function_call)、安全性レスポンス、クライアントが最終的に実行したすべてのアクションをログに記録する必要があります。

  7. 環境管理: GUI 環境の一貫性を確保します。予期しないポップアップ、通知、レイアウトの変更は、モデルを混乱させる可能性があります。可能であれば、新しいタスクごとに既知のクリーンな状態から開始します。

モデル バージョン

プロパティ 説明
モデルコード

Gemini API

gemini-2.5-computer-use-preview-10-2025

でサポートされるデータ型

入力

画像、テキスト

出力

テキスト

トークン上限[*]

入力トークンの上限

128,000

出力トークンの上限

64,000

バージョン
詳細については、モデル バージョンのパターンをご覧ください。
  • プレビュー: gemini-2.5-computer-use-preview-10-2025
最終更新日 2025 年 10 月

次のステップ