Compartir a través de


Agentes de GitHub Copilot

Microsoft Agent Framework admite la creación de agentes que usan el SDK de Copilot de GitHub como back-end. Los agentes de GitHub Copilot proporcionan acceso a eficaces funcionalidades de inteligencia artificial orientadas a codificación, como la ejecución de comandos de shell, las operaciones de archivo, la captura de direcciones URL y la integración del servidor del Protocolo de contexto de modelo (MCP).

Importante

Los agentes de GitHub Copilot requieren que la CLI de GitHub Copilot esté instalada y autenticada. Por seguridad, se recomienda ejecutar agentes con permisos de shell o archivo en un entorno contenedorizado (Docker/Dev Container).

Introducción

Agregue los paquetes NuGet necesarios al proyecto.

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

Creación de un agente de Copilot de GitHub

Como primer paso, cree un CopilotClient y inícielo. A continuación, use el método de AsAIAgent extensión para crear un agente.

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?"));

Con herramientas e instrucciones

Puede proporcionar herramientas de función e instrucciones personalizadas al crear el agente:

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?"));

Características del agente

Respuestas de streaming

Obtenga respuestas a medida que se generen:

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();

Administración de sesiones

Mantener el contexto de conversación en varias interacciones mediante sesiones:

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

De forma predeterminada, el agente no puede ejecutar comandos de shell, archivos de lectura y escritura ni capturar direcciones URL. Para habilitar estas funcionalidades, proporcione un controlador de permisos mediante 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"));

Servidores MCP

Conéctese a servidores MCP locales (stdio) o remotos (HTTP) para funcionalidades extendidas:

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

Sugerencia

Consulte los ejemplos de .NET para obtener ejemplos completos de ejecución.

Uso del agente

El agente es un AIAgent estándar y admite todas las operaciones estándar AIAgent.

Para obtener más información sobre cómo ejecutar e interactuar con agentes, consulte los tutoriales de introducción al agente.

Prerrequisitos

Instale el paquete de GitHub Copilot de Microsoft Agent Framework.

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

Configuración

El agente se puede configurar opcionalmente mediante las siguientes variables de entorno:

Variable Description
GITHUB_COPILOT_CLI_PATH Ruta de acceso al ejecutable de la CLI de Copilot
GITHUB_COPILOT_MODEL Modelo que se va a usar (por ejemplo, gpt-5, claude-sonnet-4)
GITHUB_COPILOT_TIMEOUT Tiempo de espera de solicitud en segundos
GITHUB_COPILOT_LOG_LEVEL Nivel de registro de la CLI

Introducción

Importe las clases necesarias desde Agent Framework:

import asyncio
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions

Creación de un agente de Copilot de GitHub

Creación básica del agente

La manera más sencilla de crear un agente de 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)

Con configuración explícita

Puede proporcionar una configuración explícita a través de 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)

Características del agente

Herramientas de funciones

Equipe al agente con funciones personalizadas:

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)

Respuestas de streaming

Obtenga respuestas a medida que se generen para mejorar la experiencia del usuario:

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

Administración de subprocesos

Mantener el contexto de conversación en varias interacciones:

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

De forma predeterminada, el agente no puede ejecutar comandos de shell, archivos de lectura y escritura ni capturar direcciones URL. Para habilitar estas funcionalidades, proporcione un controlador de permisos:

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)

Servidores MCP

Conéctese a servidores MCP locales (stdio) o remotos (HTTP) para funcionalidades extendidas:

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)

Uso del agente

El agente es un estándar BaseAgent y admite todas las operaciones estándar.

Para obtener más información sobre cómo ejecutar e interactuar con agentes, consulte los tutoriales de introducción al agente.

Pasos siguientes