agents-v2-py

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Azure AI Hosted Agents (Python)

Azure AI 托管Agent(Python)

Build container-based hosted agents using
ImageBasedHostedAgentDefinition
from the Azure AI Projects SDK.
使用Azure AI Projects SDK中的
ImageBasedHostedAgentDefinition
构建基于容器的托管Agent。

Installation

安装

bash
pip install azure-ai-projects>=2.0.0b3 azure-identity
Minimum SDK Version:
2.0.0b3
or later required for hosted agent support.
bash
pip install azure-ai-projects>=2.0.0b3 azure-identity
最低SDK版本: 托管Agent支持需要
2.0.0b3
或更高版本。

Environment 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:
  1. Container Image - Build and push to Azure Container Registry (ACR)
  2. ACR Pull Permissions - Grant your project's managed identity
    AcrPull
    role on the ACR
  3. Capability Host - Account-level capability host with
    enablePublicHostingEnvironment=true
  4. SDK Version - Ensure
    azure-ai-projects>=2.0.0b3
创建托管Agent前需满足:
  1. 容器镜像 - 构建并推送到Azure Container Registry(ACR)
  2. ACR拉取权限 - 为项目的托管标识授予ACR的
    AcrPull
    角色
  3. 能力主机 - 账户级别的能力主机,需设置
    enablePublicHostingEnvironment=true
  4. SDK版本 - 确保
    azure-ai-projects>=2.0.0b3

Authentication

身份验证

Always use
DefaultAzureCredential
:
python
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient

credential = DefaultAzureCredential()
client = AIProjectClient(
    endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
    credential=credential
)
请始终使用
DefaultAzureCredential
python
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参数

ParameterTypeRequiredDescription
container_protocol_versions
list[ProtocolVersionRecord]
YesProtocol versions the agent supports
image
str
YesFull container image path (registry/image:tag)
cpu
str
NoCPU allocation (e.g., "1", "2")
memory
str
NoMemory allocation (e.g., "2Gi", "4Gi")
tools
list[dict]
NoTools available to the agent
environment_variables
dict[str, str]
NoEnvironment variables for the container
参数类型是否必填描述
container_protocol_versions
list[ProtocolVersionRecord]
Agent支持的协议版本
image
str
完整的容器镜像路径(registry/image:tag)
cpu
str
CPU分配(例如:"1"、"2")
memory
str
内存分配(例如:"2Gi"、"4Gi")
tools
list[dict]
Agent可用的工具
environment_variables
dict[str, str]
容器的环境变量

Protocol Versions

协议版本

The
container_protocol_versions
parameter specifies which protocols your agent supports:
python
from azure.ai.projects.models import ProtocolVersionRecord, AgentProtocol
container_protocol_versions
参数指定Agent支持的协议:
python
from azure.ai.projects.models import ProtocolVersionRecord, AgentProtocol

RESPONSES 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:
ResourceMinMaxDefault
CPU0.541
Memory1Gi8Gi2Gi
为容器指定CPU和内存:
python
definition=ImageBasedHostedAgentDefinition(
    container_protocol_versions=[...],
    image="myregistry.azurecr.io/my-agent:latest",
    cpu="2",      # 2个CPU核心
    memory="4Gi"  # 4 GiB内存
)
资源限制:
资源最小值最大值默认值
CPU0.541
内存1Gi8Gi2Gi

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 agent
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():
    """异步创建托管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 agent

Common Errors

常见错误

ErrorCauseSolution
ImagePullBackOff
ACR pull permission deniedGrant
AcrPull
role to project's managed identity
InvalidContainerImage
Image not foundVerify image path and tag exist in ACR
CapabilityHostNotFound
No capability host configuredCreate account-level capability host
ProtocolVersionNotSupported
Invalid protocol versionUse
AgentProtocol.RESPONSES
with version
"v1"
错误原因解决方案
ImagePullBackOff
ACR拉取权限被拒绝为项目的托管标识授予
AcrPull
角色
InvalidContainerImage
镜像未找到验证ACR中的镜像路径和标签是否存在
CapabilityHostNotFound
未配置能力主机创建账户级别的能力主机
ProtocolVersionNotSupported
协议版本无效使用
AgentProtocol.RESPONSES
并指定版本
"v1"

Best Practices

最佳实践

  1. Version Your Images - Use specific tags, not
    latest
    in production
  2. Minimal Resources - Start with minimum CPU/memory, scale up as needed
  3. Environment Variables - Use for all configuration, never hardcode
  4. Error Handling - Wrap agent creation in try/except blocks
  5. Cleanup - Delete unused agent versions to free resources
  1. 镜像版本化 - 生产环境使用特定标签,而非
    latest
  2. 最小资源配置 - 从最低CPU/内存开始,按需扩容
  3. 环境变量 - 所有配置均使用环境变量,切勿硬编码
  4. 错误处理 - 将Agent创建代码包裹在try/except块中
  5. 资源清理 - 删除未使用的Agent版本以释放资源

Reference Links

参考链接