AI Agent开发学习系列 - LangGraph(4): 有多个输入的Graph(练习解答)
在AI Agent开发学习系列 - LangGraph(3): 有多个输入的Graph中,我们学习了如何创建有多个输入的Graph。为了巩固学习,我们来做一个练习。
用LangGraph创建如下图的一个Agent:
要求:
- 输入你的名字
- 输入一个数字列表,如[1,2,3,4]
- 输入一个运算符号
- 如果运算符号为+,则返回Hi there <名字>, your answer is <数字列表每项之号>
- 如果运算符号为*,则返回Hi there <名字>, your answer is <数字列表每项之积>
- 如果运算符号为以上其他,则返回Hi there <名字>! Your operation is not supported!
解答:
from typing import TypedDict, List
from langgraph.graph import StateGraph
import mathclass AgenState(TypedDict):name: strvalues: List[int]operation: strresult: strdef process_values(state: AgenState) -> AgenState:"""This function handles multiple different inputs"""if state["operation"] == "+":state["result"] = f"Hi there {state["name"]}, your answer is {sum(state["values"])}"elif state["operation"] == "*":state["result"] = f"Hi there {state["name"]}, your aswer is {math.prod(state["values"])}"else:state["result"] = f"Hi there {state["name"]}! Your operation is not supported!"return stategraph = StateGraph(AgenState)graph.add_node("processor", process_values)
graph.set_entry_point("processor")
graph.set_finish_point("processor")app = graph.compile()from IPython.display import Image, display
display(Image(app.get_graph().draw_mermaid_png()))answers = app.invoke({"values": [1, 2, 3, 4], "name": "Alex", "operation": "+"})
print(answers["result"])
运行结果:
Hi there Alex, your answer is 10