LangGrpah Subgraph
Author: Sunyoung Park (architectyou)
Design:
Peer Review:
Proofread : Chaeyoon Kim
This is a part of LangChain Open Tutorial
Overview
Using SubGraphs allows you to build complex systems containing multiple components, where these components themselves can become graphs. A common use case for SubGraphs is building multi-agent systems.
The main consideration when adding SubGraphs is how the parent graph and SubGraph communicate, specifically how they pass state to each other during graph execution.
There are two scenarios:
When the parent graph and
subgraphshare schema keys. In this case, you can add nodes with the compiledsubgraph.When the parent graph and
subgraphhave different schemas. In this case, you need to add a node function that calls thesubgraph.
This is useful when the parent graph and subgraph have different state schemas and the state needs to be transformed before and after calling the subgraph.
I'll show you how to add subgraphs for each scenario below.

Table of Contents
References
Environment Setup
Setting up your environment is the first step. See the Environment Setup guide for more details.
[Note]
The langchain-opentutorial is a package of easy-to-use environment setup guidance, useful functions and utilities for tutorials.
Check out the langchain-opentutorial for more details.
You can set API keys in a .env file or set them manually.
[Note] If you’re not using the .env file, no worries! Just enter the keys directly in the cell below, and you’re good to go.
Case 1: When Sharing Schema Keys
Adding Nodes with Compiled SubGraphs
It's a common case where the parent graph and subgraph communicate through shared state keys.
For example, in multi-agent systems, agents typically communicate through a shared 'messages' key.
When a subgraph shares state keys with the parent graph, you can add it to the graph following these steps:
Define and compile the
subgraphworkflow (subgraph_builderin the example below)Pass the compiled
subgraphto the.add_nodemethod when defining the parent graph workflow
Visualize the Graph.


The final output of the parent graph includes the results of the subgraph calls.
To check the output of the subgraph, you can specify subgraphs=True when streaming.
Case 2: When Not Sharing Schema Keys
Adding Node Functions That Call Subgraphs
In more complex systems, you might need to define subgraphs with completely different schemas from the parent graph (cases where there are no shared state keys).
In such cases, you need to define a node function that calls the subgraph.
This function must transform the parent state into child state before calling the subgraph, and transform the results back into parent state before returning state updates from the node.
Below, we'll show how to modify the original example to call the subgraph within a node.
[Note]
You cannot call more than one subgraph within the same node.
Visualize the Graph

Last updated