在 Microsoft Foundry Agent Service 中使用電腦使用工具


電腦使用工具普遍可用,讓代理能透過使用者介面與瀏覽器及桌面應用程式互動。 模型會解讀螢幕截圖,並提出點擊、輸入與捲動等動作。 您的應用程式會在隔離環境中執行這些動作,並回傳更新後的螢幕截圖。

更新後的工具採用更簡化的定義,並支援在每次電腦呼叫中執行有序的動作批次。 您可以管理應用程式中的互動迴圈,或使用支援的 SDK 工具組搭配應用程式提供的驅動程式。 開發者可以使用 Foundry 中支援電腦使用的最新 OpenAI 模型,例如 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、配置 computer 工具並將其附加到目標應用程式。 請參閱 模型與區域可用性。

Open AI 的 computer tool 支援的工具包括 click、double_click、drag、keypress、move、screenshot、scroll、type 和 wait。

在本文中,您將學會如何:

  • 使用電腦使用工具設定代理程式。
  • 執行一組有序的 UI 動作並回傳螢幕截圖。
  • 套用核准要求、執行限制及環境限制。
  • 為您的應用程式選擇一種整合方式。
  • 從 computer-use-preview 模型和工具移轉。

警告

(i) 重要 電腦使用工具會代表您與電腦系統及應用程式互動,並可能採取非預期行為。 建議進行檢測與監測。Azure OpenAI 的透明度說明。

先決條件

開始之前,請確定您具備下列先決條件:

  • 一個 Azure 訂閱和一個 Microsoft Foundry 專案。
  • 在您所選區域中支援 computer 工具的已部署模型。
  • 使用專案、代理程式及模型部署的權限。
  • 支援已發行工具結構描述的 SDK 版本,或經過驗證的 REST 用戶端。
  • 一個由您的應用程式控制的隔離瀏覽器或桌面環境。
  • 動作執行器與截圖擷取實作,或具相容驅動程式的支援 SDK 工具組。
  • 應用程式端的政策,包括允許的動作、目的地、使用者核准及執行限制。

設定 Agent 時,請使用部署名稱,而不是假設的模型識別碼。 檢查您的部署的 模型可用性 及 代理服務工具支援。

電腦使用原理

電腦使用將模型推理與動作執行區分開來:

  1. 您的應用程式會傳送一個任務。
  2. 模型會傳回包含螢幕擷取畫面要求的 computer_call。
  3. 您的應用程式會驗證呼叫、傳送螢幕截圖,並檢查是否需要使用者核准。
  4. 您的應用程式會依序執行核准的動作。
  5. 您的應用程式會擷取產生的 UI 狀態。
  6. 你的應用程式會傳送一個 computer_call_output,其中包含相符的 call_id 和更新後的截圖。
  7. 這個循環會持續,直到任務完成、使用者停止任務,或達到執行上限為止。
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

這個工具不會佈建電腦或直接控制裝置。 您的應用程式仍需對環境、執行政策及動作結果負責。

帳單是如何設定的?

每個 Responses 要求的權杖可能會產生輸入和輸出權杖費用。 截圖也算作圖片輸入。 了解更多關於 定價、模型代幣限制及地區的資訊。 如果您使用託管代理程式進行設定,則適用 Foundry 代理程式的服務費率 。

設定電腦使用工具

將工具宣告,設定 type 為 computer:

{
  "type": "computer"
}

與預覽工具不同,新定義不需要 display_width、 display_height或 environment。

你的執行器仍然需要知道實際的視窗或桌面尺寸。 從工具定義中移除這些屬性,並不會消除保持截圖和動作座標一致的需求。

選擇整合方法

Approach 何時使用 應用程式職責
具有應用程式管理迴圈的原生電腦工具 你需要對每個請求、動作批次和截圖都有明確的控制權。 執行動作、擷取截圖、維護歷史紀錄、執行政策並終止循環。
SDK 管理的電腦工具組 已發布的 SDK 提供相容的工具組與驅動程式介面契約。 提供驅動程式、設定限制與核准掛鉤,並驗證任務結果。

