AI 学习笔记阅读台
12 Agent / 工具 / 框架

Agent 框架

选型决策表、LangGraph 等定位与失败模式

LangGraph、OpenAI Agents SDK、Claude Agent SDK、CrewAI、smolagents、LlamaIndex、AutoGen → MS Agent Framework 各自的定位和最小代码。

我的态度

先手写过循环,再挑一个深入,其余只记定位。出问题就开 tracing 看真实发给模型的 messages。手写循环见《AI 笔记 · Tool calling 与 MCP》。

框架 核心抽象 好处 不足 什么时候选
LangGraph 状态图(节点 + 边 + State) checkpoint、interrupt、可回溯 概念多,上手陡 长流程、要暂停恢复
OpenAI Agents SDK Agent + tools + handoffs + guardrails 极简,能接 OpenAI 兼容模型 复杂编排自己写 多 agent 原型、分诊
Claude Agent SDK Claude Code 的循环当库用 现成读写文件、Bash、MCP、subagents 绑定 Claude 代码 / 文件类自动化
CrewAI role / goal / backstory + Task + Crew 多角色写起来直观 细粒度控制弱 内容、调研类流程
smolagents CodeAgent:模型写 Python 调工具 代码量小,HF 生态 执行代码要沙箱 组合多工具的数据处理
LlamaIndex FunctionAgent / AgentWorkflow 数据连接器、RAG 组件最全 编排非主场 以文档 / RAG 为中心
AutoGen → MS Agent Framework 对话式多 agent 多 agent 对话的先驱 AutoGen 已进入 maintenance mode(只修 bug、不加新功能,据 Langfuse 对比文引的 README),官方继任是 Microsoft Agent Framework(AutoGen + Semantic Kernel 合并);AG2 是社区分支 新项目不首选 AutoGen

代码

LangGraph:状态图 + 人工审批(实跑过:langgraph 1.x 下流程和 interrupt/resume 通过;里面的 chat() 没接过真 API)

python
# pip install langgraph —— 状态图 + checkpoint + 人工审批
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import interrupt, Command
from llm import chat

class State(TypedDict):
    topic: str
    draft: str
    approved: bool

def write(state: State) -> dict:
    return {"draft": chat([{"role": "user", "content": f"写一段关于{state['topic']}的介绍"}])}

def human_review(state: State) -> dict:
    answer = interrupt({"draft": state["draft"], "question": "通过吗?(y/n)"})  # 停在这等人
    return {"approved": answer == "y"}

g = StateGraph(State)
g.add_node("write", write)
g.add_node("human_review", human_review)
g.add_edge(START, "write")
g.add_edge("write", "human_review")
g.add_conditional_edges("human_review", lambda s: END if s["approved"] else "write")
app = g.compile(checkpointer=InMemorySaver())   # 生产换 Postgres / SQLite checkpointer

cfg = {"configurable": {"thread_id": "demo-1"}}
print(app.invoke({"topic": "GraphRAG"}, cfg)["__interrupt__"])   # 停在 interrupt
print(app.invoke(Command(resume="y"), cfg)["approved"])          # resume → True

OpenAI Agents SDK:handoff,接 DeepSeek(没实跑过)

python
# pip install openai-agents —— 用 DeepSeek 跑 Agents SDK(handoff)
import os
from agents import (Agent, Runner, function_tool, AsyncOpenAI,
                    OpenAIChatCompletionsModel, set_tracing_disabled)

set_tracing_disabled(True)   # 不用 OpenAI 平台就关 tracing 上报
client = AsyncOpenAI(base_url="https://api.deepseek.com", api_key=os.environ["DEEPSEEK_API_KEY"])
model = OpenAIChatCompletionsModel(model="deepseek-chat", openai_client=client)

@function_tool
def search_bookmarks(query: str) -> str:
    """在我的 X 书签里搜索"""
    return f"找到 3 条关于 {query} 的书签……"

researcher = Agent(name="研究员", instructions="用工具查资料并给出要点", tools=[search_bookmarks], model=model)
writer = Agent(name="写手", instructions="把要点写成中文周报", model=model)
triage = Agent(name="分诊", model=model, instructions="需要查资料就交给研究员,需要写作就交给写手",
               handoffs=[researcher, writer])
print(Runner.run_sync(triage, "帮我查一下书签里关于 MCP 的内容").final_output)

