课程首页 › Module 5 · 高级推理:规划、元认知与 Agentic RAG › L9

L9 主流 Agent 框架对比:LangGraph / AutoGen / CrewAI / smolagents / OpenAI Agents SDK

课程目标:横向对比 2025-2026 年五大主流 Agent 框架的架构理念、适用场景与代码风格,能为项目选择最合适的框架。


一、为什么需要框架对比?#

L3 你学了 smolagents,L5 你学了 LangGraph。但 2025 年的 Agent 框架远不止这两个——

面试官会问:"为什么选 LangGraph 而不是 AutoGen?"——没有标准答案,但你要能说出权衡。

这一课给你一张完整的"框架地图",帮你建立选型直觉。


二、用一个比喻:五大框架 = 五种交通工具#

把"构建 Agent 系统"比作"运输货物":

框架类比特点
LangGraph高铁显式控制流、可观测、最适合复杂长流程
AutoGen网约车对话驱动、最适合协商型多 Agent
CrewAI快递公司角色化分工、最适合业务流程自动化
smolagents自行车极简、最适合小而美的代码 Agent
OpenAI Agents SDK共享单车标准化、最适合 OpenAI 生态快速接入

没有最好,只有最合适——你需要根据团队规模、任务复杂度、生态偏好来选。


三、五大框架深度对比#

1. LangGraph#

架构理念:状态图(StateGraph)——把 Agent 工作流建模成显式的节点和边。

from langgraph.graph import StateGraph, START, END
from typing import TypedDict, Annotated
from langgraph.checkpoint.memory import MemorySaver

class AgentState(TypedDict):
    messages: Annotated[list, lambda a, b: a + b]
    next_step: str

def research_node(state: AgentState):
    return {"messages": state["messages"] + ["research_result"]}

def analysis_node(state: AgentState):
    return {"next_step": "conclude"}

graph = StateGraph(AgentState)
graph.add_node("research", research_node)
graph.add_node("analysis", analysis_node)
graph.add_edge(START, "research")
graph.add_edge("research", "analysis")
graph.add_conditional_edges("analysis", lambda s: "end" if s["next_step"] == "conclude" else "research")
memory = MemorySaver()
app = graph.compile(checkpointer=memory)

优势:

劣势:


2. AutoGen(微软)#

架构理念:群聊(GroupChat)——多个 Agent 轮流发言,模拟真实会议。

import autogen

config_list = [{"model": "gpt-4o-mini", "api_key": "sk-..."}]

assistant = autogen.AssistantAgent(
    name="researcher",
    llm_config={"config_list": config_list},
    system_message="You are a researcher. Focus on gathering data."
)

analyst = autogen.AssistantAgent(
    name="analyst",
    llm_config={"config_list": config_list},
    system_message="You are an analyst. Interpret the researcher's findings."
)

user_proxy = autogen.UserProxyAgent(
    name="user",
    human_input_mode="TERMINATE",  # 用户可打断
    code_execution_config={"work_dir": "coding"}
)

# 创建群聊
groupchat = autogen.GroupChat(
    agents=[user_proxy, assistant, analyst],
    messages=[],
    max_round=10
)
manager = autogen.GroupChatManager(groupchat=groupchat)

# 发起对话
user_proxy.initiate_chat(
    manager,
    message="Research AI agent frameworks and write a comparison report"
)

优势:

劣势:


3. CrewAI#

架构理念:角色扮演(Crews and Flows)——每个 Agent 有明确的 role / goal / backstory。

from crewai import Agent, Task, Crew, Process

researcher = Agent(
    role='Senior Research Analyst',
    goal='Uncover cutting-edge developments in AI',
    backstory='You are an expert at finding and synthesizing information',
    tools=[search_tool],
    verbose=True
)

writer = Agent(
    role='Tech Content Writer',
    goal='Create compelling technical content',
    backstory='You simplify complex topics for engineers',
    verbose=True
)

research_task = Task(
    description='Research the latest AI agent frameworks',
    agent=researcher,
    expected_output='A detailed research report'
)

writing_task = Task(
    description='Write a blog post based on research findings',
    agent=writer,
    expected_output='A 500-word blog post',
    context=[research_task]  # 依赖 research_task 的输出
)

crew = Crew(
    agents=[researcher, writer],
    tasks=[research_task, writing_task],
    process=Process.sequential,  # 顺序执行
    verbose=2
)

result = crew.kickoff()
print(result)

优势:

劣势:


4. smolagents(HuggingFace)#

架构理念:极简 Code Agent——LLM 直接生成 Python 代码执行。

from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool

agent = CodeAgent(
    tools=[DuckDuckGoSearchTool()],
    model=HfApiModel(),
    max_steps=5
)

result = agent.run("Research current AI agent frameworks and compare them")
print(result)

优势:

劣势:


5. OpenAI Agents SDK(2025 年发布)#

架构理念:官方标准化——OpenAI 推出的轻量级 Agent 框架,主打 handoff(任务转交)。

