在 [3]
已复制!
%%capture --no-stderr
%pip install -U langgraph
%%capture --no-stderr %pip install -U langgraph
定义和使用图¶
在 [6]
已复制!
from langgraph.graph import StateGraph, START, END
from typing_extensions import TypedDict
# Define the schema for the input
class InputState(TypedDict):
question: str
# Define the schema for the output
class OutputState(TypedDict):
answer: str
# Define the overall schema, combining both input and output
class OverallState(InputState, OutputState):
pass
# Define the node that processes the input and generates an answer
def answer_node(state: InputState):
# Example answer and an extra key
return {"answer": "bye", "question": state["question"]}
# Build the graph with input and output schemas specified
builder = StateGraph(OverallState, input=InputState, output=OutputState)
builder.add_node(answer_node) # Add the answer node
builder.add_edge(START, "answer_node") # Define the starting edge
builder.add_edge("answer_node", END) # Define the ending edge
graph = builder.compile() # Compile the graph
# Invoke the graph with an input and print the result
print(graph.invoke({"question": "hi"}))
from langgraph.graph import StateGraph, START, END from typing_extensions import TypedDict # 定义输入的模式 class InputState(TypedDict): question: str # 定义输出的模式 class OutputState(TypedDict): answer: str # 定义整体模式,组合输入和输出 class OverallState(InputState, OutputState): pass # 定义处理输入并生成答案的节点 def answer_node(state: InputState): # 示例答案和额外的键 return {"answer": "bye", "question": state["question"]} # 构建带有指定输入和输出模式的图 builder = StateGraph(OverallState, input=InputState, output=OutputState) builder.add_node(answer_node) # 添加答案节点 builder.add_edge(START, "answer_node") # 定义起始边 builder.add_edge("answer_node", END) # 定义结束边 graph = builder.compile() # 编译图 # 使用输入调用图并打印结果 print(graph.invoke({"question": "hi"}))
{'answer': 'bye'}
请注意,invoke 的输出仅包含输出模式。