استفاده از کامپیوتر

مدل و ابزار Gemini 2.5 Computer Use Preview شما را قادر می سازد تا عوامل کنترل مرورگر را بسازید که با وظایف تعامل داشته و آنها را خودکار می کند. با استفاده از اسکرین‌شات‌ها، مدل استفاده از رایانه می‌تواند یک صفحه رایانه را ببیند و با ایجاد عملکردهای رابط کاربری خاص مانند کلیک‌های ماوس و ورودی‌های صفحه کلید، «عمل کند». مشابه فراخوانی تابع، برای دریافت و اجرای اقدامات استفاده از رایانه، باید کد برنامه سمت سرویس گیرنده را بنویسید.

با استفاده از رایانه، می توانید عواملی بسازید که:

  • ورود داده های تکراری یا پر کردن فرم در وب سایت ها را خودکار کنید.
  • آزمایش خودکار برنامه های کاربردی وب و جریان کاربر را انجام دهید
  • انجام تحقیق در وب سایت های مختلف (به عنوان مثال، جمع آوری اطلاعات محصول، قیمت ها و بررسی ها از سایت های تجارت الکترونیک برای اطلاع از خرید)

ساده ترین راه برای آزمایش مدل استفاده از رایانه Gemini از طریق پیاده سازی مرجع یا محیط نمایشی Browserbase است.

نحوه عملکرد استفاده از کامپیوتر

برای ساختن یک عامل کنترل مرورگر با مدل Computer Use، یک حلقه عامل پیاده سازی کنید که کارهای زیر را انجام می دهد:

  1. یک درخواست برای مدل ارسال کنید

    • ابزار استفاده از رایانه و در صورت تمایل هر توابع سفارشی تعریف شده توسط کاربر یا توابع حذف شده را به درخواست API خود اضافه کنید.
    • مدل استفاده از رایانه را با درخواست کاربر و یک عکس از صفحه نمایش وضعیت فعلی رابط کاربری گرافیکی درخواست کنید.
  2. پاسخ مدل را دریافت کنید

    • مدل استفاده از رایانه درخواست کاربر و اسکرین شات را تجزیه و تحلیل می‌کند، و پاسخی تولید می‌کند که شامل یک function_call پیشنهادی است که یک عمل رابط کاربری را نشان می‌دهد (مثلاً روی مختصات (x,y) کلیک کنید یا «متن را تایپ کنید»). برای توضیح همه اقدامات رابط کاربری که توسط مدل استفاده از رایانه پشتیبانی می‌شوند، به اقدامات پشتیبانی‌شده مراجعه کنید.
    • پاسخ API همچنین ممکن است شامل یک safety_decision از یک سیستم ایمنی داخلی باشد که عملکرد پیشنهادی مدل را بررسی می‌کند. این safety_decision اقدام را به صورت زیر طبقه بندی می کند:
      • منظم / مجاز: عمل ایمن در نظر گرفته می شود. این ممکن است با عدم وجود safety_decision نیز نشان داده شود.
      • نیاز به تایید ( require_confirmation ): مدل در شرف انجام عملی است که ممکن است خطرناک باشد (به عنوان مثال، کلیک کردن بر روی "پذیرش بنر کوکی").
  3. عمل دریافتی را اجرا کنید

    • کد سمت سرویس گیرنده شما function_call و هر safety_decision همراه آن را دریافت می کند.
      • Regular / مجاز: اگر safety_decision به طور منظم / مجاز را نشان می دهد (یا اگر safety_decision وجود ندارد)، کد سمت کلاینت شما می تواند function_call مشخص شده را در محیط هدف شما (به عنوان مثال، یک مرورگر وب) اجرا کند.
      • نیاز به تأیید: اگر safety_decision نشان می‌دهد که به تأیید نیاز دارد، برنامه شما باید قبل از اجرای function_call از کاربر نهایی درخواست تأیید کند. در صورت تایید کاربر، اقدام به اجرای عمل کنید. اگر کاربر انکار کرد، اقدام را اجرا نکنید.
  4. وضعیت محیط جدید را ثبت کنید

    • اگر این عمل انجام شده باشد، کلاینت شما یک اسکرین شات جدید از رابط کاربری گرافیکی و URL فعلی می گیرد تا به عنوان بخشی از یک function_response به مدل استفاده از رایانه برگرداند.
    • اگر عملکردی توسط سیستم ایمنی مسدود شد یا توسط کاربر تأیید نشد، برنامه شما ممکن است شکل دیگری از بازخورد را به مدل ارسال کند یا به تعامل پایان دهد.

