# Microsoft-Agent-Framework-Integration

Verwenden Sie das Copilot SDK als Agentanbieter innerhalb des Microsoft Agent Framework (MAF), um Multi-Agent-Workflows zusammen mit Azure OpenAI, Anthropic und anderen Anbietern zu verfassen.

<!-- markdownlint-disable GHD046 GHD005 -->

<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->

## Übersicht

Das Microsoft Agent Framework ist der einheitliche Nachfolger von Semantischer Kernel und AutoGen. Es bietet eine Standardschnittstelle zum Erstellen, Orchestrieren und Bereitstellen von KI-Agents. Mit dedizierten Integrationspaketen können Sie einen Copilot SDK-Client als erstklassigen MAF-Agent umschließen – austauschbar mit jedem anderen Agent-Anbieter im Framework.

| Konzept                       | Beschreibung                                                                                         |
| ----------------------------- | ---------------------------------------------------------------------------------------------------- |
| **Microsoft Agent Framework** | Open-Source-Framework für die Einzel- und Multi-Agent-Orchestrierung in .NET und Python              |
| **Agentanbieter**             | Ein Back-End, das einen Agent unterstützt (Copilot, Azure OpenAI, Anthropic usw.)                    |
| **Orchestrator**              | Eine MAF-Komponente, die Agenten in sequenziellen, gleichzeitigen oder Übergabeworkflows koordiniert |
| **A2A-Protokoll**             | Vom Framework unterstützte Agent-zu-Agent-Kommunikationsstandard                                     |

> \[!NOTE]
> MAF-Integrationspakete sind für **.NET** und **Python** verfügbar. Verwenden Sie für TypeScript, Go, Java und Rust das Copilot SDK direkt – die standardmäßigen SDK-APIs bieten bereits Toolaufrufe, Streaming und benutzerdefinierte Agents.

## Voraussetzungen

Bevor Sie beginnen, stellen Sie sicher, dass Sie folgendes haben:

* Ein funktionierendes [Erstellen Sie Ihre erste Copilot-gestützte App](/de/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/getting-started) in Ihrer Wahlsprache
* Ein GitHub Copilot-Abonnement (Einzel-, Geschäfts- oder Unternehmensabonnement)
* Die Copilot-CLI ist installiert oder über die im SDK gebündelte CLI verfügbar

## Installation

Installieren Sie das Copilot SDK zusammen mit dem MAF-Integrationspaket für Ihre Sprache:

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

```shell
dotnet add package GitHub.Copilot.SDK
dotnet add package Microsoft.Agents.AI.GitHub.Copilot --prerelease
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

```shell
pip install copilot-sdk agent-framework-github-copilot
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

> \[!NOTE]
> Das Java SDK verfügt nicht über ein dediziertes MAF-Integrationspaket. Verwenden Sie das standardmäßige Copilot SDK direkt – sie stellt Toolaufrufe, Streaming und benutzerdefinierte Agents sofort bereit.

```xml
<!-- Maven -->
<!-- Set copilot.sdk.version to the version published in java/README.md / Maven Central -->
<dependency>
    <groupId>com.github</groupId>
    <artifactId>copilot-sdk-java</artifactId>
    <version>${copilot.sdk.version}</version>
</dependency>
```

</div>

</div>

## Grundlegende Nutzung

Schließen Sie den Copilot SDK-Client als MAF-Agent mit einem einzelnen Methodenaufruf um. Der resultierende Agent entspricht der Standardschnittstelle des Frameworks und kann überall verwendet werden, wo ein MAF-Agent erwartet wird.

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

<!-- docs-validate: skip -->

```csharp
using GitHub.Copilot;
using Microsoft.Agents.AI;

await using var copilotClient = new CopilotClient();
await copilotClient.StartAsync();

// Wrap as a MAF agent
AIAgent agent = copilotClient.AsAIAgent();

// Use the standard MAF interface
string response = await agent.RunAsync("Explain how dependency injection works in ASP.NET Core");
Console.WriteLine(response);
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

<!-- docs-validate: skip -->

```python
from agent_framework.github import GitHubCopilotAgent

