-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Fix and simplify ComputerUse sample #5075
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
SergeyMenshykh
merged 4 commits into
microsoft:main
from
SergeyMenshykh:computer-use-sample
Apr 7, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file added
BIN
+402 KB
...agents/AgentsWithFoundry/Agent_Step15_ComputerUse/Assets/cua_browser_search.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed
BIN
-2.5 MB
...agents/AgentsWithFoundry/Agent_Step15_ComputerUse/Assets/cua_browser_search.png
Binary file not shown.
Binary file added
BIN
+85.4 KB
...agents/AgentsWithFoundry/Agent_Step15_ComputerUse/Assets/cua_search_results.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed
BIN
-51.2 KB
...agents/AgentsWithFoundry/Agent_Step15_ComputerUse/Assets/cua_search_results.png
Binary file not shown.
Binary file added
BIN
+357 KB
...2-agents/AgentsWithFoundry/Agent_Step15_ComputerUse/Assets/cua_search_typed.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed
BIN
-2.27 MB
...2-agents/AgentsWithFoundry/Agent_Step15_ComputerUse/Assets/cua_search_typed.png
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
187 changes: 75 additions & 112 deletions
187
dotnet/samples/02-agents/AgentsWithFoundry/Agent_Step15_ComputerUse/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,146 +1,109 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| // This sample shows how to use Computer Use Tool with a ChatClientAgent. | ||
| // This sample shows how to use the Computer Use tool with AIProjectClient.AsAIAgent(...). | ||
|
|
||
| using Azure.AI.Projects; | ||
| using Azure.Identity; | ||
| using Demo.ComputerUse; | ||
| using Microsoft.Agents.AI; | ||
| using Microsoft.Agents.AI.Foundry; | ||
| using Microsoft.Extensions.AI; | ||
| using OpenAI.Responses; | ||
|
|
||
| namespace Demo.ComputerUse; | ||
| 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") ?? "computer-use-preview"; | ||
|
|
||
| internal sealed class Program | ||
| { | ||
| private static async Task Main(string[] args) | ||
| { | ||
| const string AgentInstructions = @" | ||
| 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. | ||
| "; | ||
|
|
||
| const string AgentName = "ComputerAgent-RAPI"; | ||
|
|
||
| string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set."); | ||
| string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "computer-use-preview"; | ||
|
|
||
| // WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production. | ||
| // In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid | ||
| // latency issues, unintended credential probing, and potential security risks from fallback mechanisms. | ||
| AIProjectClient aiProjectClient = new(new Uri(endpoint), new DefaultAzureCredential()); | ||
|
|
||
| // Create a AIAgent with ComputerUseTool. | ||
| AIAgent agent = aiProjectClient.AsAIAgent(deploymentName, | ||
| instructions: AgentInstructions, | ||
| name: AgentName, | ||
| description: "Computer automation agent with screen interaction capabilities.", | ||
| tools: [ | ||
| FoundryAITool.CreateComputerTool(ComputerToolEnvironment.Browser, 1026, 769), | ||
| ]); | ||
|
|
||
| await InvokeComputerUseAgentAsync(agent); | ||
| } | ||
| AIProjectClient projectClient = new(new Uri(endpoint), new DefaultAzureCredential()); | ||
| using IHostedFileClient fileClient = projectClient.GetProjectOpenAIClient().AsIHostedFileClient(); | ||
|
|
||
| private static async Task InvokeComputerUseAgentAsync(AIAgent agent) | ||
| { | ||
| // Load screenshot assets | ||
| Dictionary<string, byte[]> screenshots = ComputerUseUtil.LoadScreenshotAssets(); | ||
| AIAgent agent = projectClient.AsAIAgent( | ||
| model: deploymentName, | ||
| name: "ComputerAgent", | ||
| instructions: "You are a computer automation assistant.", | ||
| tools: [FoundryAITool.CreateComputerTool(ComputerToolEnvironment.Browser, 1026, 769)]); | ||
|
|
||
| ChatOptions chatOptions = new(); | ||
| CreateResponseOptions responseCreationOptions = new() | ||
| { | ||
| TruncationMode = ResponseTruncationMode.Auto | ||
| }; | ||
| chatOptions.RawRepresentationFactory = (_) => responseCreationOptions; | ||
| ChatClientAgentRunOptions runOptions = new(chatOptions) | ||
| { | ||
| AllowBackgroundResponses = true, | ||
| }; | ||
| Dictionary<string, string> screenshots = []; | ||
|
|
||
| ChatMessage message = new(ChatRole.User, [ | ||
| new TextContent("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."), | ||
| new DataContent(new BinaryData(screenshots["browser_search"]), "image/png") | ||
| ]); | ||
|
|
||
| // Initial request with screenshot - start with Bing search page | ||
| Console.WriteLine("Starting computer automation session (initial screenshot: cua_browser_search.png)..."); | ||
|
|
||
| // We use PreviousResponseId to chain calls, sending only the new computer_call_output items | ||
| // instead of re-sending the full context. | ||
| AgentSession session = await agent.CreateSessionAsync(); | ||
| AgentResponse response = await agent.RunAsync(message, session: session, options: runOptions); | ||
|
|
||
| // Main interaction loop | ||
| const int MaxIterations = 10; | ||
| int iteration = 0; | ||
| // Initialize state machine | ||
| SearchState currentState = SearchState.Initial; | ||
| try | ||
| { | ||
| // Upload pre-captured screenshots that simulate browser state transitions. | ||
| screenshots = await ComputerUseUtil.UploadScreenshotAssetsAsync(fileClient); | ||
|
|
||
| while (true) | ||
| // Enable auto-truncation for the Responses API. | ||
| ChatClientAgentRunOptions runOptions = new() | ||
| { | ||
| ChatOptions = new ChatOptions | ||
| { | ||
| // Poll until the response is complete. | ||
| while (response.ContinuationToken is { } token) | ||
| { | ||
| // Wait before polling again. | ||
| await Task.Delay(TimeSpan.FromSeconds(2)); | ||
| RawRepresentationFactory = (_) => new CreateResponseOptions() { TruncationMode = ResponseTruncationMode.Auto }, | ||
| } | ||
| }; | ||
|
|
||
| // Continue with the token. | ||
| runOptions.ContinuationToken = token; | ||
| // Send the initial request with a screenshot of the browser. | ||
| 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) } | ||
| ]); | ||
|
|
||
| response = await agent.RunAsync(session, runOptions); | ||
| } | ||
| Console.WriteLine("Starting computer use session..."); | ||
|
|
||
| AgentSession session = await agent.CreateSessionAsync(); | ||
| AgentResponse response = await agent.RunAsync(message, session: session, options: runOptions); | ||
|
|
||
| // Clear the continuation token so the next RunAsync call is a fresh request. | ||
| runOptions.ContinuationToken = null; | ||
| SearchState currentState = SearchState.Initial; | ||
|
|
||
| Console.WriteLine($"Agent response received (ID: {response.ResponseId})"); | ||
| for (int i = 0; i < 10; i++) | ||
| { | ||
| // Find the next computer call action. | ||
| ComputerCallResponseItem? computerCall = response.Messages | ||
| .SelectMany(m => m.Contents) | ||
| .Select(c => c.RawRepresentation as ComputerCallResponseItem) | ||
| .FirstOrDefault(item => item is not null); | ||
|
|
||
| if (iteration >= MaxIterations) | ||
| if (computerCall is null) | ||
| { | ||
| if (currentState == SearchState.PressedEnter) | ||
| { | ||
| Console.WriteLine($"\nReached maximum iterations ({MaxIterations}). Stopping."); | ||
| Console.WriteLine("No more computer actions. Done."); | ||
| Console.WriteLine(response); | ||
| break; | ||
| } | ||
|
|
||
| iteration++; | ||
| Console.WriteLine($"\n--- Iteration {iteration} ---"); | ||
|
|
||
| // Check for computer calls in the response | ||
| IEnumerable<ComputerCallResponseItem> computerCallResponseItems = response.Messages | ||
| .SelectMany(x => x.Contents) | ||
| .Where(c => c.RawRepresentation is ComputerCallResponseItem and not null) | ||
| .Select(c => (ComputerCallResponseItem)c.RawRepresentation!); | ||
|
|
||
| ComputerCallResponseItem? firstComputerCall = computerCallResponseItems.FirstOrDefault(); | ||
| if (firstComputerCall is null) | ||
| // Check if the agent is asking for confirmation to proceed, and if so, respond affirmatively. | ||
| TextContent? textContent = response.Messages | ||
| .Where(m => m.Role == ChatRole.Assistant) | ||
| .SelectMany(m => m.Contents.OfType<TextContent>()) | ||
| .FirstOrDefault(); | ||
|
|
||
| if (textContent?.Text is { } text && ( | ||
| text.Contains("Would you like me") || | ||
| text.Contains("Should I") || | ||
| text.Contains("proceed") || | ||
| text.Contains('?'))) | ||
| { | ||
| Console.WriteLine("No computer call actions found. Ending interaction."); | ||
| Console.WriteLine($"Final Response: {response}"); | ||
| break; | ||
| response = await agent.RunAsync("Please proceed.", session, runOptions); | ||
| continue; | ||
| } | ||
|
|
||
| // Process the first computer call response | ||
| ComputerCallAction action = firstComputerCall.Action; | ||
| string currentCallId = firstComputerCall.CallId; | ||
|
|
||
| Console.WriteLine($"Processing computer call (ID: {currentCallId})"); | ||
| break; | ||
| } | ||
|
|
||
| // Simulate executing the action and taking a screenshot | ||
| (SearchState CurrentState, byte[] ImageBytes) screenInfo = ComputerUseUtil.HandleComputerActionAndTakeScreenshot(action, currentState, screenshots); | ||
| currentState = screenInfo.CurrentState; | ||
| Console.WriteLine($"[{i + 1}] Action: {computerCall!.Action.Kind}"); | ||
|
|
||
| Console.WriteLine("Sending action result back to agent..."); | ||
| // Simulate the action and get the resulting screenshot. | ||
| (currentState, string fileId) = await ComputerUseUtil.GetScreenshotAsync(computerCall.Action, currentState, screenshots); | ||
|
|
||
| // Send only the computer_call_output — the session carries PreviousResponseId for context continuity. | ||
| AIContent callOutput = new() | ||
| { | ||
| RawRepresentation = new ComputerCallOutputResponseItem( | ||
| currentCallId, | ||
| output: ComputerCallOutput.CreateScreenshotOutput(new BinaryData(screenInfo.ImageBytes), "image/png")) | ||
| }; | ||
| // Send the screenshot back as the computer call output. | ||
| 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); | ||
| } | ||
| response = await agent.RunAsync([new ChatMessage(ChatRole.User, [callOutput])], session: session, options: runOptions); | ||
| } | ||
| } | ||
| finally | ||
| { | ||
| await ComputerUseUtil.EnsureDeleteScreenshotAssetsAsync(fileClient, screenshots); | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.