LESSON 58 · AI AGENTS

What is an AI Agent?

Understand how AI agents go beyond generating text by deciding what to do, using tools, observing results, and taking actions to complete a goal.

35 min read•Intermediate•Generative AI

By the end of this lesson, you will be able to:

  • Explain what an AI agent is in practical terms.
  • Identify the core parts of an agent: model, tools, instructions, state, and feedback.
  • Understand the agent loop: decide → act → observe → continue.
  • Distinguish an agent from a normal chatbot, workflow, and RAG application.
  • Design a simple Python agent mental model with safe tool boundaries.
  • Recognize where agents are useful and where deterministic workflows are better.
1

What Is an AI Agent?

An AI agent is a software system that uses an AI model to pursue a goal by deciding which actions to take, using available tools, observing their results, and continuing until it can complete the task or needs help.

Simple definition:A chatbot mainly responds to a message. An agent can decide what action is needed and use tools to move the task forward.
GoalWhat should be achieved?
→
DecideWhat should happen next?
→
ActUse a tool
→
ObserveRead the result
→
RepeatContinue or finish
2

Agent vs Ordinary LLM Response

A language model can generate a useful answer from the prompt and context it receives. An agent adds a control loop around the model so the system can choose actions and react to their results.

LLM RESPONSEGenerate an answer

User asks a question → model generates text → response is returned.

AGENTWork toward a goal

User gives a goal → model chooses an action → tool runs → result is observed → next step is selected.

The model is still important, but the system around the model is what gives an agent its ability to act.

3

The Core Components of an Agent

Most practical agents can be understood as a combination of several components. The exact implementation varies, but the responsibilities are similar.

1 · MODEL

Reasoning engine

Interprets the goal and helps choose the next step.

2 · TOOLS

Capabilities

APIs, search, databases, calculators, or application actions.

3 · STATE

Working information

Keeps relevant inputs, tool results, and progress available.

4 · RULES

Boundaries

Defines permissions, allowed actions, and stopping conditions.

4

The Agent Loop

The most useful mental model is a loop. The agent does not necessarily know the complete sequence of actions before it starts.

1. UnderstandInterpret the goal
→
2. DecideSelect next action
→
3. ToolExecute action
→
4. ObserveRead result
→
5. DecideFinish or continue
Key idea:Agentic behavior comes from repeated model–tool–observation cycles, not simply from giving a model a longer prompt.
5

What Makes an Agent “Agentic”?

Not every application that calls an LLM is an agent. The important question is whether the system has meaningful control over the next action.

FIXED WORKFLOWPredefined path

Step 1 always leads to Step 2, then Step 3. The developer controls the sequence.

AGENTIC LOOPDynamic next step

The model can select a tool or decide that another step is necessary based on observations.

A system can also combine both: deterministic business rules can control high-risk steps while an agent handles flexible tasks.

6

Tools Give Agents Real Capabilities

Without tools, an agent is largely limited to information already available in its prompt or model. Tools let it interact with external systems.

Search

Find current information from an approved search system.

Database

Read structured records or retrieve application data.

Calculator

Perform deterministic arithmetic instead of relying on generated numbers.

Application API

Create tickets, update records, or perform another permitted action.

7

A Simple Agent Mental Model in Python

The following example does not call a real LLM. It shows the control structure an agent application typically needs.

</> Python
goal = "Find the current order status"

state = {"goal": goal, "result": None}

def choose_action(state):
    # A real agent would use an LLM or policy here.
    return "get_order_status"

def get_order_status():
    return "Order #1042 is shipped."

action = choose_action(state)

if action == "get_order_status":
    state["result"] = get_order_status()

print(state["result"])

The important part is the separation between decision and tool execution. In production, the tool layer should validate inputs and permissions before performing an action.

8

Example: Customer Support Agent

Imagine a support agent that receives: “My package has not arrived. Can you check it?” The agent may need several steps.

STEP 1

Understand

Identify that the user wants delivery information.

STEP 2

Find order

Use an order lookup tool with the customer's permitted context.

STEP 3

Check shipment

Call a shipment or carrier tool if required.

STEP 4

Respond

Explain the result and next action to the customer.

Agent advantage:The exact tool sequence can depend on what each tool returns. The system can stop early when the first result is sufficient.
9

Example: Research Agent

A research agent may receive a goal such as “Compare three cloud providers for a small startup.” It could search approved sources, collect evidence, compare criteria, and produce a report.

PLANBreak the goal into tasks

Define providers, criteria, sources, and the required output.

ACTGather and inspect

Use search or data tools, inspect results, and identify missing evidence.

This is different from asking a model to “write a comparison” from memory because the agent can perform external work before generating the final answer.

10

Agent vs Chatbot

CHATBOTConversation-first

Usually responds to the current conversation using its available context.

AGENTGoal-and-action-first

Can select tools, perform steps, observe results, and continue toward a goal.

A chatbot can contain tools and still behave agentically. The distinction is not the user interface; it is the system's ability to select and execute actions.

11

Agent vs RAG

RAG and agents solve different problems, but they can work together.

RAGRetrieve evidence

Find relevant information and place it into model context so the answer can be grounded.

AGENTChoose actions

Decide whether to retrieve, call an API, calculate something, ask a question, or finish.