این فرآیند از مرحله 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.
    

کد نمونه برای گسترش به محیط اندروید در بخش Using custom user-defined functions گنجانده شده است.

1. یک درخواست برای مدل ارسال کنید

ابزار استفاده از رایانه را به درخواست API خود اضافه کنید و یک درخواست به مدل استفاده از رایانه ارسال کنید که شامل هدف کاربر و یک اسکرین شات اولیه از رابط کاربری گرافیکی است. باید از مدل Gemini Computer Use، gemini-2.5-computer-use-preview-10-2025 استفاده کنید. اگر سعی کنید از ابزار Computer Use با مدل دیگری استفاده کنید، با خطا مواجه خواهید شد.

همچنین می توانید به صورت اختیاری پارامترهای زیر را اضافه کنید:

  • کنش‌های مستثنی شده: اگر اقداماتی از فهرست عملکردهای رابط کاربری پشتیبانی‌شده وجود دارد که نمی‌خواهید مدل انجام دهد، این اقدامات را به‌عنوان excluded_predefined_functions مشخص کنید.
  • توابع تعریف شده توسط کاربر: علاوه بر ابزار استفاده از رایانه، ممکن است بخواهید توابع سفارشی تعریف شده توسط کاربر را نیز اضافه کنید.

توجه داشته باشید که در هنگام صدور درخواست نیازی به تعیین اندازه نمایشگر نیست. این مدل مختصات پیکسل را به ارتفاع و عرض صفحه پیش‌بینی می‌کند.

پایتون

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. پاسخ مدل را دریافت کنید

مدل استفاده از رایانه با یک یا چند FunctionCalls پاسخ می‌دهد اگر مشخص کند که برای تکمیل کار به اقدامات UI نیاز است. استفاده از رایانه از فراخوانی تابع موازی پشتیبانی می کند، به این معنی که مدل می تواند چندین عملکرد را در یک نوبت برگرداند.

در اینجا یک نمونه پاسخ مدل است.

