13. How to add and use subgraphs

SubGraph allows you to build complex systems that contain multiple components, and these components themselves can be graphs. A common use example of SubGraph is building a multi-agent system.

When adding SubGraph, the main consideration is how the parent graph and SubGraph communicate, i.e. how they pass the state (State) to each other during graph execution.

There are two scenarios:

  • Top graph and subgraph Share schema keys If you do. In this case Add nodes to compiled subgraphs can do

  • Top graph and subgraph Different schemas If you have. In this case Add node function to call subgraph Should do.

This is useful when the parent graph and subgraph have different state schemas and need to convert states before and after calling the subgraph.

Below we will show you how to add a subgraph for each scenario.

Preferences

Copy

# Configuration file for managing API keys as environment variables
from dotenv import load_dotenv

# Load API key information
load_dotenv()

Copy

 True 

Copy

# Set up LangSmith tracking. https://smith.langchain.com
# !pip install -qU langchain-teddynote
from langchain_teddynote import logging

# Enter a project name.
logging.langsmith("CH17-LangGraph-Modules")

Copy

Case 1: If you share a schema key

  • Add nodes with compiled SubGraph

This is a common case when parent graphs and subgraphs communicate through the State Key.

For example, Multi agent system In agents are mainly shared messages Communicate via key.

If the subgraph shares the status key with the parent graph, you can add it to the graph by following the steps:

  1. Define the subgraph workflow (of example below subgraph_builder ) Compilation

  2. When defining the parent graph walkflow .add_node Passing the subgraph compiled in the method

So, let's look at the simple example below.

Copy

Visualize the graph.

Copy

Copy

Copy

Copy

Copy

The final output of the parent graph contains the results of the subgraph call.

At this time, when streaming to check the output of the subgraph subgraphs=True Specify.

Copy

Copy

Case 2: If you do not share the schema key

  • Add node function to call subgraph

For more complex systems, you may need to define a subgraph with a schema that is completely different from the parent graph (if there is no shared state key).

If this is the case, Node function to call subgraph You need to define.

This function needs to convert the parent state to the child state before calling the subgraph, and the result back to the parent state before returning the status update from the node.

Below shows how to modify the original example to call a subgraph inside the node. Reference

  • Two or more within the same node subgraph Number of calls There is no .

Copy

Visualize the graph.

Copy

Copy

Copy

Last updated