LangGraph Agent Exercises is a hands-on playground for mastering stateful AI agents using the LangGraph framework in Python. Through sequential examples—from a simple command-line bot to sophisticated RAG-powered assistants—you’ll learn to design resilient conversation flows, bind custom tools, and ground language models with real data.
This repository covers essential AI engineering concepts:
- Structured state management with
AiMessages,HumanMessages,ToolsMessages,SystemMessageand dynamic workflows via LangGraph'sStateGraph. - Modular tool integration, custom message routing, and prompt engineering best practices.
- Retrieval-Augmented Generation (RAG) to enhance accuracy by combining retrieval and generation.
By completing these exercises, you’ll gain practical experience in building scalable, maintainable LLM applications and understand how modern AI agents orchestrate retrieval, reasoning, and generation to deliver context-aware, factual responses.
LangChain & LangGraph
LangChain lets you wire together prompts, embeddings, and tools to build LLM-powered apps. LangGraph adds a state-graph layer, so your agents can manage conversation flows, tool calls, and data pipelines as clear, visual workflows.
Retrieval-Augmented Generation (RAG)
RAG supercharges your AI’s knowledge by combining retrieval of real documents with the power of generative models. Imagine your agent has a library of PDFs and articles:
-
Query Understanding: When you ask a question, the agent turns your words into a numerical vector (embedding).
-
Smart Search: It then “zooms in” on the most relevant passages in its document store, pulling out the top 3–5 snippets.
-
Context Assembly: Those snippets get stitched into your prompt, so the AI has actual facts right in front of it.
-
Knowledgeable Answer: Finally, the LLM writes a response informed by those precise excerpts.
RAG gives you both accuracy (factual grounding) and creativity (natural-language answers), making it perfect for anything from customer support to research assistants.
-
Install SDKs:
pip install openai langchain langchain_core langchain_openai
-
API Key:
-
Create an
.envfile at project root with:OPENAI_API_KEY=sk-...
-
Load keys in Python:
from dotenv import load_dotenv load_dotenv()
-
-
Instantiate Client:
from langchain_openai import ChatOpenAI client = ChatOpenAI( model='gpt-4.1-nano', temperature=0.0, )
-
Send Messages:
from langchain_core.messages import SystemMessage, HumanMessage msgs = [SystemMessage(content='You are an expert helper'), HumanMessage(content='Hello!')] reply = client.invoke(input=msgs)
AgentExercise.ipynb– Jupyter notebook with all five agent exercisesrequirements.txt– Python dependencies.vscode/– VS Code settings and launch configurations
- Python 3.10+ (tested on 3.13.2)
- Virtual environment tool (venv, conda, etc.)
# Create & activate a virtual environment
python -m venv .venv
# macOS/Linux
source .venv/bin/activate
# Windows
.venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt- Open
AgentExercise.ipynbin VS Code or Jupyter. - Execute cells in order.
- View graph diagrams inline via
display(Image(app.get_graph().draw_mermaid_png())).
- State:
{ name: str } - Node:
compliment_node - Output:
"Hi {name}, you're doing an amazing job learning LangGraph!"
- State:
{ name: str, values: list[int], operation: "+"|"*" } - Node:
process_values - Performs addition or multiplication on
values.
- State:
{ name: str, age: int, skills: list[str], result: str } - Three nodes: greeting → age description → skill listing.
- State:
{ number1, number2, number3, number4: int; operation1, operation2: "+"|"-"; result: str } - Two conditional routers apply
+or-twice and combine results.
- State:
{ player_name, guesses: list[int], attempts, lower_bound, upper_bound, target_number, hints } - Looping graph: guess → hint → continue/exit until correct or max 7 attempts.
- You can extract each graph into standalone Python modules under
src/and add unit tests viapytestorunittest. - Extend state schemas by defining new
TypedDictentries.
A foundational example (Agent I) showing how to integrate LangChain’s ChatOpenAI model with a graph-based workflow. It:
- Defines an
AgentStateusing a list ofHumanMessageobjects. - Initializes a GPT-4.1 nano model for language generation.
- Builds and compiles a
StateGraphto manage message processing. - Demonstrates modular design and command-line interaction.
Agent II: a full-featured chatbot with conversational memory. It:
- Uses
TypedDictfor structured state (HumanMessage/AIMessage). - Maintains entire history and routes messages via
StateGraph. - Loads API credentials from
.envand logs conversation to a file. - Provides an interactive loop for context-aware AI responses.
Agent III: a ReAct (Reasoning + Acting) agent. It:
- Shows how to create and bind custom tools (
@toolfunctions). - Constructs a ReAct graph to interleave reasoning and external tool calls.
- Routes
ToolMessageandSystemMessagethroughStateGraph. - Handles dynamic message updates and error-resilient tool integration.
Agent IV: Brainstormer agent for idea generation. It:
- Generates creative prompts and appends ideas to the session state.
- Persists brainstorming output to an external file.
- Integrates with LangChain tools and a graph-based session flow.
- Illustrates functional patterns in state management.
Agent V: Retrieval-Augmented Generation (RAG) agent. It:
- Loads documents (e.g., PDF) and splits text for indexing.
- Uses
OpenAIEmbeddingsand a Chroma vector store for similarity search. - Enhances model context with retrieved content before generation.
- Manages retrieval + generation loops via
StateGraph.
Please follow our coding style guidelines and PR description template.
Licensed under the terms of the MIT License.