管理 Foundry 托管智能体
说明如何查看 Foundry 托管智能体、创建版本、用 FixedRatio 固定生产流量、禁用终结点、流式查看日志,并为实例身份分配 RBAC 角色。

目录
#管理 Foundry 托管智能体
本文说明如何管理 Foundry 智能体服务(Foundry Agent Service)中的托管智能体(Hosted agents)。在部署托管智能体之后,可以查看其状态、创建新版本、选择智能体终结点所服务的版本、监视日志,以及在不再需要时删除智能体。
平台会自动管理容器生命周期。请求到达时供应计算资源,并在配置的空闲超时后解除供应。创建智能体版本时,可将超时设为 2 到 60 分钟。默认值为 15 分钟。这种自动计算伸缩与智能体的终结点状态相互独立。不必手动启动或停止计算资源,但可以禁用智能体的终结点,使其下线,之后再重新启用。
如果使用 GitHub Copilot 这类编码智能体,Microsoft Foundry Skill 可以帮助你在项目上下文中管理版本、终结点、日志和生命周期操作。
先决条件
- 一个已部署的托管智能体。
- Azure CLI 2.80 或更高版本,并已通过
az login完成身份验证。
- Python SDK:
azure-ai-projects>=2.3.0和azure-identity。
- .NET SDK:
Azure.AI.Projects.Agents(预发布)和Azure.Identity。使用dotnet add package Azure.AI.Projects.Agents --prerelease安装。
- JavaScript/TypeScript SDK:
@azure/ai-projects和@azure/identity(npm install @azure/ai-projects @azure/identity)。
- Azure Developer CLI 1.23.0 或更高版本。
- Foundry agents 扩展:
Bash
azd ext install azure.ai.agents设置变量
本文中的 REST API 示例使用 az rest 直接调用 Foundry 智能体服务终结点。运行命令前先设置以下变量:
Bash
ACCOUNT_NAME="<your-foundry-account-name>"
PROJECT_NAME="<your-project-name>"
AGENT_NAME="<your-agent-name>"
BASE_URL="https://${ACCOUNT_NAME}.services.ai.azure.com/api/projects/${PROJECT_NAME}"
API_VERSION="v1"
RESOURCE="https://ai.azure.com"重要
对 Foundry 智能体服务数据平面终结点的所有 az rest 调用都需要 --resource 参数。没有该参数时,az rest 无法从 URL 推导出正确的 Azure AD 受众,身份验证会失败。
查看智能体和版本
使用以下命令列出智能体并检查版本详细信息。
列出项目中的全部智能体
Bash
az rest --method GET \
--url "${BASE_URL}/agents?api-version=${API_VERSION}" \
--resource "${RESOURCE}"Python
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
project_client = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
for agent in project_client.agents.list():
print(agent.name)C#
using System;
using Azure.AI.Projects.Agents;
using Azure.Identity;
var projectEndpoint = "https://{account}.services.ai.azure.com/api/projects/{project}";
AgentAdministrationClient agentsClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
foreach (ProjectsAgentRecord agent in agentsClient.GetAgents())
{
Console.WriteLine(agent.Name);
}TypeScript
import { AIProjectClient } from "@azure/ai-projects";
import { DefaultAzureCredential } from "@azure/identity";
const project = new AIProjectClient(
PROJECT_ENDPOINT,
new DefaultAzureCredential(),
);
for await (const agent of project.agents.list()) {
console.log(agent.name);
}Bash
azd ai agent show注意
azd ai agent show 从项目配置中的 azd 服务条目读取智能体名称和版本。
获取智能体详细信息
Bash
az rest --method GET \
--url "${BASE_URL}/agents/${AGENT_NAME}?api-version=${API_VERSION}" \
--resource "${RESOURCE}"响应包含智能体的最新版本、状态和定义。
Python
agent = project_client.agents.get(agent_name="my-agent")
print(f"Name: {agent.name}")
print(f"Status: {agent.versions['latest']['status']}")C#
ProjectsAgentRecord agent = agentsClient.GetAgent("my-agent");
Console.WriteLine($"Name: {agent.Name}");
Console.WriteLine($"State: {agent.State}");TypeScript
const agent = await project.agents.get("my-agent");
console.log(`Name: ${agent.name}`);
console.log(`Status: ${agent.versions.latest.status}`);Bash
azd ai agent show获取特定版本
Bash
az rest --method GET \
--url "${BASE_URL}/agents/${AGENT_NAME}/versions/1?api-version=${API_VERSION}" \
--resource "${RESOURCE}"Python
agent_version = project_client.agents.get_version(
agent_name="my-agent", agent_version="1"
)
print(f"Version: {agent_version.version}")
print(f"Status: {agent_version['status']}")C#
ProjectsAgentVersion agentVersion = agentsClient.GetAgentVersion(
agentName: "my-agent", agentVersion: "1");
Console.WriteLine($"Version: {agentVersion.Version}");
Console.WriteLine($"Status: {agentVersion.Status}");TypeScript
const agentVersion = await project.agents.getVersion("my-agent", "1");
console.log(`Version: ${agentVersion.version}`);
console.log(`Status: ${agentVersion.status}`);版本信息包含在 azd ai agent show 的输出中。
列出智能体的全部版本
Bash
az rest --method GET \
--url "${BASE_URL}/agents/${AGENT_NAME}/versions?api-version=${API_VERSION}" \
--resource "${RESOURCE}"默认情况下,列表会排除草稿版本(预览)。要包含这些版本,请添加查询参数 include_drafts=true:
Bash
az rest --method GET \
--url "${BASE_URL}/agents/${AGENT_NAME}/versions?api-version=${API_VERSION}&include_drafts=true" \
--resource "${RESOURCE}"Python
for version in project_client.agents.list_versions(agent_name="my-agent"):
print(f"Version: {version.version}, Status: {version['status']}")C#
foreach (ProjectsAgentVersion version in agentsClient.GetAgentVersions("my-agent"))
{
Console.WriteLine($"Version: {version.Version}, Status: {version.Status}");
}TypeScript
for await (const version of project.agents.listVersions("my-agent")) {
console.log(`Version: ${version.version}, Status: ${version.status}`);
}版本信息包含在 azd ai agent show 的输出中。
创建新版本
需要更新容器映像、更改资源分配或修改环境变量时,创建新的智能体版本。
Bash
az rest --method POST \
--url "${BASE_URL}/agents/${AGENT_NAME}/versions?api-version=${API_VERSION}" \
--resource "${RESOURCE}" \
--body '{
"definition": {
"kind": "hosted",
"container_configuration": {
"image": "myregistry.azurecr.io/my-agent:v2"
},
"cpu": "1",
"memory": "2Gi",
"protocol_versions": [\
{"protocol": "responses", "version": "2.0.0"}\
]
}
}'如果智能体使用 Invocations 协议,把 responses 替换为 invocations;或者同时包含两者,以公开两种协议。协议选择的详细说明见部署托管智能体。
Python
from azure.ai.projects.models import ContainerConfiguration, HostedAgentDefinition, ProtocolVersionRecord
agent = project_client.agents.create_version(
agent_name="my-agent",
definition=HostedAgentDefinition(
cpu="1",
memory="2Gi",
container_configuration=ContainerConfiguration(
image="myregistry.azurecr.io/my-agent:v2"
),
protocol_versions=[\
ProtocolVersionRecord(protocol="responses", version="2.0.0"),\
],
),
)
print(f"Created version: {agent.version}")如果智能体使用 Invocations 协议,把 responses 替换为 invocations;或者同时传入两者,以公开两种协议。
C#
var definition = new HostedAgentDefinition(
versions: new[] { new ProtocolVersionRecord(ProjectsAgentProtocol.Responses, "2.0.0") },
cpu: "1",
memory: "2Gi")
{
ContainerConfiguration = new ContainerConfiguration("myregistry.azurecr.io/my-agent:v2"),
};
ProjectsAgentVersion created = agentsClient.CreateAgentVersion(
agentName: "my-agent",
options: new ProjectsAgentVersionCreationOptions(definition));
Console.WriteLine($"Created version: {created.Version}");如果智能体使用 Invocations 协议,把 ProjectsAgentProtocol.Responses 替换为 ProjectsAgentProtocol.Invocations;或者同时传入两者,以公开两种协议。
TypeScript
const agent = await project.agents.createVersion("my-agent", {
kind: "hosted",
cpu: "1",
memory: "2Gi",
container_configuration: {
image: "myregistry.azurecr.io/my-agent:v2",
},
protocol_versions: [{ protocol: "responses", version: "2.0.0" }],
});
console.log(`Created version: ${agent.version}`);如果智能体使用 Invocations 协议,把 responses 替换为 invocations;或者同时传入两者,以公开两种协议。
运行 azd deploy 且代码或配置已更新时,会自动创建新版本。
创建草稿版本(预览)
注意
草稿版本处于预览阶段。预览功能不提供服务级别协议,不建议用于生产工作负载。行为可能变化。必须为订阅启用草稿创建;在启用之前,将 draft 设为 true 的请求会改为创建普通发布版本。
_草稿版本(draft version)_ 是可以创建和测试的实验版本,不影响智能体如何服务生产流量。草稿让你可以在把更改提升为常规发布版本之前,反复调整新映像、资源分配或配置。
草稿版本与常规发布版本的差别如下:
- 独立的版本标识符:草稿会被分配
draft-{timestamp}版本字符串(例如draft-1719600000000),而不是自增整数,因此不会推进发布版本编号。 - 排除在默认列表之外:除非传入
include_drafts=true,否则列出版本时不会出现草稿。 - 排除在隐式路由之外:草稿永远不会被解析为智能体的最新版本,因此不会自动接收流量。
- 不能作为流量路由目标:不能把流量路由规则固定到草稿版本。把流量路由到草稿的请求会被拒绝。
要创建草稿版本,在请求正文中把 draft 设为 true:
Bash
az rest --method POST \
--url "${BASE_URL}/agents/${AGENT_NAME}/versions?api-version=${API_VERSION}" \
--resource "${RESOURCE}" \
--body '{
"draft": true,
"definition": {
"kind": "hosted",
"container_configuration": {
"image": "myregistry.azurecr.io/my-agent:experimental"
},
"cpu": "1",
"memory": "2Gi",
"protocol_versions": [\
{"protocol": "responses", "version": "2.0.0"}\
]
}
}'响应的 version 字段包含所分配的 draft-{timestamp} 标识符。使用该标识符来获取或删除草稿,或直接测试它。对更改满意后,用相同映像和配置再创建一个新版本,但省略 draft(或设为 false),即可将其提升。新版本会获得常规的自增版本号,并可以参与流量路由。
Python
from azure.ai.projects.models import (
ContainerConfiguration,
HostedAgentDefinition,
ProtocolVersionRecord,
)
draft = project_client.agents.create_version(
agent_name="my-agent",
definition=HostedAgentDefinition(
cpu="1",
memory="2Gi",
container_configuration=ContainerConfiguration(
image="myregistry.azurecr.io/my-agent:experimental"
),
protocol_versions=[\
ProtocolVersionRecord(protocol="responses", version="2.0.0"),\
],
),
draft=True,
)
print(f"Created draft version: {draft.version}")C#
var definition = new HostedAgentDefinition(
versions: new[] { new ProtocolVersionRecord(ProjectsAgentProtocol.Responses, "2.0.0") },
cpu: "1",
memory: "2Gi")
{
ContainerConfiguration = new ContainerConfiguration("myregistry.azurecr.io/my-agent:experimental"),
};
ProjectsAgentVersion draft = agentsClient.CreateAgentVersion(
agentName: "my-agent",
options: new ProjectsAgentVersionCreationOptions(definition) { Draft = true });
Console.WriteLine($"Created draft version: {draft.Version}");草稿版本目前仅可通过 REST API 和 Python SDK 使用。请切换到 REST API 选项卡查看示例。
草稿版本目前仅可通过 REST API 使用。请切换到 REST 选项卡查看示例。
版本状态值
创建或更新智能体版本后,轮询版本终结点,直到状态变为 active:
| 状态 | 说明 |
|---|---|
creating | 正在供应基础设施(通常为 2–5 分钟)。 |
active | 智能体已可服务请求。 |
failed | 供应失败。查看响应中的 error 字段了解详情。 |
deleting | 正在清理该版本。 |
deleted | 版本已被完全移除。 |
创建后轮询版本状态:
Python
import time
def wait_for_version_active(project_client, agent_name, agent_version, max_attempts=60):
for attempt in range(max_attempts):
time.sleep(10)
version = project_client.agents.get_version(
agent_name=agent_name, agent_version=agent_version
)
status = version["status"]
print(f"Version status: {status} (attempt {attempt + 1})")
if status == "active":
return
if status == "failed":
raise RuntimeError(f"Version provisioning failed: {dict(version)}")
raise RuntimeError("Timed out waiting for version to become active")创建后轮询版本状态:
C#
using System.Threading;
static void WaitForVersionActive(
AgentAdministrationClient agentsClient, string agentName, string agentVersion, int maxAttempts = 60)
{
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
Thread.Sleep(TimeSpan.FromSeconds(10));
ProjectsAgentVersion version = agentsClient.GetAgentVersion(agentName, agentVersion);
Console.WriteLine($"Version status: {version.Status} (attempt {attempt + 1})");
if (version.Status == AgentVersionStatus.Active)
return;
if (version.Status == AgentVersionStatus.Failed)
throw new InvalidOperationException($"Version provisioning failed: {version.Status}");
}
throw new InvalidOperationException("Timed out waiting for version to become active");
}创建后轮询版本状态:
TypeScript
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function waitForVersionActive(
project: AIProjectClient,
agentName: string,
agentVersion: string,
maxAttempts = 60,
) {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
await sleep(10_000);
const version = await project.agents.getVersion(
agentName,
agentVersion,
);
console.log(`Version status: ${version.status} (attempt ${attempt + 1})`);
if (version.status === "active") {
return;
}
if (version.status === "failed") {
throw new Error(`Version provisioning failed: ${JSON.stringify(version)}`);
}
}
throw new Error("Timed out waiting for version to become active");
}禁用或启用智能体
禁用智能体可使其终结点下线,而不删除智能体或其任何版本。禁用期间,智能体会拒绝请求,但其配置和版本保持不变。准备好继续服务请求时,再启用该智能体。禁用是可逆的,因此它是暂时停用智能体的首选方式。
禁用智能体
Bash
az rest --method POST \
--url "${BASE_URL}/agents/${AGENT_NAME}:disable?api-version=${API_VERSION}" \
--resource "${RESOURCE}"Python
project_client.agents.disable(agent_name="my-agent")
print("Disabled agent: my-agent")C#
agentsClient.DisableAgent("my-agent");
Console.WriteLine("Disabled agent: my-agent");尚不能通过 JavaScript/TypeScript SDK 使用。请使用 REST API。
不支持作为独立命令。请使用 REST API。
启用智能体
Bash
az rest --method POST \
--url "${BASE_URL}/agents/${AGENT_NAME}:enable?api-version=${API_VERSION}" \
--resource "${RESOURCE}"Python
project_client.agents.enable(agent_name="my-agent")
print("Enabled agent: my-agent")C#
agentsClient.EnableAgent("my-agent");
Console.WriteLine("Enabled agent: my-agent");尚不能通过 JavaScript/TypeScript SDK 使用。请使用 REST API。
不支持作为独立命令。请使用 REST API。
删除智能体
可以删除特定版本,也可以删除整个智能体及其全部版本。
删除特定版本
Bash
az rest --method DELETE \
--url "${BASE_URL}/agents/${AGENT_NAME}/versions/1?api-version=${API_VERSION}" \
--resource "${RESOURCE}"Python
project_client.agents.delete_version(agent_name="my-agent", agent_version="1")C#
agentsClient.DeleteAgentVersion(agentName: "my-agent", agentVersion: "1");TypeScript
await project.agents.deleteVersion("my-agent", "1");目前不支持作为独立命令。请使用 REST API 或 SDK。
删除智能体及全部版本
警告
此操作会永久删除该智能体及其全部版本。活动会话会被终止。此操作无法撤销。
Bash
az rest --method DELETE \
--url "${BASE_URL}/agents/${AGENT_NAME}?api-version=${API_VERSION}" \
--resource "${RESOURCE}"Python
project_client.agents.delete(agent_name="my-agent")C#
agentsClient.DeleteAgent(agentName: "my-agent");TypeScript
await project.agents.delete("my-agent");目前不支持作为独立命令。请使用 REST API 或 SDK。
查看日志并监视
访问容器日志,以便调试供应和运行时问题。
从特定智能体会话流式传输日志:
Bash
AGENT_VERSION="<version>"
SESSION_ID="<session-id>"
az rest --method GET \
--url "${BASE_URL}/agents/${AGENT_NAME}/versions/${AGENT_VERSION}/sessions/${SESSION_ID}:logstream?api-version=${API_VERSION}" \
--resource "${RESOURCE}" \
--headers "Accept=text/event-stream"logstream 终结点返回带有 event: log 帧的服务器发送事件(Server-Sent Events,SSE)。每个帧包含一个 JSON 负载,其中有 timestamp、stream(stdout、stderr 或 status)和 message 字段。
超时:
- 最大连接时长:30 分钟
- 空闲超时:2 分钟
从特定智能体会话流式传输日志:
Python
def iter_sse_frames(stream):
buffer = ""
for chunk in stream:
buffer += chunk.decode("utf-8", errors="replace")
while "\n\n" in buffer:
frame, buffer = buffer.split("\n\n", 1)
event_name = None
data_lines = []
for line in frame.splitlines():
if line.startswith("event: "):
event_name = line[7:]
elif line.startswith("data: "):
data_lines.append(line[6:])
if event_name or data_lines:
yield event_name, "\n".join(data_lines)
raw_stream = project_client.agents.get_session_log_stream(
agent_name="my-agent",
agent_version="1",
session_id="<session-id>",
)
for event_name, data in iter_sse_frames(raw_stream):
print(f"SSE event: {event_name}\nSSE data: {data}\n")以服务器发送事件形式流式传输会话日志可通过 REST API 使用。请切换到 REST 选项卡查看示例。
从特定智能体会话流式传输日志:
TypeScript
async function* iterSseFrames(stream: NodeJS.ReadableStream) {
let buffer = "";
for await (const chunk of stream) {
buffer += chunk.toString("utf-8");
while (buffer.includes("\n\n")) {
const idx = buffer.indexOf("\n\n");
const frame = buffer.slice(0, idx);
buffer = buffer.slice(idx + 2);
let eventName;
const dataLines: string[] = [];
for (const line of frame.split("\n")) {
if (line.startsWith("event: ")) {
eventName = line.slice(7);
} else if (line.startsWith("data: ")) {
dataLines.push(line.slice(6));
}
}
if (dataLines.length > 0 || eventName) {
yield { event: eventName, data: dataLines.join("\n") };
}
}
}
}
const logStream = await project.agents.getSessionLogStream(
"my-agent",
"1",
"<session-id>",
);
if (logStream.readableStreamBody) {
for await (const frame of iterSseFrames(logStream.readableStreamBody)) {
console.log(`SSE event: ${frame.event}`);
console.log(`SSE data: ${frame.data}\n`);
}
}用实时状态和日志信息监视正在运行的智能体:
Bash
azd ai agent monitor此命令从项目配置中的 azd 服务条目读取智能体名称和版本。
日志输出示例
text
2026-04-09T08:43:48.72656 Connecting to the container 'agent-container'...
2026-04-09T08:43:48.75451 Successfully connected to container: 'agent-container'
2026-04-09T08:43:59.0671054Z stdout F INFO: 127.0.0.1:42588 - "GET /readiness HTTP/1.1" 200 OK配置智能体终结点路由
智能体终结点将其 100% 的流量路由到一个智能体版本。使用版本选择器选择终结点所服务的版本。
重要
不支持在智能体版本之间拆分流量。即使 version_selection_rules 是数组,也只配置一条 traffic_percentage 设为 100 的 FixedRatio 规则。
终结点路由通过修补智能体对象来配置。使用 PATCH /agents/{agent_name},并将 Content-Type 设为 application/merge-patch+json:
Bash
az rest --method PATCH \
--url "${BASE_URL}/agents/${AGENT_NAME}?api-version=${API_VERSION}" \
--resource "${RESOURCE}" \
--headers "Content-Type=application/merge-patch+json" \
--body '{
"agent_endpoint": {
"version_selector": {
"version_selection_rules": [\
{"agent_version": "1", "traffic_percentage": 100, "type": "FixedRatio"}\
]
},
"protocol_configuration": {
"responses": {}
}
}
}'将 protocol_configuration 设为 {"invocations": {}} 或 {"responses": {}, "invocations": {}},以匹配智能体所公开的协议。
Python
from azure.ai.projects.models import (
AgentEndpointConfig,
FixedRatioVersionSelectionRule,
ProtocolConfiguration,
ResponsesProtocolConfiguration,
VersionSelector,
)
endpoint_config = AgentEndpointConfig(
version_selector=VersionSelector(
version_selection_rules=[\
FixedRatioVersionSelectionRule(\
agent_version="1", traffic_percentage=100\
),\
]
),
protocol_configuration=ProtocolConfiguration(
responses=ResponsesProtocolConfiguration()
),
)
project_client.agents.update_details(
agent_name="my-agent",
agent_endpoint=endpoint_config,
)使用 REST API 配置终结点路由。请切换到 REST API 选项卡查看示例。
TypeScript
const endpointConfig = {
version_selector: {
version_selection_rules: [\
{ type: "FixedRatio", agent_version: "1", traffic_percentage: 100 },\
],
},
protocol_configuration: { responses: {} },
};
await project.agents.updateAgent("my-agent", {
agentEndpoint: endpointConfig,
});在 azd deploy 期间,该工具会应用为智能体配置的终结点设置。如果已把生产固定到某个版本,请确保这些设置不会覆盖该固定。要选择特定版本,请使用 REST API 或 SDK。
发布版本而不改变生产
在部署候选版本之前,先固定生产终结点。默认路由策略跟随最新版本,因此若未先固定生产就创建版本,可能会改变使用者收到的内容。
此工作流把部署与提升分开。可将其与 azd CI/CD 或独立 Terraform 部署 一起使用。
- 记录并固定生产。 读取智能体当前的终结点配置,并记录生产所服务的版本。用一条 100% 的
FixedRatio规则选择该具体版本。保留其标识符和容器映像,以便回滚。
- 创建候选版本。 部署新映像或新配置,但不更改生产选择器。从部署工具中记下候选版本的具体版本标识符。测试之后或等待批准期间,不要再次解析
latest。
对于 azd,在 azd deploy 之前检查已配置的终结点设置和部署挂钩。对于 Terraform,协调所有写入该具名智能体的一方:Terraform 的状态锁并不能阻止另一个 API 客户端创建版本。
- 验证就绪状态和身份。 获取候选版本,并等待其状态变为
active。确认其映像和配置与打算发布的工件一致。部署失败、超时或出现意外候选版本时,必须停止发布,且不改变生产。
- 测试绑定到候选版本的会话。 使用
type设为version_ref的version_indicator,创建固定到该候选版本的新会话。把记下的版本作为agent_version传入。
使用返回的会话 ID 进行调用。对于 Responses,把 agent_session_id 放在请求正文中。对于 Invocations,使用 agent_session_id 查询参数。检查协议是否成功完成,以及响应内容是否符合预期;仅有非空日志或 HTTP 连接并不算通过测试。
- 批准并提升。 提升之前,确认候选版本仍为活动状态,且生产仍指向已记录的版本。如果另一次发布更改了选择器,请停止并核对这一更改。批准之后,把终结点选择器更新为已测试的候选版本并设为 100%,同时保留无关的协议和授权设置。
- 验证生产并保留回滚。 创建一个不带版本覆盖的新会话,并验证它使用的是所选版本。如果发布未通过生产检查,恢复先前的具体选择器,并再次验证新会话的行为。
现有会话在创建时绑定到其版本。更改终结点选择器不会迁移这些会话。在会话或回滚要求仍然依赖先前版本和映像时,请保留它们。删除智能体或某个版本并不是回滚操作。
检索用于角色分配的智能体身份
每个托管智能体都有一个_实例身份(instance identity)_,即 Microsoft Entra ID 服务主体,智能体在运行时用它向下游资源进行身份验证。要授予智能体访问 Azure Storage 或 Azure Cosmos DB 等服务的权限,需要该身份的主体 ID,以便创建基于角色的访问控制(RBAC)角色分配。
有关智能体身份如何工作的更多信息,见智能体身份概念。
提取智能体身份主体 ID
使用 --query 参数,直接从智能体详细信息中提取 instance_identity.principal_id:
Bash
AGENT_IDENTITY=$(az rest --method GET \
--url "${BASE_URL}/agents/${AGENT_NAME}?api-version=${API_VERSION}" \
--resource "${RESOURCE}" \
--query "instance_identity.principal_id" \
--output tsv)
echo "Agent identity principal ID: ${AGENT_IDENTITY}"Python
agent = project_client.agents.get(agent_name="my-agent")
agent_identity = agent.instance_identity["principal_id"]
print(f"Agent identity principal ID: {agent_identity}")使用 REST API 检索智能体身份主体 ID。请切换到 REST API 选项卡查看示例。
TypeScript
const agent = await project.agents.get("my-agent");
if (!agent.instance_identity) {
throw new Error("Agent does not have an instance identity yet.");
}
const agentIdentity = agent.instance_identity.principal_id;
console.log(`Agent identity principal ID: ${agentIdentity}`);使用 REST API 或 Python SDK 检索智能体身份主体 ID。
为智能体身份分配角色
获得主体 ID 后,在适当的资源范围上为智能体身份分配 RBAC 角色。将 --assignee-object-id 与 --assignee-principal-type ServicePrincipal 一起使用,以避免智能体身份服务主体在 Microsoft Graph 查找时出现问题。
智能体身份可用于任何支持 RBAC 的 Azure 资源。以下示例展示两种常见情形:授予对 Foundry 项目的访问权限,以及授予对存储帐户的访问权限。
在 Foundry 项目上分配角色(例如,允许智能体使用项目资源):
Bash
az role assignment create \
--assignee-object-id "$AGENT_IDENTITY" \
--assignee-principal-type ServicePrincipal \
--role "Azure AI Developer" \
--scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.CognitiveServices/accounts/<account-name>/projects/<project-name>"在存储帐户上分配角色(例如,允许智能体读取和写入 Blob):
Bash
az role assignment create \
--assignee-object-id "$AGENT_IDENTITY" \
--assignee-principal-type ServicePrincipal \
--role "Storage Blob Data Contributor" \
--scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Storage/storageAccounts/<storage-account>"角色分配是 Azure 资源管理器(Azure Resource Manager)操作。使用 REST 选项卡中所示的 Azure CLI 命令,并代入上一步的 agent_identity 值;或者使用 Azure Authorization Management SDK 以编程方式创建角色分配。
角色分配是 Azure 资源管理器操作。使用 REST 选项卡中所示的 Azure CLI 命令,并代入上一步的智能体身份值;或者使用 .NET 的 Azure Authorization 管理库 以编程方式创建角色分配。
角色分配是 Azure 资源管理器操作。使用 REST 选项卡中所示的 Azure CLI 命令,并代入上一步的智能体身份值;或者使用 适用于 JavaScript 的 Azure SDK 管理库 以编程方式创建角色分配。
直接使用 Azure CLI 创建角色分配。先用 REST API 或 Python SDK 检索智能体身份主体 ID,然后按 REST 选项卡所示运行 az role assignment create。
验证角色分配
列出分配给智能体身份、作用在 Foundry 项目上的角色:
Bash
az role assignment list \
--assignee "$AGENT_IDENTITY" \
--scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.CognitiveServices/accounts/<account-name>/projects/<project-name>" \
--output table列出分配给智能体身份、作用在存储帐户上的角色:
Bash
az role assignment list \
--assignee "$AGENT_IDENTITY" \
--scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Storage/storageAccounts/<storage-account>" \
--output table使用 REST 选项卡中所示的 Azure CLI 命令验证角色分配。
使用 REST 选项卡中所示的 Azure CLI 命令验证角色分配。
使用 REST 选项卡中所示的 Azure CLI 命令验证角色分配。
按 REST 选项卡所示,直接使用 Azure CLI 验证角色分配。 PRIMARY_SOURCE: https://learn.microsoft.com/en-us/azure/foundry/agents/how-to/manage-hosted-agent
- #Foundry
- #托管智能体
- #版本发布
- #RBAC
- #回滚


