Building Your First Agent

Module 5: From Blueprint to Working Agent

Picture this: three parts, one helper

create_react_agent is the 6-step architecture in one call: brain + hands + memory, then stream.

ChatGroqGPT-OSS 20B
+
@toolget_system_time
+
MemorySaverthread_id
=
create_react_agentthe loop runs for you
→
streamwatch each step

Unlike Module 3, the executor actually runs the tool and feeds the clock time back to the model.

6-Step Agent Architecture

1

Choose Foundation

Select your LLM (GPT-4, Claude, Llama) and hosting.

2

Define Tools

List all tools your agent needs (calculator, search, API, etc).

3

Build Loop

Implement observe-think-plan-act-learn cycle.

4

Add Memory

Set up short-term conversation and long-term learning.

5

Test & Iterate

Run test cases and refine behavior.

6

Deploy

Launch to production with monitoring.

Example: Simple Study Agent

Here's a simplified Python skeleton for a study agent:

class StudyAgent: def __init__(self): self.llm = GPT4() # Foundation self.tools = { 'search': search_web, 'calculator': calculate, 'notes_db': query_notes } self.memory = [] # Long-term def run(self, user_query): # 1. Observe self.memory.append(user_query) # 2. Think & Plan plan = self.llm.generate_plan(user_query, self.memory) # 3. Act results = [self.tools[t]() for t in plan['tools']] # 4. Learn self.llm.generate_response(results) agent = StudyAgent() agent.run("Explain quantum computing")

Before you click Practice — Module 5 notebook

This lab is the 6-step architecture in one helper: create_react_agent wires LLM + tools + memory. You add a time tool, then stream so you can watch each step print.

ChatGroq→@tool get_system_time→create_react_agent→stream

Ask “What time is it right now?” The agent should call get_system_time, then answer with a clock time.

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

Prebuilt ReAct agent: tool + memory + stream

Unlike Module 3, the executor runs the tool and feeds the result back. recursion_limit stops an infinite Thought→Action loop.

from langchain_groq import ChatGroq
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import MemorySaver

@tool
def get_system_time() -> str:
    """Returns the current system time."""
    import datetime
    return str(datetime.datetime.now())

llm = ChatGroq(model=MODEL, temperature=0)
tools = [get_system_time]
memory = MemorySaver()

agent_executor = create_react_agent(llm, tools, checkpointer=memory)
config = {"configurable": {"thread_id": "test_thread"}, "recursion_limit": 8}

for event in agent_executor.stream(
    {"messages": [("user", "What time is it right now?")]},
    config,
):
    if not isinstance(event, dict):
        continue
    for value in event.values():
        if not isinstance(value, dict) or "messages" not in value:
            continue
        msg = value["messages"][-1]
        text = groq_text(msg)
        if text:
            print(text)
  • Docstring on get_system_time tells the model when to call it.
  • checkpointer=memory — same thread can remember a follow-up question.
  • stream — see tool use live; invoke would wait for the full result.

Expected: A printed time string from your computer, then a short natural-language answer.

Why this cell: create_react_agent is the “complete agent” from this page’s architecture: foundation (LLM), tools, loop (ReAct), memory (checkpointer). The if isinstance guards skip empty stream chunks so GPT-OSS does not crash the print loop.

✏️ Practice: Design Your Agent

Design a customer support agent. What should it have?