Skip to main content

Microsoft エージェント フレームワークの統合

Copilot SDK を Microsoft Agent Framework (MAF) 内のエージェント プロバイダーとして使用して、OpenAI、Anthropic、その他のプロバイダーと共にマルチエージェント ワークフロー Azure作成します。

概要

Microsoft Agent Framework は、セマンティック カーネルと AutoGen の統合後継です。 これは、AI エージェントを構築、調整、デプロイするための標準インターフェイスを提供します。 専用統合パッケージを使用すると、Copilot SDK クライアントをファースト クラスの MAF エージェントとしてラップできます。フレームワーク内の他のエージェント プロバイダーと交換できます。

概念説明
Microsoft Agent Framework.NET および Python での単一エージェントおよびマルチエージェント オーケストレーション用のオープン ソース フレームワーク
エージェント プロバイダーエージェントを利用するバックエンド (Copilot、Azure OpenAI、Anthropic など)
オーケストレーター順次ワークフロー、同時実行ワークフロー、またはハンドオフ ワークフローでエージェントを調整する MAF コンポーネント
A2A プロトコルフレームワークでサポートされているエージェント間通信標準

メモ

MAF 統合パッケージは、.NET および Python で使用できます。 TypeScript、Go、Java、Rustは、Copilot SDK を直接使用します。標準の SDK API には、既にツールの呼び出し、ストリーミング、カスタム エージェントが用意されています。

前提条件

始める前に、以下のことを確認してください:

  • 選択した言語で動作する 初めてのCopilot搭載アプリを構築する
  • GitHub Copilot サブスクリプション (個人、ビジネス、またはエンタープライズ)
  • COPILOT CLI がインストールされているか、SDK のバンドルされた CLI を介して使用できる

Installation

言語の MAF 統合パッケージと共に Copilot SDK をインストールします。

.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 エージェントとして 1 つのメソッド呼び出しでラップします。 結果のエージェントはフレームワークの標準インターフェイスに準拠しており、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 エージェントを拡張します。 標準の Copilot SDK を使用して定義されたツールは、エージェントが MAF 内で実行されるときに自動的に使用できます。

.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を作成することです。 フレームワークの組み込みのオーケストレーターを使用して、異なるエージェントが異なる手順を処理するパイプラインを作成します。

シーケンシャル ワークフロー

エージェントを 1 つずつ実行し、出力を次のエージェントに渡します。

.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." },
];

オーケストレーション レベルでエラーを処理する

エラー処理でエージェント呼び出しをラップします。特に、1 つのエージェントのエラーによってパイプライン全体がブロックされるべきではないマルチエージェント ワークフローでは、次のようになります。

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
}

こちらも参照ください