你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
使用 OpenAPI 3.0 和 3.1 规范将 Microsoft Foundry 代理连接到外部 API。 支持代理的 Foundry 模型可以调用外部服务、检索实时数据,并将其功能扩展到内置函数之外。
OpenAPI 规范 定义了描述 HTTP API 的标准方法,因此可以将现有服务与代理集成。 使用匿名、API 密钥或项目托管标识身份验证。 有关选择身份验证方法的帮助,请参阅 “选择身份验证方法”。
Warning
从 2027 年 1 月 8 日起,OpenAPI 工具不再支持内联托管标识身份验证(auth.type: "managed_identity")。 也不再支持使用 Foundry 帐户的托管标识进行身份验证。 此更改会影响直接附加到提示代理的工具以及工具箱中的工具。 通过 auth.type: "project_connection" 使用 OpenAPI 项目连接来使用 Foundry 项目的托管标识。 在该日期之前迁移以避免身份验证失败。 请参阅“确定需要迁移的配置”。
先决条件
在开始之前,请确保具备:
具有适当权限的Azure订阅。
Foundry 项目上用于创建和运行代理的 Foundry 用户角色。
重要
Foundry RBAC 角色最近已更名。 Foundry 用户、Foundry 所有者、Foundry 帐户所有者和 Foundry 项目经理之前的名称分别为“Azure AI 用户”、“Azure AI 所有者”、“Azure AI 帐户所有者”和“Azure AI 项目经理”。 在重命名推出时,你仍可能会在某些位置看到以前的名称。重命名后,角色 ID 和核心权限保持不变。
在 Foundry Project 上使用 Foundry Project Manager 角色创建 Project 连接。 此角色包括匿名、API 密钥和项目托管标识连接。
已创建配置了终结点的 Foundry 项目。
在项目中部署的 AI 模型。 确认模型和项目所在区域都支持 OpenAPI 工具,具体请参见 按区域和模型划分的工具支持。
为你的首选语言安装的依赖项:
- Python SDK 示例:
azure-ai-projects、azure-identity和jsonref。 直接响应示例也使用openai。 - C# SDK 示例:
Azure.AI.Projects、Azure.AI.Projects.Agents、Azure.AI.Extensions.OpenAI和Azure.Identity。 直接 HTTP 示例使用Azure.Identity。 - JavaScript/TypeScript SDK 示例:
@azure/ai-projects和@azure/identity。 直接 HTTP 示例使用@azure/identity。 - Java HTTP 示例:
com.azure:azure-identity和com.fasterxml.jackson.core:jackson-databind。
- Python SDK 示例:
满足以下要求的 OpenAPI 3.0 或 3.1 规范文件:
- 每个函数都必须有一个
operationId(这是 OpenAPI 工具所需的)。 -
operationId应仅包含字母、-和_。 - 使用描述性名称帮助模型有效地确定要使用的函数。
- 支持的请求正文内容类型:
application/jsonapplication/json-patch+json
- 每个函数都必须有一个
对于项目托管标识身份验证:具有
authType: "ProjectManagedIdentity"的 OpenAPI 项目连接,以及分配给项目托管标识的最低特权目标服务角色。 将连接的完整资源 ID 传递给工具。 请参阅 “创建项目托管标识连接”。对于 API 密钥/令牌身份验证:使用你的 API 密钥或令牌配置的项目连接。 请参阅 向项目添加新连接。
对于匿名身份验证:带有
authType: "None"的 OpenAPI 项目连接。 请参阅 创建匿名 OpenAPI 连接。
环境变量
| 变量 | 描述 |
|---|---|
FOUNDRY_PROJECT_ENDPOINT |
Foundry 项目终结点,例如 https://<account>.services.ai.azure.com/api/projects/<project>。 请勿使用外部 API 终结点。 |
FOUNDRY_MODEL_DEPLOYMENT_NAME |
您已部署的模型名称。 |
OPENAPI_CONNECTION_ID |
所选身份验证方法的 OpenAPI 连接的完整 ARM 资源 ID。 |
TOOLBOX_CONNECTION_ID |
对于通过项目连接附加工具箱的样本,该单独连接到工具箱 MCP 终结点的完整资源 ID。 |
注意
FOUNDRY_PROJECT_ENDPOINT 值是指 Microsoft Foundry 项目终结点,而不是外部 OpenAPI 服务终结点。 可以在项目的“概述”页下的 Microsoft Foundry 门户中找到此终结点。 此终结点需要对代理服务进行身份验证,并且独立于规范文件中定义的任何 OpenAPI 终结点。
使用支持
下表显示了 SDK 和设置支持。
| Microsoft Foundry 支持 | Python SDK | C# SDK | JavaScript SDK | Java SDK | REST API | 基本代理设置 | 标准代理设置 |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
注意
本文中的 Java 示例使用 Java 的 HTTP 客户端和 Azure Identity 发送与其他语言相同的 Responses 有效负载。 它不需要类型化的 OpenAPI 工具模型。
运行匿名首次成功流
从匿名天气 API 开始,验证代理是否可以加载 OpenAPI 规范并调用操作。 即使使用匿名身份验证,也要创建 OpenAPI 项目连接,并将其完整资源 ID 传递给该工具。 匿名身份验证不需要外部 API 凭据。 请参阅 创建匿名 OpenAPI 连接。
- 从 先决条件 中安装所选语言的 SDK 包。
- 下载
weather_openapi.json并将其保存到assets示例使用的路径。 - 设置 Foundry 项目终结点和模型部署值。
- 为
https://wttr.in创建匿名 OpenAPI 连接,并将OPENAPI_CONNECTION_ID设置为其完整资源 ID。 - 在所选语言部分中运行匿名示例。
- 确认响应包含西雅图的当前天气,然后删除示例创建的代理版本。
匿名调用成功后,配置目标 API 所需的身份验证。 将 API 密钥身份验证、Bearer 令牌身份验证和 项目托管标识身份验证 保留为单独的变体。
了解限制
- OpenAPI 工具不支持 OAuth 标识直通(
OAuth2连接),包括将它们添加到工具箱时。 使用匿名、基于密钥或 Project 托管标识身份验证。 对 MCP 工具的 OAuth 支持不会扩展到同一工具箱中的 OpenAPI 工具。 - OpenAPI 规范的每个操作都必须包含
operationId,且operationId只能包含字母、-和_。 - 支持的请求正文内容类型:
application/json,application/json-patch+json。 - 对于 API 密钥身份验证,请使用每个 OpenAPI 工具的一个 API 密钥安全方案。 如果需要多个安全方案,请创建多个 OpenAPI 工具。
- 定期轮换 API 密钥和持有者令牌,并在疑似暴露后立即轮换。 当凭据发生更改时,更新项目连接;不要将凭据放在 OpenAPI 规范或源代码中。
在 Foundry 门户中配置 OpenAPI 身份验证
通过 工具>自定义>OpenAPI 添加工具时,请为该工具创建项目连接。 无论是通过门户、SDK 还是 REST API 配置工具,匿名、 API 密钥和 托管标识 身份验证都需要连接。
门户的 托管标识 选项使用 Foundry 项目的托管标识,而不是 Foundry 帐户的托管标识。 工具箱中的 OpenAPI 工具还使用项目的托管标识。 从 2027 年 1 月 8 日起,这两个路径都必须使用 OpenAPI 项目连接进行托管标识身份验证。 请参阅 托管标识支持。
匿名身份验证意味着目标 API 不需要凭据。 这并不意味着可以跳过创建连接。
| Authentication | 连接配置 |
|---|---|
| 匿名 | 创建没有身份验证的 OpenAPI 项目连接(authType: "None")。 不需要 API 密钥或令牌。 |
| API 密钥 | 创建存储 API 密钥的项目连接。 将密钥名称与 OpenAPI 安全方案中的标头或查询参数匹配。 请参阅 使用 API 密钥进行身份验证。 |
| 托管标识(项目托管标识) | 使用 authType: "ProjectManagedIdentity"、目标 API 终结点以及该 API 所要求的受众创建 OpenAPI 项目连接。 将目标服务上所需的角色分配给项目的托管标识。 此选项不使用帐户的托管标识。 |
配置匿名身份验证
- 在 Foundry 项目中打开 工具>自定义>OpenAPI 。
- 在“创建 OpenAPI 工具”中,输入工具的“名称”和“描述”。
- 将 身份验证方法 设置为 Anonymous。
- 在 “连接”下,选择现有的匿名连接,或选择 “创建新连接” 以创建一个连接。
- 输入 OpenAPI 3.0+ 架构,然后选择“ 创建工具”。
即使选择了“匿名”,也需要“连接”字段。
配置托管身份身份验证
托管标识选项需要项目的托管标识。 帐户托管标识的现有角色分配不会授予对项目的托管标识的访问权限。
- 在 创建 OpenAPI 工具中,将 身份验证方法 设置为 托管标识。
- 在 “连接”下,选择现有的项目托管标识连接,或选择“创建新连接”。
- 在 “创建 OpenAPI 连接”中,输入 连接名称,并将 身份验证类型 设置为 托管标识。
- 输入 API 的目标 URL 和 API 所需的 受众 。 受众不是你的 Foundry 项目终结点。
- 选择“ 创建连接”,然后在工具的 “连接 ”字段中选择该连接。
- 输入工具的名称、说明和OpenAPI 3.0+ 架构,然后选择创建工具。
在调用该工具之前,将项目的托管标识分配给目标服务上所需的角色。
有关通过 REST 设置项目托管标识连接,请参阅 创建项目托管标识连接。 在代码中使用该连接时,传递其完整资源 ID 和 auth.type: "project_connection"。
SDK 和 REST 示例还引用项目连接。 在运行它们之前创建连接。
创建匿名 OpenAPI 连接
使用上一部分中的门户步骤,或在登录az login后使用 Azure CLI 和 curl 运行以下 Bash 命令。 将占位符替换为 Foundry 项目详细信息。 此连接之所以使用 authType: "None" ,是因为天气 API 不需要凭据。
SUB="<subscription-id>"
RESOURCE_GROUP="<resource-group>"
ACCOUNT="<foundry-account-name>"
PROJECT_NAME="<foundry-project-name>"
PROJECT="/subscriptions/$SUB/resourceGroups/$RESOURCE_GROUP"
PROJECT="$PROJECT/providers/Microsoft.CognitiveServices"
PROJECT="$PROJECT/accounts/$ACCOUNT/projects/$PROJECT_NAME"
export OPENAPI_CONNECTION_ID="$PROJECT/connections/weather-anonymous"
ARM_TOKEN="$(az account get-access-token \
--subscription "$SUB" \
--resource https://management.azure.com \
--query accessToken -o tsv)"
curl --fail-with-body --request PUT \
--url "https://management.azure.com$OPENAPI_CONNECTION_ID?api-version=2025-06-01" \
--header "Authorization: Bearer $ARM_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"properties": {
"category": "OpenAPI",
"authType": "None",
"target": "https://wttr.in",
"metadata": {
"type": "openapi"
}
}
}'
参考:Foundry 项目连接资源模式。
在该工具的 auth.security_scheme.project_connection_id 中传入 OPENAPI_CONNECTION_ID,并使用 auth.type: "project_connection"。 连接的 authType 确定目标 API 以匿名方式调用。
将 OpenAPI 工具添加到工具箱
使用此模式公开 OpenAPI 规范描述的 REST API。 对于匿名、API 密钥或项目托管标识身份验证,请将工具的 auth.type 设置为 project_connection。 连接的 authType 决定了 Foundry 如何向目标 API 进行身份验证。
对于托管标识身份验证,工具箱需要 项目托管标识。 工具箱不支持帐户托管标识,包括现有订阅。
指定 auth.type: "managed_identity" 内联的旧工具箱配置也使用项目托管标识,但身份验证方案将于 2027 年 1 月 8 日停用。
在该日期之前将这些工具迁移到 OpenAPI 项目连接。 项目的标识及其现有目标服务权限保持不变。
以下代码片段显示工具配置,并非完整的程序。 将每个空 spec 对象替换为您的 OpenAPI 规范。 若要创建工具箱,请使用以下部分中的完整语言示例。
重要
使用托管标识身份验证时,请为 Foundry 项目的托管标识 分配允许对目标服务执行所需 API 操作的最低特权 RBAC 角色。 例如,仅当 API 需要只读Azure 资源管理器访问权限时,才在目标Azure资源上分配读取器。 如果没有所需的分配,代理在调用 API 时会收到 401 Unauthorized 响应。 有关完整设置步骤,请参阅 使用托管标识进行身份验证。
匿名身份验证:
首先创建具有 authType: "None" 的 OpenAPI 连接,并将 <OPENAPI_CONNECTION_ID> 替换为其完整资源 ID。
{
"description": "REST API via OpenAPI spec",
"tools": [
{
"type": "openapi",
"openapi": {
"name": "my-api",
"spec": {},
"auth": {
"type": "project_connection",
"security_scheme": {
"project_connection_id": "<OPENAPI_CONNECTION_ID>"
}
}
}
}
]
}
Project 连接身份验证:
当 API 需要存储在 Foundry 项目连接中的密钥或令牌时,请使用此模式。
{
"description": "REST API with connection-based auth",
"tools": [
{
"type": "openapi",
"openapi": {
"name": "my-api",
"spec": {},
"auth": {
"type": "project_connection",
"security_scheme": {
"project_connection_id": "<OPENAPI_CONNECTION_ID>"
}
}
}
}
]
}
Project托管标识身份验证:
使用 authType: "ProjectManagedIdentity" 创建 OpenAPI 项目连接,并使用 auth.type: "project_connection" 传递其完整资源 ID。 不要在工具箱中使用直接 managed_identity 受众配置。
{
"description": "REST API with project managed identity auth",
"tools": [
{
"type": "openapi",
"openapi": {
"name": "my-api",
"spec": {},
"auth": {
"type": "project_connection",
"security_scheme": {
"project_connection_id": "<OPENAPI_CONNECTION_ID>"
}
}
}
}
]
}
import os
from azure.ai.projects.models import (
OpenApiFunctionDefinition,
OpenApiProjectConnectionAuthDetails,
OpenApiProjectConnectionSecurityScheme,
OpenApiToolboxTool,
)
tools = [
OpenApiToolboxTool(
openapi=OpenApiFunctionDefinition(
name="my-api",
spec={},
auth=OpenApiProjectConnectionAuthDetails(
security_scheme=OpenApiProjectConnectionSecurityScheme(
project_connection_id=os.environ["OPENAPI_CONNECTION_ID"]
)
),
)
)
]
using System;
using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects.Agents;
BinaryData specBytes = BinaryData.FromString("<OpenAPI spec JSON>");
OpenApiToolboxTool tool = new(
new OpenApiFunctionDefinition(
name: "my-api",
specification: specBytes,
authentication: new OpenApiProjectConnectionAuthenticationDetails(
new OpenApiProjectConnectionSecurityScheme(
Environment.GetEnvironmentVariable("OPENAPI_CONNECTION_ID")
?? throw new InvalidOperationException(
"Set OPENAPI_CONNECTION_ID before running.")))
)
);
ToolboxVersion toolboxVersion = await toolboxClient.CreateVersionAsync(
name: "my-toolbox",
tools: [tool],
description: "REST API via OpenAPI spec"
);
const connectionId = process.env.OPENAPI_CONNECTION_ID;
if (!connectionId) {
throw new Error("Set OPENAPI_CONNECTION_ID before running.");
}
const tools = [
{
type: "openapi",
openapi: {
name: "my-api",
spec: { /* paste OpenAPI spec object here */ },
auth: {
type: "project_connection",
security_scheme: {
project_connection_id: connectionId,
},
},
},
},
];
使用 Azure 开发人员 CLI 创建 OpenAPI 工具箱
OpenAPI 工具将规范直接嵌入到 tools: 下。 基于连接的身份验证 (connection_auth) 引用项目连接。 也创建用于匿名身份验证的连接。
第 1 步。 创建身份验证连接
对于匿名身份验证,请按照 创建匿名 OpenAPI 连接操作。 对于 API 密钥身份验证,请使用以下命令:
# API-key auth (passed by the platform on every call)
# Set OPENAPI_AUTHORIZATION_HEADER in your shell without committing its value.
azd ai connection create my-api-conn \
--kind remote-tool \
--target https://api.example.com \
--auth-type custom-keys \
--custom-key "Authorization=$OPENAPI_AUTHORIZATION_HEADER"
有关完整的标志集 azd ai connection create ,请参阅 工具箱 MCP 身份验证和配置。
步骤 2。 定义工具箱
OpenAPI 规范直接写在 tools[].openapi.spec 下方。
# my-toolbox.yaml
description: OpenAPI toolbox
tools:
- type: openapi
name: my-api
openapi:
name: my-api
spec:
openapi: "3.0.1"
info:
title: "My API"
version: "1.0"
servers:
- url: https://api.example.com/v1
paths:
/search:
get:
operationId: search
parameters:
- name: query
in: query
required: true
schema:
type: string
responses:
"200":
description: OK
auth:
type: connection_auth
connection_id: my-api-conn
对于匿名 API,请保留基于连接的身份验证。 例如,若要使用之前创建的天气连接,请将示例规范替换为 weather_openapi.json 并使用此 auth: 块:
auth:
type: connection_auth
connection_id: weather-anonymous
步骤 3。 创建工具箱
azd ai toolbox create my-toolbox --from-file my-toolbox.yaml
运行代码示例之前
- 在运行任何示例(包括匿名示例)之前创建 OpenAPI 项目连接。 对于天气示例,请使用以
https://wttr.in为目标的匿名连接,并将OPENAPI_CONNECTION_ID设置为其完整 ARM 资源 ID。 - 下载维护
tripadvisor_openapi.json的规范并将其保存到assets语言示例使用的路径。
注意
- 需要最新的 SDK 包。 .NET SDK 目前为预览版。 有关详细信息,请参阅 快速入门 。
- 使用完整的连接资源 ID:
/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.CognitiveServices/accounts/<account>/projects/<project>/connections/<connection>
重要
若要使 API 密钥身份验证正常工作,OpenAPI 规范文件必须包括:
- 包含你的 API 密钥配置(如标头名称和参数名称)的
securitySchemes部分。 -
security部分引用安全方案。 - 使用匹配的密钥名称和值配置的项目连接。
如果没有这些配置,API 密钥不会包含在请求中。 有关详细的设置说明,请参阅“ 使用 API 密钥进行身份验证 ”部分。
还可以通过将令牌存储在项目连接中来使用基于令牌的身份验证(例如持有者令牌)。 对于 Bearer 令牌身份验证,请创建一个 自定义密钥 连接,并将密钥设置为 Authorization,值设置为 Bearer <token>(将 <token> 替换为您的实际令牌)。 后跟空格的单词 Bearer 必须包含在值中。 有关详细信息,请参阅 设置持有者令牌连接。
将代理与 OpenAPI 工具配合使用的示例
此示例演示如何通过代理使用由 OpenAPI 规范 描述的服务。 它使用 wttr.in 服务获取天气及其规范文件weather_openapi.json。 选择 Prompt Agents以使用 Azure AI Projects SDK 创建服务器端提示代理,或托管代理使用 Microsoft Agent Framework 生成临时进程内代理。
提示智能体
import os
import jsonref
from typing import Any, cast
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
PromptAgentDefinition,
OpenApiTool,
OpenApiFunctionDefinition,
OpenApiProjectConnectionAuthDetails,
OpenApiProjectConnectionSecurityScheme,
)
# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
AGENT_NAME = "MyAgent"
# Create a client to call Foundry API
with AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
) as project:
weather_asset_file_path = os.path.abspath(
os.path.join(os.path.dirname(__file__), "../assets/weather_openapi.json")
)
with open(weather_asset_file_path, "r") as f:
openapi_weather = cast(dict[str, Any], jsonref.loads(f.read()))
# Initialize agent OpenAPI tool using the read in OpenAPI spec
weather_tool = OpenApiTool(
openapi=OpenApiFunctionDefinition(
name="get_weather",
spec=openapi_weather,
description="Retrieve weather information for a location.",
auth=OpenApiAnonymousAuthDetails(),
)
)
agent = project.agents.create_version(
agent_name=AGENT_NAME,
definition=PromptAgentDefinition(
model="gpt-4.1-mini",
instructions="You are a helpful assistant.",
tools=[weather_tool],
),
)
with project.get_openai_client(agent_name=agent.name) as openai:
response = openai.responses.create(
input="What's the weather in Seattle?",
)
print(response.output_text)
# Clean up resources
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
此示例使用 OpenAPI 工具创建一个提示代理,该工具使用匿名身份验证调用 wttr.in 天气 API。 该工具直接附加到代理定义。 运行代码时:
- 它从本地 JSON 文件加载天气 OpenAPI 规范。
- 创建一个配置了匿名访问天气工具的提示智能体。
- 发送询问西雅图天气的查询。
- 代理使用 OpenAPI 工具调用天气 API 并返回格式化的结果。
- 通过删除代理软件版本进行清理。
托管代理
此示例使用来自 Microsoft Agent Framework 的 FoundryChatClient,并通过使用 FoundryToolbox 连接到 toolbox MCP 终结点。 使用 pip install "agent-framework-foundry==1.15.0" "azure-ai-projects>=2.3.0,<2.8.0" jsonref 安装兼容的包版本,设置 FOUNDRY_PROJECT_ENDPOINT 环境变量,并使用 az login 登录。
OpenApiToolboxTool 是特定于工具箱的模型;仅在将工具直接附加到提示代理时使用 OpenApiTool 。
注意
对于使用 LangGraph、LangChain 或 Deep Agents 构建的 Python 代理,请使用 连接到同一个工具箱终结点。 请参阅 将工具箱与托管代理配合使用 和 LangGraph 工具箱示例。
import asyncio
import os
import jsonref
from typing import Any, cast
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient, FoundryToolbox
from azure.identity import AzureCliCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
OpenApiToolboxTool,
OpenApiFunctionDefinition,
OpenApiProjectConnectionAuthDetails,
OpenApiProjectConnectionSecurityScheme,
)
PROJECT_ENDPOINT = os.environ["FOUNDRY_PROJECT_ENDPOINT"]
async def main() -> None:
credential = AzureCliCredential()
# 1. Create the OpenAPI tool and add it to a toolbox. Using a toolbox is the
# recommended way to give agents tools: curate tools once and reuse the
# toolbox across agents. See /azure/foundry/agents/concepts/toolbox-overview
project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=credential)
weather_asset_file_path = os.path.abspath(
os.path.join(os.path.dirname(__file__), "../assets/weather_openapi.json")
)
with open(weather_asset_file_path, encoding="utf-8") as f:
openapi_weather = cast(dict[str, Any], jsonref.loads(f.read()))
weather_tool = OpenApiToolboxTool(
openapi=OpenApiFunctionDefinition(
name="get_weather",
spec=openapi_weather,
description="Retrieve weather information for a location.",
auth=OpenApiProjectConnectionAuthDetails(
security_scheme=OpenApiProjectConnectionSecurityScheme(
project_connection_id=os.environ["OPENAPI_CONNECTION_ID"]
)
),
)
)
toolbox = project.toolboxes.create_version(
name="openapi-toolbox",
description="Toolbox with the OpenAPI weather tool",
tools=[weather_tool],
)
# 2. The toolbox exposes an MCP-compatible endpoint.
TOOLBOX_MCP_URL = (
f"{PROJECT_ENDPOINT}/toolboxes/{toolbox.name}"
f"/versions/{toolbox.version}/mcp?api-version=v1"
)
# 3. Attach the toolbox to the hosted agent as an MCP tool.
toolbox_tool = FoundryToolbox(credential, url=TOOLBOX_MCP_URL)
agent = Agent(
client=FoundryChatClient(credential=credential),
instructions="You are a helpful assistant. Use the OpenAPI weather tool to answer questions.",
tools=[toolbox_tool],
)
result = await agent.run("What's the weather in Seattle?")
print(f"Agent: {result.text}")
if __name__ == "__main__":
asyncio.run(main())
预期输出
Agent: The weather in Seattle is currently cloudy with a temperature of 52°F (11°C)...
将代理与 OpenAPI 工具配合使用的示例
此示例演示如何通过代理使用由 OpenAPI 规范 描述的服务。 它使用 wttr.in 服务获取天气及其规范文件weather_openapi.json。 选择 Prompt Agents以使用 Azure AI Projects SDK 创建服务器端提示代理,或托管代理使用 Microsoft Agent Framework 生成临时进程内代理。
提示智能体
此示例使用 Azure AI Projects 客户端库的同步方法。 有关使用异步方法的示例,请参阅GitHub上.NET存储库Azure SDK中的 sample。
using System;
using System.IO;
using System.Runtime.CompilerServices;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects.Agents;
using Azure.Identity;
using OpenAI.Responses;
#pragma warning disable AAIP002
class OpenAPIDemo
{
// Utility method to get the OpenAPI specification file from the Assets folder.
private static string GetFile([CallerFilePath] string pth = "")
{
var dirName = Path.GetDirectoryName(pth) ?? "";
return Path.Combine(dirName, "Assets", "weather_openapi.json");
}
public static void Main()
{
var projectEndpoint =
Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
?? throw new InvalidOperationException(
"Set FOUNDRY_PROJECT_ENDPOINT before running.");
var deploymentName =
Environment.GetEnvironmentVariable("FOUNDRY_MODEL_DEPLOYMENT_NAME")
?? throw new InvalidOperationException(
"Set FOUNDRY_MODEL_DEPLOYMENT_NAME before running.");
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// The connection specifies anonymous authentication to the weather API.
string filePath = GetFile();
OpenApiFunctionDefinition toolDefinition = new(
name: "get_weather",
specification: BinaryData.FromBytes(File.ReadAllBytes(filePath)),
authentication: new OpenApiProjectConnectionAuthenticationDetails(
new OpenApiProjectConnectionSecurityScheme(
Environment.GetEnvironmentVariable("OPENAPI_CONNECTION_ID")
?? throw new InvalidOperationException(
"Set OPENAPI_CONNECTION_ID before running.")))
);
toolDefinition.Description = "Retrieve weather information for a location.";
OpenApiTool openapiTool = new(toolDefinition);
// Create the agent definition and the agent version.
DeclarativeAgentDefinition agentDefinition = new(model: deploymentName)
{
Instructions = "You are a helpful assistant.",
Tools = { openapiTool }
};
ProjectsAgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "myAgent",
options: new(agentDefinition));
// Create a response object and ask the question about the weather in Seattle, WA.
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentVersion.Name);
ResponseResult response = responseClient.CreateResponse(
userInputText: "Use the OpenAPI tool to print out, what is the weather in Seattle, WA today."
);
Console.WriteLine(response.GetOutputText());
// Finally, delete all the resources created in this sample.
projectClient.AgentAdministrationClient.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
}
}
此代码的作用
此 C# 示例使用 OpenAPI 工具创建代理,该工具使用匿名身份验证从 wttr.in 检索天气信息。 运行代码时:
- 它从本地 JSON 文件读取天气 OpenAPI 规范。
- 使用配置的天气工具创建智能体。
- 使用 OpenAPI 工具发送询问西雅图天气的请求。
- 代理调用天气 API 并返回结果。
- 删除智能体以进行清理。
所需的输入
- 环境变量:
FOUNDRY_PROJECT_ENDPOINT、FOUNDRY_MODEL_DEPLOYMENT_NAME和OPENAPI_CONNECTION_ID。 - 本地文件:
Assets/weather_openapi.json(OpenAPI 规范)
预期输出
The weather in Seattle, WA today is cloudy with temperatures around 52°F...
常见错误
-
FileNotFoundException:未在 Assets 文件夹中找到 OpenAPI 规范文件 -
UnauthorizedAccessException:凭据无效或 RBAC 权限不足 -
未注入 API 密钥:确认您的 OpenAPI 规范同时包含
securitySchemes(位于components中)和security部分,且方案名称一致
托管代理
此示例使用 Azure AI Projects SDK 创建 OpenAPI 工具箱,然后使用 Microsoft Agent Framework AddFoundryToolboxes 集成功能。 除 Microsoft.Agents.AI.Foundry.Hosting中的 C# 依赖项外,还使用带有 和 Azure.AI.AgentServer.Responses 的 ASP.NET Core 项目。 设置FOUNDRY_PROJECT_ENDPOINT、FOUNDRY_MODEL_DEPLOYMENT_NAME和OPENAPI_CONNECTION_ID,然后使用az login登录。
using System;
using System.IO;
using System.Runtime.CompilerServices;
using Azure.AI.AgentServer.Responses;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects.Agents;
using Azure.Identity;
using Microsoft.AspNetCore.Builder;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Foundry.Hosting;
using Microsoft.Extensions.DependencyInjection;
using OpenAI.Chat;
string GetFile([CallerFilePath] string pth = "")
{
var dirName = Path.GetDirectoryName(pth) ?? "";
return Path.Combine(dirName, "Assets", "weather_openapi.json");
}
string projectEndpoint = Environment.GetEnvironmentVariable(
"FOUNDRY_PROJECT_ENDPOINT")
?? throw new InvalidOperationException("Set FOUNDRY_PROJECT_ENDPOINT.");
string deploymentName = Environment.GetEnvironmentVariable(
"FOUNDRY_MODEL_DEPLOYMENT_NAME")
?? throw new InvalidOperationException("Set FOUNDRY_MODEL_DEPLOYMENT_NAME.");
DefaultAzureCredential credential = new();
// 1. Create the OpenAPI tool and add it to a toolbox. Using a toolbox is the
// recommended way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
AIProjectClient projectClient = new(endpoint: new Uri(projectEndpoint), tokenProvider: credential);
string filePath = GetFile();
OpenApiFunctionDefinition toolDefinition = new(
name: "get_weather",
specification: BinaryData.FromBytes(File.ReadAllBytes(filePath)),
authentication: new OpenApiProjectConnectionAuthenticationDetails(
new OpenApiProjectConnectionSecurityScheme(
Environment.GetEnvironmentVariable("OPENAPI_CONNECTION_ID")
?? throw new InvalidOperationException(
"Set OPENAPI_CONNECTION_ID before running.")))
);
toolDefinition.Description = "Retrieve weather information for a location.";
OpenApiToolboxTool openapiTool = new(toolDefinition);
ToolboxVersion toolboxVersion = projectClient.AgentAdministrationClient
.GetAgentToolboxes().CreateVersion(
name: "openapi-toolbox",
tools: [openapiTool],
description: "Toolbox with the OpenAPI weather tool");
projectClient.AgentAdministrationClient.GetAgentToolboxes()
.UpdateDefaultVersion(toolboxVersion.Name, toolboxVersion.Version);
// Create the hosted agent and register the toolbox integration.
AIAgent agent = projectClient.AsAIAgent(
model: deploymentName,
instructions: "You are a helpful assistant with access to the toolbox tools.",
name: "hosted-toolbox-agent");
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddFoundryResponses(agent);
builder.Services.AddFoundryToolboxes(credential, toolboxVersion.Name);
var app = builder.Build();
app.MapFoundryResponses();
app.Run();
预期输出
该示例启动 HTTP 服务器。 发送有关天气的 Responses 请求时,代理会通过工具箱调用 API,并返回当前条件:
The current weather in Seattle is <temperature> with <conditions>.
有关包含经过身份验证的 API 模式的完整示例,请参阅 Agent_Step17_OpenAPITools。
在 Web 服务上使用具有 OpenAPI 工具的代理的示例,需要身份验证
在此示例中,您将经过身份验证的 OpenAPI 工具直接附加到提示代理。 您使用 TripAdvisor 规范和存储在项目连接中的 API 密钥。
TripAdvisor 服务需要 API 密钥身份验证。 按照 API 密钥进行身份验证中所述创建项目连接,并将 OPENAPI_CONNECTION_ID 设置为其完整资源 ID。 连接的密钥名称必须与 TripAdvisor 规范匹配。
using System;
using System.IO;
using System.Runtime.CompilerServices;
using Azure.AI.Extensions.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.Identity;
using OpenAI.Responses;
#pragma warning disable AAIP002
class OpenAPIConnectedDemo
{
// Utility method to get the OpenAPI specification file from the Assets folder.
private static string GetFile([CallerFilePath] string pth = "")
{
var dirName = Path.GetDirectoryName(pth) ?? "";
return Path.Combine(dirName, "Assets", "tripadvisor_openapi.json");
}
public static void Main()
{
var projectEndpoint =
Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
?? throw new InvalidOperationException(
"Set FOUNDRY_PROJECT_ENDPOINT before running.");
var deploymentName =
Environment.GetEnvironmentVariable("FOUNDRY_MODEL_DEPLOYMENT_NAME")
?? throw new InvalidOperationException(
"Set FOUNDRY_MODEL_DEPLOYMENT_NAME before running.");
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Create an OpenAPI tool with authentication by project connection security scheme.
string filePath = GetFile();
var connectionId =
Environment.GetEnvironmentVariable("OPENAPI_CONNECTION_ID")
?? throw new InvalidOperationException(
"Set OPENAPI_CONNECTION_ID to the TripAdvisor connection ID.");
OpenApiFunctionDefinition toolDefinition = new(
name: "tripadvisor",
specification: BinaryData.FromBytes(File.ReadAllBytes(filePath)),
authentication: new OpenApiProjectConnectionAuthenticationDetails(new OpenApiProjectConnectionSecurityScheme(
projectConnectionId: connectionId
))
);
toolDefinition.Description = "Trip Advisor API to get travel information.";
OpenApiTool openapiTool = new(toolDefinition);
// Create the agent definition and the agent version.
DeclarativeAgentDefinition agentDefinition = new(model: deploymentName)
{
Instructions = "You are a helpful assistant.",
Tools = { openapiTool }
};
ProjectsAgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "myAgent",
options: new(agentDefinition));
// Create a response object and ask the question about the hotels in France.
// Test the Web service access before you run production scenarios.
// It can be done by setting:
// ToolChoice = ResponseToolChoice.CreateRequiredChoice()`
// in the ResponseCreationOptions. This setting will
// force Agent to use tool and will trigger the error if it is not accessible.
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentVersion.Name);
CreateResponseOptions responseOptions = new()
{
ToolChoice = ResponseToolChoice.CreateRequiredChoice(),
InputItems =
{
ResponseItem.CreateUserMessageItem("Recommend me 5 top hotels in paris, France."),
}
};
ResponseResult response = responseClient.CreateResponse(
options: responseOptions
);
Console.WriteLine(response.GetOutputText());
// Finally, delete all the resources we have created in this sample.
projectClient.AgentAdministrationClient.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
}
}
此代码的作用
此 C# 示例通过项目连接使用具有 API 密钥身份验证的 OpenAPI 工具。 运行代码时:
- 它从本地文件加载 TripAdvisor OpenAPI 规范。
- 它引用包含 API 密钥的 TripAdvisor 项目连接。
- 它将 TripAdvisor 工具附加到代理,配置为使用连接进行身份验证。
- 发送巴黎酒店推荐请求。
- 代理使用存储的 API 密钥调用 TripAdvisor API,并返回结果。
- 删除智能体以进行清理。
所需的输入
- 环境变量:
FOUNDRY_PROJECT_ENDPOINT、FOUNDRY_MODEL_DEPLOYMENT_NAME和OPENAPI_CONNECTION_ID。 - 本地文件:
Assets/tripadvisor_openapi.json - 项目连接:配置了有效的 API 密钥的
tripadvisor
预期输出
Here are 5 top hotels in Paris, France:
1. Hotel Name - Rating: 4.5/5, Location: ...
2. Hotel Name - Rating: 4.4/5, Location: ...
...
常见错误
-
ConnectionNotFoundException:找不到名为tripadvisor的 Project 连接。 -
AuthenticationException:项目连接中的 API 密钥无效,或 OpenAPI 规范中缺少或存在不正确的securitySchemes配置。 - 未使用的工具:验证
ToolChoice = ResponseToolChoice.CreateRequiredChoice()会强制使用该工具。 -
API 密钥未传递给 API:确保 OpenAPI 规范已正确配置
securitySchemes和security部分。
使用 OpenAPI 工具功能创建Java代理
此Java设置可以引用 MCP 工具,但Java SDK 尚未公开工具箱创建 API。
提示
建议:对于大多数智能体,通过 工具箱 添加 OpenAPI 工具,并将该工具箱作为 MCP 工具附加到智能体。 使用 Python、REST API、C# 或 TypeScript 示例或 Foundry 门户创建工具箱,然后从Java代理引用其 MCP 终结点作为一个McpTool。
以下示例演示如何使用 REST API 调用 OpenAPI 工具。
获取访问令牌:
AGENT_TOKEN=$(az account get-access-token --scope https://ai.azure.com/.default --query accessToken -o tsv)
匿名身份验证
通过工具箱添加 OpenAPI 工具,然后将工具箱作为 MCP 工具附加到代理。 有关详细信息,请参阅 什么是工具箱?
- 创建包含 OpenAPI 天气工具的工具箱:
curl --request POST \
--url "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/openapi-toolbox/versions?api-version=v1" \
--header "Foundry-Features: Toolboxes=V1Preview" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"description": "Toolbox with the OpenAPI weather tool",
"tools": [
{
"type": "openapi",
"openapi": {
"name": "weather",
"description": "Tool to get weather data",
"auth": {
"type": "project_connection",
"security_scheme": {
"project_connection_id": "'$OPENAPI_CONNECTION_ID'"
}
},
"spec": {
"openapi": "3.1.0",
"info": {
"title": "get weather data",
"description": "Retrieves current weather data for a location.",
"version": "v1.0.0"
},
"servers": [{ "url": "https://wttr.in" }],
"paths": {
"/{location}": {
"get": {
"description": "Get weather information for a specific location",
"operationId": "GetCurrentWeather",
"parameters": [
{
"name": "location",
"in": "path",
"description": "City or location to retrieve the weather for",
"required": true,
"schema": { "type": "string" }
},
{
"name": "format",
"in": "query",
"description": "Format in which to return data. Always use 3.",
"required": true,
"schema": { "type": "integer", "default": 3 }
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"text/plain": {
"schema": { "type": "string" }
}
}
},
"404": { "description": "Location not found" }
}
}
}
}
}
}
}
]
}'
工具箱在 $FOUNDRY_PROJECT_ENDPOINT/toolboxes/openapi-toolbox/versions/<version>/mcp?api-version=v1 处提供了一个与 MCP 兼容的端点,其中 <version> 是上一次调用返回的版本。
- 使用用户 Entra 令牌创建一个指向工具箱终结点的远程工具项目连接,以便传递调用方的身份(受众为
https://ai.azure.com)。
azd ai connection create openapi-toolbox-conn \
--kind remote-tool \
--target "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/openapi-toolbox/versions/<version>/mcp?api-version=v1" \
--auth-type user-entra-token \
--audience https://ai.azure.com
通过将工具箱附加为 MCP 工具来创建响应。
将
TOOLBOX_CONNECTION_ID设置为openapi-toolbox-conn的完整资源 ID。 此连接与OPENAPI_CONNECTION_ID中的匿名 OpenAPI 连接分开。 将<version>替换为创建工具箱时返回的版本。
curl --request POST \
--url "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
--header "Authorization: Bearer $AGENT_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"model": "'$FOUNDRY_MODEL_DEPLOYMENT_NAME'",
"input": "Use the OpenAPI tool to get the weather in Seattle, WA today.",
"tool_choice": "required",
"tools": [
{
"type": "mcp",
"server_label": "toolbox",
"server_url": "'$FOUNDRY_PROJECT_ENDPOINT'/toolboxes/openapi-toolbox/versions/<version>/mcp?api-version=v1",
"require_approval": "never",
"project_connection_id": "'$TOOLBOX_CONNECTION_ID'",
"headers": {
"Foundry-Features": "Toolboxes=V1Preview"
}
}
]
}'
API 密钥身份验证(项目连接)
仅在匿名流成功后使用此变体。 从在运行代码示例之前下载 tripadvisor_openapi.json。 按 security中所述配置 API 密钥连接和规范中的 和 securitySchemes 条目。 将 OPENAPI_CONNECTION_ID 设置为该连接的完整资源 ID,而不是匿名天气连接的资源 ID。
此 Bash 示例使用 jq 将规范包含在与项目托管标识示例相同的 remote_tool 请求格式中。
jq -n \
--arg model "$FOUNDRY_MODEL_DEPLOYMENT_NAME" \
--arg connection_id "$OPENAPI_CONNECTION_ID" \
--slurpfile spec tripadvisor_openapi.json \
'{
model: $model,
input: "Recommend five top hotels in the United States.",
tools: [
{
type: "remote_tool",
tool_arguments: [
{
name: "openapi",
arguments: {
name: "tripadvisor",
description: "TripAdvisor travel information.",
auth: {
type: "project_connection",
security_scheme: {
project_connection_id: $connection_id
}
},
spec: $spec[0]
}
}
]
}
],
tool_choice: "required"
}' > openapi-api-key-request.json
curl --fail-with-body --request POST \
--url "${FOUNDRY_PROJECT_ENDPOINT%/}/openai/v1/responses" \
--header "Authorization: Bearer $AGENT_TOKEN" \
--header "Content-Type: application/json" \
--data @openapi-api-key-request.json
对于 Bearer 令牌 API,请保留相同的 project_connection 请求结构,但要使用按照 设置 Bearer 令牌连接 中所述方式配置的连接。 连接值必须以 Bearer 后跟空格开头。
托管标识身份验证
对于项目托管标识,请先 创建 OpenAPI 项目连接。 然后在响应请求中传递其完整资源 ID。 请参阅 调用具有项目托管标识的 OpenAPI 工具中的 REST 示例。
帐户托管标识是一个旧版选项,仅适用于现有订阅中直接附加到提示代理的 OpenAPI 工具。 它将于 2027 年 1 月 8 日停用。 在该日期之前,通过 OpenAPI 项目连接将这些配置迁移到项目托管标识。
此代码的作用
此 REST API 示例演示如何使用不同的身份验证方法调用 OpenAPI 工具。 请求:
- 对于匿名身份验证,请创建一个工具箱,其中包含 OpenAPI 工具定义和天气 API 规范。
- 创建一个响应,该响应将工具箱附加为 MCP 工具,并询问西雅图的天气。
- 显示通过项目连接进行 API 密钥身份验证的其他直接 REST 工具定义。
- 代理调用工具配置选择的 API,并返回结果。
所需的输入
- 环境变量:
FOUNDRY_PROJECT_ENDPOINT、、AGENT_TOKENFOUNDRY_MODEL_DEPLOYMENT_NAME. - 对于匿名身份验证:
OPENAPI_CONNECTION_ID引用匿名 OpenAPI 项目连接,并TOOLBOX_CONNECTION_ID引用工具箱 MCP 连接。 - 对于 API 密钥身份验证:
OPENAPI_CONNECTION_ID,引用 TripAdvisor API 密钥连接,以及tripadvisor_openapi.json。 - 对于项目托管标识身份验证:
OPENAPI_CONNECTION_ID如 项目托管标识示例所示。 - 请求正文中的内联 OpenAPI 规范。
预期输出
{
"id": "resp_abc123",
"object": "response",
"output": [
{
"type": "message",
"content": [
{
"type": "output_text",
"text": "The weather in Seattle, WA today is cloudy with a temperature of 52°F (11°C)..."
}
]
}
]
}
常见错误
-
401 Unauthorized:AGENT_TOKEN无效或缺失,或者由于你的 OpenAPI 规范中缺少securitySchemes和security,API 密钥未被注入 -
404 Not Found:终结点或模型部署名称不正确 -
400 Bad Request:格式不正确的 OpenAPI 规范或无效的身份验证配置 -
API 密钥未随请求一起发送:验证 OpenAPI 规范中的
components.securitySchemes部分是否已正确配置(不为空),并与项目连接密钥名称匹配
使用 OpenAPI 工具功能创建代理
以下 TypeScript 代码示例演示如何通过将 OpenAPI 工具添加到工具箱并将工具箱附加为 MCP 工具来创建具有 OpenAPI 工具功能的 AI 代理。 代理可以调用 OpenAPI 规范定义的外部 API。 有关此示例的 JavaScript 版本,请参阅 GitHub 上的 javaScript 存储库Azure SDK中的 sample。
import { DefaultAzureCredential } from "@azure/identity";
import {
AIProjectClient,
OpenApiToolboxTool,
OpenApiFunctionDefinition,
OpenApiProjectConnectionAuthDetails,
} from "@azure/ai-projects";
import * as fs from "fs";
import * as path from "path";
function requiredEnv(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Set ${name} before running.`);
}
return value;
}
const PROJECT_ENDPOINT = requiredEnv("FOUNDRY_PROJECT_ENDPOINT");
const deploymentName = requiredEnv("FOUNDRY_MODEL_DEPLOYMENT_NAME");
const weatherSpecPath = path.resolve("assets", "weather_openapi.json");
function loadOpenApiSpec(specPath: string): unknown {
if (!fs.existsSync(specPath)) {
throw new Error(`OpenAPI specification not found at: ${specPath}`);
}
try {
const data = fs.readFileSync(specPath, "utf-8");
return JSON.parse(data);
} catch (error) {
throw new Error(`Failed to read or parse OpenAPI specification at ${specPath}: ${error}`);
}
}
function createWeatherTool(spec: unknown): OpenApiToolboxTool {
const connectionId = process.env.OPENAPI_CONNECTION_ID;
if (!connectionId) {
throw new Error("Set OPENAPI_CONNECTION_ID before running.");
}
const auth: OpenApiProjectConnectionAuthDetails = {
type: "project_connection",
security_scheme: {
project_connection_id: connectionId,
},
};
const definition: OpenApiFunctionDefinition = {
name: "get_weather",
description: "Retrieve weather information for a location using wttr.in",
spec,
auth,
};
return {
type: "openapi",
openapi: definition,
};
}
export async function main(): Promise<void> {
const weatherSpec = loadOpenApiSpec(weatherSpecPath);
// Create clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
const weatherTool = createWeatherTool(weatherSpec);
console.log("Creating a toolbox with the OpenAPI weather tool...");
// 1. Add the OpenAPI 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(
"openapi-toolbox",
[weatherTool],
{ description: "Toolbox with the OpenAPI weather 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 openapi-toolbox-conn \
// --kind remote-tool \
// --target "<toolboxMcpUrl>" \
// --auth-type user-entra-token \
// --audience https://ai.azure.com
const toolboxConnectionId = process.env.TOOLBOX_CONNECTION_ID;
if (!toolboxConnectionId) {
throw new Error("Set TOOLBOX_CONNECTION_ID to the toolbox connection ID.");
}
// 4. Attach the toolbox to a prompt agent as an MCP tool.
const agent = await project.agents.createVersion("MyOpenApiAgent", {
kind: "prompt",
model: deploymentName,
instructions:
"You are a helpful assistant that can call external APIs defined by OpenAPI specs to answer user questions.",
tools: [
{
type: "mcp",
server_label: "toolbox",
server_url: toolboxMcpUrl,
require_approval: "never",
project_connection_id: toolboxConnectionId,
headers: {
"Foundry-Features": "Toolboxes=V1Preview",
},
},
],
});
// Send a request and stream the response
const streamResponse = await openai.responses.create(
{
input:
"What's the weather in Seattle and how should I plan my outfit for the day based on the forecast?",
stream: true,
},
{
body: {
agent_reference: { name: agent.name, type: "agent_reference" },
tool_choice: "required",
},
},
);
// Process the streaming response
for await (const event of streamResponse) {
if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
} else if (event.type === "response.output_text.done") {
console.log("\n");
}
}
// Clean up resources
await project.agents.deleteVersion(agent.name, agent.version);
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
process.exitCode = 1;
});
此代码的作用
此 TypeScript 示例使用 OpenAPI 工具通过匿名身份验证创建一个代理,用于天气数据。 运行代码时:
- 它从本地 JSON 文件加载天气 OpenAPI 规范。
- 创建包含天气工具的工具箱版本。
- 将工具箱作为 MCP 工具附加到智能体中,然后发送流式请求,询问西雅图的天气情况和装备规划。
- 处理流式响应,并在增量到达时显示增量。
- 它强制使用
tool_choice: "required"工具,以确保调用 API。 - 删除智能体以进行清理。
所需的输入
- 环境变量:
FOUNDRY_PROJECT_ENDPOINT、FOUNDRY_MODEL_DEPLOYMENT_NAME、OPENAPI_CONNECTION_ID和TOOLBOX_CONNECTION_ID。 - 本地文件:
assets/weather_openapi.json(OpenAPI 规范)。
预期输出
Creating a toolbox with the OpenAPI weather tool...
The weather in Seattle is <conditions>. Consider wearing <suggestion>.
常见错误
-
Error: OpenAPI specification not found:文件路径不正确或文件缺失 -
AuthenticationError:Azure凭据无效 -
API 密钥不起作用:如果从匿名切换到 API 密钥身份验证,请确保 OpenAPI 规范已
securitySchemessecurity正确配置
创建使用通过项目连接进行身份验证的 OpenAPI 工具的代理
以下 TypeScript 代码示例演示如何创建使用通过项目连接进行身份验证的 OpenAPI 工具的 AI 代理。 代理从本地资产加载 TripAdvisor OpenAPI 规范,并通过配置的项目连接调用 API。 有关此示例的 JavaScript 版本,请参阅 GitHub 上的 javaScript 存储库Azure SDK中的 sample。
import { DefaultAzureCredential } from "@azure/identity";
import {
AIProjectClient,
OpenApiTool,
OpenApiFunctionDefinition,
OpenApiProjectConnectionAuthDetails,
} from "@azure/ai-projects";
import * as fs from "fs";
import * as path from "path";
function requiredEnv(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Set ${name} before running.`);
}
return value;
}
const PROJECT_ENDPOINT = requiredEnv("FOUNDRY_PROJECT_ENDPOINT");
const deploymentName = requiredEnv("FOUNDRY_MODEL_DEPLOYMENT_NAME");
const connectionId = requiredEnv("OPENAPI_CONNECTION_ID");
const tripAdvisorSpecPath = path.resolve("assets", "tripadvisor_openapi.json");
function loadOpenApiSpec(specPath: string): unknown {
if (!fs.existsSync(specPath)) {
throw new Error(`OpenAPI specification not found at: ${specPath}`);
}
try {
const data = fs.readFileSync(specPath, "utf-8");
return JSON.parse(data);
} catch (error) {
throw new Error(`Failed to read or parse OpenAPI specification at ${specPath}: ${error}`);
}
}
function createTripAdvisorTool(spec: unknown): OpenApiTool {
const auth: OpenApiProjectConnectionAuthDetails = {
type: "project_connection",
security_scheme: {
project_connection_id: connectionId,
},
};
const definition: OpenApiFunctionDefinition = {
name: "get_tripadvisor_location_details",
description:
"Fetch TripAdvisor location details, reviews, or photos using the Content API via project connection auth.",
spec,
auth,
};
return {
type: "openapi",
openapi: definition,
};
}
export async function main(): Promise<void> {
const tripAdvisorSpec = loadOpenApiSpec(tripAdvisorSpecPath);
// Create clients to call Foundry API
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
// Create an agent with the OpenAPI project-connection tool
const agent = await project.agents.createVersion("MyOpenApiConnectionAgent", {
kind: "prompt",
model: deploymentName,
instructions:
"You are a travel assistant that consults the TripAdvisor Content API via project connection to answer user questions about locations.",
tools: [createTripAdvisorTool(tripAdvisorSpec)],
});
// Send a request and stream the response
const streamResponse = await openai.responses.create(
{
input:
"Provide a quick overview of the TripAdvisor location 293919 including its name, rating, and review count.",
stream: true,
},
{
body: {
agent_reference: { name: agent.name, type: "agent_reference" },
tool_choice: "required",
},
},
);
// Process the streaming response
for await (const event of streamResponse) {
if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
} else if (event.type === "response.output_text.done") {
console.log("\n");
}
}
// Clean up resources
await project.agents.deleteVersion(agent.name, agent.version);
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
process.exitCode = 1;
});
此代码的作用
此 TypeScript 示例演示如何通过项目连接通过 API 密钥身份验证使用 OpenAPI 工具。 运行代码时:
- 它从本地文件加载 TripAdvisor OpenAPI 规范。
- 它使用
引用 API 密钥连接。 - 它使用 TripAdvisor 工具创建一个代理,该工具使用项目连接进行 API 密钥身份验证。
- 它会发送获取TripAdvisor位置详细信息的流式请求。
- 它强制使用
tool_choice: "required"工具,以确保调用 API。 - 它处理并显示流式响应。
- 通过删除智能体进行清理。
所需的输入
- 环境变量:
FOUNDRY_PROJECT_ENDPOINT、FOUNDRY_MODEL_DEPLOYMENT_NAME和OPENAPI_CONNECTION_ID。 - 本地文件:
../assets/tripadvisor_openapi.json - 使用 TripAdvisor API 密钥配置的项目连接
预期输出
Location 293919: <name>, rating: <rating>, review count: <count>.
常见错误
-
Error: OpenAPI specification not found:检查文件路径。 - 找不到连接:验证
OPENAPI_CONNECTION_ID是否为 API 密钥连接的完整资源 ID。 -
AuthenticationException:项目连接中的 API 密钥无效。 -
API 密钥未注入到请求中:您的 OpenAPI 规范必须在
security下包含适当的securitySchemes和components部分。 中的securitySchemes密钥名称必须与项目连接中的密钥匹配。 -
Content type is not supported:目前,仅支持这两种请求正文内容类型:application/json和application/json-patch+json。 响应内容类型不受限制。
安全性和数据注意事项
将代理连接到 OpenAPI 工具时,代理可以将派生自用户输入的请求参数发送到目标 API。
- 使用项目连接来管理机密(API 密钥和令牌)。 避免将机密放入 OpenAPI 规范文件或源代码中。
- 在生产环境中使用该工具之前,请查看 API 接收的数据及其返回的数据。
- 使用最小权限进行访问。 仅为项目的托管标识分配目标服务所需的角色。
在添加 OpenAPI 工具之前,请查看 OpenAPI 规范,包括 API、操作和参数说明及其公开的操作。 此信息可能包含在发送到模型的上下文中,并影响代理选择工具和构造请求的方式。
将提供程序提供的说明视为不受信任的输入。 仅连接到受信任的 API 提供程序、查看规范更改,以及独立于模型生成的决策强制实施权限和审批要求。
使用 API 密钥进行身份验证
将此变体用于需要标头或查询参数中的密钥的 API。 每个 OpenAPI 工具只能使用一个 API 密钥安全方案。 如果 API 需要多个安全方案,请创建多个 OpenAPI 工具。
更新 OpenAPI 规范安全架构。 它包含一个
securitySchemes部分和一个apiKey类型的方案。 例如:"securitySchemes": { "apiKeyHeader": { "type": "apiKey", "name": "x-api-key", "in": "header" } }通常只需更新
name字段,该字段与连接中的名称key相对应。 如果安全方案包含多个方案,则只保留其中一个方案。更新 OpenAPI 规范以包括一个
security部分:"security": [ { "apiKeyHeader": [] } ]删除 OpenAPI 规范中需要 API 密钥的任何参数,因为 API 密钥是通过连接存储和传递的,如本文稍后所述。
创建用于存储 API 密钥的连接。
转到 Foundry 门户 并打开您的项目。
创建或选择存储机密的连接。 请参阅 向项目添加新连接。
注意
如果稍后重新生成 API 密钥,则需要使用新密钥更新连接。
输入以下信息
键:安全架构的
name字段。 在此示例中,它应为x-api-key"securitySchemes": { "apiKeyHeader": { "type": "apiKey", "name": "x-api-key", "in": "header" } }值:YOUR_API_KEY
创建连接后,可以通过 SDK 或 REST API 使用它。 使用本文顶部的选项卡查看代码示例。
设置持有者令牌连接
对于要求在 Authorization 标头中提供持有者令牌的 API,请使用此变体。 它使用与 API 密钥身份验证相同的 project_connection 身份验证类型,但 OpenAPI 安全方案和连接值有所不同。
OpenAPI 规格如下所示:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
您需要:
更新您的 OpenAPI 规范
securitySchemes,以使用Authorization作为标头名称。"securitySchemes": { "bearerAuth": { "type": "apiKey", "name": "Authorization", "in": "header" } }添加引用方案的
security部分:"security": [ { "bearerAuth": [] } ]在 Foundry 项目中创建自定义 密钥 连接:
- 转到 Foundry 门户 并打开您的项目。
- 创建或选择存储机密的连接。 请参阅 向项目添加新连接。
- 输入以下值:
-
键:
Authorization(必须与您的name中的securitySchemes字段匹配) -
值:
Bearer <token>(将<token>替换为您的实际令牌)
-
键:
重要
该值必须包括单词
Bearer,并在该单词后跟一个空格,然后是标记。 例如:Bearer eyJhbGciOiJSUzI1NiIs.... 如果省略Bearer前缀和以下空间,API 将接收没有所需授权方案前缀的原始令牌,并且请求失败。
- 创建连接后,请将其与
project_connection代码中的身份验证类型一起使用,就像进行 API 密钥身份验证一样。 连接 ID 使用相同的格式:/subscriptions/{{subscriptionID}}/resourceGroups/{{resourceGroupName}}/providers/Microsoft.CognitiveServices/accounts/{{foundryAccountName}}/projects/{{foundryProjectName}}/connections/{{foundryConnectionName}}。
使用托管标识进行身份验证(Microsoft Entra ID)
Microsoft Entra ID是基于云的标识和访问管理服务,员工可以使用该服务访问外部资源。 通过使用 Microsoft Entra ID,可以向 API 添加额外的安全性,而无需使用 API 密钥。 设置托管身份验证时,代理会通过其使用的 Foundry 工具进行身份验证。
重要
只有当目标服务接受 Microsoft Entra ID 令牌时,托管身份验证才有效。 如果目标 API 使用不支持Microsoft Entra ID的自定义身份验证方案,请改用 API 密钥或 Bearer 令牌身份验证。
托管标识支持
对于托管标识身份验证,工具箱中的 OpenAPI 工具使用 Foundry 项目的托管标识,而不是帐户的标识。 此要求适用于所有订阅。
对于直接附加到提示智能体的 OpenAPI 工具,新订阅 OpenAPI 工具必须使用项目托管标识。 现有订阅只能在 2027 年 1 月 8 日之前使用旧帐户托管标识。
| OpenAPI 工具路径 | Subscription | 支持的托管标识 |
|---|---|---|
| 通过工具箱附加的工具。 | 所有订阅。 | 仅限 Foundry 项目托管标识。 在 2027 年 1 月 8 日之前,将旧内联身份验证迁移到 OpenAPI 项目连接。 |
| 直接附加到提示智能体的工具。 | 新订阅 OpenAPI 工具。 | 通过 OpenAPI 项目连接的 Foundry 项目托管标识 |
| 直接附加到提示智能体的工具。 | 已使用 OpenAPI 工具的现有订阅。 | 帐户托管身份是 2027 年 1 月 8 日之前的旧选项。 通过 OpenAPI 项目连接迁移到项目托管标识。 |
为项目的托管标识分配最低特权角色,该角色允许对目标服务执行所需的 API 操作。
从 2027 年 1 月 8 日起,托管标识身份验证需要具有 authType: "ProjectManagedIdentity" 的 OpenAPI 项目连接。 将工具的 auth.type 设置为 project_connection,并在 auth.security_scheme.project_connection_id 中传递连接的完整 ARM 资源 ID。 在连接中配置目标 API 的受众,而不是在工具定义中内联配置。
确定需要迁移的配置
检查直接附加到提示代理的 OpenAPI 工具以及代理使用的工具箱版本。 具有 auth.type: "managed_identity" 和使用 auth.security_scheme.audience 旧内联身份验证方案的工具,需要在 2027 年 1 月 8 日之前进行迁移。
同一内联方案在两个路径上使用不同的标识:
- 对于直接附加到提示代理的工具,它使用帐户管理的标识。 迁移标识和身份验证配置。
- 对于工具箱中的工具,它已使用项目托管标识。 保留该标识及其权限,但将身份验证配置迁移到 OpenAPI 项目连接。
已在使用配置了auth.type: "project_connection"的 OpenAPI 连接的authType: "ProjectManagedIdentity"工具不需要此次迁移。 OpenAPI 工具和项目托管标识身份验证仍受支持。
对于这两个路径,请更新受影响的配置以及创建它们的任何代码或部署模板。 从 2027 年 1 月 8 日开始,仍使用旧方案的调用无法进行身份验证,依赖于这些调用的代理步骤将失败。
从帐户迁移到项目托管标识
这些步骤适用于直接附加到使用旧帐户托管标识的提示代理的 OpenAPI 工具。 在 2027 年 1 月 8 日之前完成迁移。 对于工具箱工具,请改为遵循 从内联托管标识迁移工具箱工具 。
- 根据需要启用 Foundry 项目的托管标识,并在目标服务上为其分配最低特权角色。 帐户的托管标识角色分配不适用于项目的标识。
-
创建 OpenAPI 项目连接,并提供
authType: "ProjectManagedIdentity"、目标终结点,以及目标 API 所预期的受众。 - 将该工具的直接
managed_identity受众配置替换为auth.type: "project_connection"。 传入auth.security_scheme.project_connection_id连接的完整 ARM 资源 ID。 - 调用该工具以验证项目的托管标识是否可以访问目标 API。
- 仅在确认不需要其他工作负荷后,才删除帐户标识的目标服务角色分配。
从内联托管标识迁移工具箱工具
这些步骤适用于使用 auth.type: "managed_identity"工具箱中的 OpenAPI 工具。 在 2027 年 1 月 8 日之前完成迁移。 保留现有项目托管标识及其目标服务权限;此迁移更改身份验证配置,而不是标识。
-
在同一个项目中创建一个 OpenAPI 项目连接,并使用
authType: "ProjectManagedIdentity"。 使用现有的目标终结点和受众。 -
创建工具箱的一个新版本,保留其其他工具和设置。 对于每个受影响的 OpenAPI 工具,请将
auth.type: "managed_identity"替换为auth.type: "project_connection"。 将auth.security_scheme.audience替换为auth.security_scheme.project_connection_id,并将其设置为连接的完整 ARM 资源 ID。 - 通过 特定于版本的工具箱终结点测试受影响的 API 调用。
- 将迁移后的版本设为默认版本,供使用未版本化工具箱终结点的使用者使用。 更新使用较旧版本特定的终结点的任何使用者以使用迁移的版本。
工具箱版本是不可变的。 创建新版本不会自动更改默认版本。 有关详细信息,请参阅“管理工具箱版本”。
了解受众 URI
audience(有时称为资源标识符或应用程序ID URI)用于告知 Microsoft Entra ID 该令牌是要访问哪个服务或 API。 受众值必须与目标服务预期的值匹配,否则身份验证失败并出现 401 错误。
注意
受众不是 Foundry 项目终结点。 它是 OpenAPI 工具调用的目标服务的资源标识符。
下表列出了常见Azure服务的受众 URI:
| 目标服务 | 受众 URI |
|---|---|
| Azure 存储 | https://storage.azure.com |
| Azure 密钥保管库 | https://vault.azure.net |
| Foundry IQ(Azure AI 搜索) | https://search.azure.com |
| Azure 翻译器 | https://cognitiveservices.azure.com |
| Azure 逻辑应用 | 为工作流的Microsoft Entra ID授权配置的受众。 请参阅 对逻辑应用/Logic Apps 的安全访问。 |
| Azure API 管理(管理平面) | https://management.azure.com |
| 受Microsoft Entra应用注册保护的 API(包括使用 OAuth 的 APIM) | 应用注册中的 应用程序 ID URI (例如 api://<client-id>) |
提示
如果使用Azure API 管理通过 OAuth 2.0 验证策略保护自定义 API,则受众是保护 API 的应用注册中的 Application ID URI,而不是https://management.azure.com。 管理平面受众仅适用于 APIM 资源本身上的 Azure 资源管理器操作。
有关如何使用 Microsoft Entra ID 进行身份验证的详细信息,请参阅 Agent 标识和身份验证。
查找并验证受众
使用以下步骤确定并验证正确的受众值:
- 对于Azure服务:检查服务的文档,了解其Microsoft Entra ID资源标识符。 大多数Azure服务在其身份验证文档中列出访问群体 URI。
- 对于受Microsoft Entra应用注册保护的 API:在 Azure 门户中,转到Microsoft Entra ID>应用注册>选择应用>公开 API。 页面顶部的应用程序 ID URI是您的受众值。
-
若要验证令牌的受众:在 https://jwt.ms 对访问令牌进行解码,并检查
aud声明。 该值aud必须与目标服务期望的受众匹配。
设置托管身份认证
若要设置项目托管标识身份验证,请执行以下操作:
- 将 Foundry 项目的托管标识用于新配置。 确保已启用项目的托管标识。 在 2027 年 1 月 8 日之前迁移旧的内联托管标识配置。
- 创建或标识 OpenAPI 工具调用的目标服务。
- 在目标资源上分配对 Foundry 项目的托管标识所需的访问权限。
- 创建 Project 托管标识连接,并在工具定义中传递其完整资源 ID。
创建项目托管标识连接
在发送 Responses 请求的同一 Foundry 项目中创建该连接。 连接存储目标终结点和受众,而不是 API 密钥或访问令牌。
以下 Bash 示例使用 Azure CLI 和 curl 为 Foundry Tools 中的Azure 翻译器创建 OpenAPI 连接。 首先 az login 登录。 将占位符替换为你的订阅、资源组、Foundry 帐户、项目和 Translator 资源。
SUB="<subscription-id>"
RESOURCE_GROUP="<resource-group>"
ACCOUNT="<foundry-account-name>"
PROJECT_NAME="<foundry-project-name>"
CONNECTION_NAME="translator-project-mi"
TRANSLATOR_ENDPOINT="https://<translator-resource>.cognitiveservices.azure.com"
PROJECT="/subscriptions/$SUB/resourceGroups/$RESOURCE_GROUP"
PROJECT="$PROJECT/providers/Microsoft.CognitiveServices"
PROJECT="$PROJECT/accounts/$ACCOUNT/projects/$PROJECT_NAME"
export OPENAPI_CONNECTION_ID="$PROJECT/connections/$CONNECTION_NAME"
ARM_TOKEN="$(az account get-access-token \
--subscription "$SUB" \
--resource https://management.azure.com \
--query accessToken -o tsv)"
curl --fail-with-body --request PUT \
--url "https://management.azure.com$OPENAPI_CONNECTION_ID?api-version=2025-06-01" \
--header "Authorization: Bearer $ARM_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"properties": {
"category": "OpenAPI",
"authType": "ProjectManagedIdentity",
"target": "'"$TRANSLATOR_ENDPOINT"'/",
"audience": "https://cognitiveservices.azure.com",
"metadata": {
"type": "openapi"
}
}
}'
参考:Foundry 项目连接资源模式。
为语言示例保留 OPENAPI_CONNECTION_ID。 使用完整的连接资源 ID,而不仅仅是连接名称。 受众应在连接中指定;不要传递帐户托管标识受众来代替连接 ID。
使用项目托管标识调用 OpenAPI 工具
这些示例通过你创建的连接调用 Azure 翻译器。 它们在 remote_tool 有效负载中将内联 OpenAPI 规范发送到响应终结点。
在运行示例之前:
- 为项目的托管标识分配翻译所需的目标服务角色。
- 按照创建项目托管标识连接中所述,使用
authType: "ProjectManagedIdentity"创建 OpenAPI 连接。 - 设置
FOUNDRY_PROJECT_ENDPOINT、FOUNDRY_MODEL_DEPLOYMENT_NAME和OPENAPI_CONNECTION_ID。 连接必须属于此项目。 - 将以下规范保存为
translator_openapi.json,放在运行示例的目录中。 将<translator-resource>替换为该连接的target中使用的资源。
{
"openapi": "3.0.1",
"info": {
"title": "Azure Translator Service",
"version": "1.0.0"
},
"servers": [
{
"url": "https://<translator-resource>.cognitiveservices.azure.com/translator/text/v3.0/"
}
],
"paths": {
"/translate": {
"post": {
"operationId": "Translator_Translate",
"description": "Translate text into one or more languages.",
"parameters": [
{
"name": "api-version",
"in": "query",
"required": true,
"schema": { "type": "string", "default": "3.0" }
},
{
"name": "to",
"in": "query",
"required": true,
"schema": { "type": "string" }
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"text": { "type": "string" }
},
"required": ["text"]
}
}
}
}
},
"responses": {
"200": {
"description": "Translation response.",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"translations": {
"type": "array",
"items": {
"type": "object",
"properties": {
"text": { "type": "string" },
"to": { "type": "string" }
}
}
}
}
}
}
}
}
}
}
}
}
}
}
参考:翻译器翻译操作。
调用方使用Azure标识凭据向 Foundry 进行身份验证。 Foundry 从项目连接解析对 Translator 的身份验证,并使用项目的托管标识。
使用 pip install openai azure-identity 安装依赖项。
import json
import os
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import OpenAI
def main() -> None:
with open("translator_openapi.json", encoding="utf-8") as spec_file:
spec = json.load(spec_file)
tool = {
"type": "remote_tool",
"tool_arguments": [
{
"name": "openapi",
"arguments": {
"name": "language",
"description": "Azure Translator API for text translation.",
"default_params": ["api-version"],
"auth": {
"type": "project_connection",
"security_scheme": {
"project_connection_id": os.environ[
"OPENAPI_CONNECTION_ID"
],
},
},
"spec": spec,
},
}
],
}
with DefaultAzureCredential() as credential:
token_provider = get_bearer_token_provider(
credential, "https://ai.azure.com/.default"
)
with OpenAI(
base_url=(
os.environ["FOUNDRY_PROJECT_ENDPOINT"].rstrip("/")
+ "/openai/v1/"
),
api_key=token_provider,
) as client:
response = client.responses.create(
model=os.environ["FOUNDRY_MODEL_DEPLOYMENT_NAME"],
input="Translate 'Hello, how are you?' to Spanish.",
extra_body={
"tools": [tool],
"tool_choice": "required",
},
)
print(response.output_text)
if __name__ == "__main__":
main()
参考:Azure标识令牌提供程序。
extra_body 参数传递特定于服务的 remote_tool 有效负载,而无需在 OpenAI SDK 中使用类型化的 OpenAPI 工具模型。
使用 .NET 8 或更高版本,并使用 dotnet add package Azure.Identity 安装凭据库。 此示例使用 HttpClient.. 发送特定于服务的工具有效负载。
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using Azure.Core;
using Azure.Identity;
static string RequiredEnvironmentVariable(string name) =>
Environment.GetEnvironmentVariable(name)
?? throw new InvalidOperationException($"Set {name} before running.");
string endpoint = RequiredEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT");
string model = RequiredEnvironmentVariable("FOUNDRY_MODEL_DEPLOYMENT_NAME");
string connectionId = RequiredEnvironmentVariable("OPENAPI_CONNECTION_ID");
JsonElement spec = JsonSerializer.Deserialize<JsonElement>(
File.ReadAllText("translator_openapi.json"));
var tool = new
{
type = "remote_tool",
tool_arguments = new[]
{
new
{
name = "openapi",
arguments = new
{
name = "language",
description = "Azure Translator API for text translation.",
default_params = new[] { "api-version" },
auth = new
{
type = "project_connection",
security_scheme = new
{
project_connection_id = connectionId
}
},
spec
}
}
}
};
var credential = new DefaultAzureCredential();
AccessToken token = await credential.GetTokenAsync(
new TokenRequestContext(new[] { "https://ai.azure.com/.default" }));
using var client = new HttpClient();
using var request = new HttpRequestMessage(
HttpMethod.Post, $"{endpoint.TrimEnd('/')}/openai/v1/responses");
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token.Token);
request.Content = JsonContent.Create(new
{
model,
input = "Translate 'Hello, how are you?' to Spanish.",
tools = new[] { tool },
tool_choice = "required"
});
using HttpResponseMessage response = await client.SendAsync(request);
string responseBody = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException(
$"HTTP {(int)response.StatusCode}: {responseBody}");
}
Console.WriteLine(responseBody);
使用 Node.js 20 或更高版本,并使用 npm install @azure/identity 安装凭据库。 将此 JavaScript 示例保存为 openapi-project-mi.mjs.
import { readFile } from "node:fs/promises";
import { DefaultAzureCredential } from "@azure/identity";
function requiredEnvironmentVariable(name) {
const value = process.env[name];
if (!value) {
throw new Error(`Set ${name} before running.`);
}
return value;
}
const endpoint = requiredEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT");
const model = requiredEnvironmentVariable("FOUNDRY_MODEL_DEPLOYMENT_NAME");
const connectionId = requiredEnvironmentVariable("OPENAPI_CONNECTION_ID");
const spec = JSON.parse(
await readFile("translator_openapi.json", "utf8"),
);
const tool = {
type: "remote_tool",
tool_arguments: [
{
name: "openapi",
arguments: {
name: "language",
description: "Azure Translator API for text translation.",
default_params: ["api-version"],
auth: {
type: "project_connection",
security_scheme: {
project_connection_id: connectionId,
},
},
spec,
},
},
],
};
const credential = new DefaultAzureCredential();
const token = await credential.getToken("https://ai.azure.com/.default");
const response = await fetch(
`${endpoint.replace(/\/$/, "")}/openai/v1/responses`,
{
method: "POST",
headers: {
Authorization: `Bearer ${token.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model,
input: "Translate 'Hello, how are you?' to Spanish.",
tools: [tool],
tool_choice: "required",
}),
},
);
const responseBody = await response.text();
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${responseBody}`);
}
console.log(responseBody);
使用 Java 11 或更高版本。 将 com.azure:azure-identity 和 com.fasterxml.jackson.core:jackson-databind 添加到 Maven 依赖项中。 此示例使用 Java 的 HTTP 客户端发送特定于服务的工具有效负载。
import com.azure.core.credential.AccessToken;
import com.azure.core.credential.TokenRequestContext;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class OpenApiProjectMi {
private static String requiredEnvironmentVariable(String name) {
String value = System.getenv(name);
if (value == null || value.isBlank()) {
throw new IllegalStateException("Set " + name + " before running.");
}
return value;
}
public static void main(String[] args) throws Exception {
String endpoint = requiredEnvironmentVariable(
"FOUNDRY_PROJECT_ENDPOINT");
String model = requiredEnvironmentVariable(
"FOUNDRY_MODEL_DEPLOYMENT_NAME");
String connectionId = requiredEnvironmentVariable(
"OPENAPI_CONNECTION_ID");
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> spec = mapper.readValue(
new File("translator_openapi.json"),
new TypeReference<Map<String, Object>>() { });
Map<String, Object> tool = Map.of(
"type", "remote_tool",
"tool_arguments", List.of(Map.of(
"name", "openapi",
"arguments", Map.of(
"name", "language",
"description",
"Azure Translator API for text translation.",
"default_params", List.of("api-version"),
"auth", Map.of(
"type", "project_connection",
"security_scheme", Map.of(
"project_connection_id", connectionId)),
"spec", spec))));
Map<String, Object> body = Map.of(
"model", model,
"input", "Translate 'Hello, how are you?' to Spanish.",
"tools", List.of(tool),
"tool_choice", "required");
var credential = new DefaultAzureCredentialBuilder().build();
AccessToken token = Objects.requireNonNull(credential.getToken(
new TokenRequestContext()
.addScopes("https://ai.azure.com/.default")).block());
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(endpoint.replaceAll("/$", "")
+ "/openai/v1/responses"))
.header("Authorization", "Bearer " + token.getToken())
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
mapper.writeValueAsString(body)))
.build();
HttpResponse<String> response = HttpClient.newHttpClient().send(
request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new IllegalStateException(
"HTTP " + response.statusCode() + ": " + response.body());
}
System.out.println(response.body());
}
}
使用 Bash、Azure CLI、curl 和 jq 从 translator_openapi.json 构建请求。 调用方令牌面向 Foundry,而不是Azure 资源管理器或 Translator。
AGENT_TOKEN="$(az account get-access-token \
--resource https://ai.azure.com \
--query accessToken -o tsv)"
jq -n \
--arg model "$FOUNDRY_MODEL_DEPLOYMENT_NAME" \
--arg connection_id "$OPENAPI_CONNECTION_ID" \
--slurpfile spec translator_openapi.json \
'{
model: $model,
input: "Translate '\''Hello, how are you?'\'' to Spanish.",
tools: [
{
type: "remote_tool",
tool_arguments: [
{
name: "openapi",
arguments: {
name: "language",
description: "Azure Translator API for text translation.",
default_params: ["api-version"],
auth: {
type: "project_connection",
security_scheme: {
project_connection_id: $connection_id
}
},
spec: $spec[0]
}
}
]
}
],
tool_choice: "required"
}' > openapi-project-mi-request.json
curl --fail-with-body --request POST \
--url "${FOUNDRY_PROJECT_ENDPOINT%/}/openai/v1/responses" \
--header "Authorization: Bearer $AGENT_TOKEN" \
--header "Content-Type: application/json" \
--data @openapi-project-mi-request.json
参考:Azure CLI访问令牌。
响应包含西班牙语翻译“你好,你怎么样?” Python示例打印响应的文本。 HTTP 示例打印完整的 JSON 响应,包括工具输出和助理消息。
排查常见错误
| 症状 | 可能的原因 | 分辨率 |
|---|---|---|
| API 密钥不包括在请求中。 | OpenAPI 规范缺少 securitySchemes 或 security 部分。 |
请确保您的 OpenAPI 规范既包括 components.securitySchemes 又包括顶级 security 部分。 确保方案 name 与项目连接中的密钥名称匹配。 |
| 代理不调用 OpenAPI 工具。 | 工具选择未设置或operationId不具有描述性。 |
使用 tool_choice="required" 强制工具调用。 确保 operationId 值具有描述性,以便模型可以选择正确的操作。 |
| 项目托管标识身份验证失败。 | 项目托管标识未启用,或者缺少其角色分配。 | 验证 Foundry 项目的托管标识已启用,并且具有针对 OpenAPI 规范中操作的、目标服务的最低特权数据平面或应用程序角色。 |
| 未使用项目托管标识。 | 工具使用直接 managed_identity 受众配置而不是项目连接。 |
使用 authType: "ProjectManagedIdentity" 创建 OpenAPI 连接。 将工具的 auth.type 设置为 project_connection,并将 auth.security_scheme.project_connection_id 设置为完整连接资源 ID。 |
| 即使分配了角色,项目托管标识仍返回 401。 | 连接的受众 URI 与目标服务预期的 URI 不匹配。 | 根据目标服务的文档验证连接中的 ProjectManagedIdentity 受众 URI。 对于受Microsoft Entra ID保护的 API,请使用应用注册中的应用程序 ID URI。 请参阅 “了解受众 URI”。 |
| 项目托管标识词元被目标 API 拒绝。 | 目标服务不接受Microsoft Entra ID令牌。 | 确认目标服务支持Microsoft Entra ID身份验证。 如果不行,请使用目标服务支持的 API 密钥或其他身份验证方法。 |
| 请求失败,出现 400 错误请求。 | OpenAPI 规范与实际 API 不匹配。 | 根据实际 API 对照验证您的 OpenAPI 规范。 检查参数名称、类型和必填字段。 |
| 请求失败,出现 401 未授权。 | API 密钥或令牌无效或已过期。 | 重新生成 API 密钥/令牌并更新项目连接。 验证连接 ID 是否正确。 |
| 工具返回意外的响应格式。 | 未在 OpenAPI 规范中定义的响应架构。 | 将响应架构添加到 OpenAPI 规范,以便更好地了解模型。 |
operationId 验证错误。 |
中的 operationId字符无效。 |
在 - 值中仅使用字母、_ 和 operationId。 删除数字和特殊字符。 |
| 未找到连接错误。 | 连接资源 ID 不正确或属于另一个项目。 | 验证 OPENAPI_CONNECTION_ID 是否为 Foundry 项目中发送请求的连接的完整 ARM 资源 ID。 |
| 持有者令牌未正确发送。 | 连接值缺少 Bearer 前缀和以下空格。 |
将连接值设置为 Bearer <token> (使用标记前的单词 Bearer 和空格)。 验证 OpenAPI 规范 securitySchemes 是否使用 "name": "Authorization"。 |
选择身份验证方法
下表帮助你为 OpenAPI 工具选择正确的身份验证方法:
| 身份验证方法 | 最适合 | 配置复杂性 |
|---|---|---|
| 匿名 | 没有身份验证的公共 API。 需要与 authType: "None"OpenAPI 项目建立连接。 |
低 |
| API 密钥 | 具有基于密钥的访问的非Microsoft API | 中等 |
| 托管标识(项目托管标识) | Azure 服务和 Microsoft Entra ID 保护的 API。 需要 ProjectManagedIdentity 连接,以及分配给项目托管标识的所需目标服务角色。 |
中高 |