microsoft-agent-framework
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMicrosoft Agent Framework Skill
Microsoft Agent Framework 技能
Version: 0.1.0-preview | Last Updated: 2025-11-15 | Framework Version: 0.1.0-preview
Languages: Python 3.10+, C# (.NET 8.0+) | License: MIT
版本: 0.1.0-preview | 最后更新: 2025-11-15 | 框架版本: 0.1.0-preview
支持语言: Python 3.10+, C# (.NET 8.0+) | 许可证: MIT
Quick Reference
快速参考
Microsoft Agent Framework is an open-source platform for building production AI agents and workflows, unifying AutoGen's simplicity with Semantic Kernel's enterprise features.
Core Capabilities: AI Agents (stateful conversations, tool integration) | Workflows (graph-based orchestration, parallel processing) | Enterprise features (telemetry, middleware, MCP support)
Installation:
- Python:
pip install agent-framework --pre - C#:
dotnet add package Microsoft.Agents.AI --prerelease
Repository: https://github.com/microsoft/agent-framework (5.1k stars)
Microsoft Agent Framework是一个用于构建生产级AI Agent与工作流的开源平台,融合了AutoGen的简洁性与Semantic Kernel的企业级特性。
核心能力: AI Agent(有状态对话、工具集成)| 工作流(基于图的编排、并行处理)| 企业级特性(遥测、中间件、MCP支持)
安装方式:
- Python:
pip install agent-framework --pre - C#:
dotnet add package Microsoft.Agents.AI --prerelease
代码仓库: https://github.com/microsoft/agent-framework (5.1k星标)
When to Use This Skill
何时使用该技能
Use Microsoft Agent Framework when you need:
- Production AI Agents with enterprise features (telemetry, middleware, structured outputs)
- Multi-Agent Orchestration via graph-based workflows with conditional routing
- Tool/Function Integration with approval workflows and error handling
- Cross-Platform Development requiring both Python and C# implementations
- Research-to-Production Pipeline leveraging AutoGen + Semantic Kernel convergence
Integration with amplihack: Use Agent Framework for stateful conversational agents and complex orchestration. Use amplihack's native agent system for stateless task delegation and simple orchestration. See for detailed guidance.
@integration/decision-framework.md在以下场景中使用Microsoft Agent Framework:
- 具备企业级特性的生产级AI Agent(遥测、中间件、结构化输出)
- 基于图的工作流实现多Agent编排,支持条件路由
- 带审批流与错误处理的工具/函数集成
- 需要同时支持Python和C#实现的跨平台开发
- 借助AutoGen + Semantic Kernel融合能力的研究到生产流水线
与amplihack的集成: 使用Agent Framework处理有状态对话Agent和复杂编排。使用amplihack原生Agent系统处理无状态任务委托和简单编排。详见获取详细指导。
@integration/decision-framework.mdCore Concepts
核心概念
1. AI Agents
1. AI Agent
Stateful conversational entities that process messages, call tools, and maintain context.
Python Example:
python
from agents_framework import Agent, ModelClient有状态的对话实体,可处理消息、调用工具并维护上下文。
Python示例:
python
from agents_framework import Agent, ModelClientCreate agent with model
创建带模型的Agent
agent = Agent(
name="assistant",
model=ModelClient(model="gpt-4"),
instructions="You are a helpful assistant"
)
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)
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# Example**:
```csharp
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);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#示例**:
```csharp
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. Tools & Functions
2. 工具与函数
Extend agent capabilities by providing callable functions.
Python Example:
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能力。
Python示例:
python
from agents_framework import function_tool
@function_tool
def get_weather(location: str) -> str:
"""获取指定地点的天气。"""
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
Agent会自动调用get_weather()并返回结果
**C# Example**:
```csharp
[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") }
);
**C#示例**:
```csharp
[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. Workflows
3. 工作流
Graph-based orchestration for multi-agent systems with conditional routing and parallel execution.
Python Example:
python
from agents_framework import Workflow, GraphWorkflow基于图的编排系统,用于多Agent系统,支持条件路由与并行执行。
Python示例:
python
from agents_framework import Workflow, GraphWorkflowDefine workflow graph
定义工作流图
workflow = GraphWorkflow()
workflow = GraphWorkflow()
Add agents as nodes
将Agent添加为节点
workflow.add_node("researcher", research_agent)
workflow.add_node("writer", writer_agent)
workflow.add_node("reviewer", review_agent)
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")
workflow.add_edge("researcher", "writer") # 顺序执行
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"}
)
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# Example**:
```csharp
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");result = await workflow.run(initial_message="Research AI trends")
**C#示例**:
```csharp
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. Context & State Management
4. 上下文与状态管理
Maintain conversation history and shared state across agents.
Python:
python
from agents_framework import Thread, ContextProvider在多个Agent之间维护对话历史与共享状态。
Python:
python
from agents_framework import Thread, ContextProviderThread maintains conversation history
Thread维护对话历史
thread = Thread()
await agent.run(thread=thread, message="Remember: My name is Alice")
await agent.run(thread=thread, message="What's my name?") # "Alice"
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())
undefinedclass 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())
undefined5. Middleware & Telemetry
5. 中间件与遥测
Add cross-cutting concerns like logging, auth, and monitoring.
Python:
python
from agents_framework import Middleware
from opentelemetry import trace添加日志、认证、监控等横切关注点。
Python:
python
from agents_framework import Middleware
from opentelemetry import traceCustom 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
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
OpenTelemetry集成
tracer = trace.get_tracer(name)
with tracer.start_as_current_span("agent-run"):
response = await agent.run(message="Hello")
**C#**:
```csharp
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;
}
}tracer = trace.get_tracer(name)
with tracer.start_as_current_span("agent-run"):
response = await agent.run(message="Hello")
**C#**:
```csharp
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;
}
}Common Patterns
常见模式
Human-in-the-Loop Approval
人工介入审批
python
from agents_framework import HumanInTheLoop
@function_tool
def delete_file(path: str) -> str:
"""Delete a file (requires approval)."""
return f"Deleted {path}"python
from agents_framework import HumanInTheLoop
@function_tool
def delete_file(path: str) -> str:
"""删除文件(需要审批)。"""
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])
undefineddelete_file_with_approval = HumanInTheLoop(
tool=delete_file,
approval_prompt="Approve deletion of {path}?"
)
agent = Agent(tools=[delete_file_with_approval])
undefinedParallel Agent Execution
Agent并行执行
python
workflow = GraphWorkflow()python
workflow = GraphWorkflow()Add multiple agents
添加多个Agent
workflow.add_node("analyst1", analyst_agent)
workflow.add_node("analyst2", analyst_agent)
workflow.add_node("synthesizer", synthesis_agent)
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")
undefinedworkflow.add_edge("START", ["analyst1", "analyst2"]) # 两者并行运行
workflow.add_edge(["analyst1", "analyst2"], "synthesizer") # 等待两者完成
result = await workflow.run(message="Analyze market trends")
undefinedStructured Output Generation
结构化输出生成
python
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}")python
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}")Error Handling & Retries
错误处理与重试
python
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}")python
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"重试后仍失败: {e}")Integration with amplihack
与amplihack的集成
Decision Framework
决策框架
Use Microsoft Agent Framework when:
- Building stateful conversational agents (multi-turn dialogue)
- Need enterprise features (telemetry, middleware, auth)
- Complex multi-agent orchestration with conditional routing
- Cross-platform requirements (Python + C#)
- Integration with Microsoft ecosystem (Azure, M365)
Use amplihack native agents when:
- Stateless task delegation (code review, analysis)
- Simple sequential/parallel orchestration
- File-based operations and local tooling
- Rapid prototyping without infrastructure
- Token-efficient skill-based architecture
Hybrid Approach:
python
undefined使用Microsoft Agent Framework的场景:
- 构建有状态对话Agent(多轮对话)
- 需要企业级特性(遥测、中间件、认证)
- 带条件路由的复杂多Agent编排
- 跨平台需求(Python + C#)
- 与Microsoft生态系统集成(Azure、M365)
使用amplihack原生Agent的场景:
- 无状态任务委托(代码审查、分析)
- 简单的顺序/并行编排
- 基于文件的操作与本地工具
- 无需基础设施的快速原型开发
- 基于技能的令牌高效架构
混合方案:
python
undefinedUse amplihack for orchestration
使用amplihack进行编排
from claude import Agent as ClaudeAgent
orchestrator = ClaudeAgent("orchestrator.md")
from claude import Agent as ClaudeAgent
orchestrator = ClaudeAgent("orchestrator.md")
Delegate to Agent Framework for stateful agents
委托给Agent Framework处理有状态Agent
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")
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
使用amplihack进行最终合成
result = orchestrator.process({"responses": [response1, response2]})
See `@integration/amplihack-integration.md` for complete patterns.
---result = orchestrator.process({"responses": [response1, response2]})
完整模式详见`@integration/amplihack-integration.md`。
---Quick Start Workflow
快速开始工作流
-
Install:(Python) or
pip install agent-framework --pre(C#)dotnet add package Microsoft.Agents.AI --prerelease -
Create Basic Agent:python
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!") -
Add Tools:python
@function_tool def calculate(expr: str) -> float: return eval(expr) agent = Agent(model=model, tools=[calculate]) -
Build Workflow:python
workflow = GraphWorkflow() workflow.add_node("agent1", agent1) workflow.add_node("agent2", agent2) workflow.add_edge("agent1", "agent2") result = await workflow.run(message="Task") -
Add Telemetry:python
from opentelemetry import trace tracer = trace.get_tracer(__name__) with tracer.start_as_current_span("agent-run"): response = await agent.run(message="Hello")
-
安装:(Python)或
pip install agent-framework --pre(C#)dotnet add package Microsoft.Agents.AI --prerelease -
创建基础Agent:python
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!") -
添加工具:python
@function_tool def calculate(expr: str) -> float: return eval(expr) agent = Agent(model=model, tools=[calculate]) -
构建工作流:python
workflow = GraphWorkflow() workflow.add_node("agent1", agent1) workflow.add_node("agent2", agent2) workflow.add_edge("agent1", "agent2") result = await workflow.run(message="Task") -
添加遥测:python
from opentelemetry import trace tracer = trace.get_tracer(__name__) with tracer.start_as_current_span("agent-run"): response = await agent.run(message="Hello")
Reference Documentation
参考文档
For detailed information, see:
- - Architecture, components, use cases
@reference/01-overview.md - - Agent creation, lifecycle, advanced features
@reference/02-agents.md - - Workflow patterns, executors, checkpointing
@reference/03-workflows.md - - Tool definition, approval workflows, error handling
@reference/04-tools-functions.md - - Context providers, middleware patterns, auth
@reference/05-context-middleware.md - - OpenTelemetry, logging, debugging
@reference/06-telemetry-monitoring.md - - Multi-agent patterns, streaming, DevUI
@reference/07-advanced-patterns.md
如需详细信息,请查看:
- - 架构、组件、使用场景
@reference/01-overview.md - - Agent创建、生命周期、高级特性
@reference/02-agents.md - - 工作流模式、执行器、检查点
@reference/03-workflows.md - - 工具定义、审批流、错误处理
@reference/04-tools-functions.md - - 上下文提供器、中间件模式、认证
@reference/05-context-middleware.md - - OpenTelemetry、日志、调试
@reference/06-telemetry-monitoring.md - - 多Agent模式、流式传输、DevUI
@reference/07-advanced-patterns.md
Working Examples
可用示例
- - Simple conversational agent
@examples/01-basic-agent.py - - Agent with function calling
@examples/02-tool-integration.py - - Multi-agent workflow
@examples/03-simple-workflow.py - - C# agent implementation
@examples/04-basic-agent.cs - - C# tool integration
@examples/05-tool-integration.cs - - C# workflow example
@examples/06-simple-workflow.cs
- - 简单对话Agent
@examples/01-basic-agent.py - - 带函数调用的Agent
@examples/02-tool-integration.py - - 多Agent工作流
@examples/03-simple-workflow.py - - C# Agent实现
@examples/04-basic-agent.cs - - C#工具集成
@examples/05-tool-integration.cs - - C#工作流示例
@examples/06-simple-workflow.cs
Maintenance
维护
Check framework freshness:
python @scripts/check-freshness.pyCurrent version tracking:
@metadata/version-tracking.jsonToken Count: ~4,200 tokens (under 4,800 limit)
检查框架更新:
python @scripts/check-freshness.py当前版本跟踪:
@metadata/version-tracking.json令牌数量: ~4,200令牌(低于4,800限制)