opción

agent-framework-azure-ai-py

microsoft/skills microsoft/skills

Crea agentes persistentes en Azure AI Foundry utilizando el SDK de Python de Microsoft Agent Framework, que admite herramientas de funciones, herramientas alojadas, servidores MCP, hilos de conversación y respuestas en tiempo real.

...Expandir todo
2
Tiempo actualizado 15 de septiembre de 2026

Agent Framework: Agentes alojados en Azure

Crea agentes persistentes en Azure AI Foundry utilizando el SDK de Python de Microsoft Agent Framework.

Arquitectura

Consulta del usuario → AzureAIAgentsProvider → Servicio de agentes de Azure AI (persistente)
                    ↓
              Agent.run() / Agent.run_stream()
                    ↓
              Herramientas: Funciones | Alojadas (Código/Búsqueda/Web) | MCP
                    ↓
              AgentThread (persistencia de la conversación)

Instalación

# Marco completo (recomendado)
pip install agent-framework --pre

# O solo el paquete específico de Azure
pip install agent-framework-azure-ai --pre

Variables de entorno

export AZURE_AI_PROJECT_ENDPOINT="https://.services.ai.azure.com/api/projects/"  # Requerido para todos los métodos de autenticación
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"  # Obligatorio para todos los métodos de autenticación
export BING_CONNECTION_ID="tu-id-de-conexión-a-Bing"  # Para búsquedas en la web
export AZURE_TOKEN_CREDENTIALS=prod # Obligatorio solo si se utiliza DefaultAzureCredential en producción

Autenticación y ciclo de vida

🔑 Hay dos reglas que se aplican a todos los ejemplos de código que aparecen a continuación:

  1. Da prioridad a DefaultAzureCredential. Funciona localmente (Azure CLI / VS Code / Developer CLI) y en Azure (identidad gestionada, identidad de carga de trabajo) sin necesidad de modificar el código. Evita las cadenas de conexión y las claves de cuenta o API, ya que eluden la auditoría y la rotación de Entra.
    • Desarrollo local: DefaultAzureCredential funciona tal cual.
    • Producción: establece AZURE_TOKEN_CREDENTIALS=prod (o AZURE_TOKEN_CREDENTIALS=) para limitar la cadena de credenciales a aquellas seguras para producción.
  2. Envuelve cada cliente en un gestor de contexto para que los transportes HTTP, los sockets y las cachés de tokens se liberen de forma determinista:
    • Sincrónico: con (...) como cliente:
    • Asíncrono: async con (...) como cliente: y async con DefaultAzureCredential() como credencial: (de azure.identity.aio)

Los fragmentos de código pueden abreviar esta configuración, pero el código de producción siempre debe seguir ambas reglas.

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

# Desarrollo
credential = AzureCliCredential()

# Producción
# Desarrollo local: DefaultAzureCredential. Producción: establece AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# O bien, utiliza una credencial específica directamente en producción:
# Consulta https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

Flujo de trabajo 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="Eres un asistente muy útil.",
        )
        
        result = await agent.run("¡Hola!")
        print(result.text)

asyncio.run(main())

Agente con herramientas de funciones

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="Nombre de la ciudad para la que se desea obtener la información meteorológica")],
) -> str:
    """Obtiene la información meteorológica actual de una ubicación."""
    return f"Tiempo en {location}: 72 °F, soleado"

def get_current_time() -> str:
    """Obtiene la hora UTC actual."""
    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="Ayudas con consultas sobre el tiempo y la hora.",
            tools=[get_weather, get_current_time],  # Se pasan las funciones directamente
        )
        
        result = await agent.run("¿Qué tiempo hace en Seattle?")
        print(result.text)

Agente con herramientas alojadas

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="Puedes ejecutar código, buscar archivos y realizar búsquedas en la web.",
            tools=[
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
            ],
        )
        
        result = await agent.run("Calcular el factorial de 20 en Python")
        print(result.text)

Respuestas en tiempo real

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentsProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(
            name="StreamingAgent",
            instructions="Eres un asistente muy útil.",
        )
        
        print("Agente: ", end="", flush=True)
        async for chunk in agent.run_stream("Cuéntame una historia corta"):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()

