다음을 통해 공유


GitHub Copilot 에이전트

Microsoft Agent Framework는 GitHub Copilot SDK 를 백 엔드로 사용하는 에이전트 만들기를 지원합니다. GitHub Copilot 에이전트는 셸 명령 실행, 파일 작업, URL 페치 및 MCP(모델 컨텍스트 프로토콜) 서버 통합을 비롯한 강력한 코딩 지향 AI 기능에 대한 액세스를 제공합니다.

중요합니다

GitHub Copilot 에이전트는 GitHub Copilot CLI를 설치하고 인증해야 합니다. 보안을 위해 컨테이너화된 환경(Docker/Dev Container)에서 셸 또는 파일 권한으로 에이전트를 실행하는 것이 좋습니다.

시작하기

필요한 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

기본적으로 에이전트는 셸 명령, 읽기/쓰기 파일 또는 페치 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 로그 수준

시작하기

에이전트 프레임워크에서 필요한 클래스를 가져옵니다.

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

기본적으로 에이전트는 셸 명령, 읽기/쓰기 파일 또는 페치 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 이며 모든 표준 에이전트 작업을 지원합니다.

에이전트를 실행하고 상호 작용하는 방법에 대한 자세한 내용은 에이전트 시작 자습서를 참조하세요.

다음 단계: