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 的多次调用会共享状态。

相关推荐
Maydaycxc1 小时前
gentic RPA 深度解析|AI Agent 与 RPA 混合架构、落地痛点、选型要点
人工智能·ai·自动化·rpa
znnnk1 小时前
【AI技术】从 Vibe Coding 到 Harness:以 DeepSeek Harness 为例看 AI 项目的工程化维护
人工智能·ai·deepseek·ai工程化·harness·项目维护
ZhengEnCi8 小时前
AI 真的会替代程序员吗:从 55.8% 提速到 19% 变慢的八组关键数据拆解
aigc·ai编程
濮水大叔11 小时前
AI Vibe Coding 实战:SMS 套件提示词与开发方案
ai编程·全栈·vibecoding
特别关注外国供应商11 小时前
Qualys TotalAI:AI 安全治理的四大支柱
ai·大模型安全·ai数据安全·qualys·ai安全治理·ai saas 治理·ai代码安全
kyriewen13 小时前
我让 4 个 AI 互相 review 代码,最温柔的那个下手最狠
前端·程序员·ai编程
天外飞雨道沧桑13 小时前
我在浏览器里练了一个 792 参数的大模型,它学会了补全 JavaScript
开发语言·javascript·ai·ecmascript·ai编程
柳杉14 小时前
用 Codex 完成智慧高速 3D 可视化大屏,从 18 张行业设计稿到可交互的运行监测中心
前端·ai编程·数据可视化
漫步的猪14 小时前
# 告别混乱与付费墙!Linkit:完全免费、本地优先的开源 AI 智能书签与收藏夹管理神器
人工智能·ai·开源·react·免费·书签·收藏夹
效率工作实验室14 小时前
搭建AI智能体应用,主流智能体开发平台应关注哪些核心能力
ai·agent·智能体开发平台·核心能力·ai智能体应用