Aperçu
Microsoft Agent Framework est le successeur unifié du noyau sémantique et de l’autogen. Il fournit une interface standard pour la création, l’orchestration et le déploiement d’agents IA. Les packages d’intégration dédiés vous permettent d’encapsuler un client sdk Copilot en tant qu’agent MAF de première classe, interchangeable avec n’importe quel autre fournisseur d’agent dans l’infrastructure.
| Concept | Description |
|---|---|
| Microsoft Agent Framework | Infrastructure open source pour l’orchestration à agent unique et multi-agent dans .NET et Python |
| Fournisseur d’agents | Back-end qui alimente un agent (Copilot, Azure OpenAI, Anthropic, etc.) |
| Orchestrateur | Composant MAF qui coordonne les agents dans des flux de travail séquentiels, simultanés ou de transfert |
| Protocole A2A | Norme de communication agent-à-agent prise en charge par l’infrastructure |
Remarque
Les packages d’intégration MAF sont disponibles pour .NET et Python. Pour TypeScript, Go, Java et Rust, utilisez directement le SDK Copilot : les API standard du SDK prennent déjà en charge l’appel d’outils, le streaming et les agents personnalisés.
Prerequisites
Avant de commencer, assurez-vous d’avoir :
- Un Créez votre première application avec Copilot fonctionnel dans la langue de votre choix
- Un abonnement GitHub Copilot (individuel, professionnel ou entreprise)
- L'interface CLI Copilot installée ou disponible via l'interface CLI groupée du Kit de développement logiciel (SDK)
Installation
Installez le sdk Copilot en même temps que le package d’intégration MAF pour votre langue :
dotnet add package GitHub.Copilot.SDK
dotnet add package Microsoft.Agents.AI.GitHub.Copilot --prerelease
pip install copilot-sdk agent-framework-github-copilot
Remarque
Le sdk Java n’a pas de package d’intégration MAF dédié. Utilisez directement le SDK Copilot standard : il offre l’appel d’outils, le streaming et des agents personnalisés prêts à l’emploi.
<!-- 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>
Utilisation de base
Encapsulez le client Copilot SDK en tant qu’agent MAF à l’aide d’un seul appel de méthode. L’agent résultant est conforme à l’interface standard de l’infrastructure et peut être utilisé n’importe où un agent MAF est attendu.
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();
Ajout d’outils personnalisés
Étendez votre assistant Copilot avec des outils de fonction personnalisés. Les outils définis par le biais du Kit de développement logiciel (SDK) Copilot standard sont automatiquement disponibles lorsque l’agent s’exécute dans 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)
Vous pouvez également utiliser la définition d’outil native du SDK Copilot avec les outils 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();
}
Flux de travail multi-agent
L’avantage principal de l’intégration de MAF consiste à composer Copilot avec d’autres fournisseurs d’agents dans des workflows orchestrés. Utilisez les orchestrateurs intégrés de l’infrastructure pour créer des pipelines où différents agents gèrent différentes étapes.
Flux de travail séquentiel
Exécutez les agents les uns après les autres, en transmettant la sortie de l’un à l’autre :
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();
Flux de travail simultané
Exécutez plusieurs agents en parallèle et agrègez leurs résultats :
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();
Réponses en streaming
Lors de la création d’applications interactives, diffusez les réponses de l’agent afin d'afficher les résultats en temps réel. L'intégration de MAF conserve les fonctionnalités de streaming du KIT de développement logiciel (SDK) Copilot.
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()
Vous pouvez également diffuser directement via le kit SDK Copilot sans 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();
Référence de configuration
Options de l’agent MAF
| Propriété | Type | Description |
|---|---|---|
Instructions / instructions | string | Invite de commande du système pour l'agent |
Tools / tools | AIFunction[] / list | Outils de fonction personnalisés disponibles pour l’agent |
Streaming / streaming | bool | Activer les réponses en streaming |
Model / model | string | Remplacer le modèle par défaut |
Options du SDK Copilot (transmises telles quelles)
Toutes les options standard Créez votre première application avec Copilot sont toujours disponibles lors de la création du client Copilot sous-jacent. Le wrapper MAF délègue au Kit de développement logiciel (SDK) sous le capot :
| Fonctionnalité du Kit de développement logiciel (SDK | Prise en charge de MAF |
|---|---|
Outils personnalisés (DefineTool / AIFunctionFactory) | |
| ✅ Fusionné avec les outils MAF | |
| Serveurs MCP | |
| ✅ Configuré sur le client du Kit de développement logiciel (SDK) | |
| Agents personnalisés / sous-agents | |
| ✅ disponible dans le assistant Copilot | |
| Sessions infinies | |
| ✅ Configuré sur le client du Kit de développement logiciel (SDK) | |
| Sélection du modèle | |
| ✅ Redéfinissable par agent ou par appel | |
| Diffusion en continu | |
| ✅ Prise en charge complète des événements delta |
Bonnes pratiques
Choisir le niveau d’intégration approprié
Utilisez l’encapsuleur MAF lorsque vous devez associer Copilot à d’autres fournisseurs dans des flux de travail orchestrés. Si votre application utilise uniquement Copilot, le Kit de développement logiciel (SDK) autonome est plus simple et vous offre un contrôle total :
// 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" });
Garder les agents concentrés
Lors de la création de flux de travail multi-agents, donnez à chaque agent un rôle spécifique avec des instructions claires. Évitez les responsabilités qui se chevauchent :
// ❌ 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." },
];
Gérer les erreurs au niveau de l’orchestration
Encapsulez les appels d’agent dans une gestion des erreurs, surtout dans les flux de travail multi-agents où l’échec d’un agent ne doit pas bloquer l’ensemble du pipeline :
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
}
Voir aussi
- Créez votre première application avec Copilot : configuration initiale du Kit de développement logiciel (SDK) Copilot
- Agents personnalisés et orchestration de sous-agents : définir des sous-agents spécialisés dans le Kit de développement logiciel (SDK)
- Compétences personnalisées : modules d’invite réutilisables
- documentation Microsoft Agent Framework : documents MAF officiels pour le fournisseur de Copilot
- Blog : Créer des agents IA avec le Kit de développement logiciel (SDK) GitHub Copilot et Microsoft Agent Framework