SubGraph와 Router

2026. 2. 22. 22:45·AI/LangGraph
반응형

 

👋 들어가기 전

이번 내용은 이전에 만들었던, Self Rag, Corrective Rag, 신규 Graph를 모두 묶을려고한다.

새로 등장하는 SubGraph와 Router를 이용해서 한번 진행해보자.


🪧 Router

 

⭐정의

그래프의 흐름을 결정하는 핵심적인 의사결정 장치

 

🧩 역할

  • 입력된 정보를 분류하고, 이를 해당 분야의 전담 에이전트(Specialized Agents)에게 보내는 역할

➡️ Sub Graph

 

⭐정의

다른 그래프 안에서 하나의 노드(Node)처럼 사용되는 독립된 그래프

 

🧩 역할

  • 멀티 에이전트 시스템 구축
    • 각 에이전트가 수행하는 복잡한 단계를 별도의 그래프로 분리하여 관리 가능
  • 코드 재사용
    • 공통적으로 쓰이는 작업 흐름(예: 데이터 정제, 검색 로직)을 서브그래프로 만들어 여러 상위 그래프에서 재사용 가능
  • 개발 분업화
    • 자기 담당 영역(서브그래프)의 입력과 출력만 맞추면, 내부 로직이 어떻게 돌아가는지 상위 그래프 팀이 몰라도 독립적으로 개발 가

🤖 예제

 

우리의 목표는 다음과 같다.

 

이전 vector_store에 있는 정보가 있을 때는 Self-RAG 그래프를 이용

간단한 작업일 경우, basic_generate 이용

웹 서치가 필요할 때는 Corrective RAG를 이용

 

목표 그래프

 

route를 통해, 어떤 Agent(Graph)를 이용할지 결정

  • 정확히 어떤 경로가 존재하는 지 명확히 명시
    • BaseModel
    • with_structured_output
    • 위 2개를 통해
from langchain_core.prompts import ChatPromptTemplate
from pydantic import BaseModel, Field
from typing import Literal

class Route(BaseModel):
    target: Literal['vector_store', 'llm', 'web_search'] = Field(
        description="The target for the query to answer"
    )

# 라우팅 관련 프롬포트
router_system_prompt = """
You are an expert at routing a user's question to 'vector_store', 'llm', or 'web_search'.
'vector_store' contains information about income tax up to December 2024.
if you think the question is simple enough use 'llm'
if you think you need to search the web to answer the question use 'web_search'
"""


router_prompt = ChatPromptTemplate.from_messages([
    ('system', router_system_prompt),
    ('user', '{query}')
])

router_llm = ChatOpenAI(model="gpt-4o-mini")
structured_router_llm = router_llm.with_structured_output(Route) # Router 클래스 형태로 반환

def router(state: AgentState) -> Literal['vector_store', 'llm', 'web_search']:
    """
    사용자의 질문에 기반하여 적절한 경로를 결정합니다.

    Args:
        state (AgentState): 사용자의 질문을 포함한 에이전트의 현재 state.

    Returns:
        Literal['vector_store', 'llm', 'web_search']: 질문을 처리하기 위한 적절한 경로를 나타내는 문자열.
    """
    # state에서 질문을 추출합니다
    query = state['query']
    
    # 프롬프트와 구조화된 라우터 LLM을 연결하여 체인을 생성합니다
    router_chain = router_prompt | structured_router_llm 
    
    # 체인을 사용하여 경로를 결정합니다
    route = router_chain.invoke({'query': query})

    # 결정된 경로의 타겟을 반환합니다
    return route.target

 

 

 

그래프 연결와 edge 연결

from income_tax_graph import graph as income_tax_subgraph

graph_builder.add_node('income_tax_agent', income_tax_subgraph)
graph_builder.add_node('web_search', web_search)
graph_builder.add_node('web_generate', web_generate)
graph_builder.add_node('basic_generate', basic_generate)

from langgraph.graph import START, END

graph_builder.add_conditional_edges(
    START, 
    router,
    {
        'vector_store': 'income_tax_agent',
        'llm': 'basic_generate',
        'web_search': 'web_search'
    }
)

