你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用浏览器自动化工具自动执行浏览器任务(预览版)

重要

本文中标记为(预览)的项目目前以公共预览版提供。 此预览版在没有服务级别协议的情况下提供,不建议将其用于生产工作负荷。 某些功能可能不受支持,或者可能具有受限功能。 有关详细信息,请参阅 Microsoft Azure 预览版的使用条款

本文介绍如何将浏览器自动化工具与 Foundry 代理一起使用,以自动执行 Web 浏览工作流。

Tip

请考虑使用 工具箱添加此工具。 通过使用工具箱,可以跨代理和运行时重复使用该工具,并通过托管 MCP 终结点集中凭据管理、版本管理和策略强制实施。 请参阅 工具箱快速入门

警告

浏览器自动化工具具有重大安全风险。 使用浏览器自动化工具时,AI 会启动远程浏览器会话来执行操作,并可以使用与代理显式共享的凭据,例如电子邮件、财务帐户、社交网络和企业系统。 AI 代理可能会犯错误,并可能被 Internet 上遇到的恶意数据所愚弄。

你负责查看和测试应用程序并实施自己的负责任的 AI 缓解措施。 使用浏览器自动化工具,即表示您确认将对其任何使用行为及其所有后果承担责任与法律责任。 在决定向浏览器会话提供哪些凭据时,请谨慎判断。 请参阅 Foundry Agent Service 透明度说明

浏览器自动化工具(BAT)可在 Foundry 代理中实现可缩放、可靠的基于浏览器的自动化。 BAT 作为一个 MCP 工具提供,其无头浏览器基础设施层由 Playwright 工作区提供支持。 它与现代代理工作流无缝集成,同时提供企业级安全性、可观测性和可扩展性。

浏览器自动化工具(BAT)提供了一个全面的平台,用于通过以下方法实现浏览器自动化:

  • 剧作家工作区(正式发布服务)作为基础结构层
  • 使用实时视图进行实时调试
  • 在需要人工干预的场景中掌握控制权
  • 支持专用网站浏览(个人预览版)
  • 用于可靠性和优化的内置可观测性
  • 灵活的编排层

注意

剧作家工作区中的专用网站功能目前以个人预览版提供。 感兴趣的用户可以填写此 表单 以注册个人预览版。

使用支持

下表显示了 SDK 和设置支持。

Microsoft Foundry 支持 Python SDK C# SDK JavaScript SDK Java SDK REST API 基本代理设置 标准代理设置
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

工作原理

当用户将查询发送到连接到浏览器自动化工具的代理时,将开始交互。 例如, “从以下 URL <URL> 向我显示本周所有可用的瑜伽课程。 当代理收到请求时,Foundry 代理服务将使用预配的 Playwright 工作区创建独立的浏览器会话。 每个会话都被沙盒化以确保隐私和安全。

浏览器执行 Playwright 驱动的操作,例如导航到相关页面,并根据用户首选项(如时间、位置和讲师)应用筛选器或参数。 通过将模型与 Playwright 组合在一起,模型可以将 HTML 或 XML 分析为 DOM 文档、做出决策和执行操作,例如选择 UI 元素、键入和导航网站。 使用此工具时,请谨慎行事。

示例流为:

  1. 用户向模型发送请求,其中包含对浏览器自动化工具的调用,并附有您想要访问的 URL。

  2. 浏览器自动化工具从模型接收响应。 如果响应包含操作项,则这些项目包含建议的操作,以便朝着指定目标前进。 例如,操作可能是屏幕截图,以便模型可以使用更新的屏幕截图评估当前状态,或者单击 X/Y 坐标,指示应移动鼠标的位置。

  3. 浏览器自动化工具在沙盒环境中执行该操作。

  4. 执行该操作后,浏览器自动化工具将环境的更新状态捕获为屏幕截图。

  5. 该工具发送具有更新状态的新请求,并重复此循环,直到模型停止请求操作或用户决定停止。

    浏览器自动化工具支持多轮次对话,允许用户优化其请求并完成表单填充和 Web 抓取方案。

先决条件

在开始之前,请确保具备:

  • 一个 Azure 订阅。 免费创建一个
  • 资源组上的参与者或所有者角色。
  • 具有已配置终结点的 Foundry 项目。
  • 部署在项目中的 AI 模型(例如 gpt-5.4)。
  • Playwright 工作区资源。
  • 为 Playwright 工作区设置的项目连接。

SDK 要求

对于Python示例,请安装所需的包:

pip install "azure-ai-projects>=2.0.0"

