langgraph加上“循环”和“记忆”

第六章:加上"循环"和"记忆"

6.1 为什么需要循环?

线性流程只能走一遍就结束。但真实 Agent 需要"思考 → 行动 → 观察 → 再思考"的循环。比如模型先决定搜索,搜索完再看结果决定是否再搜。

6.2 条件边:控制"下一步去哪"

python

python 复制代码
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    count: int

def increment(state: State):
    return {"count": state["count"] + 1}

def should_continue(state: State):
    if state["count"] < 3:
        return "keep_going"
    return "stop"

builder = StateGraph(State)
builder.add_node("increment", increment)

builder.add_edge(START, "increment")

# 条件边:根据 should_continue 的返回值决定去向
builder.add_conditional_edges(
    "increment",
    should_continue,
    {
        "keep_going": "increment",  # 回到自己,形成循环
        "stop": END
    }
)

graph = builder.compile()
result = graph.invoke({"count": 0})
print(result)  # 输出 {'count': 3}

add_conditional_edges 的第三个参数是一个映射字典 :should_continue 返回 "keep_going" 就跳回 "increment",返回 "stop" 就结束。这样 count 从 0 累加到 3 才停。

6.3 记忆:让 Agent 记住上下文

默认情况下,每次 invoke() 都是全新的开始。加上 Checkpointer 后,Agent 就能记住之前的对话。

python

python 复制代码
from langgraph.checkpoint.memory import MemorySaver

checkpointer = MemorySaver()
graph = builder.compile(checkpointer=checkpointer)

# 用 thread_id 区分不同用户的对话
config = {"configurable": {"thread_id": "user_001"}}

# 第一轮
graph.invoke({"question": "我叫小明"}, config)
# 第二轮
result = graph.invoke({"question": "我叫什么?"}, config)
# Agent 能记住"小明"

thread_id 就像会话 ID,同一个 ID 的多次调用会共享状态。

相关推荐
小七-七牛开发者14 小时前
周 1 上线 | DSH 喜提原神进场动画,Anthropic 启动 IPO 路演;黄仁勋辞任;微软全球大宕机超 24 小时
ai·大模型·agent·token·工作流·claudecode·ai coding
ZhengEnCi14 小时前
项目越写越乱?先别改架构:用一次目录重排 + 一份可复算的体检脚本把乱治住
python·架构·ai编程
Karl_fang14 小时前
🥳 再也不用拿起手机抄验证码!我做了一个 Android → Mac 的「验证码接力」工具
前端·macos·ai编程
GISer_Jing14 小时前
GitHub热点I
后端·ai·langchain
ZhengEnCi14 小时前
AI 规则越多越费 Token:无关规则让每次回答多耗 46% 的规则体检提示词
aigc·ai编程·claude
谭光志15 小时前
如何让 AI 高效工作
前端·后端·ai编程
ServBay15 小时前
连AI自己也不愿意维护自己的屎山代码
后端·ai编程·claude
QuZhengRong15 小时前
【AI】Agent 全栈进阶|AgentScope 沙箱源码解析
python·学习·ai·agent·沙箱
袋鼠云数栈UED团队15 小时前
Agent外循环实践:如何编排任务、验证结果并可靠交付
ai编程
IT规划师17 小时前
热点速递 | AI 代码之争:道德讲许可,法律讲版权
ai编程