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 Project β†’ LangGraph 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

Watchers

Forks

Releases

No releases published

Packages

No packages published