Graphs

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Data Structures

Before jumping into LangGraph, it’s helpful to back up and review data structures related to graphs. It puts the “Graph” of LangGraph in context.

Linked Lists

A linked list is a chain of nodes where each node holds a reference to the next node. The node itself is a container for some data, such as an integer or a string. In the image below, the circles represent nodes, and the arrows represent the links between the nodes:

E rolqan qofz

Trees

A tree is a non-linear data structure where all nodes, except the root node, have a single parent node and zero or more child nodes. You can observe this structure in the diagram below:

O qdaa

Graphs

A graph data structure is a step beyond trees. In a graph, a single node can link to any number of other nodes. The graph below shows this structure:

E ccadr

Fobo Futo Oqri

Wupe Qupa Ugti

LangGraph vs LangChain

LangGraph is a library built by LangGraph Inc. This is the same company that also built LangChain; it is another popular AI library. In LangChain, the progression of tasks is similar to the linked list data structure above. The output of one component is passed on as the input of the next component in a linear fashion.

chain = prompt_template | model | parser

Core Concepts in LangGraph

Setting Up the Development Environment

Installation is easy. Run the following pip command in the terminal:

pip install langgraph
from langgraph.graph import Graph

graph = Graph()

Nodes and Edges

A Node in LangGraph is a wrapper for a Python function. Given the function below:

def my_function(input):
  return "Input: " + input
graph.add_node("node_1", my_function)
graph.add_edge("node_1", "node_2")
from langgraph.graph import START, END

graph.add_edge(START, "node_1")
graph.add_edge("node_2", END)

Compiling and Running a Graph

Once you’ve created all the nodes of your graph and connected them with edges, you’re ready to compile the graph. The compile step validates the graph and prepares it for execution. This is how you’d do it:

compiled_graph = graph.compile()
compiled_graph.invoke("user input")
See forum comments
Download course materials from Github
Previous: Introduction Next: Graphs Demo