adk-python用 ComputerUseToolset Playwright 构建浏览器自动化 Computer Use Agent【免费下载链接】adk-pythonAn open-source, code-first Python toolkit for building, evaluating, and deploying sophisticated AI agents with flexibility and control.项目地址: https://gitcode.com/GitHub_Trending/ad/adk-python本文以 adk-python 仓库中的 Computer Use 示例contributing/samples/multimodal/computer_use为主体完整讲解这个能操作浏览器完成用户任务的 Agent如何安装依赖、如何用adk web启动并发送任务以及从源码层面拆解PlaywrightComputer、ComputerUseToolset、ComputerUseTool三者的协作机制——工具如何自动生成、虚拟坐标系如何归一化、URL 安全校验与确认机制如何工作。示例定位一个操作浏览器的 Computer Use Agent该目录包含一个 computer use agent它能操作浏览器完成用户任务使用 Playwright 控制 Chromium 浏览器通过截图、点击、输入和页面导航与网页交互。示例本身用于演示ComputerUseToolset的用法目录结构如下agent.py主 Agent 配置使用 Google 的gemini-2.5-computer-use-preview-10-2025模型playwright.py基于 Playwright 的浏览器自动化 computer 实现requirements.txtPython 依赖运行环境要求requirements.txt 锁定了四个依赖安装版本时以文件实际内容为准termcolor3.1.0 playwright1.52.0 browserbase1.3.0 rich其中playwright1.52.0决定了后续playwright install chromium拉取浏览器版本的行为termcolor用于在终端输出彩色日志playwright.py 启动浏览器时会打印黄色/绿色提示。另外模型gemini-2.5-computer-use-preview-10-2025是 Google 提供的 computer use 预览模型Agent 需要配置可用的 Google GenAI 凭证如 API Key才能运行。环境安装步骤按仓库 README 给出的三步安装即可。1. 安装 Python 依赖uv pip install -r contributing/samples/computer_use/requirements.txt注意README 中给出的路径contributing/samples/computer_use/在当前仓库中不存在实际的依赖文件位于contributing/samples/multimodal/computer_use/下执行时请改用实际路径uv pip install -r contributing/samples/multimodal/computer_use/requirements.txt2. 安装 Playwright 系统依赖为 Chromium 安装 Playwright 所需的操作系统级依赖playwright install-deps chromium3. 安装 Chromium 浏览器playwright install chromium启动与使用 Agent启动命令从项目根目录执行adk web contributing/samples这会启动 ADK Web 界面在其中可以选择并交互computer_use这个 Agentadk web以目录名作为应用入口示例目录名即computer_use。示例查询Agent 运行起来后可以发送如下查询find me a flight from SF to Hawaii on next Monday, coming back on next Friday. start by navigating directly to flights.google.comAgent 会按以下步骤工作打开浏览器窗口导航到指定网站与页面元素交互以完成任务随时汇报进度其他示例任务预订酒店在线搜索商品填写表单导航复杂网站跨多个页面研究信息源码走读agent.py 如何组装 Agentagent.py 全部核心逻辑不到 40 行分三步完成组装。持久化浏览器 Profileimport os import tempfile from google.adk import Agent from google.adk.tools.computer_use.computer_use_toolset import ComputerUseToolset from .playwright import PlaywrightComputer # Define user_data_dir path profile_name browser_profile_for_adk profile_path os.path.join(tempfile.gettempdir(), profile_name) os.makedirs(profile_path, exist_okTrue) computer_with_profile PlaywrightComputer( screen_size(1280, 936), user_data_dirprofile_path, )这里做了一件关键的事在系统临时目录下创建名为browser_profile_for_adk的持久化浏览器用户数据目录。传入user_data_dir后PlaywrightComputer会以持久化上下文persistent context方式启动 Chromium登录态、Cookie 等信息在多次运行之间保留——这对需要登录的网站如航班搜索很有价值。若不提供该参数playwright.py 会退回为临时浏览器实例。screen_size(1280, 936)定义了浏览器视口分辨率也是 README「Technical Details」中提到的 1280x936 分辨率的来源它会被set_viewport_size应用到页面见 playwright.py#L134-L137。Agent 定义# Create agent with the toolset using the new computer instance root_agent Agent( modelgemini-2.5-computer-use-preview-10-2025, namehello_world_agent, description( computer use agent that can operate a browser on a computer to finish user tasks ), instruction you are a computer use agent , tools[ComputerUseToolset(computercomputer_with_profile)], )从 agent.py#L28-L43 可以看到组装模式把一个实现了浏览器操作的BaseComputer实例交给ComputerUseToolset再把它放进Agent的tools列表。开发者不需要手工为点击、输入、滚动写任何工具声明——工具集会自动生成机制见后文。PlaywrightComputer浏览器操作的具体实现playwright.py 中的PlaywrightComputer继承自框架的抽象基类 BaseComputer是「模型想做什么」到「浏览器实际执行」之间的适配器。构造函数参数class PlaywrightComputer(BaseComputer): Computer that controls Chromium via Playwright. def __init__( self, screen_size: tuple[int, int], initial_url: str https://www.google.com, search_engine_url: str https://www.google.com, highlight_mouse: bool False, user_data_dir: Optional[str] None, ):screen_size屏幕视口分辨率必填示例中为(1280, 936)initial_url首个页面地址默认 Google 首页search_engine_urlsearch()工具跳转的搜索引擎地址highlight_mouse是否在点击/悬停位置画红色圆圈提示默认关闭user_data_dir持久化 profile 目录示例中使用了它。启动流程initializeinitialize()playwright.py#L91-L142完成以下事情启动async_playwright()组装浏览器启动参数--disable-blink-featuresAutomationControlled关闭自动检测特征与--disable-gpu按是否存在user_data_dir分两条路径有则调用chromium.launch_persistent_context(...)复用持久 profile无则chromium.launch(...)后新建上下文两条路径均为headlessFalse即浏览器窗口是可见的用户可实时观察 Agent 操作复用已有页面或新建页面并打开initial_url通过set_viewport_size把视口设为screen_size。environment()返回ComputerEnvironment.ENVIRONMENT_BROWSERComputerUseToolset会据此在 LLM 请求中声明运行环境详见下文。键名映射与组合键模型输出的键名与 Playwright 期望的键名并不完全一致文件开头定义了PLAYWRIGHT_KEY_MAPplaywright.py#L30-L71做归一化例如用户/模型侧键名Playwright 键名backspaceBackspacereturn/enterEnterleft/up/right/downArrowLeft/ArrowUp/ArrowRight/ArrowDownpageup/pagedownPageUp/PageDowncommandMetamacOS 的 Command / Windows 的 Win 键key_combination()先按下除最后一键外的所有修饰键keyboard.downpress主键再逆序释放修饰键playwright.py#L283-L295。各操作方法的行为细节click_at/hover_at鼠标点击或移动后均调用wait_for_load_state()等待页面加载完成然后返回新的屏幕状态type_text_at点击目标坐标聚焦后若clear_before_typingTrue默认会先执行CtrlADelete清空已有内容再keyboard.type(text)输入press_enterTrue默认时最后回车scroll_document上下滚动用PageDown/PageUp组合键左右滚动则通过注入 JSwindow.scrollBy(±视口宽度/2, 0)按 50% 视口宽度平移scroll_at把鼠标移到指定坐标后用mouse.wheel(dx, dy)按magnitude量滚动适合滚动页面内局部容器go_back/go_forward/navigate/search分别对应历史后退、前进、跳转任意 URL、跳转搜索引擎首页drag_and_dropmouse.down()→ 移动到目标坐标 →mouse.up()完成拖放current_state每次操作后的「观测」步骤——先wait_for_load_state()再额外time.sleep(0.5)源码注释说明即使 Playwright 报告已加载渲染可能仍未完成最后截 PNG 截图并连同当前 URL 组成ComputerState返回。鼠标高亮当highlight_mouseTrue时highlight_mouse()会向页面注入一段 JS在点击位置创建一个 20px 红色圆圈pointerEvents: none2 秒后隐藏并在操作前停留 1 秒方便人类观察者确认 Agent 点在哪里。ComputerUseToolset框架侧的核心机制示例代码只写了ComputerUseToolset(computercomputer_with_profile)真正的魔法发生在 src/google/adk/tools/computer_use/computer_use_toolset.py。自动把 computer 方法暴露为工具get_tools()computer_use_toolset.py#L235-L295通过反射遍历BaseComputer的所有公开方法把每一个方法包装成一个ComputerUseTool。默认排除集合为EXCLUDED_METHODS {screen_size, environment, close, prepare}也就是说BaseComputer接口中定义的open_web_browser、click_at、hover_at、type_text_at、scroll_document、scroll_at、wait、go_back、go_forward、search、navigate、key_combination、drag_and_drop、current_state会自动变成模型可调用的工具。还可以构造参数excluded_predefined_functions进一步裁剪暴露给模型的工具集例如只保留导航与点击。每个方法被两层包装状态绑定包装_wrap_method_with_state_binding拦截 ADK 运行时注入的tool_context在每次调用前执行computer.prepare(tool_context)让 computer 有机会绑定会话级资源对PlaywrightComputer来说prepare是空实现但远程沙箱类 computer 会用到它。包装器还会重写函数签名以显式加入tool_context参数——源码注释解释了原因FunctionTool会按签名过滤参数URL 校验包装仅针对navigate见下节。工具构造时机是惰性的get_tools()首次被调用LLM 请求处理前才会执行await self._computer.initialize()真正启动浏览器_ensure_initializedcomputer_use_toolset.py#L78-L81。在 LLM 请求中注入 computer use 配置process_llm_request()computer_use_toolset.py#L297-L353除了把每个工具放入llm_request.tools_dict还会向GenerateContentConfig.tools追加一个types.Tool(computer_usetypes.ComputerUse(...))配置项其中environment取自computer.environment()的返回值示例中为ENVIRONMENT_BROWSERexcluded_predefined_functions透传构造参数。这个配置项是 computer use 专用模型识别「这是一个浏览器环境任务」的信号同时幂等——若请求中已存在computer_use配置则直接返回。navigate 的 URL 安全校验navigate是唯一在框架层被拦截校验的工具_wrap_navigate_with_url_validationcomputer_use_toolset.py#L131-L165。模型给出的 URL 在交给浏览器之前会检查URL 必须是字符串且主机名中不允许出现反斜杠源码注释指出浏览器与urlparse对http://169.254.169.254\example.com/这类构造的解析结果不一致宁可拒绝默认禁止目标为私有/链路本地地址如169.254.169.254元数据端点拒绝时复用load_web_page的_is_blocked_hostname与 DNS 解析通过asyncio.to_thread避免阻塞事件循环校验失败时不会抛异常而是返回{error: navigate refused: url must be http(s) and must not target a private or link-local address., url: 当前页面URL}——注释说明是因为 computer use 模型会拒绝缺少 url 的 function response所以附带当前页面 URL。如果 Agent 确实要操作 localhost 或内网地址构造ComputerUseToolset时把allow_private_network_accessTrue即可关闭该校验。虚拟坐标系归一化computer_use_tool.py 中的ComputerUseTool继承自FunctionTool核心设计是模型统一在一个1000x1000 虚拟坐标系里输出坐标virtual_screen_size默认(1000, 1000)执行前由框架按比例换算到真实屏幕尺寸并裁剪到边界内normalized int(x / self._coordinate_space[0] * self._screen_size[0]) return max(0, min(normalized, self._screen_size[0] - 1))computer_use_tool.py#L87-L103run_async()会对参数中的x、y、destination_x、destination_y做归一化然后调用底层 computer 方法computer_use_tool.py#L105-L166。返回值若为ComputerState会被转成{image: {mimetype: image/png, data: base64}, url: ...}交给模型——这就是「截图驱动」的观测回路模型看到的就是 PNG 截图。这也解释了 README Notes 中「Screenshots are taken to help the agent understand the current state」的实现来源。安全确认safety confirmationrun_async()还内置了 human-in-the-loop 拦截当模型在参数中返回safety_decision.decision require_confirmation时工具会调用tool_context.request_confirmation(hint...)请求人工批准并返回「请批准或拒绝」的占位结果若确认请求被拒绝则返回{error: This tool call is rejected.}computer_use_tool.py#L111-L132。批准执行后响应中还会附带safety_acknowledgement字段。相关行为在单元测试 tests/unittests/tools/computer_use/test_computer_use_tool.py 中有覆盖。BaseComputer 接口工具全集一览base_computer.py 定义了整个 computer use 体系的标准接口。除抽象方法外还提供两个非抽象的扩展点prepare(tool_context)每次工具调用前的会话级资源准备与initialize()/close()资源生命周期ComputerUseToolset.close()会级联调用computer.close()。ComputerStatebase_computer.py#L43-L56是一个 pydantic 模型包含screenshotPNG 字节与url两个字段。从接口文档串来看模型可获得的工具语义如下工具方法参数语义open_web_browser无打开/聚焦浏览器并返回当前状态click_atx, y在坐标点击hover_atx, y悬停可展开悬停子菜单type_text_atx, y, text, press_enterTrue, clear_before_typingTrue在坐标处输入文本默认先清空、后回车scroll_documentdirection ∈ up/down/left/right整页滚动scroll_atx, y, direction, magnitude指定位置按幅度滚动waitseconds等待未完成页面流程go_back/go_forward无浏览器历史后退/前进search无跳转搜索引擎首页navigateurl直接跳转指定 URL默认带私有地址校验key_combinationkeys: list[str]按键及组合如[Control, A]drag_and_dropx, y, destination_x, destination_y拖放current_state无仅取当前截图与 URL不执行动作坐标均按「缩放到屏幕宽高」的绝对值解释由于ComputerUseTool会做 1000x1000 → 实际尺寸的换算自定义 computer 时只需按真实像素实现即可。技术细节汇总综合 README 与源码该示例的关键技术参数为模型gemini-2.5-computer-use-preview-10-2025Google 的 computer use 预览模型注意这是 preview 版本行为与可用性以 Google 侧发布为准浏览器Playwright 驱动的自动化 ChromiumheadlessFalse窗口可见屏幕尺寸1280x936由PlaywrightComputer(screen_size(1280, 936))决定并通过set_viewport_size生效工具ComputerUseToolset自动暴露截图、点击、输入、滚动等浏览器控制工具运行环境声明为ENVIRONMENT_BROWSER实验特性标记ComputerUseToolset、ComputerUseTool、BaseComputer等类型在源码中均带有experimental(FeatureName.COMPUTER_USE)装饰器表示该功能模块属于实验特性接口可能有变动。故障排查沿用 README 的排查清单并结合源码补充定位线索Playwright 找不到浏览器确认先后执行过playwright install-deps chromium和playwright install chromium依赖缺失核对 requirements.txt 中全部包已安装playwright1.52.0与浏览器版本需匹配浏览器崩溃确认系统支持 Chromium 且资源内存/显示环境充足。注意本示例是headlessFalse模式在无显示器的服务器上可能无法正常弹出窗口权限错误确认当前用户有运行浏览器自动化的权限另外首次运行会自动在系统临时目录创建browser_profile_for_adkprofile 目录请保证临时目录可写。延伸阅读同一接口的其他环境BaseComputer是插件式的PlaywrightComputer只是其中一种实现。仓库中 contributing/samples/integrations/sandbox_computer_use/agent.py 演示了用AgentEngineSandboxComputer在远程 Vertex AI Agent Engine 沙箱中运行同一套ComputerUseToolset——组装方式完全一致ComputerUseToolset(computersandbox_computer)只是把本地 Playwright 换成了远程沙箱 computer并通过.env环境变量注入项目 ID、服务账号与沙箱参数。这说明「computer 可替换、toolset 不变」是该模块的核心设计。注意事项Agent 运行在受控的浏览器环境中浏览器窗口可见操作过程可人工监督每次工具调用后都会截图模型据此理解当前页面状态并规划下一步执行中模型会持续汇报其动作与进度复杂任务如跨多站点的航班搜索需要多轮「截图—决策—操作」循环耗时较长请耐心等待。【免费下载链接】adk-pythonAn open-source, code-first Python toolkit for building, evaluating, and deploying sophisticated AI agents with flexibility and control.项目地址: https://gitcode.com/GitHub_Trending/ad/adk-python创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
