Objectives
- Understand and define the
AgentStatestructure. - Create simple node functions to process and update state.
- Set up a basic LangGraph structure.
- Compile and invoke a LangGraph graph.
- Understand how data flows through a single node in LangGraph.
Project Setup
Before writing any code, let’s set up a clean, isolated project environment usinguv and install the required dependencies:
1. Initialize the Project
Create a new directory for your project and initialize it withuv:
2. Install Dependencies
Install the requiredlanggraph package using uv add:
.venv) and lock exact versions in uv.lock. Now you can create a file (e.g., main.py) and start editing!
Graph 0: Hello World
Goal
Build a simple graph that updates a state containing only one variablemsg to "Hello, World!".
Sample Input
Sample Output
Plan
- Define the state schema (
AgentState0) with a single variablemsg. - Define the node function
hello_nodethat setsmsgto"Hello, World!". - Build and compile the graph.
- Invoke the graph with an initial empty message.
Code Implementation
1. Define the State Schema
We define a state schema with a single fieldmsg of type str:
2. Define the Node Function
The node function updates themsg field in the state to "Hello, World!":
3. Build and Compile the Graph
We build a single-node graph:4. Invoke the Graph
We invoke the graph by passing an initial state with an empty string:Graph I: Hello World Graph
Goal
Build a simple graph that takes a user’s name as input and outputs a personalized greeting.Sample Input
Sample Output
Plan
- Define the
AgentStateschema containingnameandgreetvariables. - Define the node function
greeting_nodethat reads the inputnameand constructs the personalized greeting. - Build and compile the graph.
- Invoke the graph with a custom name.
Code Implementation
1. Define the State Schema
The state defines the data structure shared across the graph. We use aTypedDict for this:
2. Define the Node Function
A node is just a Python function that takes the current state as input and returns an updated dictionary of fields to merge back into the state:3. Build and Compile the Graph
We useStateGraph to define our nodes and layout:
4. Invoke the Graph
We invoke the compiled application by passing the initial state:Exercise: Personalized Compliment Agent 🏗
Goal
Create a Personalized Compliment Agent using LangGraph.Sample Input
Sample Output
Plan
- Define a state with
nameandcomplimentkeys. - Use a single node that updates
complimentusing the inputname. - Build, compile, and invoke the graph.
Solution
Solution
Practice & Exercises
To reinforce what you’ve learned in this section (defining schemas, creating nodes, compiling and invoking graphs), practice with the interactive notebook:Practice & Exercises
Practice variable state schemas, node functions, building/compiling graphs, and implementing a personalized compliment agent.💻 VS Code | 🚀 Colab | 📥 Download