Skip to content

lookmohan/langGraph_joke_bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 

Repository files navigation

LangGraph Joke Bot 🎭😄

An interactive joke-telling bot built with LangGraph that demonstrates loops, conditional routing, and state management.

Perfect for Learning LangGraph | Runs on Google Colab | No API Keys Required | 100% Free


🎯 What Does This Do?

This notebook teaches you LangGraph fundamentals through a fun, interactive bot that:

  • ✅ Shows you programming jokes
  • ✅ Lets you change joke categories (neutral, chuck norris, all)
  • ✅ Keeps track of jokes told
  • ✅ Loops until you quit
  • ✅ Demonstrates conditional routing and state management

The Flow:

Menu → Fetch Joke → Show Menu → Change Category → Show Menu → Quit ✓
  ↑__________________________|        ↑__________________|
           (loop)                          (loop)

🚀 Quick Start (Google Colab)

1️⃣ Open in Colab

Click here → Open In Colab

2️⃣ Run All Cells

Press Runtime > Run all and interact with the bot!

3️⃣ Play!

[n] Next  [c] Category  [q] Quit
> n

No API keys needed! Uses the free pyjokes library.


📦 What Gets Installed

# Automatically installed in Cell 1:
!pip install langgraph pydantic pyjokes

Why these?

  • langgraph → Graph-based workflow framework
  • pydantic → Data validation and state management
  • pyjokes → Programming jokes library (no API!)

🔧 How It Works

The Graph Structure

         ┌─────────────┐
    ┌────┤  show_menu  │◄──┐
    │    └─────────────┘   │
    │                      │
    ▼                      │
┌──────┐              ┌────────┐
│fetch │              │update  │
│joke  │──────────────┤category│
└──────┘              └────────┘
    │                      │
    └──────────────────────┘
    
    ▼
┌──────────┐
│ exit_bot │──► END
└──────────┘

1. State (What the Bot Remembers)

class JokeState(BaseModel):
    jokes: List[Joke] = []          # All jokes told (accumulated)
    jokes_choice: str = "n"         # User's menu choice (n/c/q)
    category: str = "neutral"       # Current joke category
    language: str = "en"            # Language for jokes
    quit: bool = False              # Exit flag

Key Concept: The jokes list uses a reducer that appends new jokes instead of replacing them!

2. Nodes (The Workers)

🟪 show_menu

  • Shows options: [n] Next, [c] Category, [q] Quit
  • Gets user input
  • Routes to appropriate node

🟩 fetch_joke

  • Gets a joke from pyjokes library
  • Displays it with formatting
  • Loops back to menu

🟦 update_category

  • Shows category options (neutral, chuck, all)
  • Updates the category
  • Loops back to menu

⛔ exit_bot

  • Shows goodbye message
  • Shows total jokes told
  • Ends the graph

3. Routing Logic

def route_choice(state: JokeState) -> str:
    if state.jokes_choice == "n":
        return "fetch_joke"      # Tell another joke
    elif state.jokes_choice == "c":
        return "update_category"  # Change category
    elif state.jokes_choice == "q":
        return "exit_bot"         # Quit

💡 Example Session

🎭🎭🎭🎭🎭🎭🎭🎭🎭🎭🎭🎭🎭
  WELCOME TO JOKE BOT!
🎭🎭🎭🎭🎭🎭🎭🎭🎭🎭🎭🎭🎭

[n] Next  [c] Category  [q] Quit
> n

==================================================
😄 Joke #1 (Category: neutral)
==================================================
Why do programmers prefer dark mode? 
Because light attracts bugs.
==================================================

[n] Next  [c] Category  [q] Quit
> c
Select category [0=neutral, 1=chuck, 2=all]: 1

[n] Next  [c] Category  [q] Quit
> n

==================================================
😄 Joke #2 (Category: chuck)
==================================================
Chuck Norris can write infinite recursion functions 
and have them return.
==================================================

[n] Next  [c] Category  [q] Quit
> q

==================================================
👋 Thanks for using Joke Bot!
📊 You enjoyed 2 jokes today!
==================================================

🎨 Customize It

Add More Categories

# In update_category function:
categories = ["neutral", "chuck", "all", "programming", "dad"]

Change Language

# In JokeState:
language: str = "de"  # German jokes!

Track More Stats

class JokeState(BaseModel):
    # ... existing fields ...
    favorite_jokes: List[Joke] = []
    ratings: List[int] = []

Add a "Rate Joke" Feature

def rate_joke(state: JokeState) -> dict:
    rating = int(input("Rate this joke (1-5): "))
    return {"ratings": [rating]}

🧠 LangGraph Concepts Demonstrated

1. State Management

# State flows through all nodes
jokes: Annotated[List[Joke], add] = []  # Accumulates
category: str = "neutral"               # Overwrites

2. Conditional Edges

workflow.add_conditional_edges(
    "show_menu",     # From this node
    route_choice,    # Use this function to decide
    {                # Map to these nodes
        "fetch_joke": "fetch_joke",
        "update_category": "update_category",
        "exit_bot": "exit_bot"
    }
)

3. Loops

# These edges create loops
workflow.add_edge("fetch_joke", "show_menu")      # Loop back
workflow.add_edge("update_category", "show_menu") # Loop back

4. Graceful Exit

workflow.add_edge("exit_bot", END)  # Special END node

📚 The 5-Step LangGraph Pattern

Every LangGraph system follows this pattern:

  1. Define the State → What to remember
  2. Write Node Functions → What each step does
  3. Create Graph Builder → Initialize the graph
  4. Add Nodes and Edges → Connect everything
  5. Compile and Run → Execute the workflow

This project demonstrates all 5 steps clearly!


🎓 Learning Path

Start Here (This Project) → Learn basics:

  • State management
  • Nodes and edges
  • Conditional routing
  • Loops

Next ProjectLangGraph Research Assistant

  • Web search integration
  • Iteration limits
  • LLM integration
  • Complex workflows

🛠️ Troubleshooting

Error: "Invalid choice"

  • Make sure you type exactly n, c, or q
  • No spaces or capital letters

Jokes not showing up

  • The pyjokes library has limited jokes
  • Try changing categories

Graph runs forever

  • Check the recursion_limit in the config
  • Default is 100 iterations (plenty for this bot)

🔄 How This Differs from Linear Chains

Traditional Chain This Graph
A → B → C → Done Menu → Action → Menu (loops)
No user interaction Interactive at each step
Fixed path Dynamic routing based on input
No memory of previous steps Tracks all jokes told

💪 Challenge Yourself

Try these modifications:

  1. Easy: Add a "Random" category option
  2. Medium: Add a "Favorites" feature to save best jokes
  3. Hard: Add joke ratings and show statistics at the end
  4. Expert: Connect to an LLM to generate custom jokes

📊 Real-World Applications

This pattern is useful for:

  1. Customer Support Bots - Route to different departments
  2. Interactive Tutorials - Let users choose their path
  3. Game Engines - Menu systems and state machines
  4. CLI Tools - Interactive command-line apps
  5. Survey Bots - Dynamic questionnaires

📚 Learn More


🤝 Contributing

Ideas for improvements:

  • Add more joke categories
  • Create a web UI version
  • Add joke ratings
  • Export favorite jokes
  • Multi-language support

Fork and share your version!


📝 License

MIT License - Use freely in your projects!


⭐ If this helped you learn LangGraph, give it a star!

Built with ❤️ for beginners learning graph-based workflows


About

Learn LangGraph fundamentals by building an interactive bot with menus, loops, and state management. Perfect first LangGraph project.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors