利用 OpenAPI 3.0 和 3.1 規範,將您的 Microsoft Foundry 代理程式連接到外部 API。 驅動代理的 Foundry 模型能呼叫外部服務、即時資料擷取,並將功能擴展至內建功能之外。
OpenAPI 規範 定義了描述 HTTP API 的標準方式,讓您能將現有服務與代理程式整合。 使用匿名、API 金鑰或專案受控識別驗證。 如需協助選擇認證方法,請參閱 選擇認證方法。
先決條件
開始前,請確保你具備:
一個擁有正確權限的 Azure 訂閱。
Foundry 專案的 Foundry 使用者角色,可建立並執行 Agent。
重要
Foundry RBAC 角色最近已重新命名。 Foundry 用戶、Foundry 擁有者、Foundry Account Owner 以及 Foundry Project Manager 先前分別被稱為 Azure AI 使用者、Azure AI 擁有者、Azure AI 帳戶擁有者及 Azure AI Project 管理者。 在更名期間,你可能還會在某些地方看到之前的名字。角色 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/json,application/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 端點之個別連線的完整資源識別碼。 |
註
FOUNDRY_PROJECT_ENDPOINT 值指的是你的 Microsoft Foundry 專案端點,而非外部 OpenAPI 服務端點。 您可以在 Microsoft Foundry 入口網站的專案概覽頁面中找到此端點。 這個端點是驗證代理服務所必需的,並且與你規格檔案中定義的任何 OpenAPI 端點是分開的。
使用支援
下表顯示 SDK 與設定支援。
| Microsoft Foundry 支援 | Python SDK | C# SDK | JavaScript SDK | Java 開發套件 | REST API | 基本代理設定 | 標準代理設定 |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
註
本文中的 Java 範例使用 Java 的 HTTP 用戶端與 Azure Identity,傳送與其他語言相同的回應負載。 它不需要具類型的 OpenAPI 工具模型。
執行匿名首次成功流程
先從匿名天氣 API 開始,驗證你的代理程式是否能載入 OpenAPI 規範並呼叫操作。 建立一個 OpenAPI 專案連線,即使是為了匿名驗證,並將完整資源識別碼傳遞給工具。 匿名認證不需要外部 API 憑證。 請參見 建立匿名 OpenAPI 連線。
- 從 Prerequisites 安裝你選擇語言的 SDK 套件。
- 下載
weather_openapi.json,並儲存到assets取樣路徑。 - 設定你的 Foundry 專案端點並建模部署值。
- 為 建立一個匿名的 OpenAPI 連線
https://wttr.in,並設定OPENAPI_CONNECTION_ID為其完整的資源 ID。 - 請在你選擇的語言區塊中執行匿名樣本。
- 確認回應中包含西雅圖的最新天氣,然後刪除樣本所建立的代理版本。
匿名呼叫成功後,設定目標 API 所需的認證。 將 API 金鑰認證、Bearer 權杖驗證與 專案受管理識別驗證 視為獨立變體。
了解限制
- OpenAPI 工具不支援 OAuth 身份直通(
OAuth2連線),包括你將它們加入工具箱時。 使用匿名、基於金鑰或專案受控識別驗證。 OAuth 對 MCP 工具的支援不適用於同一工具箱中的 OpenAPI 工具。 - 你的 OpenAPI 規範必須在每個操作中包含
operationId,而operationId只能包含字母、-和_。 - 支援的請求內容類型:
application/json,application/json-patch+json。 - API 金鑰認證時,每個 OpenAPI 工具使用一種 API 金鑰安全方案。 如果你需要多種安全方案,就建立多個 OpenAPI 工具。
- 在懷疑暴露後,定期且立即輪換 API 金鑰與持有憑證。 當憑證變更時更新專案連線;不要把憑證放在 OpenAPI 規範或原始碼裡。
在 Foundry 入口網站設定 OpenAPI 認證
當你透過 Tools>Custom>OpenAPI 新增 OpenAPI 工具時,請為該工具建立專案連線。 匿名、API 金鑰與管理式身份驗證都需要連線,無論你是透過入口網站、SDK 或 REST API 設定工具。
入口網站的 受控識別 選項使用 Foundry 專案的受控識別,而非 Foundry 帳號的受控識別。 工具箱中的 OpenAPI 工具始終需要專案受控識別,無論訂用帳戶歷史如何。 帳戶受控識別僅支援直接連接到現有訂用帳戶中提示字元 Agent 的 OpenAPI 工具。 盡快將這些設定遷移到專案受控識別。 請參閱受控識別支援。
匿名驗證代表目標 API 不需要認證。 這不代表你可以跳過建立連結。
| Authentication | 連線設定 |
|---|---|
| 匿名 | 建立一個無認證的 OpenAPI 專案連線(authType: "None")。 不需要 API 金鑰或令牌。 |
| API 金鑰 | 建立一個專案連線來儲存 API 金鑰。 將金鑰名稱與 OpenAPI 安全方案中的標頭或查詢參數相匹配。 請參考 「使用 API 金鑰認證」。 |
| 受控識別 (專案受控識別) | 建立一個具有authType: "ProjectManagedIdentity"的 OpenAPI 專案連線、目標 API 端點及該 API 預期的對象。 在目標服務上將專案的受控識別指派為必要角色。 此選項不會使用帳戶的受控識別。 |
設定匿名驗證
- 在您的 Foundry 專案中開啟 工具>自訂>OpenAPI 。
- 在 「建立 OpenAPI 工具」中,輸入工具名稱與描述。
- 將驗證方法設為匿名。
- 在連線底下,選取一個現有的匿名連線,或選取建立新連線以建立一個連線。
- 輸入 OpenAPI 3.0+ 架構,選擇 建立工具。
即使選擇匿名,連線欄位仍是必填。
設定管理身份驗證
受控識別選項需要專案的受控識別。 帳戶管理身份的現有角色指派不會授予專案管理身份的存取權限。
- 在建立 OpenAPI 工具中,將驗證方法設為受控識別。
- 在 「連線」中,選擇一個現有的專案受控識別連線,或選擇 建立新連線。
- 在 建立 OpenAPI 連線中,輸入 連線名稱,並將 認證類型 設為 受控識別。
- 輸入 API 的 目標網址 以及 API 預期的 受眾 。 受眾不是你的 Foundry 專案端點。
- 選擇「建立連線」,然後在工具的「連線」欄位中選擇該連線。
- 輸入工具 名稱、描述和 OpenAPI 3.0+ 架構,然後選擇 「建立工具」。
在呼叫工具前,先在目標服務上為專案的受控識別指派所需的角色。
關於透過 REST 設定專案受控識別連線,請參見 「建立專案受控識別連線」。 當你在程式碼中使用該連線時,請連同 auth.type: "project_connection" 一起傳遞其完整的資源 ID。
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 進行驗證。
對於受控識別驗證,工具箱需要 專案受控識別。 工具箱不支援帳戶受控識別,現有訂用帳戶也不支援。
以下片段顯示工具配置,並非完整程式。 用你的 OpenAPI 規格替換每個空 spec 物件。 工具箱建立時,請使用以下章節的完整語言範例。
重要
使用受管身分驗證時,將允許在目標服務上執行所需 API 作業的最低權限 RBAC 角色指派給 Foundry 專案的受管理身分。 例如,只有當 API 需要唯讀 Azure Resource Manager 存取時,才在目標 Azure 資源上指派 Reader。 若沒有所需的指派,代理在呼叫 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 管理身份驗證:
建立一個 OpenAPI 專案連線authType: "ProjectManagedIdentity",並以 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 Developer 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 請參見 Toolbox 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 資源識別碼。 - 下載維護的
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 規格檔必須包含:
-
securitySchemes區塊中包含您的 API 金鑰設定,例如標頭名稱和參數名稱。 - 一個
security提及安全方案的章節。 - 一個以匹配金鑰名稱和值配置的專案連線。
沒有這些設定,API 金鑰就不會包含在請求中。 如需詳細設定說明,請參閱 「使用 API 金鑰認證 」章節。
你也可以使用基於憑證的認證(例如持有憑證),將憑證儲存在專案連線中。 對於持有人令牌授權,建立一個 自訂金鑰 連線,將金鑰設為 , Authorization 值設為 Bearer <token> (替換 <token> 成你的真實令牌)。
Bearer 及後面的空格必須被包含在值中。 詳情請參見 設置持有人令牌連線。
使用 OpenAPI 工具使用代理程式的範例
此範例示範如何透過代理使用 OpenAPI規範 所描述的服務。 它使用 wttr.in 服務來取得天氣及其規格檔 weather_openapi.json。 選擇 Prompt Agents 以使用 Azure AI Projects SDK 建立伺服器端提示代理,或選擇 Hosted Agents 使用 Microsoft 代理框架建立一個短暫且進行中的代理。
提示詞 Agent
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 weather API。 該工具直接連接到代理定義。 當你執行程式碼時:
- 它會從本地的 JSON 檔案載入 weather OpenAPI 規範。
- 建立一個提示代理,並設定天氣工具以支援匿名存取。
- 傳送詢問西雅圖天氣的查詢。
- 代理程式使用 OpenAPI 工具呼叫天氣 API,並回傳格式化的結果。
- 透過刪除代理程式版本來清理。
託管代理
此範例使用 FoundryChatClient Microsoft 代理框架,並透過 FoundryToolbox連接工具箱 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 代理程式,請使用 .()AzureAIProjectToolbox連接至相同的工具箱端點。 請參閱〈 在託管代理程式中使用工具箱 〉以及〈 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 建立伺服器端提示代理,或選擇 Hosted Agents 使用 Microsoft 代理框架建立一個短暫且進行中的代理。
提示詞 Agent
此範例使用了 Azure AI Projects 客戶端函式庫的同步方法。 關於使用非同步方法的範例,請參見 Azure SDK for .NET 儲存庫中的sample,GitHub上。
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:在資產資料夾中找不到 OpenAPI 規格檔 -
UnauthorizedAccessException:無效憑證或 RBAC 權限不足 -
API 金鑰未注入:請確認您的 OpenAPI 規格在
components中包含securitySchemes與security區段,且兩者使用相符的方案名稱
託管代理
本範例使用 Azure AI Projects SDK 建立 OpenAPI 工具箱,並使用 Microsoft Agent Framework AddFoundryToolboxes 整合。 除了先決條件中的 C# 相依性之外,還要將 ASP.NET Core 專案和Azure.AI.AgentServer.Responses及Microsoft.Agents.AI.Foundry.Hosting搭配使用。 設定 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。
在網路服務上使用 OpenAPI 工具的代理程式範例,需驗證
在這個範例中,您將一個已驗證的 OpenAPI 工具直接連接到提示 Agent。 你會使用 TripAdvisor 規範和一個儲存在專案連線中的 API 金鑰。
TripAdvisor 服務需要 API 金鑰認證。 依照 Authenticate with API key 所描述建立專案連線,並設定 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# 範例使用 OpenAPI 工具,透過專案連線進行 API 金鑰驗證。 當你執行程式碼時:
- 它會從本地檔案載入 TripAdvisor OpenAPI 規範。
- 它會引用包含你的 API 金鑰的 TripAdvisor 專案連線。
- 它會將 TripAdvisor 工具連接到 Agent,並設定成使用連線進行驗證。
- 傳送建議巴黎飯店的要求。
- 代理會用你儲存的 API 金鑰呼叫 TripAdvisor API,並回傳結果。
- 透過刪除代理程式來進行清除。
所需輸入
- 環境變數:
FOUNDRY_PROJECT_ENDPOINT、FOUNDRY_MODEL_DEPLOYMENT_NAME和OPENAPI_CONNECTION_ID。 - 本地檔案:
Assets/tripadvisor_openapi.json - 專案連線:
tripadvisor,已配置有效的 API 金鑰
預期產出
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的專案連線。 -
AuthenticationException:Project 連線中的 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" }
}
}
}
}
}
}
}
]
}'
工具箱在 處暴露一個與 MCP 相容的端點 $FOUNDRY_PROJECT_ENDPOINT/toolboxes/openapi-toolbox/versions/<version>/mcp?api-version=v1,其中 <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,而不是匿名天氣連線。
這個 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
對於持有憑證 API,請保持相同的 project_connection 請求形狀,但使用如 「設定承載憑證連線」中所述的連線配置。 連線值必須以 Bearer 開頭,後面接一個空格。
管理式身份驗證
對於專案受控識別,請先 建立一個 OpenAPI 專案連線。 然後在回應請求中傳遞完整的資源 ID。 請參閱 使用專案受控識別呼叫 OpenAPI 工具中的 REST 範例。
帳戶受控識別僅支援直接連接到現有訂用帳戶中提示字元 Agent 的 OpenAPI 工具。 工具箱裡不支援這功能。 提示 Agent 也可以使用專案受控識別。 請儘快遷移現有設定。
這套程式碼的作用
這個 REST API 範例展示了如何呼叫一個帶有不同認證方法的 OpenAPI 工具。 請求內容:
- 為了匿名認證,建立包含 OpenAPI 工具定義與天氣 API 規範的工具箱。
- 建立一個回應,將工具箱附加為 MCP 工具,並詢問西雅圖的天氣狀況。
- 顯示透過專案連線進行 API 金鑰驗證的額外 REST 工具定義。
- 代理程式呼叫工具設定所選的 API,並回傳結果。
所需輸入
- 環境變數:
FOUNDRY_PROJECT_ENDPOINT,AGENT_TOKEN,FOUNDRY_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區段是否正確設定(非空),且與您的 Project 連線金鑰名稱相符
建立具備 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 檔案載入 weather 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 範例展示了使用 OpenAPI 工具,透過專案連線進行 API 金鑰認證。 當你執行程式碼時:
- 它會從本地檔案載入 TripAdvisor OpenAPI 規範。
- 它透過使用
OPENAPI_CONNECTION_ID來參照 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:Project 連線中的 API 金鑰無效。 -
API 金鑰未注入請求:您的 OpenAPI 規格必須包含適當的
securitySchemes(在components下)及security章節。 關鍵字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 使用它。 請使用本文頂端的分頁查看程式碼範例。
建立持有人代幣連線
若 API 預期在Authorization標頭中使用持有人權杖,請使用此變體。 它使用與 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 會收到未附帶所需授權方案前綴的原始權杖字串,且請求會失敗。
- 建立連線後,在程式碼中用 auth 類型使用
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 專案的受控識別。 此要求適用於所有訂閱。
對於直接連接到提示 Agent 的 OpenAPI 工具,新使用 OpenAPI 工具的訂用帳戶必須使用專案受控識別。 現有訂閱支援該路徑上的兩種身分識別,但建議使用專案受控身分識別。 盡快移轉現有帳戶受控識別設定。
| OpenAPI 工具路徑 | 訂用帳戶 | 支援的受控識別 |
|---|---|---|
| 透過工具箱連接的工具。 | 所有訂閱。 | 因為工具箱已引入,因此僅限於 Foundry 專案受控識別。 不支援帳戶受控識別。 |
| 直接連接到提示 Agent 的工具。 | 新使用 OpenAPI 工具的訂用帳戶。 | 僅限 Foundry 專案受控識別。 不支援帳戶受控識別。 |
| 直接連接到提示 Agent 的工具。 | 已有訂閱且已使用 OpenAPI 工具。 | Foundry 帳戶受控識別與 Foundry 專案受控識別。 建議使用專案受控識別;請盡快從帳戶受控識別移轉。 |
將允許對目標服務執行所需 API 作業的最低權限角色指派給專案的受控識別。
這兩種身分識別使用不同的驗證組態:
-
專案受控識別需要在 Foundry 專案中具有
authType: "ProjectManagedIdentity"的 OpenAPI 連線。 傳入該連線的完整 ARM 資源 IDauth.security_scheme.project_connection_id,搭配auth.type: "project_connection"。 -
帳戶管理身分識別僅支援用於直接附加至現有訂閱中提示代理程式的工具,使用
auth.type: "managed_identity",並直接將目標服務的audience傳遞至工具定義中。 這個設定在工具箱中不受支援,無法選取專案的受控識別,也不是入口網站的 受控識別 選項。
從帳戶移轉到專案受控識別
這些遷移步驟適用於直接附加於現有訂閱中的提示代理的 OpenAPI 工具。 工具箱已經要求專案受控識別。 對於新設定使用專案受控識別,並盡快移轉現有提示 Agent 帳戶受控識別設定:
- 將目標服務中所需的最低權限角色指派給 Foundry 專案的受控識別。 帳戶受控識別角色指派不適用於專案身分識別。
-
建立一個 OpenAPI 專案連線 ,包含
authType: "ProjectManagedIdentity"、目標端點及目標 API 預期的受眾。 - 將工具的直接
managed_identity受眾配置替換為auth.type: "project_connection"。 將連線的完整 ARM 資源 ID 傳入auth.security_scheme.project_connection_id。 - 呼叫該工具以驗證專案的受控識別是否能存取目標 API。
- 只有在確認沒有其他工作負載需要該角色指派後,才移除帳號身分的目標服務角色指派。
了解受眾 URI
audience(有時稱為 resource identifier 或 Application ID URI)告訴Microsoft Entra ID該令牌預期存取哪項服務或 API。 受眾值必須符合目標服務的期望,否則認證將因 401 錯誤而失敗。
註
不是 你的 Foundry 專案的目標受眾。 它是你的 OpenAPI 工具呼叫的目標服務的資源識別碼。
下表列出常見 Azure 服務的受眾 URI:
| 目標服務 | 受眾 URI |
|---|---|
| Azure 儲存體 | https://storage.azure.com |
| Azure Key Vault | https://vault.azure.net |
| Foundry IQ(Azure AI 搜尋服務) | https://search.azure.com |
| Azure 翻譯器 | https://cognitiveservices.azure.com |
| Azure Logic Apps | 為工作流程的 Microsoft Entra ID 授權所設定的受眾 請參見 對邏輯應用程式的安全存取。 |
| Azure API 管理 (管理平台) | https://management.azure.com |
| API 由 Microsoft Entra 應用程式註冊保護(包含帶有 OAuth 的 APIM) | 應用程式註冊時的 應用程式 ID URI (例如, api://<client-id>) |
提示
如果你用 Azure API 管理 保護一個自訂 API 並採用 OAuth 2.0 驗證政策,受眾是應用程式註冊後保護該 API 的 Application ID URI,而非 https://management.azure.com。 管理平面受眾只適用於 APIM 資源本身的 Azure Resource Manager 作業。
欲了解更多關於代理如何以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 專案的受控識別來建立新設定。 確保專案的受控識別已啟用。 帳戶受控識別僅為舊版選項,適用於直接連接到現有訂用帳戶中提示 Agent 的工具;請盡快移轉那些設定。
- 建立或識別你的 OpenAPI 工具所呼叫的目標服務。
- 將目標資源上的所需存取權限指派給 Foundry 專案的受控識別。
- 建立 Project 受控識別連線,並在工具定義中傳遞其完整資源 ID。
建立專案受控識別連線
在發送回應請求的同一個 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,而不只是連線名稱。 對象應包含在連線中;不要傳遞帳戶受控識別對象來取代連線識別碼。
使用專案受控識別呼叫 OpenAPI 工具
這些範例透過你建立的連線呼叫 Azure 翻譯工具。 他們會以內嵌的 remote_tool 有效載荷形式將 OpenAPI 規格傳送給 Responses 端點。
在執行樣本前:
- 將專案的受控識別指派為轉譯所需的目標服務角色。
- 依照
authType: "ProjectManagedIdentity"中的說明,使用 建立 OpenAPI 連線。 - 設定
FOUNDRY_PROJECT_ENDPOINT、FOUNDRY_MODEL_DEPLOYMENT_NAME、OPENAPI_CONNECTION_ID和 。 這個連線必須屬於這個計畫。 - 在您執行樣本的目錄中。將以下規格儲存為
translator_openapi.json。 將連線的target中所使用的資源取代為<translator-resource>。
{
"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 Identity 認證向 Foundry 驗證身分。 Foundry 從專案連線中解析對翻譯工具的驗證,並使用專案的受控識別。
用 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 Identity token provider.
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);
參考資料:DefaultAzureCredential, HttpClient。
使用 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);
參考資料: DefaultAzureCredential。
請使用 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 Resource Manager 或 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
Reference: Azure CLI access tokens.
回覆包含「Hello, how are you?」的西班牙語翻譯。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 與目標服務的預期不符。 | 請驗證ProjectManagedIdentity連線中的對象 URI 與目標服務的文件。 對於受 Microsoft Entra ID 保護的 API,請使用你的應用程式註冊中的應用程式 ID URI。 請參閱了解受眾的 URI。 |
| 專案受控識別權杖遭目標 API 拒絕。 | Target 服務不接受 Microsoft Entra ID 令牌。 | 確認目標服務是否支援 Microsoft Entra ID 認證。 如果沒有,就使用 API 金鑰或其他目標服務支援的認證方法。 |
| 請求失敗,且有 400 個錯誤請求。 | OpenAPI 規格和實際 API 不符。 | 將你的 OpenAPI 規範與實際 API 進行驗證比對。 檢查參數名稱、類型及所需欄位。 |
| 申請失敗,顯示 401 未授權。 | API 金鑰或權杖無效或過期。 | 重新產生 API 金鑰/權杖並更新你的專案連線。 確認連線ID是否正確。 |
| 工具回傳意外的回應格式。 | 回應架構未在 OpenAPI 規範中定義。 | 在你的 OpenAPI 規範中加入回應架構,以更好理解模型。 |
operationId 驗證錯誤。 |
operationId中有無效字元。 |
僅使用字母、- 和 _ 在 operationId 值中。 去除數字和特殊字元。 |
| 找不到連線錯誤。 | 連線資源識別碼錯誤或屬於另一個專案。 | 確認 OPENAPI_CONNECTION_ID 是 Foundry 專案中發送請求之連線的完整 ARM 資源 ID。 |
| 未正確傳送 Bearer 權杖。 | 連線值缺少 Bearer 前綴和後方空格。 |
將連線值設為 Bearer <token> (字詞 Bearer 和標記前加空格)。 請確認 OpenAPI 規範 securitySchemes 是否使用 "name": "Authorization"。 |
選擇一種認證方法
下表協助你選擇適合 OpenAPI 工具的認證方法:
| 認證方法 | 適用對象 | 設置複雜度 |
|---|---|---|
| 匿名 | 沒有驗證的公開 API。 需要與 authType: "None" 的 OpenAPI 專案建立連線。 |
低 |
| API 金鑰 | 非 Microsoft API 的基於金鑰存取 | 中 |
| 受控識別 (專案受控識別) | Azure 服務及受 Microsoft Entra ID 保護的 API。 需要ProjectManagedIdentity連線,並將所需的目標服務角色指派給專案的受控識別。 |
Medium-High |