.NET SDK 目前为预览版。 有关详细信息,请参阅 快速入门

配置

获取项目终结点:在 Foundry 门户中打开项目,并从项目概述页复制终结点。 格式为 https://{account-name}.services.ai.azure.com/api/projects/{project-name}.

Connection ID 格式:使用 /subscriptions/{{subscriptionID}}/resourceGroups/{{resourceGroupName}}/providers/Microsoft.CognitiveServices/accounts/{{foundryAccountName}}/projects/{{foundryProjectName}}/connections/{{foundryConnectionName}}。 连接浏览器自动化工具后,可以在工具的详细信息页上找到此值。

设置浏览器自动化

步骤 1:创建 Playwright 工作区

  1. Azure 门户中创建 Playwright Workspace 资源。
  2. 创建工作区后,转到 “设置>访问管理”。
  3. 确认 已启用 Playwright 服务访问令牌 身份验证方法。
  4. 选择“ 生成令牌”,输入名称(例如), foundry-connection然后选择到期期限。
  5. 立即复制令牌。 关闭页面后无法再次查看它。
  6. 在“工作区概述”页上,复制以开头的wss://
  7. 将项目标识授予 Playwright 工作区资源的参与者角色,或配置自定义角色

步骤 2:在 Foundry 中连接浏览器自动化工具

  1. 转到 Foundry 门户 并选择项目。
  2. 选择 “生成>工具”。
  3. 选择“ 创建工具箱”。
  4. 填写工具箱的名称说明
  5. “工具”下,单击“添加
  6. 选择 浏览器自动化 并单击“ 添加工具”
  7. 输入必填字段
    • 连接名称:连接的唯一名称
    • 剧作家工作区:选择剧作家工作区资源。
    • 身份验证类型:选择连接的身份验证类型。
  8. 选择 “连接”。
  9. 单击“ 发布 ”保存工具箱

创建工具箱后,可以在工具的详细信息页上查看 Project 连接 ID。 使用此值作为代码中的浏览器自动化连接 ID。

使用Azure开发人员 CLI 将浏览器自动化添加到工具箱

若要将浏览器自动化添加到工具箱,请使用Azure开发人员 CLI 创建 Playwrite 工作区。 本文假定你已有 Playwright 工作区资源。 请参阅先决条件部分。

  1. 创建 Playwright 工作区连接。
azd ai connection create my-browser-conn \
  --kind PlaywrightWorkspace \
  --target wss://your-browser-endpoint.api.playwright.microsoft.com/playwrightworkspaces/browsers \
  --auth-type api-key \
  --key "<playwright-workspaces-access-token>"

--kind PlaywrightWorkspace 必须严格使用 PascalCase。

  1. 定义工具箱(my-toolbox.yaml)
description: Browser Automation toolbox
tools:
  - type: browser_automation_preview
    project_connection_id: my-browser-conn
  1. 创建工具箱
azd ai toolbox create my-toolbox --from-file my-toolbox.yaml

浏览器自动化工具定义

运行示例后,请在 Microsoft Foundry 中使用跟踪来验证该工具是否已调用。 有关验证工具调用的指导,请参阅有关在 Microsoft Foundry 代理服务中使用工具的最佳做法。 如果使用流媒体技术,还可以查找browser_automation_preview_call 事件。

注意

  • .NET SDK 目前为预览版。 有关详细信息,请参阅 快速入门
ProjectsAgentTool tool = new BrowserAutomationPreviewTool(
    new BrowserAutomationToolOptions(
        new BrowserAutomationToolConnectionParameters("<BROWSER_AUTOMATION_PROJECT_CONNECTION_ID>")
    )
);
const tools = [
  {
    type: "browser_automation_preview",
    name: "<OPTIONAL_TOOL_NAME>",
    description: "<Optional description for the model>",
    browser_automation_preview: {
      connection: {
          project_connection_id: "<BROWSER_AUTOMATION_PROJECT_CONNECTION_ID>"
      }
    }
  },
];

将 BrowserAutomationPreviewTool 与代理示例配合使用

以下Python示例演示如何使用浏览器自动化功能创建 AI 代理。 选择 Prompt Agents以使用 Azure AI Projects SDK 创建服务器端提示代理,或托管代理使用 Agent Framework FoundryChatClient生成临时进程内代理。

import json
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    PromptAgentDefinition,
    BrowserAutomationPreviewTool,
    BrowserAutomationToolParameters,
    BrowserAutomationToolConnectionParameters,
)

# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
BROWSER_CONNECTION_ID = "your-browser-automation-connection-id"

# Create clients to call Foundry API
project = AIProjectClient(
    endpoint=PROJECT_ENDPOINT,
    credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()

tool = BrowserAutomationPreviewTool(
    browser_automation_preview=BrowserAutomationToolParameters(
        connection=BrowserAutomationToolConnectionParameters(
            project_connection_id=BROWSER_CONNECTION_ID,
        )
    )
)

agent = project.agents.create_version(
    agent_name="MyAgent",
    definition=PromptAgentDefinition(
        model="gpt-4.1-mini",
        instructions="""You are an Agent helping with browser automation tasks. 
        You can answer questions, provide information, and assist with various tasks 
        related to web browsing using the Browser Automation tool available to you.""",
        tools=[tool],
    ),
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")

stream_response = openai.responses.create(
    stream=True,
    tool_choice="required",
    input="""
        Your goal is to report the percent of Microsoft year-to-date stock price change.
        To do that, go to the website finance.yahoo.com.
        At the top of the page, you will find a search bar.
        Enter the value 'MSFT', to get information about the Microsoft stock price.
        At the top of the resulting page you will see a default chart of Microsoft stock price.
        Click on 'YTD' at the top of that chart, and report the percent value that shows up just below it.""",
    extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)

for event in stream_response:
    if event.type == "response.created":
        print(f"Follow-up response created with ID: {event.response.id}")
    elif event.type == "response.output_text.delta":
        print(f"Delta: {event.delta}")
    elif event.type == "response.text.done":
        print(f"\nFollow-up response done!")
    elif event.type == "response.output_item.done":
        item = event.item
        if item.type == "browser_automation_preview_call":
            arguments_str = getattr(item, "arguments", "{}")

            # Parse the arguments string into a dictionary
            arguments = json.loads(arguments_str)
            query = arguments.get("query")

            print(f"Call ID: {getattr(item, 'call_id')}")
            print(f"Query arguments: {query}")
    elif event.type == "response.completed":
        print(f"\nFollow-up completed!")
        print(f"Full response: {event.response.output_text}")

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

此代码的作用

此示例创建启用了浏览器自动化工具的代理版本,然后发送一个提示,该提示要求代理使用该工具。 它还处理流式事件,使您可以监控进度和工具调用。

所需的输入

  • Foundry 项目端点和浏览器自动化连接 ID。 有关详细信息,请参阅 “配置 ”。

预期输出

创建智能体时,会看到类似于以下内容的输出:

Agent created (id: ..., name: ..., version: ...)

在流式传输过程中,你还可能会看到增量和工具调用详情。 输出因网站内容和模型行为而异。

将 BrowserAutomationPreviewTool 与代理示例配合使用

在运行此示例之前,请完成 “设置浏览器自动化”中的设置步骤。

以下 C# 示例演示如何使用浏览器自动化功能创建 AI 代理。 选择 Prompt Agents以使用 Azure AI Projects SDK 创建服务器端提示代理,或托管代理使用 Microsoft Agent Framework 生成临时进程内代理。

此示例使用 Azure AI Projects 客户端库的同步方法。 有关使用异步方法的示例,请参阅 GitHub 上用于 .NET 存储库Azure SDK中的 BrowserAutomationPreviewTool 和 Agents 示例的示例。

using System;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
var browserConnectionId = "your-browser-automation-connection-id";

// Note that Browser automation operations can take longer than usual
// and require the request timeout to be at least 5 minutes.
AIProjectClientOptions options = new()
{
    NetworkTimeout = TimeSpan.FromMinutes(5)
};
AIProjectClient projectClient = new(endpoint: new Uri(projectEndpoint), tokenProvider: new DefaultAzureCredential(), options: options);

// Create the Browser Automation tool using the Playwright connection.
BrowserAutomationPreviewTool playwrightTool = new(
    new BrowserAutomationToolParameters(
        new BrowserAutomationToolConnectionParameters(browserConnectionId)
    ));

// Create the Agent version with the Browser Automation tool.
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-4.1-mini")
{
    Instructions = "You are an Agent helping with browser automation tasks.\n" +
    "You can answer questions, provide information, and assist with various tasks\n" +
    "related to web browsing using the Browser Automation tool available to you.",
    Tools = { playwrightTool }
};
AgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
    agentName: "myAgent",
    options: new(agentDefinition));

// Create the response stream. Also set ToolChoice = ResponseToolChoice.CreateRequiredChoice()
// on the ResponseCreationOptions to ensure the agent uses the Browser Automation tool.
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentVersion.Name);
CreateResponseOptions responseOptions = new()
{
    ToolChoice = ResponseToolChoice.CreateRequiredChoice(),
    StreamingEnabled = true,
    InputItems =
    {
        ResponseItem.CreateUserMessageItem("Your goal is to report the percent of Microsoft year-to-date stock price change.\n" +
            "To do that, go to the website finance.yahoo.com.\n" +
            "At the top of the page, you will find a search bar.\n" +
            "Enter the value 'MSFT', to get information about the Microsoft stock price.\n" +
            "At the top of the resulting page you will see a default chart of Microsoft stock price.\n" +
            "Click on 'YTD' at the top of that chart, and report the percent value that shows up just below it.")
    }
};
foreach (StreamingResponseUpdate update in responseClient.CreateResponseStreaming(options: responseOptions))
{
    if (update is StreamingResponseCreatedUpdate createUpdate)
    {
        Console.WriteLine($"Stream response created with ID: {createUpdate.Response.Id}");
    }
    else if (update is StreamingResponseOutputTextDeltaUpdate textDelta)
    {
        Console.WriteLine($"Delta: {textDelta.Delta}");
    }
    else if (update is StreamingResponseOutputTextDoneUpdate textDoneUpdate)
    {
        Console.WriteLine($"Response done with full message: {textDoneUpdate.Text}");
    }
    else if (update is StreamingResponseErrorUpdate errorUpdate)
    {
        throw new InvalidOperationException($"The stream has failed with the error: {errorUpdate.Message}");
    }
}

