Post

SubGraph

Let’s Understanding `SubGraph` in LangGraph.

SubGraph

Using SubGraphs, you can build complex systems that consist of multiple components in a more structured way. Each component itself can become a graph, and this concept is especially useful in multi-agent systems.

In this post, we’ll take a look at how to implement a SubGraph in a simple way.

Construct LangGraph using SubGraphs

A common scenario is when the parent graph and the subgraph communicate with each other through a shared State Key.

Let’s take the Graph we built in the previous post, restructure it as a SubGraph, and then build a new Graph that rewrites it into an SNS format.

Normal LangGraph

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Construct the Graph
workflow = StateGraph(GraphState)

workflow.add_node("MyLLM", run_llm_with_tools)
workflow.add_node("tools", tool_node)

workflow.set_entry_point("MyLLM")

# Setting Conditional Edges
## All three are equivalent!
workflow.add_conditional_edges("MyLLM", tools_condition)
# workflow.add_conditional_edges("MyLLM", my_tools_condition)
# workflow.add_conditional_edges(
#     source="MyLLM",
#     path=my_tools_condition,
#     # If the return value of `route_tools` is `"tools"`, route to the `"tools"` node; otherwise, route to the `END` node.
#     path_map={"tools": "tools", END: END},
# )

# Checkpoint configuration (memory storage)
# memory = MemorySaver()
os.makedirs("./cache", exist_ok=True)
conn = sqlite3.connect("./cache/checkpoints.sqlite", check_same_thread=False)
memory =  SqliteSaver(conn)
llm_app = workflow.compile(checkpointer=memory)

# Graph visualization
visualize_graph(llm_app, xray=True)

Execution and evaluation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
config = RunnableConfig(recursion_limit=10, configurable={"thread_id": random_uuid()})

question = "오늘의 AI 뉴스 알려줘."
inputs = {
    "messages": [
        HumanMessage(
            content=question
        )
    ],
}
result = llm_app.invoke(inputs, config)

print("====" * 4)
print(f"Total number of messages: {len(result['messages'])}")
print("====" * 4)
print("All messages:")
for idx in range(len(result['messages'])):
    print(f"{result['messages'][idx]}")