{
  "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) را بدون توجه به ابعاد تصویر ورودی، خروجی می دهد، بنابراین بخشی از مرحله ترجمه، تبدیل این مختصات نرمال شده به مقادیر پیکسل واقعی است.

اندازه صفحه نمایش توصیه شده برای استفاده با مدل Computer Use (1440، 900) است. این مدل با هر وضوحی کار می کند، اگرچه کیفیت نتایج ممکن است تحت تأثیر قرار گیرد.

توجه داشته باشید که این مثال فقط شامل اجرای 3 عملکرد رابط کاربری رایج است: open_web_browser ، click_at ، و type_text_at . برای موارد استفاده در تولید، باید سایر اقدامات رابط کاربری را از لیست اقدامات پشتیبانی شده اجرا کنید، مگر اینکه آنها را به‌صراحت به‌عنوان excluded_predefined_functions اضافه کنید.

پایتون

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

4. گرفتن وضعیت محیط جدید

پس از اجرای اکشن ها، نتیجه اجرای تابع را به مدل برگردانید تا بتواند از این اطلاعات برای تولید اکشن بعدی استفاده کند. اگر چندین کنش (تماس های موازی) اجرا شد، باید برای هر یک در نوبت بعدی کاربر یک FunctionResponse ارسال کنید.

پایتون


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

یک حلقه عامل بسازید

برای فعال کردن فعل و انفعالات چند مرحله ای، چهار مرحله از بخش How to implement Computer Use را در یک حلقه ترکیب کنید. به یاد داشته باشید که با ضمیمه کردن پاسخ های مدل و پاسخ های تابع خود، تاریخچه مکالمه را به درستی مدیریت کنید.

برای اجرای این نمونه کد باید:

پایتون


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_app ، long_press_at و go_home تطبیق می‌دهد، در حالی که کنش‌های خاص مرورگر را حذف می‌کند. این مدل می تواند به طور هوشمند این توابع سفارشی را در کنار اقدامات استاندارد UI برای تکمیل وظایف در محیط های غیر مرورگر فراخوانی کند.

پایتون

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 درخواست کند. کد سمت کلاینت شما باید منطق اجرای این اقدامات را اجرا کند. برای مثال به پیاده سازی مرجع مراجعه کنید.

نام فرمان توضیحات آرگومان ها (در تابع فراخوانی) مثال فراخوانی تابع
open_web_browser مرورگر وب را باز می کند. هیچ کدام {"name": "open_web_browser", "args": {}}
صبر_5_ثانیه اجرای را به مدت 5 ثانیه متوقف می کند تا محتوای پویا بارگیری شود یا انیمیشن ها کامل شوند. هیچ کدام {"name": "wait_5_seconds", "args": {}}
برو به عقب به صفحه قبلی در تاریخچه مرورگر هدایت می شود. هیچ کدام {"name": "go_back", "args": {}}
برو_به جلو به صفحه بعدی در تاریخچه مرورگر هدایت می شود. هیچ کدام {"name": "go_forward", "args": {}}
جستجو کنید به صفحه اصلی موتور جستجوی پیش‌فرض (مثلاً Google) حرکت می‌کند. برای شروع یک کار جستجوی جدید مفید است. هیچ کدام {"name": "search", "args": {}}
حرکت کنید مرورگر را مستقیماً به URL مشخص شده هدایت می کند. url : خ {"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}}
کلید_ترکیب کلیدها یا ترکیبات صفحه کلید، مانند "Control+C" یا "Enter" را فشار دهید. برای راه اندازی اقدامات (مانند ارسال فرم با "Enter") یا عملیات کلیپ بورد مفید است. keys : str (به عنوان مثال 'enter'، 'control+c'). {"name": "key_combination", "args": {"keys": "Control+A"}}
اسکرول_سند کل صفحه وب را «بالا»، «پایین»، «چپ» یا «راست» پیمایش می کند. direction : str ("بالا"، "پایین"، "چپ"، یا "راست") {"name": "scroll_document", "args": {"direction": "down"}}
scroll_at یک عنصر یا ناحیه خاص را در مختصات (x, y) در جهت مشخص با قدر معین پیمایش می کند. مختصات و بزرگی (پیش‌فرض 800) بر اساس یک شبکه 1000x1000 است. y : int (0-999)، x : int (0-999)، direction : str ("بالا"، "پایین"، "چپ"، "راست")، magnitude : int (0-999، اختیاری، پیش فرض 800) {"name": "scroll_at", "args": {"y": 500, "x": 500, "direction": "down", "magnitude": 400}}
بکشید و رها کنید یک عنصر را از یک مختصات شروع (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_decision require_confirmation است، باید از کاربر نهایی بخواهید تا قبل از اجرای عمل تایید کند. طبق شرایط خدمات ، شما مجاز به دور زدن درخواست‌های تایید انسانی نیستید.

این نمونه کد از کاربر نهایی درخواست می‌کند تا قبل از اجرای عمل تأیید کند. اگر کاربر اقدام را تأیید نکند، حلقه خاتمه می یابد. اگر کاربر این عمل را تأیید کند، اقدام اجرا می‌شود و فیلد safety_acknowledgement به عنوان True علامت‌گذاری می‌شود.

پایتون

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 خود وارد کنید.

پایتون

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 جدید است و خطرات جدیدی را ارائه می دهد که توسعه دهندگان باید به آنها توجه داشته باشند:

  • محتوای غیرقابل اعتماد و کلاهبرداری: همانطور که مدل سعی می کند به هدف کاربر دست یابد، ممکن است به منابع اطلاعات و دستورالعمل های غیرقابل اعتماد از صفحه متکی باشد. به عنوان مثال، اگر هدف کاربر خرید یک تلفن پیکسل باشد و مدل با کلاهبرداری «Free-Pixel در صورت تکمیل نظرسنجی» مواجه شود، احتمال اینکه مدل نظرسنجی را کامل کند وجود دارد.
  • اقدامات ناخواسته گاه به گاه: مدل می تواند هدف کاربر یا محتوای صفحه وب را به اشتباه تفسیر کند و باعث شود که اقدامات نادرستی مانند کلیک کردن روی دکمه اشتباه یا پر کردن فرم اشتباه انجام دهد. این می تواند منجر به انجام وظایف ناموفق یا حذف داده ها شود.
  • نقض خط‌مشی: قابلیت‌های API می‌تواند به‌طور عمدی یا غیرعمدی به سمت فعالیت‌هایی هدایت شود که خط‌مشی‌های Google را نقض می‌کنند ( خط‌مشی استفاده ممنوع Gen 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. محیط اجرای ایمن: عامل خود را در یک محیط امن و جعبه ایمنی اجرا کنید تا تأثیر بالقوه آن را محدود کنید (مثلاً یک ماشین مجازی sandboxed (VM)، یک کانتینر (به عنوان مثال، Docker)، یا یک نمایه مرورگر اختصاصی با مجوزهای محدود).

  3. پاکسازی ورودی: برای کاهش خطر دستورالعمل‌های ناخواسته یا تزریق سریع، تمام متن‌های تولید شده توسط کاربر را در اعلان‌ها پاکسازی کنید. این یک لایه امنیتی مفید است، اما جایگزینی برای یک محیط اجرای امن نیست.

  4. نرده‌های محافظ محتوا: از نرده‌های محافظ و APIهای ایمنی محتوا برای ارزیابی ورودی‌های کاربر، ورودی و خروجی ابزار، پاسخ یک نماینده برای مناسب بودن، تزریق سریع و تشخیص فرار از زندان استفاده کنید.

  5. لیست‌های مجاز و فهرست‌های مسدود: مکانیسم‌های فیلتر را برای کنترل مکان‌هایی که مدل می‌تواند پیمایش کند و کارهایی که می‌تواند انجام دهد، پیاده‌سازی کنید. فهرست مسدودی از وب‌سایت‌های ممنوعه نقطه شروع خوبی است، در حالی که فهرست مجاز محدودتر حتی امن‌تر است.

  6. قابلیت مشاهده و ثبت گزارش: گزارش های دقیق را برای اشکال زدایی، ممیزی و پاسخ به حادثه حفظ کنید. مشتری شما باید درخواست ها، اسکرین شات ها، اقدامات پیشنهادی مدل (function_call)، پاسخ های ایمنی و تمام اقداماتی که در نهایت توسط مشتری انجام می شود را ثبت کند.

  7. مدیریت محیط: اطمینان حاصل کنید که محیط رابط کاربری گرافیکی سازگار است. پاپ‌آپ‌های غیرمنتظره، اعلان‌ها یا تغییرات در چیدمان می‌توانند مدل را گیج کنند. در صورت امکان برای هر کار جدید از یک وضعیت شناخته شده و تمیز شروع کنید.

نسخه های مدل

اموال توضیحات
کد مدل

Gemini API

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

انواع داده های پشتیبانی شده

ورودی

تصویر، متن

خروجی

متن

محدودیت های رمز [*]

محدودیت رمز ورودی

128000

محدودیت نشانه خروجی

64000

نسخه
الگوهای نسخه مدل را برای جزئیات بیشتر بخوانید.
  • پیش نمایش: gemini-2.5-computer-use-preview-10-2025
آخرین به روز رسانی اکتبر 2025

بعدش چی