// Delete the Agent version to clean up resources.
projectClient.AgentAdministrationClient.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);

此代码的作用

此示例创建了一个启用浏览器自动化工具的代理程序版本,发送需要使用该工具的提示,并在代理程序执行浏览器步骤时打印更新流。

所需的输入

  • Foundry 项目端点和浏览器自动化连接 ID。 有关详细信息,请参阅 “配置 ”。
  • 在 Foundry 项目中创建的 Playwright 连接。

预期输出

你会看到流式处理进度消息,例如文本增量和已完成的响应。 输出因网站内容和模型行为而异。

获取访问令牌:

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

添加浏览器自动化的建议方法是通过工具箱,然后将工具箱作为 MCP 工具附加到代理。 请参阅 什么是工具箱?

  1. 创建包含浏览器自动化工具的工具箱:
curl --request POST \
  --url "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/browser-automation-toolbox/versions?api-version=v1" \
  -H "Content-Type: application/json" \
  --data '{
    "description": "Toolbox with the Browser Automation tool",
    "tools": [
      {
        "type": "browser_automation_preview",
        "browser_automation_preview": {
          "connection": {
            "project_connection_id": "'"$BROWSER_AUTOMATION_PROJECT_CONNECTION_ID"'"
          }
        }
      }
    ]
  }'