graph_builder.add_edge('web_search', 'web_generate')
graph_builder.add_edge('web_generate', END)
graph_builder.add_edge('basic_generate', END)
graph_builder.add_edge('income_tax_agent', END)

 


출처

https://arxiv.org/abs/2403.14403

 

Adaptive-RAG: Learning to Adapt Retrieval-Augmented Large Language Models through Question Complexity

Retrieval-Augmented Large Language Models (LLMs), which incorporate the non-parametric knowledge from external knowledge bases into LLMs, have emerged as a promising approach to enhancing response accuracy in several tasks, such as Question-Answering (QA).

arxiv.org

https://docs.langchain.com/oss/python/langchain/multi-agent/router

 

Router - Docs by LangChain

Tutorial: Build a multi-source knowledge base with routing Build a router that queries GitHub, Notion, and Slack in parallel, then synthesizes results into a coherent answer. Covers state definition, specialized agents, parallel execution with Send, and re

docs.langchain.com

https://docs.langchain.com/oss/python/langgraph/use-subgraphs

 

Subgraphs - Docs by LangChain

Full example: different state schemas (two levels of subgraphs)

docs.langchain.com

https://github.com/jasonkang14/inflearn-langgraph-agent

 

GitHub - jasonkang14/inflearn-langgraph-agent: 인프런의 "LangGraph를 활용한 AI Agent 개발" 강의 소스코드입니

인프런의 "LangGraph를 활용한 AI Agent 개발" 강의 소스코드입니다. Contribute to jasonkang14/inflearn-langgraph-agent development by creating an account on GitHub.

github.com

 

반응형

'AI > LangGraph' 카테고리의 다른 글

지금까지 우리가 만든건 Agent가 아니다??  (0) 2026.02.23
RunnablePassthrough  (0) 2026.02.23
Corrective RAG  (0) 2026.02.22
Self RAG  (0) 2026.02.22
Conditional Edge  (0) 2026.02.22
'AI/LangGraph' 카테고리의 다른 글
  • 지금까지 우리가 만든건 Agent가 아니다??
  • RunnablePassthrough
  • Corrective RAG
  • Self RAG
Hamp
Hamp
남들에게 보여주기 부끄러운 잡다한 글을 적어 나가는 자칭 기술 블로그입니다.
  • Hamp
    Hamp의 분리수거함
    Hamp
  • 전체
    오늘
    어제
    • 분류 전체보기 (339)
      • CS (30)
        • 객체지향 (2)
        • Network (7)
        • OS (6)
        • 자료구조 (1)
        • LiveStreaming (3)
        • 이미지 (1)
        • 잡다한 질문 정리 (0)
        • Hardware (2)
        • 이론 (6)
        • 컴퓨터 그래픽스 (0)
      • Firebase (3)
      • Programing Langauge (41)
        • swift (34)
        • python (6)
        • Kotlin (1)
      • iOS (134)
        • UIKit (37)
        • Combine (1)
        • SwiftUI (34)
        • Framework (7)
        • Swift Concurrency (22)
        • Tuist (6)
        • Setting (11)
        • Modularization (1)
        • Instruments (6)
      • PS (59)
        • 프로그래머스 (24)
        • 백준 (13)
        • LeetCode (19)
        • 알고리즘 (3)
      • Git (18)
        • 명령어 (4)
        • 이론 (2)
        • hooks (1)
        • config (2)
        • action (7)
      • Shell Script (2)
      • Linux (6)
        • 명령어 (5)
      • Spring (21)
        • 어노테이션 (6)
        • 튜토리얼 (14)
      • CI-CD (4)
      • Android (0)
        • Jetpack Compose (0)
      • AI (21)
        • 이론 (10)
        • MCP (1)
        • LangGraph (10)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    protocol
    concurrency
    AVFoundation
    투포인터
    boostcamp
    GIT
    Tuist
    UIKit
    SwiftUI
    dp
    백준
    property
    Spring
    CS
    프로그래머스
    dispatch
    lifecycle
    dfs
    Swift
    IOS
  • 최근 댓글

  • 최근 글

  • 반응형
  • hELLO· Designed By정상우.v4.10.0
Hamp
SubGraph와 Router
상단으로

티스토리툴바