ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

第四单元——第一课:LangGraph 的状态、节点和连线

第四单元——第一课:LangGraph 的状态、节点和连线 LangGraph 把流程拆成节点用状态在节点之间传递数据。先做一个不调用模型的小程序看清它如何运行。官方 Graph API 说明保存为unit4_lesson1_first_graph.pyfrom typing import NotRequired, TypedDict from langgraph.graph import END, START, StateGraph # 状态各节点共享的数据 class BookstoreState(TypedDict): question: str context: NotRequired[str] answer: NotRequired[str] # 节点一查找资料 def retrieve(state: BookstoreState) - dict[str, str]: print(执行retrieve) if 会员 in state[question]: context 会员购买图书可以享受八折优惠。 elif 退货 in state[question]: context 购买后七天内可凭购物小票申请退货。 else: context return {context: context} # 节点二根据资料组织回答 def compose_answer(state: BookstoreState) - dict[str, str]: print(执行compose_answer) if state[context]: return {answer: state[context]} return {answer: 资料中没有相关信息。} builder StateGraph(BookstoreState) builder.add_node(retrieve, retrieve) builder.add_node(compose_answer, compose_answer) builder.add_edge(START, retrieve) builder.add_edge(retrieve, compose_answer) builder.add_edge(compose_answer, END) graph builder.compile() result graph.invoke({question: 会员买书有什么优惠}) print(最终回答, result[answer]) print(完整状态, result)运行python unit4_lesson1_first_graph.py程序会按下面的顺序执行开始 → retrieve → compose_answer → 结束注意retrieve只返回{context: ...}但原来的question仍留在状态里下一节点可以读取更新后的状态。这就是本课的关键。小练习把问题改为“书店提供送货吗”观察没有资料时的回答。下一课会把这里模拟的检索节点换成你前面建立的真实向量检索。问题1LangGraph 使用可以看到图吗可以。把下面代码加在上一课的graph builder.compile()后面就能生成流程图 PNGfrom pathlib import Path image_path Path(__file__).with_name(bookstore_graph.png) image_path.write_bytes(graph.get_graph().draw_mermaid_png()) print(流程图已保存, image_path)运行脚本后打开同目录的bookstore_graph.png会看到mermaid flowchart LR A[开始] -- B[retrieve] B -- C[compose_answer] C -- D[结束] draw_mermaid_png()默认通过 Mermaid.ink 在线生成图片因此需要联网。如果只想在 CMD 中查看图的 Mermaid 文本可以运行print(graph.get_graph().draw_mermaid())图展示的是可能的流程结构某次运行实际走了哪些节点还需查看执行输出或追踪记录。LangGraph 可视化文档问题2可以通过图形化的方式编辑LangGraph吗可以“看图、调试”但如果指的是拖拽节点和连线直接修改写的 LangGraph 程序目前官方的 LangSmith Studio 不是这样的编辑器。它能显示流程图、运行流程、查看和修改运行状态图的节点与连线仍主要在 Python 代码里定义。部分提示词和助手配置可以在界面中调整但这不等于改图的结构。LangGraph Studio 介绍 · 助手配置文档对你现在这个书店例子想在retrieve和compose_answer之间加一步就在代码里添加节点和边保存后再用图形界面看效果。
返回列表