Claude Computer Use
Anthropic 官方桌面自动化 API(beta)。通过截屏 + Claude 视觉理解 + 坐标操作控制任意桌面应用。
何时使用
这是终极后备方案,仅在以下情况使用:
- peekaboo (macOS) / pywinauto (Windows) / browser (网页) 无法操作目标应用
- 需要视觉判断(看屏幕内容决定下一步)
- 目标应用不暴露 Accessibility API
- 用户明确要求精确坐标控制
优先使用轻量方案(成本更低、速度更快):
- 网页 → browser tool
- macOS 桌面 → peekaboo
- Windows 桌面 → pywinauto
支持的操作
| 操作 |
说明 |
| screenshot |
截取当前屏幕 |
| left_click |
在坐标 [x, y] 点击 |
| right_click |
右键点击 |
| double_click |
双击 |
| triple_click |
三击(全选文本) |
| middle_click |
中键点击 |
| mouse_move |
移动鼠标到坐标 |
| left_click_drag |
拖拽(从当前位置到目标坐标) |
| scroll |
滚动(方向 + 数量) |
| type |
输入文本 |
| key |
按键/组合键(如 "ctrl+s") |
| hold_key |
按住某键指定时长 |
| wait |
等待指定秒数 |
工作流程
循环:
1. 截屏 (screencapture / pyautogui.screenshot)
2. 发送截图给 Claude Computer Use API
3. Claude 分析截图,返回 tool_use (action + coordinates)
4. 在本地执行操作 (cliclick/xdotool/pyautogui)
5. 如果任务未完成,回到步骤 1
完整示例
macOS 实现
import anthropic
import subprocess
import base64
import json
client = anthropic.Anthropic()
def screenshot():
"""截取 macOS 屏幕"""
subprocess.run(["screencapture", "-x", "/tmp/screen.png"], check=True)
with open("/tmp/screen.png", "rb") as f:
return base64.b64encode(f.read()).decode()
def execute_action(action_type, **kwargs):
"""执行鼠标/键盘操作 (macOS 使用 cliclick 或 AppleScript)"""
if action_type == "left_click":
x, y = kwargs["coordinate"]
subprocess.run(["cliclick", f"c:{x},{y}"])
elif action_type == "type":
text = kwargs["text"]
subprocess.run(["cliclick", f"t:{text}"])
elif action_type == "key":
key = kwargs["key"]
# 通过 AppleScript 发送按键
subprocess.run(["osascript", "-e",
f'tell application "System Events" to keystroke "{key}"'])
elif action_type == "scroll":
direction = kwargs.get("direction", "down")
amount = kwargs.get("amount", 3)
delta = -amount if direction == "down" else amount
# AppleScript 模拟滚动
subprocess.run(["osascript", "-e",
f'tell application "System Events" to scroll area 1 by {delta}'])
elif action_type == "mouse_move":
x, y = kwargs["coordinate"]
subprocess.run(["cliclick", f"m:{x},{y}"])
elif action_type == "screenshot":
pass # 下一轮循环自动截屏
def computer_use_loop(task: str, max_iterations: int = 10):
"""Computer Use 主循环"""
messages = [{"role": "user", "content": [
{"type": "text", "text": task}
]}]
for i in range(max_iterations):
# 1. 截屏
img_b64 = screenshot()
# 2. 追加截图到消息
if i > 0:
messages.append({"role": "user", "content": [
{"type": "tool_result", "tool_use_id": tool_use_id,
"content": [{"type": "image", "source": {
"type": "base64", "media_type": "image/png", "data": img_b64
}}]}
]})
else:
messages[0]["content"].append({
"type": "image", "source": {
"type": "base64", "media_type": "image/png", "data": img_b64
}
})
# 3. 调用 Claude Computer Use API
response = client.beta.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
tools=[{
"type": "computer_20250124",
"name": "computer",
"display_width_px": 1920,
"display_height_px": 1080,
}],
messages=messages,
betas=["computer-use-2025-01-24"],
)
# 4. 解析响应
messages.append({"role": "assistant", "content": response.content})
# 检查是否完成
if response.stop_reason == "end_turn":
print("任务完成")
break
# 5. 执行操作
for block in response.content:
if block.type == "tool_use":
tool_use_id = block.id
action = block.input.get("action")
print(f" 执行: {action} {block.input}")
execute_action(action, **block.input)
return messages
Windows 实现
import pyautogui
import time
def screenshot_win():
"""截取 Windows 屏幕"""
img = pyautogui.screenshot()
img.save("/tmp/screen.png")
with open("/tmp/screen.png", "rb") as f:
return base64.b64encode(f.read()).decode()
def execute_action_win(action_type, **kwargs):
"""执行操作 (Windows 使用 pyautogui)"""
if action_type == "left_click":
x, y = kwargs["coordinate"]
pyautogui.click(x, y)
elif action_type == "right_click":
x, y = kwargs["coordinate"]
pyautogui.rightClick(x, y)
elif action_type == "double_click":
x, y = kwargs["coordinate"]
pyautogui.doubleClick(x, y)
elif action_type == "type":
pyautogui.typewrite(kwargs["text"], interval=0.02)
elif action_type == "key":
pyautogui.hotkey(*kwargs["key"].split("+"))
elif action_type == "scroll":
amount = kwargs.get("amount", 3)
direction = kwargs.get("direction", "down")
clicks = -amount if direction == "down" else amount
x, y = kwargs.get("coordinate", (960, 540))
pyautogui.scroll(clicks, x, y)
elif action_type == "mouse_move":
x, y = kwargs["coordinate"]
pyautogui.moveTo(x, y)
elif action_type == "left_click_drag":
sx, sy = kwargs.get("start_coordinate", pyautogui.position())
x, y = kwargs["coordinate"]
pyautogui.moveTo(sx, sy)
pyautogui.drag(x - sx, y - sy, duration=0.5)
API 参数
tools=[{
"type": "computer_20250124", # 或 computer_20251124 (Opus 4.6)
"name": "computer",
"display_width_px": 1920, # 屏幕宽度
"display_height_px": 1080, # 屏幕高度
"display_number": 1, # X11 显示号(可选)
}]
betas=["computer-use-2025-01-24"] # 或 computer-use-2025-11-24 (Opus 4.6)
成本估算
- 每次截屏约 1000-3000 tokens(取决于分辨率)
- 典型任务(5-10 次截屏循环):约 10,000-30,000 tokens
- 建议:降低截屏分辨率(1280x800 效果最佳)可显著减少成本
安全规则
- 每次操作前 HITL 确认:告知用户即将在屏幕上执行什么操作
- 不自动输入密码:需要登录时提示用户手动操作
- 不操作金融应用:涉及支付/转账时必须用户确认
- 限制循环次数:max_iterations 防止无限截屏循环
- 最小权限:不要给 Claude 管理员权限
1---
2name: claude-computer-use
3description: Claude Computer Use - 通过截屏+视觉理解操作任意桌面应用(精确坐标点击/滚动/拖拽/键盘/右键/双击)。终极后备方案,当 peekaboo/pywinauto/browser 无法满足时使用。
4quickstart: |
5 # 需要: ANTHROPIC_API_KEY (已配置)
6 # 截屏 → Claude 视觉分析 → 返回操作指令
7 import anthropic, subprocess, base64
8 client = anthropic.Anthropic()
9 # macOS 截屏:
10 subprocess.run(["screencapture", "-x", "/tmp/screen.png"])
11 # Windows 截屏: 用 pyautogui.screenshot() 或 PowerShell
12 img_b64 = base64.b64encode(open("/tmp/screen.png","rb").read()).decode()
13 resp = client.beta.messages.create(
14 model="claude-sonnet-4-6",
15 max_tokens=1024,
16 tools=[{"type":"computer_20250124","name":"computer",
17 "display_width_px":1920,"display_height_px":1080}],
18 messages=[{"role":"user","content":[
19 {"type":"image","source":{"type":"base64","media_type":"image/png","data":img_b64}},
20 {"type":"text","text":"描述你要执行的操作"}
21 ]}],
22 betas=["computer-use-2025-01-24"]
23 )
24 # resp.content 中包含 tool_use block,解析其 action/coordinate 执行
25metadata:
26 xiaodazi:
27 dependency_level: cloud_api
28 os: [common]
29 backend_type: local
30 user_facing: true
31---
32
33# Claude Computer Use
34
35Anthropic 官方桌面自动化 API(beta)。通过**截屏 + Claude 视觉理解 + 坐标操作**控制任意桌面应用。
36
37## 何时使用
38
39这是**终极后备方案**,仅在以下情况使用:
40
411. peekaboo (macOS) / pywinauto (Windows) / browser (网页) 无法操作目标应用
422. 需要视觉判断(看屏幕内容决定下一步)
433. 目标应用不暴露 Accessibility API
444. 用户明确要求精确坐标控制
45
46优先使用轻量方案(成本更低、速度更快):
47- 网页 → browser tool
48- macOS 桌面 → peekaboo
49- Windows 桌面 → pywinauto
50
51## 支持的操作
52
53| 操作 | 说明 |
54|---|---|
55| screenshot | 截取当前屏幕 |
56| left_click | 在坐标 [x, y] 点击 |
57| right_click | 右键点击 |
58| double_click | 双击 |
59| triple_click | 三击(全选文本) |
60| middle_click | 中键点击 |
61| mouse_move | 移动鼠标到坐标 |
62| left_click_drag | 拖拽(从当前位置到目标坐标) |
63| scroll | 滚动(方向 + 数量) |
64| type | 输入文本 |
65| key | 按键/组合键(如 "ctrl+s") |
66| hold_key | 按住某键指定时长 |
67| wait | 等待指定秒数 |
68
69## 工作流程
70
71```
72循环:
73 1. 截屏 (screencapture / pyautogui.screenshot)
74 2. 发送截图给 Claude Computer Use API
75 3. Claude 分析截图,返回 tool_use (action + coordinates)
76 4. 在本地执行操作 (cliclick/xdotool/pyautogui)
77 5. 如果任务未完成,回到步骤 1
78```
79
80## 完整示例
81
82### macOS 实现
83
84```python
85import anthropic
86import subprocess
87import base64
88import json
89
90client = anthropic.Anthropic()
91
92def screenshot():
93 """截取 macOS 屏幕"""
94 subprocess.run(["screencapture", "-x", "/tmp/screen.png"], check=True)
95 with open("/tmp/screen.png", "rb") as f:
96 return base64.b64encode(f.read()).decode()
97
98def execute_action(action_type, **kwargs):
99 """执行鼠标/键盘操作 (macOS 使用 cliclick 或 AppleScript)"""
100 if action_type == "left_click":
101 x, y = kwargs["coordinate"]
102 subprocess.run(["cliclick", f"c:{x},{y}"])
103 elif action_type == "type":
104 text = kwargs["text"]
105 subprocess.run(["cliclick", f"t:{text}"])
106 elif action_type == "key":
107 key = kwargs["key"]
108 # 通过 AppleScript 发送按键
109 subprocess.run(["osascript", "-e",
110 f'tell application "System Events" to keystroke "{key}"'])
111 elif action_type == "scroll":
112 direction = kwargs.get("direction", "down")
113 amount = kwargs.get("amount", 3)
114 delta = -amount if direction == "down" else amount
115 # AppleScript 模拟滚动
116 subprocess.run(["osascript", "-e",
117 f'tell application "System Events" to scroll area 1 by {delta}'])
118 elif action_type == "mouse_move":
119 x, y = kwargs["coordinate"]
120 subprocess.run(["cliclick", f"m:{x},{y}"])
121 elif action_type == "screenshot":
122 pass # 下一轮循环自动截屏
123
124def computer_use_loop(task: str, max_iterations: int = 10):
125 """Computer Use 主循环"""
126 messages = [{"role": "user", "content": [
127 {"type": "text", "text": task}
128 ]}]
129
130 for i in range(max_iterations):
131 # 1. 截屏
132 img_b64 = screenshot()
133
134 # 2. 追加截图到消息
135 if i > 0:
136 messages.append({"role": "user", "content": [
137 {"type": "tool_result", "tool_use_id": tool_use_id,
138 "content": [{"type": "image", "source": {
139 "type": "base64", "media_type": "image/png", "data": img_b64
140 }}]}
141 ]})
142 else:
143 messages[0]["content"].append({
144 "type": "image", "source": {
145 "type": "base64", "media_type": "image/png", "data": img_b64
146 }
147 })
148
149 # 3. 调用 Claude Computer Use API
150 response = client.beta.messages.create(
151 model="claude-sonnet-4-6",
152 max_tokens=1024,
153 tools=[{
154 "type": "computer_20250124",
155 "name": "computer",
156 "display_width_px": 1920,
157 "display_height_px": 1080,
158 }],
159 messages=messages,
160 betas=["computer-use-2025-01-24"],
161 )
162
163 # 4. 解析响应
164 messages.append({"role": "assistant", "content": response.content})
165
166 # 检查是否完成
167 if response.stop_reason == "end_turn":
168 print("任务完成")
169 break
170
171 # 5. 执行操作
172 for block in response.content:
173 if block.type == "tool_use":
174 tool_use_id = block.id
175 action = block.input.get("action")
176 print(f" 执行: {action} {block.input}")
177 execute_action(action, **block.input)
178
179 return messages
180```
181
182### Windows 实现
183
184```python
185import pyautogui
186import time
187
188def screenshot_win():
189 """截取 Windows 屏幕"""
190 img = pyautogui.screenshot()
191 img.save("/tmp/screen.png")
192 with open("/tmp/screen.png", "rb") as f:
193 return base64.b64encode(f.read()).decode()
194
195def execute_action_win(action_type, **kwargs):
196 """执行操作 (Windows 使用 pyautogui)"""
197 if action_type == "left_click":
198 x, y = kwargs["coordinate"]
199 pyautogui.click(x, y)
200 elif action_type == "right_click":
201 x, y = kwargs["coordinate"]
202 pyautogui.rightClick(x, y)
203 elif action_type == "double_click":
204 x, y = kwargs["coordinate"]
205 pyautogui.doubleClick(x, y)
206 elif action_type == "type":
207 pyautogui.typewrite(kwargs["text"], interval=0.02)
208 elif action_type == "key":
209 pyautogui.hotkey(*kwargs["key"].split("+"))
210 elif action_type == "scroll":
211 amount = kwargs.get("amount", 3)
212 direction = kwargs.get("direction", "down")
213 clicks = -amount if direction == "down" else amount
214 x, y = kwargs.get("coordinate", (960, 540))
215 pyautogui.scroll(clicks, x, y)
216 elif action_type == "mouse_move":
217 x, y = kwargs["coordinate"]
218 pyautogui.moveTo(x, y)
219 elif action_type == "left_click_drag":
220 sx, sy = kwargs.get("start_coordinate", pyautogui.position())
221 x, y = kwargs["coordinate"]
222 pyautogui.moveTo(sx, sy)
223 pyautogui.drag(x - sx, y - sy, duration=0.5)
224```
225
226## API 参数
227
228```python
229tools=[{
230 "type": "computer_20250124", # 或 computer_20251124 (Opus 4.6)
231 "name": "computer",
232 "display_width_px": 1920, # 屏幕宽度
233 "display_height_px": 1080, # 屏幕高度
234 "display_number": 1, # X11 显示号(可选)
235}]
236betas=["computer-use-2025-01-24"] # 或 computer-use-2025-11-24 (Opus 4.6)
237```
238
239## 成本估算
240
241- 每次截屏约 1000-3000 tokens(取决于分辨率)
242- 典型任务(5-10 次截屏循环):约 10,000-30,000 tokens
243- 建议:降低截屏分辨率(1280x800 效果最佳)可显著减少成本
244
245## 安全规则
246
247- **每次操作前 HITL 确认**:告知用户即将在屏幕上执行什么操作
248- **不自动输入密码**:需要登录时提示用户手动操作
249- **不操作金融应用**:涉及支付/转账时必须用户确认
250- **限制循环次数**:max_iterations 防止无限截屏循环
251- **最小权限**:不要给 Claude 管理员权限