async def main():
    agent = GitHubCopilotAgent(
        default_options={
            "instructions": "You are a helpful coding assistant.",
        }
    )

    async with agent:
        result = await agent.run("Explain how dependency injection works in FastAPI")
        print(result)
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

<!-- docs-validate: skip -->

```java
import com.github.copilot.CopilotClient;
import com.github.copilot.rpc.*;

var client = new CopilotClient();
client.start().get();

var session = client.createSession(new SessionConfig()
    .setModel("gpt-5.4")
    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();

var response = session.sendAndWait(new MessageOptions()
    .setPrompt("Explain how dependency injection works in Spring Boot")).get();
System.out.println(response.getData().content());

client.stop().get();
```

</div>

</div>

## Hinzufügen von benutzerdefinierten Tools

Erweitern Sie Ihre Copilot-Agent mit benutzerdefinierten Funktionstools. Tools, die über das Standard-Copilot SDK definiert sind, sind automatisch verfügbar, wenn der Agent innerhalb von MAF ausgeführt wird.

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

<!-- docs-validate: skip -->

```csharp
using GitHub.Copilot;
using Microsoft.Extensions.AI;
using Microsoft.Agents.AI;

// Define a custom tool
AIFunction weatherTool = CopilotTool.DefineTool(
    (string location) => $"The weather in {location} is sunny with a high of 25°C.",
    factoryOptions: new AIFunctionFactoryOptions
    {
        Name = "GetWeather",
        Description = "Get the current weather for a given location.",
    }
);

await using var copilotClient = new CopilotClient();
await copilotClient.StartAsync();

// Create agent with tools
AIAgent agent = copilotClient.AsAIAgent(new AIAgentOptions
{
    Tools = new[] { weatherTool },
});

string response = await agent.RunAsync("What's the weather like in Seattle?");
Console.WriteLine(response);
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

<!-- docs-validate: skip -->

```python
from agent_framework.github import GitHubCopilotAgent

def get_weather(location: str) -> str:
    """Get the current weather for a given location."""
    return f"The weather in {location} is sunny with a high of 25°C."

async def main():
    agent = GitHubCopilotAgent(
        default_options={
            "instructions": "You are a helpful assistant with access to weather data.",
        },
        tools=[get_weather],
    )

    async with agent:
        result = await agent.run("What's the weather like in Seattle?")
        print(result)
```

</div>

</div>

Sie können auch die systemeigene Tooldefinition Copilot SDK zusammen mit MAF-Tools verwenden:

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

```typescript
import { CopilotClient, defineTool } from "@github/copilot-sdk";

const getWeather = defineTool("GetWeather", {
    description: "Get the current weather for a given location.",
    parameters: {
        type: "object",
        properties: {
            location: { type: "string", description: "City name" },
        },
        required: ["location"],
    },
    handler: async ({ location }: { location: string }) =>
        `The weather in ${location} is sunny, 25°C.`,
});

const client = new CopilotClient();
const session = await client.createSession({
    model: "gpt-5.4",
    tools: [getWeather],
    onPermissionRequest: async () => ({ kind: "approve-once" }),
});

await session.sendAndWait({ prompt: "What's the weather like in Seattle?" });
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

```java
import com.github.copilot.CopilotClient;
import com.github.copilot.rpc.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

var getWeather = ToolDefinition.create(
    "GetWeather",
    "Get the current weather for a given location.",
    Map.of(
        "type", "object",
        "properties", Map.of(
            "location", Map.of("type", "string", "description", "City name")),
        "required", List.of("location")),
    invocation -> {
        var location = (String) invocation.getArguments().get("location");
        return CompletableFuture.completedFuture(
            "The weather in " + location + " is sunny, 25°C.");
    });

try (var client = new CopilotClient()) {
    client.start().get();

    var session = client.createSession(new SessionConfig()
        .setModel("gpt-5.4")
        .setTools(List.of(getWeather))
        .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
    ).get();

    session.sendAndWait(new MessageOptions()
        .setPrompt("What's the weather like in Seattle?")).get();
}
```

</div>

</div>

## Mehragenten-Workflows

