|
Add this skill
npx mdskills install sickn33/agents-v2-pyComprehensive guide for deploying container-based agents with excellent examples and troubleshooting
1---2name: agents-v2-py3description: |4 Build container-based Foundry Agents using Azure AI Projects SDK with ImageBasedHostedAgentDefinition.5 Use when creating hosted agents that run custom code in Azure AI Foundry with your own container images.6 Triggers: "ImageBasedHostedAgentDefinition", "hosted agent", "container agent", "Foundry Agent",7 "create_version", "ProtocolVersionRecord", "AgentProtocol.RESPONSES", "custom agent image".8package: azure-ai-projects9---1011# Azure AI Hosted Agents (Python)1213Build container-based hosted agents using `ImageBasedHostedAgentDefinition` from the Azure AI Projects SDK.1415## Installation1617```bash18pip install azure-ai-projects>=2.0.0b3 azure-identity19```2021**Minimum SDK Version:** `2.0.0b3` or later required for hosted agent support.2223## Environment Variables2425```bash26AZURE_AI_PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>27```2829## Prerequisites3031Before creating hosted agents:32331. **Container Image** - Build and push to Azure Container Registry (ACR)342. **ACR Pull Permissions** - Grant your project's managed identity `AcrPull` role on the ACR353. **Capability Host** - Account-level capability host with `enablePublicHostingEnvironment=true`364. **SDK Version** - Ensure `azure-ai-projects>=2.0.0b3`3738## Authentication3940Always use `DefaultAzureCredential`:4142```python43from azure.identity import DefaultAzureCredential44from azure.ai.projects import AIProjectClient4546credential = DefaultAzureCredential()47client = AIProjectClient(48 endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],49 credential=credential50)51```5253## Core Workflow5455### 1. Imports5657```python58import os59from azure.identity import DefaultAzureCredential60from azure.ai.projects import AIProjectClient61from azure.ai.projects.models import (62 ImageBasedHostedAgentDefinition,63 ProtocolVersionRecord,64 AgentProtocol,65)66```6768### 2. Create Hosted Agent6970```python71client = AIProjectClient(72 endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],73 credential=DefaultAzureCredential()74)7576agent = client.agents.create_version(77 agent_name="my-hosted-agent",78 definition=ImageBasedHostedAgentDefinition(79 container_protocol_versions=[80 ProtocolVersionRecord(protocol=AgentProtocol.RESPONSES, version="v1")81 ],82 cpu="1",83 memory="2Gi",84 image="myregistry.azurecr.io/my-agent:latest",85 tools=[{"type": "code_interpreter"}],86 environment_variables={87 "AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],88 "MODEL_NAME": "gpt-4o-mini"89 }90 )91)9293print(f"Created agent: {agent.name} (version: {agent.version})")94```9596### 3. List Agent Versions9798```python99versions = client.agents.list_versions(agent_name="my-hosted-agent")100for version in versions:101 print(f"Version: {version.version}, State: {version.state}")102```103104### 4. Delete Agent Version105106```python107client.agents.delete_version(108 agent_name="my-hosted-agent",109 version=agent.version110)111```112113## ImageBasedHostedAgentDefinition Parameters114115| Parameter | Type | Required | Description |116|-----------|------|----------|-------------|117| `container_protocol_versions` | `list[ProtocolVersionRecord]` | Yes | Protocol versions the agent supports |118| `image` | `str` | Yes | Full container image path (registry/image:tag) |119| `cpu` | `str` | No | CPU allocation (e.g., "1", "2") |120| `memory` | `str` | No | Memory allocation (e.g., "2Gi", "4Gi") |121| `tools` | `list[dict]` | No | Tools available to the agent |122| `environment_variables` | `dict[str, str]` | No | Environment variables for the container |123124## Protocol Versions125126The `container_protocol_versions` parameter specifies which protocols your agent supports:127128```python129from azure.ai.projects.models import ProtocolVersionRecord, AgentProtocol130131# RESPONSES protocol - standard agent responses132container_protocol_versions=[133 ProtocolVersionRecord(protocol=AgentProtocol.RESPONSES, version="v1")134]135```136137**Available Protocols:**138| Protocol | Description |139|----------|-------------|140| `AgentProtocol.RESPONSES` | Standard response protocol for agent interactions |141142## Resource Allocation143144Specify CPU and memory for your container:145146```python147definition=ImageBasedHostedAgentDefinition(148 container_protocol_versions=[...],149 image="myregistry.azurecr.io/my-agent:latest",150 cpu="2", # 2 CPU cores151 memory="4Gi" # 4 GiB memory152)153```154155**Resource Limits:**156| Resource | Min | Max | Default |157|----------|-----|-----|---------|158| CPU | 0.5 | 4 | 1 |159| Memory | 1Gi | 8Gi | 2Gi |160161## Tools Configuration162163Add tools to your hosted agent:164165### Code Interpreter166167```python168tools=[{"type": "code_interpreter"}]169```170171### MCP Tools172173```python174tools=[175 {"type": "code_interpreter"},176 {177 "type": "mcp",178 "server_label": "my-mcp-server",179 "server_url": "https://my-mcp-server.example.com"180 }181]182```183184### Multiple Tools185186```python187tools=[188 {"type": "code_interpreter"},189 {"type": "file_search"},190 {191 "type": "mcp",192 "server_label": "custom-tool",193 "server_url": "https://custom-tool.example.com"194 }195]196```197198## Environment Variables199200Pass configuration to your container:201202```python203environment_variables={204 "AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],205 "MODEL_NAME": "gpt-4o-mini",206 "LOG_LEVEL": "INFO",207 "CUSTOM_CONFIG": "value"208}209```210211**Best Practice:** Never hardcode secrets. Use environment variables or Azure Key Vault.212213## Complete Example214215```python216import os217from azure.identity import DefaultAzureCredential218from azure.ai.projects import AIProjectClient219from azure.ai.projects.models import (220 ImageBasedHostedAgentDefinition,221 ProtocolVersionRecord,222 AgentProtocol,223)224225def create_hosted_agent():226 """Create a hosted agent with custom container image."""227228 client = AIProjectClient(229 endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],230 credential=DefaultAzureCredential()231 )232233 agent = client.agents.create_version(234 agent_name="data-processor-agent",235 definition=ImageBasedHostedAgentDefinition(236 container_protocol_versions=[237 ProtocolVersionRecord(238 protocol=AgentProtocol.RESPONSES,239 version="v1"240 )241 ],242 image="myregistry.azurecr.io/data-processor:v1.0",243 cpu="2",244 memory="4Gi",245 tools=[246 {"type": "code_interpreter"},247 {"type": "file_search"}248 ],249 environment_variables={250 "AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],251 "MODEL_NAME": "gpt-4o-mini",252 "MAX_RETRIES": "3"253 }254 )255 )256257 print(f"Created hosted agent: {agent.name}")258 print(f"Version: {agent.version}")259 print(f"State: {agent.state}")260261 return agent262263if __name__ == "__main__":264 create_hosted_agent()265```266267## Async Pattern268269```python270import os271from azure.identity.aio import DefaultAzureCredential272from azure.ai.projects.aio import AIProjectClient273from azure.ai.projects.models import (274 ImageBasedHostedAgentDefinition,275 ProtocolVersionRecord,276 AgentProtocol,277)278279async def create_hosted_agent_async():280 """Create a hosted agent asynchronously."""281282 async with DefaultAzureCredential() as credential:283 async with AIProjectClient(284 endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],285 credential=credential286 ) as client:287 agent = await client.agents.create_version(288 agent_name="async-agent",289 definition=ImageBasedHostedAgentDefinition(290 container_protocol_versions=[291 ProtocolVersionRecord(292 protocol=AgentProtocol.RESPONSES,293 version="v1"294 )295 ],296 image="myregistry.azurecr.io/async-agent:latest",297 cpu="1",298 memory="2Gi"299 )300 )301 return agent302```303304## Common Errors305306| Error | Cause | Solution |307|-------|-------|----------|308| `ImagePullBackOff` | ACR pull permission denied | Grant `AcrPull` role to project's managed identity |309| `InvalidContainerImage` | Image not found | Verify image path and tag exist in ACR |310| `CapabilityHostNotFound` | No capability host configured | Create account-level capability host |311| `ProtocolVersionNotSupported` | Invalid protocol version | Use `AgentProtocol.RESPONSES` with version `"v1"` |312313## Best Practices3143151. **Version Your Images** - Use specific tags, not `latest` in production3162. **Minimal Resources** - Start with minimum CPU/memory, scale up as needed3173. **Environment Variables** - Use for all configuration, never hardcode3184. **Error Handling** - Wrap agent creation in try/except blocks3195. **Cleanup** - Delete unused agent versions to free resources320321## Reference Links322323- [Azure AI Projects SDK](https://pypi.org/project/azure-ai-projects/)324- [Hosted Agents Documentation](https://learn.microsoft.com/azure/ai-services/agents/how-to/hosted-agents)325- [Azure Container Registry](https://learn.microsoft.com/azure/container-registry/)326
Full transparency — inspect the skill content before installing.