mcpField
H
hosted-agents-v2-py

hosted-agents-v2-py

github.com/sickn33Agent 工作流48.7k55 次安装今天更新
代码仓库

关于 hosted-agents-v2-py

这是一项基于指令的 Python 技能,使用 Azure AI Projects SDK 创建和管理容器化托管 Agent。内容涵盖 Agent 版本的创建、列出和删除,以及镜像配置和前置条件。

主要功能

  1. 01创建容器化托管 Agent
  2. 02列出和删除 Agent 版本
  3. 03配置协议与容器资源
  4. 04检查镜像仓库访问前提

适用场景

  1. 01使用容器镜像准备托管 Agent 部署
  2. 02检查或删除指定 Agent 版本

MCP 相关

说明展示了带服务器 URL 和标签的应用级 MCP 工具配置,并指出仅有此配置不会创建工具或授予权限。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill hosted-agents-v2-py

安装后在 Claude Code 中输入/hosted-agents-v2-py确认已加载。

详细介绍

兼容性与维护

此兼容性组的主要编辑路径。仅包含说明的流程仍为本地流程;不随附可执行支持文件,因此现有安装仍可离线运行。这是一个共用流程,并非新增功能。 如果现有清单或客户端配置使用了可调用 ID,请保留该 ID。 于 2026-09-05 在 AAS 中修改;保留原始元数据和许可证声明。

Azure AI Hosted Agents(Python)

使用 Azure AI Projects SDK 中的 HostedAgentDefinition 构建基于容器的托管 Agent。

安装

pip install 'azure-ai-projects==2.3.0' azure-identity

这些是与当前 Microsoft 托管 Agent 指南一致的 SDK 2.3.0 说明片段。预配前,请验证已安装的架构和服务支持情况;检查文档不等同于云集成测试。

环境变量

export AZURE_AI_PROJECT_ENDPOINT="https://<resource>.services.ai.azure.com/api/projects/<project>"

先决条件

创建托管 Agent 前:

  1. 容器映像 - 构建并推送到 Azure Container Registry(ACR)
  2. ACR 拉取权限 - 为项目标识授予其权限模式支持的注册表角色;当前托管 Agent 指南使用 Container Registry Repository Reader
  3. 功能主机 - 确认当前项目/区域是否支持托管 Agent,以及应用程序的网络策略;不要自动启用公共托管
  4. SDK 版本 - 确保使用 azure-ai-projects==2.3.0

身份验证

针对目标租户/订阅,使用获批的 Azure 凭据流程;此示例使用 DefaultAzureCredential:

from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient

import os

credential = DefaultAzureCredential()
client = AIProjectClient(
    endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
    credential=credential
)

核心工作流

1. 导入
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    HostedAgentDefinition,
    ContainerConfiguration,
    ProtocolVersionRecord,
    AgentEndpointProtocol,
)
2. 创建托管 Agent
client = AIProjectClient(
    endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
    credential=DefaultAzureCredential()
)

agent = client.agents.create_version(
    agent_name="my-hosted-agent",
    definition=HostedAgentDefinition(
        protocol_versions=[
            ProtocolVersionRecord(protocol=AgentEndpointProtocol.RESPONSES, version="2.0.0")
        ],
        cpu="1",
        memory="2Gi",
        container_configuration=ContainerConfiguration(image=os.environ["REVIEWED_CONTAINER_IMAGE"]),
        environment_variables={
            "AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],
            "MODEL_NAME": os.environ["MODEL_DEPLOYMENT_NAME"]
        }
    )
)

print(f"Created agent: {agent.name} (version: {agent.version})")
3. 列出 Agent 版本
versions = client.agents.list_versions(agent_name="my-hosted-agent")
for version in versions:
    print(f"Version: {version.version}")  # Inspect supported status fields via get_version

检查返回对象的确切类型,以确认支持的字段;创建了版本并不代表运行中的容器处于健康状态。请通过受支持的上下文管理器或 close() 方法关闭同步客户端/凭据资源。

4. 删除 Agent 版本
client.agents.delete_version(
    agent_name="my-hosted-agent",
    agent_version=agent.version
)

HostedAgentDefinition 参数

参数类型必需说明
protocol_versionslist[ProtocolVersionRecord]是Agent 支持的协议版本
container_configurationContainerConfiguration使用映像部署时必需已审核的注册表映像引用
cpustr否CPU 分配量(例如 "1"、"2")
memorystr否内存分配量(例如 "2Gi"、"4Gi")
environment_variablesdict[str, str]否容器的环境变量

协议版本

protocol_versions 参数用于指定 Agent 支持的协议:

from azure.ai.projects.models import ProtocolVersionRecord, AgentEndpointProtocol

# RESPONSES protocol - standard agent responses
protocol_versions=[
    ProtocolVersionRecord(protocol=AgentEndpointProtocol.RESPONSES, version="2.0.0")
]

可用协议:

协议说明
AgentEndpointProtocol.RESPONSES用于 Agent 交互的标准响应协议

资源分配

为容器指定 CPU 和内存:

