AI Agent开发学习系列 - LangGraph(6): 有多个节点的Sequential Graph(练习解答)
在AI Agent开发学习系列 - LangGraph(5): 有多个节点的Sequential Graph中,我们学习了如何创建有多个节点的Sequential Graph。为了巩固学习,我们来做一个练习。
用LangGraph创建如下图的一个Agent:
要求:
- 输入你的名字
- 输入你的年龄
- 输入你的技能列表,如[Java, Python, JS]
- 在第一个节点中,返回结果<名字> welcmoe to the system!
- 在第二个节点中,返回第一个节点的结果加上You are <年龄> years old!
- 第三个节点中中,返回第二个节点的结果加上You have skills in <技能>, <技能> and <技能>.
- 最终输出图和最终消息结果。
解答:
from typing import TypedDict
from langgraph.graph import StateGraphclass AgentState(TypedDict):name: strage: strskills: listmessage: strdef first_note(state: AgentState) -> AgentState:"""This is the first node of our sequence"""state["message"] = f"{state["name"]}, welcmoe to the system! "return statedef second_node(state: AgentState) -> AgentState:"""This is the second node of our sequence"""state["message"] = state["message"] + f"You are {state["age"]} years old! "return statedef third_node(state: AgentState) -> AgentState:"""This is the third node of our sequence"""state["message"] = state["message"] + f"You have skills in {", ".join(state["skills"][0:-1])} and {state["skills"][-1]}."return stategraph = StateGraph(AgentState)graph.add_node("first_note", first_note)
graph.add_node("second_node", second_node)
graph.add_node("third_node", third_node)graph.set_entry_point("first_note")
graph.add_edge("first_note", "second_node")
graph.add_edge("second_node", "third_node")
graph.set_finish_point("third_node")app = graph.compile()from IPython.display import Image, display
display(Image(app.get_graph().draw_mermaid_png()))result = app.invoke({"name": "Alex", "age": "41", "skills": ["Python", "AI Agent", "LangGraph"]})
print(result["message"])
输出结果:
Alex, welcmoe to the system! You are 41 years old! You have skills in Python, AI Agent and LangGraph.