GitHub Copilot-agenter

Microsoft Agent Framework har stöd för att skapa agenter som använder GitHub Copilot SDK som serverdel. GitHub Copilot-agenter ger åtkomst till kraftfulla kodningsorienterade AI-funktioner, inklusive körning av gränssnittskommandon, filåtgärder, URL-hämtning och MCP-serverintegrering (Model Context Protocol).

Viktigt!

GitHub Copilot-agenter kräver att GitHub Copilot CLI installeras och autentiseras. För säkerhet rekommenderar vi att du kör agenter med gränssnitts- eller filbehörigheter i en containerbaserad miljö (Docker/Dev Container).

Komma igång

Lägg till nödvändiga NuGet-paket i projektet.

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

Skapa en GitHub Copilot-agent

Som ett första steg skapar du en CopilotClient och startar den. Använd AsAIAgent sedan tilläggsmetoden för att skapa en 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?"));

Med verktyg och instruktioner

Du kan ange funktionsverktyg och anpassade instruktioner när du skapar agenten:

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

Agentfunktioner

Direktuppspelningssvar

Hämta svar när de genereras:

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

Sessionshantering

Underhålla konversationskontext över flera interaktioner med hjälp av sessioner:

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

Som standard kan agenten inte köra gränssnittskommandon, läsa/skriva filer eller hämta URL:er. Om du vill aktivera dessa funktioner anger du en behörighetshanterare 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"));

MCP-servrar

Anslut till lokala (stdio) eller fjärranslutna (HTTP) MCP-servrar för utökade funktioner:

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

Tips/Råd

Se .NET-exemplen för fullständiga körbara exempel.

Använda agenten

Agenten är en standard AIAgent och stöder alla standard åtgärder AIAgent.

Mer information om hur du kör och interagerar med agenter finns i självstudierna om att komma igång med agenten.

Förutsättningar

Installera GitHub Copilot-paketet för Microsoft Agent Framework.

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

Konfiguration

Agenten kan konfigureras med hjälp av följande miljövariabler:

Variable Description
GITHUB_COPILOT_CLI_PATH Sökväg till körbar Copilot CLI
GITHUB_COPILOT_MODEL Modell som ska användas (t.ex. gpt-5, claude-sonnet-4)
GITHUB_COPILOT_TIMEOUT Tidsgräns för begäran i sekunder
GITHUB_COPILOT_LOG_LEVEL CLI-loggnivå

Komma igång

Importera de klasser som krävs från Agent Framework:

import asyncio
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions

Skapa en GitHub Copilot-agent

Skapande av grundläggande agent

Det enklaste sättet att skapa en GitHub Copilot-agent:

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)

Med uttalad konfiguration

Du kan ange en explicit konfiguration 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)

Agentfunktioner

Kontextprovidrar

Python GitHubCopilotAgent stöder context_providers=[...]också . Leverantörer kör före och efter varje anrop, så provider-tillagda meddelanden och instruktioner ingår i Copilot-prompten och historikprovidrar kan observera det slutliga svaret.

from agent_framework import InMemoryHistoryProvider

agent = GitHubCopilotAgent(
    default_options={"instructions": "You are a helpful coding assistant."},
    context_providers=[InMemoryHistoryProvider()],
)

Du kan kombinera inbyggda historikprovidrar med anpassade kontextprovidrar. Information om implementeringsmönster finns i Kontextprovidrar.

Funktionsverktyg

Utrusta din agent med anpassade funktioner:

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)

Direktuppspelningssvar

Få svar när de genereras för bättre användarupplevelse:

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

Trådhantering

Underhålla konversationskontext över flera interaktioner:

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

    async with agent:
        session = agent.create_session()

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

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

Permissions

Som standard kan agenten inte köra gränssnittskommandon, läsa/skriva filer eller hämta URL:er. Om du vill aktivera de här funktionerna anger du en behörighetshanterare:

from copilot.generated.session_events import PermissionRequest

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)

MCP-servrar

Anslut till lokala (stdio) eller fjärranslutna (HTTP) MCP-servrar för utökade funktioner:

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)

Observability

GitHubCopilotAgent har inbyggd OpenTelemetry-spårning. Anropa configure_otel_providers() en gång vid start för att aktivera intervall, mått och loggar för varje körning:

from agent_framework.observability import configure_otel_providers
from agent_framework.github import GitHubCopilotAgent

configure_otel_providers(enable_console_exporters=True)

async with GitHubCopilotAgent() as agent:
    response = await agent.run("Hello!")

Om du behöver den underliggande agenten utan telemetrilagret (till exempel omsluta den i en anpassad) importerar du RawGitHubCopilotAgent från agent_framework.github.

Information om OTLP-exportörer och mer omfattande exempel finns i observerbarhetsexemplen.

Använda agenten

Agenten är en standard BaseAgent och stöder alla standardagentåtgärder.

Mer information om hur du kör och interagerar med agenter finns i självstudierna om att komma igång med agenten.

Nästa steg