Skip to main content





Tutorial: Building OpenAI computer use agents with observability
Build a GPT-5.4 computer use agent for browser and desktop tasks, trace every screenshot, click, and decision with W&B Weave.
Last updated: June 1, 2026
Computer use agents can now click buttons, fill forms, navigate browsers, and control desktop applications autonomously. The problem is what happens when they fail. The agent saw a screenshot, clicked something, and the task went sideways. Without instrumentation, debugging means rerunning the agent and hoping to reproduce the failure.
This is the agent observability gap in computer use. The agent's inputs are images, and its outputs are coordinates. Standard text-based logging captures none of it. You cannot debug what you cannot see.
This tutorial builds a working GPT-5.4 computer use agent in Python and instruments every step with W&B Weave. By the end, every screenshot the agent saw, every click it executed, and every reasoning step it produced will be captured in a visual trace you can replay and inspect. The agent runs in two environments: browser automation via Playwright and desktop control via a containerized Linux environment.

Image by author
Table of content
Building a GPT-5.4 computer use agentComputer use agent architectureThe tutorialPrerequisitesStep 1: SetupStep 2: Initialize Weave and OpenAIStep 3: Build the perception-action loopStep 4: Execute actions with PlaywrightStep 5: Screenshot overlays and thinking textStep 6: Browser use caseStep 7: Desktop use caseStep 8: Run the desktop agentStep 9: Debug a failure in WeaveProduction considerationsConclusion
Building a GPT-5.4 computer use agent
The end state is a GPT-5.4 computer use agent with full Weave observability across two environments.
Agent capabilities:
- Browser mode: navigate websites, extract information, interact with UI elements via Playwright
- Desktop mode: control a Linux desktop environment running in Docker
Weave observability layer:
- Screenshots with red circle overlays at click coordinates
- Model thinking text logged between steps
- Per-step latency, token cost, and action metadata
- A trace dashboard to replay the full agent trajectory
Computer use agent architecture

