2026-05-25 21:33:13 +08:00

48 lines
1.4 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
LangGraph Hello World - 最简单的图
"""
from langgraph.graph import StateGraph, START, END
from typing import TypedDict, Annotated
import operator
# 1⃣ 定义状态 - 这是节点之间传递的数据结构
class GraphState(TypedDict):
"""图的状态 - 节点之间共享的数据"""
message: str # 一条消息
# 2⃣ 定义节点 - 每个节点是一个函数,接收状态并返回更新
def greet_node(state: GraphState):
"""问候节点"""
print(f"[问候节点] 收到: {state['message']}")
return {"message": "你好!我是 LangGraph 智能体 👋"}
def process_node(state: GraphState):
"""处理节点"""
print(f"[处理节点] 收到: {state['message']}")
return {"message": state['message'] + " 很高兴见到你!"}
# 3⃣ 构建图
graph = StateGraph(GraphState)
# 添加节点
graph.add_node("greet", greet_node)
graph.add_node("process", process_node)
# 添加边 - 定义流程走向
# START -> greet -> process -> END
graph.add_edge(START, "greet") # 开始 -> 问候节点
graph.add_edge("greet", "process") # 问候 -> 处理节点
graph.add_edge("process", END) # 处理 -> 结束
# 编译图
app = graph.compile()
# 4⃣ 运行!
print("=" * 40)
print("🚀 运行 LangGraph Hello World")
print("=" * 40)
result = app.invoke({"message": "Hi!"})
print()
print("最终结果:", result['message'])