Hilos de conversación

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="Eres un asistente muy útil.",
            tools=[get_weather],
        )
        
        # Crear un hilo para la persistencia de la conversación
        thread = agent.get_new_thread()
        
        # Primer turno
        result1 = await agent.run("¿Qué tiempo hace en Seattle?", thread=thread)
        print(f"Agente: {result1.text}")
        
        # Segundo turno: se mantiene el contexto
        resultado2 = await agente.run("¿Y en Portland?", hilo=hilo)
        print(f"Agente: {resultado2.text}")
        
        # Guardar el ID del hilo para reanudarlo más tarde
        print(f"ID de la conversación: {thread.conversation_id}")

Salidas estructuradas

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="Proporciona información meteorológica en formato estructurado.",
            response_format=WeatherResponse,
        )
        
        result = await agent.run("¿Qué tiempo hace en Seattle?")
        weather = WeatherResponse.model_validate_json(result.text)
        print(f"{weather.location}: {weather.temperature}°{weather.unit}")

Métodos del proveedor

Método Descripción
create_agent() Crea un nuevo agente en el servicio de Azure AI
get_agent(agent_id) Recupera un agente existente por su ID
as_agent(sdk_agent) Envuelve el objeto SDK Agent (sin llamada HTTP)

Referencia rápida de herramientas alojadas

Herramienta Importar Finalidad
HostedCodeInterpreterTool from agent_framework import HostedCodeInterpreterTool Ejecutar código Python
HostedFileSearchTool from agent_framework import HostedFileSearchTool Buscar en almacenes de vectores
HostedWebSearchTool from agent_framework import HostedWebSearchTool Búsqueda web en Bing
HostedMCPTool from agent_framework import HostedMCPTool MCP gestionado por el servicio
MCPStreamableHTTPTool from agent_framework import MCPStreamableHTTPTool MCP gestionado por el cliente

Ejemplo 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="Nombre de la ciudad")],
) -> str:
    """Obtiene la información meteorológica de una ubicación."""
    return f"El tiempo en {location}: 72 °F, soleado"


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="Eres un asistente de investigación con múltiples capacidades.",
            tools = [
                get_weather,
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
                mcp_tool,
            ],
        )
        
        thread = agent.get_new_thread()
        
        # Sin streaming
        result = await agent.run(
            "Busca las mejores prácticas de Python y resúmelas",
            thread=thread,
        )
        print(f"Respuesta: {result.text}")
        
        # En streaming
        print("\nStreaming: ", end="")
        async for chunk in agent.run_stream("Continuar con los ejemplos", thread=thread):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()
        
        # Salida estructurada
        result = await agent.run(
            "Analizar resultados",
            thread=thread,
            response_format=AnalysisResult,
        )
        analysis = AnalysisResult.model_validate_json(result.text)
        print(f"\nConfianza: {analysis.confidence}")


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

Convenciones

  • Utiliza siempre gestores de contexto asíncronos: async con provider:
  • Pasa las funciones directamente al parámetro `tools= ` (se convierten automáticamente a `AIFunction`)
  • Utiliza Annotated[type, Field(description=...)] para los parámetros de las funciones
  • Utiliza ` get_new_thread() ` para conversaciones de varios turnos
  • Da preferencia a HostedMCPTool para MCP gestionados por el servicio, y a MCPStreamableHTTPTool para los gestionados por el cliente

Prácticas recomendadas

  1. Este SDK da prioridad a la asincronía: utiliza controladores «async def » y «async with » en todo momento.
  2. Utilice siempre gestores de contexto para clientes y credenciales asíncronas. Envuelva cada cliente con Client(...) como client: (sincrónico) o async con Client(...) como client: (asíncrono). Para DefaultAzureCredential asíncrona de azure.identity.aio, utiliza también async con credential: para que se eliminen los tokens y los transportes.

Archivos de referencia

  • references/tools.md: Patrones detallados de herramientas alojadas
  • references/mcp.md: Integración de MCP (alojada + local)
  • references/threads.md: Gestión de hilos y conversaciones
  • references/advanced.md: OpenAPI, citas, salidas estructuradas
Ver en 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 los archivos

0 archivos

Instalar agent-framework-azure-ai-py

Descarga y descomprime los archivos de habilidades en tu directorio .claude/skills/.

Descargar ZIP

Clona el repositorio y copia los archivos de la habilidad a tu proyecto.

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
Configuración rápida: Copia la carpeta de la habilidad en .claude/skills/ Claude detectará y utilizará automáticamente la habilidad
Repositorio microsoft/skills

Habilidades relacionadas

web-search
Tiempo actualizado 29 de junio de 2026
webapp-testing
Tiempo actualizado 29 de junio de 2026
lark-base
Tiempo actualizado 5 de julio de 2026
agentmail
Tiempo actualizado 29 de junio de 2026
OR