Agent Framework Azure Hosted Agents
Construa agentes persistentes no Azure AI Foundry usando o SDK Python do Microsoft Agent Framework.
Arquitetura
User Query → AzureAIAgentsProvider → Azure AI Agent Service (Persistente)
↓
Agent.run() / Agent.run_stream()
↓
Ferramentas: Funções | Hospedadas (Código/Busca/Web) | MCP
↓
AgentThread (persistência de conversação)
Instalação
# Framework completo (recomendado)
pip install agent-framework --pre
# Apenas o pacote específico do Azure
pip install agent-framework-azure-ai --pre
Variáveis de Ambiente
export AZURE_AI_PROJECT_ENDPOINT="https://<projeto>.services.ai.azure.com/api/projects/<id-do-projeto>" # 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-conexao-bing" # Para busca 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:
- Prefira
DefaultAzureCredential. Funciona localmente (Azure CLI / VS Code / Developer CLI) e no Azure (identidade gerenciada, identidade de carga de trabalho) sem alteração de código. Evite cadeias de conexão, chaves de conta/API — elas ignoram a auditoria e rotação do Entra.
- Desenvolvimento local:
DefaultAzureCredentialfunciona como está.- Produção: defina
AZURE_TOKEN_CREDENTIALS=prod(ouAZURE_TOKEN_CREDENTIALS=<credencial_especifica>) para restringir a cadeia de credenciais apenas a credenciais seguras para produção.- Envolva cada cliente em um gerenciador de contexto para que transportes HTTP, sockets e caches de token sejam liberados deterministamente:
- Síncrono:
with <Client>(...) as client:- Assíncrono:
async with <Client>(...) as client:easync with DefaultAzureCredential() as credential:(deazure.identity.aio)Os trechos podem abreviar esta 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=<credencial_especifica>
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="MeuAgente",
instructions="Você é um assistente útil.",
)
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 obter o clima")],
) -> str:
"""Obter o clima atual para um local."""
return f"Clima em {location}: 22°C, ensolarado"
def get_current_time() -> str:
"""Obter 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="AgenteClima",
instructions="Você ajuda com consultas sobre clima e hora.",
tools=[get_weather, get_current_time], # Passe funções diretamente
)
result = await agent.run("Qual é o clima 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="AgenteMultiFerramenta",
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="AgenteStreaming",
instructions="Você é um assistente útil.",
)
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()
Threads de Conversação
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="AgenteChat",
instructions="Você é um assistente útil.",
tools=[get_weather],
)
# Criar thread para persistência da conversação
thread = agent.get_new_thread()
# Primeira interação
result1 = await agent.run("Qual é o clima em Seattle?", thread=thread)
print(f"Agente: {result1.text}")
# Segunda interação - o contexto é mantido
result2 = await agent.run("E em Portland?", thread=thread)
print(f"Agente: {result2.text}")
# Salvar ID da thread para retomada posterior
print(f"ID da Conversação: {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="AgenteEstruturado",
instructions="Forneça informações climáticas em formato estruturado.",
response_format=WeatherResponse,
)
result = await agent.run("Clima 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() | Criar novo agente no serviço Azure AI |
get_agent(agent_id) | Recuperar agente existente por ID |
as_agent(sdk_agent) | Envolver objeto Agent do SDK (sem chamada HTTP) |
Referência Rápida de Ferramentas Hospedadas
| Ferramenta | Importação | Propósito |
|---|---|---|
HostedCodeInterpreterTool | from agent_framework import HostedCodeInterpreterTool | Executar código Python |
HostedFileSearchTool | from agent_framework import HostedFileSearchTool | Pesquisar em armazenamentos vetoriais |
HostedWebSearchTool | from agent_framework import HostedWebSearchTool | Busca na web Bing |
HostedMCPTool | from agent_framework import HostedMCPTool | MCP gerenciado pelo 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,
)
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
def get_weather(
location: Annotated[str, Field(description="Nome da cidade")],
) -> str:
"""Obter clima para um local."""
return f"Clima em {location}: 22°C, 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="AssistentePesquisa",
instructions="Você é um assistente de pesquisa com múltiplas capacidades.",
tools=[
get_weather,
HostedCodeInterpreterTool(),
HostedWebSearchTool(name="Bing"),
mcp_tool,
],
)
thread = agent.get_new_thread()
# Sem streaming
result = await agent.run(
"Pesquise por melhores práticas em Python e resuma",
thread=thread,
)
print(f"Resposta: {result.text}")
# Streaming
print("\nStreaming: ", 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(
"Analise os 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 with provider: - Passe funções diretamente para o parâmetro
tools=(convertidas automaticamente para AIFunction) - Use
Annotated[type, Field(description=...)]para parâmetros de função - Use
get_new_thread()para conversas de múltiplas interações - Prefira
HostedMCPToolpara MCP gerenciado pelo serviço,MCPStreamableHTTPToolpara MCP gerenciado pelo cliente
Melhores Práticas
- Este SDK é assíncrono primeiro — use manipuladores
async defeasync withem todo o código. - Sempre use gerenciadores de contexto para clientes e credenciais assíncronas. Envolva cada cliente em
with Client(...) as client:(síncrono) ouasync with Client(...) as client:(assíncrono). ParaDefaultAzureCredentialassíncrono deazure.identity.aio, também useasync with credential:para que tokens e transportes sejam limpos.
Arquivos de Referência
- references/tools.md: Padrões detalhados de ferramentas hospedadas
- references/mcp.md: Integração MCP (hospedada + local)
- references/threads.md: Gerenciamento de threads e conversação
- references/advanced.md: OpenAPI, citações, saídas estruturadas