cua-agent 0.4.34__py3-none-any.whl → 0.4.35__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of cua-agent might be problematic. Click here for more details.

Files changed (61) hide show
  1. agent/__init__.py +4 -10
  2. agent/__main__.py +2 -1
  3. agent/adapters/huggingfacelocal_adapter.py +54 -61
  4. agent/adapters/human_adapter.py +116 -114
  5. agent/adapters/mlxvlm_adapter.py +110 -99
  6. agent/adapters/models/__init__.py +14 -6
  7. agent/adapters/models/generic.py +7 -4
  8. agent/adapters/models/internvl.py +66 -30
  9. agent/adapters/models/opencua.py +23 -8
  10. agent/adapters/models/qwen2_5_vl.py +7 -4
  11. agent/agent.py +184 -158
  12. agent/callbacks/__init__.py +4 -4
  13. agent/callbacks/base.py +45 -31
  14. agent/callbacks/budget_manager.py +22 -10
  15. agent/callbacks/image_retention.py +18 -13
  16. agent/callbacks/logging.py +55 -42
  17. agent/callbacks/operator_validator.py +3 -1
  18. agent/callbacks/pii_anonymization.py +19 -16
  19. agent/callbacks/telemetry.py +67 -61
  20. agent/callbacks/trajectory_saver.py +90 -70
  21. agent/cli.py +115 -110
  22. agent/computers/__init__.py +13 -8
  23. agent/computers/base.py +26 -17
  24. agent/computers/cua.py +27 -23
  25. agent/computers/custom.py +72 -69
  26. agent/decorators.py +23 -14
  27. agent/human_tool/__init__.py +2 -7
  28. agent/human_tool/__main__.py +6 -2
  29. agent/human_tool/server.py +48 -37
  30. agent/human_tool/ui.py +235 -185
  31. agent/integrations/hud/__init__.py +15 -21
  32. agent/integrations/hud/agent.py +101 -83
  33. agent/integrations/hud/proxy.py +90 -57
  34. agent/loops/__init__.py +25 -21
  35. agent/loops/anthropic.py +537 -483
  36. agent/loops/base.py +13 -14
  37. agent/loops/composed_grounded.py +135 -149
  38. agent/loops/gemini.py +31 -12
  39. agent/loops/glm45v.py +135 -133
  40. agent/loops/gta1.py +47 -50
  41. agent/loops/holo.py +4 -2
  42. agent/loops/internvl.py +6 -11
  43. agent/loops/moondream3.py +36 -12
  44. agent/loops/omniparser.py +212 -209
  45. agent/loops/openai.py +49 -50
  46. agent/loops/opencua.py +29 -41
  47. agent/loops/qwen.py +475 -0
  48. agent/loops/uitars.py +237 -202
  49. agent/proxy/examples.py +54 -50
  50. agent/proxy/handlers.py +27 -34
  51. agent/responses.py +330 -330
  52. agent/types.py +11 -5
  53. agent/ui/__init__.py +1 -1
  54. agent/ui/__main__.py +1 -1
  55. agent/ui/gradio/app.py +23 -18
  56. agent/ui/gradio/ui_components.py +310 -161
  57. {cua_agent-0.4.34.dist-info → cua_agent-0.4.35.dist-info}/METADATA +18 -10
  58. cua_agent-0.4.35.dist-info/RECORD +64 -0
  59. cua_agent-0.4.34.dist-info/RECORD +0 -63
  60. {cua_agent-0.4.34.dist-info → cua_agent-0.4.35.dist-info}/WHEEL +0 -0
  61. {cua_agent-0.4.34.dist-info → cua_agent-0.4.35.dist-info}/entry_points.txt +0 -0