使用 SDK 管理迴圈

目標 SDK 體驗包含 ComputerToolsetBrowserToolset Python 與 Node.js的整合,包含應用程式提供的驅動程式、執行限制以及動作前的掛鉤。 在程式碼中使用這些名稱前,請確認已發佈 SDK 的可用性與精確簽名。

設定相當於以下內容:

  • 一個驅動程式,能執行支援的動作並回傳新鮮截圖。
  • 一個限制模型/工具迭代次數的 步數限制。
  • 套用原則並暫停以等待核准的動作前掛鉤。
  • 逾時與使用者取消機制。
  • 動作層級限制,因為一個模型回合可能包含多個動作。

工具組可以減少編排程式碼,但並不能取代應用程式端的政策。

針對 Python、C#/.NET、TypeScript/JavaScript 和 Java,請使用相應的 Foundry SDK 發行說明及維護範例:

程式碼範例

警告

在無法接觸敏感資料或關鍵資源的虛擬機器上使用電腦使用工具。

用於電腦使用工具執行初始化的螢幕擷取畫面

以下節錄示範如何使用 GA ComputerTool建立代理程式版本、發送附有截圖的初始請求,以及執行多次迭代(包括批次 computer_call.actions)以完成任務。 選擇 Prompt Agents 以使用 Azure AI Projects SDK 建立伺服器端提示代理,或選擇 Hosted Agents 使用 Agent Framework FoundryChatClient 建立臨時且進行中的代理。

提示詞 Agent

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)

用這個工具建立代理版本

# 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})")

請傳送初始請求並附上截圖

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})")

以批次動作執行多次迭代

在 GA computer 工具協定中,每個 computer_call 項目都暴露一個批次 actions 清單(computer_call.actions),同時仍與單數 computer_call.action相容。 依序執行批次中的所有動作,擷取一張新的截圖,然後再送回 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})")

清理

project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
print("Agent deleted")

預期產出

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

託管代理

此範例使用來自 Microsoft Agent Framework 的 FoundryChatClient,搭配 GA computer 工具({"type": "computer"})。 使用 pip install agent-framework-foundry aiohttp 安裝套件,設定 FOUNDRY_PROJECT_ENDPOINT(將 FOUNDRY_MODEL 指向 gpt-6.1-sol 部署),並使用 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())

預期產出

Agent: I searched for "OpenAI news" in the address bar. The top results include articles from OpenAI's blog, TechCrunch, and The Verge ...

如需完整的螢幕擷取迴圈實作,請參閱 Foundry 提供者範例。

使用代理程式與電腦工具的範例

以下 C# 程式碼範例示範如何建立具有 GA computer 工具 ({"type": "computer"}) 的代理程式,發送初始請求並附上截圖,並執行多次迭代以完成任務。

提示詞 Agent

若要啟用您的代理程式使用 GA computer 工具,請在設定ModelReaderWriter.Read<ResponseTool>(BinaryData.FromObjectAsJson(new { type = "computer" }))時傳遞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");
    }
}

預期產出

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

託管代理

此範例使用 Microsoft Agent Framework,並透過 GA {"type": "computer"} 工具定義與 gpt-5.4 部署,在 AIProjectClient 上呼叫 AsAIAgent(...)。 安裝 Microsoft.Agents.AI.Foundry 和 Azure.AI.Projects 套件,設定 AZURE_AI_PROJECT_ENDPOINT 和 AZURE_AI_COMPUTER_USE_DEPLOYMENT_NAME 環境變數,並以 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}");

預期產出

Response: I searched for "OpenAI news" in the address bar. The top results include articles from OpenAI's blog, TechCrunch, and The Verge ...

完整的截圖輔助實作及端對端操作迴圈,請參見 Agent_Step15_ComputerUse。

使用代理程式與電腦工具的範例

以下 TypeScript 範例示範如何建立採用 GA computer 工具(tools: [{ type: "computer" }])的代理程式版本、發送含截圖的初始請求,以及執行多次迭代( computerCall.actions 處理時以批次方式並備援至 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);
});

預期產出

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!

