Azure AI 호스팅 에이전트 (Python)
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>
사전 조건
호스팅 에이전트를 생성하기 전에 다음을 확인하세요:
- 컨테이너 이미지 - 빌드하여 Azure Container Registry (ACR)에 푸시
- ACR 풀 권한 - 프로젝트의 관리 ID에 ACR의
AcrPull역할 부여 - Capability Host -
enablePublicHostingEnvironment=true로 설정된 계정 수준의 Capability Host - 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 |
도구 구성
호스팅 에이전트에 도구를 추가합니다:
코드 인터프리터
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 | Capability Host가 구성되지 않음 | 계정 수준의 Capability Host 생성 |
ProtocolVersionNotSupported | 유효하지 않은 프로토콜 버전 | AgentProtocol.RESPONSES와 버전 "v1" 사용 |
모범 사례
- 이미지 버전 관리 - 프로덕션에서는
latest대신 특정 태그 사용 - 최소 리소스 - 최소 CPU/메모리로 시작하고 필요에 따라 확장
- 환경 변수 - 모든 구성에 사용하고 절대 하드코딩하지 않음
- 오류 처리 - 에이전트 생성을 try/except 블록으로 감싸기
- 정리 - 사용하지 않는 에이전트 버전을 삭제하여 리소스 확보
참고 링크
사용 시기
이 스킬은 개요에 설명된 워크플로우 또는 작업을 실행할 때 적용됩니다.
제한 사항
- 이 스킬은 작업이 위에서 설명한 범위와 명확하게 일치하는 경우에만 사용하십시오.
- 출력물을 환경별 검증, 테스트 또는 전문가 검토의 대체 수단으로 취급하지 마십시오.
- 필요한 입력, 권한, 안전 경계 또는 성공 기준이 누락된 경우 중단하고 명확히 요청하십시오.