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>
先決條件
在建立託管代理之前:
- 容器映像 (Container Image) - 建立並推送到 Azure Container Registry (ACR)
- ACR 拉取權限 - 授予您專案受控身分在 ACR 上的
AcrPull角色 - 能力主機 (Capability Host) - 帳戶級別的能力主機,且
enablePublicHostingEnvironment=true - SDK 版本 - 確認
azure-ai-projects>=2.0.0b3
驗證
始終使用 DefaultAzureCredential:
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
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 (
ImageBasedHostedAgentDefinition,
ProtocolVersionRecord,
AgentProtocol,
)
2. 建立託管代理
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"已建立代理:{agent.name} (版本:{agent.version})")
3. 列出代理版本
versions = client.agents.list_versions(agent_name="my-hosted-agent")
for version in versions:
print(f"版本:{version.version}, 狀態:{version.state}")
4. 刪除代理版本
client.agents.delete_version(
agent_name="my-hosted-agent",
version=agent.version
)
ImageBasedHostedAgentDefinition 參數
| 參數 | 類型 | 必填 | 說明 |
|---|---|---|---|
container_protocol_versions | list[ProtocolVersionRecord] | 是 | 代理支援的協定版本 |
image | str | 是 | 完整的容器映像路徑 (registry/image:tag) |
cpu | str | 否 | CPU 配置 (例如 "1", "2") |
memory | str | 否 | 記憶體配置 (例如 "2Gi", "4Gi") |
tools | list[dict] | 否 | 代理可用的工具 |
environment_variables | dict[str, str] | 否 | 容器的環境變數 |
協定版本
container_protocol_versions 參數指定您的代理支援哪些協定:
from azure.ai.projects.models import ProtocolVersionRecord, AgentProtocol
# RESPONSES 協定 - 標準代理回應
container_protocol_versions=[
ProtocolVersionRecord(protocol=AgentProtocol.RESPONSES, version="v1")
]
可用的協定:
| 協定 | 說明 |
|---|---|
AgentProtocol.RESPONSES | 代理互動的標準回應協定 |
資源配置
為您的容器指定 CPU 和記憶體:
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 |
工具配置
將工具新增到您的託管代理:
程式碼解譯器 (Code Interpreter)
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": "gpt-4o-mini",
"LOG_LEVEL": "INFO",
"CUSTOM_CONFIG": "value"
}
最佳實務: 永遠不要將機密資訊硬編碼。請使用環境變數或 Azure Key Vault。
完整範例
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():
"""使用自訂容器映像建立託管代理。"""
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"已建立託管代理:{agent.name}")
print(f"版本:{agent.version}")
print(f"狀態:{agent.state}")
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 (
ImageBasedHostedAgentDefinition,
ProtocolVersionRecord,
AgentProtocol,
)
async def create_hosted_agent_async():
"""非同步建立託管代理。"""
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
常見錯誤
| 錯誤 | 原因 | 解決方案 |
|---|---|---|
ImagePullBackOff | ACR 拉取權限遭拒 | 授予專案受控身分 AcrPull 角色 |
InvalidContainerImage | 找不到映像 | 驗證 ACR 中的映像路徑和標籤是否存在 |
CapabilityHostNotFound | 未配置能力主機 | 建立帳戶級別的能力主機 |
ProtocolVersionNotSupported | 無效的協定版本 | 使用 AgentProtocol.RESPONSES 搭配版本 "v1" |
最佳實務
- 為您的映像設定版本 - 在生產環境中使用特定標籤,而非
latest - 最小資源 - 從最小的 CPU/記憶體開始,根據需要擴展
- 環境變數 - 用於所有配置,切勿硬編碼
- 錯誤處理 - 將代理建立包裝在 try/except 區塊中
- 清理 - 刪除未使用的代理版本以釋放資源
參考連結
使用時機
此技能適用於執行概述中所述的工作流程或動作。
限制
- 僅在任務明確符合上述描述的範圍時使用此技能。
- 請勿將輸出視為環境特定驗證、測試或專家審查的替代品。
- 如果缺少必要的輸入、權限、安全邊界或成功標準,請停止並要求澄清。