Image by author
The computer use agent's architecture follows a continuous perception-action loop. GPT-5.4 receives a task prompt and returns a computer_call action, a click, a keystroke, or a scroll. That action routes to one of two environments: Playwright for browser tasks or a Docker Linux desktop for desktop tasks.
The environment executes the action and captures a screenshot. Pillow annotates it with a red circle at the click coordinates before it gets logged to W&B Weave alongside the model's thinking text.
That annotated screenshot feeds back into GPT-5.4 as the input for the next turn. The loop continues until the model returns a final answer or hits the turn limit.
Weave sits outside the loop as a pure observability layer; the agent runs identically with or without it.
The tutorial
Prerequisites
Requirements:
- Python 3.10 or higher
- OpenAI API key with GPT-5.4 access
- Weights & Biases account (free tier is sufficient)
- Docker (for the desktop use case)
Step 1: Setup
pip install openai weave pillow playwrightplaywright install chromium
Create a `.env` file in the project root with your API keys:
WANDB_API_KEY=your-wandb-api-keyOPENAI_API_KEY=your-openai-api-key
Using a .env file keeps credentials out of source code. The python-dotenv library loads these values at runtime via load_dotenv().
For desktop tasks, pull the Linux desktop container:
docker pull ghcr.io/anthropics/anthropic-quickstarts:computer-use-demo-latest
This container runs a full Linux desktop with a VNC interface accessible on localhost. It works on macOS, Windows, and Linux without additional configuration.
Step 2: Initialize Weave and OpenAI
Create a new file called agent.py and add the following setup block at the top:
import osimport timeimport base64import weavefrom dotenv import load_dotenvfrom openai import OpenAIfrom playwright.sync_api import sync_playwrightfrom PIL import Image, ImageDrawimport ioload_dotenv()os.environ["WANDB_API_KEY"] = os.getenv("WANDB_API_KEY")weave.init("computer-use-agent")client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
load_dotenv() reads the .env file and makes the keys available via os.getenv(). The WANDB_API_KEY is set explicitly in `os.environ` so Weave can authenticate automatically.
weave.init("computer-use-agent") creates or connects to a Weave project and activates tracing for every function decorated with @weave.op() from this point forward.
When this runs, Weave prints the project URL to the terminal:
Logged in as <your-username>. View project at:
Open that URL and keep it in a browser tab. It starts empty but populates in real time as the agent runs.
Step 3: Build the perception-action loop
The perception-action loop is the core of any computer-use agent. It works as follows:
- Send the task description to GPT-5.4 via the Responses API
- The model returns a computer_call containing one or more actions
- Execute each action in the environment
- Capture a new screenshot after each action
- Send the screenshot back using previous_response_id to chain turns
- Repeat until the model returns a final message or the turn limit is reached
Using previous_response_id is simpler and more reliable than manually rebuilding a messages list each turn. The API handles conversation state on the server side.
First, add the reasoning extractor helper, which pulls the model's thinking text out of the response before any actions are processed:
def extract_reasoning(response):thinking = ""for item in response.output:if item.type == "reasoning":thinking = str(item.content)return thinking
Then wrap the full agent loop in @weave.op() so the entire execution appears as a single top-level trace in Weave with each turn as a child span:
@weave.op()def run_agent(task, max_turns=20):with sync_playwright() as p:browser = p.chromium.launch(headless=False)page = browser.new_page()page.goto("https://www.wikipedia.org/")print("Starting agent...\n")response = client.responses.create(model="gpt-5.4",tools=[{"type": "computer"}],input=task,)for turn in range(1, max_turns + 1):thinking = extract_reasoning(response)computer_call = next((item for item in response.output if item.type == "computer_call"),None,)if computer_call is None:print("\nFINAL OUTPUT:\n")for item in response.output:if item.type == "message":print(item.content[0].text)breakfor action in computer_call.actions:result = execute_action(page, action)screenshot = capture(page)log_step(turn, action, screenshot, thinking, result["latency"])screenshot = capture(page)screenshot_b64 = base64.b64encode(screenshot).decode()response = client.responses.create(model="gpt-5.4",tools=[{"type": "computer"}],previous_response_id=response.id,input=[{"type": "computer_call_output","call_id": computer_call.call_id,"output": {"type": "computer_screenshot","image_url": f"data:image/png;base64,{screenshot_b64}","detail": "original",},}],)else:print("Turn limit reached")browser.close()
The loop iterates over computer_call.actions because a single model response can contain multiple actions to execute in sequence before the next screenshot is sent. Each action is executed and logged individually, then a single fresh screenshot is captured and sent back at the end of the action batch.
If you are new to Weave, the Weave quickstart walks through the core concepts, and the OpenAI integration guide covers how auto-patching works specifically with the OpenAI SDK.
Step 4: Execute actions with Playwright
Playwright handles all browser interactions. Each action type returned by GPT-5.4 maps to a specific Playwright command. Wrapping the function in @weave.op() makes each action appear as a child span in the Weave trace tree, nested under the turn it belongs to.
The scroll action uses scrollX and scrollY attributes, with getattr defaults to handle cases where those fields are absent. The keypress handler normalizes modifier keys through a key_map because GPT-5.4 may return platform-specific key names like CTRL or CMD that Playwright expects in a specific format:
@weave.op()def execute_action(page, action):start = time.time()if action.type == "click":page.mouse.click(action.x, action.y)elif action.type == "double_click":page.mouse.dblclick(action.x, action.y)elif action.type == "scroll":page.mouse.move(action.x, action.y)page.mouse.wheel(getattr(action, "scrollX", 0),getattr(action, "scrollY", 0),)elif action.type == "type":page.keyboard.type(action.text)elif action.type == "keypress":keys = [k.upper() for k in action.keys]key_map = {"CTRL": "Meta", "CONTROL": "Meta", "CMD": "Meta","ENTER": "Enter", "ESC": "Escape", "SPACE": " ",}mapped = [key_map.get(k, k) for k in keys]combo = "+".join(mapped)page.keyboard.press(combo)elif action.type == "wait":time.sleep(2)return {"latency": time.time() - start}def capture(page):return page.screenshot(type="png")
Latency is measured with time.time() around each action execution. This per-action latency surfaces in the Weave trace and makes it easy to identify slow actions, such as a page load triggered by a click that takes several seconds before the next screenshot is captured.
Test with a simple navigation task before running the full agent:
if __name__ == "__main__":run_agent("Go to wikipedia and search for penguins")
Run the script and confirm that a Chromium window opens, the agent navigates Wikipedia, and trace entries appear in the Weave project URL printed at startup.
For the complete Playwright command reference, the Playwright Python docs cover every input method used here, and the Weave ops guide explains how @weave.op() builds the parent-child span hierarchy visible in the trace tree.
Step 5: Screenshot overlays and thinking text
This is where Weave goes from a log viewer to an actual debugging tool. Raw screenshots show what the agent saw. Annotated screenshots show exactly where it clicked and what it was thinking at that moment. The combination makes agent failures immediately obvious without rerunning anything.
Annotate screenshots with Pillow:
def annotate(image_bytes, action, turn):img = Image.open(io.BytesIO(image_bytes))draw = ImageDraw.Draw(img)if hasattr(action, "x") and hasattr(action, "y"):x, y = action.x, action.yr = 15draw.ellipse((x - r, y - r, x + r, y + r), outline="red", width=3)label = f"{action.type.upper()} | step {turn}"draw.text((20, 20), label, fill="red")buf = io.BytesIO()img.save(buf, format="PNG")return buf.getvalue()
The red circle is drawn at action.x and action.y, which are the exact pixel coordinates GPT-5.4 targeted. The step label in the top-left corner shows both the action type and the turn number, making it easy to navigate a long trace timeline.
Log annotated screenshots and thinking text to Weave:
@weave.op()def log_step(turn, action, screenshot, thinking, latency):annotated = annotate(screenshot, action, turn)img_b64 = base64.b64encode(annotated).decode("utf-8")return {"turn": turn,"action": action.type,"thinking": thinking,"latency": latency,"action_details": str(action),"screenshot": f"data:image/png;base64,{img_b64}"}
Screenshots are stored as base64 data URIs in the Weave log. This format guarantees the image renders correctly in the Weave trace panel regardless of file storage configuration. The thinking field captures whatever reasoning text the model emitted before deciding on that action, giving a direct view into the model's decision process at each step.
The resulting trace view is the most useful artifact produced by this setup. Each row in the trace is one action. Expanding a row shows the annotated screenshot, the thinking text, the action type, and the per-action latency. Finding where an agent went wrong becomes a matter of scrolling through screenshots rather than rerunning the agent repeatedly.
Step 6: Browser use case
Run the full agent on a real browser task. The Wikipedia search task is a good starting point because it involves navigation, a search interaction, and reading content from a result page:
if __name__ == "__main__":run_agent("Go to wikipedia and search for penguins")
The agent launches Chromium, navigates to wikipedia.org, types the search query, and reads the result. A typical run like this completes in three to six turns, depending on how many intermediate actions the model generates.