在 Java 代理中利用電腦功能

新增相依性至您的pom.xml:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-agents</artifactId>
    <version>2.9.0</version>
</dependency>

建立電腦使用代理

在 GA SDK(com.azure.ai.agents.models.ComputerTool)中,new ComputerTool() 可序列化為 {"type": "computer"},且不需要顯示尺寸或環境參數。

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());
    }
}

對於完整的模擬迴圈,請使用維護中的 ComputerUseSync.java 樣本及其 ComputerUseUtil.java 輔助程式。 該輔助程式會將請求的動作(包括批次 actions 動作)對應到預先擷取的截圖。 用應用程式的動作執行器、截圖擷取和安全核准流程取代這個模擬。

請使用電腦與 REST API 互動

取得存取權憑證:

export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)

建立一位使用電腦的代理人

使用 GA computer 工具,指定 "tools": [{"type": "computer"}] 以及主線電腦使用模型部署(例如 "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"
        }
      ]
    }
  }'

產生回應

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"
  }'

回應包含 computer_call 輸出項目,其中有要執行的批次 actions 陣列。 在執行任何動作之前,請檢查 pending_safety_checks。 如果陣列不是空的,請暫停並向最終使用者顯示動作與安全檢查。 只有在使用者明確同意該動作後,才能繼續進行。

請附上截圖提交行動結果

當使用者核准任何待處理的安全檢查,且應用程式在 computer_call.actions 中執行所有操作後,擷取截圖並回傳。 在acknowledged_safety_checks中包含每個已核准的檢查。 若未傳回任何檢查結果,請使用空陣列。

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"
        }
      }
    ]
  }'

將 <RESPONSE_ID>、<CALL_ID> 和 <BASE64_SCREENSHOT> 替換為前一個回應的數值。 重複此循環,直到模型回傳文字回應而非 computer_call。

清理

curl -X DELETE "$FOUNDRY_PROJECT_ENDPOINT/agents/computer-use-agent?api-version=v1" \
  -H "Authorization: Bearer $AGENT_TOKEN"

套用安全控制措施

將所有在受控環境中顯示的資訊視為不受信任的輸入。 網頁、文件、對話框或通知可能包含與使用者任務衝突的指示。

可獨立於任何模型提供的安全檢查,應用這些控制:

控制 建議作法
環境隔離 使用專用沙盒,使用僅具最低必要權限的憑證,且不包含無關資料或帳戶。
目的地限制 只允許必要的目的地。 驗證重定向並在模型外強制執行網路限制。
行動方針 根據任務需求限制檔案存取、剪貼簿使用、下載、上傳及其他功能。
重大操作核准 在購買、提交、發送訊息、破壞性編輯或帳戶變更前,取得明確的使用者同意。
安全檢查處理 顯示回傳警告給使用者並暫停。 僅確認使用者依據已發布的 API 合約所核准的檢查項目。
敏感工作流程 要求用戶積極監督,且不要在核准範圍外進行自動化。
執行限制 回合數上限、每批次動作數、經過時間與重試次數。 提供取消功能。
稽核能力 記錄動作類型、決策、失敗和核准,但不要不必要地保留敏感的螢幕擷取畫面或輸入的值。

核准應明確指出具體行動及其預期後果。 請勿以整個工作階段的全面核准,取代對重大動作的審查。

對於包含一個具重大影響的動作的批次,請在該動作及任何相依動作前暫停。 如果政策無法在批次內安全地強制執行,請停止執行並將控制權還給使用者。

從電腦使用預覽版移轉

先前的 computer use 預覽工具的主要變更 若要從舊版預覽整合遷移,請更新模型、工具定義及動作處理常式:

