인공지능 개발자 수다(유튜브 바로가기) 자세히보기

자연어처리/Langchain

[LangGraph] Graph 기본 개념

Suda_777 2025. 4. 23. 00:40

목차

    반응형

     

    langchain 버전: 0.3.23

    langgraph 버전: 0.3.31

    내용 출처 : LangGrapn Docs

     

    1. Graph 개념

    LangGraph는 Graph를 구성해 Agent를 만들 수 있다.

     

    Graph의 핵심 구성은 다음과 같다.

    • Graph(그래프) : 노드(Node, 또는 정점 Vertex) 와 간선(Edge) 으로 이루어진 자료구조
    • Node(노드) : 그래프 내의 개체. 작업 단위(Task). 주로 Tool과 chatbot이 오게 됨
    • Edge(간선) : 두 노드를 연결하는 선
    • State(상태) : 노드 간에 전달되는 데이터 묶음, 입력과 결과를 저장하는 공간

     


    2. 그래프 만들기

    2.1. State(상태) 정의

    State는 클래스(Class) 형태로 정의한다.

    필요에 따라 속성을 추가할 수 있다.

    from langchain_core.messages import AnyMessage
    from typing_extensions import TypedDict
    
    
    class State(TypedDict):
        messages: list[AnyMessage]
        extra_field: int

     


    2.2. 노드(Node) 정의

    노드는 함수 형식으로 정의한다.

    state(상태)를 입력으로 받는다.

    from langchain_core.messages import AIMessage
    
    
    def node(state: State):
        """
        노드(Node) 정의
        """
        messages = state["messages"]
        new_message = AIMessage("Hello!")
    
        return {"messages": messages + [new_message], "extra_field": 10}

     


    2.3. 그래프(Graph) 정의

    • add_node() : 노드를 그래프에 추가함
    • set_entry_point() : 그래프의 시작점을 지정함
    • compile() : 그래프를 최종 컴파일함
    from langgraph.graph import StateGraph
    
    # 그래프 정의
    graph_builder = StateGraph(State)
    
    # 노드 추가
    graph_builder.add_node(node)
    
    # 그래프의 시적지점 지정
    graph_builder.set_entry_point("node")
    
    # 최종 컴파일
    graph = graph_builder.compile()

     

    그래프 시각화

    from IPython.display import Image, display
    
    display(Image(graph.get_graph().draw_mermaid_png()))

     


    3. 그래프 실행

    그래프는 Langchain과 마찬가지로

    invoke(), stream() 메서드를 이용해 실행할 수 있다.

    from langchain_core.messages import HumanMessage
    
    result = graph.invoke({"messages": [HumanMessage("Hi")]})
    result

     

    실행 결과

    {'messages': [HumanMessage(content='Hi', additional_kwargs={}, response_metadata={}),
      AIMessage(content='Hello!', additional_kwargs={}, response_metadata={})],
     'extra_field': 10}

     

    깔끔하게 출력

    for message in result["messages"]:
        message.pretty_print()

     

    실행 결과

    ================================ Human Message =================================
    
    Hi
    ================================== Ai Message ==================================
    
    Hello!

     


    Colab 링크

     

    Graph 기본 사용법.ipynb

    Colab notebook

    colab.research.google.com

     

    반응형