agents-v2-py
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAzure AI Hosted Agents (Python)
Azure AI 托管Agent(Python)
Build container-based hosted agents using from the Azure AI Projects SDK.
ImageBasedHostedAgentDefinition使用Azure AI Projects SDK中的构建基于容器的托管Agent。
ImageBasedHostedAgentDefinitionInstallation
安装
bash
pip install azure-ai-projects>=2.0.0b3 azure-identityMinimum SDK Version: or later required for hosted agent support.
2.0.0b3bash
pip install azure-ai-projects>=2.0.0b3 azure-identity最低SDK版本: 托管Agent支持需要或更高版本。
2.0.0b3Environment Variables
环境变量
bash
AZURE_AI_PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>bash
AZURE_AI_PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>Prerequisites
前置条件
Before creating hosted agents:
- Container Image - Build and push to Azure Container Registry (ACR)
- ACR Pull Permissions - Grant your project's managed identity role on the ACR
AcrPull - Capability Host - Account-level capability host with
enablePublicHostingEnvironment=true - SDK Version - Ensure
azure-ai-projects>=2.0.0b3
创建托管Agent前需满足:
- 容器镜像 - 构建并推送到Azure Container Registry(ACR)
- ACR拉取权限 - 为项目的托管标识授予ACR的角色
AcrPull - 能力主机 - 账户级别的能力主机,需设置
enablePublicHostingEnvironment=true - SDK版本 - 确保
azure-ai-projects>=2.0.0b3
Authentication
身份验证
Always use :
DefaultAzureCredentialpython
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
credential = DefaultAzureCredential()
client = AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=credential
)请始终使用:
DefaultAzureCredentialpython
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
credential = DefaultAzureCredential()
client = AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=credential
)Core Workflow
核心工作流
1. Imports
1. 导入依赖
python
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
ImageBasedHostedAgentDefinition,
ProtocolVersionRecord,
AgentProtocol,
)python
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
ImageBasedHostedAgentDefinition,
ProtocolVersionRecord,
AgentProtocol,
)2. Create Hosted Agent
2. 创建托管Agent
python
client = AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential()
)
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"
}
)
)
print(f"Created agent: {agent.name} (version: {agent.version})")python
client = AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential()
)
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"
}
)
)
print(f"Created agent: {agent.name} (version: {agent.version})")3. List Agent Versions
3. 列出Agent版本
python
versions = client.agents.list_versions(agent_name="my-hosted-agent")
for version in versions:
print(f"Version: {version.version}, State: {version.state}")python
versions = client.agents.list_versions(agent_name="my-hosted-agent")
for version in versions:
print(f"Version: {version.version}, State: {version.state}")4. Delete Agent Version
4. 删除Agent版本
python
client.agents.delete_version(
agent_name="my-hosted-agent",
version=agent.version
)python
client.agents.delete_version(
agent_name="my-hosted-agent",
version=agent.version
)ImageBasedHostedAgentDefinition Parameters
ImageBasedHostedAgentDefinition参数
| Parameter | Type | Required | Description |
|---|---|---|---|
| | Yes | Protocol versions the agent supports |
| | Yes | Full container image path (registry/image:tag) |
| | No | CPU allocation (e.g., "1", "2") |
| | No | Memory allocation (e.g., "2Gi", "4Gi") |
| | No | Tools available to the agent |
| | No | Environment variables for the container |
| 参数 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| | 是 | Agent支持的协议版本 |
| | 是 | 完整的容器镜像路径(registry/image:tag) |
| | 否 | CPU分配(例如:"1"、"2") |
| | 否 | 内存分配(例如:"2Gi"、"4Gi") |
| | 否 | Agent可用的工具 |
| | 否 | 容器的环境变量 |
Protocol Versions
协议版本
The parameter specifies which protocols your agent supports:
container_protocol_versionspython
from azure.ai.projects.models import ProtocolVersionRecord, AgentProtocolcontainer_protocol_versionspython
from azure.ai.projects.models import ProtocolVersionRecord, AgentProtocolRESPONSES protocol - standard agent responses
RESPONSES协议 - 标准Agent响应协议
container_protocol_versions=[
ProtocolVersionRecord(protocol=AgentProtocol.RESPONSES, version="v1")
]
**Available Protocols:**
| Protocol | Description |
|----------|-------------|
| `AgentProtocol.RESPONSES` | Standard response protocol for agent interactions |container_protocol_versions=[
ProtocolVersionRecord(protocol=AgentProtocol.RESPONSES, version="v1")
]
**可用协议:**
| 协议 | 描述 |
|----------|-------------|
| `AgentProtocol.RESPONSES` | Agent交互的标准响应协议 |Resource Allocation
资源分配
Specify CPU and memory for your container:
python
definition=ImageBasedHostedAgentDefinition(
container_protocol_versions=[...],
image="myregistry.azurecr.io/my-agent:latest",
cpu="2", # 2 CPU cores
memory="4Gi" # 4 GiB memory
)Resource Limits:
| Resource | Min | Max | Default |
|---|---|---|---|
| CPU | 0.5 | 4 | 1 |
| Memory | 1Gi | 8Gi | 2Gi |
为容器指定CPU和内存:
python
definition=ImageBasedHostedAgentDefinition(
container_protocol_versions=[...],
image="myregistry.azurecr.io/my-agent:latest",
cpu="2", # 2个CPU核心
memory="4Gi" # 4 GiB内存
)资源限制:
| 资源 | 最小值 | 最大值 | 默认值 |
|---|---|---|---|
| CPU | 0.5 | 4 | 1 |
| 内存 | 1Gi | 8Gi | 2Gi |
Tools Configuration
工具配置
Add tools to your hosted agent:
为托管Agent添加工具:
Code Interpreter
代码解释器
python
tools=[{"type": "code_interpreter"}]python
tools=[{"type": "code_interpreter"}]MCP Tools
MCP工具
python
tools=[
{"type": "code_interpreter"},
{
"type": "mcp",
"server_label": "my-mcp-server",
"server_url": "https://my-mcp-server.example.com"
}
]python
tools=[
{"type": "code_interpreter"},
{
"type": "mcp",
"server_label": "my-mcp-server",
"server_url": "https://my-mcp-server.example.com"
}
]Multiple Tools
多工具配置
python
tools=[
{"type": "code_interpreter"},
{"type": "file_search"},
{
"type": "mcp",
"server_label": "custom-tool",
"server_url": "https://custom-tool.example.com"
}
]python
tools=[
{"type": "code_interpreter"},
{"type": "file_search"},
{
"type": "mcp",
"server_label": "custom-tool",
"server_url": "https://custom-tool.example.com"
}
]Environment Variables
环境变量
Pass configuration to your container:
python
environment_variables={
"AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],
"MODEL_NAME": "gpt-4o-mini",
"LOG_LEVEL": "INFO",
"CUSTOM_CONFIG": "value"
}Best Practice: Never hardcode secrets. Use environment variables or Azure Key Vault.
向容器传递配置:
python
environment_variables={
"AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],
"MODEL_NAME": "gpt-4o-mini",
"LOG_LEVEL": "INFO",
"CUSTOM_CONFIG": "value"
}最佳实践: 切勿硬编码密钥,请使用环境变量或Azure Key Vault。
Complete Example
完整示例
python
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
ImageBasedHostedAgentDefinition,
ProtocolVersionRecord,
AgentProtocol,
)
def create_hosted_agent():
"""Create a hosted agent with custom container image."""
client = AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential()
)
agent = client.agents.create_version(
agent_name="data-processor-agent",
definition=ImageBasedHostedAgentDefinition(
container_protocol_versions=[
ProtocolVersionRecord(
protocol=AgentProtocol.RESPONSES,
version="v1"
)
],
image="myregistry.azurecr.io/data-processor:v1.0",
cpu="2",
memory="4Gi",
tools=[
{"type": "code_interpreter"},
{"type": "file_search"}
],
environment_variables={
"AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],
"MODEL_NAME": "gpt-4o-mini",
"MAX_RETRIES": "3"
}
)
)
print(f"Created hosted agent: {agent.name}")
print(f"Version: {agent.version}")
print(f"State: {agent.state}")
return agent
if __name__ == "__main__":
create_hosted_agent()python
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
ImageBasedHostedAgentDefinition,
ProtocolVersionRecord,
AgentProtocol,
)
def create_hosted_agent():
"""使用自定义容器镜像创建托管Agent。"""
client = AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential()
)
agent = client.agents.create_version(
agent_name="data-processor-agent",
definition=ImageBasedHostedAgentDefinition(
container_protocol_versions=[
ProtocolVersionRecord(
protocol=AgentProtocol.RESPONSES,
version="v1"
)
],
image="myregistry.azurecr.io/data-processor:v1.0",
cpu="2",
memory="4Gi",
tools=[
{"type": "code_interpreter"},
{"type": "file_search"}
],
environment_variables={
"AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],
"MODEL_NAME": "gpt-4o-mini",
"MAX_RETRIES": "3"
}
)
)
print(f"Created hosted agent: {agent.name}")
print(f"Version: {agent.version}")
print(f"State: {agent.state}")
return agent
if __name__ == "__main__":
create_hosted_agent()Async Pattern
异步模式
python
import os
from azure.identity.aio import DefaultAzureCredential
from azure.ai.projects.aio import AIProjectClient
from azure.ai.projects.models import (
ImageBasedHostedAgentDefinition,
ProtocolVersionRecord,
AgentProtocol,
)
async def create_hosted_agent_async():
"""Create a hosted agent asynchronously."""
async with DefaultAzureCredential() as credential:
async with AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=credential
) as client:
agent = await client.agents.create_version(
agent_name="async-agent",
definition=ImageBasedHostedAgentDefinition(
container_protocol_versions=[
ProtocolVersionRecord(
protocol=AgentProtocol.RESPONSES,
version="v1"
)
],
image="myregistry.azurecr.io/async-agent:latest",
cpu="1",
memory="2Gi"
)
)
return agentpython
import os
from azure.identity.aio import DefaultAzureCredential
from azure.ai.projects.aio import AIProjectClient
from azure.ai.projects.models import (
ImageBasedHostedAgentDefinition,
ProtocolVersionRecord,
AgentProtocol,
)
async def create_hosted_agent_async():
"""异步创建托管Agent。"""
async with DefaultAzureCredential() as credential:
async with AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=credential
) as client:
agent = await client.agents.create_version(
agent_name="async-agent",
definition=ImageBasedHostedAgentDefinition(
container_protocol_versions=[
ProtocolVersionRecord(
protocol=AgentProtocol.RESPONSES,
version="v1"
)
],
image="myregistry.azurecr.io/async-agent:latest",
cpu="1",
memory="2Gi"
)
)
return agentCommon Errors
常见错误
| Error | Cause | Solution |
|---|---|---|
| ACR pull permission denied | Grant |
| Image not found | Verify image path and tag exist in ACR |
| No capability host configured | Create account-level capability host |
| Invalid protocol version | Use |
| 错误 | 原因 | 解决方案 |
|---|---|---|
| ACR拉取权限被拒绝 | 为项目的托管标识授予 |
| 镜像未找到 | 验证ACR中的镜像路径和标签是否存在 |
| 未配置能力主机 | 创建账户级别的能力主机 |
| 协议版本无效 | 使用 |
Best Practices
最佳实践
- Version Your Images - Use specific tags, not in production
latest - Minimal Resources - Start with minimum CPU/memory, scale up as needed
- Environment Variables - Use for all configuration, never hardcode
- Error Handling - Wrap agent creation in try/except blocks
- Cleanup - Delete unused agent versions to free resources
- 镜像版本化 - 生产环境使用特定标签,而非
latest - 最小资源配置 - 从最低CPU/内存开始,按需扩容
- 环境变量 - 所有配置均使用环境变量,切勿硬编码
- 错误处理 - 将Agent创建代码包裹在try/except块中
- 资源清理 - 删除未使用的Agent版本以释放资源