類別 預覽整合 GA 整合
型號 computer-use-preview gpt-6.1-sol、、 gpt-6.1-terra、 gpt-6-astra、 gpt-6-luna、 gpt-6-sol
工具名稱 tools: [{ type: "computer_use_preview", display_width: ..., display_height: ..., environment: ... }] tools: [{ type: "computer" }]
Python SDK 工具 ComputerUsePreviewTool(display_width=1026, display_height=769, environment="windows") ComputerTool() (from azure.ai.projects.models import ComputerTool)
C#/.NET SDK 工具 ResponseTool.CreateComputerTool(environment, displayWidth, displayHeight) ModelReaderWriter.Read<ResponseTool>(BinaryData.FromObjectAsJson(new { type = "computer" }))
TypeScript/JS SDK 工具 { type: "computer_use_preview", display_width: 1026, display_height: 769, environment: "windows" } { type: "computer" }
Java SDK 工具 new ComputerUsePreviewTool(ComputerEnvironment.WINDOWS, 1026, 769) new ComputerTool() (com.azure.ai.agents.models.ComputerTool)
Actions 每個computer_call上各有一個action 在每個 computer_call 上的批次 actions[] 陣列
截斷 truncation: "auto" 必填 truncation 不必

替換預覽工具定義:

{
  "type": "computer_use_preview",
  "display_width": 1024,
  "display_height": 768,
  "environment": "windows"
}

取代為:

{
  "type": "computer"
}

更新讀取computer_call.action的處理常式,使其依序逐一處理computer_call.actions。 不要把舊處理程式包裝成並行執行。

驗證遷移後的應用程式

切換生產流量前:

  1. 確認替換部署接受該工具定義。
  2. 執行一個狹窄任務並附上即時截圖,並驗證工具輸出是否匹配。
  3. 測試多動作批次,包含焦點變更或導覽。
  4. 測試修飾鍵和額外滑鼠按鍵,如果你的應用程式有使用它們。
  5. 測試螢幕縮放、視窗變更與座標映射。
  6. 驗證核准、拒絕、取消、目的地限制,以及傳回的安全檢查。
  7. 確認部分批次失敗是否會停止依賴動作並顯示錯誤。
  8. 確認行動限制以及回合限制。
  9. 在具代表性的工作流程上,衡量任務成功率、耗時、輪次與成本。
  10. 只有在替換方案已驗證且您的回滾計畫允許後,才移除預覽部署。

批次操作可以減少模型往返次數。 實際對延遲與成本的影響取決於任務、部署、動作執行者以及所需的驗證量。

安全檢查處理作業

"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>" 
            } 
        } 
    ]

故障排除

問題 要檢查的事項
API 拒絕 type: "computer"。 確認該工具在您的版本中可用、所選部署支援,且 SDK/API 版本使用新架構。
回應中沒有包含電腦呼叫。 檢查回應狀態、代理程式設定、部署相容性,以及任務是否需要 UI 互動。
你的處理常式預期 action,但卻接收 actions。 更新已排序批次的處理程序。 在預覽版與更新版整合之間分享程式碼前,請先檢視相容性。
動作的目標位置錯誤。 檢查截圖尺寸、視窗大小、桌面縮放,以及任何座標變換。
後續動作會在錯誤的視窗或欄位中執行。 保留批次順序,並在依賴動作前驗證焦點與導覽。
代理程式一再要求截圖。 回傳一張實際環境的新截圖,並確認執行器已套用所要求的動作。
安全檢查或核准要求會中斷執行。 暫停、向使用者顯示動作與警告,並僅透過文件記載的核准流程繼續。
批次僅部分執行。 停止相依的動作,在安全時擷取目前狀態,並回報失敗。 請勿盲目重新執行整個批次。
循環已至極限。 回報任務未完成。 提高限制之前,請先調查過時的螢幕擷取畫面、失敗的動作或限制不足的情況。
SDK 工具組或輔助工具無法匯入。 檢查套件版本和發行可用性。 使用持續維護的範例及其必要資產,而不是僅限預覽版的協助程式名稱。

清理

測試完成後:

  • 刪除不再需要的測試代理程式版本與模型部署。
  • 關閉或處置隔離的執行環境。
  • 依照你的保留政策移除臨時截圖和下載內容。
  • 撤銷臨時憑證並關閉測試工作階段。

如果範例建立代理程式版本,請清理該版本,而非刪除與其他應用程式共用的代理程式。 處理失敗、取消以及成功完成時的清理作業。