mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-17 21:25:46 +02:00
4.9 KiB
4.9 KiB
In [ ]:
%%capture --no-stderr
%pip install -U langgraphIn [9]:
from langgraph.graph import StateGraph, START, END
from typing import TypedDict
# The overall state of the graph
class OverallState(TypedDict):
question: str
answer: str
# This is what the node that generates the query will return
class QueryOutputState(TypedDict):
query: str
# This is what the node that retrieves the documents will return
class DocumentOutputState(TypedDict):
docs: list[str]
# This is what the node that generates the final answer will take in
class GenerateInputState(OverallState, DocumentOutputState):
pass
# Node to generate query
def generate_query(state: OverallState) -> QueryOutputState:
# Replace this with real logic
return {"query": state["question"][:2]}
# Node to retrieve documents
def retrieve_documents(state: QueryOutputState) -> DocumentOutputState:
# Replace this with real logic
return {"docs": [state["query"]] * 2}
# Node to generate answer
def generate(state: GenerateInputState) -> OverallState:
return {"answer": "\n\n".join(state["docs"] + [state["question"]])}
graph = StateGraph(OverallState)
graph.add_node(generate_query)
graph.add_node(retrieve_documents)
graph.add_node(generate)
graph.add_edge(START, "generate_query")
graph.add_edge("generate_query", "retrieve_documents")
graph.add_edge("retrieve_documents", "generate")
graph.add_edge("generate", END)
graph = graph.compile()
graph.invoke({"question": "foo"})Out [9]:
{'question': 'foo', 'answer': 'fo\n\nfo\n\nfoo'}