1. 首页>
  2. 技术文章>
  3. LangGraph学习笔记1

LangGraph学习笔记1

9/15/26 3:20:14 PM 浏览 595 评论 0

LangGraph

安装langgraph

pip install -U langgraph

定义state

from langchain_core.messages import AnyMessage
from typing_extensions import TypedDict
#定义节点间通讯的消息格式
class State(TypedDict):
    messages: list[AnyMessage]
    extra_field:int

定义节点

from langchain_core.messages import AIMessage
def node(state:State):
   messages = state["messages"]
   new_message = AIMessage(content="Hello,i am node1")
   
   return {
       "messages": messages + [new_message],
       "extra_field": 1
   }

创建图

from langgraph.graph import StateGraph,START, END
graph = StateGraph(State)
graph.add_edge(START, "node")
graph.add_node("node",node)
graph_builder = graph.compile()

查看节点与图结构:Mermaid是一种基于文本的图标和可视化工具,允许通过简单的文本语法来拆跟你讲复杂的图表和流程图。

from IPython.display import Image,display
display(Image(graph_builder.get_graph().draw_mermaid_png()))

调用

from langchain_core.messages import HumanMessage
initial_state = {
    "messages": [HumanMessage(content="Hello, i am human")],
    "extra_field": 0
}
result = graph_builder.invoke(initial_state)
result

使用pretty_print来格式化输出

from langchain_core.messages import HumanMessage
result = graph_builder.invoke({
    "messages":[HumanMessage(content="Hello, i am human")]
})
for message in result["messages"]:
    message.pretty_print()

串行控制

from typing_extensions import TypedDict
from IPython.display import Image,display
from langgraph.graph import START, END, StateGraph
class State(TypedDict):
    value_1:str
    value_2:str
   
def step_1(state:State):
    return {"value_1": "第一步"}
def step_2(state:State):
    current_value_1 = state["value_1"]
   
    return { "value_1": f"{current_value_1}  第二步"}
def step_3(state:State):
    return {"value_2": "第三步"}
   
graph_builder = StateGraph(State)
#添加节点
graph_builder.add_node(step_1)
graph_builder.add_node(step_2)
graph_builder.add_node(step_3)
# 添加边
graph_builder.add_edge(START, "step_1")
graph_builder.add_edge("step_1", "step_2")
graph_builder.add_edge("step_2", "step_3")
graph = graph_builder.compile()
display(Image(graph.get_graph().draw_mermaid_png()))
graph.invoke({"value_1": "1", "value_2": "2"})


网友讨论