Claude Agent SDK:只读代码审查(没实跑过)

python
# pip install claude-agent-sdk(需要 ANTHROPIC_API_KEY)
import anyio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock

async def main():
    options = ClaudeAgentOptions(
        system_prompt="你是代码审查助手,只读不改。",
        allowed_tools=["Read", "Grep", "Glob"],
        disallowed_tools=["Write", "Edit", "Bash"],
        max_turns=10,                                  # 这里也有轮数上限
    )
    async for msg in query(prompt="审查 src/ 下的 Python 代码,列出 3 个最严重的问题", options=options):
        if isinstance(msg, AssistantMessage):
            for block in msg.content:
                if isinstance(block, TextBlock):
                    print(block.text)

anyio.run(main)

CrewAI(没实跑过)

python
# pip install crewai —— llm 用 LiteLLM 命名 provider/model
from crewai import Agent, Task, Crew

researcher = Agent(role="AI 研究员", goal="整理 GraphRAG 的最新做法",
                   backstory="你擅长读论文和开源项目", llm="deepseek/deepseek-chat")
writer = Agent(role="技术写手", goal="写出面向后端工程师的中文讲解",
               backstory="你写过很多技术博客", llm="deepseek/deepseek-chat")
t1 = Task(description="列出 GraphRAG 的 5 个关键概念", expected_output="5 条要点", agent=researcher)
t2 = Task(description="基于要点写 500 字讲解", expected_output="一篇短文", agent=writer)
print(Crew(agents=[researcher, writer], tasks=[t1, t2]).kickoff())

smolagents:CodeAgent 接 Qwen(没实跑过)

python
# pip install smolagents openai —— CodeAgent:模型写 Python 来调工具
import os
from smolagents import CodeAgent, OpenAIModel, tool

@tool
def count_words(text: str) -> int:
    """统计文本字数。

    Args:
        text: 要统计的文本
    """
    return len(text)

model = OpenAIModel(model_id="qwen-plus",
                    api_base="https://dashscope.aliyuncs.com/compatible-mode/v1",
                    api_key=os.environ["DASHSCOPE_API_KEY"])
print(CodeAgent(tools=[count_words], model=model).run("'检索增强生成' 有多少个字?再乘以 3"))

LlamaIndex:FunctionAgent(没实跑过)

python
# pip install llama-index llama-index-llms-openai-like
import os, asyncio
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.llms.openai_like import OpenAILike

llm = OpenAILike(model="deepseek-chat", api_base="https://api.deepseek.com",
                 api_key=os.environ["DEEPSEEK_API_KEY"], is_chat_model=True,
                 is_function_calling_model=True)

def multiply(a: float, b: float) -> float:
    """两数相乘"""
    return a * b

agent = FunctionAgent(tools=[multiply], llm=llm, system_prompt="你是会用工具的助手")

async def main():
    print(await agent.run("1234 乘以 5678 等于多少?"))

asyncio.run(main())

选型决策(先看这张)

我的情况 优先试 别先上
长流程、要暂停/恢复、要可审计分支 LangGraph(+ 需要时 DeepAgents harness) 纯模型驱动环当唯一编排
Python 服务里嵌单 agent,要类型/校验 Pydantic AI(Langfuse 对比文推荐) 一上来画大图
多角色调研/写稿原型 CrewAI(Crew + Flows) 为角色感硬上图编排
要复用 Claude Code 那套工具环 Claude Agent SDK 指望它当通用多模型运行时
OpenAI 兼容模型 + 分诊 handoff OpenAI Agents SDK 复杂状态机全靠它
文档/RAG 为中心 LlamaIndex AgentWorkflow 用它当通用工作流引擎
模型写代码调工具、HF 生态 smolagents CodeAgent 无沙箱就放开 Bash
TypeScript 全栈 Mastra / Vercel AI SDK(Langfuse 文) 硬搬 Python 框架心智
微软/.NET/Azure Microsoft Agent Framework 新项目继续 AutoGen(已 maintenance)
AWS / Bedrock 默认 Strands Agents 只因「新」就换栈
  • 决策口诀(摘自 Langfuse 2026-07 对比文口径,我没逐项实装):复杂有状态 → LangGraph;类型安全 Python → Pydantic AI;TS → Mastra/Vercel;角色多 agent → CrewAI;绑某家生态 → 对应 SDK。
  • DeepAgents = LangGraph 上的意见化 harness(规划/子 agent/文件系统记忆/skills)。要「深 agent」又不想自己拼,可看它——和 Claude Agent SDK 是同类模式、不同底座。
  • 出问题先开 tracing(Langfuse / 各家 OTel),看真实发给模型的 messages,再怪框架。