Here's what that looks like:

After the run completes, open the Weave project URL. The trace panel shows every turn with its annotated screenshot, action type, thinking text, and latency. The top-level run_agent trace shows total latency and the number of child spans, one per action.
Token cost note: Each screenshot is a base64-encoded PNG passed to the vision model. At GPT-5.4 vision token rates, a full-resolution screenshot costs roughly 800 to 1,200 tokens per turn. A six-turn task uses between 5,000 and 7,000 tokens in image input alone, not counting the text prompt and response tokens. If cost is a concern, resize screenshots before encoding:
def capture(page):raw = page.screenshot(type="png")img = Image.open(io.BytesIO(raw))img = img.resize((int(img.width * 0.5), int(img.height * 0.5)))buf = io.BytesIO()img.save(buf, format="PNG")return buf.getvalue()
Step 7: Desktop use case
Switch to desktop control by launching the containerized Linux environment. Start the container with a single command:
docker run -p 5900:5900 -p 8501:8501 \ghcr.io/anthropics/anthropic-quickstarts:computer-use-demo-latest
The container exposes two ports. Port 5900 is the VNC interface for viewing the desktop visually. Port 8501 is the HTTP API used for programmatic screenshot capture and action execution. Once the container is running, the desktop is ready to accept commands.
Desktop connection setup
The agent connects to the VNC server using the mapped host port:
VNC_HOST = "127.0.0.1"VNC_PORT = 5901VNC_ADDRESS = f"{VNC_HOST}::{VNC_PORT}"def connect_vnc():vnc = api.connect(VNC_ADDRESS, password=None)vnc.timeout = 30return vnc
Reliable screenshot capture
Screenshots are captured via VNC and validated before use:
def capture_desktop(vnc_client, retries=10, delay=1.0) -> bytes:for _ in range(retries):with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:tmp_path = tmp.nametry:vnc_client.captureScreen(tmp_path)data = Path(tmp_path).read_bytes()if len(data) > 1000 and is_valid_png(data):return datafinally:Path(tmp_path).unlink(missing_ok=True)time.sleep(delay)raise RuntimeError("Could not capture a valid screenshot")
Execute desktop actions
Each action from GPT-5.4 is mapped to a VNC command:
def execute_desktop_action(vnc_client, action):start = time.time()if action.type == "click":vnc_client.mouseMove(int(action.x), int(action.y))vnc_client.mousePress(1)elif action.type == "type":text = getattr(action, "text", "")if hasattr(vnc_client, "paste"):vnc_client.paste(text)else:for ch in text:vnc_client.keyPress(ch)elif action.type == "keypress":keys = [_key_name(k) for k in action.keys]combo = "-".join(keys) if keys else "enter"vnc_client.keyPress(combo)elif action.type == "scroll":v = int(getattr(action, "scrollY", 0))vnc_client.mouseMove(int(action.x), int(action.y))button = 5 if v > 0 else 4for _ in range(max(1, abs(v) // 120)):vnc_client.mousePress(button)elif action.type == "wait":time.sleep(2)return {"latency": time.time() - start}
Desktop agent loop
The agent follows a perception-action loop with screenshot feedback:
@weave.op()def run_desktop_agent(task, max_turns=20):print("🖥️ Starting desktop agent...")time.sleep(5) # allow container to fully initializevnc = connect_vnc()screenshot = capture_desktop(vnc)response = client.responses.create(model="gpt-5.4",tools=[{"type": "computer"}],input=task,)for turn in range(1, max_turns + 1):thinking = extract_reasoning(response)computer_call = next((item for item in response.output if item.type == "computer_call"),None,)if computer_call is None:for item in response.output:if item.type == "message":print(item.content[0].text)breakfor action in computer_call.actions:result = execute_desktop_action(vnc, action)screenshot = capture_desktop(vnc)log_step(turn, action, screenshot, thinking, result["latency"])screenshot = capture_desktop(vnc)screenshot_b64 = base64.b64encode(screenshot).decode()response = client.responses.create(model="gpt-5.4",tools=[{"type": "computer"}],previous_response_id=response.id,input=[{"type": "computer_call_output","call_id": computer_call.call_id,"output": {"type": "computer_screenshot","image_url": f"data:image/png;base64,{screenshot_b64}","detail": "original",},}],)
Step 8: Run the desktop agent
if __name__ == "__main__":run_desktop_agent("""create a new file called notes.txt using touch command, type hello world, save it.Then verify the file exists and display its contents.Finally print TASK COMPLETED SUCCESSFULLY.""")


The log_step function requires no changes. It receives the same inputs regardless of environment, so annotated screenshots and thinking text appear in the Weave trace identically to the browser case.
Desktop tasks typically require more turns than browser tasks. File management operations that a human completes in three clicks often take eight to twelve agent turns because the agent must locate UI elements visually rather than via DOM selectors. The model re-examines the screen after each action to confirm the result before deciding on the next step.
Comparing the browser and desktop traces in Weave makes this difference concrete. Open both traces side by side in the Weave dashboard. The browser trace shows short turns with precise coordinates targeting known UI elements. The desktop trace shows longer turns with more reasoning text as the model interprets unfamiliar UI patterns from screenshots alone. Both traces use the same log_step structure, so the comparison is direct and the per-action latency numbers are comparable across environments.
Step 9: Debug a failure in Weave
Run the agent on a task that is likely to cause trouble. A good candidate is a multi-step interaction where a target element is small, moves after a prior action, or is obscured by a dropdown or modal:
if __name__ == "__main__":run_agent("Go to wikipedia, search for penguins, ""click the first reference link in the article, ""and return the title of that page.")
When the agent fails or gets stuck, open the trace in Weave. Navigate turn by turn through the annotated screenshots. The red circle on each screenshot shows exactly where the agent clicked. The thinking text shows what it believed it was clicking on.
A common failure pattern in browser agents: the agent clicks at coordinates that were correct in the previous screenshot, but the page has since scrolled or a tooltip has appeared, shifting the target element. Without Weave, the only signal is that the task did not complete. With Weave, the misalignment between the model's mental model and the actual screen state is visible in a single screenshot.
Production considerations
Log every run during development, but sample at 10 to 25 percent in production to control Weave storage costs
Use weave.attributes() to tag runs with task category, environment, and model version so traces are filterable in the dashboard
Treat any run that hits max_turns as a failure signal. Turn-limit exits almost always mean the agent is looping, and annotated screenshots make the loop immediately visible
Conclusion
Computer use agents are among the most capable AI systems available and among the hardest to debug. The inputs are images, and the outputs are pixel coordinates, neither of which is in a text log.
Weave makes computer use agents observable by capturing the full visual reasoning chain: what the agent saw, where it clicked, what it was thinking, and how long each step took. Every failure becomes diagnosable in a single trace view.
The same pattern applies to any agent that operates on a visual state. The perception-action loop, the screenshot annotation, and the Weave tracing layer generalize beyond computer use to any vision-based agent workflow.