Skip to main content

Microsoft代理框架集成

Microsoft Agent Framework(MAF)中将 Copilot SDK 用作代理提供程序,并结合 Azure OpenAI、Anthropic 和其他提供程序来构建多代理工作流。

概述

Microsoft Agent Framework 是语义内核和 AutoGen 的统一继任者。 它提供用于生成、协调和部署 AI 代理的标准接口。 借助专用集成包,可以将 Copilot SDK 客户端包装为一流的 MAF 代理,与框架中的其他任何代理提供程序互换。

概念说明
Microsoft代理框架用于 .NET 和 Python 的单代理和多代理编排的开源框架
代理提供程序为助手(如 Copilot、Azure OpenAI、Anthropic 等)提供支持的后端。
业务流程协调程序****在顺序、并发或切换工作流中协调智能体的 MAF 组件
A2A 协议框架支持的代理到代理通信标准

注意

MAF 集成包可用于 .NETPython。 对于 TypeScript、Go、Java 和 Rust,直接使用 Copilot SDK—标准 SDK API 已经提供工具调用、流式处理和自定义代理。

先决条件

在开始之前,请确保具备:

安装

同时安装 Copilot SDK 和适用于您的编程语言的 MAF 集成包:

.NET
dotnet add package GitHub.Copilot.SDK
dotnet add package Microsoft.Agents.AI.GitHub.Copilot --prerelease
Python
pip install copilot-sdk agent-framework-github-copilot
Java

注意

Java SDK 没有专用 MAF 集成包。 直接使用标准 Copilot SDK——它开箱即用地提供工具调用、流式传输和自定义代理。

<!-- Maven -->
<!-- Set copilot.sdk.version to the version published in java/README.md / Maven Central -->
<dependency>
    <groupId>com.github</groupId>
    <artifactId>copilot-sdk-java</artifactId>
    <version>${copilot.sdk.version}</version>
</dependency>

基本用法

使用单个方法调用将 Copilot SDK 客户端包装为 MAF 代理。 生成的代理符合框架的标准接口,可在预期 MAF 代理的任何位置使用。

.NET
using GitHub.Copilot;
using Microsoft.Agents.AI;

await using var copilotClient = new CopilotClient();
await copilotClient.StartAsync();

// Wrap as a MAF agent
AIAgent agent = copilotClient.AsAIAgent();

// Use the standard MAF interface
string response = await agent.RunAsync("Explain how dependency injection works in ASP.NET Core");
Console.WriteLine(response);
Python
from agent_framework.github import GitHubCopilotAgent

async def main():
    agent = GitHubCopilotAgent(
        default_options={
            "instructions": "You are a helpful coding assistant.",
        }
    )

    async with agent:
        result = await agent.run("Explain how dependency injection works in FastAPI")
        print(result)
Java
import com.github.copilot.sdk.CopilotClient;
import com.github.copilot.sdk.events.*;
import com.github.copilot.sdk.json.*;

var client = new CopilotClient();
client.start().get();

