mcpField
M
microsoft-agent-framework

microsoft-agent-framework

github.com/rysweetAgent 工作流76258 次安装22 周前更新
代码仓库

关于 microsoft-agent-framework

面向使用 Python 或 C# 构建有状态 AI Agent 和工作流的 Microsoft Agent Framework 技能指南,涵盖工具、共享上下文、中间件与遥测。

主要功能

  1. 01有状态对话 Agent
  2. 02基于图的工作流编排
  3. 03工具与函数集成
  4. 04共享上下文和对话状态
  5. 05中间件与遥测
  6. 06人工审批与结构化输出

适用场景

  1. 01构建多轮对话 Agent
  2. 02通过条件或并行工作流协调 Agent
  3. 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.md
README.md
examples/
01-basic-agent.py
02-tool-integration.py
03-simple-workflow.py
04-basic-agent.cs
05-tool-integration.cs
06-simple-workflow.cs
integration/
amplihack-integration.md
decision-framework.md
migration-guide.md
metadata/
last-updated.txt
sources.json
version-tracking.json
reference/
01-overview.md
02-agents.md
03-workflows.md
04-tools-functions.md
05-context-middleware.md
06-telemetry-monitoring.md
07-advanced-patterns.md
scripts/
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 是一个用于构建生产级 AI Agent 和工作流的开源平台,将 AutoGen 的简洁性与 Semantic Kernel 的企业级功能融为一体。

核心功能:AI Agent(有状态对话、工具集成)| 工作流(基于图的编排、并行处理)| 企业级功能(遥测、中间件、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:

  1. 生产级 AI Agent,需要企业级功能(遥测、中间件、结构化输出)
  2. 多 Agent 编排,通过基于图的工作流进行条件路由
  3. 工具/函数集成,包含审批工作流和错误处理
  4. 跨平台开发,需要同时使用 Python 和 C# 实现
  5. 从研究到生产的流程,利用 AutoGen 与 Semantic Kernel 的融合

与 amplihack 集成:使用 Agent Framework 构建有状态的对话式 Agent和实现复杂编排。使用 amplihack 的原生 Agent 系统进行无状态任务委派和简单编排。详细指南请参阅 @integration/decision-framework.md。


核心概念

1. AI Agent

处理消息、调用工具并保留上下文的有状态对话实体。

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. 工具与函数

通过提供可调用的函数扩展 Agent 的功能。

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. 工作流

用于多 Agent 系统的基于图的编排,支持条件路由和并行执行。

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. 上下文与状态管理

在多个 Agent 之间保留对话历史和共享状态。

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])
并行执行 Agent
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:

  • 构建有状态的对话式 Agent(多轮对话)
  • 需要企业级功能(遥测、中间件、身份验证)
  • 需要通过条件路由实现复杂的多 Agent 编排
  • 有跨平台需求(Python + C#)
  • 需要与 Microsoft 生态系统集成(Azure、M365)

在以下情况下使用 amplihack 原生 Agent:

  • 无状态任务委派(代码审查、分析)
  • 简单的顺序/并行编排
  • 基于文件的操作和本地工具
  • 无需基础设施的快速原型开发
  • 注重令牌效率的技能型架构

混合方案:

# 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。


快速入门工作流

  1. 安装:pip install agent-framework-core --pre(Python),或 dotnet add package Microsoft.Agents.AI --prerelease(C#)

  2. 创建基础 Agent:

    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!")
    
  3. 添加工具:

    @function_tool
    def calculate(expr: str) -> float:
        return eval(expr)
    
    agent = Agent(model=model, tools=[calculate])
    
  4. 构建工作流:

    workflow = GraphWorkflow()
    workflow.add_node("agent1", agent1)
    workflow.add_node("agent2", agent2)
    workflow.add_edge("agent1", "agent2")
    result = await workflow.run(message="Task")
    
  5. 添加遥测:

    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 - Agent 创建、生命周期、高级功能
  • @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 - 多 Agent 模式、流式传输、DevUI

可运行示例

  • @examples/01-basic-agent.py - 简单的对话式 Agent
  • @examples/02-tool-integration.py - 支持函数调用的 Agent
  • @examples/03-simple-workflow.py - 多 Agent 工作流
  • @examples/04-basic-agent.cs - C# Agent 实现
  • @examples/05-tool-integration.cs - C# 工具集成
  • @examples/06-simple-workflow.cs - C# 工作流示例

维护

检查框架的新鲜度:python @scripts/check-freshness.py

当前版本跟踪信息:@metadata/version-tracking.json


Token 数量:约 4,200 个(低于 4,800 个上限)

评论

支持 Markdown