Skip to content

Computer Use

ComputerUse lets your agent use a desktop. It adds one tool, computer, that the model calls with mouse and keyboard actions. The actions run on the screen of the run’s workspace, and the tool returns a screenshot of the result.

Source

While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy.

Get started

Terminal
pip install "pydantic-ai-harness[anthropic]"

Use your model provider’s extra instead of anthropic. Set ANTHROPIC_API_KEY, and have Docker running.

computer_use.py
from pydantic_ai import Agent
from pydantic_ai_harness import ComputerUse, DockerContainer

agent = Agent('anthropic:claude-sonnet-5-5', capabilities=[DockerContainer(desktop=True), ComputerUse()])

result = agent.run_sync('Open Firefox and find the current Python release on python.org.')
print(result.output)

The first run builds a desktop image with Firefox, which takes a few minutes. The agent then looks at the screen, clicks and types until it has the answer, and prints it. The container keeps running afterwards; to remove it, see Clean up.

Models

The model must accept images. On the models listed under OpenAI, Anthropic and Google, it gets its provider’s own computer use tool. Every other model, and any model with ComputerUse(native=False), gets computer as a regular function tool.

Sandboxes

SandboxTurn on its screen
DockerDockerContainer(desktop=True)
boxdBoxdSandbox(desktop=True)
BoxLiteBoxLiteSandbox(desktop=True)
DaytonaDaytonaSandbox(desktop=True)
E2BE2BSandbox(desktop=True)
Fly.io SpritesSpritesSandbox(desktop=True)
KubernetesKubernetesSandbox(warm_pool=..., desktop=True)
ModalModalSandbox(desktop=True)
OpenSandboxOpenSandbox(image=..., desktop=True)
RenderRenderSandbox(desktop=True)
smolvmSmolSandbox(desktop=True)

For any other workspace, see Your own display.

What the display needs

Daytona and boxd start their own desktops. Every other sandbox above needs these programs:

  • Xvfb, unless an X server is already running
  • xdotool
  • xwininfo (Debian’s x11-utils)
  • scrot
  • setsid
  • fluxbox, tint2 and xterm, for the windows, the panel and its terminal, on every sandbox but E2B, which uses its template’s XFCE desktop (startxfce4) instead

The first use of the display installs any that are missing with apt-get, as root or with passwordless sudo. Add them to your image so the first use doesn’t wait for the install. If one of the first five can’t be installed, the run ends with a WorkspaceUnavailableError naming what’s missing. Without the last three, the screen works without the panel. To give the agent a browser, install one in your image, such as firefox-esr.

Drags move the pointer in steps with short pauses, so a web page’s drag-and-drop sees them. Now and then a page still misses one.

Safety

The model controls a real screen, and anything it clicks or types happens. Run it in a sandbox that holds only what the task needs. To approve each call that does more than look at the screen, raise ApprovalRequired from a before_tool_execute hook:

computer_use_ask_before_acting.py
from pydantic_ai import ApprovalRequired
from pydantic_ai.capabilities import Hooks
from pydantic_ai.computer_use import COMPUTER_KIND

hooks = Hooks()


@hooks.on.before_tool_execute
async def ask_before_acting(ctx, *, call, tool_def, args):
    looking = {'screenshot', 'zoom', 'wait', 'cursor_position'}
    if tool_def.tool_kind == COMPUTER_KIND.id and not ctx.tool_call_approved:
        if any(action.type not in looking for action in args['actions']):
            raise ApprovalRequired
    return args

Gemini can flag an action for a person to approve. ComputerUse then asks for approval itself, after your hooks run, so no hook can skip it. If your own hook already asked and the call was approved, that approval counts. A Gemini agent without a way to resolve the approval fails at the first flagged action; see Google for the handler to add.

A read-only workspace gets no computer tool, since actions on the screen can change anything the workspace holds.

Durable execution

Use TemporalDurability or PrefectDurability; the deprecated TemporalAgent, PrefectAgent and DBOSAgent can’t run ComputerUse. Each computer call is one durable step, and a step cut off before it was recorded can run again. On Temporal, set these on TemporalDurability:

  • activity_config=ActivityConfig(start_to_close_timeout=..., retry_policy=RetryPolicy(maximum_attempts=1)): a timeout longer than your longest call (the default is 60 seconds), and one attempt so a call never runs twice (the default retries without limit).
  • model_activity_config=ActivityConfig(retry_policy=RetryPolicy()), and toolset_activity_config for other tools: this gives them back the retries the line above takes away.
  • External storage: after a few steps, the screenshots pass Temporal’s 2 MB payload limit.

Your own display

To give your own workspace backend a screen, implement SupportsDisplay: a display property that returns the same Display every time, or None for no screen, without doing I/O. A Display has display_size(), screenshot(), which returns PNG bytes, and act(), which runs one DisplayAction. Positions are in screenshot pixels. Raise UnsupportedActionError for an action it can’t do exactly. For the zoom and cursor_position actions, also implement SupportsZoom and SupportsCursorPosition. See the API reference.

