Courses / Agentic AI from Scratch (Python)
Session 20 of 40
What an agent is: the reason, act, observe loop
Notes
What Is an AI Agent and How Does the Reason, Act, Observe Loop Work?
Agentic AI Foundations · Session 20 — What an agent is: the reason, act, observe loop
Before you start: what do I need before I build my first Python agent?
You need the code folder for this session open in your terminal. It holds agent_basic.py, model_prompts/agent.md and one build prompt in prompts/. This session needs no index and no data files, because the agent has no documents yet. Install the libraries with pip install langchain langchain-openai. You need the settings from session 1 (LLM_BASE_URL, LLM_API_KEY, LLM_MODEL), and the model must support tool calling. Recap of what this session assumes: a chat model takes a list of messages and returns the next message, and the copilot of sessions 15 to 19 answers policy questions from retrieved chunks. Have paper or a notes app ready for the Flashcards and the Model answer.
Summary: what is an AI agent and the ReAct loop?
A chatbot answers from what the model already knows, so when an employee asks about a live ticket it has to guess. An agent is a model that calls tools in a loop until the task is complete: at each turn it either asks for a tool or writes its final answer. The loop has three beats, reason, act and observe, and your code, not the model, runs the tool and hands the result back. An agent is the right choice when the path to an answer is open, and a fixed chain of steps is better when you already know the steps. This session runs a small agent with a calculator tool and shows how to read what it did, step by step.
Key concepts: AI agent and ReAct loop terms explained in plain English
| Term | Definition |
|---|---|
| Agent | A model that calls tools in a loop until a task is complete; each turn it asks for a tool or writes the final answer. |
| Chatbot | A model that replies from what it already knows, with no way to fetch anything new. |
| Tool | A function the model may ask your code to run, described by a name, a plain-English description and typed inputs. |
@tool |
The marker placed above a plain Python function, as in code/agent_basic.py, so that the function is offered to the agent as a tool. |
| Reason, act, observe | The agent’s cycle: work out what is needed, ask for a tool, then read the result and decide again. |
| ReAct | The research name for interleaving reasoning with actions so a model can gather information as it works. |
| Observation | The result a tool returns, which is added to the conversation for the model to read. |
create_agent |
The LangChain function that builds the agent loop from a model, a list of tools and a system prompt. |
| Message list | The conversation history an agent keeps in its state; each tool request and result is added to it. |
| Fixed chain | A workflow whose steps and their order you wrote in advance. |
Explanations: how does the ReAct loop work inside an AI agent?
How is a chatbot different from an AI agent?
Failure first. An employee asks, “What is the status of ticket T-1042?” and a plain chatbot replies, in an illustrative example: “Good news: ticket T-1042 has been resolved and closed.” The ticket is still open. Nothing in the chatbot can read a ticket, so the model wrote a status that sounded right. That is the same fluent-but-made-up behaviour you met in session 3.
Picture a new hire on the phones with no computer: asked about an order, they have to say something plausible. Now give them a phone and a filing cabinet. They look up the record, then answer. The first is a chatbot; the second is an agent. LangChain’s docs describe an agent as a model that keeps calling tools in a loop until the job it was given is done.
An agent is a model that calls tools in a loop until the task is complete. At each turn the model either asks for a tool, with the inputs to give it, or writes its final answer. Compare the two designs:
CHATBOT AGENT
Question Question
| |
v v
[ Model ] [ Model ] <---------+
| | |
v needs a tool? -yes-> [ Tool ]
Answer (from memory) | result goes back
no to the model
v
Answer (from what it found)
The way back is the new part: a tool’s result returns to the model, which may then ask again.
What is the reason, act, observe loop (ReAct)?
Think of a chef tasting soup: taste, add salt, taste again, and serve when it is right. Or a taxi driver with a map app: look, turn, look again, stop when the address appears. Each look decides the next move. An agent works the same way and the pattern has three beats:
- Reason: the model works out what it still needs.
- Act: it asks for a tool, naming it and giving the inputs.
- Observe: your code runs the tool and the result goes into the conversation; the model reads it and reasons again.
The research paper that named the approach, ReAct, describes generating reasoning traces and task-specific actions in an interleaved manner: the reasoning helps the model plan and handle exceptions, and the actions let it reach outside sources for more information.
Notice who does what. The model does not run anything; it asks for a tool. Your code does the work, so what the model says next rests on a real result. Think of a doctor who orders a blood test, reads the result, and then decides whether another test is needed: what came back from one step decides the next. The header of code/agent_basic.py says a question costs one chat call per turn of the loop, so a long loop means more calls and, where calls are metered, more cost. That is why session 22 adds a limit.
How do you write a tool and build an agent with create_agent?
The calculator is the smallest useful tool. You write a plain Python function, mark it with @tool, and hand it to create_agent with a model and a system prompt. The model is shown three things: the name (calculate), the docstring (what it does and when to use it) and the typed input (expression: str). In LangChain the function’s docstring becomes the description by default, and type hints are required because they define the input schema.
@tool
def calculate(expression: str) -> str:
"""Work out an arithmetic sum such as "23 - 4 * 5".
Use it for any calculation with numbers."""
# only digits, spaces and + - * / . ( ) are allowed
...
return str(eval(expression))
eval runs text as Python, so the real function first refuses anything but digits, spaces and + - * / . ( ), and refuses **. Text from a model is input you do not control, like text typed by a stranger. When the check fails the tool returns the sentence Error: use only numbers and + - * / ( )., and the model can read that sentence and try again with a plain sum.
The agent is one call. It reads its system prompt from model_prompts/agent.md, which says the agent is a help desk agent, to use the calculator instead of working sums out in its head, and to say so plainly when a question is outside what its tools can do:
system_text = (Path(__file__).parent / "model_prompts"
/ "agent.md").read_text()
agent = create_agent(model, tools=[calculate],
system_prompt=system_text)
agent.invoke returns the agent’s state, and its messages field holds the whole conversation as a list of messages. Each tool request is an AI message with tool_calls, each result is a message of type tool, and the last AI message is the answer. show_steps prints them in order, so you read the loop instead of guessing at it.
What does the agent print when it runs?
Run python agent_basic.py. Ours printed:
question: My learning budget is 600 and I booked 2 courses at 175 each. How much of the budget is left?
act : calculate({'expression': '600 - 2 * 175'})
observe : 250
answer: You have 250 left from your learning budget.
question: Hello! What can you help me with?
answer: I can help you with any arithmetic calculation.
Read the first question. The model did not do the sum itself: it asked for calculate with an expression, your code ran it, and the result 250 went back to the model, which then wrote the answer. The act line is the reason and the act, the observe line is the observation, and the answer line comes after the model reads it. The second question needs no tool, so there is no act line: the model decides whether to use a tool. Ask your own with python agent_basic.py "What is 18% of 250?".
When should you use an AI agent instead of a fixed chain?
Imagine two ways to run a help desk. In one, each request follows a printed checklist: step one, step two, step three. In the other, a skilled person reads the request and decides what to do. The checklist is a fixed chain; the person is an agent. The framework’s workflow docs draw the same line: workflows have predetermined code paths and run in a set order, while agents are dynamic and define their own processes and tool use. They add that agents suit situations where the problem and its solution are unpredictable.
| Question to ask | A fixed chain of steps | An agent |
|---|---|---|
| Are the steps known in advance? | Yes: you write the order | No: the model picks the next step |
| Who decides which tool runs? | Your code | The model, from the tool descriptions |
| How predictable is a run? | The same path each time | The path can differ between runs |
| What does it cost? | A known number of model calls | A number that depends on the question |
A second way to see it: summarising a ticket and then drafting a reply is two known steps, so chain them. Answering “what is the status of my ticket and what policy applies to it?” may need a ticket lookup, a policy search, or both, so let an agent choose. Sessions 21 and 22 build that agent.
What goes wrong without tools, and what does it mean for the design?
Before the design table, three situations you will meet:
- The copilot says T-1042 is resolved when it is still open. The model had no tool to read the ticket, so it wrote a plausible status.
- The copilot gives a wrong total for a leave sum. The model did the arithmetic from memory, where a calculator tool does the sum in code.
- An agent keeps calling the same tool about a ticket that does not exist. Nothing told it to stop, so it kept going. Session 22 adds a limit.
What these mean for the design:
| What you learned | The design decision | Where it shows |
|---|---|---|
| A model on its own cannot look things up | Give it a tool for what it must not guess | calculate in agent_basic.py |
| The loop decides one step at a time | Print each step beside the answer | show_steps |
| The prompt says when to use the tool | Write that rule down for the model | model_prompts/agent.md |
| A loop with no stop can run on | Plan a limit on turns (session 22) | The agent’s settings |
Flashcards: test yourself on AI agent and ReAct loop
Say the answer aloud before revealing it. Speaking is a different skill from reading, so practise both.
1. What is an AI agent?
An agent is a model that calls tools in a loop until the task is complete. Each turn it either asks for a tool, with the inputs to give it, or writes its final answer.2. Why did a plain chatbot say a ticket was resolved when it was open?
It had no tool to read the ticket, so the model wrote a status that sounded plausible. An agent with a ticket tool can quote the record instead.3. What are the three beats of the reason, act, observe loop?
Reason: the model works out what it needs. Act: it asks for a tool with inputs. Observe: the tool's result goes back to the model, which reads it and decides again.4. Who runs the tool: the model or your code?
Your code. The model asks for a tool by name with inputs; your code runs the function and puts the result back in the conversation.5. What three things does the model see about a tool?
Its name, its docstring and its typed inputs. Those three are what it has to decide with, so the docstring should say what the tool does and when to use it.6. Why does `calculate` refuse letters?
It works the sum out with `eval`, which runs text as Python. Restricting the input to digits, spaces and `+ - * / . ( )` makes it harder for a model to run other code through it.7. How do you see what an agent did, beyond its final answer?
The `messages` field of the state `agent.invoke` returns is a list. Print each one in order: the question, each tool request, each tool result and the final answer, as `show_steps` does.8. Why was there no `act` line for "Hello! What can you help me with?"
The model decides whether to use a tool. A greeting needs no calculation, so it answered directly.9. When is a fixed chain better than an agent?
When you know the steps and their order in advance. A chain takes the same path each time and costs a known number of model calls, while an agent's path and cost vary.10. Why does a long agent loop cost more?
Each trip round the loop is another call to the model, and where calls are metered each one adds cost. That is why a limit on the number of steps matters, which session 22 adds.Model answer: how do I explain AI agents and the ReAct loop in an interview?
The core question this session answers: “A teammate asks: the copilot told an employee a ticket was resolved. What is an agent, and how would it have avoided that?”
Four beats a teammate listens for, in this order: chatbot or agent · the loop · who does what · choose with care. Skip any of these four and the answer is incomplete.
- Chatbot or agent: a chatbot answers from memory; an agent can use tools.
- The loop: reason, act, observe, and repeat until the task is complete.
- Who does what: the model asks for a tool; your code runs it and returns the result.
- Choose with care: an agent where the path is open, a fixed chain where the steps are known.
The full answer, said aloud:
(Chatbot or agent) “A chatbot answers from what it learned, so it guessed the ticket’s status. An agent can also call tools, so it can read the ticket record before it answers.
(The loop) It works in a loop: it reasons about what it needs, acts by asking for a tool, observes the result, and repeats until the task is complete.
(Who does what) The model asks for a tool with inputs. Our code runs the function and sends the result back, so the answer rests on a real record.
(Choose with care) I would use an agent for open questions like this one, and a fixed chain where the steps are known, because an agent’s path and its cost vary.“
Missing a beat is a failure state. The follow-up question lands where you went quiet: leave out the last beat and the next question is why you did not simply chain the steps. Practise until the four come out without prompting, then stop talking and let the questions come.
Why this matters: why do AI agents and the ReAct loop matter at work?
In a conversation with a teammate or manager: people ask why an assistant said something and where the answer came from. Being able to say “it called this tool and this came back” turns an opinion into evidence.
On the job: assistants that read tickets, look up orders or run calculations are agents. Reading their steps is the first thing you do when an answer is wrong.
In the rest of this course: session 21 writes tools well and gives the agent a ticket lookup and the copilot as a tool, session 22 makes tools fail safely, sessions 23 to 28 put the agent inside a graph you can see, and sessions 29 to 32 let several agents and outside tool servers work together.
After this unit: what do I do after this lesson, and what comes next?
Assignment. Run agent_basic.py, read the steps of the budget question, and label the reason, the act and the observation. The project work, changing one thing and seeing the effect, is set out in the project brief. Keep agent_basic.py: the next session builds on it.
What’s next. Session 21 is about writing tools well: a name, a description the model reads and typed inputs, and an agent with three tools, one of them a ticket lookup over SQLite and one the session-19 copilot.
Want help building this with someone?
Tell us what you are working on and we will write back about a mentor-led cohort, live sessions or 1:1 training. It is only an enquiry: you choose whether to go further.
Ask about mentor-led trainingTechEazy Consulting training material — not affiliated with or endorsed by OpenAI, Anthropic, LangChain or any other company named in this course.