Обзор
Microsoft Agent Framework является унифицированным преемником Semantic Kernel и AutoGen. Он предоставляет стандартный интерфейс для создания, оркестрации и развертывания агентов ИИ. Специализированные интеграционные пакеты позволяют обернуть клиент Copilot SDK как первоклассный MAF-агент — взаимозаменяемый с любым другим поставщиком агентов в фреймворке.
| Концепция | Описание |
|---|---|
| Microsoft Агентный фреймворк | Открытый фреймворк для оркестрации с одним и несколькими агентами в .NET и Python |
| Поставщик агентов | Бэкенд, который питает агента (Copilot, Azure OpenAI, Anthropic и др.) |
| Оркестратор | Компонент MAF, координирующий агентов в последовательных, одновременных или передачных рабочих процессах |
| Протокол A2A | Стандарт коммуникации между агентами, поддерживаемый фреймворком |
Примечание.
Пакеты интеграции MAF доступны для .NET и Python. Для TypeScript, Go, Java и Rust используйте Copilot SDK напрямую — стандартные SDK API уже обеспечивают вызов инструментов, потоковую передачу и пользовательские агенты.
Необходимые условия
Прежде чем начать, убедитесь, что у вас есть следующее:
- Рабочий автозаголовок на выбранном вами языке
- Подписка на GitHub Copilot (индивидуальная, бизнес-или корпоративная)
- CLI Copilot, установленный или доступный через комплектный CLI SDK
Installation
Установите Copilot SDK вместе с пакетом интеграции MAF для вашего языка:
dotnet add package GitHub.Copilot.SDK
dotnet add package Microsoft.Agents.AI.GitHub.Copilot --prerelease
pip install copilot-sdk agent-framework-github-copilot
Примечание.
Java SDK не имеет выделенного пакета интеграции MAF. Используйте стандартный SDK Copilot напрямую — он предоставляет вызов инструментов, потоковую трансляцию и кастомные агенты из коробки.
<!-- 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>
Основное использование
Оберните клиент Copilot SDK как агент MAF с помощью одного вызова метода. Полученный агент соответствует стандартному интерфейсу фреймворка и может использоваться в любом месте, где ожидается MAF-агент.
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);
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)
import com.github.copilot.sdk.CopilotClient;
import com.github.copilot.sdk.events.*;
import com.github.copilot.sdk.json.*;
var client = new CopilotClient();
client.start().get();
var session = client.createSession(new SessionConfig()
.setModel("gpt-4.1")
.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();
Добавление пользовательских инструментов
Расширяйте свой агент Copilot с помощью инструментов для индивидуальных функций. Инструменты, определённые через стандартный Copilot SDK, автоматически доступны при работе агента внутри MAF.
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);
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)
Вы также можете использовать нативное определение инструмента Copilot SDK вместе с инструментами MAF:
import { CopilotClient, DefineTool } from "@github/copilot-sdk";
const getWeather = DefineTool({
name: "GetWeather",
description: "Get the current weather for a given location.",
parameters: { location: { type: "string", description: "City name" } },
execute: async ({ location }) => `The weather in ${location} is sunny, 25°C.`,
});
const client = new CopilotClient();
const session = await client.createSession({
model: "gpt-4.1",
tools: [getWeather],
onPermissionRequest: async () => ({ kind: "approve-once" }),
});
await session.sendAndWait({ prompt: "What's the weather like in Seattle?" });
import com.github.copilot.sdk.CopilotClient;
import com.github.copilot.sdk.events.*;
import com.github.copilot.sdk.json.*;
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-4.1")
.setTools(List.of(getWeather))
.setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();
session.sendAndWait(new MessageOptions()
.setPrompt("What's the weather like in Seattle?")).get();
}
Рабочие процессы с несколькими агентами
Основное преимущество интеграции MAF — это создание Copilot вместе с другими поставщиками агентов в организованных рабочих процессах. Используйте встроенные оркестраторы фреймворка для создания конвейеров, где разные агенты выполняют разные этапы.
Последовательный рабочий процесс
Запускайте агенты один за другим, передавая выходные данные от одного к другому:
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-4.1",
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);
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-4.1",
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)
import com.github.copilot.sdk.CopilotClient;
import com.github.copilot.sdk.events.*;
import com.github.copilot.sdk.json.*;
// 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-4.1")
.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-4.1")
.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();
Параллельный рабочий процесс
Запускайте несколько агентов параллельно и агрегируйте их результаты:
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);
import com.github.copilot.sdk.CopilotClient;
import com.github.copilot.sdk.events.*;
import com.github.copilot.sdk.json.*;
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-4.1")
.setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();
var perfSession = client.createSession(new SessionConfig()
.setModel("gpt-4.1")
.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();
Потоковая передача ответов
При создании интерактивных приложений отклики агентов подают для отображения выхода в реальном времени. Интеграция MAF сохраняет возможности потокового вещания Copilot SDK.
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();
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()
Вы также можете транслировать напрямую через Copilot SDK без MAF:
import { CopilotClient } from "@github/copilot-sdk";
const client = new CopilotClient();
const session = await client.createSession({
model: "gpt-4.1",
streaming: true,
onPermissionRequest: async () => ({ kind: "approve-once" }),
});
session.on("assistant.message_delta", (event) => {
process.stdout.write(event.data.delta ?? "");
});
await session.sendAndWait({ prompt: "Write a quicksort implementation in TypeScript" });
import com.github.copilot.sdk.CopilotClient;
import com.github.copilot.sdk.events.*;
import com.github.copilot.sdk.json.*;
var client = new CopilotClient();
client.start().get();
var session = client.createSession(new SessionConfig()
.setModel("gpt-4.1")
.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();
Справочник по конфигурации
Опции агентов MAF
| Недвижимость | Тип | Описание |
|---|---|---|
Instructions / instructions | string | Системный запрос для агента |
Tools / tools | AIFunction[] / list | Пользовательские функциональные инструменты, доступные агенту |
Streaming / streaming | bool | Включить потоковые ответы |
Model / model | string | Переопределить модель по умолчанию |
Опции SDK Copilot (прошёл)
Все стандартные опции Создайте своё первое приложение на базе Copilot всё ещё доступны при создании базового Copilot-клиента. Обёртка MAF делегирует на SDK под капотом:
| Функция SDK | Поддержка MAF |
|---|---|
Кастомные инструменты (DefineTool / AIFunctionFactory) | |
| ✅ Объединение с инструментами MAF | |
| Серверы MCP | |
| ✅ Настроено на клиенте SDK | |
| Таможенные агенты / субагенты | |
| ✅ Доступно внутри агент Copilot | |
| Бесконечные сессии | |
| ✅ Настроено на клиенте SDK | |
| Выбор модели | |
| ✅ Переопределённое для каждого агента или звонка | |
| Стриминг | |
| ✅ Полная поддержка событий дельта |
Лучшие практики
Выберите правильный уровень интеграции
Используйте MAF-обёртку, когда нужно сочинять Copilot вместе с другими провайдерами в организованных рабочих процессах. Если ваше приложение использует только Copilot, отдельный SDK проще и даёт полный контроль:
// Standalone SDK — full control, simpler setup
import { CopilotClient } from "@github/copilot-sdk";
const client = new CopilotClient();
const session = await client.createSession({
model: "gpt-4.1",
onPermissionRequest: async () => ({ kind: "approve-once" }),
});
const response = await session.sendAndWait({ prompt: "Explain this code" });
Держите агентов в фокусе
При создании рабочих процессов с несколькими агентами дайте каждому агенту конкретную роль с чёткими инструкциями. Избегайте пересечения обязанностей:
// ❌ 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 при обработке ошибок, особенно в рабочих процессах с несколькими агентами, где отказ одного агента не должен блокировать весь конвейер:
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: начальная настройка Copilot SDK
- Пользовательские агенты и оркестровка субагентов: определить специализированные субагенты внутри SDK
- Настраиваемые навыки: многоразовые модули подсказок
- Microsoft документация Agent Framework: официальная документация MAF для Copilot провайдера
- Блог: Создайте AI-агентов с помощью GitHub Copilot SDK и Microsoft Agent Framework