Azure AI ホステッドエージェント (Python)
ImageBasedHostedAgentDefinition を使用して、Azure AI Projects SDK でコンテナベースのホステッドエージェントを構築します。
インストール
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 Container Registry (ACR) にプッシュする
- ACR プル許可 - プロジェクトのマネージド ID に ACR の
AcrPullロールを付与する - 機能ホスト - アカウントレベルの機能ホストが
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 | はい | 完全なコンテナイメージパス (レジストリ/イメージ:タグ) |
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 |
ツール設定
ホステッドエージェントにツールを追加します:
コードインタープリタ
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 プル許可が拒否された | プロジェクトのマネージド ID に AcrPull ロールを付与する |
InvalidContainerImage | イメージが見つからない | ACR にイメージパスとタグが存在することを確認する |
CapabilityHostNotFound | 機能ホストが設定されていない | アカウントレベルの機能ホストを作成する |
ProtocolVersionNotSupported | 無効なプロトコルバージョン | バージョン "v1" で AgentProtocol.RESPONSES を使用する |
ベストプラクティス
- イメージにバージョンタグを付ける - 本番環境では
latestではなく、特定のタグを使用する - 最小リソース - 最小限の CPU/メモリから始め、必要に応じてスケールアップする
- 環境変数 - すべての設定に環境変数を使用し、ハードコードしない
- エラーハンドリング - エージェント作成を try/except ブロックでラップする
- クリーンアップ - 未使用のエージェントバージョンを削除してリソースを解放する
参考リンク
使用タイミング
このスキルは、概要に記載されたワークフローやアクションを実行する場合に適用されます。
制限事項
- タスクが上記の範囲に明確に一致する場合にのみ、このスキルを使用してください。
- 出力を環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
- 必要な入力、許可、安全境界、または成功基準が欠落している場合は、停止して明確化を求めてください。