🦔

Microsoft Agent Framework (C#) を見てみよう その13 .NET 10用のAgentプロジェクトテンプレート

に公開

シリーズ記事

はじめに

先日、.NET 10 と Visual Studio 2026 がリリースされました。それにあわせて Microsoft Agent Framework を使ったアプリケーション用のプロジェクトテンプレートもリリースされていました。

Microsoft.Agents.AI.ProjectTemplates という NuGet パッケージで提供されており、.NET 10 SDK がインストールされている環境であれば以下のコマンドでインストールできます。

dotnet new install Microsoft.Agents.AI.ProjectTemplates::1.0.0-preview.1.25560.10

インストールが完了したら dotnet new コマンドでもテンプレートが利用できるようになりますし、Visual Studio 2026 の新規プロジェクトの作成ダイアログでも、以下のように AI Agent Web API プロジェクトテンプレートが選択できるようになります。

API なんですね。ちょっと意外。

プロジェクトを作成してみる

ということで早速 Visual Studio 2026 で新規プロジェクトを作成してみました。
モデルとして Azure OpenAI や GitHub Models や Ollama などが選べますが、開発用途で一番使いやすい GitHub Models を選択しました。そうすると GITHUB_TOKEN という名前のユーザーシークレットか環境変数を作って実行するように説明されている README が表示されます。

そこに書いてある以下の手順に従って GITHUB_TOKEN の取得を行いました。

#### Get a GitHub Models Token

1. Visit [GitHub Models](https://github.com/marketplace/models)
2. Sign in with your GitHub account
3. Select a model (e.g., gpt-4o-mini)
4. Click "Get API Key" or follow the authentication instructions
5. Copy your personal access token

取得したトークンは Visual Studio のソリューションエクスプローラーでプロジェクトを右クリックして「ユーザーシークレットの管理」を選択して、GITHUB_TOKEN という名前で以下のように登録しました。

secrets.json
{
  "GITHUB_TOKEN": "github_pat_xxxx..."
}

実行すると以下のような画面が表示されます。動く…!

これは Microsoft Agent Framework の DevUI という Agent や Workflow を試すための開発用の UI になります。
画面があるのいいですね。

コードを見てみよう

プロジェクトのコードを見てみましょう。
といっても、驚くくらい少ないコードで実装されています。プログラムは Program.cs だけです。

Program.cs
using System.ClientModel;
using System.ComponentModel;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.DevUI;
using Microsoft.Agents.AI.Hosting;
using Microsoft.Agents.AI.Workflows;
using Microsoft.Extensions.AI;
using OpenAI;
using OpenAI.Chat;

var builder = WebApplication.CreateBuilder(args);

// You will need to set the token to your own value
// You can do this using Visual Studio's "Manage User Secrets" UI, or on the command line:
//   cd this-project-directory
//   dotnet user-secrets set "GITHUB_TOKEN" "your-github-models-token-here"
var chatClient = new ChatClient(
        "gpt-4o-mini",
        new ApiKeyCredential(builder.Configuration["GITHUB_TOKEN"] ?? throw new InvalidOperationException("Missing configuration: GITHUB_TOKEN")),
        new OpenAIClientOptions { Endpoint = new Uri("https://models.inference.ai.azure.com") })
    .AsIChatClient();

builder.Services.AddChatClient(chatClient);

builder.AddAIAgent("writer", "You write short stories (300 words or less) about the specified topic.");

builder.AddAIAgent("editor", (sp, key) => new ChatClientAgent(
    chatClient,
    name: key,
    instructions: "You edit short stories to improve grammar and style, ensuring the stories are less than 300 words. Once finished editing, you select a title and format the story for publishing.",
    tools: [AIFunctionFactory.Create(FormatStory)]
));

builder.AddWorkflow("publisher", (sp, key) => AgentWorkflowBuilder.BuildSequential(
    workflowName: key,
    sp.GetRequiredKeyedService<AIAgent>("writer"),
    sp.GetRequiredKeyedService<AIAgent>("editor")
)).AddAsAIAgent();

// Register services for OpenAI responses and conversations (also required for DevUI)
builder.Services.AddOpenAIResponses();
builder.Services.AddOpenAIConversations();

var app = builder.Build();
app.UseHttpsRedirection();

// Map endpoints for OpenAI responses and conversations (also required for DevUI)
app.MapOpenAIResponses();
app.MapOpenAIConversations();

if (builder.Environment.IsDevelopment())
{
    // Map DevUI endpoint to /devui
    app.MapDevUI();
}

app.Run();

[Description("Formats the story for publication, revealing its title.")]
string FormatStory(string title, string story) => $"""
    **Title**: {title}

    {story}
    """;

コメントや空行を除くと 40 行程度しかありません。かなりシンプルですね。この中で注目すべきは AddAIAgentAddWorkflow メソッドだと思います。これらの拡張メソッドを使って Agent や Workflow を DI コンテナに登録しています。さらに興味深いのは以下の 4 行です。

// Register services for OpenAI responses and conversations (also required for DevUI)
builder.Services.AddOpenAIResponses();
builder.Services.AddOpenAIConversations();

// 中略

// Map endpoints for OpenAI responses and conversations (also required for DevUI)
app.MapOpenAIResponses();
app.MapOpenAIConversations();

この 4 行を追加するだけで OpenAI の Responses API が生えるっぽいです。これは普通に便利ですね。
この Responses API を通じて DevUI が動いているようです。DevUI を追加するには、以下のように MapDevUI メソッドを呼び出します。これで先ほどの DevUI の画面が利用できるようになります。

if (builder.Environment.IsDevelopment())
{
    // Map DevUI endpoint to /devui
    app.MapDevUI();
}

これだけでチャットやワークフローを試せる UI が利用できるのはとても便利ですね。ワークフローを試せる画面も以下のように、とてもいい感じです。

Chat Completion API の利用

AddOpenAIResponses, AddOpenAIConversationsMapOpenAIResponsesMapOpenAIConversations を使うことで、OpenAI の Responses API を簡単に利用できるようになるのですが、実は AddOpenAIChatCompletionsMapOpenAIChatCompletions で Chat Completions API も利用できるようになります。MapOpenAIChatCompletions の引数には AIAgent を渡すことで、そのエージェントを使った Chat Completions API のエンドポイントが生えます。例えば、以下のように writer という名前のエージェントを Chat Completions API としてマッピングできます。

builder.Services.AddOpenAIChatCompletions();

// 中略

app.MapOpenAIChatCompletions(app.Services.GetRequiredKeyedService<AIAgent>("writer"));

こうすることで以下のように Chat Completions API として Agent が叩けるようになります。

using Azure;
using Azure.AI.OpenAI;
using Microsoft.Extensions.AI;
var client = new HttpClient
{
    BaseAddress = new("https://localhost:7226")
};

var response = await client.PostAsync("/writer/v1/chat/completions",
    new StringContent("""
        {
          "model": "gpt-4.1",
          "messages": [
            { "role": "user", "content": "Hello world" }
          ]
        }
        """,
        System.Text.Encoding.UTF8,
        "application/json"));
Console.WriteLine(await response.Content.ReadAsStringAsync());

地味に便利かもしれないですね。

まとめ

ということで軽くテンプレートを見てみました。
AddAIAgent や AddWorkflow、MapDevUI などの拡張メソッドを使うことで、かなり簡単にエージェントやワークフローを登録して試せるようになっていることが分かりました。Responses API や Chat Completions API として Agent を公開することもできるのでかなりやりやすくなってますね。

正式リリースは来年の早いタイミングみたいなので、楽しみです。

Microsoft (有志)

Discussion