工具箱公开了 MCP 兼容的终结点,该终结点 $FOUNDRY_PROJECT_ENDPOINT/toolboxes/browser-automation-toolbox/versions/<version>/mcp?api-version=v1<version> 上一次调用返回的版本。

  1. 使用用户 Entra 令牌创建指向工具箱终结点的远程工具项目连接,以便调用方的身份通过(受众 https://ai.azure.com) 传递。
azd ai connection create browser-automation-toolbox-conn \
  --kind remote-tool \
  --target "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/browser-automation-toolbox/versions/<version>/mcp?api-version=v1" \
  --auth-type user-entra-token \
  --audience https://ai.azure.com
  1. 通过附加工具箱作为 MCP 工具创建使用工具箱的响应。
curl --request POST \
  --url "${FOUNDRY_PROJECT_ENDPOINT}/openai/v1/responses" \
  --header "Authorization: Bearer ${AGENT_TOKEN}" \
  --header "Content-Type: application/json" \
  --header "User-Agent: insomnia/11.6.1" \
  --data @- <<JSON
{
  "model": "${FOUNDRY_MODEL_DEPLOYMENT_NAME}",
  "input": [
    {
      "role": "user",
      "content": [
        {
          "type": "input_text",
          "text": "Your goal is to report the percent of Microsoft year-to-date stock price change."
        },
        {
          "type": "input_text",
          "text": "Go to finance.yahoo.com, search for MSFT, select YTD on the chart, and report the percent value shown."
        }
      ]
    }
  ],
  "tools": [
    {
      "type": "mcp",
      "server_label": "toolbox",
      "server_url": "${FOUNDRY_PROJECT_ENDPOINT}/toolboxes/browser-automation-toolbox/versions/<version>/mcp?api-version=v1",
      "require_approval": "never",
      "project_connection_id": "browser-automation-toolbox-conn"
    }
  ]
}
JSON

将浏览器自动化工具与代理示例配合使用

以下 TypeScript 示例演示如何使用浏览器自动化工具创建代理、执行 Web 浏览任务,以及使用浏览器自动化事件处理流式处理响应。 有关此示例的 JavaScript 版本,请参阅 GitHub 上适用于 JavaScript 存储库的 Azure SDK 中的 JavaScript 示例 for Browser Automation tool

import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const BROWSER_CONNECTION_ID = "your-browser-automation-connection-id";

const handleBrowserCall = (item: any) => {
  // TODO: support browser_automation_preview_call schema
  const callId = item.call_id;
  const argumentsStr = item.arguments;

  // Parse the arguments string into a dictionary
  let query = null;
  if (argumentsStr && typeof argumentsStr === "string") {
    try {
      const argumentsObj = JSON.parse(argumentsStr);
      query = argumentsObj.query;
    } catch (e) {
      console.error("Failed to parse arguments:", e);
    }
  }

  console.log(`Call ID: ${callId ?? "None"}`);
  console.log(`Query arguments: ${query ?? "None"}`);
};

export async function main(): Promise<void> {
  // Create clients to call Foundry API
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  console.log("Creating a toolbox with the Browser Automation tool...");

  // 1. Add the Browser Automation tool to a toolbox. Using a toolbox is the recommended
  //    way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
  const toolbox = await project.toolboxes.createVersion(
    "browser-automation-toolbox",
    [
      {
        type: "browser_automation_preview",
        browser_automation_preview: {
          connection: {
            project_connection_id: BROWSER_CONNECTION_ID,
          },
        },
      },
    ],
    { description: "Toolbox with the Browser Automation tool" },
  );

  // 2. The toolbox exposes an MCP-compatible endpoint.
  const toolboxMcpUrl =
    `${PROJECT_ENDPOINT}/toolboxes/${toolbox.name}` +
    `/versions/${toolbox.version}/mcp?api-version=v1`;

  // 3. Create a remote-tool project connection that points at the toolbox endpoint.
  //    Use a user Entra token so the caller's identity is passed through
  //    (audience https://ai.azure.com). Create the connection once, for example
  //    with the Azure Developer CLI:
  //
  //    azd ai connection create browser-automation-toolbox-conn \
  //      --kind remote-tool \
  //      --target "<toolboxMcpUrl>" \
  //      --auth-type user-entra-token \
  //      --audience https://ai.azure.com
  const toolboxConnectionName = "browser-automation-toolbox-conn";

  // 4. Attach the toolbox to a prompt agent as an MCP tool.
  const agent = await project.agents.createVersion("MyAgent", {
    kind: "prompt",
    model: "gpt-4.1-mini",
    instructions: `You are an Agent helping with browser automation tasks. 
            You can answer questions, provide information, and assist with various tasks 
            related to web browsing using the Browser Automation tool available to you.`,
    tools: [
      {
        type: "mcp",
        server_label: "toolbox",
        server_url: toolboxMcpUrl,
        require_approval: "never",
        project_connection_id: toolboxConnectionName,
      },
    ],
  });
  console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

  console.log("\nSending browser automation request with streaming...");
  const streamResponse = await openai.responses.create(
    {
      input: `Your goal is to report the percent of Microsoft year-to-date stock price change.
            To do that, go to the website finance.yahoo.com.
            At the top of the page, you will find a search bar.
            Enter the value 'MSFT', to get information about the Microsoft stock price.
            At the top of the resulting page you will see a default chart of Microsoft stock price.
            Click on 'YTD' at the top of that chart, and report the percent value that shows up just below it.`,
      stream: true,
    },
    {
      body: {
        agent: { name: agent.name, type: "agent_reference" },
        tool_choice: "required",
      },
    },
  );

  // Process the streaming response
  for await (const event of streamResponse) {
    if (event.type === "response.created") {
      console.log(`Follow-up response created with ID: ${event.response.id}`);
    } else if (event.type === "response.output_text.delta") {
      process.stdout.write(event.delta);
    } else if (event.type === "response.output_text.done") {
      console.log("\n\nFollow-up response done!");
    } else if (
      event.type === "response.output_item.done" ||
      event.type === "response.output_item.added"
    ) {
      const item = event.item as any;
      if (item.type === "browser_automation_preview_call") {
        handleBrowserCall(item);
      }
    } else if (event.type === "response.completed") {
      console.log("\nFollow-up completed!");
    }
  }

  // Clean up resources by deleting the agent version
  // This prevents accumulation of unused resources in your project
  console.log("\nCleaning up resources...");
  await project.agents.deleteVersion(agent.name, agent.version);
  console.log("Agent deleted");

  console.log("\nBrowser Automation sample completed!");
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

此代码的作用

本示例创建了一个启用了浏览器自动化工具的代理版本,发送需要使用该工具的提示,并在流式传输事件(如浏览器自动化调用事件)到达时进行处理。

所需的输入

  • Foundry 项目端点和浏览器自动化连接 ID。 有关详细信息,请参阅 “配置 ”。

预期输出

调用工具时,您会看到“代理已创建...”消息、流式文本输出,以及(可选的)浏览器调用详细信息。 输出因网站内容和模型行为而异。

在Java代理中使用浏览器自动化

创建工具箱后,在Java代理中更新这些值:

  • projectEndpoint — 项目终结点。
  • toolboxMcpUrl — 包含浏览器自动化工具的工具箱版本的 MCP 终结点。
  • toolboxConnectionName — 工具箱终结点的远程工具项目连接名称。

将依赖项添加到pom.xml

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

Tip

推荐: 对于大多数代理,请通过 工具箱 添加浏览器自动化工具,并将工具箱作为 MCP 工具附加到代理。 Java SDK 尚未公开工具箱创建 API,因此使用 PythonREST APIC#TypeScript 示例或 Foundry 门户创建工具箱,然后从Java代理引用其 MCP 终结点作为一个McpTool

限制

  • 仅受信任的站点:仅对信任的网站使用此工具。 避免提示输入凭据、付款或其他敏感操作的页面。
  • 页面波动性:网页可以随时更改。 如果页面布局、标签或导航流发生更改,代理可能会失败。 在工作流中构建错误处理。
  • 复杂的单页应用程序:具有动态内容的 JavaScript 密集型 SPA 可能无法正确呈现。

成本注意事项

此工具使用 Playwright 工作区资源来运行浏览器会话。 查看 Playwright 工作区文档,了解定价和使用情况详细信息。 有关优化工具使用的指导,请参阅 Microsoft Foundry 代理服务中的工具使用最佳实践

故障 排除

代理不使用该工具

  • 确认已启用浏览器自动化工具创建代理。
  • 在请求中,要求使用工具(例如,tool_choice="required")。
  • 在 Microsoft Foundry 中使用跟踪来确认是否发生了工具调用。 有关指南,请参阅有关在 Microsoft Foundry 代理服务中使用工具的最佳做法

连接或授权错误

  • 确认浏览器自动化连接 ID 与项目中的 Playwright 工作区连接资源 ID 匹配。
  • 确认项目身份具有访问 Playwright 工作区资源的权限。
  • 如果最近轮换了 Playwright 访问令牌,请更新 Foundry 项目连接密钥。

Python SDK 错误

  • 找不到工作区:验证项目终结点使用正确的格式: https://{account-name}.services.ai.azure.com/api/projects/{project-name}。 请勿使用旧版 Azure ML 终结点格式。
  • 意外的关键字参数错误:确保使用的是最新版本的 azure-ai-projects。 运行 pip install "azure-ai-projects>=2.0.0" --upgrade 以更新。
  • 导入错误:安装所有必需的包: pip install "azure-ai-projects>=2.0.0"

请求超时

浏览器自动化可能需要比典型请求更长的时间。

  • 增加客户端超时(C# 示例设置 5 分钟超时)。
  • 减少提示的范围(例如,减少页面和更少的交互)。

清理

  • 删除为测试创建的代理版本。
  • 如果不再需要 Playwright 访问令牌,请撤销或轮换该令牌。
  • 如果不再需要项目连接,请将其删除。 有关详细信息,请参阅 在 Microsoft Foundry 中添加连接

示例方案

  • 表单填充:处理各种表单类型,涵盖验证、DOM、身份验证、合规性,并支持多轮推理。

  • Web 抓取:导航经过身份验证的网站,以跨源抓取、比较和结构数据。

透明度说明

使用此工具时查看 透明度说明 。 浏览器自动化工具是一种工具,可以通过自然语言提示执行真实浏览器任务,无需人工干预即可实现自动浏览活动。

使用此工具时,请查看 负责任的 AI 注意事项