# Интеграция с Microsoft Agent Framework

Используйте Copilot SDK в качестве поставщика агентов внутри Microsoft Agent Framework (MAF) для создания многоагентных рабочих процессов вместе с Azure OpenAI, Anthropic и другими провайдерами.

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

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

## Обзор

Microsoft Agent Framework является унифицированным преемником Semantic Kernel и AutoGen. Он предоставляет стандартный интерфейс для создания, оркестрации и развертывания агентов ИИ. Специализированные интеграционные пакеты позволяют обернуть клиент Copilot SDK как первоклассный MAF-агент — взаимозаменяемый с любым другим поставщиком агентов в фреймворке.

| Концепция                        | Описание                                                                                                 |
| -------------------------------- | -------------------------------------------------------------------------------------------------------- |
| **Microsoft Агентный фреймворк** | Открытый фреймворк для оркестрации с одним и несколькими агентами в .NET и Python                        |
| **Поставщик агентов**            | Бэкенд, который питает агента (Copilot, Azure OpenAI, Anthropic и др.)                                   |
| **Оркестратор**                  | Компонент MAF, координирующий агентов в последовательных, одновременных или передачных рабочих процессах |
| **Протокол A2A**                 | Стандарт коммуникации между агентами, поддерживаемый фреймворком                                         |

> \[!NOTE]
> Пакеты интеграции MAF доступны для **.NET** и **Python**. Для TypeScript, Go, Java и Rust используйте Copilot SDK напрямую — стандартные SDK API уже обеспечивают вызов инструментов, потоковую передачу и пользовательские агенты.

## Необходимые условия

Прежде чем начать, убедитесь, что у вас есть следующее:

* [Рабочий автозаголовок](/ru/copilot/how-tos/copilot-sdk/getting-started) на выбранном вами языке
* Подписка на GitHub Copilot (индивидуальная, бизнес-или корпоративная)
* CLI Copilot, установленный или доступный через комплектный CLI SDK

## Installation

Установите Copilot SDK вместе с пакетом интеграции MAF для вашего языка:

<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]
> Java SDK не имеет выделенного пакета интеграции MAF. Используйте стандартный SDK Copilot напрямую — он предоставляет вызов инструментов, потоковую трансляцию и кастомные агенты из коробки.

```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>

## Основное использование

Оберните клиент Copilot SDK как агент MAF с помощью одного вызова метода. Полученный агент соответствует стандартному интерфейсу фреймворка и может использоваться в любом месте, где ожидается MAF-агент.

<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>

## Добавление пользовательских инструментов

Расширяйте свой агент Copilot с помощью инструментов для индивидуальных функций. Инструменты, определённые через стандартный Copilot SDK, автоматически доступны при работе агента внутри MAF.

<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>

Вы также можете использовать нативное определение инструмента Copilot SDK вместе с инструментами MAF:

<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>

## Рабочие процессы с несколькими агентами

Основное преимущество интеграции MAF — это создание Copilot вместе с другими поставщиками агентов в организованных рабочих процессах. Используйте встроенные оркестраторы фреймворка для создания конвейеров, где разные агенты выполняют разные этапы.

### Последовательный рабочий процесс

Запускайте агенты один за другим, передавая выходные данные от одного к другому:

<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>

### Параллельный рабочий процесс

Запускайте несколько агентов параллельно и агрегируйте их результаты:

<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>

## Потоковая передача ответов

При создании интерактивных приложений отклики агентов подают для отображения выхода в реальном времени. Интеграция MAF сохраняет возможности потокового вещания Copilot SDK.

<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>

Вы также можете транслировать напрямую через Copilot SDK без MAF:

<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>

## Справочник по конфигурации

### Опции агентов MAF

| Недвижимость                    | Тип                     | Описание                                                      |
| ------------------------------- | ----------------------- | ------------------------------------------------------------- |
| `Instructions` / `instructions` | `string`                | Системный запрос для агента                                   |
| `Tools` / `tools`               | `AIFunction[]` / `list` | Пользовательские функциональные инструменты, доступные агенту |
| `Streaming` / `streaming`       | `bool`                  | Включить потоковые ответы                                     |
| `Model` / `model`               | `string`                | Переопределить модель по умолчанию                            |

### Опции SDK Copilot (прошёл)

Все стандартные опции [Создайте своё первое приложение на базе Copilot](/ru/copilot/how-tos/copilot-sdk/getting-started) всё ещё доступны при создании базового Copilot-клиента. Обёртка MAF делегирует на SDK под капотом:

| Функция SDK                                                | Поддержка MAF |
| ---------------------------------------------------------- | ------------- |
| Кастомные инструменты (`DefineTool` / `AIFunctionFactory`) |               |
| ✅ Объединение с инструментами MAF                          |               |
| Серверы MCP                                                |               |
| ✅ Настроено на клиенте SDK                                 |               |
| Таможенные агенты / субагенты                              |               |
| ✅ Доступно внутри агент Copilot                            |               |
| Бесконечные сессии                                         |               |
| ✅ Настроено на клиенте SDK                                 |               |
| Выбор модели                                               |               |
| ✅ Переопределённое для каждого агента или звонка           |               |
| Стриминг                                                   |               |
| ✅ Полная поддержка событий дельта                          |               |

## Лучшие практики

### Выберите правильный уровень интеграции

Используйте MAF-обёртку, когда нужно сочинять Copilot вместе с другими провайдерами в организованных рабочих процессах. Если ваше приложение использует только Copilot, отдельный SDK проще и даёт полный контроль:

```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" });
```

### Держите агентов в фокусе

При создании рабочих процессов с несколькими агентами дайте каждому агенту конкретную роль с чёткими инструкциями. Избегайте пересечения обязанностей:

```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." },
];
```

### Обработка ошибок на уровне оркестрации

Вызовы агентов wrap при обработке ошибок, особенно в рабочих процессах с несколькими агентами, где отказ одного агента не должен блокировать весь конвейер:

<!-- 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
}
```

## См. также

* [Создайте своё первое приложение на базе Copilot](/ru/copilot/how-tos/copilot-sdk/getting-started): начальная настройка Copilot SDK
* [Пользовательские агенты и оркестровка субагентов](/ru/copilot/how-tos/copilot-sdk/features/custom-agents): определить специализированные субагенты внутри SDK
* [Настраиваемые навыки](/ru/copilot/how-tos/copilot-sdk/features/skills): многоразовые модули подсказок
* [Microsoft документация Agent Framework](https://learn.microsoft.com/en-us/agent-framework/agents/providers/github-copilot): официальная документация MAF для Copilot провайдера
* [Блог: Создайте AI-агентов с помощью GitHub Copilot SDK и Microsoft Agent Framework](https://devblogs.microsoft.com/semantic-kernel/build-ai-agents-with-github-copilot-sdk-and-microsoft-agent-framework/)