[Python] The conditional edge in LangGraph causes the reduce function to be invoked twice

Discussão em 'Python' iniciado por Stack, Agosto 4, 2025.

  1. Stack

    Stack Membro Participativo

    I am a beginner with LangGraph and am learning to create a graph to compute the Fibonacci sequence. The program has two nodes: one responsible for updating the Fibonacci sequence, and the other for controlling the loop. The complete code is as follows:

    from langchain_core.runnables import Runnable
    from collections.abc import Iterable
    from langgraph.graph import StateGraph
    from pydantic import BaseModel
    from typing import Any, Dict, Annotated
    from langgraph.constants import END
    def append_to_list(a : list, b) -> list:
    print(f"append_to_list:{a}, {b}")
    if isinstance(b, Iterable) and not isinstance(b, str):
    a.extend(b)
    else:
    a.append(b)
    return a
    class Node(Runnable):
    def __init__(self, name : str):
    self.name = name
    def invoke(self, input: Any, config: Dict | None = None) -> Any:
    c = input.a + input.b
    print(f"{self.name}:{input}")
    return {"a":input.b, "b":c, "fibonacci_list":c}

    class ConditionalNode(Runnable):
    def __init__(self, name : str, threshold: int):
    self.threshold = threshold
    self.name = name

    def invoke(self, input: Any, config) -> Any:
    print(f"{self.name}:{input}")
    return {"path" : input.b >= self.threshold}
    class State(BaseModel):
    a : int
    b : int
    fibonacci_list : Annotated[list[int], append_to_list]

    graph = StateGraph(State)
    graph.add_node("n1", Node(name = "n1"))
    graph.add_conditional_edges("n1", ConditionalNode(name = "CN", threshold = 10), {True : END, False: "n1"})
    graph.set_entry_point("n1")
    g = graph.compile()
    s = g.invoke({"a":1, "b":1, "fibonacci_list":[1, 1]})
    print(s)


    The n1 node is responsible for computing the latest value in the Fibonacci sequence and returning updates to the graph state. The append_to_list function is intended to add the newly generated fibonacci_list value to the fibonacci_list list in the graph state. I originally thought that append_to_list would be called only once after the n1 node finishes execution, and that the final result would be a complete Fibonacci sequence.

    However, in reality, the append_to_list function is also called every time the CN node finishes executing, and the arguments passed to it are the same as those passed after the n1 node finishes. This results in duplicate values being added to the Fibonacci sequence. For example, I expected to get [1, 1, 2, 3, 5, 8, 13], but instead I got [1, 1, 2, 2, 3, 3, 5, 5, 8, 8, 13, 13].

    How can I prevent the conditional edge from triggering the reduce function?

    Continue reading...

Compartilhe esta Página