Partager via


GitHub Copilot Agents

Microsoft Agent Framework prend en charge la création d’agents qui utilisent le Kit de développement logiciel (SDK) Copilot GitHub en tant que serveur principal. Les agents GitHub Copilot offrent un accès aux puissantes fonctionnalités d’IA orientées codage, notamment l’exécution de commandes de l’interpréteur de commandes, les opérations de fichier, la récupération d’URL et l’intégration du serveur MCP (Model Context Protocol).

Important

Les agents GitHub Copilot nécessitent que l’interface CLI GitHub Copilot soit installée et authentifiée. Pour la sécurité, il est recommandé d’exécuter des agents avec des autorisations d’interpréteur de commandes ou de fichiers dans un environnement conteneurisé (Docker/Dev Container).

Getting Started

Ajoutez les packages NuGet requis à votre projet.

dotnet add package Microsoft.Agents.AI.GitHub.Copilot --prerelease

Créer un agent GitHub Copilot

En première étape, créez-en un CopilotClient et démarrez-le. Utilisez ensuite la méthode d’extension AsAIAgent pour créer un agent.

using GitHub.Copilot.SDK;
using Microsoft.Agents.AI;

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

AIAgent agent = copilotClient.AsAIAgent();

Console.WriteLine(await agent.RunAsync("What is Microsoft Agent Framework?"));

Avec des outils et des instructions

Vous pouvez fournir des outils de fonction et des instructions personnalisées lors de la création de l’agent :

using GitHub.Copilot.SDK;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

AIFunction weatherTool = AIFunctionFactory.Create((string location) =>
{
    return $"The weather in {location} is sunny with a high of 25C.";
}, "GetWeather", "Get the weather for a given location.");

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

AIAgent agent = copilotClient.AsAIAgent(
    tools: [weatherTool],
    instructions: "You are a helpful weather agent.");

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

Fonctionnalités de l’agent

Réponses en continu

Obtenez les réponses à mesure qu’elles sont générées :

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

AIAgent agent = copilotClient.AsAIAgent();

await foreach (AgentResponseUpdate update in agent.RunStreamingAsync("Tell me a short story."))
{
    Console.Write(update);
}

Console.WriteLine();

Gestion des sessions

Gérez le contexte de conversation entre plusieurs interactions à l’aide de sessions :

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

await using GitHubCopilotAgent agent = new(
    copilotClient,
    instructions: "You are a helpful assistant. Keep your answers short.");

AgentSession session = await agent.CreateSessionAsync();

// First turn
await agent.RunAsync("My name is Alice.", session);

// Second turn - agent remembers the context
AgentResponse response = await agent.RunAsync("What is my name?", session);
Console.WriteLine(response); // Should mention "Alice"

Permissions

Par défaut, l’agent ne peut pas exécuter de commandes shell, lire/écrire des fichiers ou extraire des URL. Pour activer ces fonctionnalités, fournissez un gestionnaire d’autorisations via SessionConfig:

static Task<PermissionRequestResult> PromptPermission(
    PermissionRequest request, PermissionInvocation invocation)
{
    Console.WriteLine($"\n[Permission Request: {request.Kind}]");
    Console.Write("Approve? (y/n): ");

    string? input = Console.ReadLine()?.Trim().ToUpperInvariant();
    string kind = input is "Y" or "YES" ? "approved" : "denied-interactively-by-user";

    return Task.FromResult(new PermissionRequestResult { Kind = kind });
}

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

SessionConfig sessionConfig = new()
{
    OnPermissionRequest = PromptPermission,
};

AIAgent agent = copilotClient.AsAIAgent(sessionConfig);

Console.WriteLine(await agent.RunAsync("List all files in the current directory"));

Serveurs MCP

Connectez-vous à des serveurs MCP locaux (stdio) ou distants (HTTP) pour des fonctionnalités étendues :

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

SessionConfig sessionConfig = new()
{
    OnPermissionRequest = PromptPermission,
    McpServers = new Dictionary<string, object>
    {
        // Local stdio server
        ["filesystem"] = new McpLocalServerConfig
        {
            Type = "stdio",
            Command = "npx",
            Args = ["-y", "@modelcontextprotocol/server-filesystem", "."],
            Tools = ["*"],
        },
        // Remote HTTP server
        ["microsoft-learn"] = new McpRemoteServerConfig
        {
            Type = "http",
            Url = "https://learn.microsoft.com/api/mcp",
            Tools = ["*"],
        },
    },
};

AIAgent agent = copilotClient.AsAIAgent(sessionConfig);

Console.WriteLine(await agent.RunAsync("Search Microsoft Learn for 'Azure Functions' and summarize the top result"));

Conseil / Astuce

Consultez les exemples .NET pour obtenir des exemples exécutables complets.

Utilisation de l’agent