definition=HostedAgentDefinition(
    protocol_versions=[...],
    container_configuration=ContainerConfiguration(image=os.environ["REVIEWED_CONTAINER_IMAGE"]),
    cpu="2",      # 2 CPU cores
    memory="4Gi"  # 4 GiB memory
)

以下为示例资源规格;预配前请核实区域/SKU 限制:

资源最小值最大值默认值
CPU0.541
内存1Gi8Gi2Gi

工具配置

在所选容器运行时/框架中配置工具支持。以下工具字典描述的是特定于应用程序的意图;不要假设 HostedAgentDefinition 上存在 tools 字段,也不要假设定义该字段会预配工具或授予权限:

代码解释器
tools=[{"type": "code_interpreter"}]
MCP 工具
tools=[
    {"type": "code_interpreter"},
    {
        "type": "mcp",
        "server_label": "my-mcp-server",
        "server_url": "https://my-mcp-server.example.com"
    }
]
多种工具
tools=[
    {"type": "code_interpreter"},
    {"type": "file_search"},
    {
        "type": "mcp",
        "server_label": "custom-tool",
        "server_url": "https://custom-tool.example.com"
    }
]
环境变量

向容器传递配置:

environment_variables={
    "AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],
    "MODEL_NAME": os.environ["MODEL_DEPLOYMENT_NAME"],
    "LOG_LEVEL": "INFO",
    "CUSTOM_CONFIG": "value"
}

最佳实践: 在配置中保留非机密的部署名称和经过审核的不可变映像引用;机密信息需要通过平台实际提供的受保护注入机制传递。任意环境字典并不能建立与 Key Vault 的集成。

完整示例

import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    HostedAgentDefinition,
    ContainerConfiguration,
    ProtocolVersionRecord,
    AgentEndpointProtocol,
)

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=HostedAgentDefinition(
            protocol_versions=[
                ProtocolVersionRecord(
                    protocol=AgentEndpointProtocol.RESPONSES,
                    version="2.0.0"
                )
            ],
            container_configuration=ContainerConfiguration(image=os.environ["REVIEWED_CONTAINER_IMAGE"]),
            cpu="2",
            memory="4Gi",
            environment_variables={
                "AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],
                "MODEL_NAME": os.environ["MODEL_DEPLOYMENT_NAME"],
                "MAX_RETRIES": "3"
            }
        )
    )
    
    print(f"Created hosted agent: {agent.name}")
    print(f"Version: {agent.version}")
    # Poll get_version status with a deadline before treating deployment as active.
    
    return agent

if __name__ == "__main__":
    create_hosted_agent()

异步模式

import os
from azure.identity.aio import DefaultAzureCredential
from azure.ai.projects.aio import AIProjectClient
from azure.ai.projects.models import (
    HostedAgentDefinition,
    ContainerConfiguration,
    ProtocolVersionRecord,
    AgentEndpointProtocol,
)

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=HostedAgentDefinition(
                    protocol_versions=[
                        ProtocolVersionRecord(
                            protocol=AgentEndpointProtocol.RESPONSES,
                            version="2.0.0"
                        )
                    ],
                    container_configuration=ContainerConfiguration(image=os.environ["REVIEWED_CONTAINER_IMAGE"]),
                    cpu="1",
                    memory="2Gi"
                )
            )
            return agent

常见错误

错误原因解决方案
ImagePullBackOffACR 拉取权限被拒绝验证注册表权限模式,以及项目身份是否具有范围限定的读取者角色
InvalidContainerImage找不到镜像验证 ACR 中存在该镜像路径和标签
CapabilityHostNotFound未配置能力主机创建账户级能力主机
ProtocolVersionNotSupported协议版本无效使用 AgentEndpointProtocol.RESPONSES,版本为 "2.0.0"

最佳实践

  1. 为镜像设置版本 - 生产环境中使用特定标签,不要使用 latest
  2. 资源配置从简 - 从最低 CPU/内存配置开始,按需扩容
  3. 环境变量 - 所有配置都使用环境变量,绝不硬编码
  4. 错误处理 - 使用 try/except 块包装 Agent 创建过程
  5. 清理 - 删除未使用的 Agent 版本以释放资源

参考链接

适用场景

用于审查或创建明确要求的、基于容器的 Foundry 托管 Agent。首先确认镜像摘要、订阅/租户、区域、服务可用性、权限和成本范围。创建 Agent、授予角色和删除版本都属于云端写入操作;只有在用户授权范围内才能执行。

审查示例

给定一个固定版本的容器镜像和测试项目,检查 SDK 模型字段和注册表拉取权限,然后准备创建请求。仅在获得授权后进行预配,并记录确切返回的版本和观察到的运行状况。不要将删除无关版本作为例行清理操作。预期结果应是特定版本的回执,而不是假定部署成功。

限制

  • 仅当任务明确符合上述范围时才使用此技能。
  • 不要将输出视为环境特定验证、测试或专家审查的替代品。
  • 如果缺少必需输入、权限、安全边界或成功标准,请停止并请求澄清。

评论

支持 Markdown