Option
HeimHeim Skill Datenwissenschaft und ML agent-framework-azure-ai-py

agent-framework-azure-ai-py

microsoft/skills microsoft/skills

Erstellen Sie persistente Agenten in Azure AI Foundry mithilfe des Microsoft Agent Framework Python SDK, das Unterstützung für Function-Tools, gehostete Tools, MCP-Server, Konversations-Threads und Streaming-Antworten bietet.

...Alle erweitern
2
Zeit aktualisiert 15. September 2026

Agent Framework – Von Azure gehostete Agenten

Erstellen Sie mit dem Microsoft Agent Framework Python SDK dauerhafte Agenten auf Azure AI Foundry.

Architektur

Benutzeranfrage → AzureAIAgentsProvider → Azure AI Agent Service (persistent)
                    ↓
              Agent.run() / Agent.run_stream()
                    ↓
              Tools: Functions | Hosted (Code/Search/Web) | MCP
                    ↓
              AgentThread (Persistenz der Konversation)

Installation

# Vollständiges Framework (empfohlen)
pip install agent-framework --pre

# Oder nur das Azure-spezifische Paket
pip install agent-framework-azure-ai --pre

Umgebungsvariablen

export AZURE_AI_PROJECT_ENDPOINT="https://.services.ai.azure.com/api/projects/"  # Erforderlich für alle Authentifizierungsmethoden
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"  # Erforderlich für alle Authentifizierungsmethoden
export BING_CONNECTION_ID="your-bing-connection-id"  # Für die Websuche
export AZURE_TOKEN_CREDENTIALS=prod # Nur erforderlich, wenn „DefaultAzureCredential“ in der Produktion verwendet wird

Authentifizierung und Lebenszyklus

🔑 Für alle folgenden Code-Beispiele gelten zwei Regeln:

  1. Bevorzugen Sie „DefaultAzureCredential“. Es funktioniert lokal (Azure CLI / VS Code / Developer CLI) und in Azure (verwaltete Identität, Workload-Identität) ohne Codeänderung. Vermeiden Sie Verbindungszeichenfolgen, Konto- und API-Schlüssel – diese umgehen die Entra-Überprüfung und -Rotation.
    • Lokale Entwicklung: „DefaultAzureCredential“ funktioniert unverändert.
    • Produktion: Setzen Sie AZURE_TOKEN_CREDENTIALS=prod (oder AZURE_TOKEN_CREDENTIALS=), um die Anmeldeinformationskette auf produktionssichere Anmeldeinformationen zu beschränken.
  2. Hüllen Sie jeden Client in einen Kontextmanager, damit HTTP-Transporte, Sockets und Token-Caches deterministisch freigegeben werden:
    • Synchron: mit ` (...)` als Client:
    • Asynchron: async mit (...) als Client: und async mit DefaultAzureCredential() als Anmeldeinformationen: (aus azure.identity.aio)

Code-Schnipsel können diese Konfiguration zwar verkürzen, aber Produktionscode sollte stets beide Regeln befolgen.

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

# Entwicklung
credential = AzureCliCredential()

# Produktion
# Lokale Entwicklung: DefaultAzureCredential. Produktion: AZURE_TOKEN_CREDENTIALS=prod oder AZURE_TOKEN_CREDENTIALS=setzen 
credential = DefaultAzureCredential(require_envvar=True)
# Oder verwenden Sie in der Produktion direkt eine bestimmte Anmeldeinformation:
# Siehe https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

Kern-Workflow

Basis-Agent

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="Du bist ein hilfsbereiter Assistent.",
        )
        
        result = await agent.run("Hallo!")
        print(result.text)

asyncio.run(main())

Agent mit Funktionstools

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="Name der Stadt, für die das Wetter abgerufen werden soll")],
) -> str:
    """Das aktuelle Wetter für einen Ort abrufen."""
    return f"Wetter in {location}: 72°F, sonnig"

def get_current_time() -> str:
    """Die aktuelle UTC-Zeit abrufen."""
    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="Du hilfst bei Wetter- und Zeitabfragen.",
            tools=[get_weather, get_current_time],  # Funktionen direkt übergeben
        )
        
        result = await agent.run("Wie ist das Wetter in Seattle?")
        print(result.text)

Agent mit gehosteten Tools

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="Sie können Code ausführen, nach Dateien suchen und im Internet suchen.",
            tools=[
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
            ],
        )
        
        result = await agent.run("Berechne die Fakultät von 20 in Python")
        print(result.text)

Streaming von Antworten

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentsProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(
            name="StreamingAgent",
            instructions="Du bist ein hilfsbereiter Assistent.",
        )
        
        print("Agent: ", end="", flush=True)
        async for chunk in agent.run_stream("Erzähl mir eine kurze Geschichte"):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()

Konversations-Threads

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="Du bist ein hilfsbereiter Assistent.",
            tools=[get_weather],
        )
        
        # Thread für die Persistenz der Konversation erstellen
        thread = agent.get_new_thread()
        
        # Erster Zug
        result1 = await agent.run("Wie ist das Wetter in Seattle?", thread=thread)
        print(f"Agent: {result1.text}")
        
        # Zweiter Zug – der Kontext bleibt erhalten
        result2 = await agent.run("Wie sieht es in Portland aus?", thread=thread)
        print(f"Agent: {result2.text}")
        
        # Thread-ID für spätere Fortsetzung speichern
        print(f"Konversations-ID: {thread.conversation_id}")

Strukturierte Ausgaben

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="Liefern Sie Wetterinformationen in strukturiertem Format.",
            response_format=WeatherResponse,
        )
        
        result = await agent.run("Wie ist das Wetter in Seattle?")
        weather = WeatherResponse.model_validate_json(result.text)
        print(f"{weather.location}: {weather.temperature}°{weather.unit}")

Anbieter-Methoden

Methode Beschreibung
create_agent() Neuen Agenten im Azure AI-Dienst erstellen
get_agent(agent_id) Vorhandenen Agenten anhand der ID abrufen
as_agent(sdk_agent) SDK-Agent-Objekt verpacken (kein HTTP-Aufruf)

Schnellreferenz zu gehosteten Tools

Tool Import Zweck
HostedCodeInterpreterTool from agent_framework import HostedCodeInterpreterTool Python-Code ausführen
HostedFileSearchTool from agent_framework import HostedFileSearchTool Vektorspeicher durchsuchen
HostedWebSearchTool from agent_framework import HostedWebSearchTool Bing-Websuche
HostedMCPTool from agent_framework import HostedMCPTool Dienstgesteuertes MCP
MCPStreamableHTTPTool from agent_framework import MCPStreamableHTTPTool Client-verwaltetes MCP

Vollständiges Beispiel

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="Name der Stadt")],
) -> str:
    """Wetterdaten für einen Ort abrufen."""
    return f"Wetter in {location}: 72°F, sonnig"


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="Du bist ein wissenschaftlicher Mitarbeiter mit vielfältigen Fähigkeiten.",
            tools=[
                get_weather,
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
                mcp_tool,
            ],
        )
        
        thread = agent.get_new_thread()
        
        # Nicht-Streaming
        result = await agent.run(
            "Nach Python-Best-Practices suchen und zusammenfassen",
            thread=thread,
        )
        print(f"Antwort: {result.text}")
        
        # Streaming
        print("\nStreaming: ", end="")
        async for chunk in agent.run_stream("Weiter mit den Beispielen", thread=thread):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()
        
        # Strukturierte Ausgabe
        result = await agent.run(
            "Ergebnisse analysieren",
            thread=thread,
            response_format=AnalysisResult,
        )
        analysis = AnalysisResult.model_validate_json(result.text)
        print(f"\nKonfidenz: {analysis.confidence}")


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

Konventionen

  • Verwenden Sie stets asynchrone Kontextmanager: ` async with provider:`
  • Funktionen direkt an den Parameter `tools=` übergeben (wird automatisch in `AIFunction` konvertiert)
  • Verwende ` Annotated[type, Field(description=...)]` für Funktionsparameter
  • Verwenden Sie ` get_new_thread() ` für mehrrundige Konversationen
  • Bevorzugen Sie „HostedMCPTool“ für serviceverwaltete MCP und „MCPStreamableHTTPTool“ für clientverwaltete

Bewährte Vorgehensweisen

  1. Dieses SDK ist „async-first“ – verwenden Sie „async def “-Handler und „async“ durchgehend.
  2. Verwenden Sie stets Kontextmanager für Clients und asynchrone Anmeldeinformationen. Umschließen Sie jeden Client mit `Client(...) as client: ` (synchron) oder `async` mit `Client(...) as client: ` (asynchron). Verwenden Sie für `async DefaultAzureCredential ` aus ` azure.identity.aio` zusätzlich `async with credential:`, damit Tokens und Transporte bereinigt werden.

Referenzdateien

  • references/tools.md: Detaillierte Muster für gehostete Tools
  • references/mcp.md: MCP-Integration (gehostet + lokal)
  • references/threads.md: Thread- und Konversationsverwaltung
  • references/advanced.md: OpenAPI, Zitate, strukturierte Ausgaben
Auf GitHub ansehen
---
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

Alle Dateien

0 Dateien

agent-framework-azure-ai-py installieren

Laden Sie die Skill-Dateien herunter und entpacken Sie sie in Ihr Verzeichnis „.claude/skills/“.

ZIP herunterladen

Klonen Sie das Repository und kopieren Sie die Skill-Dateien in Ihr Projekt.

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

Kopieren Kopieren
Schnelle Einrichtung: Kopiere den Skill-Ordner nach „.claude/skills/“. Claude erkennt den Skill automatisch und nutzt ihn.
Repository microsoft/skills

Ähnliche Skills

web-search
Zeit aktualisiert 29. Juni 2026
webapp-testing
Zeit aktualisiert 29. Juni 2026
lark-base
Zeit aktualisiert 5. Juli 2026
agentmail
Zeit aktualisiert 29. Juni 2026
OR