Der Hauptvorteil der MAF-Integration besteht darin, Copilot gemeinsam mit anderen Agent-Anbietern in orchestrierten Workflows zu kombinieren. Verwenden Sie die integrierten Orchestratoren des Frameworks, um Pipelines zu erstellen, in denen verschiedene Agents unterschiedliche Schritte ausführen.

### Sequenzieller Workflow

Führen Sie Agenten nacheinander aus, übergeben Sie die Ausgabe von einem an den nächsten:

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

<!-- docs-validate: skip -->

```csharp
using GitHub.Copilot;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Orchestration;

await using var copilotClient = new CopilotClient();
await copilotClient.StartAsync();

// Copilot agent for code review
AIAgent reviewer = copilotClient.AsAIAgent(new AIAgentOptions
{
    Instructions = "You review code for bugs, security issues, and best practices. Be thorough.",
});

// Azure OpenAI agent for generating documentation
AIAgent documentor = AIAgent.FromOpenAI(new OpenAIAgentOptions
{
    Model = "gpt-5.4",
    Instructions = "You write clear, concise documentation for code changes.",
});

// Compose in a sequential pipeline
var pipeline = new SequentialOrchestrator(new[] { reviewer, documentor });

string result = await pipeline.RunAsync(
    "Review and document this pull request: added retry logic to the HTTP client"
);
Console.WriteLine(result);
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

<!-- docs-validate: skip -->

```python
from agent_framework.github import GitHubCopilotAgent
from agent_framework.openai import OpenAIAgent
from agent_framework.orchestration import SequentialOrchestrator

async def main():
    # Copilot agent for code review
    reviewer = GitHubCopilotAgent(
        default_options={
            "instructions": "You review code for bugs, security issues, and best practices.",
        }
    )

    # OpenAI agent for documentation
    documentor = OpenAIAgent(
        model="gpt-5.4",
        instructions="You write clear, concise documentation for code changes.",
    )

    # Compose in a sequential pipeline
    pipeline = SequentialOrchestrator(agents=[reviewer, documentor])

    async with pipeline:
        result = await pipeline.run(
            "Review and document this PR: added retry logic to the HTTP client"
        )
        print(result)
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

<!-- docs-validate: skip -->

```java
import com.github.copilot.CopilotClient;
import com.github.copilot.rpc.*;

// Java uses the standard SDK directly — no MAF orchestrator needed
var client = new CopilotClient();
client.start().get();

// Step 1: Code review session
var reviewer = client.createSession(new SessionConfig()
    .setModel("gpt-5.4")
    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();

var review = reviewer.sendAndWait(new MessageOptions()
    .setPrompt("Review this PR for bugs, security issues, and best practices: "
        + "added retry logic to the HTTP client")).get();

// Step 2: Documentation session using review output
var documentor = client.createSession(new SessionConfig()
    .setModel("gpt-5.4")
    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();

var docs = documentor.sendAndWait(new MessageOptions()
    .setPrompt("Write documentation for these changes: " + review.getData().content())).get();
System.out.println(docs.getData().content());

client.stop().get();
```

</div>

</div>

### Gleichzeitiger Workflow

Führen Sie mehrere Agents parallel aus, und aggregieren Sie ihre Ergebnisse:

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

<!-- docs-validate: skip -->

```csharp
using GitHub.Copilot;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Orchestration;

await using var copilotClient = new CopilotClient();
await copilotClient.StartAsync();

AIAgent securityReviewer = copilotClient.AsAIAgent(new AIAgentOptions
{
    Instructions = "Focus exclusively on security vulnerabilities and risks.",
});

AIAgent performanceReviewer = copilotClient.AsAIAgent(new AIAgentOptions
{
    Instructions = "Focus exclusively on performance bottlenecks and optimization opportunities.",
});

// Run both reviews concurrently
var concurrent = new ConcurrentOrchestrator(new[] { securityReviewer, performanceReviewer });

string combinedResult = await concurrent.RunAsync(
    "Analyze this database query module for issues"
);
Console.WriteLine(combinedResult);
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

<!-- docs-validate: skip -->

```java
import com.github.copilot.CopilotClient;
import com.github.copilot.rpc.*;
import java.util.concurrent.CompletableFuture;