from agents import Agent, Runner, function_tool

@function_tool
def get_weather(city: str) -> str:
    """Get current weather for a city"""
    return f"Sunny, 25°C in {city}"

specialist_agent = Agent(
    name="Weather Specialist",
    instructions="You answer weather questions",
    tools=[get_weather]
)

triage_agent = Agent(
    name="Triage",
    instructions="Route user requests to appropriate specialist",
    handoffs=[specialist_agent]
)

result = Runner.run_sync(triage_agent, "What's the weather in Tokyo?")
print(result.final_output)

优势:

劣势:


四、五大框架横向对比表#

维度LangGraphAutoGenCrewAIsmolagentsOpenAI Agents SDK
架构核心状态图群聊角色扮演代码生成任务转交
学习曲线陡中平缓平缓平缓
生产成熟度⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
多 Agent 支持强强(原生)强(原生)弱中
Human-in-Loop优秀良好有限有限良好
状态管理显式强隐式Flow 抽象极简会话级
可观测性LangSmith内置 trace基础基础OpenAI Dashboard
代码执行通过工具原生支持通过工具原生(核心)通过工具
工具生态LangChain 庞大微软系成长中HF HubOpenAI 工具
开源协议MITMIT + 商业MITApache 2.0Apache 2.0
最适合复杂生产工作流研究/多 Agent业务流程代码 AgentOpenAI 生态快速开发

五、选型决策树#

你的项目需要处理复杂长流程(>10 个步骤)吗?
├── 是 → 需要 Human-in-the-Loop 吗?
│        ├── 是 → LangGraph(生产级)
│        └── 否 → CrewAI(业务友好)或 LangGraph
│
└── 否 → 需要多 Agent 协商吗?
         ├── 是 → AutoGen(群聊最强)
         └── 否 → 主要任务是代码生成吗?
                  ├── 是 → smolagents(极简)
                  └── 否 → 用 OpenAI 生态吗?
                           ├── 是 → OpenAI Agents SDK
                           └── 否 → LangGraph(最灵活)或 smolagents(最简单)

决策速查表#

