ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

在 macOS 上构建你自己的 Computer-Use Operator:基于 cua-agent 框架的实战指南(Part 2)

在 macOS 上构建你自己的 Computer-Use Operator:基于 cua-agent 框架的实战指南(Part 2) 在 macOS 上构建你自己的 Computer-Use Operator基于 cua-agent 框架的实战指南Part 2【免费下载链接】cuaScale computer-use 2.0 with open-source drivers, cross-OS fleets, and benchmarks for training, evaluation, and data generation.项目地址: https://gitcode.com/GitHub_Trending/cua/cua本篇是《Build Your Own Operator on macOS》系列的第二部分。在 Part 1 中我们用computer-use-preview模型和 cua-computer 包从零手写了 Computer-Use 控制循环。本部分将改用 cua-agent 高层框架它自动封装了虚拟机交互、截图处理、模型通信与动作执行的全部复杂度让你把精力放在“定义任务”而不是“实现机制”上。读完本文你将掌握四种 Agent Loop 的选型、安装配置、本地模型接入、多任务编排、结构化响应解析以及如何用 Gradio 为你的 Operator 加上可视化界面。前置准备开始之前请确认满足以下条件与本仓库当前代码要求一致已完成 Part 1 的环境准备Lume CLI 已安装macOS Cua 镜像已拉取Python 3.10。注意本仓库 libs/python/agent/pyproject.toml 中requires-python 3.11,3.14建议直接使用 Python 3.11 或 3.12 以获得最佳兼容性OpenAI 和/或 Anthropic 的 API Key使用本地模型时可选预计耗时 3045 分钟。cua-agent 框架是什么cua-agent是一个基于 liteLLM 的 Computer-Use 框架仓库中对应 libs/python/agent包版本 0.8.4核心定位是“用高层抽象替代手工控制循环”。它提供多 Provider 支持OpenAI、Anthropic、UI-TARS、本地模型Ollama以及任意 OpenAI 兼容端点LM Studio、vLLM、LocalAI、OpenRouter、Groq 等灵活的 Loop 类型针对不同模型的交互模式提供专门优化结构化响应遵循 OpenAI Agent SDKResponses API规范的统一输出便于解析、日志与监控本地模型支持以低成本运行本地模型Gradio UI可选的图形化交互界面。从源码看框架的入口是ComputerAgent类libs/python/agent/cua_agent/agent.py它通过装饰器注册机制自动为模型匹配对应的 Agent Loop每个 Loop 用register_agent(models正则, priority..., tool_type...)注册见 libs/python/agent/cua_agent/decorators.pyfind_agent_config()按优先级顺序匹配模型名并实例化对应的 Loop 类。这解释了为什么你在代码里只需传modelopenai/computer-use-preview框架就能自动选中正确的循环实现。安装从你的 Python 3.10 环境运行# 全部功能 pip install cua-agent[all] # 或按需安装 pip install cua-agent[openai] # OpenAI 支持 pip install cua-agent[anthropic] # Anthropic 支持 pip install cua-agent[uitars] # UI-TARS 支持 pip install cua-agent[omni] # OmniParser VLMs 支持 pip install cua-agent[ui] # Gradio UI各 extra 的具体依赖可以对照 libs/python/agent/pyproject.toml例如omni引入cua-somSet-of-Marks 检测uitars在 macOS 上可选mlx-vlmall聚合了 torch/transformers、gradio、gemini、qwen 等全部依赖。如果只是云端/容器场景做 API 调用还可以用轻量的cua-agent[cloud]避免安装本地推理依赖。搭建运行环境创建项目目录mkdir cua-agent-tutorial cd cua-agent-tutorial创建 Python 环境任选其一# Option Aconda conda create -n cua-agent python3.10 conda activate cua-agent # Option BAnaconda Navigator UI # 左侧 Environments → Create → 命名 cua-agent → 选择 Python 3.10 → Create # 创建后选中该环境并点击 Open Terminal # Option Cvenv python -m venv cua-env source cua-env/bin/activate # macOS/Linux安装依赖pip install cua-agent[all]设置 API Key 环境变量export OPENAI_API_KEYyour_openai_key_here export ANTHROPIC_API_KEYyour_anthropic_key_here创建 Python 脚本或 VS Code notebook.ipynb在单元中运行示例代码。理解 Agent LoopAgent Loop 是 cua-agent 的核心抽象实现了 AI 模型与计算机环境之间的连续交互循环捕获计算机状态的截图处理截图可带 UI 元素检测将视觉上下文连同任务指令发送给模型接收模型的动作决策在环境中安全执行动作重复直到任务完成。框架为你处理了错误处理、重试、上下文管理和模型特有的交互模式。四种 Agent LoopAgent Loop支持模型描述Set-Of-MarksAgentLoop.OPENAI•computer_use_preview使用 OpenAI Operator Cua Preview 模型不需要AgentLoop.ANTHROPIC•claude-sonnet-4-5-20250929•claude-3-7-sonnet-20250219使用 Anthropic Computer-Use Beta Tools不需要AgentLoop.UITARS•ByteDance-Seed/UI-TARS-1.5-7B使用字节跳动 UI-TARS 1.5 模型不需要AgentLoop.OMNI•claude-sonnet-4-5-20250929•claude-3-7-sonnet-20250219•gpt-4.5-preview•gpt-4o•gpt-4•phi4•phi4-mini•gemma3•...• 任意 Ollama 或 OpenAI 兼容模型用 OmniParser 做像素级元素检测SoM任意 VLM 做 UI Grounding 与推理OmniParser在仓库当前实现中libs/python/agent/cua_agent/loops 目录下的 Loop 实现已远超四种还包含 gemini、qwen、internvl、moondream3、GLM-4.5V、Holo、Gelato、GTA1、FARA、OpenCUA、Yutori 等并注册了对应的模型正则如 openai.py 匹配computer-use-preview、anthropic.py 匹配claude-*、omniparser.py 匹配omniparser*/omni*、uitars.py 匹配ui-tars。这意味着你甚至可以通过omnigoogle/gemini-...这类组合语法让任意视觉模型获得 Computer-Use 能力。为什么需要不同的 Agent Loop不同模型有各自独特的 API 结构、响应格式和约定OpenAI Loop使用 Responses API以特定的computer_call_output格式在动作后回传截图需要处理安全检查pending_safety_checks并用previous_response_id维护请求链Anthropic Loop实现多智能体循环模式支持 Anthropic / Bedrock / Vertex 等多种 API 提供商具备 token 管理与 prompt cachingUI-TARS Loop自定义消息格式用 “box token” 系统从文本响应中解析 UI 元素标识对应的动作OMNI Loop用 Microsoft OmniParser 生成 UI 的 Set-of-MarksSoM表示使任意视觉语言模型无需专门的 UI 训练即可操作界面——这是对预算敏感或没有原生 computer-use 模型时最灵活的选择。这些抽象让你无需改动应用代码即可切换 Provider。选择哪个 Loop不仅取决于 API 访问权限还取决于具体任务的形态桌面、浏览器还是移动端。Computer-Use 模型能力对比不同模型在各类任务上的表现差异显著。以下基准评估衡量 Agent 在不同计算环境中遵循指令、完成真实世界任务的能力数据来自原文档用于帮助选型不作为本项目自身的评测结论基准类型基准UI-TARS-1.5OpenAI CuaClaude 3.7此前 SOTA人类Computer UseOSworld (100 步)42.536.42838.1 (200 步)72.4Windows Agent Arena (50 步)42.1--29.8-Browser UseWebVoyager84.88784.187-Online-Mind2web75.87162.971-Phone UseAndroid World64.2--59.5-何时选择哪种 LoopAgentLoop.OPENAI拥有 OpenAI Tier 3 访问权限、需要做浏览器类任务时选择在浏览器基准上表现强劲AgentLoop.ANTHROPIC拥有 Anthropic API 且需要强推理能力时选择使用claude-sonnet-4-5-20250929与claude-3-7-sonnet-20250219AgentLoop.UITARS需要更强的 OS/桌面级、低延迟自动化时选择——UI-TARS-1.5 在 OS 能力基准上领先需本地运行或通过兼容端点如 Hugging Face访问AgentLoop.OMNI预算敏感或需要本地/开源模型时选择几乎兼容任何视觉语言模型。创建你的第一个 Computer-Use Agentimport asyncio from computer import Computer from cua_agent import ComputerAgent async def run_simple_task(): async with Computer() as macos_computer: # 使用 OpenAI Loop 创建 Agent agent ComputerAgent( modelopenai/computer-use-preview, tools[macos_computer] ) # 定义一个简单任务 task Open Safari and search for Python tutorials # 运行任务并处理响应 async for result in agent.run(task): print(fAction: {result.get(text)}) if __name__ __main__: asyncio.run(run_simple_task())保存为simple_task.py后运行python simple_task.py代码会初始化 macOS 虚拟机、创建 Agent 并执行“打开 Safari 搜索 Python 教程”。也可以把代码去掉if __name__ __main__:部分放入 VS Code notebook 单元运行。对比 Part 1 的手写实现几十行控制循环缩减为寥寥几行。后台机制run() 里发生了什么ComputerAgent.run()是异步生成器libs/python/agent/cua_agent/agent.py。其主循环在内部解析传入消息_process_input把 Computer 对象与自定义函数统一转成工具 schema_process_tools支持sandboxed()装饰的函数见 libs/python/agent/example.py调用_predict_step_with_retry()执行模型推理对限流、超时、5xx 等瞬时错误做指数退避重试默认最多 3 次max_retries参数可调对返回的computer_call类型条目通过computer_handler执行对应动作点击、拖拽、按键、滚动等动作后按screenshot_delay默认 0.5 秒截图并回传computer_call_output形成视觉闭环对function_call条目执行自定义工具并把结果包装成function_call_output重复直到模型输出terminate动作或达到终止条件。这套机制与 Part 1 手写的循环完全同构但错误重试、动作映射、消息链维护都由框架承担。多任务编排框架的另一优势是轻松串联多个任务无需手动管理任务间状态import asyncio from computer import Computer from cua_agent import ComputerAgent async def run_multi_task_workflow(): async with Computer() as macos_computer: agent ComputerAgent( modelanthropic/claude-sonnet-4-5-20250929, tools[macos_computer] ) tasks [ Open Safari and go to github.com, Search for trycua/cua, Open the repository page, Click on the Issues tab, Read the first open issue ] for i, task in enumerate(tasks): print(f\nTask {i1}/{len(tasks)}: {task}) async for result in agent.run(task): if result.get(text): print(f → {result.get(text)}) print(f✅ Task {i1} completed) if __name__ __main__: asyncio.run(run_multi_task_workflow())运行前确认 Anthropic API Key 已设置然后python multi_task.py。由于 Agent 在任务之间维持视觉上下文复杂序列动作的成功率更高。理解响应格式每次动作都会返回遵循 OpenAI Agent SDK 规范的结构化响应。完整的响应读取方式如下async for result in agent.run(task): # 基本信息 print(fResponse ID: {result.get(id)}) print(fResponse Text: {result.get(text)}) # 详细的 token 用量统计 usage result.get(usage) if usage: print(fInput Tokens: {usage.get(input_tokens)}) print(fOutput Tokens: {usage.get(output_tokens)}) # 推理过程与动作 for output in result.get(output, []): if output.get(type) reasoning: print(fReasoning: {output.get(summary, [{}])[0].get(text)}) elif output.get(type) computer_call: action output.get(action, {}) print(fAction: {action.get(type)} at ({action.get(x)}, {action.get(y)}))在仓库中computer_call、reasoning、message、function_call等条目类型均由 libs/python/agent/cua_agent/responses.py 构造动作类型覆盖click、double_click、drag、keypress、move、screenshot、scroll、wait等。结构化格式带来的收益记录 Agent 动作的详细信息向用户提供实时反馈追踪 token 用量以监控成本获取决策背后的推理过程便于调试与解释。使用本地模型OMNI 循环OMNI 循环配合 OmniParser 与本地模型能大幅降低成本并保持可接受的可靠性。安装 Ollama 并拉取 Gemma 3 模型ollama pull gemma3:4b-it-q4_K_M创建local_model.pyimport asyncio from computer import Computer from cua_agent import ComputerAgent async def run_with_local_model(): async with Computer() as macos_computer: agent ComputerAgent( modelomniparserollama_chat/gemma3, tools[macos_computer] ) task Open the Calculator app and perform a simple calculation async for result in agent.run(task): print(fAction: {result.get(text)}) if __name__ __main__: asyncio.run(run_with_local_model())运行python local_model.py使用 OAICOMPAT Provider 连接任意本地端点任何遵循 OpenAI API 结构的端点都能接入agent ComputerAgent( modelLLM( providerLLMProvider.OAICOMPAT, namegemma-3-12b-it, provider_base_urlhttp://localhost:1234/v1 # LM Studio 端点 ), tools[macos_computer] )常见本地端点LM Studiohttp://localhost:1234/v1vLLMhttp://localhost:8000/v1LocalAIhttp://localhost:8080/v1OllamaOpenAI 兼容模式http://localhost:11434/v1注意Ollama 的原生聊天协议不支持图片输入。仓库源码在 agent.py 中内置了“Ollama 图像输入守卫”——当模型名含ollama/或ollama_chat/且消息含image_url时直接报错提醒你改用视觉模型或omniparserollama_chat/...组合。这是使用本地模型时最值得注意的坑。该方案的适用场景无 API 成本的开发测试、无法访问外部 API 的离线/隔离环境、数据不能出内网的隐私敏感应用、以及探索哪种模型最适合你的场景。部署并使用 UI-TARSUI-TARS 是字节跳动的 Computer-Use 模型擅长 OS 级界面导航在 OSworld、Windows Agent Arena 等 OS 级基准上表现最佳。部署选项本地部署按其部署指南在本地运行模型Hugging Face Endpoint部署到 HF Inference Endpoints获得形如https://**************.us-east-1.aws.endpoints.huggingface.cloud/v1的 URL接入 cua-agentagent ComputerAgent( modelLLM( providerLLMProvider.OAICOMPAT, nametgi, provider_base_urlhttps://**************.us-east-1.aws.endpoints.huggingface.cloud/v1 ), tools[macos_computer] )在仓库中UI-TARS 的本地加载还有一条huggingface-local/ByteDance-Seed/UI-TARS-1.5-7B路径见 libs/python/agent/example.py通过HuggingFaceLocalAdapter与 liteLLM 自定义 provider 映射agent.py注册。深入理解 Agent 响应run()产出的结构化响应信息非常丰富完整解析如下async for result in agent.run(task): # 基本 ID 与文本 print(Response ID:, result.get(id)) print(Response Text:, result.get(text)) # Token 用量统计 usage result.get(usage) if usage: print(\nUsage Details:) print(f Input Tokens: {usage.get(input_tokens)}) if input_tokens_details in usage: print(f Input Tokens Details: {usage.get(input_tokens_details)}) print(f Output Tokens: {usage.get(output_tokens)}) if output_tokens_details in usage: print(f Output Tokens Details: {usage.get(output_tokens_details)}) print(f Total Tokens: {usage.get(total_tokens)}) # 详细推理与动作 outputs result.get(output, []) for output in outputs: output_type output.get(type) if output_type reasoning: print(\nReasoning:) for summary in output.get(summary, []): print(f {summary.get(text)}) elif output_type computer_call: action output.get(action, {}) print(\nComputer Action:) print(f Type: {action.get(type)}) print(f Position: ({action.get(x)}, {action.get(y)})) if action.get(text): print(f Text: {action.get(text)})这些细节对调试、日志记录和理解 Agent 在 agentic 系统中的决策过程非常宝贵。构建 Gradio UI包内附带 Gradio UI实现见 libs/python/agent/cua_agent/ui/gradio/app.py提供模型 Provider 选择、Agent Loop 选择、任务输入框、VM 截图实时显示与动作历史。创建launch_ui.pyfrom cua_agent.ui.gradio.app import create_gradio_ui if __name__ __main__: app create_gradio_ui() app.launch(shareFalse) # shareFalse 仅本机访问安装 UI 依赖并运行pip install cua-agent[ui] python launch_ui.py浏览器打开显示的地址通常为 http://127.0.0.1:7860。创建可共享链接可选if __name__ __main__: app create_gradio_ui() app.launch(shareTrue) # 生成公共链接运行后 Gradio 会同时显示本地与公共地址Running on local URL: http://127.0.0.1:7860 Running on public URL: https://abcd1234.gradio.live安全提示公共链接的任何访问者都能完整操控你的 Agent建议加基本认证app.launch(shareTrue, auth(username, password))仅用于个人或团队使用不要用于生产环境停止 Gradio 应用后临时链接即失效。为 UI 设置 API Keyexport OPENAI_API_KEYyour_openai_key_here export ANTHROPIC_API_KEYyour_anthropic_key_here # 两者都设置时 OPENAI_API_KEYyour_key ANTHROPIC_API_KEYyour_key python launch_ui.pyUI 设置的持久化Gradio UI 会自动保存配置Agent Loop、模型选择、自定义 Base URL 等到项目根目录的.gradio_settings.json重启后自动加载。仓库源码在 app.py 中通过load_settings()/save_settings()实现且save_settings()会显式剔除provider_api_key字段——即API Key 出于安全原因不会被保存。建议将.gradio_settings.json加入.gitignore。高级示例GitHub 仓库工作流import asyncio import logging from computer import Computer from cua_agent import ComputerAgent async def github_workflow(): async with Computer(verbositylogging.INFO) as macos_computer: agent ComputerAgent( modelopenai/computer-use-preview, save_trajectoryTrue, # 保存截图用于调试 only_n_most_recent_images3, # 上下文中仅保留最近 3 张图 verbositylogging.INFO, tools[macos_computer] ) tasks [ Look for a repository named trycua/cua on GitHub., Check the open issues, open the most recent one and read it., Clone the repository in users/lume/projects if it doesnt exist yet., Open the repository with Cursor (on the dock, black background and white cube icon)., From Cursor, open Composer if not already open., Focus on the Composer text area, then write and submit a task to help resolve the GitHub issue., ] for i, task in enumerate(tasks): print(f\nExecuting task {i1}/{len(tasks)}: {task}) async for result in agent.run(task): print(fAction: {result.get(text)}) print(f✅ Task {i1}/{len(tasks)} completed) if __name__ __main__: asyncio.run(github_workflow())设置OPENAI_API_KEY后运行python github_workflow.py观察 Agent 完整执行搜索 GitHub → 调研 issue → clone 仓库 → 用 Cursor 打开 → 借助 Cursor 的 AI 能力撰写解决方案。关键参数说明示例中的only_n_most_recent_images3会通过ImageRetentionCallback裁剪消息历史中的截图数量控制上下文长度与成本save_trajectoryTrue对应源码中的trajectory_dir参数通过TrajectorySaverCallback保存轨迹截图与响应供事后分析见 libs/python/agent/cua_agent/agent.py。此外框架还支持max_trajectory_budget通过 budget_manager.py 的BudgetManagerCallback按美元成本限制总开销超支可抛错或优雅停止示例max_trajectory_budget{max_budget: 1.0, raise_error: True, reset_after_each_run: False}use_prompt_cachingTrue针对 Anthropic 系 Provider 启用 prompt caching避免重复处理相同提示instructions注入系统指令通过PromptInstructionsCallback附加到每次 LLM 调用api_key/api_base在构造器或run()中覆盖 Provider 凭证。两种实现方式对比手动实现Part 1需要为交互循环编写自定义代码需显式处理不同动作类型需直接管理 OpenAI API 调用基础功能约 50100 行代码局限于 OpenAI computer-use 模型。框架实现Part 2抽象交互循环自动处理所有动作类型内部管理 API 调用同样功能仅需 1015 行代码支持多模型 Provider内置 UI 能力。结论cua-agent把复杂的 Computer-Use 构建任务转化为简洁的高层接口。它替你承担了技术细节让你专注于定义任务本身。何时选择哪种方式手动实现Part 1需要完全掌控交互循环或正在实现定制化方案时框架Part 2绝大多数希望快速构建和部署 Computer-Use Agent 的场景。下一步探索方向用更多参数自定义 Agent 行为预算控制、轨迹保存、图像保留策略、PII 匿名化回调等见 libs/python/agent/cua_agent/callbacks构建跨多个应用的复杂工作流将 Agent 集成到其他应用中HUD、playground、proxy 等子模块见 libs/python/agent/cua_agent为开源项目贡献代码。【免费下载链接】cuaScale computer-use 2.0 with open-source drivers, cross-OS fleets, and benchmarks for training, evaluation, and data generation.项目地址: https://gitcode.com/GitHub_Trending/cua/cua创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表