Hinweis
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, sich anzumelden oder das Verzeichnis zu wechseln.
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, das Verzeichnis zu wechseln.
Microsoft Agent Framework unterstützt das Erstellen von Agents, die das GitHub Copilot SDK als Back-End verwenden. GitHub Copilot-Agents bieten Zugriff auf leistungsstarke codierungsorientierte KI-Funktionen, einschließlich Shell-Befehlsausführung, Dateivorgänge, URL-Abruf und MCP-Serverintegration (Model Context Protocol).
Von Bedeutung
GitHub Copilot Agents erfordern die Installation und Authentifizierung der GitHub Copilot CLI. Zur Sicherheit wird empfohlen, Agents mit Shell- oder Dateiberechtigungen in einer containerisierten Umgebung (Docker/Dev Container) auszuführen.
Erste Schritte
Fügen Sie dem Projekt die erforderlichen NuGet-Pakete hinzu.
dotnet add package Microsoft.Agents.AI.GitHub.Copilot --prerelease
Einen GitHub Copilot-Agent erstellen
Erstellen Sie als ersten Schritt eine CopilotClient und starten Sie sie. Verwenden Sie dann die AsAIAgent Erweiterungsmethode, um einen Agent zu erstellen.
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?"));
Mit Tools und Anweisungen
Sie können Beim Erstellen des Agents Funktionstools und benutzerdefinierte Anweisungen bereitstellen:
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?"));
Agentfeatures
Streaming-Antworten
Erhalten Sie Antworten, während sie generiert werden:
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();
Sitzungsverwaltung
Den Gesprächskontext über mehrere Interaktionen hinweg mithilfe von Sitzungen beibehalten.
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"
Erlaubnisse
Standardmäßig kann der Agent keine Shellbefehle ausführen, Dateien lesen/schreiben oder URLs abrufen. Um diese Funktionen zu aktivieren, richten Sie einen Berechtigungshandler über SessionConfig ein:
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-Server
Stellen Sie eine Verbindung mit lokalen (Stdio) oder REMOTE-MCP-Servern (HTTP) für erweiterte Funktionen her:
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"));
Tipp
Vollständige Runnable-Beispiele finden Sie in den .NET-Beispielen .
Den Agent verwenden
Der Agent ist ein AIAgent Standard und unterstützt alle AIAgent Standardoperationen.
Weitere Informationen zum Ausführen und Interagieren mit Agenten finden Sie in den Agenten-Einführungstutorials.
Voraussetzungen
Installieren Sie das GitHub Copilot-Paket von Microsoft Agent Framework.
pip install agent-framework-github-copilot --pre
Konfiguration
Der Agent kann optional mithilfe der folgenden Umgebungsvariablen konfiguriert werden:
| Variable | Description |
|---|---|
GITHUB_COPILOT_CLI_PATH |
Pfad zur ausführbaren Datei der Copilot CLI |
GITHUB_COPILOT_MODEL |
Zu verwendende Modell (z. B. gpt-5, claude-sonnet-4) |
GITHUB_COPILOT_TIMEOUT |
Anforderungstimeout in Sekunden |
GITHUB_COPILOT_LOG_LEVEL |
CLI-Protokollebene |
Erste Schritte
Importieren Sie die erforderlichen Klassen aus dem Agent-Framework:
import asyncio
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions
Einen GitHub Copilot-Agent erstellen
Grundlegende Agent-Erstellung
Die einfachste Möglichkeit zum Erstellen eines GitHub Copilot-Agents:
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)
Mit expliziter Konfiguration
Sie können eine explizite Konfiguration über default_options bereitstellen.
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)
Agentfeatures
Funktionstools
Rüsten Sie Ihren Agent mit benutzerdefinierten Funktionen aus:
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)
Streaming-Antworten
Erhalten Sie Antworten, wenn sie generiert werden, um eine bessere Benutzererfahrung zu erzielen:
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()
Threadverwaltung
Den Gesprächskontext über mehrere Interaktionen hinweg beibehalten.
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"
Erlaubnisse
Standardmäßig kann der Agent keine Shellbefehle ausführen, Dateien lesen/schreiben oder URLs abrufen. Um diese Funktionen zu aktivieren, geben Sie einen Berechtigungshandler an:
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-Server
Stellen Sie eine Verbindung mit lokalen (Stdio) oder REMOTE-MCP-Servern (HTTP) für erweiterte Funktionen her:
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)
Den Agent verwenden
Der Agent ist ein Standard BaseAgent und unterstützt alle Standard-Agent-Vorgänge.
Weitere Informationen zum Ausführen und Interagieren mit Agenten finden Sie in den Agenten-Einführungstutorials.