LANGGRAPH

LangGraph 中的应用程序从一个入口点开始,根据执行情况,流程可能会进入一个函数或另一个函数,直到到达END。

1. 状态

**状态(State)**是 LangGraph 的核心概念。它表示流经您应用程序的所有信息。

复制代码
from typing_extensions import TypedDict

class State(TypedDict):
    graph_state: str

状态是用户定义的,因此字段应精心设计,以包含决策过程所需的所有数据!

2. 节点

**节点(Nodes)**是 Python 函数。每个节点:

  • 将状态作为输入
  • 执行一些操作
  • 返回状态的更新
复制代码
def node_1(state):
    print("---Node 1---")
    return {"graph_state": state['graph_state'] +" I am"}

def node_2(state):
    print("---Node 2---")
    return {"graph_state": state['graph_state'] +" happy!"}

def node_3(state):
    print("---Node 3---")
    return {"graph_state": state['graph_state'] +" sad!"}

例如,节点可以包含:

  • LLM 调用:生成文本或做出决策
  • 工具调用:与外部系统交互
  • 条件逻辑:确定后续步骤
  • 人工干预:从用户获取输入

3. 边

**边(Edges)**连接节点并定义通过图的可能路径

复制代码
import random
from typing import Literal

def decide_mood(state) -> Literal["node_2", "node_3"]:
    
    # Often, we will use state to decide on the next node to visit
    user_input = state['graph_state'] 
    
    # Here, let's just do a 50 / 50 split between nodes 2, 3
    if random.random() < 0.5:

        # 50% of the time, we return Node 2
        return "node_2"
    
    # 50% of the time, we return Node 3
    return "node_3"

边可以是:

  • 直接的:始终从节点 A 到节点 B
  • 有条件的:根据当前状态选择下一个节点

4. 状态图

**状态图(StateGraph)**是包含您整个代理工作流的容器

复制代码
from IPython.display import Image, display
from langgraph.graph import StateGraph, START, END

# Build graph
builder = StateGraph(State)
builder.add_node("node_1", node_1)
builder.add_node("node_2", node_2)
builder.add_node("node_3", node_3)

# Logic
builder.add_edge(START, "node_1")
builder.add_conditional_edges("node_1", decide_mood)
builder.add_edge("node_2", END)
builder.add_edge("node_3", END)

# Add
graph = builder.compile()
相关推荐
青春易逝丶6 分钟前
策略模式
java·开发语言·策略模式
贼爱学习的小黄14 分钟前
NC BIP参照开发
java·前端·nc
小江的记录本18 分钟前
【MyBatis-Plus】MyBatis-Plus的核心特性、条件构造器、分页插件、乐观锁插件
java·前端·spring boot·后端·sql·tomcat·mybatis
小张会进步19 分钟前
数组:二维数组
java·javascript·算法
你有按下913的勇气吗22 分钟前
【Agent,RAG,Transform】
linux·运维·服务器
光影少年23 分钟前
如何进行前端性能优化?
前端·性能优化
vx-程序开发26 分钟前
springboot在线装修管理系统-计算机毕业设计源码56278
java·c语言·spring boot·python·spring·django·php
大傻^30 分钟前
Spring AI Alibaba 可观测性实践:AI应用监控与链路追踪
java·人工智能·后端·spring·springaialibaba
Dxy123931021630 分钟前
js如何把字符串转数字
开发语言·前端·javascript
云烟成雨TD35 分钟前
Spring AI Alibaba 1.x 系列【1】阿里巴巴 AI 生态
java·人工智能·spring