1. Core Concepts Explained
This project illustrates the following agentic concepts:- State Management: Using the shared graph state to pass specialized variables (like
destination,weather_info, andbudget_estimate) between agents. - Separation of Duties: Dividing tasks so the Weather Node focuses solely on weather details, and the Budget Node handles numerical calculations.
- Persistent Session Thread: Using a checkpointer to remember what destination the user is planning to visit, allowing them to ask follow-up questions without repeating details.
2. Key APIs & Classes Used
StateGraph: The core graph builder class from LangGraph.MemorySaver: An in-memory database checkpointer used to store chat sessions.add_messages: Reducer function telling the graph to append new chat messages instead of overwriting the history.thread_id: Session key passed to the checkpointer to scope the memory to a specific conversation thread.
3. Step-by-Step Practical Implementation
Step 1: Define the Shared State Schema
The state holds the conversation history (messages), the destination city, the retrieved weather_info, and the generated budget_estimate:
Step 2: Create a Weather Search Tool
We write a mock tool using the@tool decorator that returns the current temperature and forecast for a destination:
Step 3: Define Node Functions
Nodes read from the state, call the LLM/tools, and return state key updates:- Weather Node: Analyzes the query, calls the weather tool, and updates
destinationandweather_info. - Budget Node: Calculates hotel/flight costs based on the destination and updates
budget_estimate.
Step 4: Assemble Nodes and Edges
We construct the graph, adding nodes and setting the routing path:Step 5: Compile with Memory Saver
We compile the graph with an in-memory checkpointer:4. Combined Running Code Project
Here is the complete, self-contained Python script combining all steps:5. Practice Exercises
Practice 1: Add a Packing Planner Node
Extend the stateful graph by adding a third node calledpacking_agent that runs after the budget_agent node. It should read the weather_info from the state and suggest 3 items the user should pack for their trip.
Instructions:
- Update
TravelStateto include apacking_listkey. - Define a function
packing_node(state: TravelState)that takes theweather_infoand generates a list of 3 items to pack. - Add the node to the graph and update the edges:
budget_agentpacking_agentEND.
Solution
Solution