Nota
O acesso a esta página requer autorização. Podes tentar iniciar sessão ou mudar de diretório.
O acesso a esta página requer autorização. Podes tentar mudar de diretório.
O Microsoft Agent Framework suporta a criação de agentes que utilizam o GitHub Copilot SDK como backend. Os agentes GitHub Copilot fornecem acesso a poderosas capacidades de IA orientadas para programação, incluindo execução de comandos shell, operações de ficheiros, obtenção de URLs e integração com servidores Model Context Protocol (MCP).
Importante
Os agentes do GitHub Copilot exigem que a CLI do GitHub Copilot seja instalada e autenticada. Para segurança, recomenda-se executar agentes com permissões de shell ou ficheiro num ambiente containerizado (Docker/Dev Container).
Introdução
Adicione os pacotes NuGet necessários ao seu projeto.
dotnet add package Microsoft.Agents.AI.GitHub.Copilot --prerelease
Criar um agente do GitHub Copilot
Como primeiro passo, crie um CopilotClient e comece. Depois, use o método de extensão AsAIAgent para criar um 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?"));
Com Ferramentas e Instruções
Pode fornecer ferramentas funcionais e instruções personalizadas ao criar o 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?"));
Funcionalidades do agente
Respostas de streaming
Obtenha respostas à medida que forem geradas:
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();
Gestão de Sessões
Mantenha o contexto da conversa em múltiplas interações usando sessões:
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
Por defeito, o agente não pode executar comandos de shell, ler/escrever ficheiros ou buscar URLs. Para ativar estas capacidades, forneça um manipulador de permissões através de 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
Ligue-se a servidores MCP locais (stdio) ou remotos (HTTP) para capacidades alargadas:
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"));
Sugestão
Consulte os exemplos do .NET para exemplos completos executáveis.
Usando o agente
O agente é um padrão AIAgent e suporta todas as operações padrão AIAgent .
Para mais informações sobre como gerir e interagir com agentes, consulte os tutoriais de Início de Agentes.
Pré-requisitos
Instala o pacote Microsoft Agent Framework GitHub Copilot.
pip install agent-framework-github-copilot --pre
Configuração
O agente pode ser configurado opcionalmente usando as seguintes variáveis de ambiente:
| Variable | Description |
|---|---|
GITHUB_COPILOT_CLI_PATH |
Caminho para o executável da CLI Copilot |
GITHUB_COPILOT_MODEL |
Modelo a usar (por exemplo, gpt-5, claude-sonnet-4) |
GITHUB_COPILOT_TIMEOUT |
Peça tempo limite em segundos |
GITHUB_COPILOT_LOG_LEVEL |
Nível de log do CLI |
Introdução
Importar as classes necessárias do Agent Framework:
import asyncio
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions
Criar um agente do GitHub Copilot
Criação básica de agentes
A forma mais simples de criar um agente 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)
Com Configuração Explícita
Pode fornecer uma configuração explícita atravé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)
Funcionalidades do agente
Ferramentas de Função
Equipe seu agente com funções 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)
Respostas de streaming
Obtenha respostas à medida que são geradas para uma melhor experiência do utilizador:
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()
Gerenciamento de threads
Mantenha o contexto da conversa ao longo de múltiplas interações:
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
Por defeito, o agente não pode executar comandos de shell, ler/escrever ficheiros ou buscar URLs. Para ativar estas capacidades, forneça um manipulador de permissões:
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
Ligue-se a servidores MCP locais (stdio) ou remotos (HTTP) para capacidades alargadas:
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)
Usando o agente
O agente é um BaseAgent padrão e suporta todas as operações padrão de um agente.
Para mais informações sobre como gerir e interagir com agentes, consulte os tutoriais de Início de Agentes.