print("====" * 4)
print(f"Final response:\n{result['messages'][-1].content}")
print("====" * 4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
=== 일반 실행 방식 ===
================
총 메시지 수: 4
================
전체 메시지 출력:
content='오늘의 AI 뉴스 알려줘.' additional_kwargs={} response_metadata={} id='7c9dbb49-6b90-4e0f-8bf4-3da794db310e'
content='' additional_kwargs={'tool_calls': [{'id': '0', 'function': {'arguments': '{"query": "AI 뉴스"}', 'name': 'googlenews_search_tool'}, 'type': 'function', 'index': 0}], 'refusal': None} response_metadata={'token_usage': {'completion_tokens': 11, 'prompt_tokens': 660, 'total_tokens': 671, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'meta-llama/llama-4-maverick', 'system_fingerprint': None, 'id': 'gen-1758401378-zmJbSy4ZwWwCx13ERHRm', 'service_tier': None, 'finish_reason': 'tool_calls', 'logprobs': None} id='run--9e45d1dc-b748-40bc-a36d-480ffeef189a-0' tool_calls=[{'name': 'googlenews_search_tool', 'args': {'query': 'AI 뉴스'}, 'id': '0', 'type': 'tool_call'}] usage_metadata={'input_tokens': 660, 'output_tokens': 11, 'total_tokens': 671, 'input_token_details': {}, 'output_token_details': {}}
content='- "AI 사리부터 3D 피규어까지"...나노 바나나, 인도에서 바이럴 폭발 - AI타임스\n- AI 경쟁서 한국 존재감…미중 이어 세계 3위 - 연합뉴스\n- 삼성·하이닉스 불기둥 뒤엔 결국…더 주목받는 미국 AI주 ‘3대장’ - 매일경제' name='googlenews_search_tool' id='3ac90a9f-243a-47a1-852a-4c0ddc663088' tool_call_id='0'
content='AI 뉴스는 다음과 같습니다.\n1. "AI 사리부터 3D 피규어까지"...나노 바나나, 인도에서 바이럴 폭발 - AI타임스\n2. AI 경쟁서 한국 존재감…미중 이어 세계 3위 - 연합뉴스\n3. 삼성·하이닉스 불기둥 뒤엔 결국…더 주목받는 미국 AI주 ‘3대장’ - 매일경제' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 84, 'prompt_tokens': 758, 'total_tokens': 842, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'meta-llama/llama-4-maverick', 'system_fingerprint': None, 'id': 'gen-1758401379-eorWMC45ZPvsagDUIDRr', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None} id='run--e5be250d-2779-430b-ac59-b2e549efc86c-0' usage_metadata={'input_tokens': 758, 'output_tokens': 84, 'total_tokens': 842, 'input_token_details': {}, 'output_token_details': {}}
================
최종 답변:
AI 뉴스는 다음과 같습니다.
1. "AI 사리부터 3D 피규어까지"...나노 바나나, 인도에서 바이럴 폭발 - AI타임스
2. AI 경쟁서 한국 존재감…미중 이어 세계 3위 - 연합뉴스
3. 삼성·하이닉스 불기둥 뒤엔 결국…더 주목받는 미국 AI주 ‘3대장’ - 매일경제
================

LangGraph using SubGraphs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Construct the SubGraph
def create_agentbysubgraph():
    subgraph = StateGraph(GraphState)

    subgraph.add_node("MyLLM", run_llm_with_tools)
    subgraph.add_node("tools", tool_node)
    
    subgraph.set_entry_point("MyLLM")
    subgraph.add_conditional_edges("MyLLM", tools_condition)        
    subgraph.add_edge("tools", "MyLLM")

    return subgraph.compile()
#########################################################################

workflow = StateGraph(GraphState)

# Add the SubGraph
agent_subgraph = create_agentbysubgraph()
workflow.add_node("agent_subgraph", agent_subgraph)
workflow.add_node("sns_post", run_llm_sns_format)

workflow.set_entry_point("agent_subgraph")
workflow.add_edge("agent_subgraph", "sns_post")
workflow.add_edge("sns_post", END)

graph = workflow.compile()

# Checkpoint configuration (memory storage)
# memory = MemorySaver()
os.makedirs("./cache", exist_ok=True)
conn = sqlite3.connect("./cache/checkpoints.sqlite", check_same_thread=False)
memory =  SqliteSaver(conn)
llm_include_sns_app = workflow.compile(checkpointer=memory)

# Graph visualization
visualize_graph(llm_include_sns_app, xray=True)

Execution and evaluation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
config = RunnableConfig(recursion_limit=10, configurable={"thread_id": random_uuid()})

question = "오늘의 AI 뉴스 알려줘."
inputs = {
    "messages": [
        HumanMessage(
            content=question
        )
    ],
}
result = llm_include_sns_app.invoke(inputs, config)

print("====" * 4)
print(f"Total number of messages: {len(result['messages'])}")
print("====" * 4)
print("All messages:")
for idx in range(len(result['messages'])):
    print(f"{result['messages'][idx]}")
print("====" * 4)
print(f"Final response:\n{result['messages'][-1].content}")
print("====" * 4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
=== 일반 실행 방식 ===
================
총 메시지 수: 5
================
전체 메시지 출력:
content='오늘의 AI 뉴스 알려줘.' additional_kwargs={} response_metadata={} id='67210ba7-9ff9-44af-aeca-535bebc29d32'
content='' additional_kwargs={'tool_calls': [{'id': 'call_0rej121yb2qh1o5yikrrxhip', 'function': {'arguments': '{"query":"AI 뉴스"}', 'name': 'googlenews_search_tool'}, 'type': 'function', 'index': 0}], 'refusal': None} response_metadata={'token_usage': {'completion_tokens': 33, 'prompt_tokens': 1141, 'total_tokens': 1174, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'meta-llama/llama-4-maverick', 'system_fingerprint': None, 'id': 'gen-1758401365-RHxAKhqsTK4QKGobSC9V', 'service_tier': None, 'finish_reason': 'tool_calls', 'logprobs': None} id='run--df0caa45-de0d-419b-9dd0-82eb4c600fa3-0' tool_calls=[{'name': 'googlenews_search_tool', 'args': {'query': 'AI 뉴스'}, 'id': 'call_0rej121yb2qh1o5yikrrxhip', 'type': 'tool_call'}] usage_metadata={'input_tokens': 1141, 'output_tokens': 33, 'total_tokens': 1174, 'input_token_details': {}, 'output_token_details': {}}
content='- "AI 사리부터 3D 피규어까지"...나노 바나나, 인도에서 바이럴 폭발 - AI타임스\n- AI 경쟁서 한국 존재감…미중 이어 세계 3위 - 연합뉴스\n- 삼성·하이닉스 불기둥 뒤엔 결국…더 주목받는 미국 AI주 ‘3대장’ - 매일경제' name='googlenews_search_tool' id='2fee9d77-3116-4e81-a692-48c64f240b77' tool_call_id='call_0rej121yb2qh1o5yikrrxhip'
content='1. 인도에서 "AI 사리부터 3D 피규어까지"를 제작한 나노 바나나가 바이럴되고 있습니다.\n2. 한국의 AI 경쟁력이 세계 3위로 평가받고 있습니다.\n3. 삼성과 하이닉스의 반도체 경쟁력으로 인해 미국 AI 관련 주식 3대장이 주목받고 있습니다.' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 69, 'prompt_tokens': 1091, 'total_tokens': 1160, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'meta-llama/llama-4-maverick', 'system_fingerprint': None, 'id': 'gen-1758401367-d9Atir74U095fXnDo49O', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None} id='run--6ae6bfd5-5b0f-4b80-8ca0-dff567b55756-0' usage_metadata={'input_tokens': 1091, 'output_tokens': 69, 'total_tokens': 1160, 'input_token_details': {}, 'output_token_details': {}}
content='"AI HOT 이슈 🔥\n\n1️⃣ 인도에서 AI 사리부터 3D 피규어까지! 나노 바나나가 화제 🤯\n2️⃣ 한국 AI, 세계 3위 등신! 🇰🇷\n3️⃣ 삼성·하이닉스 반도체 경쟁력으로 미국 AI주 \'3대장\' 주목! 💸\n\n#AI뉴스 #인공지능 #테크 #나노바나나"' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 92, 'prompt_tokens': 250, 'total_tokens': 342, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'meta-llama/llama-4-maverick', 'system_fingerprint': None, 'id': 'gen-1758401368-sIKJpY1Bc7jUzI4IwpWG', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None} id='run--1ea0f9eb-21e2-4a68-b983-928127cbd3e9-0' usage_metadata={'input_tokens': 250, 'output_tokens': 92, 'total_tokens': 342, 'input_token_details': {}, 'output_token_details': {}}
================
최종 답변:
"AI HOT 이슈 🔥

1️⃣ 인도에서 AI 사리부터 3D 피규어까지! 나노 바나나가 화제 🤯
2️⃣ 한국 AI, 세계 3위 등신! 🇰🇷
3️⃣ 삼성·하이닉스 반도체 경쟁력으로 미국 AI주 '3대장' 주목! 💸

#AI뉴스 #인공지능 #테크 #나노바나나"
================

LangGraph using SubGraph LangGraph using SubGraph

This post is licensed under CC BY 4.0 by the author.