빅데이타 & 머신러닝/생성형 AI (ChatGPT etc)

고급 Agent를 위한 Langgraph - Multi State 사용시 주의해야할점

Terry Cho 2025. 7. 10. 16:49

Langgraph에서는 하나의 Graph에서 여러개의 State를 동시에 사용할 수 있다. 

또한 정의된 State는 전역변수 처럼 인식되서, 다른 Node로 그 값을 넘기지 않아도 그 값이 그대로 유지되고 사용이 가능하다.

예를 들어

  • node1(State1)->State2
  • node2(State2)->State3
  • node3(State1)->State3

로 호출하는 구조가 있다고 하자.

이 경우, node1의 output인 State2는 node2의 Input에 들어가지만, node2의 output이 State3인데, node3에서 State3를 받지 않고, State1을 받을 수 있을까? 답변은 된다.

State1,2,3의 정보가 같이 유지되고 있기 때문에, 이전 노드의 State가 아니더라도 사용이 가능하다. 

아래 코드는 위에서 설명한 내용을 구현한 코드이다. 

from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
import os

class State1(TypedDict):
    name: str
    age: int

class State2(TypedDict):
    name: str
    address: str

class State3(TypedDict):
    message: str
    prompt: str

def node1(state: State1) -> State2:
    print("Executing node1...")
    print(f"State 1: {state}")
    
    return {"name": "terry", "address": "bayarea"}

def node2(state: State2) -> State3:
    print("Executing node2...")
    print(f"State 2: {state}")
    
    return {"message": "message", "prompt": "prompt"}

def node3(state: State1) -> State3:
    print("Executing node3...")
    print(f"State 1: {state}")
    
    return {"message": "hello", "prompt": "prompt"}

builder = StateGraph(State1)

builder.add_node("node1", node1)
builder.add_node("node2", node2)
builder.add_node("node3", node3)

builder.add_edge(START, "node1")
builder.add_edge("node1", "node2")
builder.add_edge("node2", "node3")
builder.add_edge("node3", END)

graph = builder.compile()

if __name__ == "__main__":
    result = graph.invoke({"name": "initial", "age": 0})
    
    print("\nFinal State:")
    print(f"Result: {result}")

아래는 실행결과이다. 

Executing node1...
State 1: {'name': 'initial', 'age': 0}
Executing node2...
State 2: {'name': 'terry', 'address': 'bayarea'}
Executing node3...
State 1: {'name': 'terry', 'age': 0}

Final State:
Result: {'name': 'terry', 'age': 0}

그런데 이상한점을 보면, node1에서는 State2를 리턴했다. 즉 State1의 정보를 업데이트 하지 않았다는 이야기인데, 

node3에서 State1의 정보를 출력해보면 name이 "terry'로 변경된 것을 확인할 수 있다. 

코드 어느부분에서도 State1을 업데이트 한적이 없는데, 왜 State1이 변경이 되었을까?

Langgraph는 node에서 리턴할때 모든 state값을 병합하여 저장한다. 그래서 state에 같은 이름이 있을 경우에는 어느 state의 정보인지 상관없이 공통적으로 변경이 된다. 

이를 방지하기 위해서는 State마다 다른 변수 이름을 사용하는 것이 좋다.