agent-framework-azure-ai-py
microsoft/skills
Microsoft Agent Framework Python SDK를 사용하여 Azure AI Foundry에서 영구 에이전트를 구축하고, 함수 도구, 호스팅 도구, MCP 서버, 대화 스레드 및 스트리밍 응답을 지원합니다.
...모든 것을 확장하십시오에이전트 프레임워크: Azure 호스팅 에이전트
Microsoft Agent Framework Python SDK를 사용하여 Azure AI Foundry에서 영구 에이전트를 구축합니다.
아키텍처
사용자 쿼리 → AzureAIAgentsProvider → Azure AI 에이전트 서비스(상시 실행)
↓
Agent.run() / Agent.run_stream()
↓
도구: Functions | 호스팅형(코드/검색/웹) | MCP
↓
AgentThread (대화 지속성)
설치
# 전체 프레임워크 (권장)
pip install agent-framework --pre
# 또는 Azure 전용 패키지만
pip install agent-framework-azure-ai --pre
환경 변수
export AZURE_AI_PROJECT_ENDPOINT="https://.services.ai.azure.com/api/projects/" # 모든 인증 방식에 필수
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # 모든 인증 방법에 필수
export BING_CONNECTION_ID="your-bing-connection-id" # 웹 검색용
export AZURE_TOKEN_CREDENTIALS=prod # 프로덕션 환경에서 DefaultAzureCredential을 사용하는 경우에만 필수
인증 및 수명 주기
🔑 아래의 모든 코드 예제에는 다음 두 가지 규칙이 적용됩니다:
DefaultAzureCredential을우선적으로 사용하십시오. 코드 변경 없이 로컬(Azure CLI / VS Code / Developer CLI) 및 Azure(관리형 ID, 워크로드 ID)에서 모두 작동합니다. 연결 문자열, 계정/API 키는 사용하지 마십시오. 이러한 방법은 Entra 감사 및 키 순환을 우회합니다.
- 로컬 개발:
DefaultAzureCredential은별다른 설정 없이 바로 작동합니다.- 프로덕션:
AZURE_TOKEN_CREDENTIALS=prod(또는AZURE_TOKEN_CREDENTIALS=)를 설정하여 자격 증명 체인을 프로덕션에 안전한 자격 증명으로 제한하십시오.- 모든 클라이언트를 컨텍스트 매니저로 감싸서 HTTP 전송, 소켓 및 토큰 캐시가 결정론적으로 해제되도록 하십시오:
- 동기식:
(...) as client: - 비동기:
및(...)을 클라이언트로 사용하는 async DefaultAzureCredential()을 자격 증명으로 사용하는 async:(azure.identity.aio에서 제공)코드 예제에서는 이 설정을 생략할 수 있지만, 실제 운영 환경의 코드에서는 항상 두 가지 규칙을 모두 따라야 합니다.
from azure.identity.aio import AzureCliCredential, DefaultAzureCredential, ManagedIdentityCredential
# 개발 환경
credential = AzureCliCredential()
# 프로덕션
# 로컬 개발: DefaultAzureCredential. 프로덕션: AZURE_TOKEN_CREDENTIALS=prod 또는 AZURE_TOKEN_CREDENTIALS=설정
credential = DefaultAzureCredential(require_envvar=True)
# 또는 프로덕션 환경에서 특정 자격 증명을 직접 사용할 수 있습니다:
# https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes 참조
# credential = ManagedIdentityCredential()
핵심 워크플로
기본 에이전트
import asyncio
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyAgent",
instructions="You are a helpful assistant.",
)
result = await agent.run("Hello!")
print(result.text)
asyncio.run(main())
함수 도구를 사용하는 에이전트
from typing import Annotated
from pydantic import Field
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
def get_weather(
location: Annotated[str, Field(description="날씨를 조회할 도시 이름")],
) -> str:
"""지정의 위치에 대한 현재 날씨를 조회합니다."""
return f"{location}의 날씨: 72°F, 맑음"
def get_current_time() -> str:
"""현재 UTC 시간을 가져옵니다."""
from datetime import datetime, timezone
return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="WeatherAgent",
instructions="날씨 및 시간 관련 질의를 도와주세요.",
tools=[get_weather, get_current_time], # 함수를 직접 전달
)
result = await agent.run("시애틀 날씨는 어때요?")
print(result.text)
호스팅된 도구를 사용하는 에이전트
from agent_framework import (
HostedCodeInterpreterTool,
HostedFileSearchTool,
HostedWebSearchTool,
)
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MultiToolAgent",
instructions="코드를 실행하고, 파일을 검색하며, 웹을 검색할 수 있습니다.",
tools=[
HostedCodeInterpreterTool(),
HostedWebSearchTool(name="Bing"),
],
)
result = await agent.run("Python으로 20의 계승 계산하기")
print(result.text)
응답 스트리밍
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="StreamingAgent",
instructions="당신은 도움이 되는 조수입니다.",
)
print("에이전트: ", end="", flush=True)
async for chunk in agent.run_stream("짧은 이야기를 들려주세요"):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
대화 스레드
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="ChatAgent",
instructions="당신은 도움이 되는 비서입니다.",
tools=[get_weather],
)
# 대화 지속성을 위한 스레드 생성
thread = agent.get_new_thread()
# 첫 번째 대화
result1 = await agent.run("시애틀 날씨는 어때요?", thread=thread)
print(f"에이전트: {result1.text}")
# 두 번째 대화 - 컨텍스트가 유지됨
result2 = await agent.run("포틀랜드는 어때요?", thread=thread)
print(f"에이전트: {result2.text}")
# 나중에 대화를 재개할 수 있도록 스레드 ID 저장
print(f"대화 ID: {thread.conversation_id}")
구조화된 출력
from pydantic import BaseModel, ConfigDict
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
class WeatherResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
location: str
temperature: float
unit: str
conditions: str
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="StructuredAgent",
instructions="구조화된 형식으로 날씨 정보를 제공해 주세요.",
response_format=WeatherResponse,
)
result = await agent.run("시애틀의 날씨는?")
weather = WeatherResponse.model_validate_json(result.text)
print(f"{weather.location}: {weather.temperature}°{weather.unit}")
프로바이더 메서드
| 메서드 | 설명 |
|---|---|
create_agent() |
Azure AI 서비스에 새 에이전트 생성 |
get_agent(agent_id) |
ID를 사용하여 기존 에이전트 가져오기 |
as_agent(sdk_agent) |
SDK 에이전트 객체를 래핑합니다(HTTP 호출 없음) |
호스팅 도구 빠른 참조
| 도구 | 가져오기 | 목적 |
|---|---|---|
HostedCodeInterpreterTool |
from agent_framework import HostedCodeInterpreterTool |
파이썬 코드 실행 |
HostedFileSearchTool |
from agent_framework import HostedFileSearchTool |
벡터 저장소 검색 |
HostedWebSearchTool |
from agent_framework import HostedWebSearchTool |
Bing 웹 검색 |
호스팅형 MCPTool |
from agent_framework import HostedMCPTool |
서비스 관리형 MCP |
MCPStreamableHTTPTool |
from agent_framework import MCPStreamableHTTPTool |
클라이언트 관리형 MCP |
전체 예제
import asyncio
from typing import Annotated
from pydantic import BaseModel, Field
from agent_framework import (
HostedCodeInterpreterTool,
HostedWebSearchTool,
MCPStreamableHTTPTool,
)
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
def get_weather(
location: Annotated[str, Field(description="도시 이름")],
) -> str:
"""지정된 위치의 날씨를 가져옵니다."""
return f"{location}의 날씨: 72°F, 맑음"
class AnalysisResult(BaseModel):
summary: str
key_findings: list[str]
confidence: float
async def main():
async with (
AzureCliCredential() as credential,
MCPStreamableHTTPTool(
name="Docs MCP",
url="https://learn.microsoft.com/api/mcp",
) as mcp_tool,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="ResearchAssistant",
instructions="여러 능력을 갖춘 연구 조교입니다.",
tools=[
get_weather,
HostedCodeInterpreterTool(),
HostedWebSearchTool(name="Bing"),
mcp_tool,
],
)
thread = agent.get_new_thread()
# 비스트리밍
result = await agent.run(
"Python 모범 사례를 검색하고 요약해 주세요",
thread=thread,
)
print(f"응답: {result.text}")
# 스트리밍
print("\n스트리밍: ", end="")
async for chunk in agent.run_stream("예제를 계속 진행", thread=thread):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
# 구조화된 출력
result = await agent.run(
"분석 결과 분석",
thread=thread,
response_format=AnalysisResult,
)
analysis = AnalysisResult.model_validate_json(result.text)
print(f"\n신뢰도: {analysis.confidence}")
if __name__ == "__main__":
asyncio.run(main())
약정
- 항상 비동기 컨텍스트 매니저를 사용하십시오:
async with provider: - 함수를
tools=매개변수에 직접 전달하세요 (AIFunction으로 자동 변환됨) - 함수 매개변수에는
Annotated[type, Field(description=...)]를사용하십시오 - 다중 턴 대화의 경우
get_new_thread()를사용하십시오 - 서비스 관리형 MCP의 경우
HostedMCPTool을, 클라이언트 관리형 MCP의 경우MCPStreamableHTTPTool을우선적으로 사용하십시오
모범 사례
- 이 SDK는 비동기 우선 (async-first) 방식입니다.
비동기 def핸들러와async with를전반적으로 사용하십시오. - 클라이언트 및 비동기 자격 증명에는 항상 컨텍스트 관리자를 사용하십시오. 모든 클라이언트를
Client(...) as client:(동기) 또는Client(...) as client: (비동기)로감싸십시오.azure.identity.aio의비동기DefaultAzureCredential의경우,async with credential:을함께 사용하여 토큰과 전송 수단이 정리되도록 하십시오.
참조 파일
- references/tools.md: 호스팅된 도구 패턴에 대한 상세 정보
- references/mcp.md: MCP 통합 (호스팅형 + 로컬)
- references/threads.md: 스레드 및 대화 관리
- references/advanced.md: OpenAPI, 인용, 구조화된 출력
---
name: agent-framework-azure-ai-py
description: Build persistent agents on Azure AI Foundry using the Microsoft Agent Framework Python SDK, with support for function tools, hosted tools, MCP servers, conversation threads, and streaming responses.
license: MIT
---
# Agent Framework Azure Hosted Agents
Build persistent agents on Azure AI Foundry using the Microsoft Agent Framework Python SDK.
## Architecture
```
User Query → AzureAIAgentsProvider → Azure AI Agent Service (Persistent)
↓
Agent.run() / Agent.run_stream()
↓
Tools: Functions | Hosted (Code/Search/Web) | MCP
↓
AgentThread (conversation persistence)
```
## Installation
```bash
# Full framework (recommended)
pip install agent-framework --pre
# Or Azure-specific package only
pip install agent-framework-azure-ai --pre
```
## Environment Variables
```bash
export AZURE_AI_PROJECT_ENDPOINT="https://<project>.services.ai.azure.com/api/projects/<project-id>" # Required for all auth methods
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Required for all auth methods
export BING_CONNECTION_ID="your-bing-connection-id" # For web search
export AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Authentication & Lifecycle
> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
> - Local dev: `DefaultAzureCredential` works as-is.
> - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
> - Sync: `with <Client>(...) as client:`
> - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.
```python
from azure.identity.aio import AzureCliCredential, DefaultAzureCredential, ManagedIdentityCredential
# Development
credential = AzureCliCredential()
# Production
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
```
## Core Workflow
### Basic Agent
```python
import asyncio
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyAgent",
instructions="You are a helpful assistant.",
)
result = await agent.run("Hello!")
print(result.text)
asyncio.run(main())
```
### Agent with Function Tools
```python
from typing import Annotated
from pydantic import Field
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
def get_weather(
location: Annotated[str, Field(description="City name to get weather for")],
) -> str:
"""Get the current weather for a location."""
return f"Weather in {location}: 72°F, sunny"
def get_current_time() -> str:
"""Get the current UTC time."""
from datetime import datetime, timezone
return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="WeatherAgent",
instructions="You help with weather and time queries.",
tools=[get_weather, get_current_time], # Pass functions directly
)
result = await agent.run("What's the weather in Seattle?")
print(result.text)
```
### Agent with Hosted Tools
```python
from agent_framework import (
HostedCodeInterpreterTool,
HostedFileSearchTool,
HostedWebSearchTool,
)
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MultiToolAgent",
instructions="You can execute code, search files, and search the web.",
tools=[
HostedCodeInterpreterTool(),
HostedWebSearchTool(name="Bing"),
],
)
result = await agent.run("Calculate the factorial of 20 in Python")
print(result.text)
```
### Streaming Responses
```python
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="StreamingAgent",
instructions="You are a helpful assistant.",
)
print("Agent: ", end="", flush=True)
async for chunk in agent.run_stream("Tell me a short story"):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
```
### Conversation Threads
```python
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="ChatAgent",
instructions="You are a helpful assistant.",
tools=[get_weather],
)
# Create thread for conversation persistence
thread = agent.get_new_thread()
# First turn
result1 = await agent.run("What's the weather in Seattle?", thread=thread)
print(f"Agent: {result1.text}")
# Second turn - context is maintained
result2 = await agent.run("What about Portland?", thread=thread)
print(f"Agent: {result2.text}")
# Save thread ID for later resumption
print(f"Conversation ID: {thread.conversation_id}")
```
### Structured Outputs
```python
from pydantic import BaseModel, ConfigDict
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
class WeatherResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
location: str
temperature: float
unit: str
conditions: str
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="StructuredAgent",
instructions="Provide weather information in structured format.",
response_format=WeatherResponse,
)
result = await agent.run("Weather in Seattle?")
weather = WeatherResponse.model_validate_json(result.text)
print(f"{weather.location}: {weather.temperature}°{weather.unit}")
```
## Provider Methods
| Method | Description |
|--------|-------------|
| `create_agent()` | Create new agent on Azure AI service |
| `get_agent(agent_id)` | Retrieve existing agent by ID |
| `as_agent(sdk_agent)` | Wrap SDK Agent object (no HTTP call) |
## Hosted Tools Quick Reference
| Tool | Import | Purpose |
|------|--------|---------|
| `HostedCodeInterpreterTool` | `from agent_framework import HostedCodeInterpreterTool` | Execute Python code |
| `HostedFileSearchTool` | `from agent_framework import HostedFileSearchTool` | Search vector stores |
| `HostedWebSearchTool` | `from agent_framework import HostedWebSearchTool` | Bing web search |
| `HostedMCPTool` | `from agent_framework import HostedMCPTool` | Service-managed MCP |
| `MCPStreamableHTTPTool` | `from agent_framework import MCPStreamableHTTPTool` | Client-managed MCP |
## Complete Example
```python
import asyncio
from typing import Annotated
from pydantic import BaseModel, Field
from agent_framework import (
HostedCodeInterpreterTool,
HostedWebSearchTool,
MCPStreamableHTTPTool,
)
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
def get_weather(
location: Annotated[str, Field(description="City name")],
) -> str:
"""Get weather for a location."""
return f"Weather in {location}: 72°F, sunny"
class AnalysisResult(BaseModel):
summary: str
key_findings: list[str]
confidence: float
async def main():
async with (
AzureCliCredential() as credential,
MCPStreamableHTTPTool(
name="Docs MCP",
url="https://learn.microsoft.com/api/mcp",
) as mcp_tool,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="ResearchAssistant",
instructions="You are a research assistant with multiple capabilities.",
tools=[
get_weather,
HostedCodeInterpreterTool(),
HostedWebSearchTool(name="Bing"),
mcp_tool,
],
)
thread = agent.get_new_thread()
# Non-streaming
result = await agent.run(
"Search for Python best practices and summarize",
thread=thread,
)
print(f"Response: {result.text}")
# Streaming
print("\nStreaming: ", end="")
async for chunk in agent.run_stream("Continue with examples", thread=thread):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
# Structured output
result = await agent.run(
"Analyze findings",
thread=thread,
response_format=AnalysisResult,
)
analysis = AnalysisResult.model_validate_json(result.text)
print(f"\nConfidence: {analysis.confidence}")
if __name__ == "__main__":
asyncio.run(main())
```
## Conventions
- Always use async context managers: `async with provider:`
- Pass functions directly to `tools=` parameter (auto-converted to AIFunction)
- Use `Annotated[type, Field(description=...)]` for function parameters
- Use `get_new_thread()` for multi-turn conversations
- Prefer `HostedMCPTool` for service-managed MCP, `MCPStreamableHTTPTool` for client-managed
## Best Practices
1. **This SDK is async-first** — use `async def` handlers and `async with` throughout.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with Client(...) as client:` (sync) or `async with Client(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
## Reference Files
- [references/tools.md](references/tools.md): Detailed hosted tool patterns
- [references/mcp.md](references/mcp.md): MCP integration (hosted + local)
- [references/threads.md](references/threads.md): Thread and conversation management
- [references/advanced.md](references/advanced.md): OpenAPI, citations, structured outputs
모든 파일
0개 파일agent-framework-azure-ai-py 설치
스킬 파일을 다운로드하여 .claude/skills/ 디렉터리에 압축을 풀어주세요.
ZIP 다운로드저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/agent-framework-azure-ai-py # Copy SKILL.md to your .claude/skills/ directory
복사





집
