Nuta
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować się zalogować lub zmienić katalog.
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zmienić katalogi.
Program Microsoft Agent Framework obsługuje tworzenie agentów korzystających z zestawu SDK narzędzia GitHub Copilot jako zaplecza. Agenci GitHub Copilot zapewniają dostęp do potężnych możliwości sztucznej inteligencji zorientowanej na kodowanie, w tym wykonywanie poleceń powłoki, operacje na plikach, pobieranie adresów URL oraz integrację z serwerem PROTOKOŁU MCP (Model Context Protocol).
Ważne
Agenty GitHub Copilot wymagają zainstalowania i uwierzytelnienia CLI GitHub Copilot. W przypadku zabezpieczeń zaleca się uruchamianie agentów z uprawnieniami powłoki lub plików w środowisku konteneryzowanym (Docker/Dev Container).
Wprowadzenie
Dodaj wymagane pakiety NuGet do projektu.
dotnet add package Microsoft.Agents.AI.GitHub.Copilot --prerelease
Tworzenie agenta Copilot w usłudze GitHub
Na początku utwórz CopilotClient i uruchom go. Następnie użyj AsAIAgent metody rozszerzenia, aby utworzyć agenta.
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?"));
Za pomocą narzędzi i instrukcji
Podczas tworzenia agenta można udostępnić narzędzia funkcji i instrukcje niestandardowe:
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?"));
Funkcje agenta
Odpowiedzi w strumieniowaniu
Pobierz odpowiedzi w miarę ich generowania:
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();
Zarządzanie sesjami
Zachowaj kontekst konwersacji w wielu interakcjach przy użyciu sesji:
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
Domyślnie agent nie może wykonywać poleceń powłoki, odczytywać/zapisywać plików ani pobierać URL-i. Aby włączyć te możliwości, podaj procedurę obsługi uprawnień za pomocą polecenia 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"));
Serwery MCP
Nawiąż połączenie z lokalnymi (stdio) lub zdalnymi serwerami MCP (HTTP), aby uzyskać rozszerzone możliwości:
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"));
Tip
Zobacz przykłady dla platformy .NET , aby uzyskać pełne przykłady możliwych do uruchomienia.
Korzystanie z agenta
Agent jest standardowy AIAgent i obsługuje wszystkie standardowe AIAgent operacje.
Aby uzyskać więcej informacji na temat uruchamiania agentów i interakcji z nimi, zobacz samouczki wprowadzające do agenta.
Wymagania wstępne
Zainstaluj pakiet GitHub Copilot programu Microsoft Agent Framework.
pip install agent-framework-github-copilot --pre
Konfiguracja
Agent można opcjonalnie skonfigurować przy użyciu następujących zmiennych środowiskowych:
| Variable | Opis |
|---|---|
GITHUB_COPILOT_CLI_PATH |
Ścieżka do pliku wykonywalnego Copilot CLI |
GITHUB_COPILOT_MODEL |
Model do użycia (np. gpt-5, claude-sonnet-4) |
GITHUB_COPILOT_TIMEOUT |
Limit czasu żądania w sekundach |
GITHUB_COPILOT_LOG_LEVEL |
Poziom logów CLI |
Wprowadzenie
Zaimportuj wymagane klasy z programu Agent Framework:
import asyncio
from agent_framework.github import GitHubCopilotAgent, GitHubCopilotOptions
Tworzenie agenta Copilot w usłudze GitHub
Tworzenie podstawowego agenta
Najprostszy sposób na stworzenie agenta 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)
Z jawną konfiguracją
Konfigurację jawną można podać za pomocą elementu 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)
Funkcje agenta
Narzędzia funkcji
Wyposażyć agenta w funkcje niestandardowe:
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)
Odpowiedzi w strumieniowaniu
Uzyskuj odpowiedzi w miarę ich generowania w celu lepszego doświadczenia użytkownika.
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()
Zarządzanie wątkami
Zachowaj kontekst konwersacji w wielu interakcjach:
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
Domyślnie agent nie może wykonywać poleceń powłoki, odczytywać/zapisywać plików ani pobierać URL-i. Aby włączyć te możliwości, podaj procedurę obsługi uprawnień:
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)
Serwery MCP
Nawiąż połączenie z lokalnymi (stdio) lub zdalnymi serwerami MCP (HTTP), aby uzyskać rozszerzone możliwości:
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)
Korzystanie z agenta
Agent jest standardowy BaseAgent i obsługuje wszystkie standardowe operacje agenta.
Aby uzyskać więcej informacji na temat uruchamiania agentów i interakcji z nimi, zobacz samouczki wprowadzające do agenta.