agent/loops/qwen.py ADDED
@@ -0,0 +1,475 @@
1
+ """
2
+ Qwen3-VL agent loop implementation using litellm with function/tool calling.
3
+ - Passes a ComputerUse tool schema to acompletion
4
+ - Converts between Responses items and completion messages using helpers
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from typing import Any, Dict, List, Optional, Tuple
9
+
10
+ import json
11
+ import re
12
+ import litellm
13
+ from litellm.responses.litellm_completion_transformation.transformation import (
14
+ LiteLLMCompletionResponsesConfig,
15
+ )
16
+
17
+ from ..decorators import register_agent
18
+ from ..loops.base import AsyncAgentConfig
19
+ from ..types import AgentCapability
20
+ from ..responses import (
21
+ convert_responses_items_to_completion_messages,
22
+ convert_completion_messages_to_responses_items,
23
+ )
24
+
25
+
26
+ # ComputerUse tool schema (OpenAI function tool format)
27
+ QWEN3_COMPUTER_TOOL: Dict[str, Any] = {
28
+ "type": "function",
29
+ "function": {
30
+ "name": "computer",
31
+ "description": (
32
+ "Use a mouse and keyboard to interact with a computer, and take screenshots.\n"
33
+ "* This is an interface to a desktop GUI. You do not have access to a terminal or applications menu. You must click on desktop icons to start applications.\n"
34
+ "* Some applications may take time to start or process actions, so you may need to wait and take successive screenshots to see the results of your actions. E.g. if you click on Firefox and a window doesn't open, try wait and taking another screenshot.\n"
35
+ "* The screen's resolution is 1000x1000.\n"
36
+ "* Whenever you intend to move the cursor to click on an element like an icon, you should consult a screenshot to determine the coordinates of the element before moving the cursor.\n"
37
+ "* If you tried clicking on a program or link but it failed to load, even after waiting, try adjusting your cursor position so that the tip of the cursor visually falls on the element that you want to click.\n"
38
+ "* Make sure to click any buttons, links, icons, etc with the cursor tip in the center of the element. Don't click boxes on their edges."
39
+ ),
40
+ "parameters": {
41
+ "type": "object",
42
+ "properties": {
43
+ "action": {
44
+ "description": "The action to perform.",
45
+ "enum": [
46
+ "key",
47
+ "type",
48
+ "mouse_move",
49
+ "left_click",
50
+ "left_click_drag",
51
+ "right_click",
52
+ "middle_click",
53
+ "double_click",
54
+ "triple_click",
55
+ "scroll",
56
+ "hscroll",
57
+ "screenshot",
58
+ "wait",
59
+ # "terminate",
60
+ # "answer",
61
+ ],
62
+ "type": "string",
63
+ },
64
+ "keys": {
65
+ "description": "Required only by action=key.",
66
+ "type": "array",
67
+ "items": {"type": "string"},
68
+ },
69
+ "text": {
70
+ "description": "Required only by action=type and action=answer.",
71
+ "type": "string",
72
+ },
73
+ "coordinate": {
74
+ "description": "(x, y): Pixel coordinates from top-left.",
75
+ "type": "array",
76
+ "items": {"type": ["number", "integer"]},
77
+ "minItems": 2,
78
+ "maxItems": 2,
79
+ },
80
+ "pixels": {
81
+ "description": "Scroll amount. Positive=up, negative=down. For scroll/hscroll.",
82
+ "type": "number",
83
+ },
84
+ "time": {
85
+ "description": "Seconds to wait (action=wait).",
86
+ "type": "number",
87
+ },
88
+ # "status": {
89
+ # "description": "Task status (action=terminate).",
90
+ # "type": "string",
91
+ # "enum": ["success", "failure"],
92
+ # },
93
+ },
94
+ "required": ["action"],
95
+ },
96
+ },
97
+ }
98
+
99
+ def _build_nous_system(functions: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
100
+ """Use qwen-agent NousFnCallPrompt to generate a system message embedding tool schema."""
101
+ try:
102
+ from qwen_agent.llm.fncall_prompts.nous_fncall_prompt import (
103
+ NousFnCallPrompt,
104
+ Message as NousMessage,
105
+ ContentItem as NousContentItem,
106
+ )
107
+ except ImportError:
108
+ raise ImportError("qwen-agent not installed. Please install it with `pip install cua-agent[qwen]`.")
109
+ msgs = NousFnCallPrompt().preprocess_fncall_messages(
110
+ messages=[NousMessage(role="system", content=[NousContentItem(text="You are a helpful assistant.")])],
111
+ functions=functions,
112
+ lang="en",
113
+ )
114
+ sys = msgs[0].model_dump()
115
+ # Convert qwen-agent structured content to OpenAI-style content list
116
+ content = [{"type": "text", "text": c["text"]} for c in sys.get("content", [])]
117
+ return {"role": "system", "content": content}
118
+
119
+ def _parse_tool_call_from_text(text: str) -> Optional[Dict[str, Any]]:
120
+ """Extract JSON object within <tool_call>...</tool_call> from model text."""
121
+ m = re.search(r"<tool_call>\s*(\{[\s\S]*?\})\s*</tool_call>", text)
122
+ if not m:
123
+ return None
124
+ try:
125
+ return json.loads(m.group(1))
126
+ except Exception:
127
+ return None
128
+
129
+ async def _unnormalize_coordinate(args: Dict[str, Any], dims: Tuple[int, int]) -> Dict[str, Any]:
130
+ """Coordinates appear in 0..1000 space, scale to actual screen size using dims if provided."""
131
+ coord = args.get("coordinate")
132
+ if not coord or not isinstance(coord, (list, tuple)) or len(coord) < 2:
133
+ return args
134
+ x, y = float(coord[0]), float(coord[1])
135
+ width, height = float(dims[0]), float(dims[1])
136
+ x_abs = max(0.0, min(width, (x / 1000.0) * width))
137
+ y_abs = max(0.0, min(height, (y / 1000.0) * height))
138
+ args = {**args, "coordinate": [round(x_abs), round(y_abs)]}
139
+ return args
140
+
141
+
142
+ def convert_qwen_tool_args_to_computer_action(args: Dict[str, Any]) -> Optional[Dict[str, Any]]:
143
+ """
144
+ Convert Qwen computer tool arguments to the Computer Calls action schema.
145
+
146
+ Qwen (example):
147
+ {"action": "left_click", "coordinate": [114, 68]}
148
+
149
+ Target (example):
150
+ {"action": "left_click", "x": 114, "y": 68}
151
+
152
+ Other mappings:
153
+ - right_click, middle_click, double_click (triple_click -> double_click)
154
+ - mouse_move -> { action: "move", x, y }
155
+ - key -> { action: "keypress", keys: [...] }
156
+ - type -> { action: "type", text }
157
+ - scroll/hscroll -> { action: "scroll", scroll_x, scroll_y, x, y }
158
+ - wait -> { action: "wait" }
159
+ - terminate/answer are not direct UI actions; return None for now
160
+ """
161
+ if not isinstance(args, dict):
162
+ return None
163
+
164
+ action = args.get("action")
165
+ if not isinstance(action, str):
166
+ return None
167
+
168
+ # Coordinates helper
169
+ coord = args.get("coordinate")
170
+ x = y = None
171
+ if isinstance(coord, (list, tuple)) and len(coord) >= 2:
172
+ try:
173
+ x = int(round(float(coord[0])))
174
+ y = int(round(float(coord[1])))
175
+ except Exception:
176
+ x = y = None
177
+
178
+ # Map actions
179
+ a = action.lower()
180
+ if a in {"left_click", "right_click", "middle_click", "double_click"}:
181
+ if x is None or y is None:
182
+ return None
183
+ return {"action": a, "x": x, "y": y}
184
+ if a == "triple_click":
185
+ # Approximate as double_click
186
+ if x is None or y is None:
187
+ return None
188
+ return {"action": "double_click", "x": x, "y": y}
189
+ if a == "mouse_move":
190
+ if x is None or y is None:
191
+ return None
192
+ return {"action": "move", "x": x, "y": y}
193
+ if a == "key":
194
+ keys = args.get("keys")
195
+ if isinstance(keys, list) and all(isinstance(k, str) for k in keys):
196
+ return {"action": "keypress", "keys": keys}
197
+ return None
198
+ if a == "type":
199
+ text = args.get("text")
200
+ if isinstance(text, str):
201
+ return {"action": "type", "text": text}
202
+ return None
203
+ if a in {"scroll", "hscroll"}:
204
+ pixels = args.get("pixels") or 0
205
+ try:
206
+ pixels_val = int(round(float(pixels)))
207
+ except Exception:
208
+ pixels_val = 0
209
+ scroll_x = pixels_val if a == "hscroll" else 0
210
+ scroll_y = pixels_val if a == "scroll" else 0
211
+ # Include cursor position if available (optional)
212
+ out: Dict[str, Any] = {"action": "scroll", "scroll_x": scroll_x, "scroll_y": scroll_y}
213
+ if x is not None and y is not None:
214
+ out.update({"x": x, "y": y})
215
+ return out
216
+ if a == "wait":
217
+ return {"action": "wait"}
218
+
219
+ # Non-UI or terminal actions: terminate/answer -> not mapped here
220
+ return None
221
+
222
+
223
+ @register_agent(models=r"(?i).*qwen.*", priority=-1)
224
+ class Qwen3VlConfig(AsyncAgentConfig):
225
+ async def predict_step(
226
+ self,
227
+ messages: List[Dict[str, Any]],
228
+ model: str,
229
+ tools: Optional[List[Dict[str, Any]]] = None,
230
+ max_retries: Optional[int] = None,
231
+ stream: bool = False,
232
+ computer_handler=None,
233
+ use_prompt_caching: Optional[bool] = False,
234
+ _on_api_start=None,
235
+ _on_api_end=None,
236
+ _on_usage=None,
237
+ _on_screenshot=None,
238
+ **kwargs,
239
+ ) -> Dict[str, Any]:
240
+ # Build messages using NousFnCallPrompt system with tool schema in text
241
+ # Start with converted conversation (images/text preserved)
242
+ converted_msgs = convert_responses_items_to_completion_messages(
243
+ messages,
244
+ allow_images_in_tool_results=False,
245
+ )
246
+
247
+ # Prepend Nous-generated system if available
248
+ nous_system = _build_nous_system([QWEN3_COMPUTER_TOOL["function"]])
249
+ completion_messages = ([nous_system] if nous_system else []) + converted_msgs
250
+
251
+ # If there is no screenshot in the conversation, take one now and inject it.
252
+ # Also record a pre_output_items assistant message to reflect action.
253
+ def _has_any_image(msgs: List[Dict[str, Any]]) -> bool:
254
+ for m in msgs:
255
+ content = m.get("content")
256
+ if isinstance(content, list):
257
+ for p in content:
258
+ if isinstance(p, dict) and p.get("type") == "image_url":
259
+ return True
260
+ return False
261
+
262
+ pre_output_items: List[Dict[str, Any]] = []
263
+ if not _has_any_image(completion_messages):
264
+ if computer_handler is None or not hasattr(computer_handler, "screenshot"):
265
+ raise RuntimeError("No screenshots present and computer_handler.screenshot is not available.")
266
+ screenshot_b64 = await computer_handler.screenshot()
267
+ if not screenshot_b64:
268
+ raise RuntimeError("Failed to capture screenshot from computer_handler.")
269
+ # Inject a user message with the screenshot so the model can see current context
270
+ completion_messages.append(
271
+ {
272
+ "role": "user",
273
+ "content": [
274
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{screenshot_b64}"}},
275
+ {"type": "text", "text": "Current screen"},
276
+ ],
277
+ }
278
+ )
279
+ # Add assistant message to outputs to reflect the action, similar to composed_grounded.py
280
+ pre_output_items.append(
281
+ {
282
+ "type": "message",
283
+ "role": "assistant",
284
+ "content": [
285
+ {"type": "text", "text": "Taking a screenshot to see the current computer screen."}
286
+ ],
287
+ }
288
+ )
289
+
290
+ # Smart-resize all screenshots and attach min/max pixel hints. Fail fast if deps missing.
291
+ # Also record the last resized width/height to unnormalize coordinates later.
292
+ last_rw: Optional[int] = None
293
+ last_rh: Optional[int] = None
294
+ MIN_PIXELS = 3136
295
+ MAX_PIXELS = 12845056
296
+ try:
297
+ from qwen_vl_utils import smart_resize # type: ignore
298
+ from PIL import Image # type: ignore
299
+ import base64, io
300
+ except Exception:
301
+ raise ImportError("qwen-vl-utils not installed. Please install it with `pip install cua-agent[qwen]`.")
302
+
303
+ for msg in completion_messages:
304
+ content = msg.get("content")
305
+ if not isinstance(content, list):
306
+ continue
307
+ for part in content:
308
+ if isinstance(part, dict) and part.get("type") == "image_url":
309
+ url = (((part.get("image_url") or {}).get("url")) or "")
310
+ # Expect data URL like data:image/png;base64,<b64>
311
+ if url.startswith("data:") and "," in url:
312
+ b64 = url.split(",", 1)[1]
313
+ img_bytes = base64.b64decode(b64)
314
+ im = Image.open(io.BytesIO(img_bytes))
315
+ h, w = im.height, im.width
316
+ rh, rw = smart_resize(h, w, factor=32, min_pixels=MIN_PIXELS, max_pixels=MAX_PIXELS)
317
+ # Attach hints on this image block
318
+ part["min_pixels"] = MIN_PIXELS
319
+ part["max_pixels"] = MAX_PIXELS
320
+ last_rw, last_rh = rw, rh
321
+
322
+ api_kwargs: Dict[str, Any] = {
323
+ "model": model,
324
+ "messages": completion_messages,
325
+ "max_retries": max_retries,
326
+ "stream": stream,
327
+ **{k: v for k, v in kwargs.items()},
328
+ }
329
+ if use_prompt_caching:
330
+ api_kwargs["use_prompt_caching"] = use_prompt_caching
331
+
332
+ if _on_api_start:
333
+ await _on_api_start(api_kwargs)
334
+
335
+ response = await litellm.acompletion(**api_kwargs)
336
+
337
+ if _on_api_end:
338
+ await _on_api_end(api_kwargs, response)
339
+
340
+ usage = {
341
+ **LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage( # type: ignore
342
+ response.usage
343
+ ).model_dump(),
344
+ "response_cost": response._hidden_params.get("response_cost", 0.0),
345
+ }
346
+ if _on_usage:
347
+ await _on_usage(usage)
348
+
349
+ # Parse tool call from text; then convert to responses items via fake tool_calls
350
+ resp_dict = response.model_dump() # type: ignore
351
+ choice = (resp_dict.get("choices") or [{}])[0]
352
+ content_text = (((choice.get("message") or {}).get("content")) or "")
353
+ tool_call = _parse_tool_call_from_text(content_text)
354
+
355
+ output_items: List[Dict[str, Any]] = []
356
+ if tool_call and isinstance(tool_call, dict):
357
+ fn_name = tool_call.get("name") or "computer"
358
+ raw_args = tool_call.get("arguments") or {}
359
+ # Unnormalize coordinates to actual screen size using last resized dims
360
+ if last_rw is None or last_rh is None:
361
+ raise RuntimeError("No screenshots found to derive dimensions for coordinate unnormalization.")
362
+ args = await _unnormalize_coordinate(raw_args, (last_rw, last_rh))
363
+
364
+ # Build an OpenAI-style tool call so we can reuse the converter
365
+ fake_cm = {
366
+ "role": "assistant",
367
+ "tool_calls": [
368
+ {
369
+ "type": "function",
370
+ "id": "call_0",
371
+ "function": {
372
+ "name": fn_name,
373
+ "arguments": json.dumps(args),
374
+ },
375
+ }
376
+ ],
377
+ }
378
+ output_items.extend(convert_completion_messages_to_responses_items([fake_cm]))
379
+ else:
380
+ # Fallback: just return assistant text
381
+ fake_cm = {"role": "assistant", "content": content_text}
382
+ output_items.extend(convert_completion_messages_to_responses_items([fake_cm]))
383
+
384
+ # Prepend any pre_output_items (e.g., simulated screenshot-taking message)
385
+ return {"output": (pre_output_items + output_items), "usage": usage}
386
+
387
+ def get_capabilities(self) -> List[AgentCapability]:
388
+ return ["step"]
389
+
390
+ async def predict_click(
391
+ self, model: str, image_b64: str, instruction: str, **kwargs
392
+ ) -> Optional[Tuple[int, int]]:
393
+ """
394
+ Predict click coordinates using Qwen3-VL via litellm.acompletion.
395
+
396
+ Only exposes a reduced tool schema with left_click to bias model to output a single click.
397
+ Returns (x, y) absolute pixels when screen dimensions can be obtained; otherwise normalized 0..1000 integers.
398
+ """
399
+ # Reduced tool
400
+ reduced_tool = {
401
+ "type": "function",
402
+ "function": {
403
+ **QWEN3_COMPUTER_TOOL["function"],
404
+ "parameters": {
405
+ "type": "object",
406
+ "properties": {
407
+ "action": {"type": "string", "enum": ["left_click"]},
408
+ "coordinate": {
409
+ "description": "(x, y) in 0..1000 reference space",
410
+ "type": "array",
411
+ "items": {"type": ["number", "integer"]},
412
+ "minItems": 2,
413
+ "maxItems": 2,
414
+ },
415
+ },
416
+ "required": ["action", "coordinate"],
417
+ },
418
+ },
419
+ }
420
+
421
+ # Build Nous system (lazy import inside helper already raises clear guidance if missing)
422
+ nous_system = _build_nous_system([reduced_tool["function"]])
423
+
424
+ # Pre-process using smart_resize
425
+ min_pixels = 3136
426
+ max_pixels = 12845056
427
+ try:
428
+ # Lazy import to avoid hard dependency
429
+ from qwen_vl_utils import smart_resize # type: ignore
430
+ # If PIL is available, estimate size from image to derive smart bounds
431
+ from PIL import Image
432
+ import io, base64
433
+
434
+ img_bytes = base64.b64decode(image_b64)
435
+ im = Image.open(io.BytesIO(img_bytes))
436
+ h, w = im.height, im.width
437
+ # Qwen notebook suggests factor=32 and a wide min/max range
438
+ rh, rw = smart_resize(h, w, factor=32, min_pixels=min_pixels, max_pixels=max_pixels)
439
+ except Exception:
440
+ raise ImportError("qwen-vl-utils not installed. Please install it with `pip install cua-agent[qwen]`.")
441
+
442
+ messages = []
443
+ if nous_system:
444
+ messages.append(nous_system)
445
+ image_block: Dict[str, Any] = {
446
+ "type": "image_url",
447
+ "image_url": {
448
+ "url": f"data:image/png;base64,{image_b64}"
449
+ },
450
+ "min_pixels": min_pixels,
451
+ "max_pixels": max_pixels,
452
+ }
453
+ # Single user message with image and instruction, matching OpenAI-style content blocks
454
+ messages.append(
455
+ {
456
+ "role": "user",
457
+ "content": [
458
+ image_block,
459
+ {"type": "text", "text": instruction},
460
+ ],
461
+ }
462
+ )
463
+
464
+ api_kwargs: Dict[str, Any] = {"model": model, "messages": messages, **{k: v for k, v in kwargs.items()}}
465
+ response = await litellm.acompletion(**api_kwargs)
466
+ resp = response.model_dump() # type: ignore
467
+ choice = (resp.get("choices") or [{}])[0]
468
+ content_text = (((choice.get("message") or {}).get("content")) or "")
469
+ tool_call = _parse_tool_call_from_text(content_text) or {}
470
+ args = tool_call.get("arguments") or {}
471
+ args = await _unnormalize_coordinate(args, (rh, rw))
472
+ coord = args.get("coordinate")
473
+ if isinstance(coord, (list, tuple)) and len(coord) >= 2:
474
+ return int(coord[0]), int(coord[1])
475
+ return None