你的场景推荐框架
企业生产系统、长流程、复杂状态LangGraph
多 Agent 群聊、研究型应用AutoGen
业务流程自动化、角色化分工CrewAI
快速原型、代码生成 Agentsmolagents
OpenAI 生态、标准化要求OpenAI Agents SDK
与 HuggingFace 生态集成smolagents
微软技术栈(C# / .NET)Semantic Kernel
不确定LangGraph(最灵活,能覆盖 80% 场景)

六、Hello World 五行代码对比#

同一个任务"查询北京天气并发送邮件",五个框架的实现:

LangGraph(~50 行)#

# 需要 StateGraph + Node + Edge + Checkpointer(已在 L5 详解)

AutoGen(~15 行)#

import autogen
config = [{"model": "gpt-4o-mini", "api_key": "sk-..."}]
weather_agent = autogen.AssistantAgent("weather", llm_config={"config_list": config})
email_agent = autogen.AssistantAgent("email", llm_config={"config_list": config})
user = autogen.UserProxyAgent("user", human_input_mode="NEVER")
group = autogen.GroupChat([user, weather_agent, email_agent], messages=[], max_round=5)
user.initiate_chat(autogen.GroupChatManager(group), message="查北京天气并发邮件给 alice@example.com")

CrewAI(~15 行)#

from crewai import Agent, Task, Crew
weather_agent = Agent(role="Weather Expert", goal="查询天气", tools=[weather_tool])
email_agent = Agent(role="Email Sender", goal="发送邮件", tools=[email_tool])
t1 = Task(description="查北京天气", agent=weather_agent)
t2 = Task(description="发邮件给 alice", agent=email_agent, context=[t1])
crew = Crew(agents=[weather_agent, email_agent], tasks=[t1, t2])
print(crew.kickoff())

smolagents(~5 行)#

from smolagents import CodeAgent, HfApiModel
agent = CodeAgent(tools=[weather_tool, email_tool], model=HfApiModel())
print(agent.run("查北京天气并发邮件给 alice@example.com"))

OpenAI Agents SDK(~10 行)#

from agents import Agent, Runner
agent = Agent(name="Assistant", instructions="Help users", tools=[weather_tool, email_tool])
print(Runner.run_sync(agent, "查北京天气并发邮件给 alice@example.com").final_output)

观察:实现同样功能,代码量从 5 行(smolagents)到 50 行(LangGraph)不等。框架选择本质是"灵活度 vs 简洁度"的权衡。


七、生产环境的组合策略#

实战中很少用"纯框架",更多是组合:

┌──────────────────────────────────────┐
│  LangGraph(顶层流程编排)            │
│    ├── CrewAI Crew(业务流程)        │
│    │     └── AutoGen GroupChat(协商)│
│    └── smolagents(代码生成子任务)   │
└──────────────────────────────────────┘

典型例子:Devin 的架构就是 LangGraph + AutoGen 思路的混合——用 LangGraph 管顶层流程,复杂子任务用对话式协作。


八、和 L1-L9 的连接#

课程框架对比中的位置
L3 smolagents已学,现在横向对比
L5 LangGraph已学,是对比的"基准"
L6 多 AgentAutoGen、CrewAI 都是多 Agent 框架
L11 MCP所有框架都在集成 MCP
L7 PlanningLangGraph / AutoGen 都支持 Plan-and-Execute
L8 元认知框架对元认知的支持程度不一

九、动手时间:30 分钟选型实验#

请你完成以下三个小实验,亲身感受五个框架的差异:

实验 1:smolagents(5 行 vs 50 行)#

用 smolagents 实现一个"查询天气" Agent,然后改用 LangGraph 实现,对比代码量。

实验 2:CrewAI 角色定义#

用 CrewAI 定义三个角色(Researcher / Writer / Editor),让它们协作写一篇博客。观察 CrewAI 如何处理任务依赖(context=[task1])。

实验 3:AutoGen 群聊#

用 AutoGen 创建两个 Agent(乐观派 / 悲观派),让它们讨论"AI Agent 会不会取代程序员"。观察 GroupChat 如何决定下一位发言者。

📋 实验 3 关键代码(点击展开)
import autogen

config = [{"model": "gpt-4o-mini", "api_key": "sk-..."}]

optimist = autogen.AssistantAgent(
    name="Optimist",
    llm_config={"config_list": config},
    system_message="你是乐观派,强调 AI Agent 的优势和机会"
)

pessimist = autogen.AssistantAgent(
    name="Pessimist",
    llm_config={"config_list": config},
    system_message="你是悲观派,强调 AI Agent 的风险和局限"
)

moderator = autogen.AssistantAgent(
    name="Moderator",
    llm_config={"config_list": config},
    system_message="你是主持人,每次发言前先总结上一轮讨论"
)

user = autogen.UserProxyAgent(
    name="User",
    human_input_mode="NEVER",
    code_execution_config=False
)

groupchat = autogen.GroupChat(
    agents=[user, moderator, optimist, pessimist],
    messages=[],
    max_round=8,
    speaker_selection_method="auto"  # ← AutoGen 自动决定下一位发言者
)
manager = autogen.GroupChatManager(groupchat=groupchat)

user.initiate_chat(manager, message="AI Agent 会不会取代程序员?")

观察点:

  1. speaker_selection_method="auto" 让 LLM 决定谁下一个发言

  2. 每条消息都广播给所有 Agent(Token 消耗大)

  3. Moderator 的 system_message 关键——它决定对话节奏


十、小结#

知识点一句话回顾
LangGraph状态图驱动,最强生产级特性(checkpoint、可观测、HIL)
AutoGen群聊驱动,多 Agent 协作事实标准,微软背书
CrewAI角色扮演驱动,业务流程自动化最快上手
smolagents代码生成驱动,30 行跑通,HF 生态集成
OpenAI Agents SDK任务转交驱动,2025 年新星,OpenAI 生态标准化
选型原则没有最好,先想"团队 + 任务 + 生态"三个约束

十一、Read next#

下一节 L10 Agentic RAG,我们学习传统 RAG 与 Agentic RAG 的本质差异,让 LLM 主动决定"什么时候检索、检索什么"。

主要参考:


十二、Sources#


💬 有疑问? 试试问我:"我的项目该选哪个框架?"、"AutoGen 和 CrewAI 的本质区别是什么?"、"LangGraph 是不是要绑定 LangChain?"——我会用代码或比喻为你解答。

自测 · 检验是否真的掌握了

1. 你要做一个研究型的多 Agent 协作系统,需要多个 Agent 轮流发言协商,并让模型决定下一个发言者。最合适的选择是?

AutoGen 的架构核心是群聊(GroupChat),消息在成员间广播,并可用 speaker_selection_method 让模型决定下一位发言者,天然适合协商型多 Agent。LangGraph 强在显式状态图与生产级控制,CrewAI 强在角色化分工,smolagents 强在代码生成极简,都不是群聊协商模型。

2. 按课程给出的选型决策树,一个流程超过十步且需要人工介入审批的生产系统,应该优先选择?

长流程加人工介入正好命中决策树里「复杂长流程 + Human-in-the-Loop」的分支,对应 LangGraph:显式状态图便于调试,Checkpoint 支撑中断与恢复,interrupt_before 这类能力最完整。群聊和角色扮演都不擅长显式流程控制,而极简代码代理缺少生产级特性。

3. 课程强调框架选择的本质是什么?

课程给出的选型原则是「没有最好,只有最合适」,要综合团队规模、任务复杂度与生态偏好三个约束,本质是灵活度与简洁度的权衡。代码行数少不等于整体成本低,生产成熟度也只是其中一个维度,而开源协议属于合规问题,不是架构选型的决定性因素。