Estimated time: 15 minutes

What is an Agent?

Understanding the Theoretical Foundation

📚 Core Definition from AI Theory

An AI Agent is a computational system that can perceive its environment through sensors and act upon that environment through actuators to achieve specific goals.

🎯 Key Components of Agency

👁️ Perception

The ability to observe and interpret information from the environment

In AI agents, perception includes:

  • Processing text inputs (prompts, documents)
  • Analyzing structured data (APIs, databases)
  • Understanding context and state
  • Recognizing patterns and anomalies

🧠 Reasoning

The ability to process information and make decisions

Reasoning in modern AI agents involves:

  • Planning sequences of actions
  • Evaluating multiple options
  • Predicting outcomes
  • Adapting strategies based on feedback

⚡ Action

The ability to interact with and modify the environment

Actions available to AI agents include:

  • Generating text responses
  • Calling APIs and tools
  • Modifying data or files
  • Triggering workflows

🎯 Goal-Oriented Autonomy

The ability to work independently towards objectives

Autonomous behavior includes:

  • Breaking down complex goals
  • Self-directing through tasks
  • Handling errors and obstacles
  • Optimizing for efficiency

🌟 Real-World Example

You Are an Agent!

As you interact with this lesson, you demonstrate all the properties of an agent:

💡 Key Insight

"Agency is not about consciousness or self-awareness, but about the ability to perceive, reason, and act in pursuit of goals. This definition applies equally to humans, animals, robots, and AI systems."

Components of AI Agents

Building Blocks of Intelligent Systems

🏗️ The Agent Architecture

Modern AI agents are composed of several interconnected components. Click each to explore:

🧠
Large Language Model
The reasoning engine that processes information, makes decisions, and generates responses based on the agent's objectives.
🔧
Tools & Actions
External capabilities like web search, calculations, API calls, or file operations that extend the agent's abilities.
💾
Memory System
Short-term and long-term storage that allows the agent to remember past interactions and build upon previous knowledge.

🔄 How Components Work Together

The Agent Loop

Perception Input Processing LLM Reasoning Decision Action Selection Tools Execute Actions

🎮 Interactive Exercise

Match the component to its function:

Components
🧠 LLM
🔧 Tools
💾 Memory
Functions
Stores conversation history
Executes external actions
Processes and reasons

From Chatbots to Agents

The Evolution of AI Systems

📈 The Evolution Timeline

Rule-Based If-Then Logic 1960s-1990s Chatbots Q&A Systems 2000s-2020s AI Agents Autonomous 2023-Present ELIZA, Expert Systems Siri, ChatGPT AutoGPT, LangGraph

🔄 Key Differences

💬 Traditional Chatbots

  • ❌ Single-turn conversations
  • ❌ No memory between sessions
  • ❌ Cannot use external tools
  • ❌ Reactive only
  • ❌ Fixed capabilities

🤖 AI Agents

  • ✅ Multi-step task execution
  • ✅ Persistent memory
  • ✅ Tool usage (APIs, search, etc.)
  • ✅ Proactive planning
  • ✅ Extensible capabilities

🎯 See the Difference in Action

Same request, different approaches:

User: "Book me a flight to Paris next week"

Introduction to LangGraph

Building Stateful Agent Applications

📊 What is LangGraph?

LangGraph is a framework by LangChain for building reliable, stateful agents with complex workflows. Think of it as a way to create "flow charts" for AI reasoning.

📥 Input

User Query

→
🤔 Plan

Decide Actions

→
⚡ Execute

Use Tools

→
📤 Output

Final Result

Key concepts in LangGraph:

  • Nodes: Represent different states or actions in your agent workflow
  • Edges: Define how the agent moves between states
  • State: Maintains context and data throughout the execution
  • Checkpointing: Save and restore agent state for reliability

🎯 Why LangGraph?

🔄 Cycles & Loops

Unlike simple chains, LangGraph supports loops for iterative reasoning

💾 Built-in Persistence

Automatically saves state between steps for reliability

🎮 Human-in-the-Loop

Easy to add approval steps and human oversight

🔍 Streaming & Debugging

See exactly what your agent is thinking at each step

🏗️ LangGraph Mental Model

Think of LangGraph as building a state machine:

  1. Define your State - What information needs to persist?
  2. Create Nodes - Each node is a function that modifies state
  3. Connect with Edges - Define how to move between nodes
  4. Add Conditions - Make decisions based on state
  5. Compile & Run - Execute your agent graph

