Model dan alat Penggunaan Komputer Gemini 2.5 memungkinkan Anda mengaktifkan aplikasi untuk berinteraksi dengan dan mengotomatiskan tugas di browser. Dengan menggunakan screenshot, model penggunaan komputer dapat menyimpulkan informasi tentang layar komputer, dan melakukan tindakan dengan membuat tindakan UI tertentu seperti klik mouse dan input keyboard. Mirip dengan panggilan fungsi, Anda perlu menulis kode aplikasi sisi klien untuk menerima panggilan fungsi model Penggunaan Komputer dan alat serta menjalankan tindakan yang sesuai.
Dengan model dan alat Penggunaan Komputer, Anda dapat membuat agen yang dapat:
- Mengotomatiskan entri data atau pengisian formulir yang berulang di situs.
- Membuka situs untuk mengumpulkan informasi.
- Membantu pengguna dengan melakukan serangkaian tindakan di aplikasi web.
Panduan ini mencakup:
- Cara kerja model dan alat Penggunaan Komputer
- Cara mengaktifkan model dan alat Penggunaan Komputer
- Cara mengirim permintaan, menerima respons, dan membuat loop agen
- Tindakan komputer yang didukung
- Dukungan keselamatan dan keamanan
- Pratinjau harga
Panduan ini mengasumsikan bahwa Anda menggunakan Gen AI SDK untuk Python dan sudah terbiasa dengan Playwright API.
Model dan alat Penggunaan Komputer tidak didukung dalam bahasa SDK lain atau konsol selama pratinjau ini. Google Cloud
Selain itu, Anda dapat melihat implementasi referensi untuk model dan alat Penggunaan Komputer di GitHub.
Cara kerja model dan alat Penggunaan Komputer
Alih-alih membuat respons teks, model dan alat Penggunaan Komputer menentukan kapan harus melakukan tindakan UI tertentu seperti klik mouse, dan menampilkan parameter yang diperlukan untuk menjalankan tindakan ini. Anda perlu menulis kode aplikasi sisi klien untuk menerima model dan alat Penggunaan Komputer function_call
serta menjalankan tindakan yang sesuai.
Interaksi model dan alat Penggunaan Komputer mengikuti proses loop agentik:
Mengirim permintaan ke model
- Tambahkan model dan alat Penggunaan Komputer, serta alat tambahan lainnya jika perlu, ke permintaan API Anda.
- Minta model dan alat Penggunaan Komputer dengan permintaan pengguna dan screenshot yang menampilkan status GUI saat ini.
Menerima respons model
- Model menganalisis permintaan dan screenshot pengguna, lalu membuat respons yang mencakup
function_call
yang disarankan yang merepresentasikan tindakan UI (misalnya, "klik di koordinat (x,y)" atau "ketik 'teks'"). Lihat Tindakan yang didukung untuk mengetahui daftar semua tindakan yang dapat Anda gunakan dengan model. - Respons API juga dapat menyertakan
safety_response
dari sistem keamanan internal yang telah memeriksa tindakan yang diusulkan model.safety_response
mengklasifikasikan tindakan sebagai:- Reguler atau diizinkan: Tindakan dianggap aman. Hal ini juga dapat
ditampilkan dengan tidak adanya
safety_response
. - Memerlukan konfirmasi: Model akan melakukan tindakan yang berisiko (misalnya, mengklik "banner setuju cookie").
- Reguler atau diizinkan: Tindakan dianggap aman. Hal ini juga dapat
ditampilkan dengan tidak adanya
- Model menganalisis permintaan dan screenshot pengguna, lalu membuat respons yang mencakup
Menjalankan tindakan yang diterima
- Kode sisi klien Anda menerima
function_call
dansafety_response
yang menyertainya. - Jika
safety_response
menunjukkan reguler atau diizinkan (atau jika tidak adasafety_response
), kode sisi klien Anda dapat mengeksekusifunction_call
yang ditentukan di lingkungan target Anda (seperti browser web). - Jika
safety_response
menunjukkan konfirmasi yang diperlukan, aplikasi Anda harus meminta konfirmasi pengguna akhir sebelum mengeksekusifunction_call
. Jika pengguna mengonfirmasi, lanjutkan untuk menjalankan tindakan. Jika pengguna menolak, jangan jalankan tindakan.
- Kode sisi klien Anda menerima
Merekam status lingkungan baru
- Jika tindakan telah dieksekusi, klien Anda akan mengambil screenshot baru
GUI dan URL saat ini untuk dikirim kembali ke
model dan alat Penggunaan Komputer sebagai bagian dari
function_response
. - Jika tindakan diblokir oleh sistem keamanan atau konfirmasi ditolak oleh pengguna, aplikasi Anda dapat mengirimkan bentuk masukan yang berbeda ke model atau mengakhiri interaksi.
- Jika tindakan telah dieksekusi, klien Anda akan mengambil screenshot baru
GUI dan URL saat ini untuk dikirim kembali ke
model dan alat Penggunaan Komputer sebagai bagian dari
Permintaan baru dikirim ke model dengan status yang diperbarui. Proses ini berulang dari langkah 2, dengan model dan alat Penggunaan Komputer menggunakan screenshot baru (jika disediakan) dan sasaran yang sedang berlangsung untuk menyarankan tindakan berikutnya. Loop berlanjut hingga tugas selesai, terjadi error, atau proses dihentikan (misalnya, jika respons diblokir oleh filter keamanan atau keputusan pengguna).
Diagram berikut menggambarkan cara kerja model dan alat Penggunaan Komputer:
Mengaktifkan model dan alat Penggunaan Komputer
Untuk mengaktifkan model dan alat Penggunaan Komputer, gunakan gemini-2.5-computer-use-preview-10-2025
sebagai model Anda, lalu tambahkan model dan alat Penggunaan Komputer ke daftar alat yang diaktifkan:
Python
from google import genai from google.genai import types from google.genai.types import Content, Part, FunctionResponse client = genai.Client() # Add Computer Use model and tool to the list of tools generate_content_config = genai.types.GenerateContentConfig( tools=[ types.Tool( computer_use=types.ComputerUse( environment=types.Environment.ENVIRONMENT_BROWSER, ) ), ] ) # Example request using the Computer Use model and tool contents = [ Content( role="user", parts=[ Part(text="Go to google.com and search for 'weather in New York'"), ], ) ] response = client.models.generate_content( model="gemini-2.5-computer-use-preview-10-2025", contents=contents, config=generate_content_config, )
Mengirim permintaan
Setelah mengonfigurasi model dan alat Penggunaan Komputer, kirim perintah ke model yang mencakup tujuan pengguna dan screenshot awal GUI.
Anda juga dapat menambahkan hal berikut secara opsional:
- Tindakan yang dikecualikan: Jika ada tindakan dari daftar tindakan UI yang didukung yang tidak ingin Anda lakukan oleh model, tentukan tindakan ini dalam
excluded_predefined_functions
. - Fungsi yang ditentukan pengguna: Selain model dan alat Penggunaan Komputer, Anda mungkin ingin menyertakan fungsi kustom yang ditentukan pengguna.
Contoh kode berikut mengaktifkan model dan alat Penggunaan Komputer serta mengirimkan permintaan ke model:
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"] # Configuration for the Computer Use model and tool with browser environment generate_content_config = genai.types.GenerateContentConfig( tools=[ # 1. Computer Use model and 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 (need to defined above) # types.Tool( # function_declarations=custom_functions # ) ], ) # Create the content with user message contents: list[Content] = [ 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.text)
Anda juga dapat menyertakan fungsi kustom yang ditentukan pengguna untuk memperluas fungsi model. Lihat Menggunakan model dan alat Penggunaan Komputer untuk kasus penggunaan seluler untuk mengetahui informasi tentang cara mengonfigurasi penggunaan komputer untuk kasus penggunaan seluler dengan menambahkan tindakan seperti open_app
, long_press_at
, dan go_home
sambil mengecualikan tindakan khusus browser.
Menerima respons
Model merespons dengan satu atau beberapa FunctionCalls
jika menentukan bahwa tindakan UI atau fungsi yang ditentukan pengguna diperlukan untuk menyelesaikan tugas. Kode
aplikasi Anda perlu mengurai tindakan ini, menjalankannya, dan mengumpulkan
hasilnya. Model dan alat Penggunaan Komputer mendukung panggilan fungsi paralel, yang berarti model dapat menampilkan beberapa tindakan independen dalam satu giliran.
{
"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
}
}
}
]
}
}
Bergantung pada tindakan, respons API juga dapat menampilkan safety_response
:
{
"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"
}
}
}
}
]
}
}
Menjalankan tindakan yang diterima
Setelah Anda menerima respons, model perlu menjalankan tindakan yang diterima.
Kode berikut mengekstrak panggilan fungsi dari respons Gemini, mengonversi koordinat dari rentang 0-1000 ke piksel sebenarnya, menjalankan tindakan browser menggunakan Playwright, dan menampilkan status berhasil atau gagal untuk setiap tindakan:
import time
from typing import Any, List, Tuple
def normalize_x(x: int, screen_width: int) -> int:
"""Convert normalized x coordinate (0-1000) to actual pixel coordinate."""
return int(x / 1000 * screen_width)
def normalize_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(response, page, screen_width: int, screen_height: int) -> List[Tuple[str, Any]]:
"""
Extract and execute function calls from Gemini response.
Args:
response: Gemini API response object
page: Playwright page object
screen_width: Screen width in pixels
screen_height: Screen height in pixels
Returns:
List of tuples: [(function_name, result), ...]
"""
# Extract function calls and thoughts from the model's response
candidate = response.candidates[0]
function_calls = []
thoughts = []
for part in candidate.content.parts:
if hasattr(part, 'function_call') and part.function_call:
function_calls.append(part.function_call)
elif hasattr(part, 'text') and part.text:
thoughts.append(part.text)
if thoughts:
print(f"Model Reasoning: {' '.join(thoughts)}")
# Execute each function call
results = []
for function_call in function_calls:
result = None
try:
if function_call.name == "open_web_browser":
print("Executing open_web_browser")
# Browser is already open via Playwright, so this is a no-op
result = "success"
elif function_call.name == "click_at":
actual_x = normalize_x(function_call.args["x"], screen_width)
actual_y = normalize_y(function_call.args["y"], screen_height)
print(f"Executing click_at: ({actual_x}, {actual_y})")
page.mouse.click(actual_x, actual_y)
result = "success"
elif function_call.name == "type_text_at":
actual_x = normalize_x(function_call.args["x"], screen_width)
actual_y = normalize_y(function_call.args["y"], screen_height)
text = function_call.args["text"]
press_enter = function_call.args.get("press_enter", False)
clear_before_typing = function_call.args.get("clear_before_typing", True)
print(f"Executing type_text_at: ({actual_x}, {actual_y}) text='{text}'")
# Click at the specified location
page.mouse.click(actual_x, actual_y)
time.sleep(0.1)
# Clear existing text if requested
if clear_before_typing:
page.keyboard.press("Control+A")
page.keyboard.press("Backspace")
# Type the text
page.keyboard.type(text)
# Press enter if requested
if press_enter:
page.keyboard.press("Enter")
result = "success"
else:
# For any functions not parsed above
print(f"Unrecognized function: {function_call.name}")
result = "unknown_function"
except Exception as e:
print(f"Error executing {function_call.name}: {e}")
result = f"error: {str(e)}"
results.append((function_call.name, result))
return results
Jika safety_decision
yang ditampilkan adalah require_confirmation
, Anda harus meminta
pengguna untuk mengonfirmasi sebelum melanjutkan eksekusi tindakan. Berdasarkan persyaratan layanan, Anda tidak diizinkan untuk melewati permintaan konfirmasi manusia.
Kode berikut menambahkan logika keamanan ke kode sebelumnya:
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(response, page, screen_width: int, screen_height: int):
# ... 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"
# ... Execute function call and append to results ...
Merekam status baru
Setelah menjalankan tindakan, kirim hasil eksekusi fungsi kembali ke model agar model dapat menggunakan informasi ini untuk membuat tindakan berikutnya. Jika
beberapa tindakan (panggilan paralel) dijalankan, Anda harus mengirimkan
FunctionResponse
untuk setiap tindakan pada giliran pengguna berikutnya. Untuk fungsi yang ditentukan pengguna, FunctionResponse
harus berisi nilai yang ditampilkan dari fungsi yang dijalankan.
function_response_parts = []
for name, result in results:
# Take screenshot after each action
screenshot = page.screenshot()
current_url = page.url
function_response_parts.append(
FunctionResponse(
name=name,
response={"url": current_url}, # Include safety acknowledgement
parts=[
types.FunctionResponsePart(
inline_data=types.FunctionResponseBlob(
mime_type="image/png", data=screenshot
)
)
]
)
)
# Create the user feedback content with all responses
user_feedback_content = Content(
role="user",
parts=function_response_parts
)
# Append this feedback to the 'contents' history list for the next API call
contents.append(user_feedback_content)
Membangun loop agen
Gabungkan langkah-langkah sebelumnya ke dalam loop untuk mengaktifkan interaksi multi-langkah. Loop harus menangani panggilan fungsi paralel. Jangan lupa untuk mengelola histori percakapan (array konten) dengan benar dengan menambahkan respons model dan respons fungsi Anda.
Python
from google import genai from google.genai.types import Content, Part from playwright.sync_api import sync_playwright def has_function_calls(response): """Check if response contains any function calls.""" candidate = response.candidates[0] return any(hasattr(part, 'function_call') and part.function_call for part in candidate.content.parts) def main(): client = genai.Client() # ... (config setup from "Send a request to model" section) ... with sync_playwright() as p: browser = p.chromium.launch(headless=False) page = browser.new_page() page.goto("https://www.google.com") screen_width, screen_height = 1920, 1080 # ... (initial contents setup from "Send a request to model" section) ... # Agent loop: iterate until model provides final answer for iteration in range(10): print(f"\nIteration {iteration + 1}\n") # 1. Send request to model (see "Send a request to model" section) response = client.models.generate_content( model='gemini-2.5-computer-use-preview-10-2025', contents=contents, config=generate_content_config, ) contents.append(response.candidates[0].content) # 2. Check if done - no function calls means final answer if not has_function_calls(response): print(f"FINAL RESPONSE:\n{response.text}") break # 3. Execute actions (see "Execute the received actions" section) results = execute_function_calls(response, page, screen_width, screen_height) time.sleep(1) # 4. Capture state and create feedback (see "Capture the New State" section) contents.append(create_feedback(results, page)) input("\nPress Enter to close browser...") browser.close() if __name__ == "__main__": main()
Model dan alat Penggunaan Komputer untuk kasus penggunaan seluler
Contoh berikut menunjukkan cara menentukan fungsi kustom (seperti
open_app
, long_press_at
, dan go_home
), menggabungkannya dengan alat penggunaan komputer bawaan Gemini, dan mengecualikan fungsi khusus browser yang tidak diperlukan. Dengan mendaftarkan fungsi kustom ini, model dapat memanggilnya secara cerdas bersama tindakan UI standar untuk menyelesaikan tugas di lingkungan non-browser.
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()
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, duration_ms: int = 500) -> 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).
duration_ms: Press duration in milliseconds. Defaults to 500.
Returns:
Object with the coordinates pressed and the duration used.
"""
return {"x": x, "y": y, "duration_ms": duration_ms}
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(
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=generate_content_config,
)
print(response)
Tindakan yang didukung
Model dan alat Penggunaan Komputer memungkinkan model meminta tindakan berikut menggunakan
FunctionCall
. Kode sisi klien Anda harus menerapkan logika eksekusi untuk
tindakan ini. Lihat contoh implementasi referensi.
Command Name | Deskripsi | Argumen (dalam Panggilan Fungsi) | Contoh Panggilan Fungsi |
---|---|---|---|
open_web_browser | Membuka browser web. | Tidak ada | {"name": "open_web_browser", "args": {}} |
wait_5_seconds | Menjeda eksekusi selama 5 detik untuk memungkinkan konten dinamis dimuat atau animasi selesai. | Tidak ada | {"name": "wait_5_seconds", "args": {}} |
go_back | Membuka halaman sebelumnya dalam histori browser. | Tidak ada | {"name": "go_back", "args": {}} |
go_forward | Membuka halaman berikutnya dalam histori browser. | Tidak ada | {"name": "go_forward", "args": {}} |
search | Membuka halaman beranda mesin telusur default (misalnya, Google). Berguna untuk memulai tugas penelusuran baru. | Tidak ada | {"name": "search", "args": {}} |
navigate | Membuka URL yang ditentukan secara langsung di browser. | url : str |
{"name": "navigate", "args": {"url": "https://www.wikipedia.org"}} |
click_at | Mengklik pada koordinat tertentu di halaman web. Nilai x dan y didasarkan pada petak 1000x1000 dan diskalakan ke dimensi layar. | y : int (0-999), x : int (0-999) |
{"name": "click_at", "args": {"y": 300, "x": 500}} |
hover_at | Mengarahkan kursor ke koordinat tertentu di halaman web. Berguna untuk menampilkan sub-menu. x dan y didasarkan pada petak 1000x1000. | y : int (0-999) x : int (0-999) |
{"name": "hover_at", "args": {"y": 150, "x": 250}} |
type_text_at | Mengetik teks pada koordinat tertentu, secara default menghapus kolom terlebih dahulu dan menekan ENTER setelah mengetik, tetapi ini dapat dinonaktifkan. x dan y didasarkan pada petak 1000x1000. | y : int (0-999), x : int (0-999), text : str, press_enter : bool (Opsional, default Benar), clear_before_typing : bool (Opsional, default Benar) |
{"name": "type_text_at", "args": {"y": 250, "x": 400, "text": "search query", "press_enter": false}} |
key_combination | Tekan tombol atau kombinasi tombol keyboard, seperti "Control+C" atau "Enter". Berguna untuk memicu tindakan (seperti mengirimkan formulir dengan "Enter") atau operasi papan klip. | keys : str (misalnya, 'enter', 'control+c'. Lihat referensi API untuk mengetahui daftar lengkap kunci yang diizinkan) |
{"name": "key_combination", "args": {"keys": "Control+A"}} |
scroll_document | Men-scroll seluruh halaman web "ke atas", "ke bawah", "ke kiri", atau "ke kanan". | direction : str ("up", "down", "left", atau "right") |
{"name": "scroll_document", "args": {"direction": "down"}} |
scroll_at | Men-scroll elemen atau area tertentu pada koordinat (x, y) ke arah yang ditentukan dengan besaran tertentu. Koordinat dan besaran (default 800) didasarkan pada petak 1000x1000. | y : int (0-999), x : int (0-999), direction : str ("up", "down", "left", "right"), magnitude : int (0-999, Opsional, default 800) |
{"name": "scroll_at", "args": {"y": 500, "x": 500, "direction": "down", "magnitude": 400}} |
drag_and_drop | Menarik elemen dari koordinat awal (x, y) dan meletakkannya di koordinat tujuan (destination_x, destination_y). Semua koordinat didasarkan pada petak 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}} |
Keselamatan dan keamanan
Bagian ini menjelaskan pengamanan yang diterapkan oleh model dan alat Penggunaan Komputer untuk meningkatkan kontrol pengguna dan meningkatkan keamanan. Selain itu, dokumen ini juga menjelaskan praktik terbaik untuk mengurangi potensi risiko baru yang mungkin ditimbulkan oleh alat tersebut.
Mengonfirmasi keputusan keamanan
Bergantung pada tindakan, respons dari model dan alat Penggunaan Komputer dapat mencakup
safety_decision
dari sistem keamanan internal. Keputusan ini memverifikasi
tindakan yang diusulkan oleh alat untuk keamanan.
{
"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"
}
}
}
}
]
}
}
Jika safety_decision
adalah require_confirmation
, Anda harus meminta pengguna akhir untuk mengonfirmasi sebelum melanjutkan eksekusi tindakan.
Contoh kode berikut meminta konfirmasi pengguna akhir sebelum menjalankan
tindakan. Jika pengguna tidak mengonfirmasi tindakan, loop akan berakhir. Jika pengguna
mengonfirmasi tindakan, tindakan akan dijalankan dan kolom safety_acknowledgement
ditandai sebagai 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(response, page, screen_width: int, screen_height: int):
# ... 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 ...
Jika pengguna mengonfirmasi, Anda harus menyertakan pernyataan persetujuan keselamatan dalam 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
)
)
]
)
)
Praktik terbaik keamanan
Model dan alat Penggunaan Komputer adalah alat baru dan menimbulkan risiko baru yang harus diperhatikan oleh developer:
- Konten yang Tidak Tepercaya & Penipuan: Saat mencoba mencapai tujuan pengguna, model mungkin mengandalkan sumber informasi dan petunjuk yang tidak tepercaya dari layar. Misalnya, jika sasaran pengguna adalah membeli ponsel Pixel dan model menemukan penipuan "Pixel Gratis jika Anda menyelesaikan survei", ada kemungkinan model akan menyelesaikan survei.
- Tindakan yang Tidak Disengaja Sesekali: Model dapat salah menafsirkan tujuan pengguna atau konten halaman web, sehingga menyebabkan model melakukan tindakan yang salah seperti mengklik tombol yang salah atau mengisi formulir yang salah. Hal ini dapat menyebabkan kegagalan tugas atau ekstraksi data.
- Pelanggaran Kebijakan: Kemampuan API dapat diarahkan, baik secara sengaja maupun tidak sengaja, ke aktivitas yang melanggar kebijakan Google (Kebijakan Penggunaan Terlarang untuk AI Generatif dan Persyaratan Layanan Tambahan Gemini API). Hal ini mencakup tindakan yang dapat mengganggu integritas sistem, membahayakan keamanan, mengabaikan langkah-langkah keamanan seperti CAPTCHA, mengontrol perangkat medis, dll.
Untuk mengatasi risiko ini, Anda dapat menerapkan langkah-langkah keamanan dan praktik terbaik berikut:
- Human-in-the-Loop (HITL):
- Terapkan konfirmasi pengguna: Jika respons keamanan menunjukkan require_confirmation, Anda harus menerapkan konfirmasi pengguna sebelum eksekusi.
- Memberikan petunjuk keamanan kustom: Selain pemeriksaan konfirmasi pengguna bawaan, developer dapat secara opsional menambahkan petunjuk sistem kustom yang menerapkan kebijakan keamanannya sendiri, baik untuk memblokir tindakan model tertentu atau mewajibkan konfirmasi pengguna sebelum model melakukan tindakan tidak dapat diubah yang berisiko tinggi. Berikut contoh instruksi sistem keamanan kustom yang dapat Anda sertakan saat berinteraksi dengan model.
Klik untuk melihat contoh pembuatan koneksi
## **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 th e 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 these cases: - User confirmation - When the task is complete or you have enough information to respond to the user
- Lingkungan Eksekusi yang Aman: Jalankan agen Anda di lingkungan dalam sandbox yang aman untuk membatasi potensi dampaknya (misalnya, mesin virtual (VM) dalam sandbox, container (seperti Docker), atau profil browser khusus dengan izin terbatas).
- Sanitisasi Input: Sanitasi semua teks buatan pengguna dalam perintah untuk memitigasi risiko perintah yang tidak diinginkan atau injeksi perintah. Ini adalah lapisan keamanan yang berguna, tetapi bukan pengganti lingkungan eksekusi yang aman.
- Daftar yang Diizinkan dan Daftar yang Tidak Diizinkan: Terapkan mekanisme pemfilteran untuk mengontrol ke mana model dapat membuka dan apa yang dapat dilakukannya. Daftar yang tidak diizinkan untuk situs yang dilarang adalah titik awal yang baik, sementara daftar yang diizinkan yang lebih ketat akan lebih aman.
- Observabilitas dan Logging: Pertahankan log mendetail untuk proses debug, audit, dan respons insiden. Klien Anda harus mencatat perintah, screenshot, tindakan yang disarankan model (
function_call
), respons keamanan, dan semua tindakan yang akhirnya dilakukan oleh klien.
Harga
Model dan alat Penggunaan Komputer dihargai dengan tarif yang sama seperti Gemini 2.5 Pro dan menggunakan SKU yang sama. Untuk memisahkan biaya model dan alat Penggunaan Komputer, gunakan label metadata kustom. Untuk mengetahui informasi selengkapnya tentang cara menggunakan label metadata kustom untuk pemantauan biaya, lihat Label metadata kustom.