opção
LarLar Skill Ciência de dados e ML agent-framework-azure-ai-py

agent-framework-azure-ai-py

microsoft/skills microsoft/skills

Crie agentes persistentes no Azure AI Foundry usando o SDK do Microsoft Agent Framework para Python, com suporte a ferramentas de função, ferramentas hospedadas, servidores MCP, threads de conversa e respostas em streaming.

...Expandir tudo
1
Tempo atualizado 15 de Setembro de 2026

Agent Framework: Agentes hospedados no Azure

Crie agentes persistentes no Azure AI Foundry usando o SDK do Microsoft Agent Framework para Python.

Arquitetura

Consulta do usuário → AzureAIAgentsProvider → Serviço de Agente do Azure AI (Persistente)
                    ↓
              Agent.run() / Agent.run_stream()
                    ↓
              Ferramentas: Funções | Hospedadas (Código/Pesquisa/Web) | MCP
                    ↓
              AgentThread (persistência da conversa)

Instalação

# Estrutura completa (recomendado)
pip install agent-framework --pre

# Ou apenas o pacote específico do Azure
pip install agent-framework-azure-ai --pre

Variáveis de ambiente

export AZURE_AI_PROJECT_ENDPOINT="https://.services.ai.azure.com/api/projects/"  # Obrigatório para todos os métodos de autenticação
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"  # Obrigatório para todos os métodos de autenticação
export BING_CONNECTION_ID="seu-id-de-conexão-do-Bing"  # Para pesquisa na web
export AZURE_TOKEN_CREDENTIALS=prod # Obrigatório apenas se DefaultAzureCredential for usado em produção

Autenticação e ciclo de vida

🔑 Duas regras se aplicam a todos os exemplos de código abaixo:

  1. Dê preferência ao DefaultAzureCredential. Ele funciona localmente (Azure CLI / VS Code / Developer CLI) e no Azure (identidade gerenciada, identidade de carga de trabalho) sem alteração no código. Evite strings de conexão, chaves de conta/API — elas contornam a auditoria e a rotação do Entra.
    • Desenvolvimento local: o DefaultAzureCredential funciona como está.
    • Produção: defina AZURE_TOKEN_CREDENTIALS=prod (ou AZURE_TOKEN_CREDENTIALS=) para restringir a cadeia de credenciais a credenciais seguras para produção.
  2. Envolva cada cliente em um gerenciador de contexto para que transportes HTTP, soquetes e caches de tokens sejam liberados de forma determinística:
    • Sincrônica: com (...) como cliente:
    • Assíncrono: async com (...) como cliente: e async com DefaultAzureCredential() como credencial: (de azure.identity.aio)

Trechos de código podem abreviar essa configuração, mas o código de produção deve sempre seguir ambas as regras.

from azure.identity.aio import AzureCliCredential, DefaultAzureCredential, ManagedIdentityCredential

# Desenvolvimento
credential = AzureCliCredential()

# Produção
# Desenvolvimento local: DefaultAzureCredential. Produção: defina AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# Ou use uma credencial específica diretamente em produção:
# Consulte https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

Fluxo de trabalho principal

Agente básico

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="Você é um assistente prestativo.",
        )
        
        result = await agent.run("Olá!")
        print(result.text)

asyncio.run(main())

Agente com Ferramentas de Função

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="Nome da cidade para a qual se deseja obter a previsão do tempo")],
) -> str:
    """Obtém a previsão do tempo atual para um local."""
    return f"Clima em {location}: 72°F, ensolarado"

def get_current_time() -> str:
    """Obtém a hora UTC atual."""
    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="Você ajuda com consultas sobre o tempo e a hora.",
            tools=[get_weather, get_current_time],  # Passa as funções diretamente
        )
        
        result = await agent.run("Como está o tempo em Seattle?")
        print(result.text)

Agente com ferramentas hospedadas

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="Você pode executar código, pesquisar arquivos e pesquisar na web.",
            tools=[
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
            ],
        )
        
        result = await agent.run("Calcule o fatorial de 20 em Python")
        print(result.text)

Respostas em streaming

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentsProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(
            name="StreamingAgent",
            instructions="Você é um assistente prestativo.",
        )
        
        print("Agente: ", end="", flush=True)
        async for chunk in agent.run_stream("Conte-me uma história curta"):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()

Tópicos de conversa

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="Você é um assistente prestativo.",
            tools=[get_weather],
        )
        
        # Cria um thread para manter a persistência da conversa
        thread = agent.get_new_thread()
        
        # Primeira rodada
        result1 = await agent.run("Como está o tempo em Seattle?", thread=thread)
        print(f"Agente: {result1.text}")
        
        # Segunda vez — o contexto é mantido
        result2 = await agent.run("E em Portland?", thread=thread)
        print(f"Agente: {result2.text}")
        
        # Salvar o ID da thread para retomada posterior
        print(f"ID da conversa: {thread.conversation_id}")