Building Your First Agent

Hands-on with LangGraph

💻 Let's Build a Research Agent

We'll create an agent that can search the web and synthesize information:

Step 1: Import Dependencies
from langchain_core.messages import HumanMessage, AIMessage
from langgraph.graph import StateGraph, END
from langchain_openai import ChatOpenAI
from typing import TypedDict, List
from langchain.tools import DuckDuckGoSearchRun
Step 2: Define Agent State
class AgentState(TypedDict):
    """State that persists throughout the agent execution"""
    messages: List[BaseMessage]
    search_results: str
    final_answer: str
Step 3: Create Agent Functions
def plan_step(state: AgentState):
    """Decide if we need to search or can answer directly"""
    llm = ChatOpenAI(model="gpt-4")
    
    # Analyze the user's question
    user_question = state["messages"][-1].content
    
    planning_prompt = f"""
    Question: {user_question}
    
    Do I need to search for current information to answer this?
    Respond with 'SEARCH' or 'ANSWER'.
    """
    
    decision = llm.invoke(planning_prompt).content.strip()
    
    return {"next_action": decision}

def search_step(state: AgentState):
    """Execute web search"""
    search = DuckDuckGoSearchRun()
    query = state["messages"][-1].content
    results = search.run(query)
    
    return {"search_results": results}

def answer_step(state: AgentState):
    """Generate final answer"""
    llm = ChatOpenAI(model="gpt-4")
    
    context = state.get("search_results", "")
    question = state["messages"][-1].content
    
    prompt = f"""
    Question: {question}
    Context: {context}
    
    Provide a comprehensive answer.
    """
    
    answer = llm.invoke(prompt).content
    
    return {"final_answer": answer}
Step 4: Build the Graph
# Create the graph
workflow = StateGraph(AgentState)

# Add nodes
workflow.add_node("plan", plan_step)
workflow.add_node("search", search_step)
workflow.add_node("answer", answer_step)

# Define edges
workflow.add_edge("start", "plan")
workflow.add_conditional_edges(
    "plan",
    lambda x: x["next_action"],
    {
        "SEARCH": "search",
        "ANSWER": "answer"
    }
)
workflow.add_edge("search", "answer")
workflow.add_edge("answer", END)

# Compile the graph
app = workflow.compile()

Interactive Demo & Practice

Put It All Together

🎮 Try the Agent Yourself

Let's walk through how our research agent handles a real query:

📥 Step 1: Receive Query

"What are the latest developments in quantum computing?"

🤔 Step 2: Planning

Agent decides: Need to SEARCH for current information

🔍 Step 3: Web Search

Searching for: "latest quantum computing developments 2024"

📊 Step 4: Process Results

Found 5 relevant articles about quantum breakthroughs...

✨ Step 5: Generate Answer

Recent quantum computing developments include new error correction methods, IBM's 1000+ qubit processor, and breakthrough applications in drug discovery...

🚀 Your Next Steps

1️⃣ Start Simple

Build a basic agent with one tool (like web search or calculator)

pip install langgraph langchain-openai

2️⃣ Add Memory

Implement conversation memory to maintain context

from langchain.memory import ConversationBufferMemory

3️⃣ Expand Tools

Add more capabilities: APIs, databases, file systems

from langchain.tools import DuckDuckGoSearchRun, WikipediaQueryRun

4️⃣ Production Ready

Add error handling, logging, and monitoring

app = workflow.compile(checkpointer=SqliteSaver(".checkpoints.db"))

📚 Lesson Summary

🎯

Agents vs Chatbots

Agents are goal-oriented systems that can plan, use tools, and maintain state - going beyond simple Q&A interactions.

🏗️

Core Components

Every agent needs an LLM for reasoning, tools for actions, and memory for maintaining context across tasks.

📊

LangGraph Benefits

Provides structure for complex workflows, state management, and makes agents more reliable and debuggable.

🚀

Getting Started

Start simple with basic tools, then gradually add complexity like memory, multiple agents, and advanced planning.

⚡

Best Practices

Always validate tool outputs, implement error handling, and design with specific use cases in mind.

🔮

Future Direction

Agents are evolving towards more autonomous systems with better reasoning, planning, and real-world interaction.

🎉 Congratulations!

You now understand the fundamentals of AI Agents and LangGraph

Ready to build your own agents? Start with the code examples from this lesson!