失败模式

现象 常见原因 我怎么处置
教程跑不通 框架大版本变了 对官方当前文档;别抄 6 个月前帖
图跑飞 / 递归爆 没设 recursion_limit / 终止条件 见《Agent 模式与 ReAct》;LangGraph 默认别当无限
多框架半吊子 同时学三个 一个框架做完一个真实项目再换
AutoGen 新功能找不到 官方 maintenance mode 新项目迁 MS Agent Framework;社区分支 AG2 另论
tracing 空白 / 乱报 接了兼容模型却开着平台 tracing Agents SDK 示例里 set_tracing_disabled;或接 Langfuse
Claude SDK 想换模型 循环绑 Claude Code 能力 接受绑定,或换 OpenAI Agents / LangGraph
Crew 看起来热闹没结果 缺 expected_output / 无终止 Task 写清产出;Flows 包确定性步骤

踩坑 / 注意

  • ❌ 坑:框架 API 变得快,网上旧教程照抄前先对官方文档。
  • ❌ 坑:同时学三个框架——选一个做完一个项目。
  • ❌ 坑:把「低代码工作流平台」和「代码框架」混为一谈——平台见《工作流平台》页。

补充(raw 里核对过)

  • Langfuse 的框架对比文给的短答案:复杂有状态流程默认 LangGraph;Python 要类型安全选 Pydantic AI;TypeScript 看 Mastra / Vercel AI SDK;绑定某家生态就用对应 SDK(Strands / OpenAI / Claude / Google ADK / MS Agent Framework);角色式多 agent 最容易上手是 CrewAI。Langfuse 是做 tracing 的,文章里带了各框架的接入链接。
  • Claude Agent SDK 的循环:gather context → take action → verify work → repeat(Anthropic 工程博客)。跟《Agent 模式与 ReAct 循环控制》里的循环一个意思,多了“验证”这一步。
  • @hwchase17 的分法:framework(LangChain)/ runtime(LangGraph)/ harness(DeepAgents)。上下文工程那页的 harness 就是这个意思。
  • Google ADK:code-first 的 Python 框架(README 原话),我没用过。@svpino 说它是他最喜欢的——个人偏好。

待试

  • [ ] 用 LangGraph 重写书签 agent,加“发日报前人工确认”节点
  • [ ] Microsoft Agent Framework 还没写过任何代码,先看仓库 README

收藏

更多收藏

  • @hwchase17 framework / runtime / harness https://x.com/hwchase17/status/1982119865118023835 ;“为什么你的框架比 LangGraph 好” https://x.com/hwchase17/status/1913662736963412365
  • Claude Agent SDK:@omarsar0 https://x.com/omarsar0/status/1987167737639325886 ;@shao__meng 转述 https://x.com/shao__meng/status/1987717447286505961 ;@trq212 Structured Outputs 做工作流 https://x.com/trq212/status/1991568738622091551 ;@dotey Craft Agents https://x.com/dotey/status/2013516064361943148
  • @svpino Google ADK https://x.com/svpino/status/1972680289643311155 ;@DevLeaderCa MS Agent Framework middleware https://x.com/DevLeaderCa/status/2039467034774233310 ;@GitHub_Daily 开源 AI 学习笔记 https://x.com/GitHub_Daily/status/2080503264391598154
  • @omarsar0 早期帖 https://x.com/omarsar0/status/1904301461200339392 、https://x.com/omarsar0/status/1904649151004217654 、https://x.com/omarsar0/status/1905618238060335229
  • 各框架 README:LangGraph https://raw.githubusercontent.com/langchain-ai/langgraph/main/README.md ;OpenAI Agents SDK https://raw.githubusercontent.com/openai/openai-agents-python/main/README.md ;CrewAI https://raw.githubusercontent.com/crewAIInc/crewAI/main/README.md ;smolagents https://raw.githubusercontent.com/huggingface/smolagents/main/README.md ;LlamaIndex https://raw.githubusercontent.com/run-llama/llama_index/main/README.md ;MS Agent Framework https://raw.githubusercontent.com/microsoft/agent-framework/main/README.md