Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
The computer use tool is generally available and enables agents to interact with browsers and desktop applications through their user interfaces. The model interprets screenshots and proposes actions such as clicking, typing, and scrolling. Your application executes those actions in an isolated environment and returns an updated screenshot.
The updated tool uses a simpler definition and supports an ordered batch of actions in each computer call. You can manage the interaction loop in your application or use a supported SDK toolset with an application-supplied driver. The developer can use the latest OpenAI models in Foundry that support computer use, such as GPT-6.1 series : gpt-6.1-sol, gpt-6.1-terra ; GPT-6 series : gpt-6-astra, NEW gpt-6-luna, gpt-6-sol, configure the computer tool, and attach it to the target application. See model and regional availability.
The tools supported by Open AI's computer tool are click, double_click, drag, keypress, move, screenshot, scroll, type, and wait.
In this article, you learn how to:
- Configure an agent with the computer use tool.
- Execute an ordered batch of UI actions and return a screenshot.
- Apply approval requirements, execution limits, and environment restrictions.
- Choose an integration approach for your application.
- Migrate from the
computer-use-previewmodel and tool.
Warning
(i) Important The computer use tool interacts with computer systems and applications on your behalf and can take unintended actions. Testing and monitoring are recommended.Transparency note for Azure OpenAI .
Prerequisites
Before you begin, ensure you have the following prerequisites:
- An Azure subscription and a Microsoft Foundry project.
- A deployed model that supports the
computertool in your selected region. - Permission to use the project, agent, and model deployment.
- An SDK version that supports the released tool schema, or an authenticated REST client.
- An isolated browser or desktop environment that your application can control.
- An action executor and screenshot-capture implementation, or a supported SDK toolset with a compatible driver.
- Application-side policies for allowed actions, destinations, user approvals, and execution limits.
Use the deployment name, not an assumed model identifier, when configuring the agent. Check model availability and Agent Service tool support for your deployment.
How computer use works
Computer use separates model reasoning from action execution:
- Your application sends a task.
- The model returns a
computer_callwith a screenshot request. - Your application validates the call, sends the screenshot, and checks whether user approval is required.
- Your application executes approved actions in order.
- Your application captures the resulting UI state.
- Your application sends a
computer_call_outputwith the matchingcall_idand updated screenshot. - The cycle continues until the task finishes, the user stops it, or an execution limit is reached.
User task + initial screenshot
|
v
Foundry agent
|
v
computer_call.actions[]
|
v
Validate and obtain approval
|
v
Execute actions in an isolated environment
|
v
Capture a fresh screenshot
|
v
computer_call_output
|
+----------> Foundry agent
The tool doesn't provision a computer or directly control a device. Your application remains responsible for the environment, execution policy, and action results.
How is billing configured?
The tokens for each Responses request can incur charges for input and output tokens. Screenshots count as image input. Learn more about pricing, model token limits, and regions. If you use hosted agents for setup, then Foundry agent service pricing applies.
Configure the computer use tool
Declare the tool with type set to computer:
{
"type": "computer"
}
Unlike the preview tool, the new definition doesn't require display_width, display_height, or environment.
Your executor still needs to know the actual viewport or desktop dimensions. Removing those properties from the tool definition doesn't remove the need to keep screenshots and action coordinates consistent.
Choose an integration approach
| Approach | Use when | Application responsibilities |
|---|---|---|
| Native computer tool with an application-managed loop | You need explicit control over each request, action batch, and screenshot. | Execute actions, capture screenshots, maintain history, enforce policy, and stop the loop. |
| SDK-managed computer toolset | A released SDK provides a compatible toolset and driver contract. | Supply the driver, configure limits and approval hooks, and verify task outcomes. |
Use an SDK-managed loop
The target SDK experience includes ComputerToolset and BrowserToolset integrations in Python and Node.js, with an application-supplied driver, execution limits, and a before-action hook. Confirm availability and exact signatures in the released SDK before using these names in code.
Configure the equivalent of:
- A driver that executes supported actions and returns fresh screenshots.
- A step limit that bounds model/tool iterations.
- A before-action hook that applies policy and pauses for approval.
- A timeout and user cancellation mechanism.
- Action-level limits, because one model turn can contain several actions.
A toolset can reduce orchestration code, but it doesn't replace application-side policy.
For Python, C#/.NET, TypeScript/JavaScript, and Java, use the corresponding Foundry SDK release notes and maintained samples:
- Python (
azure-ai-projects >= 2.11.0): Computer use sample and computer use helper. - C#/.NET (
Azure.AI.Projects >= 2.11.0,Azure.AI.Extensions.OpenAI >= 2.0.0): Azure.AI.Extensions.OpenAI computer use sample and Agent Framework computer use sample. - TypeScript/JavaScript (
@azure/ai-projects >= 2.11.0): Computer use sample and computer use helper. - Java (
com.azure:azure-ai-agents >= 2.9.0): Computer use sample and computer use helper.
Code samples
Warning
Use the computer use tool on virtual machines with no access to sensitive data or critical resources.
Screenshot initialization for computer use tool execution
The following excerpts demonstrate how to create an agent version with the GA ComputerTool, send an initial request with a screenshot, and perform multiple iterations (including batched computer_call.actions) to complete a task. Select Prompt Agents to use the Azure AI Projects SDK to create a server-side prompt agent, or Hosted Agents to use the Agent Framework FoundryChatClient to build an ephemeral, in-process agent.
Prompt agents
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, ComputerTool
# Import shared helper functions
from computer_use_util import (
SearchState,
load_screenshot_assets,
handle_computer_action_and_take_screenshot,
print_final_output,
)
"""Main function to demonstrate Computer Use Agent functionality (GA)."""
# Initialize state machine
current_state = SearchState.INITIAL
# Load screenshot assets
try:
screenshots = load_screenshot_assets()
print("Successfully loaded screenshot assets")
except FileNotFoundError:
print("Failed to load required screenshot assets. Use the maintained SDK sample on GitHub to get the helper file and images.")
exit(1)
Create an agent version with the tool
# Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = os.environ.get("AZURE_AI_PROJECT_ENDPOINT", "your_project_endpoint")
MODEL_DEPLOYMENT_NAME = os.environ.get("COMPUTER_USE_MODEL_DEPLOYMENT_NAME", "gpt-5.4")
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
# GA ComputerTool: serializes to {"type": "computer"} with no display size or environment needed
computer_use_tool = ComputerTool()
agent = project.agents.create_version(
agent_name="ComputerUseAgent",
definition=PromptAgentDefinition(
model=MODEL_DEPLOYMENT_NAME,
instructions="""
You are a computer automation assistant.
Be direct and efficient. When you reach the search results page, read and describe the actual search result titles and descriptions you can see.
""",
tools=[computer_use_tool],
),
description="Computer automation agent with screen interaction capabilities.",
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")
Send the initial request with a screenshot
openai = project.get_openai_client()
# Initial request with screenshot - start with Bing search page
print("Starting computer automation session (initial screenshot: cua_browser_search.png)...")
response = openai.responses.create(
input=[
{
"role": "user",
"content": [
{
"type": "input_text",
"text": "I need you to help me search for 'OpenAI news'. Please type 'OpenAI news' and submit the search. Once you see search results, the task is complete.",
},
{
"type": "input_image",
"image_url": screenshots["browser_search"]["url"],
"detail": "original",
}, # Start with Bing search page
],
}
],
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
truncation="auto",
)
print(f"Initial response received (ID: {response.id})")
Perform multiple iterations with batched actions
In the GA computer tool protocol, each computer_call item exposes a batched actions list (computer_call.actions), while remaining compatible with singular computer_call.action. Execute all actions in the batch in order, capture a fresh screenshot, and send it back in computer_call_output.
max_iterations = 10 # Allow enough iterations for completion
iteration = 0
while True:
if iteration >= max_iterations:
print(f"\nReached maximum iterations ({max_iterations}). Stopping.")
break
iteration += 1
print(f"\n--- Iteration {iteration} ---")
# Check for computer calls in the response
computer_calls = [item for item in response.output if item.type == "computer_call"]
if not computer_calls:
print_final_output(response)
break
# Process the first computer call
computer_call = computer_calls[0]
call_id = computer_call.call_id
# GA computer_call returns batched `actions` (fallback to singular `action` if needed)
actions = getattr(computer_call, "actions", None) or (
[computer_call.action] if getattr(computer_call, "action", None) else []
)
if not actions:
continue
# Never execute an action with pending safety checks without user approval.
safety_checks = getattr(computer_call, "pending_safety_checks", None) or []
if safety_checks:
for check in safety_checks:
print(f"Safety check: {check.code}: {check.message}")
if input("Approve this action? Type yes to continue: ").lower() != "yes":
print("Action rejected by the user.")
break
print(f"Processing computer call (ID: {call_id}) with {len(actions)} action(s)")
# Execute each action in the batch and update state/screenshot
screenshot_info = screenshots["browser_search"]
for action in actions:
screenshot_info, current_state = handle_computer_action_and_take_screenshot(
action, current_state, screenshots
)
print(f"Sending action result back to agent (using {screenshot_info['filename']})...")
# Regular response with just the resulting screenshot
response = openai.responses.create(
previous_response_id=response.id,
input=[
{
"call_id": call_id,
"type": "computer_call_output",
"acknowledged_safety_checks": safety_checks,
"output": {
"type": "computer_screenshot",
"image_url": screenshot_info["url"],
"detail": "original",
},
}
],
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
truncation="auto",
)
print(f"Follow-up response received (ID: {response.id})")
Clean up
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
print("Agent deleted")
Expected output
Successfully loaded screenshot assets
Agent created (id: ..., name: ComputerUseAgent, version: 1)
Starting computer automation session (initial screenshot: cua_browser_search.png)...
Initial response received (ID: ...)
--- Iteration 1 ---
Processing computer call (ID: ...) with 1 action(s)
Executing computer action: type
Typing text "OpenAI news" - Simulating keyboard input
-> Action processed: type
Sending action result back to agent (using cua_search_typed.png)...
Follow-up response received (ID: ...)
--- Iteration 2 ---
Processing computer call (ID: ...) with 1 action(s)
Executing computer action: click
Click at (512, 384) - Simulating click on UI element
-> Detected click after typing
-> Action processed: click
Sending action result back to agent (using cua_search_results.png)...
Follow-up response received (ID: ...)
--- Iteration 3 ---
No computer calls found. Agent completed the task:
Final status: completed
Final result: Here are the search results for "OpenAI news":
1. OpenAI - Official News & Announcements (https://openai.com/news)
Latest updates on GPT models, research breakthroughs, and safety initiatives from OpenAI.
2. OpenAI News - Latest Updates | Reuters
Breaking coverage of OpenAI product launches, enterprise partnerships, and AI regulation.
Agent deleted
Hosted agents
This sample uses FoundryChatClient from the Microsoft Agent Framework with the GA computer tool ({"type": "computer"}). Install the package with pip install agent-framework-foundry aiohttp, set FOUNDRY_PROJECT_ENDPOINT (point FOUNDRY_MODEL at a gpt-6.1-sol deployment), and sign in with az login.
import asyncio
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
async def main() -> None:
agent = Agent(
client=FoundryChatClient(credential=AzureCliCredential()),
instructions=(
"You are a computer automation assistant. Be direct and efficient. "
"When you reach the search results page, describe the actual result titles you can see."
),
tools=[
{"type": "computer"}
],
)
# Replace this with your screenshot capture + action handler loop.
# See the upstream samples folder for a reference implementation.
result = await agent.run(
"Help me search for 'OpenAI news'. Type the query and submit the search."
)
print(f"Agent: {result.text}")
if __name__ == "__main__":
asyncio.run(main())
Expected output
Agent: I searched for "OpenAI news" in the address bar. The top results include articles from OpenAI's blog, TechCrunch, and The Verge ...
For a full screenshot-loop implementation, see the Foundry provider samples.
Sample for use of an Agent with Computer Use tool
The following C# code sample demonstrates how to create an agent with the GA computer tool ({"type": "computer"}), send an initial request with a screenshot, and perform multiple iterations to complete a task.
Prompt agents
To enable your agent to use the GA computer tool, pass ModelReaderWriter.Read<ResponseTool>(BinaryData.FromObjectAsJson(new { type = "computer" })) when configuring DeclarativeAgentDefinition.Tools.
using System;
using System.ClientModel.Primitives;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text.Json;
using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.Identity;
using OpenAI.Responses;
class ComputerUseDemo
{
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
private static readonly string ProjectEndpoint =
Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT") ?? "your_project_endpoint";
private static readonly string ModelDeploymentName =
Environment.GetEnvironmentVariable("COMPUTER_USE_MODEL_DEPLOYMENT_NAME") ?? "gpt-5.4";
// Read image files using `ReadImageFile` method.
private static BinaryData ReadImageFile(string name, [CallerFilePath] string pth = "")
{
var dirName = Path.GetDirectoryName(pth) ?? "";
return new BinaryData(File.ReadAllBytes(Path.Combine(dirName, name)));
}
// Helper method to parse ComputerTool outputs (including batched actions) and respond with new screenshots.
private static string ProcessComputerUseCall(ComputerCallResponseItem item, string oldScreenshot)
{
string currentScreenshot = oldScreenshot;
foreach (ReadOnlyMemory<byte> actionJson in item.Patch.EnumerateArray("$.actions"u8))
{
ComputerCallAction action = ModelReaderWriter.Read<ComputerCallAction>(BinaryData.FromBytes(actionJson));
switch (action.Kind)
{
case ComputerCallActionKind.Type:
Console.WriteLine($" Typing text \"{action.TypeText}\" - Simulating keyboard input");
currentScreenshot = "search_typed";
break;
case ComputerCallActionKind.KeyPress:
if (action.KeyPressKeyCodes.Contains("Return") || action.KeyPressKeyCodes.Contains("ENTER"))
{
if (string.Equals(currentScreenshot, "search_typed"))
{
Console.WriteLine(" -> Detected ENTER key press, when search field was populated, displaying results.");
currentScreenshot = "search_results";
}
else
{
Console.WriteLine(" -> Detected ENTER key press, on results or unpopulated search, do nothing.");
}
}
else
{
Console.WriteLine($" Key press: {string.Join("+", action.KeyPressKeyCodes)} - Simulating key combination");
}
break;
case ComputerCallActionKind.Click:
Console.WriteLine($" Click at ({action.ClickCoordinates.Value.X}, {action.ClickCoordinates.Value.Y}) - Simulating click on UI element");
if (string.Equals(currentScreenshot, "search_typed"))
{
Console.WriteLine(" -> Assuming click on Search button when search field was populated, displaying results.");
currentScreenshot = "search_results";
}
else
{
Console.WriteLine(" -> Assuming click on Search on results or when search was not populated, do nothing.");
}
break;
case ComputerCallActionKind.Drag:
Console.WriteLine($" Drag path: {string.Join(" -> ", action.DragPath.Select(p => $"{p.X}, {p.Y}"))} - Simulating drag operation");
break;
case ComputerCallActionKind.Scroll:
Console.WriteLine($" Scroll at ({action.ScrollCoordinates.Value.X}, {action.ScrollCoordinates.Value.Y}) - Simulating scroll action");
break;
case ComputerCallActionKind.Screenshot:
Console.WriteLine(" Taking screenshot - Capturing current screen state");
break;
default:
break;
}
Console.WriteLine($" -> Action processed: {action.Kind}");
}
return currentScreenshot;
}
public static void Main()
{
// Create project client
AIProjectClient projectClient = new(endpoint: new Uri(ProjectEndpoint), tokenProvider: new DefaultAzureCredential());
// Read in three example screenshots and place them into a dictionary.
Dictionary<string, BinaryData> screenshots = new()
{
{ "browser_search", ReadImageFile("Assets/cua_browser_search.png") },
{ "search_typed", ReadImageFile("Assets/cua_search_typed.png") },
{ "search_results", ReadImageFile("Assets/cua_search_results.png") },
};
// Create a DeclarativeAgentDefinition with the GA ComputerTool ({"type": "computer"}).
DeclarativeAgentDefinition agentDefinition = new(model: ModelDeploymentName)
{
Instructions = "You are a computer automation assistant.\n\n" +
"Be direct and efficient. When you reach the search results page, read and describe the actual search result titles and descriptions you can see.",
Tools =
{
ModelReaderWriter.Read<ResponseTool>(BinaryData.FromObjectAsJson(new { type = "computer" })),
}
};
ProjectsAgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "myAgent",
options: new(agentDefinition)
);
Console.WriteLine($"Agent created (id: {agentVersion.Id}, name: {agentVersion.Name}, version: {agentVersion.Version})");
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentVersion.Name);
CreateResponseOptions responseOptions = new()
{
TruncationMode = ResponseTruncationMode.Auto,
InputItems =
{
ResponseItem.CreateUserMessageItem(
[
ResponseContentPart.CreateInputTextPart("I need you to help me search for 'OpenAI news'. Please type 'OpenAI news' and submit the search. Once you see search results, the task is complete."),
ResponseContentPart.CreateInputImagePart(imageBytes: screenshots["browser_search"], imageBytesMediaType: "image/png", imageDetailLevel: ResponseImageDetailLevel.High)
]),
},
};
Console.WriteLine("Starting computer automation session (initial screenshot: cua_browser_search.png)...");
bool computerUseCalled = false;
string currentScreenshot = "browser_search";
int limitIteration = 10;
int iteration = 0;
ResponseResult response;
do
{
response = responseClient.CreateResponse(responseOptions);
if (iteration == 0)
{
Console.WriteLine($"Initial response received (ID: {response.Id})");
}
else
{
Console.WriteLine($"Follow-up response received (ID: {response.Id})");
}
iteration++;
computerUseCalled = false;
responseOptions.InputItems.Clear();
responseOptions.PreviousResponseId = response.Id;
foreach (ResponseItem responseItem in response.OutputItems)
{
if (responseItem is ComputerCallResponseItem computerCall)
{
Console.WriteLine($"--- Iteration {iteration} ---");
Console.WriteLine($"Processing computer call (ID: {computerCall.CallId})");
if (computerCall.PendingSafetyChecks.Count > 0)
{
throw new InvalidOperationException(
"Pause execution and obtain end-user approval before acknowledging safety checks."
);
}
currentScreenshot = ProcessComputerUseCall(computerCall, currentScreenshot);
Console.WriteLine($"Sending action result back to agent (using cua_{currentScreenshot}.png)...");
responseOptions.InputItems.Add(
ResponseItem.CreateComputerCallOutputItem(
callId: computerCall.CallId,
output: ComputerCallOutput.CreateScreenshotOutput(
screenshotImageBytes: screenshots[currentScreenshot],
screenshotImageBytesMediaType: "image/png")));
computerUseCalled = true;
}
}
limitIteration--;
} while (computerUseCalled && limitIteration > 0);
Console.WriteLine(response.GetOutputText());
// Clean up resources by deleting Agent.
projectClient.AgentAdministrationClient.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
Console.WriteLine("Agent deleted");
}
}
Expected output
Agent created (id: ..., name: myAgent, version: 1)
Starting computer automation session (initial screenshot: cua_browser_search.png)...
Initial response received (ID: ...)
--- Iteration 1 ---
Processing computer call (ID: ...)
Typing text "OpenAI news" - Simulating keyboard input
-> Action processed: Type
Sending action result back to agent (using cua_search_typed.png)...
Follow-up response received (ID: ...)
--- Iteration 2 ---
Processing computer call (ID: ...)
Click at (512, 384) - Simulating click on UI element
-> Assuming click on Search button when search field was populated, displaying results.
-> Action processed: Click
Sending action result back to agent (using cua_search_results.png)...
Follow-up response received (ID: ...)
OpenAI news - Latest Updates
Agent deleted
Hosted agents
This sample uses the Microsoft Agent Framework and calls AsAIAgent(...) on AIProjectClient with the GA {"type": "computer"} tool definition and gpt-5.4 deployment. Install the Microsoft.Agents.AI.Foundry and Azure.AI.Projects packages, set the AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_COMPUTER_USE_DEPLOYMENT_NAME environment variables, and sign in with az login.
using System.ClientModel.Primitives;
using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Foundry;
using Microsoft.Extensions.AI;
using OpenAI.Responses;
string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_COMPUTER_USE_DEPLOYMENT_NAME") ?? "gpt-5.4";
AIProjectClient projectClient = new(new Uri(endpoint), new DefaultAzureCredential());
using IHostedFileClient fileClient = projectClient.GetProjectOpenAIClient().AsIHostedFileClient();
ResponseTool gaComputerTool = ModelReaderWriter.Read<ResponseTool>(BinaryData.FromObjectAsJson(new { type = "computer" }));
AIAgent agent = projectClient.AsAIAgent(
model: deploymentName,
name: "ComputerAgent",
instructions: "You are a computer automation assistant.",
tools: [gaComputerTool.AsAITool()]);
// Upload pre-captured screenshots that simulate browser state transitions.
// (See the full sample for ComputerUseUtil implementation.)
Dictionary<string, string> screenshots = await ComputerUseUtil.UploadScreenshotAssetsAsync(fileClient);
ChatClientAgentRunOptions runOptions = new()
{
ChatOptions = new ChatOptions
{
RawRepresentationFactory = (_) => new CreateResponseOptions { TruncationMode = ResponseTruncationMode.Auto },
}
};
ChatMessage message = new(ChatRole.User,
[
new TextContent("Search for 'OpenAI news'. Type it and submit. Once you see results, the task is complete."),
new AIContent { RawRepresentation = ResponseContentPart.CreateInputImagePart(imageFileId: screenshots["browser_search"], imageDetailLevel: ResponseImageDetailLevel.High) }
]);
AgentSession session = await agent.CreateSessionAsync();
AgentResponse response = await agent.RunAsync(message, session: session, options: runOptions);
// Loop: parse computer call actions from response, simulate them, return new screenshots.
for (int i = 0; i < 10; i++)
{
ComputerCallResponseItem? computerCall = response.Messages
.SelectMany(m => m.Contents)
.Select(c => c.RawRepresentation as ComputerCallResponseItem)
.FirstOrDefault(item => item is not null);
if (computerCall is null) break;
string fileId = screenshots["browser_search"];
foreach (ReadOnlyMemory<byte> actionJson in computerCall.Patch.EnumerateArray("$.actions"u8))
{
ComputerCallAction action = ModelReaderWriter.Read<ComputerCallAction>(BinaryData.FromBytes(actionJson));
(_, fileId) = await ComputerUseUtil.GetScreenshotAsync(action, default, screenshots);
}
AIContent callOutput = new()
{
RawRepresentation = new ComputerCallOutputResponseItem(
computerCall.CallId,
output: ComputerCallOutput.CreateScreenshotOutput(screenshotImageFileId: fileId))
};
response = await agent.RunAsync([new ChatMessage(ChatRole.User, [callOutput])], session: session, options: runOptions);
}
await ComputerUseUtil.EnsureDeleteScreenshotAssetsAsync(fileClient, screenshots);
Console.WriteLine($"Response: {response.Text}");
Expected output
Response: I searched for "OpenAI news" in the address bar. The top results include articles from OpenAI's blog, TechCrunch, and The Verge ...
For the full screenshot helper implementation and end-to-end action loop, see Agent_Step15_ComputerUse.
Sample for use of an Agent with Computer Use tool
The following TypeScript sample demonstrates how to create an agent version with the GA computer tool (tools: [{ type: "computer" }]), send an initial request with a screenshot, and perform multiple iterations (handling batched computerCall.actions with fallback to computerCall.action).
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
import { createInterface } from "node:readline/promises";
import { stdin, stdout } from "node:process";
import {
SearchState,
loadScreenshotAssets,
handleComputerActionAndTakeScreenshot,
printFinalOutput,
type ComputerAction,
} from "./computerUseUtil.js";
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = process.env["AZURE_AI_PROJECT_ENDPOINT"] || "your_project_endpoint";
const MODEL_DEPLOYMENT_NAME = process.env["COMPUTER_USE_MODEL_DEPLOYMENT_NAME"] || "gpt-5.4";
export async function main(): Promise<void> {
// Initialize state machine
let currentState = SearchState.INITIAL;
// Load screenshot assets
const screenshots = loadScreenshotAssets();
console.log("Successfully loaded screenshot assets");
// Create AI Project client
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
console.log("Creating Computer Use Agent...");
const agent = await project.agents.createVersion("ComputerUseAgent", {
kind: "prompt" as const,
model: MODEL_DEPLOYMENT_NAME,
instructions: `
You are a computer automation assistant.
Be direct and efficient. When you reach the search results page, read and describe the actual search result titles and descriptions you can see.
`.trim(),
tools: [
{
type: "computer" as const,
},
],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
// Initial request with screenshot - start with Bing search page
console.log(
"Starting computer automation session (initial screenshot: cua_browser_search.png)...",
);
let response = await openai.responses.create(
{
input: [
{
role: "user" as const,
content: [
{
type: "input_text",
text: "I need you to help me search for 'OpenAI news'. Please type 'OpenAI news' and submit the search. Once you see search results, the task is complete.",
},
{
type: "input_image",
image_url: screenshots.browser_search.url,
detail: "original" as any,
},
],
},
],
truncation: "auto",
},
{
body: { agent_reference: { name: agent.name, type: "agent_reference" } },
},
);
console.log(`Initial response received (ID: ${response.id})`);
// Main interaction loop with deterministic completion
const maxIterations = 10; // Allow enough iterations for completion
let iteration = 0;
while (iteration < maxIterations) {
iteration++;
console.log(`\n--- Iteration ${iteration} ---`);
// Check for computer calls in the response
const computerCalls = response.output.filter((item) => item.type === "computer_call");
if (computerCalls.length === 0) {
printFinalOutput({
output: response.output,
status: response.status ?? "",
});
break;
}
// Process the first computer call
const computerCall = computerCalls[0] as any;
const actions: ComputerAction[] =
computerCall.actions ?? (computerCall.action ? [computerCall.action] : []);
const callId: string = computerCall.call_id;
// Never execute an action with pending safety checks without user approval.
const safetyChecks = computerCall.pending_safety_checks ?? [];
if (safetyChecks.length > 0) {
for (const check of safetyChecks) {
console.warn(`Safety check: ${check.code}: ${check.message}`);
}
const prompt = createInterface({ input: stdin, output: stdout });
const answer = await prompt.question("Approve this action? Type yes to continue: ");
prompt.close();
if (answer.toLowerCase() !== "yes") {
throw new Error("Action rejected by the user.");
}
}
console.log(`Processing computer call (ID: ${callId}) with ${actions.length} action(s)`);
// Handle all batched actions in order and get the resulting screenshot info
let screenshotInfo = screenshots.browser_search;
for (const action of actions) {
const [nextScreenshot, updatedState] = handleComputerActionAndTakeScreenshot(
action,
currentState,
screenshots,
);
screenshotInfo = nextScreenshot;
currentState = updatedState;
}
console.log(`Sending action result back to agent (using ${screenshotInfo.filename})...`);
// Regular response with just the screenshot
response = await openai.responses.create(
{
previous_response_id: response.id,
input: [
{
call_id: callId,
type: "computer_call_output",
acknowledged_safety_checks: safetyChecks,
output: {
type: "computer_screenshot",
image_url: screenshotInfo.url,
},
},
],
truncation: "auto",
},
{
body: { agent_reference: { name: agent.name, type: "agent_reference" } },
},
);
console.log(`Follow-up response received (ID: ${response.id})`);
}
if (iteration >= maxIterations) {
console.log(`\nReached maximum iterations (${maxIterations}). Stopping.`);
}
// Clean up resources
console.log("\nCleaning up...");
await project.agents.deleteVersion(agent.name, agent.version);
console.log("Agent deleted");
console.log("\nComputer Use Agent sample completed!");
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
Expected output
Successfully loaded screenshot assets
Creating Computer Use Agent...
Agent created (id: ..., name: ComputerUseAgent, version: 1)
Starting computer automation session (initial screenshot: cua_browser_search.png)...
Initial response received (ID: ...)
--- Iteration 1 ---
Processing computer call (ID: ...) with 1 action(s)
Executing computer action: type
Typing text "OpenAI news" - Simulating keyboard input
-> Action processed: type
Sending action result back to agent (using cua_search_typed.png)...
Follow-up response received (ID: ...)
--- Iteration 2 ---
Processing computer call (ID: ...) with 1 action(s)
Executing computer action: click
Click at (512, 384) - Simulating click on UI element
-> Assuming click on Search button when search field was populated, displaying results.
-> Action processed: click
Sending action result back to agent (using cua_search_results.png)...
Follow-up response received (ID: ...)
--- Iteration 3 ---
No computer calls found. Agent completed the task:
Final status: completed
Final result: OpenAI news - Latest Updates
Cleaning up...
Agent deleted
Computer Use Agent sample completed!
Use computer use in a Java agent
Add the dependency to your pom.xml:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.9.0</version>
</dependency>
Create a computer use agent
In the GA SDK (com.azure.ai.agents.models.ComputerTool), new ComputerTool() serializes to {"type": "computer"} and requires no display dimensions or environment arguments.
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.ai.agents.models.ComputerTool;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import java.util.Collections;
public class ComputerUseExample {
// Format: "https://resource_name.services.ai.azure.com/api/projects/project_name"
private static final String PROJECT_ENDPOINT =
System.getenv().getOrDefault("FOUNDRY_PROJECT_ENDPOINT", "your_project_endpoint");
private static final String MODEL_DEPLOYMENT_NAME =
System.getenv().getOrDefault("AZURE_COMPUTER_USE_MODEL_DEPLOYMENT_NAME", "gpt-5.4");
public static void main(String[] args) {
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(PROJECT_ENDPOINT);
AgentsClient agentsClient = builder.buildAgentsClient();
ResponsesClient responsesClient = builder.buildResponsesClient();
// Create GA computer tool (serializes to {"type": "computer"})
ComputerTool tool = new ComputerTool();
// Create agent with GA computer tool
PromptAgentDefinition agentDefinition = new PromptAgentDefinition(MODEL_DEPLOYMENT_NAME)
.setInstructions("You are a computer automation assistant.")
.setTools(Collections.singletonList(tool));
AgentVersionDetails agent = agentsClient.createAgentVersion("computer-use-agent", agentDefinition);
System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion());
// Create a response with initial prompt
AgentReference agentReference = new AgentReference(agent.getName())
.setVersion(agent.getVersion());
Response response = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentReference),
ResponseCreateParams.builder()
.input("Open the browser and navigate to microsoft.com"));
System.out.println("Response: " + response.output());
// The response will contain computer_call items with actions
// to execute. Process each action in the batch, take screenshots, and
// send results back using responsesClient.createAzureResponse()
// with the previousResponseId and computer call output.
// Clean up
agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
}
}
For the complete simulated loop, use the maintained ComputerUseSync.java sample with its ComputerUseUtil.java helper. The helper maps requested actions (including batched actions) to pre-captured screenshots. Replace that simulation with your application's action executor, screenshot capture, and safety approval flow.
Use computer use with the REST API
Get an access token:
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
Create an agent with computer use
With the GA computer tool, specify "tools": [{"type": "computer"}] and a mainline computer-use model deployment such as "gpt-5.4":
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/agents?api-version=v1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"name": "computer-use-agent",
"definition": {
"kind": "prompt",
"model": "gpt-5.4",
"instructions": "You are a computer automation assistant.",
"tools": [
{
"type": "computer"
}
]
}
}'
Generate a response
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"agent_reference": {"type": "agent_reference", "name": "computer-use-agent"},
"input": "Open the browser and navigate to microsoft.com"
}'
The response includes computer_call output items with a batched actions array to execute. Before you execute any action, inspect pending_safety_checks. If the array isn't empty, pause and show the actions and safety checks to the end user. Continue only after the user explicitly approves the action.
Submit action results with screenshot
After the user approves any pending safety checks and your application executes all actions in computer_call.actions, capture a screenshot and send it back. Include each approved check in acknowledged_safety_checks. If no checks were returned, use an empty array.
curl -X POST "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d '{
"agent_reference": {"type": "agent_reference", "name": "computer-use-agent"},
"previous_response_id": "<RESPONSE_ID>",
"input": [
{
"type": "computer_call_output",
"call_id": "<CALL_ID>",
"acknowledged_safety_checks": [],
"output": {
"type": "computer_screenshot",
"image_url": "data:image/png;base64,<BASE64_SCREENSHOT>",
"detail": "original"
}
}
]
}'
Replace <RESPONSE_ID>, <CALL_ID>, and <BASE64_SCREENSHOT> with values from the previous response. Repeat this cycle until the model returns a text response instead of a computer_call.
Clean up
curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/computer-use-agent?api-version=v1" \
-H "Authorization: Bearer $AGENT_TOKEN"
Apply safety controls
Treat everything displayed inside the controlled environment as untrusted input. A webpage, document, dialog, or notification can contain instructions that conflict with the user's task.
Apply these controls independently of any model-provided safety checks:
| Control | Recommended behavior |
|---|---|
| Environment isolation | Use a dedicated sandbox with least-privilege credentials and no unrelated data or accounts. |
| Destination restrictions | Allow only required destinations. Validate redirects and enforce network restrictions outside the model. |
| Action policy | Restrict file access, clipboard use, downloads, uploads, and other capabilities to the task's needs. |
| Consequential-action approval | Obtain explicit user approval before purchases, submissions, sending messages, destructive edits, or account changes. |
| Safety-check handling | Show returned warnings to the user and pause. Acknowledge only checks that the user approved using the released API contract. |
| Sensitive workflows | Require active user supervision and don't automate beyond the approved scope. |
| Execution limits | Bound turns, actions per batch, elapsed time, and retries. Provide cancellation. |
| Auditability | Record action types, decisions, failures, and approvals without unnecessarily retaining sensitive screenshots or typed values. |
Approval should identify the specific action and its expected consequence. Don't use blanket approval for an entire session as a substitute for reviewing consequential actions.
For a batch containing a consequential action, pause before that action and any dependent actions. If policy can't be enforced safely within a batch, stop execution and return control to the user.
Migrate from computer use preview
Key changes from the previous computer use preview tool To migrate from the legacy preview integration, update the model, tool definition, and action handler:
| Category | Preview integration | GA integration |
|---|---|---|
| Model | computer-use-preview |
gpt-6.1-sol, gpt-6.1-terra, gpt-6-astra, gpt-6-luna, gpt-6-sol |
| Tool name | tools: [{ type: "computer_use_preview", display_width: ..., display_height: ..., environment: ... }] |
tools: [{ type: "computer" }] |
| Python SDK tool | ComputerUsePreviewTool(display_width=1026, display_height=769, environment="windows") |
ComputerTool() (from azure.ai.projects.models import ComputerTool) |
| C#/.NET SDK tool | ResponseTool.CreateComputerTool(environment, displayWidth, displayHeight) |
ModelReaderWriter.Read<ResponseTool>(BinaryData.FromObjectAsJson(new { type = "computer" })) |
| TypeScript/JS SDK tool | { type: "computer_use_preview", display_width: 1026, display_height: 769, environment: "windows" } |
{ type: "computer" } |
| Java SDK tool | new ComputerUsePreviewTool(ComputerEnvironment.WINDOWS, 1026, 769) |
new ComputerTool() (com.azure.ai.agents.models.ComputerTool) |
| Actions | One action on each computer_call |
A batched actions[] array on each computer_call |
| Truncation | truncation: "auto" required |
truncation not necessary |
Replace the preview tool definition:
{
"type": "computer_use_preview",
"display_width": 1024,
"display_height": 768,
"environment": "windows"
}
With:
{
"type": "computer"
}
Update handlers that read computer_call.action to iterate through computer_call.actions in order. Don't wrap the old handler in concurrent execution.
Validate the migrated application
Before switching production traffic:
- Confirm that the replacement deployment accepts the tool definition.
- Run a narrow task with a live screenshot and verify a matching tool output.
- Test a multi-action batch with focus changes or navigation.
- Test modifier keys and extra mouse buttons if your application uses them.
- Test screenshot scaling, viewport changes, and coordinate mapping.
- Verify approval, denial, cancellation, destination restrictions, and returned safety checks.
- Verify that a partial batch failure stops dependent actions and surfaces an error.
- Verify action limits as well as turn limits.
- Measure task success, elapsed time, turns, and cost on representative workflows.
- Remove the preview deployment only after the replacement is verified and your rollback plan permits it.
Batched actions can reduce model round trips. The actual effect on latency and cost depends on the task, deployment, action executor, and amount of validation required.
Safety check handling
"input":[
{
"type": "computer_call_output",
"call_id": "<call_id>",
"acknowledged_safety_checks": [
{
"id": "<safety_check_id>",
"code": "malicious_instructions",
"message": "We've detected instructions that may cause your application to perform malicious or unauthorized actions. Please acknowledge this warning if you'd like to proceed."
}
],
"output": {
"type": "computer_screenshot",
"image_url": "<image_url>"
}
}
]
Troubleshooting
| Issue | What to check |
|---|---|
The API rejects type: "computer". |
Confirm that the tool is available in your release, the selected deployment supports it, and the SDK/API version uses the new schema. |
| The response doesn't contain a computer call. | Check the response status, agent configuration, deployment compatibility, and whether the task requires UI interaction. |
Your handler expects action, but receives actions. |
Update the handler for ordered batches. Review compatibility before sharing code between preview and updated integrations. |
| Actions target the wrong location. | Check screenshot dimensions, viewport size, desktop scaling, and any coordinate transform. |
| Later actions run in the wrong window or field. | Preserve batch order and verify focus and navigation before dependent actions. |
| The agent repeatedly requests screenshots. | Return a fresh screenshot of the actual environment and verify that your executor applied the requested actions. |
| A safety check or approval requirement interrupts execution. | Pause, show the action and warning to the user, and resume only through the documented approval flow. |
| The batch partially executes. | Stop dependent actions, capture the current state when safe, and surface the failure. Don't replay the whole batch blindly. |
| The loop reaches its limit. | Report that the task is incomplete. Investigate stale screenshots, failed actions, or insufficient limits before increasing the limit. |
| An SDK toolset or helper can't be imported. | Check package version and release availability. Use a maintained sample with its required assets rather than preview-only helper names. |
Clean up
When testing is complete:
- Delete test agent versions and model deployments that you no longer need.
- Shut down or dispose of the isolated execution environment.
- Remove temporary screenshots and downloads according to your retention policy.
- Revoke temporary credentials and close test sessions.
If an example creates an agent version, clean up that version rather than deleting an agent shared with other applications. Handle cleanup on failure and cancellation as well as successful completion.