主题
Agent 框架对比
主流 AI Agent 框架的特点、适用场景和选择建议。
框架对比总览
| 框架 | 语言 | 特点 | 适合场景 |
|---|---|---|---|
| LangChain | Python/JS | 生态最丰富,上手快 | 快速原型、学习 |
| LangGraph | Python/JS | LangChain 官方,有状态图 | 复杂流程控制 |
| AutoGen | Python | 多 Agent 对话 | 需要 Agent 协作 |
| CrewAI | Python | 角色分工清晰 | 模拟团队协作 |
| OpenAI Assistants API | API | 官方托管,无需自己管理状态 | 快速集成 |
| Semantic Kernel | C#/Python | 微软出品,企业级 | .NET 项目 |
LangChain
优点
- 生态最丰富,集成最多(LLM、向量库、工具)
- 文档完善,社区活跃
- Python 和 JavaScript 双语言支持
- 适合快速原型
缺点
- 抽象层次高,定制困难
- 性能一般(中间层多)
- 版本更新快,API 不稳定
示例
python
from langchain.agents import create_openai_functions_agent, AgentExecutor
from langchain_openai import ChatOpenAI
from langchain.tools import Tool
llm = ChatOpenAI(model="gpt-4")
tools = [/* 定义工具 */]
agent = create_openai_functions_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools)
result = executor.invoke({"input": "帮我查北京天气"})LangGraph
LangChain 官方出品的 Agent 编排框架,用"图"来定义 Agent 流程。
优点
- 流程可控(用图定义,清晰可见)
- 支持循环、条件分支
- 有状态管理(支持长时间运行的任务)
- 与 LangChain 生态无缝集成
缺点
- 学习曲线较陡
- 概念较多(Node、Edge、State)
示例
python
from langgraph.graph import StateGraph, END
# 定义状态
class State(TypedDict):
input: str
result: str
# 定义图
graph = StateGraph(State)
graph.add_node("research", research_node)
graph.add_node("write", write_node)
graph.add_edge("research", "write")
graph.add_edge("write", END)
app = graph.compile()
result = app.invoke({"input": "写一篇关于 RAG 的文章"})AutoGen
微软出品的多 Agent 对话框架。
优点
- 多 Agent 对话能力强
- 支持代码自动执行
- 适合复杂任务(多个 Agent 协作)
- 人类反馈机制(human-in-the-loop)
缺点
- 仅支持 Python
- 配置相对复杂
- 文档不如 LangChain 完善
示例
python
import autogen
coder = autogen.AssistantAgent("coder", llm_config=llm_config)
user = autogen.UserProxyAgent("user", code_execution_config={"work_dir": "."})
user.initiate_chat(coder, message="写一个贪吃蛇游戏")CrewAI
专注于"角色分工"的 Agent 框架,设计理念类似人类团队。
优点
- 角色(Role)概念清晰,易于理解
- 支持顺序、并行、评审等多种协作模式
- 代码简洁,上手快
- 适合模拟人类团队工作流
缺点
- 仅支持 Python
- 生态较新,集成相对较少
- 自定义流程不如 LangGraph 灵活
示例
python
from crewai import Agent, Task, Crew
researcher = Agent(role="研究员", goal="调研")
writer = Agent(role="作家", goal="写作")
task1 = Task(description="调研 AI Agent", agent=researcher)
task2 = Task(description="写文章", agent=writer)
crew = Crew(agents=[researcher, writer], tasks=[task1, task2])
crew.kickoff()OpenAI Assistants API
OpenAI 官方提供的托管式 Agent 方案。
优点
- 无需自己管理状态和对话历史
- 内置代码解释器、文件检索等工具
- 与 GPT 模型深度集成
- 最简单(不需要框架)
缺点
- 仅支持 OpenAI 模型
- 定制能力有限
- 按 Token 计费,成本需控制
示例
python
from openai import OpenAI
client = OpenAI()
# 创建 Assistant
assistant = client.beta.assistants.create(
model="gpt-4",
tools=[{"type": "code_interpreter"}]
)
# 创建 Thread(对话)
thread = client.beta.threads.create()
# 添加消息并运行
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id
)如何选择
新手学习 → LangChain(文档多,例子多)
需要复杂流程控制 → LangGraph
多 Agent 协作 → AutoGen 或 CrewAI
快速上线、不想管基础设施 → OpenAI Assistants API
.NET 项目 → Semantic Kernel