L’agent standard AIAgent prend en charge toutes les opérations standard AIAgent.

Pour plus d’informations sur l’exécution et l’interaction avec les agents, consultez les didacticiels de prise en main de l’agent.

Prerequisites

Installez le package Microsoft Agent Framework GitHub Copilot.

pip install agent-framework-github-copilot --pre

Paramétrage

L’agent peut éventuellement être configuré à l’aide des variables d’environnement suivantes :

Variable Descriptif
GITHUB_COPILOT_CLI_PATH Chemin d’accès à l’exécutable de la CLI Copilot
GITHUB_COPILOT_MODEL Modèle à utiliser (par exemple, gpt-5, claude-sonnet-4)
GITHUB_COPILOT_TIMEOUT Délai d’expiration de la demande en secondes
GITHUB_COPILOT_LOG_LEVEL Niveau de journalisation CLI

Getting Started

Importez les classes requises à partir d’Agent Framework :

import asyncio
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions

Créer un agent GitHub Copilot

Création d'un agent basique

La façon la plus simple de créer un agent GitHub Copilot :

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

    async with agent:
        result = await agent.run("What is Microsoft Agent Framework?")
        print(result)

Avec une configuration explicite

Vous pouvez fournir une configuration explicite via default_options:

async def explicit_config_example():
    agent = GitHubCopilotAgent(
        default_options={
            "instructions": "You are a helpful assistant.",
            "model": "gpt-5",
            "timeout": 120,
        },
    )

    async with agent:
        result = await agent.run("What can you do?")
        print(result)

Fonctionnalités de l’agent

Outils de fonction

Équipez votre agent avec des fonctions personnalisées :

from typing import Annotated
from pydantic import Field

def get_weather(
    location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
    """Get the weather for a given location."""
    return f"The weather in {location} is sunny with a high of 25C."

async def tools_example():
    agent = GitHubCopilotAgent(
        default_options={"instructions": "You are a helpful weather agent."},
        tools=[get_weather],
    )

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

Réponses en continu

Obtenez des réponses à mesure qu’elles sont générées pour une meilleure expérience utilisateur :

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

    async with agent:
        print("Agent: ", end="", flush=True)
        async for chunk in agent.run("Tell me a short story.", stream=True):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()

Gestion des threads

Maintenez le contexte de conversation entre plusieurs interactions :

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

    async with agent:
        thread = agent.create_session()

        # First interaction
        result1 = await agent.run("My name is Alice.", session=thread)
        print(f"Agent: {result1}")

        # Second interaction - agent remembers the context
        result2 = await agent.run("What's my name?", session=thread)
        print(f"Agent: {result2}")  # Should remember "Alice"

Permissions

Par défaut, l’agent ne peut pas exécuter de commandes shell, lire/écrire des fichiers ou extraire des URL. Pour activer ces fonctionnalités, fournissez un gestionnaire d’autorisations :

from copilot.types import PermissionRequest, PermissionRequestResult

def prompt_permission(
    request: PermissionRequest, context: dict[str, str]
) -> PermissionRequestResult:
    kind = request.get("kind", "unknown")
    print(f"\n[Permission Request: {kind}]")

    response = input("Approve? (y/n): ").strip().lower()
    if response in ("y", "yes"):
        return PermissionRequestResult(kind="approved")
    return PermissionRequestResult(kind="denied-interactively-by-user")

async def permissions_example():
    agent = GitHubCopilotAgent(
        default_options={
            "instructions": "You are a helpful assistant that can execute shell commands.",
            "on_permission_request": prompt_permission,
        },
    )

    async with agent:
        result = await agent.run("List the Python files in the current directory")
        print(result)

Serveurs MCP

Connectez-vous à des serveurs MCP locaux (stdio) ou distants (HTTP) pour des fonctionnalités étendues :

from copilot.types import MCPServerConfig

async def mcp_example():
    mcp_servers: dict[str, MCPServerConfig] = {
        # Local stdio server
        "filesystem": {
            "type": "stdio",
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
            "tools": ["*"],
        },
        # Remote HTTP server
        "microsoft-learn": {
            "type": "http",
            "url": "https://learn.microsoft.com/api/mcp",
            "tools": ["*"],
        },
    }

    agent = GitHubCopilotAgent(
        default_options={
            "instructions": "You are a helpful assistant with access to the filesystem and Microsoft Learn.",
            "on_permission_request": prompt_permission,
            "mcp_servers": mcp_servers,
        },
    )

    async with agent:
        result = await agent.run("Search Microsoft Learn for 'Azure Functions' and summarize the top result")
        print(result)

Utilisation de l’agent

L’agent est standard BaseAgent et prend en charge toutes les opérations d’agent standard.

Pour plus d’informations sur l’exécution et l’interaction avec les agents, consultez les didacticiels de prise en main de l’agent.

Prochaines étapes