microsoft-agent-framework について
Python または C# でステートフルな AI エージェントやワークフローを構築するための Microsoft Agent Framework のガイドです。ツール、共有コンテキスト、ミドルウェア、テレメトリーを扱います。
主な機能
- 01ステートフルな対話エージェント
- 02グラフベースのワークフロー編成
- 03ツールと関数の統合
- 04共有コンテキストと会話状態
- 05ミドルウェアとテレメトリー
- 06人による承認と構造化出力
活用シーン
- 01複数ターンの対話エージェントの構築
- 02条件分岐や並列ワークフローによるエージェント連携
- 03承認処理付きツール呼び出しの追加
MCP 対応
フレームワークは統合機能として MCP をサポートします。スキルには MCP サーバーの接続や管理方法の記載はありません。
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ rysweet/ amplihack --skill microsoft-agent-frameworkインストール後、Claude Code で/microsoft-agent-frameworkを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
IMPLEMENTATION_SUMMARY.mdREADME.mdexamples/01-basic-agent.py02-tool-integration.py03-simple-workflow.py04-basic-agent.cs05-tool-integration.cs06-simple-workflow.csintegration/amplihack-integration.mddecision-framework.mdmigration-guide.mdmetadata/last-updated.txtsources.jsonversion-tracking.jsonreference/01-overview.md02-agents.md03-workflows.md04-tools-functions.md05-context-middleware.md06-telemetry-monitoring.md07-advanced-patterns.mdscripts/check-freshness.py詳細
Microsoft Agent Framework スキル
バージョン: 0.1.0-preview | 最終更新日: 2025-11-15 | フレームワークのバージョン: 0.1.0-preview 言語: Python 3.10+、C# (.NET 8.0+) | ライセンス: MIT
クイックリファレンス
Microsoft Agent Framework は、AutoGen のシンプルさと Semantic Kernel のエンタープライズ機能を統合した、実運用向けの AI エージェントとワークフローを構築するためのオープンソースプラットフォームです。
主な機能: AI エージェント(状態を保持する会話、ツール統合) | ワークフロー(グラフベースのオーケストレーション、並列処理) | エンタープライズ機能(テレメトリ、ミドルウェア、MCP サポート)
インストール:
- Python:
pip install agent-framework-core --pre - C#:
dotnet add package Microsoft.Agents.AI --prerelease
リポジトリ: https://github.com/microsoft/agent-framework(星 5.1k)
このスキルを使用する場面
次の用途には、Microsoft Agent Framework を使用してください。
- 実運用向けの AI エージェント(テレメトリ、ミドルウェア、構造化出力などのエンタープライズ機能)
- マルチエージェントのオーケストレーション(条件分岐ルーティングを備えたグラフベースのワークフロー)
- ツール/関数の統合(承認ワークフローとエラー処理)
- クロスプラットフォーム開発(Python と C# の両方の実装が必要な場合)
- 研究から実運用へのパイプライン(AutoGen と Semantic Kernel の融合を活用)
amplihack との統合: 状態を保持する会話型エージェントと複雑なオーケストレーションには Agent Framework を使用してください。ステートレスなタスク委任とシンプルなオーケストレーションには amplihack のネイティブエージェントシステムを使用してください。詳しいガイダンスについては、@integration/decision-framework.md を参照してください。
主な概念
1. AI エージェント
メッセージを処理し、ツールを呼び出し、コンテキストを維持する、状態を保持する会話型のエンティティです。
Python の例:
from agents_framework import Agent, ModelClient
# Create agent with model
agent = Agent(
name="assistant",
model=ModelClient(model="gpt-4"),
instructions="You are a helpful assistant"
)
# Single-turn conversation
response = await agent.run(message="Hello!")
print(response.content)
# Multi-turn with thread
from agents_framework import Thread
thread = Thread()
response = await agent.run(thread=thread, message="What's 2+2?")
response = await agent.run(thread=thread, message="Double that")
C# の例:
using Microsoft.Agents.AI;
var agent = new Agent(
name: "assistant",
model: new ModelClient(model: "gpt-4"),
instructions: "You are a helpful assistant"
);
var response = await agent.RunAsync("Hello!");
Console.WriteLine(response.Content);
2. ツールと関数
呼び出し可能な関数を提供して、エージェントの機能を拡張します。
Python の例:
from agents_framework import function_tool
@function_tool
def get_weather(location: str) -> str:
"""Get weather for a location."""
return f"Weather in {location}: Sunny, 72°F"
agent = Agent(
name="assistant",
model=ModelClient(model="gpt-4"),
tools=[get_weather]
)
response = await agent.run(message="What's the weather in Seattle?")
# Agent automatically calls get_weather() and responds with result
C# の例:
[FunctionTool]
public static string GetWeather(string location)
{
return $"Weather in {location}: Sunny, 72°F";
}
var agent = new Agent(
name: "assistant",
model: new ModelClient(model: "gpt-4"),
tools: new[] { typeof(Tools).GetMethod("GetWeather") }
);
3. ワークフロー
条件分岐ルーティングと並列実行に対応した、マルチエージェントシステム向けのグラフベースのオーケストレーションです。
Python の例:
from agents_framework import Workflow, GraphWorkflow
# Define workflow graph
workflow = GraphWorkflow()
# Add agents as nodes
workflow.add_node("researcher", research_agent)
workflow.add_node("writer", writer_agent)
workflow.add_node("reviewer", review_agent)
# Define edges (control flow)
workflow.add_edge("researcher", "writer") # Sequential
workflow.add_edge("writer", "reviewer")
# Conditional routing
def should_revise(state):
return state.get("needs_revision", False)
workflow.add_conditional_edge(
"reviewer",
should_revise,
{"revise": "writer", "done": "END"}
)
# Execute workflow
result = await workflow.run(initial_message="Research AI trends")
C# の例:
var workflow = new GraphWorkflow();
workflow.AddNode("researcher", researchAgent);
workflow.AddNode("writer", writerAgent);
workflow.AddNode("reviewer", reviewAgent);
workflow.AddEdge("researcher", "writer");
workflow.AddEdge("writer", "reviewer");
var result = await workflow.RunAsync("Research AI trends");
4. コンテキストと状態管理
会話履歴と共有状態をエージェント間で維持します。
Python:
from agents_framework import Thread, ContextProvider
# Thread maintains conversation history
thread = Thread()
await agent.run(thread=thread, message="Remember: My name is Alice")
await agent.run(thread=thread, message="What's my name?") # "Alice"
# Custom context provider
class DatabaseContext(ContextProvider):
async def get_context(self, thread_id: str):
return await db.fetch_history(thread_id)
async def save_context(self, thread_id: str, messages):
await db.save_history(thread_id, messages)
agent = Agent(model=model, context_provider=DatabaseContext())
5. ミドルウェアとテレメトリ
ログ記録、認証、監視などの横断的な関心事を追加します。
Python:
from agents_framework import Middleware
from opentelemetry import trace
# Custom middleware
class LoggingMiddleware(Middleware):
async def process(self, message, next_handler):
print(f"Processing: {message.content}")
response = await next_handler(message)
print(f"Response: {response.content}")
return response
# OpenTelemetry integration
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("agent-run"):
response = await agent.run(message="Hello")
C#:
public class LoggingMiddleware : IMiddleware
{
public async Task<Message> ProcessAsync(Message message, Func<Message, Task<Message>> next)
{
Console.WriteLine($"Processing: {message.Content}");
var response = await next(message);
Console.WriteLine($"Response: {response.Content}");
return response;
}
}
よくあるパターン
人間による承認を含むプロセス
from agents_framework import HumanInTheLoop
@function_tool
def delete_file(path: str) -> str:
"""Delete a file (requires approval)."""
return f"Deleted {path}"
# Add approval wrapper
delete_file_with_approval = HumanInTheLoop(
tool=delete_file,
approval_prompt="Approve deletion of {path}?"
)
agent = Agent(tools=[delete_file_with_approval])
エージェントの並列実行
workflow = GraphWorkflow()
# Add multiple agents
workflow.add_node("analyst1", analyst_agent)
workflow.add_node("analyst2", analyst_agent)
workflow.add_node("synthesizer", synthesis_agent)
# Parallel execution
workflow.add_edge("START", ["analyst1", "analyst2"]) # Both run in parallel
workflow.add_edge(["analyst1", "analyst2"], "synthesizer") # Wait for both
result = await workflow.run(message="Analyze market trends")
構造化出力の生成
from pydantic import BaseModel
class WeatherReport(BaseModel):
location: str
temperature: float
conditions: str
agent = Agent(
model=model,
instructions="Generate weather reports",
response_format=WeatherReport
)
response = await agent.run(message="Weather in Seattle")
report: WeatherReport = response.parsed
print(f"{report.location}: {report.temperature}°F, {report.conditions}")
エラー処理と再試行
from agents_framework import RetryPolicy
agent = Agent(
model=model,
retry_policy=RetryPolicy(
max_retries=3,
backoff_factor=2.0,
exceptions=[TimeoutError, ConnectionError]
)
)
try:
response = await agent.run(message="Hello")
except Exception as e:
print(f"Failed after retries: {e}")
amplihack との統合
判断フレームワーク
次の場合は Microsoft Agent Framework を使用します:
- 状態を保持する会話型エージェントを構築する(複数ターンの対話)
- エンタープライズ機能(テレメトリ、ミドルウェア、認証)が必要
- 条件分岐ルーティングを伴う複雑なマルチエージェントオーケストレーションが必要
- クロスプラットフォーム要件がある(Python + C#)
- Microsoft エコシステム(Azure、M365)との統合が必要
次の場合は amplihack のネイティブエージェントを使用します:
- ステートレスなタスク委任(コードレビュー、分析)
- シンプルな逐次/並列オーケストレーション
- ファイルベースの操作とローカルツール
- インフラストラクチャなしでの迅速なプロトタイピング
- トークン効率の高いスキルベースのアーキテクチャ
ハイブリッドアプローチ:
# Use amplihack for orchestration
from claude import Agent as ClaudeAgent
orchestrator = ClaudeAgent("orchestrator.md")
# Delegate to Agent Framework for stateful agents
from agents_framework import Agent, Thread
conversational_agent = Agent(
model=ModelClient(model="gpt-4"),
instructions="Maintain conversation context"
)
thread = Thread()
response1 = await conversational_agent.run(thread=thread, message="Start task")
response2 = await conversational_agent.run(thread=thread, message="Continue")
# Use amplihack for final synthesis
result = orchestrator.process({"responses": [response1, response2]})
すべてのパターンについては、@integration/amplihack-integration.md を参照してください。
クイックスタートのワークフロー
-
インストール:
pip install agent-framework-core --pre(Python)またはdotnet add package Microsoft.Agents.AI --prerelease(C#) -
基本的なエージェントを作成:
from agents_framework import Agent, ModelClient agent = Agent( name="assistant", model=ModelClient(model="gpt-4"), instructions="You are a helpful assistant" ) response = await agent.run(message="Hello!") -
ツールを追加:
@function_tool def calculate(expr: str) -> float: return eval(expr) agent = Agent(model=model, tools=[calculate]) -
ワークフローを構築:
workflow = GraphWorkflow() workflow.add_node("agent1", agent1) workflow.add_node("agent2", agent2) workflow.add_edge("agent1", "agent2") result = await workflow.run(message="Task") -
テレメトリを追加:
from opentelemetry import trace tracer = trace.get_tracer(__name__) with tracer.start_as_current_span("agent-run"): response = await agent.run(message="Hello")
リファレンスドキュメント
詳細については、以下を参照してください。
@reference/01-overview.md- アーキテクチャ、コンポーネント、ユースケース@reference/02-agents.md- エージェントの作成、ライフサイクル、高度な機能@reference/03-workflows.md- ワークフローパターン、実行機能、チェックポイント@reference/04-tools-functions.md- ツールの定義、承認ワークフロー、エラー処理@reference/05-context-middleware.md- コンテキストプロバイダー、ミドルウェアパターン、認証@reference/06-telemetry-monitoring.md- OpenTelemetry、ロギング、デバッグ@reference/07-advanced-patterns.md- マルチエージェントパターン、ストリーミング、DevUI
動作するサンプル
@examples/01-basic-agent.py- シンプルな会話型エージェント@examples/02-tool-integration.py- 関数呼び出しを行うエージェント@examples/03-simple-workflow.py- マルチエージェントワークフロー@examples/04-basic-agent.cs- C# エージェントの実装@examples/05-tool-integration.cs- C# ツールの統合@examples/06-simple-workflow.cs- C# ワークフローのサンプル
メンテナンス
フレームワークの最新状態を確認します:python @scripts/check-freshness.py
現在のバージョン管理:@metadata/version-tracking.json
トークン数:約 4,200 トークン(上限 4,800 未満)