How Agents Think

Module 2: The Agent Loop and Architecture

Picture this: the thinking loop

Every turn is the same six moves. ReAct is this loop written as Thought → Action → Observation.

1 Observeread the question
→
2 Thinkwhat is missing?
→
3 Planpick a next step
→
4 Actcall a tool or reply
→
5 See resultobservation
→
6 Learnupdate the plan

The notebook forces this shape with a PromptTemplate. There is no real Search tool yet — the model only writes the words.

The Agent Loop

📥
Observe
🧠
Think
📋
Plan
⚙️
Act
👀
Result
📚
Learn
∞

The Agent Loop is a continuous cycle: Agents don't respond instantly like chatbots. Instead, they follow a structured loop where they observe the current situation, think about what to do, plan the steps, execute actions, observe the results, and learn for next time. This loop repeats until the goal is achieved.

Anatomy of an AI Agent

🧠

Brain (LLM)

The reasoning engine. Uses language models to think, plan, and decide what actions to take.

👁️

Perception

Observes the environment. Reads user queries, sensor data, API responses, and file contents.

🛠️

Tools

The hands. Calculators, search engines, APIs, databases, file systems that agents use to act.

💾

Memory

Short-term (conversation) and long-term (persistent database) memory for learning from history.

🔄

Control Loop

The process that orchestrates observation, thinking, planning, acting, and learning steps.

The Agent Thinking Process

1

Observe (Perception)

Agent receives input: "What's 25 × 8 + 100?"

input = "Calculate: 25 × 8 + 100"
2

Think (Analysis)

Agent analyzes: "I need to use math. This requires multiplication first (25×8=200), then addition."

reasoning = "Use calculator tool for 25*8, then add 100"
3

Plan (Strategy)

Agent decides: "I'll call the calculator tool twice: first multiply, then add."

plan = [multiply(25, 8), add(result, 100)]
4

Act (Execution)

Agent executes the plan by invoking tools in sequence.

calc.multiply(25, 8) → 200
calc.add(200, 100) → 300
5

Observe Result (Feedback)

Agent checks if the result makes sense and if the goal is achieved.

result = 300 ✓ Goal achieved
6

Learn (Memory Update)

Agent stores: "For this type of problem, use calculator. Order of operations matters."

memory.add("Math problems", {strategy: "calculator", priority: "multiplication first"})

Before you click Practice — Module 2 notebook

The Agent Loop you just saw (observe → think → act) is written as a ReAct prompt. The model is not calling a real search tool yet — it is learning the shape of Thought / Action / Observation / Final Answer.

Install→API key→ChatGroq→PromptTemplate | llm

Run install → key → create llm → ReAct chain. Read the printed Thought lines; that is the “thinking” this module is about.

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

Create the LLM (brain only)

Same ChatGroq as Module 1. You will pipe a prompt template into this object.

from langchain_groq import ChatGroq
from langchain_core.prompts import PromptTemplate

llm = ChatGroq(model=MODEL, temperature=0)
print("Model ready:", MODEL)

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

Why this cell: Keeping the LLM in its own cell means if the next cell fails, you do not re-install packages. temperature=0 makes the ReAct format more consistent.
Practice task 4

ReAct prompt chain: Thought → Action → Final Answer

The template is a script the model must follow. {tools}, {tool_names}, and {input} are filled when you call chain.invoke(...). The | operator connects prompt → LLM.

react_prompt = PromptTemplate.from_template("""
Answer the following question as best you can. You have access to the following tools:
{tools}
Use the following format:
Question: ...
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
Thought: I now know the final answer
Final Answer: ...
Question: {input}
Thought:""")

chain = react_prompt | llm
response = chain.invoke({
    "tools": "Search: useful for current events",
    "tool_names": "Search",
    "input": "Who is the current CEO of Microsoft?"
})
print(groq_text(response) or response)
  • PromptTemplate.from_template — reusable prompt with holes to fill.
  • chain = react_prompt | llm — LangChain LCEL: fill prompt, then call the model.
  • Look for Thought: in the output — that is the agent “thinking out loud.”

Expected: Printed text with Thought / Action / Final Answer (CEO of Microsoft).

Why this cell: This is prompted ReAct, not a real agent loop. There is no Python function named Search. The model writes “Action: Search” as text. Module 3 binds real tools; Module 5 runs the actual ReAct executor.

✏️ Practice: Identify the Agent Loop Step

Scenario 1: An agent reads the user query "Book a flight from NYC to LA on Friday" and decides to search available flights. Which step is this?
Scenario 2: After booking the flight, the agent saves "User prefers morning flights" to its database. Which step is this?
Scenario 3: The agent receives "What's the best restaurant in Boston?" and breaks it down into steps: search for restaurants, check ratings, summarize recommendations. Which step is this?