旅游网站建设系统宁德seo推广
文章目录
- 画图
- 简单解析
- 再贴结果图
画图
from langgraph.graph import StateGraph, END
from typing import TypedDict# 定义状态结构
# (刚入门可能不理解这是什么,可以理解为一个自定义的变量库,你的所有的入参出参都可以定义在这里)
# 如下:input和response就是2个自定义的字符串变量
class AgentState(TypedDict) :input: strresponse: str# 创建代理节点
def agent_node(state: AgentState) :return {"response":f"手工输入{state['input']}"}# 创建工具节点
def tool_node(state: AgentState) :return {"response":f"执行工具{state['response']}"}# 构建流程图
workflow = StateGraph(AgentState)# 添加节点
workflow.add_node("agent", agent_node)
workflow.add_node("tool", tool_node)# 添加边
workflow.set_entry_point("agent")
workflow.add_edge("agent","tool")
workflow.add_edge("tool", END)# 编译,生成图
graph = workflow.compile()# 执行
result = graph.invoke({"input":"你是谁啊!!!"})# 打印执行结果
print(f"result.input:{result['input']}")
print(f"result.response:{result['response']}")
print(f"result:{result}")
执行效果如下:
简单解析
上面基本每个地方都有注释,这里不介绍代码了。
介绍下结果为什么是这样?
我们画的图如下
START → [agent] → [tool] → END
其中START和 END是系统节点,agent和tool是我们的自定义节点。系统节点没有操作,只代表状态。所以我们重点看2个自定义节点。
[agent]
执行该节点之前:
input:你是谁啊!!!
response:
代码先走到agent节点,agent节点重新定义了response的值
"response":f"手工输入{state['input']}"
response拼接input后值为“手工输入你是谁啊!!!”
[tool]
在上面agent节点操作之后,此时
input:你是谁啊!!!
response:手工输入你是谁啊!!!
tool节点的操作为:
"response":f"执行工具{state['response']}"
在原response的基础上又拼接了“执行工具”,所以response最终结果为:执行工具手工输入你是谁啊!!!
再贴结果图
再看到这个结果图,就知道response为什么是这样了吧
还有一个点需要说明一下:最终返回值是 AgentState 类型字典中 所有累积的键值对 。