微软 Agent Framework 集成 GitHub Copilot SDK,支持构建多智能体 AI 应用

Microsoft Agent Framework 现已集成 GitHub Copilot SDK,让你能够构建由 GitHub Copilot 驱动的 AI Agent。此次集成将 Agent Framework 的统一 Agent 抽象与 GitHub Copilot 的能力结合在一起,包括函数调用、流式响应、多轮对话、Shell 命令执行、文件操作、URL 抓取,以及 Model Context Protocol(MCP)服务器集成——并且 .NET 和 Python 都可用。
为什么要将 Agent Framework 与 GitHub Copilot SDK 一起使用?
你当然可以单独使用 GitHub Copilot SDK 来构建 Agent。那为什么还要通过 Agent Framework 来用?核心原因如下:
- 统一的 Agent 抽象 —— GitHub Copilot Agent 实现了与框架中其他 Agent 相同的
AIAgent(.NET)/BaseAgent(Python)接口。你可以在不重构代码的前提下替换 provider,或将多个 provider 组合使用。 - 多智能体工作流 —— 借助内置编排器,可将 GitHub Copilot Agent 与其他 Agent(Azure OpenAI、OpenAI、Anthropic 等)组合为串行、并行、handoff 和群聊等工作流。
- 生态集成 —— 可直接接入完整 Agent Framework 生态:声明式 Agent 定义、A2A 协议支持,以及跨 provider 一致的函数工具、会话与流式处理模式。
简而言之,Agent Framework 让你把 GitHub Copilot 当作更大 Agent 系统中的一个构建模块,而不是一个孤立工具。
安装 GitHub Copilot 集成
.NET
dotnet add package Microsoft.Agents.AI.GitHub.Copilot --prerelease
Python
pip install agent-framework-github-copilot --pre
创建 GitHub Copilot Agent
上手非常直接。创建一个 CopilotClient(.NET)或 GitHubCopilotAgent(Python),然后开始与 Agent 交互。
.NET
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?"));
Python
from agent_framework.github import GitHubCopilotAgent
async def main():
agent = GitHubCopilotAgent(
default_options={"instructions": "You are a helpful assistant."},
)
async with agent:
result = await agent.run("What is Microsoft Agent Framework?")
print(result)
添加函数工具
通过自定义函数工具扩展 Agent,为其注入领域能力。
.NET
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?"));
Python
from typing import Annotated
from pydantic import Field
from agent_framework.github import GitHubCopilotAgent
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 main():
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)
流式输出响应
为获得更好的用户体验,你可以在生成过程中实时流式输出,而不是等完整结果返回。
.NET
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();
Python
from agent_framework.github import GitHubCopilotAgent
async def main():
agent = GitHubCopilotAgent(
default_options={"instructions": "You are a helpful assistant."},
)
async with agent:
print("Agent: ", end="", flush=True)
async for chunk in agent.run_stream("Tell me a short story."):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
多轮对话
可通过 session(.NET)或 thread(Python)在多次交互中保持上下文。
.NET
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.GetNewSessionAsync();
// 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"
Python
from agent_framework.github import GitHubCopilotAgent
async def main():
agent = GitHubCopilotAgent(
default_options={"instructions": "You are a helpful assistant."},
)
async with agent:
thread = agent.get_new_thread()
# First interaction
result1 = await agent.run("My name is Alice.", thread=thread)
print(f"Agent: {result1}")
# Second interaction - agent remembers the context
result2 = await agent.run("What's my name?", thread=thread)
print(f"Agent: {result2}") # Should remember "Alice"
启用权限控制
默认情况下,Agent 不能执行 Shell 命令、读写文件或抓取 URL。要启用这些能力,需要提供一个权限处理器来批准或拒绝请求。
.NET
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"));
Python
from agent_framework.github import GitHubCopilotAgent
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 main():
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 服务器
GitHub Copilot Agent 支持连接本地(stdio)和远程(HTTP)MCP 服务器,让 Agent 能访问外部工具与数据源。
.NET
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"));
Python
from agent_framework.github import GitHubCopilotAgent
from copilot.types import MCPServerConfig
async def main():
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)
在多智能体工作流中使用 GitHub Copilot
使用 Agent Framework 的关键价值之一,是能把 GitHub Copilot 与其他 Agent 组合进同一多智能体工作流。下面这个示例中,Azure OpenAI Agent 先生成营销标语,再由 GitHub Copilot Agent 审阅——全流程由串行 pipeline 编排。
.NET
using Azure.AI.OpenAI;
using Azure.Identity;
using GitHub.Copilot.SDK;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.GitHub.Copilot;
using Microsoft.Agents.AI.Workflows;
using Microsoft.Extensions.AI;
// Create an Azure OpenAI agent as a copywriter
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!;
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
var chatClient = new AzureOpenAIClient(new Uri(endpoint), new AzureCliCredential())
.GetChatClient(deploymentName)
.AsIChatClient();
ChatClientAgent writer = new(chatClient,
"You are a concise copywriter. Provide a single, punchy marketing sentence based on the prompt.",
"writer");
// Create a GitHub Copilot agent as a reviewer
await using CopilotClient copilotClient = new();
await copilotClient.StartAsync();
GitHubCopilotAgent reviewer = new(copilotClient,
instructions: "You are a thoughtful reviewer. Give brief feedback on the previous assistant message.");
// Build a sequential workflow: writer -> reviewer
Workflow workflow = AgentWorkflowBuilder.BuildSequential([writer, reviewer]);
// Run the workflow
await using StreamingRun run = await InProcessExecution.StreamAsync(workflow, input: prompt);
await run.TrySendMessageAsync(new TurnToken(emitEvents: true));
await foreach (WorkflowEvent evt in run.WatchStreamAsync())
{
if (evt is AgentResponseUpdateEvent e)
{
Console.Write(e.Update.Text);
}
}
Python
import asyncio
from typing import cast
from agent_framework import ChatMessage, Role, SequentialBuilder, WorkflowOutputEvent
from agent_framework.azure import AzureOpenAIChatClient
from agent_framework.github import GitHubCopilotAgent
from azure.identity import AzureCliCredential
async def main():
# Create an Azure OpenAI agent as a copywriter
chat_client = AzureOpenAIChatClient(credential=AzureCliCredential())
writer = chat_client.as_agent(
instructions="You are a concise copywriter. Provide a single, punchy marketing sentence based on the prompt.",
name="writer",
)
# Create a GitHub Copilot agent as a reviewer
reviewer = GitHubCopilotAgent(
default_options={"instructions": "You are a thoughtful reviewer. Give brief feedback on the previous assistant message."},
name="reviewer",
)
# Build a sequential workflow: writer -> reviewer
workflow = SequentialBuilder().participants([writer, reviewer]).build()
# Run the workflow
async for event in workflow.run_stream("Write a tagline for a budget-friendly electric bike."):
if isinstance(event, WorkflowOutputEvent):
messages = cast(list[ChatMessage], event.data)
for msg in messages:
name = msg.author_name or ("assistant" if msg.role == Role.ASSISTANT else "user")
print(f"[{name}]: {msg.text}\n")
asyncio.run(main())
这个例子展示了如何在单个工作流中组合不同 provider 的 Agent。你也可以将同样模式扩展到并行、handoff 和群聊工作流。
更多信息
总结
微软 Agent Framework 对 GitHub Copilot SDK 的集成,让构建可利用 GitHub Copilot 能力的 AI Agent 变得更加简单。借助 .NET 与 Python 双栈对函数工具、流式响应、多轮会话、权限机制和 MCP 服务器的支持,你可以构建能与代码、文件、Shell 命令以及外部服务交互的强大 Agent 应用。
我们也非常期待你的反馈。如果你有建议、问题或希望进一步讨论,欢迎在 GitHub 的讨论区与我们和社区交流!如果你喜欢 Agent Framework,也欢迎在 GitHub 上给我们点个 Star。
分类
作者

高级软件工程师