Combined system:An agent can use a RAG retriever as one of its tools when it needs information from a knowledge base.
12

Agent Memory and State

Agents often need state so they can use information from earlier steps. “Memory” can mean several different things.

WORKING STATE

Current task

Tool results, intermediate data, and decisions for the current run.

CONVERSATION

Recent context

Relevant messages from the current interaction.

LONG-TERM

Stored information

User or application information deliberately persisted for future tasks.

KNOWLEDGE

External data

Documents and databases retrieved when needed rather than copied into memory.

Good agent design stores only what is useful and permitted. More memory is not automatically better.

13

Planning Does Not Always Mean a Long Plan

An agent may decide one action at a time, create a short plan, or use a structured workflow. The right strategy depends on task complexity.

SIMPLE TASKAct immediately

If the correct tool is obvious, an extra planning phase can add unnecessary latency.

COMPLEX TASKPlan and verify

Multiple dependent steps may benefit from explicit planning, checkpoints, and validation.

14

Agent Safety: Tools Need Boundaries

The most important production concern is that an agent can trigger actions. Tool access should therefore be narrower than the agent's general language ability.

Least privilege

Give each tool only the permissions it needs.

Validate inputs

Do not trust model-generated arguments without application validation.

Require approval

Use human confirmation for high-impact actions when appropriate.

Log actions

Record tool calls and outcomes so failures can be investigated.

15

When Should You Use an Agent?

GOOD FITFlexible multi-step tasks

Research, support investigation, data analysis, and tasks where the next step depends on results.

POOR FITSimple deterministic operations

A fixed workflow is often easier to test, faster, cheaper, and safer when the steps never change.

Rule of thumb:Use agentic behavior when dynamic decisions add real value. Do not add an agent simply because an LLM is already part of the application.
16

Agent Cost and Latency

Agentic systems can perform multiple model calls and tool calls. That flexibility can increase cost and response time.

MORE STEPS

More model calls

Each decision or reflection step may add tokens and latency.

MORE TOOLS

More external calls

APIs and searches can become the slowest part of a run.

MORE CONTROL

More validation

Checks and approvals add time but can reduce costly mistakes.

OPTIMIZE

Stop early

Finish as soon as the task is reliably complete.

17

A Minimal Agent Loop in Python

Here is a simplified loop that shows the essential architecture without tying the lesson to a particular agent framework.

</> Python
def agent_loop(goal, model, tools, max_steps=5):
    state = {"goal": goal, "history": []}

    for _ in range(max_steps):
        decision = model(state, tools)

        if decision["type"] == "final":
            return decision["answer"]

        if decision["type"] == "tool":
            name = decision["name"]
            arguments = decision["arguments"]

            result = tools[name](arguments)
            state["history"].append({
                "tool": name,
                "result": result,
            })

    return "The agent stopped before completing the task."

Production code should validate tool names and arguments, enforce permissions, handle failures, limit loops, and avoid exposing secrets to the model.

18

Common Agent Mistakes

Giving the agent too many tools

Large tool sets can make selection harder and increase risk.

No stopping condition

A loop without clear limits can waste time and money.

Trusting generated arguments

Every tool should validate its inputs independently.

Using agents for fixed workflows

Deterministic code is often better when the process is known in advance.

19

How to Evaluate an Agent

Evaluate both the final outcome and the path used to reach it.

OUTCOME

Task success

Did the agent actually complete the user's goal?

TOOLS

Correct actions

Did it select appropriate tools and arguments?

EFFICIENCY

Steps and cost

How many model and tool calls were required?

SAFETY

Policy compliance

Did it stay within permissions and approval rules?

Keep representative tasks as an evaluation set and compare agent versions using the same scenarios.

20

Mini Project: Design a Simple AI Agent

Design an agent for a support application that can answer account questions and check order status.

GOALResolve customer questions

Define what the agent should accomplish.

TOOLSOrder lookup + knowledge search

Define the smallest safe tool set.

BOUNDARIESRead-only first

Require approval before high-impact changes.

STOPAnswer or escalate

Stop when evidence is sufficient or a human is required.

Challenge: Draw the agent loop and list three situations where the agent should stop instead of trying another tool.

21

Quick Quiz

1. What is a core characteristic of an AI agent?

A) It only generates text   B) It can choose actions and use tools toward a goal   C) It never uses external systems

2. What usually happens after a tool call?

A) The result is observed and can influence the next step   B) The system must always stop   C) The tool becomes the model

3. What is often a better choice for a fixed, predictable process?

A) A deterministic workflow   B) An unlimited agent loop   C) More tools

4. Why should tool inputs be validated?

A) Models are databases   B) Model-generated arguments should not bypass application safety rules   C) Validation increases hallucinations

22

30-Second Recap

1An AI agent uses a model to pursue a goal through actions.
2Tools connect the agent to external capabilities.
3The agent loop is decide → act → observe → continue.
4RAG can be one tool inside an agent system.
5Use boundaries, validation, limits, and evaluation in production.
23

Key Takeaways

Remember:An AI agent is not simply a smarter chatbot. It is a system that combines an AI model with tools, state, rules, and an execution loop so it can take actions toward a goal.

Good agent engineering is about giving the model useful choices inside safe boundaries. The next lessons will break down those choices, starting with how agents differ from ordinary chatbots and how tools are defined.