共用方式為


GitHub Copilot 代理程式

Microsoft Agent Framework 支援建立以 GitHub Copilot SDK 作為後端的代理程式。 GitHub Copilot 代理提供強大的程式導向 AI 功能,包括 shell 指令執行、檔案操作、URL 擷取及模型上下文協定(MCP)伺服器整合。

這很重要

GitHub Copilot 代理程式需要安裝並驗證 GitHub Copilot CLI。 為了安全起見,建議在容器化環境(Docker/Dev Container)中執行帶有 shell 或檔案權限的代理程式。

使用者入門

將必要的 NuGet 套件新增至您的專案。

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

建立 GitHub Copilot 代理

第一步,先建立一個 CopilotClient 並開始做。 接著用 AsAIAgent 擴充方法建立代理。

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

附有工具與說明

你可以在建立代理時提供函式工具和自訂指令:

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

代理功能

串流回應

即時收到回應:

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

會話管理

透過多段對話維持對話上下文:

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"

權限

預設情況下,代理程式無法執行 shell 指令、讀寫檔案或擷取 URL。 為了啟用這些功能,請透過以下 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 伺服器

連接本地(stdio)或遠端(HTTP)MCP 伺服器以擴充功能:

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

小提示

完整可執行範例請參閱 .NET 範例

使用代理程式

代理程式是標準 AIAgent ,支援所有標準 AIAgent 作業。

想了解更多如何執行及與代理互動的資訊,請參閱代理 入門教學

先決條件

安裝 Microsoft Agent Framework GitHub Copilot 套件。

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

設定

代理程式可選擇性地使用以下環境變數來設定:

變數 Description
GITHUB_COPILOT_CLI_PATH Copilot CLI 執行檔的路徑
GITHUB_COPILOT_MODEL 使用模型(例如, gpt-5claude-sonnet-4
GITHUB_COPILOT_TIMEOUT 請求逾時時間(秒數)
GITHUB_COPILOT_LOG_LEVEL CLI 日誌層級

使用者入門

從 Agent Framework 匯入所需的類別:

import asyncio
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions

建立 GitHub Copilot 代理

基本代理程式創建

建立 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)

使用明確配置

您可以透過以下 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)

代理功能

功能工具

為您的代理程式配備自訂功能:

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)

串流回應

在生成響應時獲取響應以獲得更好的用戶體驗:

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

線程管理

在多次互動中維持對話脈絡:

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"

權限

預設情況下,代理程式無法執行 shell 指令、讀寫檔案或擷取 URL。 為了啟用這些功能,請提供權限處理程序:

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)

MCP 伺服器

連接本地(stdio)或遠端(HTTP)MCP 伺服器以擴充功能:

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)

使用代理程式

代理程式是標準 BaseAgent ,支援所有標準代理程式作業。

想了解更多如何執行及與代理互動的資訊,請參閱代理 入門教學

後續步驟