Saídas estruturadas

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="Forneça informações meteorológicas em formato estruturado.",
            response_format=WeatherResponse,
        )
        
        result = await agent.run("Como está o tempo em Seattle?")
        weather = WeatherResponse.model_validate_json(result.text)
        print(f"{weather.location}: {weather.temperature}°{weather.unit}")

Métodos do provedor

Método Descrição
create_agent() Cria um novo agente no serviço Azure AI
get_agent(agent_id) Recuperar um agente existente pelo ID
as_agent(sdk_agent) Envolver o objeto SDK Agent (sem chamada HTTP)

Referência rápida das ferramentas hospedadas

Ferramenta Importar Finalidade
HostedCodeInterpreterTool from agent_framework import HostedCodeInterpreterTool Executar código Python
HostedFileSearchTool from agent_framework import HostedFileSearchTool Pesquisar bancos de dados vetoriais
HostedWebSearchTool from agent_framework import HostedWebSearchTool Pesquisa na web do Bing
HostedMCPTool from agent_framework import HostedMCPTool MCP gerenciado por serviço
MCPStreamableHTTPTool from agent_framework import MCPStreamableHTTPTool MCP gerenciado pelo cliente

Exemplo completo

import asyncio
from typing import Annotated
from pydantic import BaseModel, Field
from agent_framework import (
    HostedCodeInterpreterTool,
    HostedWebSearchTool,
    MCPStreamableHTTPTool,
)
de agent_framework.azure import AzureAIAgentsProvider
de azure.identity.aio import AzureCliCredential


def get_weather(
    location: Annotated[str, Field(description="Nome da cidade")],
) -> str:
    """Obtém a previsão do tempo para um local."""
    return f"Clima em {location}: 72°F, ensolarado"


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="Você é um assistente de pesquisa com várias capacidades.",
            tools=[
                get_weather,
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
                mcp_tool,
            ],
        )
        
        thread = agent.get_new_thread()
        
        # Sem streaming
        result = await agent.run(
            "Pesquise as melhores práticas de Python e resuma",
            thread=thread,
        )
        print(f"Resposta: {result.text}")
        
        # Transmissão contínua
        print("\nTransmissão contínua: ", end="")
        async for chunk in agent.run_stream("Continue com exemplos", thread=thread):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()
        
        # Saída estruturada
        result = await agent.run(
            "Analisar resultados",
            thread=thread,
            response_format=AnalysisResult,
        )
        analysis = AnalysisResult.model_validate_json(result.text)
        print(f"\nConfiança: {analysis.confidence}")


if __name__ == "__main__":
    asyncio.run(main())

Convenções

  • Sempre use gerenciadores de contexto assíncronos: async com provider:
  • Passe funções diretamente para o parâmetro `tools=` (convertido automaticamente para `AIFunction`)
  • Use ` Annotated[type, Field(description=...)]` para parâmetros de função
  • Use get_new_thread() para conversas com várias trocas de mensagens
  • Dê preferência ao HostedMCPTool para MCP gerenciado pelo serviço e ao MCPStreamableHTTPTool para MCP gerenciado pelo cliente

Práticas recomendadas

  1. Este SDK prioriza a assíncronia — use manipuladores ` async def ` e a sintaxe `async` em todo o código.
  2. Sempre use gerenciadores de contexto para clientes e credenciais assíncronas. Envolva cada cliente com Client(...) como client: (síncrono) ou async com Client(...) como client: (assíncrono). Para o DefaultAzureCredential assíncrono do azure.identity.aio, use também async com credential: para que os tokens e transportes sejam liberados.

Arquivos de referência

  • references/tools.md: Padrões detalhados de ferramentas hospedadas
  • references/mcp.md: integração com o MCP (hospedado + local)
  • references/threads.md: Gerenciamento de tópicos e conversas
  • references/advanced.md: OpenAPI, citações, saídas estruturadas
Ver no GitHub
---
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

Todos os arquivos

0 arquivos

Instalar agent-framework-azure-ai-py

Baixe e descompacte os arquivos de habilidades no diretório .claude/skills/.

Baixar ZIP

Clone o repositório e copie os arquivos da habilidade para o seu projeto.

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

Copiar Copiar
Configuração rápida: Copie a pasta da habilidade para .claude/skills/ O Claude detectará e utilizará automaticamente a habilidade
Repositório microsoft/skills

Habilidades relacionadas

web-search
Tempo atualizado 29 de Junho de 2026
webapp-testing
Tempo atualizado 29 de Junho de 2026
lark-base
Tempo atualizado 5 de Julho de 2026
agentmail
Tempo atualizado 29 de Junho de 2026
OR