Design Patterns

Module 7: Proven Patterns for Building Agents

Picture this: Worker + Reviewer

Two roles, one loop. The router is a fork: approved (or 3 turns) → END, else back to the worker.

START
→
Worker1-sentence draft
→
ReviewerYES or NO
→
Routerapproved or turns ≥ 3?
→
ENDor back to worker

This is the Multi-Agent row in the table: slower, but jobs are split. ReAct (Module 2/5) is one brain thinking out loud instead.

Core Agent Patterns

ReAct

Reasoning + Acting

Agent alternates between thinking and tool use.

Thought → Action → Observation
→ Thought → Action → Observation
→ Final Answer

✓ Best for: Multi-step reasoning

Tool Calling

Function Calling Pattern

LLM directly calls functions. Structured, fast.

Query → LLM Decides Tool
→ Execute Tool
→ Respond

✓ Best for: Simple, direct tasks

Multi-Agent

Delegation Pattern

Multiple specialized agents collaborate.

Manager Agent
→ Specialist 1, 2, 3
→ Synthesize

✓ Best for: Complex projects

ReAct Pattern Deep Dive

ReAct = Reasoning + Acting

The agent explains its thinking before taking action. This makes it more interpretable and reliable.

Step 1 - Thought:
"I need to search for current stock price of Tesla"
Step 2 - Action:
search_tool("Tesla stock price today")
Step 3 - Observation:
"Tesla (TSLA) is trading at $245.30"
Final Answer:
"Tesla is currently at $245.30"

Pattern Comparison

Pattern Complexity Speed Best For
Tool Calling Simple Fast Quick tasks, APIs
ReAct Medium Medium Reasoning, debugging
Multi-Agent Complex Slow Large projects, teams

Before you click Practice — Module 7 notebook

The Multi-Agent pattern on this page is a Worker + Reviewer loop. Worker writes a one-sentence draft; Reviewer says YES or NO; a router either sends work back or stops. A turn cap (3) prevents an infinite loop.

worker→reviewer→router YES/NO or 3 turns→END

Watch stdout: Worker Draft, then Reviewer (Approved=...). After at most 3 worker turns the graph hits END.

Practice task 1

Install packages into this notebook’s Python

Run the first code cell. It uses sys.executable -m pip so packages go into Kodin’s Jupyter kernel, not a random Windows pip.

# Install into THIS notebook kernel (not Windows pip).
import sys
import subprocess

print("Installing into:", sys.executable)
subprocess.check_call([
    sys.executable, "-m", "pip", "install", "-qU",
    "langgraph", "langchain-groq", "langchain-core",
])
print("Done. Run the next cells.")

Expected: Prints the kernel path, then “Done.”

Why this cell: A plain !pip install on Windows often installs into a different Python, then the next cell fails with ModuleNotFoundError: langgraph. If import still fails: Kernel → Restart Kernel, then Run All.
Practice task 2

API key + MODEL + groq_text (same as Module 1)

Every practice notebook repeats this cell. Run it before any Groq call. Key stays in os.environ["GROQ_API_KEY"] for this kernel session.

import os
MODEL = "openai/gpt-oss-20b"

def groq_text(msg) -> str:
    # GPT-OSS may return text, a list of parts, or reasoning_content
    ...

if not os.getenv("GROQ_API_KEY"):
    os.environ["GROQ_API_KEY"] = input("Enter GROQ_API_KEY: ").strip()
print("API key ready. Model:", MODEL)

Expected: “API key ready. Model: openai/gpt-oss-20b”

Why this cell: Without this cell, ChatGroq has no key. Without groq_text, later prints can look empty even when the model answered.
Practice task 3

Worker / Reviewer graph with a conditional router

State holds the task, draft, review, approved flag, and turn count. Conditional edges need a path map so LangGraph knows that the router may return either "worker" or END.

from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langchain_groq import ChatGroq

class AgentState(TypedDict):
    task: str
    draft: str
    review: str
    approved: bool
    turns: int

llm = ChatGroq(model=MODEL, temperature=0.2)

def worker(state: AgentState):
    draft = groq_text(llm.invoke(f"Write a 1-sentence draft about {state['task']}"))
    return {"draft": draft, "turns": int(state.get("turns") or 0) + 1}

def reviewer(state: AgentState):
    review = groq_text(llm.invoke(
        f"Is this draft good and exactly one sentence? Draft: {state['draft']}. Reply YES or NO."
    ))
    approved = "YES" in review.upper()
    return {"review": review, "approved": approved}

def router(state: AgentState):
    if state.get("approved") or int(state.get("turns") or 0) >= 3:
        return END
    return "worker"

graph = StateGraph(AgentState)
graph.add_node("worker", worker)
graph.add_node("reviewer", reviewer)
graph.add_edge(START, "worker")
graph.add_edge("worker", "reviewer")
graph.add_conditional_edges("reviewer", router, {"worker": "worker", END: END})

app = graph.compile()
app.invoke({"task": "AI Agents", "approved": False, "turns": 0}, {"recursion_limit": 12})
  • START → worker → reviewer → (router)
  • Approved or 3 turns → END; else back to worker.
  • recursion_limit: 12 is a safety net, not the main stop condition.

Expected: Several Worker Draft / Reviewer lines, then the cell finishes without error.

Why this cell: This is the Multi-Agent row in the comparison table: slower, but roles are split. temperature=0.2 lets the draft vary a little. The path map {'worker': 'worker', END: END} is required so routing is explicit. Without the 3-turn cap, a picky reviewer could loop forever (and hit recursion_limit).

✏️ Practice: Identify the Pattern

Scenario: You're building a customer support agent that needs to understand the problem, check knowledge base, look up customer history, and compose a response.

Which pattern is best?