spinny:~/writing $ less agentic-ai-frameworks-comparison.md
12AI Agent已经从研究演示发展为生产系统。预计到2026年,超过60%的企业AI应用将包含Agent组件。但从零开始构建Agent - 管理工具循环、状态、内存、错误处理和多Agent协调 - 是非常复杂的。这就是框架发挥作用的地方。342026年有四个框架占据主导地位: **LangGraph**、**CrewAI**、**OpenAI Agents SDK** 和 **Claude Agent SDK**。每个框架对同一个问题采取了根本不同的方法: 赋予LLM推理、规划、使用工具和协作的能力。56## 总览78| 方面 | LangGraph | CrewAI | OpenAI Agents SDK | Claude Agent SDK |9|--------|-----------|--------|-------------------|-----------------|10| **开发方** | LangChain | CrewAI Inc. | OpenAI | Anthropic |11| **架构** | 基于图 | 基于角色 | 基于交接 | 自主循环 |12| **理念** | 最大控制力 | 团队协作 | 最少抽象 | 给Agent一台电脑 |13| **语言** | Python, TypeScript | Python | Python | Python, TypeScript |14| **模型支持** | 任意 (OpenAI, Claude, 本地) | 任意 | 任意 (不顾其名称) | 仅限Claude |15| **GitHub stars** | ~29k | ~40k | ~21k | ~6k |16| **最适合** | 复杂的有状态工作流 | 多Agent专业化 | 路由和分流 | 编码和文件密集型任务 |1718## LangGraph: 图构建器1920LangGraph将Agent工作流建模为**有向循环图**。你定义节点(执行工作的函数)和边(节点之间的转换,可以是条件性的)。状态在图中流动,并通过检查点实现持久化。2122这是最显式、最可控的框架 - 每一步都由你自己连接。2324```mermaid25graph LR26 Start --> Router[Router Node]27 Router -->|needs research| Research[Research Node]28 Router -->|needs code| Code[Code Node]29 Research --> Synthesize[Synthesize Node]30 Code --> Synthesize31 Synthesize --> End32```3334### 核心概念3536- **StateGraph**: 带类型化状态的图定义37- **Nodes**: 转换状态的Python函数38- **Edges**: 节点之间的连接,可以是条件性的39- **Checkpointing**: 用于长时间运行工作流的内置持久化4041### 代码示例4243```python44from langgraph.graph import StateGraph, MessagesState, START, END45from langchain_openai import ChatOpenAI4647llm = ChatOpenAI(model="gpt-4o")4849def call_agent(state: MessagesState):50 response = llm.invoke(state["messages"])51 return {"messages": [response]}5253def should_continue(state: MessagesState):54 last = state["messages"][-1]55 if last.tool_calls:56 return "tools"57 return END5859def call_tools(state: MessagesState):60 # Execute tool calls and return results61 results = []62 for tool_call in state["messages"][-1].tool_calls:63 result = execute_tool(tool_call)64 results.append(result)65 return {"messages": results}6667graph = StateGraph(MessagesState)68graph.add_node("agent", call_agent)69graph.add_node("tools", call_tools)70graph.add_edge(START, "agent")71graph.add_conditional_edges("agent", should_continue, {"tools": "tools", END: END})72graph.add_edge("tools", "agent")7374app = graph.compile()75result = app.invoke({"messages": [{"role": "user", "content": "What's the weather?"}]})76```7778### 优势7980- 对每个步骤和转换进行细粒度控制81- 内置检查点和human-in-the-loop82- TypeScript完全支持83- 兼容任何LLM提供商84- 最适合具有条件分支和循环的复杂工作流8586### 劣势8788- 学习曲线陡峭 - 需要理解图论概念89- 对于简单用例过于冗长 - 基本Agent需要比其他框架更多的模板代码90- 没有LangSmith的情况下调试图流程可能很困难9192### 定价9394开源 (MIT)。LangSmith (托管可观测性平台) 提供生产监控的付费层级。9596## CrewAI: 团队组装器9798CrewAI采用人类隐喻: 你组建一个由专业Agent组成的**团队**,每个Agent都有**角色**、**目标**和**背景故事**。Agent使用**工具**在**任务**上协作,由**流程** (顺序、层级或共识) 进行协调。99100可以把它想象成雇佣一个团队,每个成员都有特定的职位和专长。101102```mermaid103graph TD104 Crew[Crew Manager] --> R[Researcher\nRole: Find data\nTools: WebSearch]105 Crew --> W[Writer\nRole: Write content\nTools: FileWrite]106 Crew --> E[Editor\nRole: Review quality\nTools: FileRead]107 R --> Task1[Research Task]108 W --> Task2[Writing Task]109 E --> Task3[Review Task]110 Task1 --> Task2 --> Task3111```112113### 核心概念114115- **Agent**: 具有角色、目标、背景故事和工具的角色116- **Task**: 具有描述、预期输出和指定Agent的任务分配117- **Crew**: 协同工作的Agent组118- **Process**: 执行策略 (顺序、层级、共识)119- **Flow**: 用于连接多个团队的事件驱动编排层120121### 代码示例122123```python124from crewai import Agent, Task, Crew, Process125126researcher = Agent(127 role="Senior Research Analyst",128 goal="Find comprehensive data about the given topic",129 backstory="You have 10 years of experience in technology research. "130 "You are thorough and always verify facts from multiple sources.",131 tools=[web_search_tool],132 verbose=True,133)134135writer = Agent(136 role="Technical Writer",137 goal="Create clear, engaging technical content",138 backstory="You write for a developer audience. "139 "Your articles are practical and include code examples.",140 tools=[file_tool],141 verbose=True,142)143144research_task = Task(145 description="Research the latest developments in WebAssembly in 2026. "146 "Focus on WASI, Component Model, and production use cases.",147 expected_output="A structured research document with key findings and sources.",148 agent=researcher,149)150151writing_task = Task(152 description="Write a blog post based on the research. "153 "Include code examples and Mermaid diagrams.",154 expected_output="A complete blog post in Markdown format.",155 agent=writer,156 context=[research_task], # Writer receives researcher's output157)158159crew = Crew(160 agents=[researcher, writer],161 tasks=[research_task, writing_task],162 process=Process.sequential,163 verbose=True,164)165166result = crew.kickoff()167print(result.raw)168```169170### 优势171172- 直观的基于角色的抽象 - 易于理解173- 100+内置工具集成174- Agent间共享内存 (短期、长期、实体)175- 最大的社区 (~40k GitHub stars)176- 具有"管理者"Agent的层级流程,可以委派和验证177178### 劣势179180- 不如LangGraph那样细粒度的控制 - 你定义的是角色,不是精确的执行路径181- 当Agent意见不一致时,层级流程可能不可预测182- 多Agent对话的调试比单Agent流程更困难183184### 定价185186开源核心 (免费)。CrewAI Platform: $99/月 (Teams) 到 $120k/年 (Enterprise)。基于活跃团队数和月执行次数定价。187188## OpenAI Agents SDK: 路由器189190OpenAI Agents SDK (Swarm的精神继承者) 专注于**交接** - Agent将对话转移给其他专业Agent。这是最精简的框架: Agent、工具、交接和护栏。仅此而已。191192```mermaid193graph LR194 User --> Triage[Triage Agent]195 Triage -->|billing question| Billing[Billing Agent]196 Triage -->|refund request| Refund[Refund Agent]197 Triage -->|technical issue| Support[Support Agent]198 Billing --> Response[Response]199 Refund --> Response200 Support --> Response201```202203### 核心概念204205- **Agent**: 模型 + 指令 + 工具 + 交接206- **Handoff**: 向另一个Agent的转移 (建模为LLM可以调用的工具)207- **Guardrail**: 与Agent并行运行的输入/输出验证208- **Runner**: 执行Agent循环209- **Tracing**: 所有LLM调用、工具调用和交接的内置可观测性210211### 代码示例212213```python214from agents import Agent, Runner, handoff, InputGuardrail, GuardrailFunctionOutput215from pydantic import BaseModel216217class SafetyCheck(BaseModel):218 is_safe: bool219 reason: str220221async def content_safety(ctx, agent, input_text):222 result = await Runner.run(223 Agent(name="Safety", instructions="Check if input is safe. No PII."),224 input_text,225 context=ctx,226 )227 output = SafetyCheck.model_validate_json(result.final_output)228 return GuardrailFunctionOutput(229 output_info=output, tripwire_triggered=not output.is_safe230 )231232billing_agent = Agent(233 name="Billing Agent",234 instructions="You handle billing inquiries. Be precise with numbers.",235 tools=[lookup_invoice, process_payment],236)237238refund_agent = Agent(239 name="Refund Agent",240 instructions="You process refund requests. Always verify the order first.",241 tools=[lookup_order, issue_refund],242)243244triage_agent = Agent(245 name="Triage Agent",246 instructions="Route the customer to the right specialist. "247 "Ask clarifying questions if needed.",248 handoffs=[billing_agent, refund_agent],249 input_guardrails=[InputGuardrail(guardrail_function=content_safety)],250)251252result = await Runner.run(triage_agent, "I need a refund for order #4521")253print(result.final_output)254# The triage agent routes to refund_agent, which processes the refund255```256257### 优势258259- 简洁的交接模式 - 对路由/分流工作流来说很自然260- 护栏与执行并行运行 (快速失败,非阻塞)261- 内置调试用的追踪仪表板262- 尽管名称如此,也支持非OpenAI模型263- 最少抽象 - 易于理解和扩展264265### 劣势266267- 状态管理不如LangGraph成熟268- 没有内置持久化或检查点269- 第三方工具生态系统较小270- 以交接为中心的设计可能不适合所有架构271272### 定价273274开源 (MIT)。按使用的模型按token付费。275276## Claude Agent SDK: 开发者277278Claude Agent SDK采取了不同的方法: 不是定义工作流或角色,而是给Agent**一组工具,让它自己找出如何完成任务**。它使用与Claude Code相同的自主循环 - 读取、执行、验证、迭代。279280```mermaid281graph TD282 Prompt[User Prompt] --> Loop[Autonomous Agent Loop]283 Loop --> Reason[Reason about next step]284 Reason --> Act[Execute tool]285 Act --> Verify[Check result]286 Verify -->|not done| Loop287 Verify -->|done| Output[Final output]288```289290### 核心概念291292- **query()**: 启动Agent循环的主入口293- **内置工具**: Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch294- **通过MCP自定义工具**: 将工具定义为进程内MCP服务器295- **子Agent**: 父Agent可以委派的专业Agent296- **Sessions**: 在多次交互中保持上下文297298### 代码示例299300```typescript301import { tool, createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk";302import { z } from "zod";303304const searchDocs = tool(305 "search_docs",306 "Search the internal documentation for relevant information",307 { query: z.string().describe("Search query") },308 async ({ query }) => {309 const results = await vectorStore.similaritySearch(query, 5);310 return {311 content: [{ type: "text", text: results.map(r => r.pageContent).join("\n\n") }],312 };313 }314);315316const docsServer = createSdkMcpServer({317 name: "docs",318 version: "1.0.0",319 tools: [searchDocs],320});321322for await (const message of query({323 prompt: "Find how authentication works in our system and write a summary",324 options: {325 mcpServers: { docs: docsServer },326 allowedTools: ["Read", "Glob", "Grep", "mcp__docs__search_docs"],327 },328})) {329 if (message.type === "result" && message.subtype === "success") {330 console.log(message.result);331 }332}333```334335### 优势336337- 一流的MCP集成 - 连接任何MCP服务器生态系统338- 文件操作、终端和网络访问的内置工具339- 大型代码库的自动上下文压缩340- 复杂任务的子Agent并行处理341- 与Claude Code相同的引擎 - 在真实开发工作流中经过实战检验342343### 劣势344345- 仅限Claude模型 - 不支持多提供商346- 较新的框架,社区较小347- 即使是Python SDK也需要Node.js运行时348- 与LangGraph相比,工作流控制不那么显式349350### 定价351352开源。标准Claude API token费率。Managed Agents (托管版): 除token费用外,每会话小时$0.08。353354## 何时选择哪个355356```mermaid357graph TD358 Start{What's your priority?}359 Start -->|Full control over workflow| LG[LangGraph]360 Start -->|Multi-agent collaboration| CA[CrewAI]361 Start -->|Routing and triage| OA[OpenAI Agents SDK]362 Start -->|Coding and file automation| CS[Claude Agent SDK]363364 LG --> LGU[Complex stateful workflows\nConditional branching\nHuman-in-the-loop]365 CA --> CAU[Team of specialized agents\nResearch + writing pipelines\nContent generation]366 OA --> OAU[Customer service routing\nMulti-step handoffs\nInput validation]367 CS --> CSU[Code generation and review\nFile-heavy automation\nMCP tool ecosystem]368```369370### 选择LangGraph如果:371- 你需要精确控制工作流的每一步372- 你的用例涉及复杂的条件逻辑和循环373- 你需要内置的持久化和human-in-the-loop检查点374- 你需要在同一工作流中使用多个LLM提供商375376### 选择CrewAI如果:377- 你想要直观的基于角色的抽象378- 你的任务涉及多个具有不同专长的Agent379- 你需要Agent之间协作并传递上下文380- 你重视最大的社区和最多的内置集成381382### 选择OpenAI Agents SDK如果:383- 你的主要模式是将对话路由给专家384- 你需要并行验证输入/输出的护栏385- 你想要最简单的抽象和最少的模板代码386- 内置的追踪和可观测性很重要387388### 选择Claude Agent SDK如果:389- 你的Agent需要读写和执行代码390- 你想要一流的MCP服务器集成391- 你需要能够迭代和自我修正的自主Agent392- 你已经在使用Claude并想要最深度的集成393394## 可以组合使用框架吗?395396可以。一个常见的模式是使用一个框架进行编排,另一个用于单独的Agent:397398- **LangGraph** 用于整体工作流图399- **CrewAI** 用于需要多Agent协作的特定节点400- **Claude Agent SDK** 用于通过MCP处理编码相关的子任务401- **OpenAI Agents SDK** 用于面向客户的分流和路由402403这些框架并不是互相排斥的。选择适合系统各个部分的框架即可。404405## 结论406407每个框架都有明确的方向:408409- **LangGraph** 优化控制 - 你决定每一次转换410- **CrewAI** 优化协作 - Agent作为团队工作411- **OpenAI Agents SDK** 优化简洁 - 最少抽象,干净的交接412- **Claude Agent SDK** 优化自主性 - 给它工具,让它工作413414正确的选择取决于你的工作流、团队和现有技术栈。选择与你主要用例匹配的框架,深入学习它,当遇到其他框架擅长的场景时再引入它们。415
:Agent AI框架对比: LangGraph vs CrewAI vs OpenAI Agents SDK vs Claude Agent SDKlines 1-415 (END) — press q to close