Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-bench): RL integration of tinker into cua-bench (#1200)

Kai Mei43734e749973
diff --git a/libs/cua-bench/Dockerfile b/libs/cua-bench/Dockerfile
index 166222a091..e39ea66f45 100644
--- a/libs/cua-bench/Dockerfile
+++ b/libs/cua-bench/Dockerfile
@@ -9,6 +9,7 @@ RUN apt-get update && \
build-essential \
python3-dev \
portaudio19-dev \
+ libsndfile1 \
bash \
# Playwright system dependencies
libnss3 \
@@ -43,7 +44,8 @@ RUN python -m pip install --upgrade pip && \
playwright install --with-deps chromium
# Install cua-agent and non torch optional deps
-RUN python -m pip install --no-cache-dir cua-agent[qwen,omni,gemini]
+RUN python -m pip install --no-cache-dir soundfile cua-agent[qwen,omni,gemini] && \
+ python -m pip install --no-cache-dir opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
# Create a non-root user and set ownership
RUN useradd -m -u 1000 cuauser && \
diff --git a/libs/cua-bench/cua_bench/agents/__init__.py b/libs/cua-bench/cua_bench/agents/__init__.py
index 775ad65151..f54e42b7b7 100644
--- a/libs/cua-bench/cua_bench/agents/__init__.py
+++ b/libs/cua-bench/cua_bench/agents/__init__.py
@@ -99,6 +99,7 @@ def list_agents(config_loader: "ConfigLoader | None" = None) -> list[str]:
# Import agents (they will self-register via decorators)
from .cua_agent import CuaAgent # noqa: E402
from .gemini import GeminiAgent # noqa: E402
+from .qwen35_agent import Qwen35Agent # noqa: E402
__all__ = [
"BaseAgent",
@@ -106,6 +107,7 @@ __all__ = [
"FailureMode",
"CuaAgent",
"GeminiAgent",
+ "Qwen35Agent",
"register_agent",
"get_agent",
"list_agents",
diff --git a/libs/cua-bench/cua_bench/agents/opencua_agent.py b/libs/cua-bench/cua_bench/agents/opencua_agent.py
new file mode 100644
index 0000000000..eca1e9cd00
--- /dev/null
+++ b/libs/cua-bench/cua_bench/agents/opencua_agent.py
@@ -0,0 +1,277 @@
+import asyncio
+import base64
+import os
+import sys
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Dict, List
+
+from . import register_agent
+from .base import AgentResult, BaseAgent, FailureMode
+
+
+def _is_retryable_api_error(exc: BaseException) -> bool:
+ """Return True if the exception is a transient error that can be retried."""
+ if isinstance(exc, (asyncio.TimeoutError, TimeoutError)):
+ return True
+ try:
+ import litellm.exceptions as _le
+
+ if isinstance(
+ exc,
+ (
+ _le.RateLimitError,
+ _le.ServiceUnavailableError,
+ _le.APIConnectionError,
+ _le.Timeout,
+ _le.InternalServerError,
+ ),
+ ):
+ return True
+ except Exception:
+ pass
+ msg = str(exc).lower()
+ return any(k in msg for k in ("timeout", "rate limit", "503", "502", "429", "connection"))
+
+
+if TYPE_CHECKING:
+ from ..computers import DesktopSession
+
+
+@register_agent("opencua")
+class OpenCUAAgent(BaseAgent):
+ """Agent implementation using an OpenCUA model via the CUA Computer Agent SDK."""
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.model = kwargs.get("model", "openai/opencua-7b")
+ self.base_url = kwargs.get("base_url") or os.environ.get("OPENAI_ENDPOINT")
+ self.api_key = kwargs.get("api_key") or os.environ.get("OPENAI_API_KEY", "EMPTY")
+ self.max_steps = kwargs.get("max_steps", 50)
+ self.task_retries = int(kwargs.get("task_retries", 0))
+
+ @staticmethod
+ def name() -> str:
+ return "opencua"
+
+ def _create_custom_computer(self, session: "DesktopSession") -> Dict[str, Any]:
+ """Build a computer-handler dict from a DesktopSession."""
+ from ..types import (
+ ClickAction,
+ DoubleClickAction,
+ DragAction,
+ HotkeyAction,
+ KeyAction,
+ MiddleClickAction,
+ MoveToAction,
+ RightClickAction,
+ ScrollAction,
+ TypeAction,
+ WaitAction,
+ )
+
+ async def screenshot():
+ raw = await session.screenshot()
+ return base64.b64encode(raw).decode("utf-8")
+
+ async def click(x: int, y: int, button: str = "left"):
+ if button == "left":
+ action = ClickAction(x=x, y=y)
+ elif button == "right":
+ action = RightClickAction(x=x, y=y)
+ elif button == "middle":
+ action = MiddleClickAction(x=x, y=y)
+ else:
+ raise ValueError(f"Unknown button type: {button}")
+ await session.execute_action(action)
+
+ async def double_click(x: int, y: int):
+ await session.execute_action(DoubleClickAction(x=x, y=y))
+
+ async def type_text(text: str):
+ await session.execute_action(TypeAction(text=text))
+
+ async def keypress(keys):
+ if isinstance(keys, str):
+ await session.execute_action(KeyAction(key=keys))
+ else:
+ await session.execute_action(HotkeyAction(keys=list(keys)))
+
+ async def move(x: int, y: int):
+ await session.execute_action(MoveToAction(x=x, y=y))
+
+ async def scroll(x: int, y: int, scroll_x: int, scroll_y: int):
+ direction = "up" if scroll_y < 0 else "down"
+ await session.execute_action(ScrollAction(direction=direction, amount=abs(scroll_y)))
+
+ async def drag(path: List[Dict[str, int]]):
+ if len(path) < 2:
+ raise ValueError("Path must have at least 2 points")
+ start, end = path[0], path[-1]
+ await session.execute_action(
+ DragAction(from_x=start["x"], from_y=start["y"], to_x=end["x"], to_y=end["y"])
+ )
+
+ async def wait(ms: int = 1000):
+ await session.execute_action(WaitAction(seconds=ms / 1000.0))
+
+ async def get_dimensions():
+ return (1280, 800)
+
+ async def get_environment():
+ return "linux"
+
+ return {
+ "screenshot": screenshot,
+ "dimensions": get_dimensions,
+ "environment": get_environment,
+ "click": click,
+ "double_click": double_click,
+ "type": type_text,
+ "keypress": keypress,
+ "move": move,
+ "scroll": scroll,
+ "drag": drag,
+ "wait": wait,
+ }
+
+ async def perform_task(
+ self,
+ task_description: str,
+ session: "DesktopSession",
+ logging_dir: Path | None = None,
+ tracer=None,
+ ) -> AgentResult:
+ """Run the task using the OpenCUA model via the CUA Computer Agent SDK."""
+ try:
+ from agent import ComputerAgent
+ except ImportError as e:
+ raise RuntimeError(
+ "opencua-agent requires the `cua-agent` package to be installed. "
+ "Install it with: pip install cua-agent"
+ ) from e
+
+ instruction = self._render_instruction(task_description)
+
+ print(f"Instruction: {instruction}")
+
+ trajectory_dir = None
+ if logging_dir:
+ trajectory_dir = logging_dir / "trajectories"
+ trajectory_dir.mkdir(parents=True, exist_ok=True)
+
+ custom_computer = self._create_custom_computer(session)
+
+ # Extra litellm kwargs forwarded to the OpenCUA loop
+ extra_kwargs: Dict[str, Any] = {}
+ if self.base_url:
+ extra_kwargs["base_url"] = self.base_url
+ if self.api_key:
+ extra_kwargs["api_key"] = self.api_key
+
+ # OpenCUAConfig only declares "click" capability, so it cannot be used
+ # directly as the top-level agent loop. Using "model+model" routes
+ # through ComposedGroundedConfig (capabilities: ["click", "step"]),
+ # which uses the same OpenCUA model for both grounding (click prediction)
+ # and thinking (task reasoning) — identical to what OpenCUAConfig does
+ # internally in its own predict_step.
+ composed_model = f"{self.model}+{self.model}"
+
+ agent = ComputerAgent(
+ model=composed_model,
+ tools=[custom_computer],
+ only_n_most_recent_images=3,
+ trajectory_dir=trajectory_dir,
+ telemetry_enabled=False,
+ instructions=(
+ "Use the provided computer to complete the task as described. "
+ "When the task is complete, indicate so clearly by outputting 'DONE'."
+ ),
+ **extra_kwargs,
+ )
+
+ print(f"OpenCUA Agent initialized with model: {composed_model}")
+
+ total_usage = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "response_cost": 0.0,
+ }
+
+ last_exc: BaseException | None = None
+
+ try:
+ step = 0
+ task_completed = False
+
+ async for result in agent.run(instruction):
+ sys.stdout.flush()
+ step += 1
+
+ for k in total_usage:
+ total_usage[k] += result["usage"].get(k, 0)
+
+ if tracer:
+ try:
+ screenshot_bytes = await session.screenshot()
+ usage = result["usage"]
+ if hasattr(usage, "model_dump"):
+ usage = usage.model_dump()
+ elif not isinstance(usage, dict):
+ usage = dict(usage)
+ tracer.record(
+ "agent_step",
+ {
+ "step": step,
+ "agent": self.name(),
+ "model": self.model,
+ "usage": usage,
+ "output": result["output"],
+ },
+ [screenshot_bytes],
+ )
+ except Exception as e:
+ print(f"Warning: Failed to record agent step to tracer: {e}")
+
+ if step >= self.max_steps:
+ print(f"\n[Max steps reached] Stopped at step {step}/{self.max_steps}")
+ break
+
+ for item in result["output"]:
+ if item["type"] == "message":
+ content = item.get("content", [])
+ if content and "DONE" in content[0].get("text", ""):
+ print(f"\n[Task completed] Agent indicated completion at step {step}")
+ task_completed = True
+ break
+
+ print(f"\nTotal usage: {total_usage}")
+ print(f"Steps completed: {step}/{self.max_steps}")
+
+ if task_completed:
+ failure_mode = FailureMode.NONE
+ elif step >= self.max_steps:
+ failure_mode = FailureMode.MAX_STEPS_EXCEEDED
+ else:
+ failure_mode = FailureMode.NONE
+
+ return AgentResult(
+ total_input_tokens=total_usage.get("prompt_tokens", 0),
+ total_output_tokens=total_usage.get("completion_tokens", 0),
+ failure_mode=failure_mode,
+ )
+
+ except Exception as exc:
+ import traceback
+
+ print(f"Agent execution failed: {exc}")
+ traceback.print_exc()
+
+ failure_mode = (
+ FailureMode.API_ERROR if _is_retryable_api_error(exc) else FailureMode.UNKNOWN
+ )
+ return AgentResult(
+ total_input_tokens=0,
+ total_output_tokens=0,
+ failure_mode=failure_mode,
+ )
diff --git a/libs/cua-bench/cua_bench/agents/qwen35_agent.py b/libs/cua-bench/cua_bench/agents/qwen35_agent.py
new file mode 100644
index 0000000000..8c292d72df
--- /dev/null
+++ b/libs/cua-bench/cua_bench/agents/qwen35_agent.py
@@ -0,0 +1,264 @@
+import asyncio
+import base64
+import os
+import sys
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Dict, List
+
+from . import register_agent
+from .base import AgentResult, BaseAgent, FailureMode
+
+
+def _is_retryable_api_error(exc: BaseException) -> bool:
+ """Return True if the exception is a transient error that can be retried."""
+ if isinstance(exc, (asyncio.TimeoutError, TimeoutError)):
+ return True
+ try:
+ import litellm.exceptions as _le
+
+ if isinstance(
+ exc,
+ (
+ _le.RateLimitError,
+ _le.ServiceUnavailableError,
+ _le.APIConnectionError,
+ _le.Timeout,
+ _le.InternalServerError,
+ ),
+ ):
+ return True
+ except Exception:
+ pass
+ msg = str(exc).lower()
+ return any(k in msg for k in ("timeout", "rate limit", "503", "502", "429", "connection"))
+
+
+if TYPE_CHECKING:
+ from ..computers import DesktopSession
+
+
+@register_agent("qwen35")
+class Qwen35Agent(BaseAgent):
+ """Agent implementation using a Qwen3.5 model via the CUA Computer Agent SDK."""
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.model = kwargs.get("model", "openai/qwen35-4b")
+ self.base_url = kwargs.get("base_url") or os.environ.get("OPENAI_ENDPOINT")
+ self.api_key = kwargs.get("api_key") or os.environ.get("OPENAI_API_KEY", "EMPTY")
+ self.max_steps = kwargs.get("max_steps", 50)
+ self.task_retries = int(kwargs.get("task_retries", 0))
+
+ @staticmethod
+ def name() -> str:
+ return "qwen35"
+
+ def _create_custom_computer(self, session: "DesktopSession") -> Dict[str, Any]:
+ """Build a computer-handler dict from a DesktopSession."""
+ from ..types import (
+ ClickAction,
+ DoubleClickAction,
+ DragAction,
+ HotkeyAction,
+ KeyAction,
+ MiddleClickAction,
+ MoveToAction,
+ RightClickAction,
+ ScrollAction,
+ TypeAction,
+ WaitAction,
+ )
+
+ async def screenshot():
+ raw = await session.screenshot()
+ return base64.b64encode(raw).decode("utf-8")
+
+ async def click(x: int, y: int, button: str = "left"):
+ if button == "left":
+ action = ClickAction(x=x, y=y)
+ elif button == "right":
+ action = RightClickAction(x=x, y=y)
+ elif button == "middle":
+ action = MiddleClickAction(x=x, y=y)
+ else:
+ raise ValueError(f"Unknown button type: {button}")
+ await session.execute_action(action)
+
+ async def double_click(x: int, y: int):
+ await session.execute_action(DoubleClickAction(x=x, y=y))
+
+ async def type_text(text: str):
+ await session.execute_action(TypeAction(text=text))
+
+ async def keypress(keys):
+ if isinstance(keys, str):
+ await session.execute_action(KeyAction(key=keys))
+ else:
+ await session.execute_action(HotkeyAction(keys=list(keys)))
+
+ async def move(x: int, y: int):
+ await session.execute_action(MoveToAction(x=x, y=y))
+
+ async def scroll(x: int, y: int, scroll_x: int, scroll_y: int):
+ direction = "up" if scroll_y < 0 else "down"
+ await session.execute_action(ScrollAction(direction=direction, amount=abs(scroll_y)))
+
+ async def drag(path: List[Dict[str, int]]):
+ if len(path) < 2:
+ raise ValueError("Path must have at least 2 points")
+ start, end = path[0], path[-1]
+ await session.execute_action(
+ DragAction(from_x=start["x"], from_y=start["y"], to_x=end["x"], to_y=end["y"])
+ )
+
+ async def wait(ms: int = 1000):
+ await session.execute_action(WaitAction(seconds=ms / 1000.0))
+
+ async def get_dimensions():
+ return (1280, 800)
+
+ async def get_environment():
+ return "linux"
+
+ return {
+ "screenshot": screenshot,
+ "dimensions": get_dimensions,
+ "environment": get_environment,
+ "click": click,
+ "double_click": double_click,
+ "type": type_text,
+ "keypress": keypress,
+ "move": move,
+ "scroll": scroll,
+ "drag": drag,
+ "wait": wait
+ }
+
+ async def perform_task(
+ self,
+ task_description: str,
+ session: "DesktopSession",
+ logging_dir: Path | None = None,
+ tracer=None,
+ ) -> AgentResult:
+ """Run the task using the Qwen3.5 model via the CUA Computer Agent SDK."""
+ try:
+ from agent import ComputerAgent
+ except ImportError as e:
+ raise RuntimeError(
+ "qwen35-agent requires the `cua-agent` package to be installed. "
+ "Install it with: pip install cua-agent"
+ ) from e
+
+ instruction = f"Task: {self._render_instruction(task_description)}"
+
+ # print(f"Instruction: {instruction}")
+
+ trajectory_dir = None
+ if logging_dir:
+ trajectory_dir = logging_dir / "trajectories"
+ trajectory_dir.mkdir(parents=True, exist_ok=True)
+
+ custom_computer = self._create_custom_computer(session)
+
+ # Extra litellm kwargs forwarded to the loop
+ extra_kwargs: Dict[str, Any] = {}
+ if self.base_url:
+ extra_kwargs["base_url"] = self.base_url
+ if self.api_key:
+ extra_kwargs["api_key"] = self.api_key
+
+ agent = ComputerAgent(
+ model=self.model,
+ tools=[custom_computer],
+ only_n_most_recent_images=3,
+ trajectory_dir=trajectory_dir,
+ telemetry_enabled=False,
+ instructions=(
+ "Use the provided tools to interact with the computer (click, type, scroll, etc.) to accomplish the task. When the task is complete, indicate so clearly by outputting 'DONE'."
+ ),
+ **extra_kwargs,
+ )
+
+ total_usage = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "response_cost": 0.0,
+ }
+
+ try:
+ step = 0
+ task_completed = False
+
+ async for result in agent.run(instruction):
+ sys.stdout.flush()
+ step += 1
+
+ for k in total_usage:
+ total_usage[k] += result["usage"].get(k, 0)
+
+ if tracer:
+ try:
+ screenshot_bytes = await session.screenshot()
+ usage = result["usage"]
+ if hasattr(usage, "model_dump"):
+ usage = usage.model_dump()
+ elif not isinstance(usage, dict):
+ usage = dict(usage)
+ tracer.record(
+ "agent_step",
+ {
+ "step": step,
+ "agent": self.name(),
+ "model": self.model,
+ "usage": usage,
+ "output": result["output"],
+ },
+ [screenshot_bytes],
+ )
+ except Exception as e:
+ print(f"Warning: Failed to record agent step to tracer: {e}")
+
+ if step >= self.max_steps:
+ print(f"\n[Max steps reached] Stopped at step {step}/{self.max_steps}")
+ break
+
+ for item in result["output"]:
+ if item["type"] == "message":
+ content = item.get("content", [])
+ if content and "DONE" in content[0].get("text", ""):
+ print(f"\n[Task completed] Agent indicated completion at step {step}")
+ task_completed = True
+ break
+
+ print(f"\nTotal usage: {total_usage}")
+ print(f"Steps completed: {step}/{self.max_steps}")
+
+ if task_completed:
+ failure_mode = FailureMode.NONE
+ # elif step >= self.max_steps:
+ # failure_mode = FailureMode.MAX_STEPS_EXCEEDED
+ else:
+ failure_mode = FailureMode.NONE
+
+ return AgentResult(
+ total_input_tokens=total_usage.get("prompt_tokens", 0),
+ total_output_tokens=total_usage.get("completion_tokens", 0),
+ failure_mode=failure_mode,
+ )
+
+ except Exception as exc:
+ import traceback
+
+ # print(f"Agent execution failed: {exc}")
+ traceback.print_exc()
+
+ failure_mode = (
+ FailureMode.API_ERROR if _is_retryable_api_error(exc) else FailureMode.UNKNOWN
+ )
+ return AgentResult(
+ total_input_tokens=0,
+ total_output_tokens=0,
+ failure_mode=failure_mode,
+ )
diff --git a/libs/cua-bench/cua_bench/agents/qwen3vl_agent.py b/libs/cua-bench/cua_bench/agents/qwen3vl_agent.py
new file mode 100644
index 0000000000..c827d680fd
--- /dev/null
+++ b/libs/cua-bench/cua_bench/agents/qwen3vl_agent.py
@@ -0,0 +1,288 @@
+import asyncio
+import base64
+import os
+import sys
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Dict, List
+
+from . import register_agent
+from .base import AgentResult, BaseAgent, FailureMode
+
+
+def _is_retryable_api_error(exc: BaseException) -> bool:
+ """Return True if the exception is a transient error that can be retried."""
+ if isinstance(exc, (asyncio.TimeoutError, TimeoutError)):
+ return True
+ try:
+ import litellm.exceptions as _le
+
+ if isinstance(
+ exc,
+ (
+ _le.RateLimitError,
+ _le.ServiceUnavailableError,
+ _le.APIConnectionError,
+ _le.Timeout,
+ _le.InternalServerError,
+ ),
+ ):
+ return True
+ except Exception:
+ pass
+ msg = str(exc).lower()
+ return any(k in msg for k in ("timeout", "rate limit", "503", "502", "429", "connection"))
+
+
+if TYPE_CHECKING:
+ from ..computers import DesktopSession
+
+
+@register_agent("qwen3vl")
+class Qwen3VLAgent(BaseAgent):
+ """Agent implementation using a Qwen3-VL model via the CUA Computer Agent SDK."""
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self.model = kwargs.get("model", "openai/qwen3-vl")
+ self.base_url = kwargs.get("base_url") or os.environ.get("OPENAI_ENDPOINT")
+ self.api_key = kwargs.get("api_key") or os.environ.get("OPENAI_API_KEY", "EMPTY")
+ self.max_steps = kwargs.get("max_steps", 50)
+ self.task_retries = int(kwargs.get("task_retries", 0))
+
+ @staticmethod
+ def name() -> str:
+ return "qwen3vl"
+
+ def _create_custom_computer(self, session: "DesktopSession") -> Dict[str, Any]:
+ """Build a computer-handler dict from a DesktopSession."""
+ from ..types import (
+ ClickAction,
+ DoubleClickAction,
+ DragAction,
+ HotkeyAction,
+ KeyAction,
+ MiddleClickAction,
+ MoveToAction,
+ RightClickAction,
+ ScrollAction,
+ TypeAction,
+ WaitAction,
+ )
+
+ async def screenshot():
+ raw = await session.screenshot()
+ return base64.b64encode(raw).decode("utf-8")
+
+ async def click(x: int, y: int, button: str = "left"):
+ if button == "left":
+ action = ClickAction(x=x, y=y)
+ elif button == "right":
+ action = RightClickAction(x=x, y=y)
+ elif button == "middle":
+ action = MiddleClickAction(x=x, y=y)
+ else:
+ raise ValueError(f"Unknown button type: {button}")
+ await session.execute_action(action)
+
+ async def double_click(x: int, y: int):
+ await session.execute_action(DoubleClickAction(x=x, y=y))
+
+ async def type_text(text: str):
+ await session.execute_action(TypeAction(text=text))
+
+ async def keypress(keys):
+ if isinstance(keys, str):
+ await session.execute_action(KeyAction(key=keys))
+ else:
+ await session.execute_action(HotkeyAction(keys=list(keys)))
+
+ async def move(x: int, y: int):
+ await session.execute_action(MoveToAction(x=x, y=y))
+
+ async def scroll(x: int, y: int, scroll_x: int, scroll_y: int):
+ direction = "up" if scroll_y < 0 else "down"
+ await session.execute_action(ScrollAction(direction=direction, amount=abs(scroll_y)))
+
+ async def drag(path: List[Dict[str, int]]):
+ if len(path) < 2:
+ raise ValueError("Path must have at least 2 points")
+ start, end = path[0], path[-1]
+ await session.execute_action(
+ DragAction(from_x=start["x"], from_y=start["y"], to_x=end["x"], to_y=end["y"])
+ )
+
+ async def wait(ms: int = 1000):
+ await session.execute_action(WaitAction(seconds=ms / 1000.0))
+
+ async def get_dimensions():
+ return (1280, 800)
+
+ async def get_environment():
+ return "linux"
+
+ return {
+ "screenshot": screenshot,
+ "dimensions": get_dimensions,
+ "environment": get_environment,
+ "click": click,
+ "double_click": double_click,
+ "type": type_text,
+ "keypress": keypress,
+ "move": move,
+ "scroll": scroll,
+ "drag": drag,
+ "wait": wait,
+ }
+
+ async def perform_task(
+ self,
+ task_description: str,
+ session: "DesktopSession",
+ logging_dir: Path | None = None,
+ tracer=None,
+ ) -> AgentResult:
+ """Run the task using the Qwen3-VL model via the CUA Computer Agent SDK."""
+ try:
+ from agent import ComputerAgent
+ except ImportError as e:
+ raise RuntimeError(
+ "qwen3vl-agent requires the `cua-agent` package to be installed. "
+ "Install it with: pip install cua-agent"
+ ) from e
+
+ instruction = self._render_instruction(task_description)
+
+ print(f"Instruction: {instruction}")
+
+ trajectory_dir = None
+ if logging_dir:
+ trajectory_dir = logging_dir / "trajectories"
+ trajectory_dir.mkdir(parents=True, exist_ok=True)
+
+ custom_computer = self._create_custom_computer(session)
+
+ # Extra litellm kwargs forwarded to the loop
+ extra_kwargs: Dict[str, Any] = {}
+ if self.base_url:
+ extra_kwargs["base_url"] = self.base_url
+ if self.api_key:
+ extra_kwargs["api_key"] = self.api_key
+
+ agent = ComputerAgent(
+ model=self.model,
+ tools=[custom_computer],
+ only_n_most_recent_images=3,
+ trajectory_dir=trajectory_dir,
+ telemetry_enabled=False,
+ instructions=(
+ "Use the provided computer to complete the task as described. "
+ "When the task is complete, indicate so clearly by outputting 'DONE'."
+ ),
+ **extra_kwargs,
+ )
+
+ print(f"Qwen3VL Agent initialized with model: {self.model}")
+
+ total_usage = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "response_cost": 0.0,
+ }
+
+ try:
+ step = 0
+ task_completed = False
+
+ async for result in agent.run(instruction):
+ sys.stdout.flush()
+ step += 1
+
+ # Debug: print LLM response and actions
+ print(f"\n[DEBUG][Step {step}] usage={result.get('usage')}")
+ for idx, out_item in enumerate(result.get("output", [])):
+ item_type = out_item.get("type", "unknown")
+ if item_type == "computer_call":
+ action = out_item.get("action", {})
+ print(f" [{idx}] computer_call: action={action}")
+ elif item_type == "function_call":
+ print(f" [{idx}] function_call: name={out_item.get('name')}, args={out_item.get('arguments')}")
+ elif item_type == "computer_call_output":
+ output = out_item.get("output", {})
+ has_img = "image_url" in output if isinstance(output, dict) else False
+ print(f" [{idx}] computer_call_output: has_screenshot={has_img}")
+ elif item_type == "message":
+ content = out_item.get("content", [])
+ texts = [c.get("text", "") for c in content if isinstance(c, dict) and c.get("text")]
+ print(f" [{idx}] message: {' '.join(texts)[:200]}")
+ else:
+ print(f" [{idx}] {item_type}: {str(out_item)[:200]}")
+ sys.stdout.flush()
+
+ for k in total_usage:
+ total_usage[k] += result["usage"].get(k, 0)
+
+ if tracer:
+ try:
+ screenshot_bytes = await session.screenshot()
+ usage = result["usage"]
+ if hasattr(usage, "model_dump"):
+ usage = usage.model_dump()
+ elif not isinstance(usage, dict):
+ usage = dict(usage)
+ tracer.record(
+ "agent_step",
+ {
+ "step": step,
+ "agent": self.name(),
+ "model": self.model,
+ "usage": usage,
+ "output": result["output"],
+ },
+ [screenshot_bytes],
+ )
+ except Exception as e:
+ print(f"Warning: Failed to record agent step to tracer: {e}")
+
+ if step >= self.max_steps:
+ print(f"\n[Max steps reached] Stopped at step {step}/{self.max_steps}")
+ break
+
+ for item in result["output"]:
+ if item["type"] == "message":
+ content = item.get("content", [])
+ if content and "DONE" in content[0].get("text", ""):
+ print(f"\n[Task completed] Agent indicated completion at step {step}")
+ task_completed = True
+ break
+
+ print(f"\nTotal usage: {total_usage}")
+ print(f"Steps completed: {step}/{self.max_steps}")
+
+ if task_completed:
+ failure_mode = FailureMode.NONE
+ elif step >= self.max_steps:
+ failure_mode = FailureMode.MAX_STEPS_EXCEEDED
+ else:
+ failure_mode = FailureMode.NONE
+
+ return AgentResult(
+ total_input_tokens=total_usage.get("prompt_tokens", 0),
+ total_output_tokens=total_usage.get("completion_tokens", 0),
+ failure_mode=failure_mode,
+ )
+
+ except Exception as exc:
+ import traceback
+
+ print(f"Agent execution failed: {exc}")
+ traceback.print_exc()
+
+ failure_mode = (
+ FailureMode.API_ERROR if _is_retryable_api_error(exc) else FailureMode.UNKNOWN
+ )
+ return AgentResult(
+ total_input_tokens=0,
+ total_output_tokens=0,
+ failure_mode=failure_mode,
+ )
diff --git a/libs/cua-bench/cua_bench/cli/commands/interact.py b/libs/cua-bench/cua_bench/cli/commands/interact.py
index d9bf77b428..d59ecaa991 100644
--- a/libs/cua-bench/cua_bench/cli/commands/interact.py
+++ b/libs/cua-bench/cua_bench/cli/commands/interact.py
@@ -169,8 +169,17 @@ async def _execute_simulated_interactive(args, env_path: Path) -> int:
print(f"{CYAN}Loading environment: {env_path}{RESET}")
env = make(str(env_path))
- # Set headless to False for interactive mode
- env.headless = False
+ # Set headless to False for interactive mode (fall back if no display available)
+ import os
+ import sys
+ has_display = (
+ sys.platform == "darwin"
+ or bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
+ )
+ if not has_display:
+ print(f"{GREY}No graphical display detected. Running in headless mode.{RESET}")
+
+ env.headless = not has_display
env.print_actions = True
# Apply max steps if provided
if getattr(args, "max_steps", None) is not None:
diff --git a/libs/cua-bench/cua_bench/cli/commands/run.py b/libs/cua-bench/cua_bench/cli/commands/run.py
index 006b7f55a1..431c8a2f94 100644
--- a/libs/cua-bench/cua_bench/cli/commands/run.py
+++ b/libs/cua-bench/cua_bench/cli/commands/run.py
@@ -1325,9 +1325,10 @@ async def _cmd_run_task_detached(args) -> int:
if provider_type in ("simulated", "webtop"):
cmd.extend(["--provider-type", "simulated"])
- # Forward --with paths to subprocess
+ # Forward --with paths to subprocess (resolve to absolute so CWD changes don't matter)
for dev_path in getattr(args, "dev_paths", None) or []:
- cmd.extend(["--with", dev_path])
+ abs_dev_path = str(Path(dev_path).resolve())
+ cmd.extend(["--with", abs_dev_path])
# Forward --verbose
if getattr(args, "verbose", False):
diff --git a/libs/cua-bench/cua_bench/runner/task_runner.py b/libs/cua-bench/cua_bench/runner/task_runner.py
index ff97e3587f..dc51f58b0e 100644
--- a/libs/cua-bench/cua_bench/runner/task_runner.py
+++ b/libs/cua-bench/cua_bench/runner/task_runner.py
@@ -853,6 +853,7 @@ class TaskRunner:
api_keys = [
"ANTHROPIC_API_KEY",
"OPENAI_API_KEY",
+ "OPENAI_ENDPOINT",
"GOOGLE_API_KEY",
"GOOGLE_CLOUD_PROJECT",
"AZURE_OPENAI_API_KEY",
@@ -882,7 +883,15 @@ class TaskRunner:
if dev_paths:
install_parts = []
for i, dev_path in enumerate(dev_paths):
- abs_path = Path(dev_path).absolute()
+ abs_path = Path(dev_path).resolve()
+ if not abs_path.exists():
+ raise FileNotFoundError(
+ f"--with path does not exist: {dev_path} (resolved to {abs_path})"
+ )
+ if not (abs_path / "pyproject.toml").exists() and not (abs_path / "setup.py").exists():
+ raise FileNotFoundError(
+ f"--with path is not an installable package (no pyproject.toml or setup.py): {abs_path}"
+ )
container_path = f"/app/dev_{i}"
volumes.append(f"{abs_path}:{container_path}:ro")
# Copy to tmp first since pip needs a writable source dir to build.
diff --git a/libs/cua-bench/cua_bench/trainer/__init__.py b/libs/cua-bench/cua_bench/trainer/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/libs/cua-bench/cua_bench/trainer/off_policy/__init__.py b/libs/cua-bench/cua_bench/trainer/off_policy/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/__init__.py b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/__init__.py
new file mode 100644
index 0000000000..81f371f7fa
--- /dev/null
+++ b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/__init__.py
@@ -0,0 +1,12 @@
+from .rl_loop import TrainingConfig, run
+from .grpo import GRPOConfig
+from .checkpoints import CheckpointInfo, save_checkpoint, get_last_checkpoint
+
+__all__ = [
+ "TrainingConfig",
+ "GRPOConfig",
+ "run",
+ "CheckpointInfo",
+ "get_last_checkpoint",
+ "save_checkpoint",
+]
diff --git a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/checkpoints.py b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/checkpoints.py
new file mode 100644
index 0000000000..94b06bbdba
--- /dev/null
+++ b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/checkpoints.py
@@ -0,0 +1,122 @@
+"""
+Checkpoint utilities for the Tinker RL training loop.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING, Optional
+
+if TYPE_CHECKING:
+ from tinker import TrainingClient
+
+
+# ---------------------------------------------------------------------------
+# Data types
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class CheckpointInfo:
+ """Metadata returned by ``get_last_checkpoint``."""
+
+ state_path: str
+ epoch: int
+
+
+# ---------------------------------------------------------------------------
+# Save
+# ---------------------------------------------------------------------------
+
+
+def save_checkpoint(
+ training_client: "TrainingClient",
+ name: str,
+ log_path: str,
+ *,
+ kind: str = "state",
+ loop_state: Optional[dict] = None,
+ ttl_seconds: Optional[int] = None,
+) -> str:
+ """Save training state with loop metadata.
+
+ Parameters
+ ----------
+ training_client:
+ Active Tinker ``TrainingClient``.
+ name:
+ Human-readable label (e.g. ``"epoch-5"`` or ``"final"``).
+ log_path:
+ Local directory where a ``checkpoints.json`` manifest is maintained.
+ kind:
+ ``"state"`` (weights + optimiser) or ``"weights"`` (weights only).
+ Currently only ``"state"`` is implemented.
+ loop_state:
+ Arbitrary dict persisted alongside the checkpoint (e.g.
+ ``{"epoch": 5}``). Used by ``get_last_checkpoint`` for resume.
+ ttl_seconds:
+ Optional TTL forwarded to Tinker's ``save_state``.
+
+ Returns
+ -------
+ A ``tinker://`` path string identifying the checkpoint.
+ """
+ save_kwargs: dict = {"name": name}
+ if ttl_seconds is not None:
+ save_kwargs["ttl_seconds"] = ttl_seconds
+
+ state_path: str = training_client.save_state(**save_kwargs).result()
+ print(f"[checkpoint] State saved: {state_path}")
+
+ # Persist a local manifest so we can resume without querying Tinker.
+ manifest_path = Path(log_path) / "checkpoints.json"
+ manifest_path.parent.mkdir(parents=True, exist_ok=True)
+
+ manifest: list[dict] = []
+ if manifest_path.exists():
+ try:
+ manifest = json.loads(manifest_path.read_text())
+ except Exception:
+ manifest = []
+
+ entry = {
+ "name": name,
+ "state_path": state_path,
+ "kind": kind,
+ **(loop_state or {}),
+ }
+ manifest.append(entry)
+ manifest_path.write_text(json.dumps(manifest, indent=2))
+
+ return state_path
+
+
+# ---------------------------------------------------------------------------
+# Resume
+# ---------------------------------------------------------------------------
+
+
+def get_last_checkpoint(log_path: str) -> Optional[CheckpointInfo]:
+ """Return the most recent checkpoint from the local manifest.
+
+ Returns ``None`` if no checkpoints have been saved yet.
+ """
+ manifest_path = Path(log_path) / "checkpoints.json"
+ if not manifest_path.exists():
+ return None
+
+ try:
+ manifest = json.loads(manifest_path.read_text())
+ except Exception:
+ return None
+
+ if not manifest:
+ return None
+
+ last = manifest[-1]
+ return CheckpointInfo(
+ state_path=last["state_path"],
+ epoch=last.get("epoch", 0),
+ )
diff --git a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/grpo.py b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/grpo.py
new file mode 100644
index 0000000000..1e5b3af63e
--- /dev/null
+++ b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/grpo.py
@@ -0,0 +1,288 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Optional
+
+if TYPE_CHECKING:
+ from tinker import SamplingClient, TrainingClient
+ import tinker.types as tt
+
+ from .traces import Episode
+
+from PIL import Image
+
+from tinker_cookbook import renderers
+
+# ---------------------------------------------------------------------------
+# Configuration
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class GRPOConfig:
+ # Discount factor (kept for compatibility; not used with trajectory-level rewards).
+ gamma: float = 1.0
+ # AdamW hyperparameters.
+ learning_rate: float = 1e-5
+ beta1: float = 0.9
+ beta2: float = 0.95
+ eps: float = 1e-8
+ # PPO clip thresholds (kept for potential future clipped variants).
+ clip_low: float = 0.8
+ clip_high: float = 1.2
+ # Maximum number of recent images to keep per trajectory message.
+ max_images: int = 3
+
+
+# ---------------------------------------------------------------------------
+# Advantage estimation (GRPO-style: trajectory-level, group-relative)
+# ---------------------------------------------------------------------------
+
+
+def _group_episodes_by_task(episodes: list["Episode"]) -> dict[str, list["Episode"]]:
+ """Group episodes by their task_description (the 'task' that was rolled out)."""
+ groups: dict[str, list["Episode"]] = {}
+ for ep in episodes:
+ groups.setdefault(ep.task_description, []).append(ep)
+ return groups
+
+
+def _trajectory_advantage(
+ episode: "Episode",
+ task_episodes: list["Episode"],
+) -> float:
+ """GRPO-style advantage: reward - mean(rewards across trajectories for this task)."""
+ mean_reward = sum(e.terminal_reward for e in task_episodes) / len(task_episodes)
+ return episode.terminal_reward - mean_reward
+
+
+# ---------------------------------------------------------------------------
+# Message construction (latest N images from trajectory)
+# ---------------------------------------------------------------------------
+
+
+def _build_trajectory_messages(
+ episode: "Episode",
+ max_images: int = 3,
+) -> list[dict]:
+ """Build a chat-style message list for the full trajectory.
+
+ Keeps the latest ``max_images`` screenshots so the prompt stays bounded.
+ Each step contributes its screenshot (the observation the model saw)
+ and the action_text it produced. The task description is included as the
+ initial user instruction.
+ """
+ # Collect (image, action_text) pairs from steps that have screenshots
+ step_entries: list[tuple[Image.Image, str]] = []
+ for step in episode.steps:
+ if step.screenshot is not None:
+ step_entries.append((step.screenshot, step.action_text))
+
+ # Keep only the latest max_images steps
+ if len(step_entries) > max_images:
+ step_entries = step_entries[-max_images:]
+
+ # Build the message list
+ content_parts: list[dict] = []
+
+ # Task instruction as text
+ content_parts.append({"type": "text", "text": episode.task_description})
+
+ # Add image + action pairs
+ for img, action_text in step_entries:
+ content_parts.append({"type": "image", "image": img.convert("RGB")})
+ content_parts.append({"type": "text", "text": action_text})
+
+ messages = [{"role": "user", "content": content_parts}]
+ return messages
+
+
+# ---------------------------------------------------------------------------
+# Datum construction (matches GRPO reference pattern)
+# ---------------------------------------------------------------------------
+
+
+def _build_datum(
+ prompt: "tt.ModelInput",
+ advantage: float,
+ ref_logprobs: list[float],
+ action_ids: list[int],
+) -> Optional["tt.Datum"]:
+ """Assemble a single Tinker Datum for one trajectory.
+
+ Layout follows the GRPO reference:
+ model_input = prompt.append(action_tokens)
+ target_tokens = [0]*ob_len + action_ids
+ logprobs = [0]*ob_len + ref_logprobs
+ advantages = [0]*ob_len + [advantage]*action_len
+ """
+ import torch
+ import tinker.types as tt
+ from tinker.types.tensor_data import TensorData
+
+ if not action_ids:
+ return None
+
+ ob_len = prompt.length - 1
+
+ # Full model input: prompt + action tokens (shifted by 1 for next-token prediction)
+ model_input = prompt.append(tt.EncodedTextChunk(tokens=action_ids[:-1]))
+
+ # Aligned training arrays (padded over the observation prefix)
+ target_tokens = [0] * ob_len + action_ids
+ padded_logprobs = [0.0] * ob_len + ref_logprobs
+ padded_advantages = [0.0] * ob_len + [advantage] * len(action_ids)
+
+ assert model_input.length == len(target_tokens) == len(padded_logprobs) == len(padded_advantages), (
+ f"model_input.length: {model_input.length}, "
+ f"len(target_tokens): {len(target_tokens)}, "
+ f"len(padded_logprobs): {len(padded_logprobs)}, "
+ f"len(padded_advantages): {len(padded_advantages)}"
+ )
+
+ return tt.Datum(
+ model_input=model_input,
+ loss_fn_inputs={
+ "target_tokens": TensorData.from_torch(torch.tensor(target_tokens)),
+ "logprobs": TensorData.from_torch(torch.tensor(padded_logprobs)),
+ "advantages": TensorData.from_torch(torch.tensor(padded_advantages)),
+ }
+ )
+
+
+# ---------------------------------------------------------------------------
+# Batch construction (GRPO: trajectory-level, group-relative advantage)
+# ---------------------------------------------------------------------------
+
+
+def build_batch(
+ renderer: "renderers.Renderer",
+ episodes: list["Episode"],
+ sampling_client: "SamplingClient",
+ sampling_params: "tt.SamplingParams",
+ tokenizer,
+ gamma: float = 1.0,
+ max_images: int = 3,
+) -> list["tt.Datum"]:
+ """Convert episodes into a training batch (GRPO-style).
+
+ For each task, episodes are grouped and advantage is computed as:
+ advantage = episode.terminal_reward - mean(task_rewards)
+ """
+ task_groups = _group_episodes_by_task(episodes)
+
+ breakpoint()
+
+ # --- Build prompts and submit reference log-prob requests in bulk ---
+ # Each entry: (episode, advantage, prompt, action_ids, future)
+ pending: list[tuple] = []
+
+ for task_desc, task_episodes in task_groups.items():
+ for ep in task_episodes:
+ advantage = _trajectory_advantage(ep, task_episodes)
+
+ # Skip if advantage is exactly zero (all same reward in group)
+ # if advantage == 0.0:
+ # continue
+
+ # Build trajectory-level messages with latest N images
+ messages = _build_trajectory_messages(ep, max_images=max_images)
+
+ # Use renderer to convert messages into a ModelInput prompt
+ prompt = renderer.build_generation_prompt(messages)
+
+ # Tokenize the last action text as the "action" to train on
+ last_step = ep.steps[-1] if ep.steps else None
+ if last_step is None:
+ continue
+ action_ids = tokenizer.encode(last_step.action_text, add_special_tokens=False)
+ if not action_ids:
+ continue
+
+ # Submit async — do NOT call .result() yet; batch all futures first.
+ future = sampling_client.sample(
+ prompt=prompt,
+ num_samples=1,
+ sampling_params=sampling_params,
+ )
+ pending.append((ep, advantage, prompt, action_ids, future))
+
+ # --- Collect futures and build datums ---
+ datums: list = []
+ skipped_zero_advantage = 0
+
+ for ep, advantage, prompt, action_ids, future in pending:
+ sample_result = future.result()
+ # Extract logprobs from the sampling response
+ ref_logprobs: list[float] = []
+ if sample_result.sequences:
+ seq = sample_result.sequences[0]
+ if seq.logprobs is not None:
+ ref_logprobs = seq.logprobs
+
+ # Pad or truncate ref_logprobs to match action_ids length
+ if len(ref_logprobs) < len(action_ids):
+ ref_logprobs = ref_logprobs + [0.0] * (len(action_ids) - len(ref_logprobs))
+ elif len(ref_logprobs) > len(action_ids):
+ ref_logprobs = ref_logprobs[: len(action_ids)]
+
+ datum = _build_datum(prompt, advantage, ref_logprobs, action_ids)
+ if datum is not None:
+ datums.append(datum)
+
+ if skipped_zero_advantage > 0:
+ print(f"[grpo] Skipped {skipped_zero_advantage} datums with zero advantage")
+
+ return datums
+
+
+# ---------------------------------------------------------------------------
+# Training step (follows GRPO reference pattern)
+# ---------------------------------------------------------------------------
+
+
+def train_step(
+ training_client: "TrainingClient",
+ datums: list["tt.Datum"],
+ config: GRPOConfig,
+) -> dict[str, float]:
+ """Execute one gradient update via Tinker using importance_sampling loss.
+
+ Submits ``forward_backward`` and ``optim_step`` back-to-back before
+ blocking on either. Tinker processes operations in discrete ~10 s
+ clock cycles; submitting both futures in the same cycle avoids paying
+ a full cycle penalty for the optimiser step.
+
+ Returns
+ -------
+ Dict with ``"loss"`` and ``"n_datums"`` for logging.
+ """
+ import tinker.types as tt
+
+ if not datums:
+ return {"loss": 0.0, "n_datums": 0}
+
+ adam_params = tt.AdamParams(
+ learning_rate=config.learning_rate,
+ beta1=config.beta1,
+ beta2=config.beta2,
+ eps=config.eps,
+ )
+
+ # Submit both futures before blocking — lands in same Tinker cycle
+ fwd_bwd_future = training_client.forward_backward(
+ datums, loss_fn="importance_sampling"
+ )
+ optim_step_future = training_client.optim_step(adam_params)
+
+ # Block and collect results
+ fwd_bwd_result = fwd_bwd_future.result()
+ optim_result = optim_step_future.result()
+
+ loss = getattr(fwd_bwd_result, "loss", float("nan"))
+
+ metrics: dict[str, float] = {"loss": loss, "n_datums": len(datums)}
+ if optim_result.metrics:
+ metrics.update(optim_result.metrics)
+
+ return metrics
diff --git a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rl_loop.py b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rl_loop.py
new file mode 100644
index 0000000000..0c2284927e
--- /dev/null
+++ b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rl_loop.py
@@ -0,0 +1,307 @@
+from __future__ import annotations
+
+import argparse
+import os
+import time
+from dataclasses import dataclass, field
+from typing import Optional
+
+from .grpo import GRPOConfig
+from tinker_cookbook import checkpoint_utils, model_info, renderers
+from tinker_cookbook.image_processing_utils import get_image_processor
+
+# ---------------------------------------------------------------------------
+# Configuration
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class TrainingConfig:
+ # --- Mode ---
+ # "online" = collect rollouts via `cb run` each epoch.
+ # "offline" = use pre-collected run IDs (skip rollout collection).
+ mode: str = "online"
+
+ # --- Model ---
+ base_model: str = "Qwen/Qwen3-8B"
+ lora_rank: int = 16
+ lora_seed: int = 42
+
+ # --- Agent / rollout (online mode) ---
+ tasks_path: str = "tasks/"
+ agent: str = "opencua"
+ model: str = "openai/opencua"
+ max_steps_per_episode: int = 50
+ vllm_base_url: str = "http://localhost:30000/v1"
+
+ # --- Offline mode ---
+ # List of pre-collected run IDs to train on. Reused every epoch.
+ offline_run_ids: list[str] = field(default_factory=list)
+
+ # --- Training loop ---
+ epochs: int = 20
+ save_every: int = 5
+ log_path: str = "/tmp/tinker-cua-rl"
+ ttl_seconds: Optional[int] = 604800 # 7 days
+
+ # --- GRPO rollout ---
+ # Number of rollouts per task per epoch (must be >= 2 for GRPO).
+ num_rollouts: int = 2
+
+ # --- GRPO hyperparameters ---
+ grpo: GRPOConfig = field(default_factory=GRPOConfig)
+
+ # --- Resume ---
+ resume_from: Optional[str] = None
+
+ # --- Tinker ---
+ tinker_api_key: Optional[str] = None
+
+ # --- Rollout subprocess environment ---
+ rollout_env: dict[str, str] = field(default_factory=dict)
+
+
+# ---------------------------------------------------------------------------
+# Training loop
+# ---------------------------------------------------------------------------
+
+
+def run(config: TrainingConfig) -> None:
+ """Execute the full RL training loop.
+
+ All Tinker imports are deferred so the module can be imported in
+ environments where ``tinker`` is not installed.
+ """
+ from tinker import ServiceClient
+ import tinker.types as tt
+ from transformers import AutoTokenizer, AutoProcessor
+
+ from . import traces, rollout, grpo, checkpoints
+ from .rollout import _get_run_output_dir
+
+ if config.mode not in ("online", "offline"):
+ raise ValueError(f"Unknown mode {config.mode!r}. Must be 'online' or 'offline'.")
+
+ if config.mode == "offline" and not config.offline_run_ids:
+ raise ValueError("offline mode requires at least one run ID in offline_run_ids.")
+
+ api_key = config.tinker_api_key or os.environ.get("TINKER_API_KEY")
+ if not api_key:
+ raise ValueError(
+ "Tinker API key not found. "
+ "Set TINKER_API_KEY in the environment or pass it via TrainingConfig."
+ )
+
+ service_client = ServiceClient(api_key=api_key)
+
+ # --- Resume or fresh start ---
+ resume_info = checkpoints.get_last_checkpoint(config.log_path)
+
+ if resume_info:
+ print(f"[loop] Resuming from checkpoint: {resume_info.state_path} (epoch {resume_info.epoch})")
+ training_client = service_client.create_training_client_from_state_with_optimizer(
+ resume_info.state_path
+ )
+ start_epoch = resume_info.epoch
+ else:
+ print(f"[loop] Starting fresh LoRA training on {config.base_model}")
+ training_client = service_client.create_lora_training_client(
+ base_model=config.base_model,
+ rank=config.lora_rank,
+ seed=config.lora_seed,
+ )
+ start_epoch = 0
+
+ # --- Tokenizer ---
+ tokenizer = AutoTokenizer.from_pretrained(
+ config.base_model, trust_remote_code=True
+ )
+
+ image_processor = get_image_processor(config.base_model)
+
+ renderer_name = model_info.get_recommended_renderer_name(config.base_model)
+ renderer = renderers.get_renderer(renderer_name, tokenizer=tokenizer, image_processor=image_processor)
+
+ # --- Sampling params for reference logprobs ---
+ sampling_params = tt.SamplingParams(max_tokens=1)
+
+ print(f"[loop] Training for {config.epochs} epochs (starting from {start_epoch})")
+
+ # --- Main loop ---
+ for epoch in range(start_epoch + 1, config.epochs + 1):
+ t_epoch = time.monotonic()
+ print(f"\n[loop] === Epoch {epoch}/{config.epochs} ===")
+
+ metrics: dict[str, float] = {
+ "progress/epoch": epoch,
+ "progress/done_frac": epoch / config.epochs,
+ "optim/lr": config.grpo.learning_rate,
+ }
+
+ # 1. Periodic checkpoint (before rollout so we can resume on crash)
+ if config.save_every > 0 and epoch > 1 and (epoch - 1) % config.save_every == 0:
+ checkpoints.save_checkpoint(
+ training_client=training_client,
+ name=f"epoch-{epoch - 1}",
+ log_path=config.log_path,
+ kind="state",
+ loop_state={"epoch": epoch - 1},
+ ttl_seconds=config.ttl_seconds
+ )
+
+ # 2. Snapshot current weights for reference logprobs
+ sampling_client = training_client.save_weights_and_get_sampling_client()
+
+ # 3. Collect or resolve rollout data
+ if config.mode == "online":
+ print(f"[loop] Collecting {config.num_rollouts} rollout(s)...")
+ rollout_results = rollout.run_rollouts(
+ tasks_path=config.tasks_path,
+ agent=config.agent,
+ model=config.model,
+ max_steps=config.max_steps_per_episode,
+ num_rollouts=config.num_rollouts,
+ extra_env=config.rollout_env or None,
+ )
+ run_ids = [r[0] for r in rollout_results]
+ run_dirs = [r[1] for r in rollout_results]
+ else:
+ # Offline: reuse pre-collected run IDs every epoch
+ run_ids = list(config.offline_run_ids)
+ run_dirs = [_get_run_output_dir(rid) for rid in run_ids]
+ missing = [d for d in run_dirs if not d.exists()]
+ if missing:
+ raise FileNotFoundError(
+ f"Offline run directories not found: {missing}. "
+ "Check that the run IDs are correct and traces exist on disk."
+ )
+ print(f"[loop] Offline mode: using {len(run_ids)} pre-collected run(s)")
+
+ # 4. Load traces from all rollout runs
+ episodes = traces.load_runs(run_dirs)
+
+ breakpoint()
+
+ if not episodes:
+ print(f"[loop] No valid episodes across {len(run_dirs)} runs. Skipping epoch.")
+ continue
+
+ # Validate GRPO group sizes — warn if any task has only 1 trajectory
+ task_groups: dict[str, int] = {}
+ for ep in episodes:
+ task_groups[ep.task_description] = task_groups.get(ep.task_description, 0) + 1
+ singleton_tasks = [t for t, c in task_groups.items() if c < 2]
+ if singleton_tasks:
+ print(
+ f"[loop] Warning: {len(singleton_tasks)} task(s) have < 2 trajectories "
+ f"(GRPO needs group_size > 1). These will be skipped."
+ )
+
+ rewards_P = [ep.terminal_reward for ep in episodes]
+ avg_reward = sum(rewards_P) / len(rewards_P)
+ print(
+ f"[loop] {len(episodes)} episodes across {len(run_ids)} runs | "
+ f"avg_reward={avg_reward:.4f}"
+ )
+ metrics["reward/total"] = avg_reward
+
+ # 5. Build datums
+ print("[loop] Building training batch...")
+
+ datums_D = grpo.build_batch(
+ renderer=renderer,
+ episodes=episodes,
+ sampling_client=sampling_client,
+ sampling_params=sampling_params,
+ tokenizer=tokenizer,
+ gamma=config.grpo.gamma,
+ max_images=config.grpo.max_images
+ )
+
+ # 6. Training step
+ if not datums_D:
+ print("[loop] All advantages zero — skipping training step.")
+ else:
+ print(f"[loop] Training on {len(datums_D)} datums...")
+ step_stats = grpo.train_step(training_client, datums_D, config.grpo)
+ metrics.update(step_stats)
+
+ elapsed = time.monotonic() - t_epoch
+ metrics["time/total"] = elapsed
+ print(
+ f"[loop] loss={metrics.get('loss', 0.0):.4f} | "
+ f"n_datums={metrics.get('n_datums', 0)} | "
+ f"t={elapsed:.1f}s"
+ )
+
+ # Final checkpoint
+ checkpoints.save_checkpoint(
+ training_client=training_client,
+ name="final",
+ log_path=config.log_path,
+ kind="state",
+ loop_state={"epoch": config.epochs},
+ ttl_seconds=None,
+ )
+ print(f"\n[loop] Training complete.")
+
+
+# ---------------------------------------------------------------------------
+# CLI entry point
+# ---------------------------------------------------------------------------
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ p = argparse.ArgumentParser(
+ description="Off-policy RL training loop using Tinker (GRPO-style).",
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ )
+ p.add_argument("--mode", choices=["online", "offline"], default="online",
+ help="'online' collects rollouts via cb run; 'offline' uses pre-collected run IDs")
+ p.add_argument("--base-model", default="Qwen/Qwen3-8B")
+ p.add_argument("--lora-rank", type=int, default=16)
+ p.add_argument("--tasks-path", default="tasks/")
+ p.add_argument("--agent", default="opencua")
+ p.add_argument("--model", default="openai/opencua",
+ help="litellm model string forwarded to cb run")
+ p.add_argument("--max-steps", type=int, default=50)
+ p.add_argument("--vllm-url", default="http://localhost:30000/v1")
+ p.add_argument("--epochs", type=int, default=20)
+ p.add_argument("--save-every", type=int, default=5)
+ p.add_argument("--log-path", default="/tmp/tinker-cua-rl")
+ p.add_argument("--num-rollouts", type=int, default=2,
+ help="Number of rollouts per task per epoch (>= 2 for GRPO)")
+ p.add_argument("--offline-run-ids", nargs="*", default=[],
+ help="Run IDs for offline mode (reused every epoch)")
+ p.add_argument("--gamma", type=float, default=0.99)
+ p.add_argument("--lr", type=float, default=1e-5)
+ p.add_argument("--resume-from", default=None,
+ help="tinker:// checkpoint path to resume from")
+ return p
+
+
+if __name__ == "__main__":
+ args = _build_parser().parse_args()
+
+ config = TrainingConfig(
+ mode=args.mode,
+ base_model=args.base_model,
+ lora_rank=args.lora_rank,
+ tasks_path=args.tasks_path,
+ agent=args.agent,
+ model=args.model,
+ max_steps_per_episode=args.max_steps,
+ vllm_base_url=args.vllm_url,
+ epochs=args.epochs,
+ save_every=args.save_every,
+ log_path=args.log_path,
+ num_rollouts=args.num_rollouts,
+ offline_run_ids=args.offline_run_ids,
+ resume_from=args.resume_from,
+ grpo=GRPOConfig(
+ gamma=args.gamma,
+ learning_rate=args.lr,
+ ),
+ )
+
+ run(config)
diff --git a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rollout.py b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rollout.py
new file mode 100644
index 0000000000..2e7e6a56d4
--- /dev/null
+++ b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/rollout.py
@@ -0,0 +1,134 @@
+from __future__ import annotations
+
+import os
+import re
+import subprocess
+import time
+from pathlib import Path
+
+
+# ---------------------------------------------------------------------------
+# Internal helpers
+# ---------------------------------------------------------------------------
+
+_ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
+_RUN_ID_RE = re.compile(r"Run ID:\s+([a-f0-9-]{8,})")
+
+
+def _get_run_output_dir(run_id: str) -> Path:
+ xdg_data = os.environ.get("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
+ return Path(xdg_data) / "cua-bench" / "runs" / run_id
+
+
+def _parse_run_id(text: str) -> str | None:
+ clean = _ANSI_RE.sub("", text)
+ m = _RUN_ID_RE.search(clean)
+ return m.group(1) if m else None
+
+
+def _terminal_statuses() -> frozenset[str]:
+ return frozenset({"completed", "failed", "cancelled"})
+
+
+def _all_sessions_terminal(run_id: str) -> bool:
+ """Return True when every session in *run_id* has reached a terminal state."""
+ from cua_bench.sessions.manager import list_sessions
+
+ sessions = [s for s in list_sessions() if s.get("run_id") == run_id]
+ if not sessions:
+ return False
+ return all(s.get("status") in _terminal_statuses() for s in sessions)
+
+
+def _run_single_rollout(
+ tasks_path: str | Path,
+ agent: str,
+ model: str,
+ max_steps: int,
+ *,
+ timeout: int = 3600,
+ poll_interval: int = 10,
+ extra_env: dict[str, str] | None = None,
+) -> tuple[str, Path]:
+ """Run a single ``cb run task`` invocation and block until it finishes."""
+ env = {**os.environ, **(extra_env or {})}
+
+ cmd = [
+ "cb", "run", "dataset", str(tasks_path),
+ "--agent", agent,
+ "--model", model,
+ "--max-steps", str(max_steps),
+ "--with", "libs/python/agent/agent"
+ ]
+
+ print(f"[rollout] Launching: {' '.join(cmd)}")
+ proc = subprocess.run(cmd, capture_output=True, text=True, env=env)
+
+ combined_output = proc.stdout + proc.stderr
+ run_id = _parse_run_id(combined_output)
+
+ if run_id is None:
+ raise RuntimeError(
+ "Could not parse run_id from cb output.\n"
+ f"STDOUT:\n{proc.stdout}\n"
+ f"STDERR:\n{proc.stderr}"
+ )
+
+ print(f"[rollout] Run {run_id} launched. Waiting for sessions to complete...")
+
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if _all_sessions_terminal(run_id):
+ break
+ time.sleep(poll_interval)
+ else:
+ raise TimeoutError(
+ f"Run {run_id} did not complete within {timeout}s. "
+ "Consider increasing the timeout or checking for stuck containers."
+ )
+
+ print(f"[rollout] Run {run_id} complete.")
+
+ run_dir = _get_run_output_dir(run_id)
+ if not run_dir.exists():
+ raise FileNotFoundError(
+ f"Expected run output directory not found: {run_dir}. "
+ "The run may have used a custom output path."
+ )
+
+ return run_id, run_dir
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def run_rollouts(
+ tasks_path: str | Path,
+ agent: str,
+ model: str,
+ max_steps: int,
+ *,
+ num_rollouts: int = 1,
+ timeout: int = 3600,
+ poll_interval: int = 10,
+ extra_env: dict[str, str] | None = None,
+) -> list[tuple[str, Path]]:
+ """Run cua-bench rollouts and block until all sessions finish.
+ """
+ results: list[tuple[str, Path]] = []
+ for i in range(num_rollouts):
+ if num_rollouts > 1:
+ print(f"[rollout] === Rollout {i + 1}/{num_rollouts} ===")
+ run_id, run_dir = _run_single_rollout(
+ tasks_path=tasks_path,
+ agent=agent,
+ model=model,
+ max_steps=max_steps,
+ timeout=timeout,
+ poll_interval=poll_interval,
+ extra_env=extra_env,
+ )
+ results.append((run_id, run_dir))
+ return results
diff --git a/libs/cua-bench/cua_bench/trainer/off_policy/tinker/traces.py b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/traces.py
new file mode 100644
index 0000000000..7132adbbb8
--- /dev/null
+++ b/libs/cua-bench/cua_bench/trainer/off_policy/tinker/traces.py
@@ -0,0 +1,185 @@
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional
+
+from PIL import Image
+
+
+@dataclass
+class Step:
+ step_num: int
+ # Screenshot (observation) visible to the model at this step.
+ screenshot: Optional[Image.Image]
+ # Raw text reconstructed from the ComputerAgent output items (thinking + action).
+ action_text: str
+
+
+@dataclass
+class Episode:
+ trajectory_id: str
+ task_description: str
+ steps: list[Step]
+ terminal_reward: float
+
+
+# ---------------------------------------------------------------------------
+# Internal helpers
+# ---------------------------------------------------------------------------
+
+
+def _extract_action_text(output_items: list[dict]) -> str:
+ """Reconstruct printable text from ComputerAgent SDK output items.
+
+ The SDK returns a list of typed blocks such as:
+ - ``{"type": "message", "content": [{"type": "output_text", "text": "..."}]}``
+ - ``{"type": "computer_call", "action": {...}, "call_id": "..."}``
+ - ``{"type": "tool_use", "name": "click", "input": {...}}``
+
+ We join all text content and JSON-serialised tool/computer calls so the
+ tokenizer receives a single string that faithfully represents the model's
+ response.
+ """
+ parts: list[str] = []
+ for item in output_items:
+ kind = item.get("type")
+ if kind == "message":
+ for block in item.get("content", []):
+ if isinstance(block, dict):
+ text = block.get("text")
+ if text:
+ parts.append(text)
+ elif kind == "computer_call":
+ parts.append(json.dumps({"action": item.get("action")}))
+ elif kind == "tool_use":
+ parts.append(
+ json.dumps({"tool": item.get("name"), "input": item.get("input")})
+ )
+ # Fallback: if nothing matched, serialise the raw list so we always have
+ # *something* to tokenise.
+ return "\n".join(parts) if parts else json.dumps(output_items)
+
+
+def _as_pil(img) -> Optional[Image.Image]:
+ """Coerce an HF Dataset image value to PIL, or return None."""
+ if img is None:
+ return None
+ if isinstance(img, Image.Image):
+ return img
+ # HF sometimes returns a dict with a "bytes" key when the image was saved
+ # as a raw buffer rather than a decoded PIL image.
+ if isinstance(img, dict) and "bytes" in img:
+ import io
+ return Image.open(io.BytesIO(img["bytes"])).convert("RGB")
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def load_episode(trace_dir: str | Path) -> Optional[Episode]:
+ """Load a single task trace directory into an Episode.
+
+ Returns ``None`` if the trace is missing the ``evaluate`` event (i.e. the
+ task did not finish cleanly).
+ """
+ from datasets import load_from_disk
+
+ ds = load_from_disk(str(trace_dir))
+
+ # Group rows by event type for easy lookup.
+ by_event: dict[str, list] = {}
+ for row in ds:
+ by_event.setdefault(row["event_name"], []).append(row)
+
+ if "evaluate" not in by_event:
+ return None
+
+ raw_result = json.loads(by_event["evaluate"][0]["data_json"]).get("result", 0.0)
+ # result may be a list (e.g. [0.0]) or a scalar
+ if isinstance(raw_result, list):
+ terminal_reward = float(raw_result[0]) if raw_result else 0.0
+ else:
+ terminal_reward = float(raw_result)
+
+ # Task description comes from the reset event.
+ task_description = ""
+ reset_screenshot: Optional[Image.Image] = None
+ for reset_row in by_event.get("reset", []):
+ reset_data = json.loads(reset_row["data_json"])
+ task_description = reset_data.get("task", "")
+ images = reset_row.get("data_images") or []
+ if images:
+ reset_screenshot = _as_pil(images[0])
+ break
+
+ # Sort agent steps by the step counter stored in data_json.
+ agent_steps = sorted(
+ by_event.get("agent_step", []),
+ key=lambda r: json.loads(r["data_json"]).get("step", 0),
+ )
+
+ steps: list[Step] = []
+ prev_screenshot = reset_screenshot
+
+ for i, row in enumerate(agent_steps):
+ data = json.loads(row["data_json"])
+ images = row.get("data_images") or []
+ post_screenshot = _as_pil(images[0]) if images else None
+
+ steps.append(
+ Step(
+ step_num=data.get("step", i + 1),
+ screenshot=prev_screenshot,
+ action_text=_extract_action_text(data.get("output", [])),
+ )
+ )
+
+ # Advance screenshot cursor: use post_screenshot if available.
+ if post_screenshot is not None:
+ prev_screenshot = post_screenshot
+
+ trajectory_id = ds[0]["trajectory_id"] if len(ds) > 0 and ds[0]["trajectory_id"] is not None else ""
+ assert isinstance(trajectory_id, str), f"trajectory_id is not a string: {trajectory_id}"
+
+ return Episode(
+ trajectory_id=trajectory_id,
+ task_description=task_description,
+ steps=steps,
+ terminal_reward=terminal_reward,
+ )
+
+
+def load_run(run_dir: str | Path) -> list[Episode]:
+ """Load all task trace directories from a cua-bench run output directory.
+
+ Skips trace directories that are missing the evaluate event or whose
+ dataset cannot be read (e.g. a task that crashed mid-run).
+ """
+ run_path = Path(run_dir)
+ episodes: list[Episode] = []
+ for trace_dir in sorted(run_path.glob("*/task_*_trace")):
+ try:
+ ep = load_episode(trace_dir)
+ if ep is not None:
+ episodes.append(ep)
+ except Exception as exc:
+ # Non-fatal: log and continue so one bad trace doesn't abort the epoch.
+ print(f"[traces] Warning: could not load {trace_dir}: {exc}")
+ return episodes
+
+
+def load_runs(run_dirs: list[str | Path]) -> list[Episode]:
+ """Load episodes from multiple run directories and merge them.
+
+ This is needed for GRPO where group_size > 1 requires multiple
+ trajectories per task, collected across repeated rollouts.
+ """
+ all_episodes: list[Episode] = []
+ for run_dir in run_dirs:
+ all_episodes.extend(load_run(run_dir))
+ return all_episodes
diff --git a/libs/cua-bench/plan.md b/libs/cua-bench/plan.md
new file mode 100644
index 0000000000..b287106931
--- /dev/null
+++ b/libs/cua-bench/plan.md
@@ -0,0 +1,531 @@
+# Plan: Tinker RL Training Integration with cua-bench
+
+## Overview
+
+This plan describes how to integrate [Tinker](https://tinker-docs.thinkingmachines.ai/) as an RL training backend for the OpenCUA model using `cua-bench` as the environment. The result is a closed training loop: `cua-bench` generates rollout trajectories and rewards → Tinker updates model weights via PPO → updated weights reload into vLLM → next rollout round.
+
+---
+
+## 1. How Traces Are Collected Today
+
+After running `cb run tasks --agent opencua`, each task execution produces a **HuggingFace Dataset** stored on disk via `cua_bench/tracing.py`.
+
+### Trace event schema
+
+| Field | Type | Description |
+|---|---|---|
+| `event_name` | `str` | One of `"reset"`, `"agent_step"`, `"solve"`, `"evaluate"` |
+| `data_json` | `str` | JSON payload specific to event type |
+| `data_images` | `Sequence[Image]` | Screenshots at that moment |
+| `trajectory_id` | `str` | UUID identifying the full episode |
+| `timestamp` | `str` | ISO-8601 UTC timestamp |
+
+### Events recorded per task
+
+| Event | When | Key `data_json` fields |
+|---|---|---|
+| `reset` | After env setup completes | `{task, task_index, elapsed}` |
+| `agent_step` | After every agent action | `{step, agent, model, usage, output}` |
+| `solve` | After oracle solution (non-eval runs) | `{completed: bool}` |
+| `evaluate` | After evaluation function | `{result: <reward_value>}` |
+
+The `agent_step` `output` field mirrors the raw message list from the ComputerAgent SDK, including typed actions (`click`, `type_text`, etc.) and the final `"DONE"` message.
+
+### Trace storage paths
+
+```
+~/.local/share/cua-bench/runs/<run_id>/
+├── task_0_trace/ # HF Dataset (arrow files)
+│ ├── dataset_info.json
+│ ├── state.json
+│ └── data/
+├── task_0_agent_logs/
+│ └── trajectories/ # ComputerAgent internal trajectories
+└── imgs/ # Optional PNG dumps (--save-pngs flag)
+```
+
+### Loading traces programmatically
+
+```python
+from datasets import load_from_disk
+
+ds = load_from_disk("~/.local/share/cua-bench/runs/<run_id>/task_0_trace/")
+
+# Extract reward from evaluate event
+reward_row = next(r for r in ds if r["event_name"] == "evaluate")
+reward = json.loads(reward_row["data_json"])["result"]
+
+# Extract agent steps in order
+steps = [r for r in ds if r["event_name"] == "agent_step"]
+for step in steps:
+ data = json.loads(step["data_json"])
+ screenshot = step["data_images"][0] # PIL.Image
+```
+
+---
+
+## 2. Tinker API Overview
+
+Tinker is a cloud-hosted RL/SL fine-tuning platform for LLMs. It abstracts distributed GPU training while exposing a simple Python API.
+
+### Core client hierarchy
+
+```
+ServiceClient (entry point)
+├── create_lora_training_client() → TrainingClient
+│ ├── forward_backward(data, loss_fn) → Future
+│ ├── optim_step(AdamParams) → Future
+│ ├── save_state(name) → Future[str] (tinker:// path)
+│ └── save_weights_and_get_sampling_client() → SamplingClient
+├── create_sampling_client(checkpoint) → SamplingClient
+│ ├── sample(prompt, params) → List[str]
+│ └── compute_logprobs(prompt, target) → List[float]
+└── create_rest_client() → RestClient
+ ├── list_checkpoints(run_id)
+ └── get_checkpoint_archive_url_from_tinker_path(path)
+```
+
+### Supported RL loss functions
+
+| Loss | Use case |
+|---|---|
+| `"importance_sampling"` | Off-policy PPO without clipping |
+| `"ppo"` | Clipped PPO (standard RLHF) |
+| `"cispo"` | Clipped importance sampling coefficients |
+| `"dro"` | Direct reward optimization with quadratic penalty |
+| Custom | Via `forward_backward_custom()` with arbitrary differentiable loss |
+
+### Checkpoint persistence
+
+| Method | Saves | When to use |
+|---|---|---|
+| `save_weights_for_sampler(name)` | Weights only | Quick eval between epochs |
+| `save_state(name)` | Weights + optimizer state | Full resume / multi-phase SL→RL |
+| `save_weights_and_get_sampling_client()` | Weights → new SamplingClient | End of training step, for next rollout |
+
+Checkpoint paths follow the scheme `tinker://<model_id>/<name>`. Default TTL is 7 days; use `RestClient` to extend.
+
+---
+
+## 3. Proposed Architecture
+
+```
+┌─────────────────────────────────────────────────────────────┐
+│ RL Training Loop │
+│ │
+│ ┌──────────────┐ rollouts ┌───────────────────────┐ │
+│ │ cua-bench │ ─────────────▶│ Trace Collector │ │
+│ │ (env) │ │ (HF Datasets) │ │
+│ └──────┬───────┘ └──────────┬────────────┘ │
+│ │ │ │
+│ ┌──────▼───────┐ ┌──────────▼────────────┐ │
+│ │ vLLM │ ◀─ weights ── │ Tinker │ │
+│ │ (OpenCUA) │ │ TrainingClient │ │
+│ └──────────────┘ │ (PPO / IS loss) │ │
+│ └───────────────────────┘ │
+└─────────────────────────────────────────────────────────────┘
+```
+
+### Component roles
+
+| Component | Role |
+|---|---|
+| `cua-bench` | Rollout environment; generates trajectories + reward signals |
+| `cua_bench/tracing.py` | Serializes trajectories to HF Datasets on disk |
+| `Trace Collector` | Reads traces, extracts `(prompt, action, reward)` tuples |
+| `Datum Builder` | Converts tuples to Tinker `Datum` objects (token sequences + masks) |
+| `Tinker TrainingClient` | Runs PPO gradient updates on remote GPU cluster |
+| `Tinker SamplingClient` | Not used for generation (vLLM does that), but used for `compute_logprobs` to get reference policy log-probs for IS ratio |
+| `vLLM` | Serves the current policy for cua-bench rollouts |
+| `Weight Sync` | Downloads updated LoRA weights from Tinker checkpoint → hot-reloads into vLLM |
+
+---
+
+## 4. Implementation Plan
+
+### Phase 1: Trace extraction pipeline
+
+**New file**: `cua_bench/rl/trace_reader.py`
+
+```python
+"""
+Read completed cua-bench run traces and convert them to RL experience tuples.
+"""
+import json
+from pathlib import Path
+from dataclasses import dataclass
+from typing import List, Optional
+from datasets import load_from_disk
+
+@dataclass
+class RLStep:
+ step: int
+ prompt_images: list # screenshots before action
+ action_text: str # raw action output from model
+ reward: float # 0.0 except at terminal step
+
+@dataclass
+class Episode:
+ trajectory_id: str
+ task_description: str
+ steps: List[RLStep]
+ terminal_reward: float # from "evaluate" event
+
+def load_episode_from_trace(trace_dir: str) -> Episode:
+ ds = load_from_disk(trace_dir)
+ rows_by_event = {}
+ for row in ds:
+ rows_by_event.setdefault(row["event_name"], []).append(row)
+
+ reward = float(json.loads(rows_by_event["evaluate"][0]["data_json"])["result"])
+ trajectory_id = ds[0]["trajectory_id"]
+
+ steps = []
+ for row in rows_by_event.get("agent_step", []):
+ data = json.loads(row["data_json"])
+ steps.append(RLStep(
+ step=data["step"],
+ prompt_images=row["data_images"],
+ action_text=str(data["output"]),
+ reward=0.0,
+ ))
+
+ # Assign terminal reward to last step only (sparse reward)
+ if steps:
+ steps[-1].reward = reward
+
+ return Episode(trajectory_id, task_description="", steps=steps, terminal_reward=reward)
+
+def load_run_episodes(run_dir: str) -> List[Episode]:
+ """Load all task traces from a cua-bench run directory."""
+ run_path = Path(run_dir)
+ episodes = []
+ for trace_dir in sorted(run_path.glob("task_*_trace")):
+ episodes.append(load_episode_from_trace(str(trace_dir)))
+ return episodes
+```
+
+### Phase 2: Datum construction
+
+**New file**: `cua_bench/rl/datum_builder.py`
+
+The Tinker `Datum` format requires tokenized inputs with explicit weight masks. For a vision-language model like OpenCUA (based on Qwen-VL), each step's datum looks like:
+
+```
+[system_tokens] [image_tokens] [user_instruction_tokens] [action_tokens]
+ ^^^^^^^^^^^^^^^^
+ loss computed here
+```
+
+Key decisions:
+- **Input sequence**: System prompt + screenshot(s) + task description (this is the `model_input`)
+- **Target sequence**: The action the agent took (this is the `loss_fn_inputs` target)
+- **Weight mask**: 1.0 on action tokens, 0.0 on prompt tokens
+- **Advantage weighting**: For PPO, multiply step reward by a per-step advantage estimate; apply as weight multiplier on action tokens
+
+```python
+import tinker.types as tt
+from transformers import AutoTokenizer
+
+def build_datum(step: RLStep, tokenizer, advantage: float) -> tt.Datum:
+ """Convert a single RL step to a Tinker Datum."""
+ # Tokenize action (target)
+ action_ids = tokenizer.encode(step.action_text, add_special_tokens=False)
+
+ # Tokenize prompt context (images + instruction handled by rendering pipeline)
+ # ... (use Tinker's ImageChunk + EncodedTextChunk for multimodal)
+
+ model_input = tt.ModelInput(
+ chunks=[
+ tt.EncodedTextChunk(token_ids=prompt_ids),
+ tt.ImageChunk(image=step.prompt_images[0]), # latest screenshot
+ tt.EncodedTextChunk(token_ids=action_ids),
+ ]
+ )
+
+ # Shift targets: model predicts token[i+1] from token[i]
+ target_ids = action_ids # shifted internally by Tinker
+ weights = [max(0.0, advantage)] * len(action_ids) # zero-out negative advantages
+
+ return tt.Datum(
+ model_input=model_input,
+ loss_fn_inputs=tt.LossFnInputs(
+ target_token_ids=target_ids,
+ weights=weights,
+ )
+ )
+
+def build_batch(episode: Episode, tokenizer, gamma=0.99) -> list[tt.Datum]:
+ """Convert episode to list of Datums with discounted advantage estimates."""
+ # Compute discounted returns (simple Monte Carlo)
+ G = 0.0
+ returns = []
+ for step in reversed(episode.steps):
+ G = step.reward + gamma * G
+ returns.insert(0, G)
+
+ baseline = sum(returns) / len(returns) if returns else 0.0
+
+ datums = []
+ for step, G in zip(episode.steps, returns):
+ advantage = G - baseline
+ datums.append(build_datum(step, tokenizer, advantage))
+ return datums
+```
+
+### Phase 3: RL training loop
+
+**New file**: `cua_bench/rl/train.py`
+
+```python
+"""
+Main RL training loop using Tinker.
+
+Usage:
+ python -m cua_bench.rl.train \
+ --base-model Qwen/Qwen3-8B \
+ --run-dir ~/.local/share/cua-bench/runs/<run_id> \
+ --epochs 10 \
+ --lr 1e-5
+"""
+import tinker
+from tinker import ServiceClient
+import tinker.types as tt
+
+def train_epoch(training_client, episodes: list, tokenizer, args):
+ """Run one PPO update epoch over a batch of episodes."""
+ all_datums = []
+ for ep in episodes:
+ all_datums.extend(build_batch(ep, tokenizer, gamma=args.gamma))
+
+ if not all_datums:
+ return
+
+ # Submit forward-backward and optim step without awaiting between them
+ # (keeps operations in the same ~10s Tinker clock cycle)
+ fwdbwd_future = training_client.forward_backward_async(
+ data=all_datums,
+ loss_fn="ppo",
+ loss_fn_params=tt.PpoParams(
+ clip_low_threshold=0.8,
+ clip_high_threshold=1.2,
+ ),
+ )
+ optim_future = training_client.optim_step_async(
+ tt.AdamParams(
+ learning_rate=args.lr,
+ betas=(0.9, 0.999),
+ weight_decay=0.01,
+ grad_clip=1.0,
+ )
+ )
+
+ # Collect results
+ fwdbwd_result = fwdbwd_future.result()
+ optim_future.result()
+ return fwdbwd_result
+
+def main(args):
+ service_client = ServiceClient(api_key=args.tinker_api_key)
+
+ training_client = service_client.create_lora_training_client(
+ base_model=args.base_model,
+ lora_config=tt.LoraConfig(rank=16, seed=42),
+ )
+
+ tokenizer = training_client.get_sampling_client().tokenizer
+
+ for epoch in range(args.epochs):
+ # 1. Run cua-bench rollouts with current policy
+ run_id = run_cuabench_rollouts(args)
+
+ # 2. Load traces
+ run_dir = f"~/.local/share/cua-bench/runs/{run_id}"
+ episodes = load_run_episodes(run_dir)
+
+ # 3. Log stats
+ avg_reward = sum(ep.terminal_reward for ep in episodes) / max(len(episodes), 1)
+ print(f"Epoch {epoch}: {len(episodes)} episodes, avg_reward={avg_reward:.3f}")
+
+ # 4. Train
+ train_epoch(training_client, episodes, tokenizer, args)
+
+ # 5. Save weights and get new sampling client
+ sampling_client = training_client.save_weights_and_get_sampling_client()
+
+ # 6. Checkpoint full state every N epochs
+ if (epoch + 1) % args.checkpoint_every == 0:
+ ckpt_path = training_client.save_state(name=f"epoch-{epoch+1}").result()
+ print(f"Checkpoint saved: {ckpt_path}")
+
+ # 7. Hot-reload updated weights into vLLM
+ sync_weights_to_vllm(training_client, args.vllm_url)
+
+def run_cuabench_rollouts(args) -> str:
+ """Launch a cua-bench dataset run and return the run_id."""
+ import subprocess, re
+ result = subprocess.run([
+ "cb", "run", "dataset", args.tasks_path,
+ "--agent", "opencua",
+ "--model", args.model,
+ "--max-steps", str(args.max_steps),
+ ], capture_output=True, text=True)
+ run_id = re.search(r"run-[a-f0-9-]+", result.stdout).group(0)
+ # Wait for all sessions to complete (cb run watch or poll cb run info)
+ wait_for_run(run_id)
+ return run_id
+```
+
+### Phase 4: Weight sync to vLLM
+
+After each Tinker training step the updated LoRA weights must reload into the running vLLM server so that subsequent cua-bench rollouts use the new policy.
+
+**New file**: `cua_bench/rl/weight_sync.py`
+
+```python
+"""
+Download LoRA checkpoint from Tinker and hot-reload into a running vLLM instance.
+"""
+import requests
+import tarfile
+import tempfile
+from pathlib import Path
+
+def sync_weights_to_vllm(training_client, vllm_base_url: str):
+ """
+ 1. Save weights to Tinker checkpoint
+ 2. Download tar archive
+ 3. POST to vLLM's /load_lora_adapter endpoint
+ """
+ # Save weights-only checkpoint (faster than save_state)
+ ckpt_path = training_client.save_weights_for_sampler(name="current").result()
+
+ # Get signed download URL via RestClient
+ rest_client = training_client.service_client.create_rest_client()
+ url_response = rest_client.get_checkpoint_archive_url_from_tinker_path(ckpt_path)
+
+ # Download tar archive
+ with tempfile.TemporaryDirectory() as tmpdir:
+ archive_path = Path(tmpdir) / "lora.tar"
+ r = requests.get(url_response.url, stream=True)
+ r.raise_for_status()
+ with open(archive_path, "wb") as f:
+ for chunk in r.iter_content(chunk_size=8192):
+ f.write(chunk)
+
+ # Extract LoRA adapter files
+ with tarfile.open(archive_path) as tar:
+ tar.extractall(tmpdir)
+
+ adapter_dir = Path(tmpdir) / "adapter"
+
+ # Hot-reload via vLLM dynamic LoRA API
+ requests.post(
+ f"{vllm_base_url}/load_lora_adapter",
+ json={
+ "lora_name": "opencua-current",
+ "lora_path": str(adapter_dir),
+ }
+ ).raise_for_status()
+```
+
+### Phase 5: Resume training from checkpoint
+
+```python
+# Resume full training state (weights + optimizer momentum)
+training_client = service_client.create_training_client_from_state_with_optimizer(
+ checkpoint_path="tinker://<model_id>/epoch-5"
+)
+
+# Resume weights only (fresh optimizer)
+training_client = service_client.create_lora_training_client(
+ base_model=args.base_model,
+ lora_config=tt.LoraConfig(rank=16),
+ initial_checkpoint="tinker://<model_id>/epoch-5",
+)
+```
+
+---
+
+## 5. File Structure
+
+```
+libs/cua-bench/
+├── cua_bench/
+│ └── rl/
+│ ├── __init__.py
+│ ├── trace_reader.py # Load HF Dataset traces → Episode objects
+│ ├── datum_builder.py # Episode → Tinker Datum (tokenized, masked)
+│ ├── train.py # Main RL training loop (entry point)
+│ └── weight_sync.py # Download Tinker checkpoint → reload vLLM
+├── plan.md # This file
+└── pyproject.toml # Add tinker to [project.optional-dependencies]
+```
+
+Add to `pyproject.toml`:
+```toml
+[project.optional-dependencies]
+rl = [
+ "tinker",
+ "transformers>=4.57.0,<5.0",
+]
+```
+
+---
+
+## 6. End-to-End Training Script
+
+```bash
+# 1. Start vLLM with base model
+vllm serve Qwen/Qwen3-8B \
+ --served-model-name opencua \
+ --enable-lora \
+ --host 0.0.0.0 --port 30000
+
+# 2. Set env vars
+export OPENCUA_BASE_URL=http://localhost:30000/v1
+export OPENCUA_API_KEY=EMPTY
+export TINKER_API_KEY=<your_tinker_key>
+
+# 3. Run RL training loop
+python -m cua_bench.rl.train \
+ --base-model Qwen/Qwen3-8B \
+ --tasks-path tasks/slack_env \
+ --model openai/opencua \
+ --max-steps 50 \
+ --epochs 20 \
+ --lr 1e-5 \
+ --gamma 0.99 \
+ --checkpoint-every 5 \
+ --vllm-url http://localhost:30000/v1
+```
+
+---
+
+## 7. Key Design Decisions
+
+| Decision | Rationale |
+|---|---|
+| **Sparse reward** | `evaluate_task` returns a single terminal reward per episode; intermediate steps get reward 0.0 and the terminal step gets the full reward |
+| **Monte Carlo returns** with simple baseline | Simple, unbiased, works well with sparse rewards; GAE would need a value network |
+| **PPO loss in Tinker** | Standard choice for LLM RL; clip thresholds prevent oversized updates when off-policy rollouts diverge |
+| **LoRA fine-tuning** | Tinker only supports LoRA currently; keeps checkpoint size small for fast sync to vLLM |
+| **Weights-only sync to vLLM** | `save_weights_for_sampler` is faster than `save_state`; vLLM's dynamic LoRA API avoids server restart |
+| **Async Tinker calls** | Submit `forward_backward_async` and `optim_step_async` without awaiting between them to keep both in the same ~10s Tinker clock cycle |
+| **Screenshot as model input** | Each `agent_step` trace row has a screenshot; use the most recent as the visual context for that step's datum |
+
+---
+
+## 8. Open Questions / Future Work
+
+1. **Reference policy for IS ratio**: PPO needs log-probs from both current policy (from Tinker `compute_logprobs`) and sampling policy (from vLLM generation). Need to capture vLLM log-probs at rollout time and store them in trace metadata.
+
+2. **Dense rewards**: Currently uses sparse evaluation reward. Could add partial rewards (e.g., intermediate task completion signals from `evaluate_task` called mid-episode) for faster learning.
+
+3. **Multi-task batching**: Different task types may have very different reward scales. Per-task reward normalization or separate baselines may be needed.
+
+4. **Rollout parallelism**: `cb run dataset` already parallelizes across tasks. Tinker's clock-cycle architecture means training throughput is bounded by how many rollout batches can be collected per ~10s cycle.
+
+5. **Vision input**: OpenCUA is a vision-language model. Tinker supports Qwen3-VL via `ImageChunk`. The datum builder must encode screenshots as Tinker image chunks rather than base64 strings.
+
+6. **SL warm-start before RL**: Use `save_state` after a supervised learning phase, then `create_training_client_from_state_with_optimizer` to continue into RL without losing optimizer momentum.
diff --git a/libs/cua-bench/pyproject.toml b/libs/cua-bench/pyproject.toml
index f24ec9e30d..8c85789a4f 100644
--- a/libs/cua-bench/pyproject.toml
+++ b/libs/cua-bench/pyproject.toml
@@ -54,6 +54,7 @@ dependencies = [
# CUA SDK
"cua-computer>=0.4.19",
"cua-core>=0.1.18",
+ "playwright>=1.55.0",
]
[project.optional-dependencies]
diff --git a/libs/python/agent/agent/agent.py b/libs/python/agent/agent/agent.py
index 95906a4e4a..3d64a4dbc6 100644
--- a/libs/python/agent/agent/agent.py
+++ b/libs/python/agent/agent/agent.py
@@ -639,7 +639,7 @@ class ComputerAgent:
for callback in self.callbacks:
if hasattr(callback, "on_run_continue"):
should_continue = await callback.on_run_continue(kwargs, old_items, new_items)
- if not should_continue:
+ if not should_continue:
return False
return True
@@ -1022,9 +1022,6 @@ class ComputerAgent:
)
result = get_json(result)
- # Lifecycle hook: Postprocess messages after the LLM call
- # Use cases:
- # - PII deanonymization (if you want tool calls to see PII)
result["output"] = await self._on_llm_end(result.get("output", []))
await self._on_responses(loop_kwargs, result)
@@ -1033,7 +1030,7 @@ class ComputerAgent:
# Add agent response to new_items
new_items += result.get("output")
-
+
# Get output call ids
output_call_ids = get_output_call_ids(result.get("output", []))
@@ -1042,6 +1039,15 @@ class ComputerAgent:
partial_items = await self._handle_item(
item, self.computer_handler, ignore_call_ids=output_call_ids
)
+
+ if partial_items:
+ for pi in partial_items:
+ pi_type = pi.get("type", "")
+ if pi_type == "computer_call_output":
+ output = pi.get("output", {})
+ has_image = "image_url" in output if isinstance(output, dict) else False
+
+
new_items += partial_items
# Yield partial response if any
diff --git a/libs/python/agent/agent/loops/__init__.py b/libs/python/agent/agent/loops/__init__.py
index 2b528cad68..1bad824017 100644
--- a/libs/python/agent/agent/loops/__init__.py
+++ b/libs/python/agent/agent/loops/__init__.py
@@ -18,6 +18,8 @@ from . import (
omniparser,
openai,
opencua,
+ qwen3vl,
+ qwen35,
uiins,
uitars,
uitars2,
@@ -39,6 +41,8 @@ __all__ = [
"omniparser",
"openai",
"opencua",
+ "qwen3vl",
+ "qwen35",
"uiins",
"uitars",
"uitars2",
diff --git a/libs/python/agent/agent/loops/opencua.py b/libs/python/agent/agent/loops/opencua.py
index ee7fec93a4..b35d059af2 100644
--- a/libs/python/agent/agent/loops/opencua.py
+++ b/libs/python/agent/agent/loops/opencua.py
@@ -1,24 +1,36 @@
"""
-OpenCUA agent loop implementation for click prediction using litellm.acompletion
+OpenCUA agent loop implementation for click prediction and step execution using litellm.acompletion.
Based on OpenCUA model for GUI grounding tasks.
"""
-import asyncio
import base64
+import io
import json
-import math
import re
import uuid
-from io import BytesIO
-from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, Union
+from typing import Any, Dict, List, Optional, Tuple
import litellm
+from litellm.responses.litellm_completion_transformation.transformation import (
+ LiteLLMCompletionResponsesConfig,
+)
from PIL import Image
from ..decorators import register_agent
from ..loops.base import AsyncAgentConfig
-from ..types import AgentCapability, AgentResponse, Messages, Tools
+from ..responses import (
+ convert_completion_messages_to_responses_items,
+ convert_responses_items_to_completion_messages,
+ make_reasoning_item,
+)
+from ..types import AgentCapability
from .composed_grounded import ComposedGroundedConfig
+from .generic_vlm import (
+ QWEN3_COMPUTER_TOOL,
+ _build_nous_system,
+ _parse_tool_call_from_text,
+ convert_qwen_tool_args_to_computer_action,
+)
def extract_coordinates_from_click(text: str) -> Optional[Tuple[int, int]]:
@@ -39,9 +51,23 @@ def extract_coordinates_from_click(text: str) -> Optional[Tuple[int, int]]:
return None
+def _rescale_coordinate(
+ x: int,
+ y: int,
+ orig_w: int,
+ orig_h: int,
+ resized_w: int,
+ resized_h: int,
+) -> Tuple[int, int]:
+ """Rescale coordinates from resized image space back to original image space."""
+ if resized_w == 0 or resized_h == 0:
+ return (x, y)
+ return (round(x * orig_w / resized_w), round(y * orig_h / resized_h))
+
+
@register_agent(models=r"(?i).*OpenCUA.*")
class OpenCUAConfig(ComposedGroundedConfig):
- """OpenCUA agent configuration implementing AsyncAgentConfig protocol for click prediction."""
+ """OpenCUA agent configuration implementing AsyncAgentConfig protocol for click prediction and step execution."""
def __init__(self):
super().__init__()
@@ -56,27 +82,305 @@ class OpenCUAConfig(ComposedGroundedConfig):
max_retries: Optional[int] = None,
stream: bool = False,
computer_handler=None,
+ use_prompt_caching: Optional[bool] = False,
_on_api_start=None,
_on_api_end=None,
_on_usage=None,
_on_screenshot=None,
**kwargs,
) -> Dict[str, Any]:
- """Fallback to a self-composed model"""
- return await super().predict_step(
- messages=messages,
- model=f"{model}+{model}",
- tools=tools,
- max_retries=max_retries,
- stream=stream,
- computer_handler=computer_handler,
- _on_api_start=_on_api_start,
- _on_api_end=_on_api_end,
- _on_usage=_on_usage,
- _on_screenshot=_on_screenshot,
- **kwargs,
+ """Predict the next step using the OpenCUA model with smart resize (factor=28)."""
+
+ # Convert responses items to completion messages
+ converted_msgs = convert_responses_items_to_completion_messages(
+ messages,
+ allow_images_in_tool_results=False,
)
+ # Build function schemas from tools array
+ function_schemas: List[Dict[str, Any]] = []
+ if tools:
+ from ..computers import is_agent_computer
+
+ for tool in tools:
+ tool_type = tool.get("type")
+ if tool_type == "computer":
+ computer = tool.get("computer")
+ if computer and is_agent_computer(computer):
+ function_schemas.append(QWEN3_COMPUTER_TOOL["function"])
+ elif tool_type == "function":
+ function_schema = tool.get("function")
+ if function_schema:
+ function_schemas.append(function_schema)
+
+ if not function_schemas:
+ function_schemas = [QWEN3_COMPUTER_TOOL["function"]]
+
+ # Prepend Nous-generated system prompt with tool schema
+ nous_system = _build_nous_system(function_schemas)
+ completion_messages = ([nous_system] if nous_system else []) + converted_msgs
+
+ # ------------------------------------------------------------------
+ # If there are no screenshots in the conversation, take one now
+ # ------------------------------------------------------------------
+ def _has_any_image(msgs: List[Dict[str, Any]]) -> bool:
+ for m in msgs:
+ content = m.get("content")
+ if isinstance(content, list):
+ for p in content:
+ if isinstance(p, dict) and p.get("type") == "image_url":
+ return True
+ return False
+
+ def _has_screenshot_message(msgs: List[Dict[str, Any]]) -> bool:
+ screenshot_text = "Taking a screenshot to see the current computer screen."
+ for m in msgs:
+ content = m.get("content")
+ if isinstance(content, str) and screenshot_text in content:
+ return True
+ if isinstance(content, list):
+ for p in content:
+ if isinstance(p, dict) and p.get("type") == "text":
+ if screenshot_text in (p.get("text") or ""):
+ return True
+ return False
+
+ pre_output_items: List[Dict[str, Any]] = []
+ if not _has_any_image(completion_messages):
+ if computer_handler is None or not hasattr(computer_handler, "screenshot"):
+ raise RuntimeError(
+ "No screenshots present and computer_handler.screenshot is not available."
+ )
+ screenshot_b64 = await computer_handler.screenshot()
+ if not screenshot_b64:
+ raise RuntimeError("Failed to capture screenshot from computer_handler.")
+ completion_messages.append(
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:image/png;base64,{screenshot_b64}"},
+ },
+ {"type": "text", "text": "Current screen"},
+ ],
+ }
+ )
+ if not _has_screenshot_message(messages):
+ pre_output_items.append(
+ {
+ "type": "message",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "Taking a screenshot to see the current computer screen.",
+ }
+ ],
+ }
+ )
+
+ # ------------------------------------------------------------------
+ # Smart-resize all screenshots with factor=28
+ # Unlike generic_vlm (which sets min/max pixel hints for the provider),
+ # OpenCUA uses an OpenAI-compatible endpoint that does not honour those
+ # hints, so we actually resize the image before sending.
+ # ------------------------------------------------------------------
+ MIN_PIXELS = 3136
+ MAX_PIXELS = 12845056
+ FACTOR = 28
+
+ try:
+ from qwen_vl_utils import smart_resize # type: ignore
+ except ImportError:
+ raise ImportError(
+ "qwen-vl-utils not installed. Please install it with: pip install qwen-vl-utils"
+ )
+
+ last_orig_w: Optional[int] = None
+ last_orig_h: Optional[int] = None
+ last_rw: Optional[int] = None
+ last_rh: Optional[int] = None
+
+ for msg in completion_messages:
+ content = msg.get("content")
+ if not isinstance(content, list):
+ continue
+ for part in content:
+ if isinstance(part, dict) and part.get("type") == "image_url":
+ url = ((part.get("image_url") or {}).get("url")) or ""
+ if url.startswith("data:") and "," in url:
+ b64 = url.split(",", 1)[1]
+ img_bytes = base64.b64decode(b64)
+ im = Image.open(io.BytesIO(img_bytes))
+ orig_h, orig_w = im.height, im.width
+ rh, rw = smart_resize(
+ orig_h,
+ orig_w,
+ factor=FACTOR,
+ min_pixels=MIN_PIXELS,
+ max_pixels=MAX_PIXELS,
+ )
+
+ # Actually resize the image
+ resized_im = im.resize((rw, rh))
+ buf = io.BytesIO()
+ resized_im.save(buf, format="PNG")
+ new_b64 = base64.b64encode(buf.getvalue()).decode("utf-8")
+ part["image_url"]["url"] = f"data:image/png;base64,{new_b64}"
+
+ last_orig_w, last_orig_h = orig_w, orig_h
+ last_rw, last_rh = rw, rh
+
+ # ------------------------------------------------------------------
+ # Call litellm
+ # ------------------------------------------------------------------
+ api_kwargs: Dict[str, Any] = {
+ "model": model,
+ "messages": completion_messages,
+ "max_retries": max_retries,
+ "stream": stream,
+ **{k: v for k, v in kwargs.items()},
+ }
+ if use_prompt_caching:
+ api_kwargs["use_prompt_caching"] = use_prompt_caching
+
+ if _on_api_start:
+ await _on_api_start(api_kwargs)
+
+ response = await litellm.acompletion(**api_kwargs)
+
+ if _on_api_end:
+ await _on_api_end(api_kwargs, response)
+
+ usage = {
+ **LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage( # type: ignore
+ response.usage
+ ).model_dump(),
+ "response_cost": response._hidden_params.get("response_cost", 0.0),
+ }
+ if _on_usage:
+ await _on_usage(usage)
+
+ # ------------------------------------------------------------------
+ # Parse response
+ # ------------------------------------------------------------------
+ resp_dict = response.model_dump() # type: ignore
+ choice = (resp_dict.get("choices") or [{}])[0]
+ message = choice.get("message") or {}
+ content_text = message.get("content") or ""
+ tool_calls_array = message.get("tool_calls") or []
+ reasoning_text = message.get("reasoning") or ""
+
+ output_items: List[Dict[str, Any]] = []
+
+ if reasoning_text:
+ output_items.append(make_reasoning_item(reasoning_text))
+
+ # Helper: rescale coordinates from resized space to original space
+ def _rescale(x: int, y: int) -> Tuple[int, int]:
+ if last_orig_w and last_orig_h and last_rw and last_rh:
+ return _rescale_coordinate(x, y, last_orig_w, last_orig_h, last_rw, last_rh)
+ return (x, y)
+
+ # Priority 1: OpenCUA native click(x=..., y=...) format
+ coords = extract_coordinates_from_click(content_text)
+ if coords:
+ x, y = _rescale(coords[0], coords[1])
+ fake_cm: Dict[str, Any] = {
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "type": "function",
+ "id": "call_0",
+ "function": {
+ "name": "computer",
+ "arguments": json.dumps({"action": "left_click", "x": x, "y": y}),
+ },
+ }
+ ],
+ }
+ output_items.extend(convert_completion_messages_to_responses_items([fake_cm]))
+
+ # Priority 2: <tool_call>...</tool_call> XML format
+ elif not tool_calls_array:
+ tool_call = _parse_tool_call_from_text(content_text)
+ if tool_call and isinstance(tool_call, dict):
+ fn_name = tool_call.get("name") or "computer"
+ raw_args = tool_call.get("arguments") or {}
+
+ # Rescale any coordinate field
+ coord = raw_args.get("coordinate")
+ if coord and isinstance(coord, (list, tuple)) and len(coord) >= 2:
+ rx, ry = _rescale(int(round(float(coord[0]))), int(round(float(coord[1]))))
+ raw_args = {**raw_args, "coordinate": [rx, ry]}
+
+ fake_cm = {
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "type": "function",
+ "id": "call_0",
+ "function": {
+ "name": fn_name,
+ "arguments": json.dumps(raw_args),
+ },
+ }
+ ],
+ }
+ output_items.extend(convert_completion_messages_to_responses_items([fake_cm]))
+ else:
+ # Plain text response
+ fake_cm = {"role": "assistant", "content": content_text}
+ output_items.extend(convert_completion_messages_to_responses_items([fake_cm]))
+
+ # Priority 3: tool_calls array from response
+ else:
+ processed_tool_calls = []
+ for tc in tool_calls_array:
+ function = tc.get("function", {})
+ fn_name = function.get("name", "computer")
+ args_str = function.get("arguments", "{}")
+
+ try:
+ args = json.loads(args_str)
+
+ # Rescale coordinates if present
+ coord = args.get("coordinate")
+ if coord and isinstance(coord, (list, tuple)) and len(coord) >= 2:
+ rx, ry = _rescale(
+ int(round(float(coord[0]))), int(round(float(coord[1])))
+ )
+ args = {**args, "coordinate": [rx, ry]}
+
+ # Convert Qwen format to Computer Calls format
+ if fn_name == "computer":
+ converted_action = convert_qwen_tool_args_to_computer_action(args)
+ if converted_action:
+ args = converted_action
+
+ processed_tool_calls.append(
+ {
+ "type": tc.get("type", "function"),
+ "id": tc.get("id", "call_0"),
+ "function": {
+ "name": fn_name,
+ "arguments": json.dumps(args),
+ },
+ }
+ )
+ except json.JSONDecodeError:
+ processed_tool_calls.append(tc)
+
+ fake_cm = {
+ "role": "assistant",
+ "content": content_text if content_text else "",
+ "tool_calls": processed_tool_calls,
+ }
+ output_items.extend(convert_completion_messages_to_responses_items([fake_cm]))
+
+ return {"output": (pre_output_items + output_items), "usage": usage}
+
async def predict_click(
self, model: str, image_b64: str, instruction: str, **kwargs
) -> Optional[Tuple[int, int]]:
@@ -122,13 +426,12 @@ class OpenCUAConfig(ComposedGroundedConfig):
# Extract response text
output_text = response.choices[0].message.content
- # print(output_text)
- # Extract coordinates from click format (supports both click() and pyautogui.click() for backwards compatibility)
+ # Extract coordinates from click format
coordinates = extract_coordinates_from_click(output_text)
return coordinates
def get_capabilities(self) -> List[AgentCapability]:
"""Return the capabilities supported by this agent."""
- return ["click"]
+ return ["click", "step"]
diff --git a/libs/python/agent/agent/loops/qwen35.py b/libs/python/agent/agent/loops/qwen35.py
new file mode 100644
index 0000000000..55b0ff636e
--- /dev/null
+++ b/libs/python/agent/agent/loops/qwen35.py
@@ -0,0 +1,685 @@
+"""
+Qwen3-VL agent loop implementation using litellm with function/tool calling.
+- Passes a ComputerUse tool schema to acompletion
+- Converts between Responses items and completion messages using helpers
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Any, Dict, List, Optional, Tuple
+
+import litellm
+from litellm.responses.litellm_completion_transformation.transformation import (
+ LiteLLMCompletionResponsesConfig,
+)
+
+from ..decorators import register_agent
+from ..loops.base import AsyncAgentConfig
+from ..responses import (
+ convert_completion_messages_to_responses_items,
+ convert_responses_items_to_completion_messages,
+ make_reasoning_item,
+)
+from ..types import AgentCapability
+
+# ComputerUse tool schema (OpenAI function tool format)
+QWEN3_5_COMPUTER_TOOL: Dict[str, Any] = {
+ "type": "function",
+ "function": {
+ "name": "computer",
+ "description": (
+ "* `key`: Performs key down presses on the arguments passed in order, then performs key releases in reverse order.\n"
+ "* `type`: Type a string of text on the keyboard.\n"
+ "* `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on the screen.\n"
+ "* `left_click`: Click the left mouse button at a specified (x, y) pixel coordinate on the screen. Optional `text` parameter can specify modifier keys (e.g., \"ctrl\", \"shift\", \"ctrl+shift\") that will be held during the click.\n"
+ "* `left_click_drag`: Click and drag the cursor to a specified (x, y) pixel coordinate on the screen.\n"
+ "* `right_click`: Click the right mouse button at a specified (x, y) pixel coordinate on the screen. Optional `text` parameter can specify modifier keys that will be held during the click.\n"
+ "* `middle_click`: Click the middle mouse button at a specified (x, y) pixel coordinate on the screen. Optional `text` parameter can specify modifier keys that will be held during the click.\n"
+ "* `double_click`: Double-click the left mouse button at a specified (x, y) pixel coordinate on the screen. Optional `text` parameter can specify modifier keys that will be held during the click.\n"
+ "* `triple_click`: Triple-click the left mouse button at a specified (x, y) pixel coordinate on the screen (simulated as double-click since it's the closest action). Optional `text` parameter can specify modifier keys that will be held during the click.\n"
+ "* `scroll`: Performs a scroll of the mouse scroll wheel. Optional `text` parameter can specify a modifier key (e.g., \"shift\", \"ctrl\") that will be held during scrolling.\n"
+ "* `hscroll`: Performs a horizontal scroll (mapped to regular scroll). Optional `text` parameter can specify a modifier key that will be held during scrolling.\n"
+ "* `wait`: Wait specified seconds for the change to happen.\n"
+ # "* `terminate`: Terminate the current task and report its completion status.\n"
+ # "* `answer`: Answer a question.\n"
+ ),
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "action": {
+ "description": "The action to perform.",
+ "enum": [
+ "key",
+ "type",
+ "mouse_move",
+ "left_click",
+ "left_click_drag",
+ "right_click",
+ "middle_click",
+ "double_click",
+ "triple_click",
+ "scroll",
+ "hscroll",
+ # "screenshot",
+ "wait",
+ # "terminate",
+ # "answer",
+ ],
+ "type": "string",
+ },
+ "keys": {
+ "description": "Required only by action=key.",
+ "type": "array",
+ "items": {"type": "string"},
+ },
+ "text": {
+ "description": "Required only by action=type and action=answer.",
+ "type": "string",
+ },
+ "coordinate": {
+ "description": "(x, y): Pixel coordinates from top-left.",
+ "type": "array",
+ "items": {"type": ["number", "integer"]},
+ "minItems": 2,
+ "maxItems": 2,
+ },
+ "pixels": {
+ "description": "Scroll amount. Positive=up, negative=down. For scroll/hscroll.",
+ "type": "number",
+ },
+ "time": {
+ "description": "Seconds to wait (action=wait).",
+ "type": "number",
+ },
+ # "status": {
+ # "description": "Task status (action=terminate).",
+ # "type": "string",
+ # "enum": ["success", "failure"],
+ # },
+ },
+ "required": ["action"],
+ },
+ },
+}
+
+
+def _build_nous_system(functions: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
+ """Use qwen-agent NousFnCallPrompt to generate a system message embedding tool schema."""
+ try:
+ from qwen_agent.llm.fncall_prompts.nous_fncall_prompt import (
+ ContentItem as NousContentItem,
+ )
+ from qwen_agent.llm.fncall_prompts.nous_fncall_prompt import (
+ Message as NousMessage,
+ )
+ from qwen_agent.llm.fncall_prompts.nous_fncall_prompt import (
+ NousFnCallPrompt,
+ )
+ except ImportError:
+ raise ImportError(
+ "qwen-agent not installed. Please install it with `pip install cua-agent[qwen]`."
+ )
+ msgs = NousFnCallPrompt().preprocess_fncall_messages(
+ messages=[
+ NousMessage(
+ role="system", content=[NousContentItem(text="You are a helpful assistant.")]
+ )
+ ],
+ functions=functions,
+ lang="en",
+ )
+ sys = msgs[0].model_dump()
+ # Convert qwen-agent structured content to OpenAI-style content list
+ content = [{"type": "text", "text": c["text"]} for c in sys.get("content", [])]
+ return {"role": "system", "content": content}
+
+
+def _parse_tool_call_from_text(text: str) -> Optional[Dict[str, Any]]:
+ """Extract a tool call from <tool_call>...</tool_call> in model text.
+
+ Handles two formats:
+ 1. JSON: ``<tool_call>{"name": "computer", "arguments": {...}}</tool_call>``
+ 2. XML-style (qwen35-4b): ``<tool_call><function=computer><parameter=action>left_click</parameter>...</tool_call>``
+ """
+ # --- Format 1: JSON ---
+ m = re.search(r"<tool_call>\s*(\{[\s\S]*?\})\s*</tool_call>", text)
+ if m:
+ try:
+ return json.loads(m.group(1))
+ except Exception:
+ pass
+
+ # --- Format 2: XML-style <function=name><parameter=key>value</parameter> ---
+ fn_match = re.search(
+ r"<tool_call>\s*<function=(\w+)>([\s\S]*?)</function>\s*</tool_call>", text
+ )
+ if fn_match:
+ fn_name = fn_match.group(1)
+ params_block = fn_match.group(2)
+ # Extract all <parameter=key>value</parameter> pairs
+ params: Dict[str, Any] = {}
+ for pm in re.finditer(
+ r"<parameter=(\w+)>\s*([\s\S]*?)\s*</parameter>", params_block
+ ):
+ key = pm.group(1)
+ val = pm.group(2).strip()
+ # Try to parse as JSON (for arrays/numbers), fall back to string
+ try:
+ params[key] = json.loads(val)
+ except (json.JSONDecodeError, ValueError):
+ params[key] = val
+ # The XML format uses <parameter=type> for the action field name,
+ # but the Qwen tool schema calls it "action". Remap if we got
+ # "type" that looks like an action name rather than a literal type.
+ if "type" in params and "action" not in params:
+ params["action"] = params.pop("type")
+ return {"name": fn_name, "arguments": params}
+
+ return None
+
+
+async def _unnormalize_coordinate(args: Dict[str, Any], dims: Tuple[int, int]) -> Dict[str, Any]:
+ """Coordinates appear in 0..1000 space, scale to actual screen size using dims if provided."""
+ coord = args.get("coordinate")
+ if not coord or not isinstance(coord, (list, tuple)) or len(coord) < 2:
+ return args
+ x, y = float(coord[0]), float(coord[1])
+ width, height = float(dims[0]), float(dims[1])
+ x_abs = max(0.0, min(width, (x / 1000.0) * width))
+ y_abs = max(0.0, min(height, (y / 1000.0) * height))
+ args = {**args, "coordinate": [round(x_abs), round(y_abs)]}
+ return args
+
+
+def convert_qwen_tool_args_to_computer_action(args: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+ """
+ Convert Qwen computer tool arguments to the Computer Calls action schema.
+
+ Qwen (example):
+ {"action": "left_click", "coordinate": [114, 68]}
+
+ Target (example):
+ {"action": "left_click", "x": 114, "y": 68}
+
+ Other mappings:
+ - right_click, middle_click, double_click (triple_click -> double_click)
+ - mouse_move -> { action: "move", x, y }
+ - key -> { action: "keypress", keys: [...] }
+ - type -> { action: "type", text }
+ - scroll/hscroll -> { action: "scroll", scroll_x, scroll_y, x, y }
+ - wait -> { action: "wait" }
+ - terminate/answer are not direct UI actions; return None for now
+ """
+ if not isinstance(args, dict):
+ return None
+
+ action = args.get("action")
+ if not isinstance(action, str):
+ return None
+
+ # Coordinates helper
+ coord = args.get("coordinate")
+ x = y = None
+ if isinstance(coord, (list, tuple)) and len(coord) >= 2:
+ try:
+ x = int(round(float(coord[0])))
+ y = int(round(float(coord[1])))
+ except Exception:
+ x = y = None
+
+ # Map actions
+ a = action.lower()
+ if a in {"left_click", "right_click", "middle_click", "double_click"}:
+ if x is None or y is None:
+ return None
+ return {"action": a, "x": x, "y": y}
+ if a == "triple_click":
+ # Approximate as double_click
+ if x is None or y is None:
+ return None
+ return {"action": "double_click", "x": x, "y": y}
+ if a == "mouse_move":
+ if x is None or y is None:
+ return None
+ return {"action": "move", "x": x, "y": y}
+ if a == "key":
+ keys = args.get("keys")
+ if isinstance(keys, list) and all(isinstance(k, str) for k in keys):
+ return {"action": "keypress", "keys": keys}
+ return None
+ if a == "type":
+ text = args.get("text")
+ if isinstance(text, str):
+ return {"action": "type", "text": text}
+ return None
+ if a in {"scroll", "hscroll"}:
+ pixels = args.get("pixels") or 0
+ try:
+ pixels_val = int(round(float(pixels)))
+ except Exception:
+ pixels_val = 0
+ scroll_x = pixels_val if a == "hscroll" else 0
+ scroll_y = pixels_val if a == "scroll" else 0
+ # Include cursor position if available (optional)
+ out: Dict[str, Any] = {"action": "scroll", "scroll_x": scroll_x, "scroll_y": scroll_y}
+ if x is not None and y is not None:
+ out.update({"x": x, "y": y})
+ return out
+ if a == "wait":
+ return {"action": "wait"}
+
+ # Non-UI or terminal actions: terminate/answer -> not mapped here
+ return None
+
+
+@register_agent(models=r"(?i).*qwen35.*", priority=1)
+class Qwen35Config(AsyncAgentConfig):
+ async def predict_step(
+ self,
+ messages: List[Dict[str, Any]],
+ model: str,
+ tools: Optional[List[Dict[str, Any]]] = None,
+ max_retries: Optional[int] = None,
+ stream: bool = False,
+ computer_handler=None,
+ use_prompt_caching: Optional[bool] = False,
+ _on_api_start=None,
+ _on_api_end=None,
+ _on_usage=None,
+ _on_screenshot=None,
+ **kwargs,
+ ) -> Dict[str, Any]:
+ # Build messages using NousFnCallPrompt system with tool schema in text
+ # Start with converted conversation (images/text preserved)
+ converted_msgs = convert_responses_items_to_completion_messages(
+ messages,
+ allow_images_in_tool_results=False,
+ )
+
+ # print(f"The number of items in the converted_msgs: {len(converted_msgs)}")
+
+ # Build function schemas from tools array
+ function_schemas = []
+ if tools:
+ from ..computers import is_agent_computer
+
+ for tool in tools:
+ tool_type = tool.get("type")
+
+ if tool_type == "computer":
+ # For computer tools, use QWEN3_COMPUTER_TOOL schema
+ computer = tool.get("computer")
+ if computer and is_agent_computer(computer):
+ function_schemas.append(QWEN3_5_COMPUTER_TOOL["function"])
+ elif tool_type == "function":
+ # For function tools, use the provided function schema
+ function_schema = tool.get("function")
+ if function_schema:
+ function_schemas.append(function_schema)
+
+ # If no tools provided or no computer tool found, use default QWEN3_COMPUTER_TOOL
+ if not function_schemas:
+ function_schemas = [QWEN3_5_COMPUTER_TOOL["function"]]
+
+ # print(f"[qwen35] function_schemas: {function_schemas}")
+
+ # Prepend Nous-generated system if available
+ nous_system = _build_nous_system(function_schemas)
+ completion_messages = ([nous_system] if nous_system else []) + converted_msgs
+
+ # If there is no screenshot in the conversation, take one now and inject it.
+ # Also record a pre_output_items assistant message to reflect action.
+ def _has_any_image(msgs: List[Dict[str, Any]]) -> bool:
+ for m in msgs:
+ content = m.get("content")
+ if isinstance(content, list):
+ for p in content:
+ if isinstance(p, dict) and p.get("type") == "image_url":
+ return True
+ return False
+
+ def _has_screenshot_message(msgs: List[Dict[str, Any]]) -> bool:
+ """Check if messages already contain the 'Taking a screenshot' text."""
+ screenshot_text = "Taking a screenshot to see the current computer screen."
+ for m in msgs:
+ content = m.get("content")
+ if isinstance(content, str) and screenshot_text in content:
+ return True
+ if isinstance(content, list):
+ for p in content:
+ if isinstance(p, dict) and p.get("type") == "text":
+ if screenshot_text in (p.get("text") or ""):
+ return True
+ return False
+
+ pre_output_items: List[Dict[str, Any]] = []
+ if not _has_any_image(completion_messages):
+ if computer_handler is None or not hasattr(computer_handler, "screenshot"):
+ raise RuntimeError(
+ "No screenshots present and computer_handler.screenshot is not available."
+ )
+ screenshot_b64 = await computer_handler.screenshot()
+ if not screenshot_b64:
+ raise RuntimeError("Failed to capture screenshot from computer_handler.")
+ # Inject a user message with the screenshot so the model can see current context
+ completion_messages.append(
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:image/png;base64,{screenshot_b64}"},
+ },
+ {"type": "text", "text": "Current screen"},
+ ],
+ }
+ )
+ # Add assistant message to outputs to reflect the action, only if not already present
+ if not _has_screenshot_message(messages):
+ pre_output_items.append(
+ {
+ "type": "message",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "Taking a screenshot to see the current computer screen.",
+ }
+ ],
+ }
+ )
+
+ # Smart-resize all screenshots and attach min/max pixel hints. Fail fast if deps missing.
+ # Also record the last resized width/height to unnormalize coordinates later.
+ last_rw: Optional[int] = None
+ last_rh: Optional[int] = None
+ MIN_PIXELS = 3136
+ MAX_PIXELS = 12845056
+ try:
+ import base64
+ import io
+
+ from PIL import Image # type: ignore
+ from qwen_vl_utils import smart_resize # type: ignore
+ except Exception:
+ raise ImportError(
+ "qwen-vl-utils not installed. Please install it with `pip install cua-agent[qwen]`."
+ )
+
+ for msg in completion_messages:
+ content = msg.get("content")
+ if not isinstance(content, list):
+ continue
+ for part in content:
+ if isinstance(part, dict) and part.get("type") == "image_url":
+ url = ((part.get("image_url") or {}).get("url")) or ""
+ # Expect data URL like data:image/png;base64,<b64>
+ if url.startswith("data:") and "," in url:
+ b64 = url.split(",", 1)[1]
+ img_bytes = base64.b64decode(b64)
+ im = Image.open(io.BytesIO(img_bytes))
+ h, w = im.height, im.width
+ rh, rw = smart_resize(
+ h, w, factor=32, min_pixels=MIN_PIXELS, max_pixels=MAX_PIXELS
+ )
+ # Attach hints on this image block
+ part["min_pixels"] = MIN_PIXELS
+ part["max_pixels"] = MAX_PIXELS
+ last_rw, last_rh = rw, rh
+
+ for i, msg in enumerate(completion_messages):
+ role = msg.get("role")
+ content = msg.get("content")
+ if isinstance(content, list):
+ step_content = []
+ for item in content:
+ item_type = item.get("type")
+ if item_type == "text":
+ step_content.append(item.get('text'))
+ elif item_type == "image_url":
+ step_content.append("Image URL: " + item.get('image_url').get('url')[:100])
+ else:
+ item = content
+ step_content = ""
+ if isinstance(item, dict) and item.get("type") == "image_url":
+ step_content = "Image URL: " + item.get('image_url').get('url')[:100]
+ else:
+ step_content = content
+
+ print(f"Step {i}: Role: {role}, Content: {step_content}")
+
+ api_kwargs: Dict[str, Any] = {
+ "model": model,
+ "messages": completion_messages,
+ "max_retries": max_retries,
+ "stream": stream,
+ **{k: v for k, v in kwargs.items()},
+ }
+ if use_prompt_caching:
+ api_kwargs["use_prompt_caching"] = use_prompt_caching
+
+ if _on_api_start:
+ await _on_api_start(api_kwargs)
+
+ response = await litellm.acompletion(**api_kwargs)
+
+ if _on_api_end:
+ await _on_api_end(api_kwargs, response)
+
+ usage = {
+ **LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage( # type: ignore
+ response.usage
+ ).model_dump(),
+ "response_cost": response._hidden_params.get("response_cost", 0.0),
+ }
+ if _on_usage:
+ await _on_usage(usage)
+
+ # Extract response data
+ resp_dict = response.model_dump() # type: ignore
+ choice = (resp_dict.get("choices") or [{}])[0]
+ message = choice.get("message") or {}
+ content_text = message.get("content") or ""
+ tool_calls_array = message.get("tool_calls") or []
+ reasoning_text = message.get("reasoning") or ""
+
+ output_items: List[Dict[str, Any]] = []
+
+ # Add reasoning if present (Ollama Cloud format)
+ if reasoning_text:
+ output_items.append(make_reasoning_item(reasoning_text))
+
+ # Priority 1: Try to parse tool call from content text (OpenRouter format)
+ tool_call = _parse_tool_call_from_text(content_text)
+
+ if tool_call and isinstance(tool_call, dict):
+ fn_name = tool_call.get("name") or "computer"
+ raw_args = tool_call.get("arguments") or {}
+
+ output_items.append({
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": content_text}],
+ })
+
+ # Unnormalize coordinates to actual screen size using last resized dims
+ if last_rw is None or last_rh is None:
+ raise RuntimeError(
+ "No screenshots found to derive dimensions for coordinate unnormalization."
+ )
+ args = await _unnormalize_coordinate(raw_args, (last_rw, last_rh))
+
+ # Convert Qwen format to Computer Calls format if this is a computer tool
+ if fn_name == "computer":
+ converted_action = convert_qwen_tool_args_to_computer_action(args)
+ if converted_action:
+ args = converted_action
+
+ # Build an OpenAI-style tool call so we can reuse the converter
+ fake_cm = {
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "type": "function",
+ "id": "call_0",
+ "function": {
+ "name": fn_name,
+ "arguments": json.dumps(args),
+ },
+ }
+ ]
+ }
+ output_items.extend(convert_completion_messages_to_responses_items([fake_cm]))
+
+ elif tool_calls_array:
+
+ output_items.append({
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": content_text}],
+ })
+
+ processed_tool_calls = []
+ for tc in tool_calls_array:
+ function = tc.get("function", {})
+ fn_name = function.get("name", "computer")
+ args_str = function.get("arguments", "{}")
+
+ try:
+ args = json.loads(args_str)
+
+ # Unnormalize coordinates if present
+ if "coordinate" in args and last_rw is not None and last_rh is not None:
+ args = await _unnormalize_coordinate(args, (last_rw, last_rh))
+
+ # Convert Qwen format to Computer Calls format if this is a computer tool
+ if fn_name == "computer":
+ converted_action = convert_qwen_tool_args_to_computer_action(args)
+ if converted_action:
+ args = converted_action
+
+ processed_tool_calls.append(
+ {
+ "type": tc.get("type", "function"),
+ "id": tc.get("id", "call_0"),
+ "function": {
+ "name": fn_name,
+ "arguments": json.dumps(args),
+ },
+ }
+ )
+ except json.JSONDecodeError:
+ processed_tool_calls.append(tc)
+
+ fake_cm = {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": processed_tool_calls,
+ }
+ output_items.extend(convert_completion_messages_to_responses_items([fake_cm]))
+
+ else:
+ # No tool calls found in either format, return text response
+ fake_cm = {"role": "assistant", "content": content_text}
+ output_items.extend(convert_completion_messages_to_responses_items([fake_cm]))
+
+ # Prepend any pre_output_items (e.g., simulated screenshot-taking message)
+ return {"output": (pre_output_items + output_items), "usage": usage}
+
+ def get_capabilities(self) -> List[AgentCapability]:
+ return ["click", "step"]
+
+ async def predict_click(
+ self, model: str, image_b64: str, instruction: str, **kwargs
+ ) -> Optional[Tuple[int, int]]:
+ """
+ Predict click coordinates using Qwen3-VL via litellm.acompletion.
+
+ Only exposes a reduced tool schema with left_click to bias model to output a single click.
+ Returns (x, y) absolute pixels when screen dimensions can be obtained; otherwise normalized 0..1000 integers.
+ """
+ # Reduced tool
+ reduced_tool = {
+ "type": "function",
+ "function": {
+ **QWEN3_5_COMPUTER_TOOL["function"],
+ "parameters": {**QWEN3_5_COMPUTER_TOOL["function"]["parameters"],
+ "type": "object",
+ "properties": {
+ "action": {"type": "string", "enum": ["left_click"]},
+ "coordinate": {
+ "description": "(x, y) in 0..1000 reference space",
+ "type": "array",
+ "items": {"type": ["number", "integer"]},
+ "minItems": 2,
+ "maxItems": 2,
+ },
+ },
+ "required": ["action", "coordinate"],
+ },
+ },
+ }
+
+ # Build Nous system (lazy import inside helper already raises clear guidance if missing)
+ nous_system = _build_nous_system([reduced_tool["function"]])
+
+ # Pre-process using smart_resize
+ min_pixels = 3136
+ max_pixels = 12845056
+ try:
+ # Lazy import to avoid hard dependency
+ import base64
+ import io
+
+ # If PIL is available, estimate size from image to derive smart bounds
+ from PIL import Image
+ from qwen_vl_utils import smart_resize # type: ignore
+
+ img_bytes = base64.b64decode(image_b64)
+ im = Image.open(io.BytesIO(img_bytes))
+ h, w = im.height, im.width
+ # Qwen notebook suggests factor=32 and a wide min/max range
+ rh, rw = smart_resize(h, w, factor=32, min_pixels=min_pixels, max_pixels=max_pixels)
+ except Exception:
+ raise ImportError(
+ "qwen-vl-utils not installed. Please install it with `pip install cua-agent[qwen]`."
+ )
+
+ messages = []
+ if nous_system:
+ messages.append(nous_system)
+ image_block: Dict[str, Any] = {
+ "type": "image_url",
+ "image_url": {"url": f"data:image/png;base64,{image_b64}"},
+ "min_pixels": min_pixels,
+ "max_pixels": max_pixels,
+ }
+ # Single user message with image and instruction, matching OpenAI-style content blocks
+ messages.append(
+ {
+ "role": "user",
+ "content": [
+ image_block,
+ {"type": "text", "text": instruction},
+ ],
+ }
+ )
+
+ api_kwargs: Dict[str, Any] = {
+ "model": model,
+ "messages": messages,
+ **{k: v for k, v in kwargs.items()},
+ }
+ response = await litellm.acompletion(**api_kwargs)
+ resp = response.model_dump() # type: ignore
+ choice = (resp.get("choices") or [{}])[0]
+ content_text = ((choice.get("message") or {}).get("content")) or ""
+ tool_call = _parse_tool_call_from_text(content_text) or {}
+ args = tool_call.get("arguments") or {}
+ args = await _unnormalize_coordinate(args, (rh, rw))
+ coord = args.get("coordinate")
+ if isinstance(coord, (list, tuple)) and len(coord) >= 2:
+ return int(coord[0]), int(coord[1])
+ return None
diff --git a/libs/python/agent/agent/loops/qwen3vl.py b/libs/python/agent/agent/loops/qwen3vl.py
new file mode 100644
index 0000000000..507c4a9c32
--- /dev/null
+++ b/libs/python/agent/agent/loops/qwen3vl.py
@@ -0,0 +1,17 @@
+"""
+Qwen3-VL dedicated agent loop configuration.
+Re-exports GenericVlmConfig under a Qwen-specific model pattern so that
+Qwen model strings are matched at normal priority instead of the generic
+catch-all (priority -100).
+"""
+
+from __future__ import annotations
+
+from ..decorators import register_agent
+from .generic_vlm import GenericVlmConfig
+
+
+@register_agent(models=r"(?i).*qwen.*")
+class Qwen3VlConfig(GenericVlmConfig):
+ """Qwen3-VL agent loop using litellm with function/tool calling."""
+ pass