Agents

An agent is an LLM-driven software loop that plans, acts with tools, observes results, updates memory, and decides what to do next.

The Big Question

Memory gave the application persistent state. Function calling gave it access to external tools. But both are still ingredients. The next question is how to combine them into a loop that can pursue a goal over multiple steps.

What if one tool call is not enough?

Consider: Find the cheapest flight to Tokyo next Friday, check whether I am free on my calendar, book it if it is under $900, then email me the itinerary.

Now the model must break the problem into steps, remember previous results, decide which tool to call next, recover if a step fails, ask for approval before booking, and know when to stop. That is the motivation for agents.

Core Intuition

Function calling is like hiring a specialist. An agent is like hiring a project manager. The manager does not personally fly the plane, query the airline database, or send mail from scratch. The manager repeatedly asks: what should happen next?

That recursive decision-making is the essence of an agent. It is not usually a new kind of neural network. Most LLM agents today are:

LLM
+ loop
+ memory
+ tools
+ controller

The novelty comes from the software architecture around the model. The model performs inference repeatedly while the surrounding system tracks state, executes tools, and decides whether the objective is complete.

Interactive Demo

Agent loop lab

Goal

Find the cheapest flight from Vancouver to Tokyo next Friday, check my calendar, consider weather, and ask before booking if it is under $900.

Loop trace

Think
Break the travel goal into subtasks
Actsearch_flights
Search flights
Observe
Flight result received
Actcalendar
Check calendar
Observe
Calendar is clear
Actweather
Check Tokyo weather
Observe
Weather result received
Think
Decide whether to book
Done
Final response
Current iteration
Think

Break the travel goal into subtasks

Need flights, calendar availability, weather, hotel options, price check, and confirmation.

Status
8 planned steps remain

Agent memory

  • Goal: plan Japan trip under $900 flight budget.

What to notice

  • The agent repeatedly chooses what to do next.
  • Observations change later actions.
  • Memory prevents repeated work and lost context.
  • Stopping rules prevent runaway loops and costs.

Step through the loop. Notice how each observation changes the next action, and how memory and stopping rules prevent the system from losing track or running forever.

The Agent Loop

The canonical loop is:

Goal
Think
Act
Observe
Think
Act
Observe
Done

A compact algorithm is:

while not finished:
    thought = think(goal, memory)
    action = choose_action(thought, available_tools)
    observation = execute(action)
    memory = update(memory, action, observation)
    finished = check_stopping_condition(goal, memory)

This is fundamentally different from one-shot prompting. A one-shot prompt produces one answer. An agent repeatedly uses the answer to decide what to do next.

State, Action, Observation

We can describe an agent loop with a simple state transition:

StπAtenvironmentOtupdateSt+1S_t \xrightarrow{\pi} A_t \xrightarrow{\text{environment}} O_t \xrightarrow{\text{update}} S_{t+1}

StS_t is the current state: goal, memory, tools, observations, constraints, and current plan. π\pi is a policy that chooses an action AtA_t. The environment returns an observation OtO_t, and the controller updates state.

Reinforcement learning studies how to learn policies. Most LLM agents today do not learn during deployment. They approximate a policy by running inference repeatedly inside a software loop.

Planning And Reacting

Some agents are mostly reactive: observe, choose the next useful action, observe again. This works when the task is short or the next action is obvious.

More complex tasks benefit from planning:

Goal
Plan
Subtasks
Execute
Revise

For a Japan holiday planner, a first plan might be: check dates, search flights, check weather, find hotel options, compare budget, ask for booking approval, send itinerary. The plan is useful, but it must remain revisable. If flight search fails or prices are too high, the agent should change strategy rather than blindly continue.

Memory

Agents need memory because later actions depend on earlier observations. Without memory, an agent may repeat tool calls, forget constraints, or contradict itself.

Memory typeMeaningExample
Conversation memoryThe visible dialogue so farUser constraints, confirmations, and corrections
ScratchpadTemporary working statePlan, intermediate calculations, unresolved subtasks
Tool observationsOutputs returned by toolsFlight prices, calendar availability, weather
Retrieved documentsContext from RAGTravel policy, booking rules, visa notes
Long-term memoryPersistent external storageUser preferences, past trips, saved addresses

Short-term memory often lives in the context window: conversation history, tool outputs, plans, and intermediate state. Long-term memory usually lives outside the model in vector databases, SQL databases, files, knowledge graphs, or user profile stores. Agents often combine memory with RAG.

Tool Orchestration

Agents generalize function calling by coordinating multiple calls over time.

PatternMeaningTravel example
SequentialCall tools one after anotherSearch flights, then check calendar, then draft email
ParallelCall independent tools togetherCheck weather and hotel availability at the same time
ConditionalChoose the next step from an observationIf weather is rainy, suggest indoor activities
LoopingRepeat until a condition is metKeep searching flights until one is under budget or options run out

Branching is especially important. If the weather is good, suggest an outdoor activity. If it is rainy, suggest a museum. If the flight is over budget, search nearby dates. Agent behavior depends on observations.

