Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Microsoft Agent Framework supporta la creazione di agenti che usano GitHub Copilot SDK come back-end. Gli agenti di GitHub Copilot forniscono l'accesso a potenti funzionalità di intelligenza artificiale orientate alla codifica, tra cui l'esecuzione dei comandi della shell, le operazioni di file, il recupero di URL e l'integrazione del server MCP (Model Context Protocol).
Importante
Gli agenti di GitHub Copilot richiedono l'installazione e l'autenticazione dell'interfaccia della riga di comando di GitHub Copilot. Per motivi di sicurezza, è consigliabile eseguire agenti con autorizzazioni shell o file in un ambiente in contenitori (contenitore Docker/Dev).
Come iniziare
Aggiungere i pacchetti NuGet necessari al progetto.
dotnet add package Microsoft.Agents.AI.GitHub.Copilot --prerelease
Creare un agente Copilot di GitHub
Come primo passaggio, creare un CopilotClient e avviarlo. Usare quindi il AsAIAgent metodo di estensione per creare un 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?"));
Con strumenti e istruzioni
È possibile fornire strumenti per le funzioni e istruzioni personalizzate durante la creazione dell'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?"));
Funzionalità dell'agente
Risposte in streaming
Ottenere risposte man mano che vengono generate:
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();
Gestione delle sessioni
Mantenere il contesto della conversazione tra più interazioni usando sessioni:
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
Per impostazione predefinita, l'agente non può eseguire comandi della shell, file di lettura/scrittura o recuperare GLI URL. Per abilitare queste funzionalità, fornire un gestore di autorizzazioni tramite 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"));
Server MCP
Connettersi ai server MCP locali (stdio) o remoti (HTTP) per le funzionalità estese:
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"));
Suggerimento
Uso dell'agente
L'agente è uno standard AIAgent e supporta tutte le operazioni standard AIAgent .
Per altre informazioni su come eseguire e interagire con gli agenti, vedere le esercitazioni introduttive su Agent.
Prerequisiti
Installare il pacchetto GitHub Copilot di Microsoft Agent Framework.
pip install agent-framework-github-copilot --pre
Impostazione
L'agente può essere configurato facoltativamente usando le variabili di ambiente seguenti:
| Variabile | Descrzione |
|---|---|
GITHUB_COPILOT_CLI_PATH |
Percorso dell'eseguibile di Copilot CLI |
GITHUB_COPILOT_MODEL |
Modello da usare (ad esempio, gpt-5, claude-sonnet-4) |
GITHUB_COPILOT_TIMEOUT |
Timeout della richiesta in secondi |
GITHUB_COPILOT_LOG_LEVEL |
Livello di log CLI |
Come iniziare
Importare le classi necessarie da Agent Framework:
import asyncio
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions
Creare un agente Copilot di GitHub
Creazione dell'agente di base
Il modo più semplice per creare un agente Di 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)
Con configurazione esplicita
È possibile fornire una configurazione esplicita tramite 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)
Funzionalità dell'agente
Strumenti per le funzioni
Equipaggiare l'agente con funzioni personalizzate:
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)
Risposte in streaming
Ottenere risposte man mano che vengono generate per un'esperienza utente migliore:
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()
Gestione dei thread
Mantenere il contesto della conversazione tra più interazioni:
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
Per impostazione predefinita, l'agente non può eseguire comandi della shell, file di lettura/scrittura o recuperare GLI URL. Per abilitare queste funzionalità, fornire un gestore di autorizzazioni:
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)
Server MCP
Connettersi ai server MCP locali (stdio) o remoti (HTTP) per le funzionalità estese:
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)
Uso dell'agente
L'agente è uno standard BaseAgent e supporta tutte le operazioni dell'agente standard.
Per altre informazioni su come eseguire e interagire con gli agenti, vedere le esercitazioni introduttive su Agent.