// Java uses CompletableFuture for concurrent execution
var client = new CopilotClient();
client.start().get();

var securitySession = client.createSession(new SessionConfig()
    .setModel("gpt-5.4")
    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();

var perfSession = client.createSession(new SessionConfig()
    .setModel("gpt-5.4")
    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();

// Run both reviews concurrently
var securityFuture = securitySession.sendAndWait(new MessageOptions()
    .setPrompt("Focus on security vulnerabilities in this database query module"));
var perfFuture = perfSession.sendAndWait(new MessageOptions()
    .setPrompt("Focus on performance bottlenecks in this database query module"));

CompletableFuture.allOf(securityFuture, perfFuture).get();

System.out.println("Security: " + securityFuture.get().getData().content());
System.out.println("Performance: " + perfFuture.get().getData().content());

client.stop().get();
```

</div>

</div>

## Antworten bei Streaming-Diensten

Beim Erstellen interaktiver Anwendungen sollten Antworten von Streaming-Agenten verwendet werden, um die Echtzeitausgabe anzuzeigen. Die MAF-Integration behält die Streamingfunktionen des Copilot SDK bei.

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="dotnet" data-label=".NET"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">.NET</div>

<!-- docs-validate: skip -->

```csharp
using GitHub.Copilot;
using Microsoft.Agents.AI;

await using var copilotClient = new CopilotClient();
await copilotClient.StartAsync();

AIAgent agent = copilotClient.AsAIAgent(new AIAgentOptions
{
    Streaming = true,
});

await foreach (var chunk in agent.RunStreamingAsync("Write a quicksort implementation in C#"))
{
    Console.Write(chunk);
}
Console.WriteLine();
```

</div>

<div class="ghd-codetab" data-lang="python" data-label="Python"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Python</div>

<!-- docs-validate: skip -->

```python
from agent_framework.github import GitHubCopilotAgent

async def main():
    agent = GitHubCopilotAgent(
        default_options={"streaming": True}
    )

    async with agent:
        async for chunk in agent.run_streaming("Write a quicksort in Python"):
            print(chunk, end="", flush=True)
        print()
```

</div>

</div>

Sie können auch direkt über das Copilot SDK ohne MAF streamen:

<div class="ghd-codetabs">
<div class="ghd-codetab" data-lang="typescript" data-label="TypeScript"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">TypeScript</div>

```typescript
import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();
const session = await client.createSession({
    model: "gpt-5.4",
    streaming: true,
    onPermissionRequest: async () => ({ kind: "approve-once" }),
});

session.on("assistant.message_delta", (event) => {
    process.stdout.write(event.data.deltaContent ?? "");
});

await session.sendAndWait({ prompt: "Write a quicksort implementation in TypeScript" });
```

</div>

<div class="ghd-codetab" data-lang="java" data-label="Java"><div class="ghd-codetab-fallback-label" role="heading" aria-level="3">Java</div>

<!-- docs-validate: skip -->

```java
import com.github.copilot.CopilotClient;
import com.github.copilot.rpc.*;

var client = new CopilotClient();
client.start().get();

var session = client.createSession(new SessionConfig()
    .setModel("gpt-5.4")
    .setStreaming(true)
    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();

session.on(AssistantMessageDeltaEvent.class, event -> {
    System.out.print(event.getData().deltaContent());
});

session.sendAndWait(new MessageOptions()
    .setPrompt("Write a quicksort implementation in Java")).get();
System.out.println();

client.stop().get();
```

</div>

</div>

## Konfigurationsreferenz

### MAF-Agentoptionen

| Eigentum                        | Typ                     | Beschreibung                                                        |
| ------------------------------- | ----------------------- | ------------------------------------------------------------------- |
| `Instructions` / `instructions` | `string`                | Systemaufforderung für den Agent                                    |
| `Tools` / `tools`               | `AIFunction[]` / `list` | Benutzerdefinierte Funktionstools, die für den Agent verfügbar sind |
| `Streaming` / `streaming`       | `bool`                  | Streamingantworten aktivieren                                       |
| `Model` / `model`               | `string`                | Überschreiben des Standardmodells                                   |

### Copilot SDK-Optionen (übergeben)

Alle Standardoptionen [Erstellen Sie Ihre erste Copilot-gestützte App](/de/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/getting-started) stehen beim Erstellen des zugrunde liegenden Copilot Clients weiterhin zur Verfügung. Der MAF-Wrapper delegiert unter der Haube an das SDK:

| SDK-Funktion                                                  | MAF-Unterstützung |
| ------------------------------------------------------------- | ----------------- |
| Benutzerdefinierte Tools (`DefineTool` / `AIFunctionFactory`) |                   |
| ✅ Mit MAF-Tools zusammengeführt                               |                   |
| MCP-Server                                                    |                   |
| ✅ Konfiguriert auf dem SDK-Client                             |                   |
| Benutzerdefinierte Agenten / Unteragenten                     |                   |
| ✅ Im Copilot-Agent verfügbar                                  |                   |
| Unendliche Sitzungen                                          |                   |
| ✅ Konfiguriert auf dem SDK-Client                             |                   |
| Modellauswahl                                                 |                   |
| ✅ Überschreibbar pro Agent oder pro Anruf                     |                   |
| Streamen                                                      |                   |
| ✅ Vollständige Delta-Ereignisunterstützung                    |                   |

## Bewährte Methoden

### Auswählen der richtigen Integrationsebene

Verwenden Sie den MAF-Wrapper, wenn Sie Copilot in orchestrierten Workflows mit anderen Anbietern kombinieren möchten. Wenn Ihre Anwendung nur Copilot verwendet, ist das eigenständige SDK einfacher und bietet Ihnen die vollständige Kontrolle:

```typescript
// Standalone SDK — full control, simpler setup
import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();
const session = await client.createSession({
    model: "gpt-5.4",
    onPermissionRequest: async () => ({ kind: "approve-once" }),
});
const response = await session.sendAndWait({ prompt: "Explain this code" });
```

### Agenten fokussiert halten

Geben Sie jedem Agent beim Erstellen von Workflows mit mehreren Agents eine bestimmte Rolle mit klaren Anweisungen. Überlappende Zuständigkeiten vermeiden:

```typescript
// ❌ Too vague — overlapping roles
const agents = [
    { instructions: "Help with code" },
    { instructions: "Assist with programming" },
];

// ✅ Focused — clear separation of concerns
const agents = [
    { instructions: "Review code for security vulnerabilities. Flag SQL injection, XSS, and auth issues." },
    { instructions: "Optimize code performance. Focus on algorithmic complexity and memory usage." },
];
```

### Handhabung von Fehlern auf der Orchestrierungsebene

Agentenaufrufe in die Fehlerbehandlung verpacken, insbesondere in Multi-Agent-Workflows, damit der Fehler eines Agenten nicht die gesamte Pipeline blockiert:

<!-- docs-validate: skip -->

```csharp
try
{
    string result = await pipeline.RunAsync("Analyze this module");
    Console.WriteLine(result);
}
catch (AgentException ex)
{
    Console.Error.WriteLine($"Agent {ex.AgentName} failed: {ex.Message}");
    // Fall back to single-agent mode or retry
}
```

## Siehe auch

* [Erstellen Sie Ihre erste Copilot-gestützte App](/de/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/getting-started): anfängliches Copilot SDK-Setup
* [Angepasste Agents und Orchestrierung von Unteragenten](/de/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/custom-agents): Definieren von spezialisierten Unter-Agents innerhalb des SDK
* [Benutzerdefinierte Fähigkeiten](/de/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/skills): wiederverwendbare Prompt-Module
* [Microsoft Agent Framework-Dokumentation](https://learn.microsoft.com/en-us/agent-framework/agents/providers/github-copilot): offizielle MAF-Dokumente für den Copilot Anbieter
* [Blog: Erstellen von KI-Agents mit GitHub Copilot SDK und Microsoft Agent Framework](https://devblogs.microsoft.com/semantic-kernel/build-ai-agents-with-github-copilot-sdk-and-microsoft-agent-framework/)