
关于
使用 Azure AI Projects SDK 和 ImageBasedHostedAgentDefinition 构建托管 Agent。用于创建容器化 AI Agent。
name: hosted-agents-v2-py description: "使用Azure AI Projects SDK构建基于容器的托管代理" risk: unknown source: community date_added: "2026-02-27"
Azure AI 托管代理(Python)
使用Azure AI Projects SDK的 ImageBasedHostedAgentDefinition 构建基于容器的托管代理。
安装
pip install azure-ai-projects>=2.0.0b3 azure-identity
最低SDK版本: 需要 2.0.0b3 或更高版本。
环境变量
AZURE_AI_PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>
前提条件
- 容器镜像 - 构建并推送到Azure容器注册表(ACR)
- ACR拉取权限 - 授予
AcrPull角色 - 能力主机 - 设置
enablePublicHostingEnvironment=true - SDK版本 - 确保
azure-ai-projects>=2.0.0b3
认证
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
credential = DefaultAzureCredential()
client = AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=credential
)
核心工作流
创建托管代理
agent = client.agents.create_version(
agent_name="my-hosted-agent",
definition=ImageBasedHostedAgentDefinition(
container_protocol_versions=[
ProtocolVersionRecord(protocol=AgentProtocol.RESPONSES, version="v1")
],
cpu="1",
memory="2Gi",
image="myregistry.azurecr.io/my-agent:latest",
tools=[{"type": "code_interpreter"}],
environment_variables={
"AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],
"MODEL_NAME": "gpt-4o-mini"
}
)
)
列出代理版本
versions = client.agents.list_versions(agent_name="my-hosted-agent")
for version in versions:
print(f"Version: {version.version}, State: {version.state}")
删除代理版本
client.agents.delete_version(agent_name="my-hosted-agent", version=agent.version)
参数说明
| 参数 | 类型 | 必需 | 描述 |
|------|------|------|------|
| container_protocol_versions | list | 是 | 支持的协议版本 |
| image | str | 是 | ACR容器镜像URI |
| cpu | str | 否 | CPU分配 |
| memory | str | 否 | 内存分配 |
| tools | list | 否 | 可用工具 |
| environment_variables | dict | 否 | 环境变量 |
常见问题
- 权限错误:确保有ACR的
AcrPull角色 - 镜像拉取失败:验证镜像URI和ACR可访问性
- 代理创建超时:检查镜像大小和网络
- 协议版本不匹配:确认
AgentProtocol枚举值
兼容工具
Claude CodeCursor
标签
AI与机器学习