30

Core: LangGraph 기반 Agent 아키텍처 상세

RAG + Agent 파이프라인 통합

학습 목표

LangGraph StateGraph의 핵심 개념을 이해한다 Agent의 노드-엣지 구조를 설명할 수 있다 Tool 호출 흐름을 단계별로 추적할 수 있다

LangGraph Agent 아키텍처

StateGraph 핵심 개념

LangGraph의 핵심 3요소:

1. State (상태)
   - 에이전트가 "기억"하는 정보
   - messages, tool_calls, results...

2. Node (노드)
   - 실제 작업을 수행하는 함수
   - agent_node: LLM 호출
   - tool_node: 도구 실행

3. Edge (엣지)
   - 노드 간 전환 조건
   - "도구가 필요하면 tool_node로"
   - "답변 준비되면 END로"

Agent 그래프 구조

                    ┌──────────┐
                    │  START   │
                    └────┬─────┘
                         │
                    ┌────▼─────┐
              ┌─────│  agent   │◄──────────────┐
              │     │  (LLM)   │               │
              │     └────┬─────┘               │
              │          │                     │
              │    should_continue?             │
              │     /          \               │
              │   도구 필요     답변 준비        │
              │     /              \            │
              │ ┌──▼───┐      ┌────▼───┐       │
              │ │tools │      │  END   │       │
              │ │(실행) │      └────────┘       │
              │ └──┬───┘                       │
              │    │                           │
              │    └───────────────────────────┘
              │         (결과 반환)
              │
              └─── (최대 반복 초과 시 강제 종료)

Agent State 정의

from typing import TypedDict, Annotated
from langgraph.graph import MessagesState

class AgentState(MessagesState):
    """에이전트 상태

    MessagesState를 상속하면 messages 필드가 자동 포함됨.
    추가 상태가 필요하면 여기에 정의.
    """
    # 사용된 도구 기록
    tool_calls_count: int
    # 최종 응답에 포함할 소스 정보
    sources: list[dict]
    # KG 시각화 데이터
    kg_data: dict

노드 함수 상세

# 1. Agent 노드: LLM이 다음 행동을 결정
def agent_node(state: AgentState) -> dict:
    """
    LLM에게 현재 상태를 보여주고,
    도구를 호출할지, 최종 답변을 할지 결정하게 함
    """
    messages = state["messages"]
    response = llm.invoke(messages)
    return {"messages": [response]}


# 2. Tool 노드: 선택된 도구를 실행
def tool_node(state: AgentState) -> dict:
    """
    Agent가 선택한 도구를 실행하고,
    결과를 messages에 추가
    """
    last_message = state["messages"][-1]
    tool_calls = last_message.tool_calls

    results = []
    for call in tool_calls:
        tool = tool_map[call["name"]]
        result = tool.invoke(call["args"])
        results.append(ToolMessage(content=result, ...))

    return {"messages": results}


# 3. 조건부 엣지: 계속할지 끝낼지 판단
def should_continue(state: AgentState) -> str:
    last_message = state["messages"][-1]

    if last_message.tool_calls:
        return "tools"    # 도구 호출 필요
    else:
        return "end"      # 최종 답변 준비됨

전체 실행 흐름 예시

사용자: "CNC-001 알람 E-042 대응법?"

Step 1 [agent_node]:
  LLM 생각: "알람 관련 매뉴얼을 찾아야 함"
  -> tool_call: search_documents("CNC E-042 알람 대응")

Step 2 [should_continue]: tool_calls 있음 -> "tools"

Step 3 [tool_node]:
  search_documents 실행
  -> 결과: "매뉴얼 3.4.2절: E-042는 스핀들 과열..."

Step 4 [agent_node]:
  LLM 생각: "설비 관련 부품도 확인해야 함"
  -> tool_call: query_knowledge_graph("CNC-001")

Step 5 [should_continue]: tool_calls 있음 -> "tools"

Step 6 [tool_node]:
  query_knowledge_graph 실행
  -> 결과: "CNC-001 -> CL-003(냉각) -> CP-007(펌프)"

Step 7 [agent_node]:
  LLM 생각: "충분한 정보가 모였음. 종합 답변 생성"
  -> 최종 답변 생성 (tool_calls 없음)

Step 8 [should_continue]: tool_calls 없음 -> "end"

최종 응답:
  "E-042 알람은 스핀들 과열입니다.
   CNC-001의 냉각시스템 CL-003을 확인하세요.
   냉각수펌프 CP-007의 작동 상태를 점검하세요."
AI로 학습하기 — 꿀팁
🧪LangGraph 노드-엣지 제조 설계AI 학습 팁

LangGraph StateGraph의 노드-엣지 개념을 제조 고장 진단 Agent로 설계해보는 예시를 AI에게 요청하세요.

LangGraph StateGraph를 사용해 제조 설비 고장 진단 Agent를 설계한다면, 어떤 노드(상태 처리 단계)와 엣지(조건 분기)가 필요한지 설명하고, 간단한 Python 코드 뼈대(StateGraph 정의 + 노드 2~3개 + conditional_edges)를 보여줘.
이 팁이 도움이 됐나요?
핵심 포인트
  • LangGraph = State + Node + Edge
  • Agent Node: LLM이 도구 사용 여부를 결정
  • Tool Node: 선택된 도구를 실행하고 결과 반환
  • should_continue: 루프 제어 (계속/종료)