通过


GitHub Copilot 代理

Microsoft代理框架支持创建使用 GitHub Copilot SDK 作为其后端的代理。 GitHub Copilot 代理提供对功能强大的面向编码的 AI 功能的访问权限,包括 shell 命令执行、文件作、URL 提取和模型上下文协议 (MCP) 服务器集成。

重要

GitHub Copilot 代理要求安装并验证 GitHub Copilot CLI。 为了安全,建议在容器化环境中(如 Docker 或开发容器)运行具有 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"

Permissions

默认情况下,代理无法执行 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

配置

可以使用以下环境变量选择性地配置代理:

Variable 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"

Permissions

默认情况下,代理无法执行 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 代理,支持所有标准代理操作。

有关如何运行和与代理交互的详细信息,请参阅 代理入门教程

后续步骤