var session = client.createSession(new SessionConfig()
    .setModel("gpt-4.1")
    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();

var response = session.sendAndWait(new MessageOptions()
    .setPrompt("Explain how dependency injection works in Spring Boot")).get();
System.out.println(response.getData().content());

client.stop().get();

添加自定义工具

使用自定义函数工具扩展Copilot 智能体。 当代理在 MAF 中运行时,通过标准Copilot SDK 定义的工具将自动可用。

.NET
using GitHub.Copilot;
using Microsoft.Extensions.AI;
using Microsoft.Agents.AI;

// Define a custom tool
AIFunction weatherTool = CopilotTool.DefineTool(
    (string location) => $"The weather in {location} is sunny with a high of 25°C.",
    factoryOptions: new AIFunctionFactoryOptions
    {
        Name = "GetWeather",
        Description = "Get the current weather for a given location.",
    }
);

await using var copilotClient = new CopilotClient();
await copilotClient.StartAsync();

// Create agent with tools
AIAgent agent = copilotClient.AsAIAgent(new AIAgentOptions
{
    Tools = new[] { weatherTool },
});

string response = await agent.RunAsync("What's the weather like in Seattle?");
Console.WriteLine(response);
Python
from agent_framework.github import GitHubCopilotAgent

def get_weather(location: str) -> str:
    """Get the current weather for a given location."""
    return f"The weather in {location} is sunny with a high of 25°C."

async def main():
    agent = GitHubCopilotAgent(
        default_options={
            "instructions": "You are a helpful assistant with access to weather data.",
        },
        tools=[get_weather],
    )

    async with agent:
        result = await agent.run("What's the weather like in Seattle?")
        print(result)

还可以将 Copilot SDK 的本机工具定义与 MAF 工具一起使用:

TypeScript
import { CopilotClient, DefineTool } from "@github/copilot-sdk";

const getWeather = DefineTool({
    name: "GetWeather",
    description: "Get the current weather for a given location.",
    parameters: { location: { type: "string", description: "City name" } },
    execute: async ({ location }) => `The weather in ${location} is sunny, 25°C.`,
});

const client = new CopilotClient();
const session = await client.createSession({
    model: "gpt-4.1",
    tools: [getWeather],
    onPermissionRequest: async () => ({ kind: "approve-once" }),
});

await session.sendAndWait({ prompt: "What's the weather like in Seattle?" });
Java
import com.github.copilot.sdk.CopilotClient;
import com.github.copilot.sdk.events.*;
import com.github.copilot.sdk.json.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

var getWeather = ToolDefinition.create(
    "GetWeather",
    "Get the current weather for a given location.",
    Map.of(
        "type", "object",
        "properties", Map.of(
            "location", Map.of("type", "string", "description", "City name")),
        "required", List.of("location")),
    invocation -> {
        var location = (String) invocation.getArguments().get("location");
        return CompletableFuture.completedFuture(
            "The weather in " + location + " is sunny, 25°C.");
    });

try (var client = new CopilotClient()) {
    client.start().get();

    var session = client.createSession(new SessionConfig()
        .setModel("gpt-4.1")
        .setTools(List.of(getWeather))
        .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
    ).get();

    session.sendAndWait(new MessageOptions()
        .setPrompt("What's the weather like in Seattle?")).get();
}

多代理工作流

MAF 集成的主要优势在于,能够在编排式工作流中将 Copilot 与其他代理提供程序结合使用。 使用框架内置的编排器创建流水线,不同的代理负责不同的步骤。

顺序工作流

逐个运行代理,将输出从一个传递到下一个:

.NET
using GitHub.Copilot;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Orchestration;

await using var copilotClient = new CopilotClient();
await copilotClient.StartAsync();

// Copilot agent for code review
AIAgent reviewer = copilotClient.AsAIAgent(new AIAgentOptions
{
    Instructions = "You review code for bugs, security issues, and best practices. Be thorough.",
});

// Azure OpenAI agent for generating documentation
AIAgent documentor = AIAgent.FromOpenAI(new OpenAIAgentOptions
{
    Model = "gpt-4.1",
    Instructions = "You write clear, concise documentation for code changes.",
});

// Compose in a sequential pipeline
var pipeline = new SequentialOrchestrator(new[] { reviewer, documentor });

string result = await pipeline.RunAsync(
    "Review and document this pull request: added retry logic to the HTTP client"
);
Console.WriteLine(result);
Python
from agent_framework.github import GitHubCopilotAgent
from agent_framework.openai import OpenAIAgent
from agent_framework.orchestration import SequentialOrchestrator

async def main():
    # Copilot agent for code review
    reviewer = GitHubCopilotAgent(
        default_options={
            "instructions": "You review code for bugs, security issues, and best practices.",
        }
    )

    # OpenAI agent for documentation
    documentor = OpenAIAgent(
        model="gpt-4.1",
        instructions="You write clear, concise documentation for code changes.",
    )

    # Compose in a sequential pipeline
    pipeline = SequentialOrchestrator(agents=[reviewer, documentor])

    async with pipeline:
        result = await pipeline.run(
            "Review and document this PR: added retry logic to the HTTP client"
        )
        print(result)
Java
import com.github.copilot.sdk.CopilotClient;
import com.github.copilot.sdk.events.*;
import com.github.copilot.sdk.json.*;

// Java uses the standard SDK directly — no MAF orchestrator needed
var client = new CopilotClient();
client.start().get();

// Step 1: Code review session
var reviewer = client.createSession(new SessionConfig()
    .setModel("gpt-4.1")
    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();

var review = reviewer.sendAndWait(new MessageOptions()
    .setPrompt("Review this PR for bugs, security issues, and best practices: "
        + "added retry logic to the HTTP client")).get();

// Step 2: Documentation session using review output
var documentor = client.createSession(new SessionConfig()
    .setModel("gpt-4.1")
    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();

var docs = documentor.sendAndWait(new MessageOptions()
    .setPrompt("Write documentation for these changes: " + review.getData().content())).get();
System.out.println(docs.getData().content());

client.stop().get();

并发工作流

并行运行多个代理并聚合其结果:

.NET
using GitHub.Copilot;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Orchestration;

await using var copilotClient = new CopilotClient();
await copilotClient.StartAsync();

AIAgent securityReviewer = copilotClient.AsAIAgent(new AIAgentOptions
{
    Instructions = "Focus exclusively on security vulnerabilities and risks.",
});

AIAgent performanceReviewer = copilotClient.AsAIAgent(new AIAgentOptions
{
    Instructions = "Focus exclusively on performance bottlenecks and optimization opportunities.",
});

// Run both reviews concurrently
var concurrent = new ConcurrentOrchestrator(new[] { securityReviewer, performanceReviewer });

string combinedResult = await concurrent.RunAsync(
    "Analyze this database query module for issues"
);
Console.WriteLine(combinedResult);
Java
import com.github.copilot.sdk.CopilotClient;
import com.github.copilot.sdk.events.*;
import com.github.copilot.sdk.json.*;
import java.util.concurrent.CompletableFuture;

// Java uses CompletableFuture for concurrent execution
var client = new CopilotClient();
client.start().get();

var securitySession = client.createSession(new SessionConfig()
    .setModel("gpt-4.1")
    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();

var perfSession = client.createSession(new SessionConfig()
    .setModel("gpt-4.1")
    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();

// Run both reviews concurrently
var securityFuture = securitySession.sendAndWait(new MessageOptions()
    .setPrompt("Focus on security vulnerabilities in this database query module"));
var perfFuture = perfSession.sendAndWait(new MessageOptions()
    .setPrompt("Focus on performance bottlenecks in this database query module"));

CompletableFuture.allOf(securityFuture, perfFuture).get();

System.out.println("Security: " + securityFuture.get().getData().content());
System.out.println("Performance: " + perfFuture.get().getData().content());

client.stop().get();

流式响应

在构建交互式应用程序时,通过流式传输代理的响应,以显示实时输出。 MAF 集成保留了 Copilot SDK 的流式传输能力。

.NET
using GitHub.Copilot;
using Microsoft.Agents.AI;

await using var copilotClient = new CopilotClient();
await copilotClient.StartAsync();

AIAgent agent = copilotClient.AsAIAgent(new AIAgentOptions
{
    Streaming = true,
});

await foreach (var chunk in agent.RunStreamingAsync("Write a quicksort implementation in C#"))
{
    Console.Write(chunk);
}
Console.WriteLine();
Python
from agent_framework.github import GitHubCopilotAgent

async def main():
    agent = GitHubCopilotAgent(
        default_options={"streaming": True}
    )

    async with agent:
        async for chunk in agent.run_streaming("Write a quicksort in Python"):
            print(chunk, end="", flush=True)
        print()

还可以直接通过没有 MAF 的 Copilot SDK 进行流式传输:

TypeScript
import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();
const session = await client.createSession({
    model: "gpt-4.1",
    streaming: true,
    onPermissionRequest: async () => ({ kind: "approve-once" }),
});

session.on("assistant.message_delta", (event) => {
    process.stdout.write(event.data.delta ?? "");
});

await session.sendAndWait({ prompt: "Write a quicksort implementation in TypeScript" });
Java
import com.github.copilot.sdk.CopilotClient;
import com.github.copilot.sdk.events.*;
import com.github.copilot.sdk.json.*;

var client = new CopilotClient();
client.start().get();

var session = client.createSession(new SessionConfig()
    .setModel("gpt-4.1")
    .setStreaming(true)
    .setOnPermissionRequest(PermissionHandler.APPROVE_ALL)
).get();

session.on(AssistantMessageDeltaEvent.class, event -> {
    System.out.print(event.getData().deltaContent());
});

session.sendAndWait(new MessageOptions()
    .setPrompt("Write a quicksort implementation in Java")).get();
System.out.println();

client.stop().get();

配置参考

MAF 代理选项

财产类型说明
Instructions / instructionsstring代理的系统提示
Tools / toolsAIFunction[] / list代理可用的自定义函数工具
Streaming / streamingbool启用流式处理响应
Model / modelstring覆盖默认模型

Copilot SDK 选项(直通传递)

创建基础Copilot客户端时,所有标准 构建你的第一个由 Copilot 提供支持的应用 选项仍然可用。 MAF 包装器在底层调用 SDK:

SDK 功能MAF 支持
自定义工具 (DefineTool / AIFunctionFactory
✅ 已与 MAF 工具合并
MCP 服务器
✅ 在 SDK 客户端上配置
自定义代理/子代理
✅ 在 Copilot 代理中可用
无限会话
✅ 在 SDK 客户端上配置
模型选择
✅ 可重写每个代理或每个调用
流媒体
✅ 完整增量事件支持

最佳做法

选择正确的集成级别

当您需要在编排工作流中将 Copilot 与其他提供程序集成时,请使用 MAF 包装器。 如果您的应用仅使用 Copilot,那么独立的 SDK 更简单,并且可让您完全掌控:

// Standalone SDK — full control, simpler setup
import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();
const session = await client.createSession({
    model: "gpt-4.1",
    onPermissionRequest: async () => ({ kind: "approve-once" }),
});
const response = await session.sendAndWait({ prompt: "Explain this code" });

使代理保持专注

生成多代理工作流时,请为每个代理提供一个具有明确说明的特定角色。 避免重叠责任:

// ❌ Too vague — overlapping roles
const agents = [
    { instructions: "Help with code" },
    { instructions: "Assist with programming" },
];

// ✅ Focused — clear separation of concerns
const agents = [
    { instructions: "Review code for security vulnerabilities. Flag SQL injection, XSS, and auth issues." },
    { instructions: "Optimize code performance. Focus on algorithmic complexity and memory usage." },
];

在业务流程级别处理错误

将智能体调用包装在错误处理中,尤其是在多智能体工作流中,其中一个智能体的故障不应阻止整个管道:

try
{
    string result = await pipeline.RunAsync("Analyze this module");
    Console.WriteLine(result);
}
catch (AgentException ex)
{
    Console.Error.WriteLine($"Agent {ex.AgentName} failed: {ex.Message}");
    // Fall back to single-agent mode or retry
}

另见