How to pass state that uses add operator to subgraph without duplicating it? #2730
-
Consider this minimal reproducible example: # %%
from typing import TypedDict, Annotated
from operator import add
from langgraph.graph import END, START, StateGraph
# %%
class State(TypedDict):
q: Annotated[list[str], add]
answer: Annotated[list[str], add]
docs: Annotated[list[str], add]
# %%
def put_docs(state):
q = state["q"]
return {
"q": [],
"answer": [],
"docs": ["Some doc"]
}
# %%
subgraph = StateGraph(State).add_node(put_docs).add_edge(START, "put_docs").add_edge("put_docs", END).compile()
# %%
def answer_node(state: State):
q = state['q']
return {
"q": [],
"answer": ["Answer"],
"docs": []
}
# %%
graph = (
StateGraph(State)
.add_node(answer_node)
.add_node("subgraph", subgraph)
.add_edge(START, "answer_node")
.add_edge("answer_node", "subgraph")
.add_edge("subgraph", END)
.compile()
)
# %%
q = {"q": ["Hi"]}
print(graph.invoke(q)) This prints Is there a way to avoid this duplication? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
yes, you can write a custom reducer (instead of operator.add) that assigns an ID to the answer and then deduplicates based on the IDs, something similar to |
Beta Was this translation helpful? Give feedback.
-
Or you can put the subgraph in a function and filter the inputs & outputs:
|
Beta Was this translation helpful? Give feedback.
yes, you can write a custom reducer (instead of operator.add) that assigns an ID to the answer and then deduplicates based on the IDs, something similar to
add_messages
reducer https://github.com/langchain-ai/langgraph/blob/main/libs/langgraph/langgraph/graph/message.py#L18