Stopping Conditions And Costs

Termination is a critical design problem. An agent should stop when the goal is achieved, when it needs human approval, when maximum iterations are reached, when a timeout occurs, or when a cost limit is hit.

Agents consume tokens, latency, API calls, and money. A loop of ten model calls and five API calls may be far more expensive than one well-structured prompt. Autonomy is useful only when the loop creates enough value to justify the cost.

For actions with real consequences, stopping should include human confirmation: purchases, bookings, emails, deletes, payments, and permission changes should not be hidden inside an autonomous loop.

Implementation

Small Agent Loop

def run_agent(goal, tools, max_steps=8):
    memory = []

    for step in range(max_steps):
        action = choose_next_action(goal=goal, memory=memory, tools=tools)

        if action["type"] == "final":
            return action["message"]

        if action["type"] == "needs_approval":
            return ask_user_for_confirmation(action["message"])

        observation = execute_tool(action["tool"], action["arguments"])
        memory.append({
            "action": action,
            "observation": observation,
        })

    return "Stopped because the agent reached the iteration limit."

In a real LLM agent, choose_next_action is often a model call using the goal, current memory, tool descriptions, policies, and stopping rules.

Travel Planner Sketch

goal = "Plan a Japan trip under a $900 flight budget."

tools = {
    "search_flights": search_flights,
    "calendar": get_calendar_events,
    "weather": get_weather,
    "hotels": search_hotels,
    "email": draft_email,
}

state = {
    "goal": goal,
    "budget": 900,
    "memory": [],
    "needs_confirmation": ["book_flight", "send_email"],
}

final_answer = run_agent(goal=goal, tools=tools, max_steps=10)

Evaluation

Agents should be evaluated as systems, not as single responses.

Success rateDid the agent complete the task?
Tool accuracyDid it choose the right tools with valid arguments?
Average iterationsHow many loop steps did completion require?
LatencyHow long did the user wait?
CostHow many model calls, tokens, and API calls were used?
Failure recoveryDid it adapt when a tool failed?
Human satisfactionWas the final outcome actually useful?

A beautiful final answer is not enough if the agent called the wrong tools, spent too much money, ignored a failure, or took an unsafe action along the way.

Failure Modes And Security

Agent failures include infinite loops, repeated tool use, hallucinated plans, context overflow, tool misuse, wrong stopping, planning collapse, and failure to recover after an observation contradicts the plan.

Security matters because agents can chain actions. Use permission boundaries, tool allowlists, rate limits, secret isolation, prompt-injection defenses, audit logs, and user confirmation before purchases, bookings, deletes, emails, or payments.

Tool outputs should be treated as data, not instructions. A retrieved page or API response should not be allowed to override system rules or grant itself new permissions.

Comparison

CapabilityPromptRAGFunction CallAgent
Uses toolsNoOptionalYesYes
Multiple tool callsNoNoLimitedYes
PlanningNoNoNoYes
MemoryContextContextContextExtended
Reacts to outcomesNoNoLimitedYes

A useful mental model is: prompting shapes one response, RAG supplies evidence, function calling executes one step, and agents coordinate multiple steps over time.

Interview Discussion

What is an AI agent?

An agent is a system that repeatedly uses a model to choose actions, execute tools, observe results, update memory, and continue until a stopping condition is met.

How are agents related to function calling?

Function calling executes one structured action. Agents generalize this into a loop over multiple actions and observations.

Do LLM agents learn during deployment?

Usually no. They run inference repeatedly and store state in memory; the model weights usually remain fixed.

Why are stopping conditions important?

They prevent runaway loops, excessive cost, unsafe actions, and tasks that never reach completion.

What makes agent evaluation harder than chatbot evaluation?

You must evaluate the whole trajectory: tool choices, observations, recovery, cost, safety, and final result.

Active Recall

1. Why is one function call insufficient for many real tasks?

2. What are the stages of the Think-Act-Observe loop?

3. What is stored in agent memory?

4. How does an agent differ from a one-shot prompt?

5. What is the difference between planning and reacting?

6. Why do most LLM agents not count as learning systems during deployment?

7. What stopping conditions should an agent have?

8. Why should purchases and emails require human confirmation?

Common Mistakes

  • Treating agents as a fundamentally new kind of AI. Most are LLMs inside software loops with tools, memory, and controllers.
  • Giving agents too much autonomy too early. More autonomy means more failure modes and more need for guardrails.
  • Forgetting stopping conditions. Without limits, agents can loop, spend money, and repeat failed actions.
  • Confusing memory with learning. Most deployed agents do not update model weights; they store state externally or in context.
  • Measuring only the final answer. The path matters: tools, cost, latency, safety, and recovery all count.

Connection To Multi-Agent Systems

A single agent can plan, use tools, and revise its strategy. But complex workflows can also be divided across specialized roles: planner, researcher, coder, reviewer, critic, and supervisor.

That leads to multi-agent systems, where multiple model-driven components coordinate, critique, and hand off work to one another.