Errors and limits

  • If the workspace is gone, for example because its sandbox was deleted, the run ends with WorkspaceUnavailableError.
  • Each computer call takes one model request, so a long task can reach the default request_limit of 50. To allow more, pass higher UsageLimits.
  • Every request sends all the earlier screenshots again. They are the main cost, which ComputerUse lowers by turning on prompt caching, and a long run can reach a provider’s image limit: Claude refuses a request with more than 100 images on its models with a 200k-token context.
  • A 1280x800 screen suits every model. A larger one costs more tokens per screenshot.
  • On Claude, a screenshot over the model’s image size limit fails the request or makes clicks miss; see Anthropic.
  • If the screen changes size, a call that gives positions is refused until the model takes a new screenshot.
  • When one computer call in a model response fails, the response’s later computer calls don’t run, and the model is told so.
  • A drag must finish within one run, approvals included: when a run ends, held mouse buttons are released.

API reference

ComputerUse

Bases: AbstractCapability[AgentDepsT]

Lets the agent see and control the screen of its workspace through one computer tool.

The model calls the tool with mouse and keyboard actions. They run in order, and the tool returns a screenshot. The workspace’s backend needs a screen, which means it implements SupportsDisplay, as a sandbox started with a desktop does. The model has to accept images to see the screen. One that can’t gets a note in place of each screenshot.

Attributes

settle_seconds

How long, in seconds, to wait at most for the screen to stop changing after acting, before a zoom or screenshot.

ComputerUse takes screenshots until two in a row match. 0 takes the screenshot at once. A wait action from the model adds to this time.

Type: float Default: 2

native

Give the model its provider’s own computer tool when it has one, such as Claude’s or OpenAI’s.

ComputerUse runs that tool’s calls. False sends the computer function tool to every model instead. OpenAI’s own computer tool can’t zoom, triple-click, hold a key, press or release a mouse button, or read the pointer position; the function tool can.

Type: bool Default: True

id

The capability’s fixed ID. An agent controls one screen, so it has one ComputerUse.

Type: str | None Default: 'computer_use'

description

What the model reads about the capability before it loads it, when defer_loading=True defers it.

Type: str | None Default: "See and control the screen of the computer you work on. Load it when the work needs the screen: using a program's window, checking what the screen shows, or doing what the user asked to be done on the screen."

Methods

get_model_settings
def get_model_settings() -> AgentModelSettings[AgentDepsT]

Turn on prompt caching, unless the run’s settings already say whether to cache.

Returns

AgentModelSettings[AgentDepsT]

get_native_tools
def get_native_tools() -> Sequence[AgentNativeTool[AgentDepsT]]

The provider’s own computer tool, whose calls this capability runs, unless native is False.

Returns

Sequence[AgentNativeTool[AgentDepsT]]

wrap_run

@async

def wrap_run(
    ctx: RunContext[AgentDepsT],
    *,
    handler: WrapRunHandler,
) -> AgentRunResult[Any]

Release any mouse buttons still pressed when the run ends, however it ends, even if the caller stops it.

Returns

AgentRunResult[Any]

ActionsPerformedEvent

Bases: CapabilityEvent

A computer call finished and returned a screenshot. tool_call_id says which call.

Attributes

result

What the call did. The tool result’s metadata keeps the same record in the message history.

Type: ComputerResult

Display

Bases: Protocol

A screen that takes screenshots, mouse input and keyboard input.

Positions are in screenshot pixels, counted from the top left corner. A display may start its screen on the first method call. It can also implement SupportsZoom and SupportsCursorPosition.

Methods

display_size

@async

def display_size() -> tuple[int, int]

The (width, height) of the next screenshot, in pixels. Every action’s positions are in this space.

The size can change between calls.

Returns

tuple[int, int]

screenshot

@async

def screenshot() -> bytes

Capture the whole screen as PNG bytes, at the size display_size reports.

Returns

bytes

act

@async

def act(action: DisplayAction) -> None

Run one action.

Raise UnsupportedActionError for an action, or a value of it, that the display can’t run exactly. That includes action types added after the display was written. Raise it only before the action has changed anything on the screen.

Returns

None

SupportsDisplay

Bases: Protocol

A workspace backend with a Display for ComputerUse to drive.

Attributes

display

This workspace’s display, or None when it has no screen. Reading it must not do I/O.

It returns the same object for as long as the backend exists, even after the screen restarts or reconnects.

Type: Display | None

SupportsZoom

Bases: Protocol

An optional extra for a Display: capture part of the screen.

Methods

zoom

@async

def zoom(region: Region) -> bytes

Capture the region as PNG bytes. The region and the image are in screenshot pixels.

Returns

bytes

SupportsCursorPosition

Bases: Protocol

An optional extra for a Display: report where the pointer is.

Methods

cursor_position

@async

def cursor_position() -> Point

The pointer’s position in screenshot pixels.

Returns

Point

DisplayAction

A mouse or keyboard action for a Display to run, with positions in the display’s own pixels.

Later releases may add action types, so a display raises UnsupportedActionError for a type it doesn’t know.

Type: TypeAlias Default: Annotated[Click | MouseMove | Drag | MouseDown | MouseUp | Scroll | TypeText | PressKeys | HoldKeys, Field(discriminator='type')]

UnsupportedActionError

Bases: WorkspaceError

Raised by a Display that can’t run an action, or this value of it.

Raise it only before the action has changed anything on the screen. ComputerUse tells the model the action failed, and the actions after it in the call don’t run.