What you'll learn: what an AI agent really is (a model, tools, a loop, a goal and a stop rule), how to decide whether you need one, and how the next fourteen lessons build one in Java that you can run, test and ship.
A page at 02:47
Your phone buzzes at 02:47: checkout is slow. You open the alert, then a metrics dashboard, then the log search, then the runbook. Four tabs, one question: what changed? Each tab you open depends on what the last one told you, so you cannot write the steps down in advance. You look, think, and look again until you can say "it was the 02:41 deploy".
That look-think-look-again habit is what an agent automates. The idea of this lesson fits in one sentence: an agent is a loop in which a model chooses the next step, and everything else is engineering around that loop. The rest of the course is that engineering, in Java.
Invented example. Parcelo is a made-up delivery company. Its checkout, payments and inventory services, its alerts and its on-call assistant, TriageDesk, are invented for this course. All numbers in the lessons are the fixed data of the labs, not real measurements.
The idea in one picture
Figure 1. An agent in one picture: a loop around a model and some tools
How to read this: follow the moving packets round the loop. The model never touches a tool; it asks, your code runs it and hands back the result, and the stop rule ends the run.
What an agent is: five parts
An agent has five parts, and each one is something you can point to in code.
- Model. A large language model (LLM) is a program that reads text and writes text. A chat model reads a list of messages and writes the next message. It is the part that decides.
- Tools. A tool is an ordinary function of yours that the model may ask for, such as "get this alert" or "search these logs". The model sees only a name, a description and the parameters.
- Loop. Your code asks the model, runs the tools it requests, gives the results back and asks again.
- Goal. The task in plain words: "Alert A-1042 is firing. What is going on?"
- Stop rule. The run ends when the model gives a final answer, or when a hard budget (a maximum number of steps) runs out.
Picture it: a new colleague on the night shift. You give them a goal ("find out why checkout is slow"), a phone, and a short list of systems they may open. They try something, read the result, try something else, and tell you when they have an answer. Where the picture stops: a colleague can refuse or ask you a question. A model only continues the text you give it, so every limit has to be written into your code.
One fact matters more than the rest. A tool call is a request, not an action. The model writes text that says "please run get_alert with alert_id A-1042". Your code decides whether that runs. The course's loop makes this visible in the type of a model's answer: it is either a final answer or a request for tools, and nothing else.
Verified: examples/backend/labs/agent-loop/src/main/java/buildingai/labs/agent/ModelReply.java
public sealed interface ModelReply {
/** The model is done and gives its answer. */
record FinalAnswer(String text) implements ModelReply {}
/** The model wants these tools run before it continues. */
record ToolRequest(List<ToolCall> calls) implements ModelReply {
public ToolRequest {
calls = List.copyOf(calls);
}
}
// ...
}
Java helps here. A sealed interface lists every shape a value can have, so the compiler can check that your loop handles both. Lesson 2 shows the loop that does.
A run is a small state machine, and it is worth seeing as one before you meet the code.
Figure 2. The states of one agent run
How to read this: every run ends in one of two boxes, Done or StepLimit. A real agent always needs both exits.
Three levels of autonomy: call, workflow, agent
"Agent" is used loosely, so here is a precise ladder. The question is who decides the next step.
- A single model call. You send one prompt and use the reply: classify a ticket, extract fields, summarise a text. There is no loop.
- A workflow. Your code fixes the order of the steps. A model does the fuzzy parts (read the email, draft the reply), and your code decides what happens next. Lesson 8 covers the common shapes.
- An agent. The model decides the next step, and when to stop. The path differs every time because it depends on what each tool returns.
Figure 3. Who picks the next step
How to read this: in the first two lanes the path is fixed, so it looks the same every time. In the bottom lane the packets go back and forth, and how often depends on the task.
Each step up the ladder buys flexibility and costs something. An agent makes several model calls instead of one, so it is slower and costs more. Its path varies, so it is harder to test. Its tools can do real things, so a wrong step can do real damage. That is why the honest question is not "can we use an agent?" but "do we need one?".
Picture it: finding your way across a city. A single call is asking a passer-by once. A workflow is a printed route you follow turn by turn. An agent is a driver with a satnav who looks at the road and re-plans after every turn. Where the picture stops: the driver sees the road. The model sees only the text you pass it, so what it "sees" is exactly what your tools return.
Do you need an agent?
Work through this chart for any task. It is deliberately blunt: most tasks leave through a "no" exit.
Figure 4. Do you need an agent?
How to read this: start at the top and follow yes or no at each diamond. Only the last rectangle is an agent.
Here are three Parcelo tasks, run through the chart.
| Task | Where it leaves the chart | Why |
|---|---|---|
| Tag a support ticket as "delivery" or "billing" | One model call | One input, one label, no tools needed |
| For each refund request: look up the order, check the policy, draft a reply | Workflow | The same three steps every time, so your code fixes the order |
| "Why is checkout slow right now?" | Agent, if read-only | Each look depends on the last, and reading cannot break anything |
The third row only reaches the agent because TriageDesk, the assistant you will build, is read-only by default: it investigates and suggests, and a person approves any change. That is the answer to the fourth diamond.
On call, 3 a.m.: Mira at Parcelo built an agent to label support tickets, with a "search the order database" tool and a step budget of eight. It worked in the demo. In production it made several model calls per ticket, and the labels were no better than one call with the ticket text and the order status pasted in. She deleted the loop and kept the prompt. Labelling got cheaper, faster and easier to test. Invented example.
The anatomy of an agent
Behind the five parts sit three things that turn a demo into a service: memory, guardrails and observability.
Figure 5. What is inside an agent
How to read this: the loop is the centre. Memory feeds it, the model advises it, guardrails stand between a request and a tool, and observability records every event without slowing the run.
- Memory is, to begin with, just the list of messages that is sent to the model on every call. Lesson 2 shows that list growing, and lesson 6 adds longer-term memory and retrieval.
- Guardrails are the checks between "the model asked" and "your code did it": validate arguments, limit permissions, ask a person for risky changes. Lesson 3 starts and lesson 11 finishes.
- Observability means recording a trace of every step, so that when the agent does something strange you can read what it did and why. Lesson 13 turns the trace into metrics and cost.
Picture it: a fuse box. It does not make the lights work. It stops one bad appliance from burning the house down. Guardrails do not make an agent smarter; they limit what a wrong decision can cost. Where the picture stops: a fuse trips on its own, but a guardrail exists only if you wrote it.
What changes when you build it in Java
Many agent tutorials are short Python scripts with loose dictionaries, which is fine for a first look. A service that wakes people at night needs more, and Java is good at exactly that.
- Typed. A tool's arguments can be a Java
recordthat your code parses and validates. A model's reply is asealedtype, so the compiler checks that you handled every case. - Testable. The model is one small interface. In a test you put a script behind it, and the same loop runs without a network or an API key.
- Concurrent. Virtual threads let a loop wait on several slow tools without tying up platform threads (lesson 10).
- Observable. You already have metrics, tracing and logging in your services. An agent is one more thing to instrument, not a new world.
- Deployable. It is a class in your application, with your security, configuration and release process.
An honest counterweight: many agent tutorials are written in Python, so expect to translate some of them. Java has solid options (Spring AI and LangChain4j, lessons 4 and 5), and a plain-Java loop is short enough that you can own it.
The testability comes from one small seam.
Verified: examples/backend/labs/agent-loop/src/main/java/buildingai/labs/agent/ChatModel.java
@FunctionalInterface
public interface ChatModel {
ModelReply reply(List<Message> conversation, List<ToolSpec> tools);
}
Figure 6. The seam that makes an agent testable
How to read this: the loop calls the interface and cannot tell what is behind it. Swap the script for an HTTP client and the loop is unchanged.
Picture it: a wall socket. The lamp does not care whether the power comes from the grid or from a test generator. ChatModel is the socket, and that is why every lab in this course runs without a key.
Meet Parcelo and TriageDesk
The running example is Parcelo, an invented delivery company, and TriageDesk, its on-call assistant. When an alert fires, TriageDesk investigates with four read-only tools (the alert text, a metric, log lines, a runbook entry) and proposes a likely cause. Two more tools can change production, a restart and a rollback, and TriageDesk may not use them without a person's approval. You will build that approval gate yourself in lesson 11, and the whole assistant in lesson 15.
Figure 7. TriageDesk, the assistant you will build
How to read this: reading is free and fast. Anything that changes production has to pass the approval gate first.
The incident the labs replay is small and fixed. At 02:41 UTC a new version of payments-gateway is deployed. From 02:44 its database connection pool is full, so checkout-api, which calls it, slows down and starts failing. The agent has to work that out from four tools, and every lab uses the same data, so every lab prints the same text.
On call, 3 a.m.: Dev at Parcelo is paged, opens four dashboards, and spends eleven minutes finding the deploy that caused it. The next night the same alert fires, and a draft of the answer is already in the channel: the deploy, the full pool, the runbook step. Dev still decides, but starts at minute one instead of minute eleven. That is the pitch for an agent like TriageDesk: not replacing Dev, but doing the looking. Invented example.
The course map
Fifteen lessons, in four groups. You can stop after the first group and own a working agent; the rest makes it safe, fast and shippable.
Figure 8. The fifteen lessons in four groups
How to read this: the packets mark the hand-offs between groups. Every group builds on the one before it, and the capstone at the bottom right uses all of them.
| # | Lesson | You will be able to |
|---|---|---|
| 1 | This lesson | Decide whether a task needs an agent |
| 2 | The agent loop in plain Java | Write the loop, with validation and a step budget |
| 3 | Designing tools an agent can use safely | Give tools typed arguments, shaped results and time limits |
| 4 | Build an agent with Spring AI | Run the same idea on Spring AI's tool calling |
| 5 | Build an agent with LangChain4j | Do it again with LangChain4j and compare |
| 6 | Memory, context and retrieval | Keep context small and fetch what is needed |
| 7 | MCP: tools as a service | Offer tools through the Model Context Protocol |
| 8 | Workflow patterns | Chain, route, parallelise and evaluate before reaching for an agent |
| 9 | Multi-agent design | Split work between an orchestrator and workers |
| 10 | Concurrency | Run tools in parallel with timeouts and cancellation |
| 11 | Guardrails | Add permissions, approval gates and prompt-injection defences |
| 12 | Testing and evals | Test and evaluate a non-deterministic agent |
| 13 | Observability and cost | Trace, measure and budget a run |
| 14 | Where to use agents | Match use cases to architectures |
| 15 | Capstone: TriageDesk | Assemble the whole assistant |
Picture it: learning to drive. First the car park: the loop and the tools, where nothing can go wrong. Then a quiet road with a proper car (the frameworks), then traffic (patterns), and only then the motorway with the lights on and a seat belt (production). Where the picture stops: here you build the car too.
How the labs work
Every lab is a small Gradle project in examples/backend/labs/. You need a JDK 25 or newer and nothing else: the Gradle wrapper is in the repository, there is no API key and no network call, and nothing is installed globally. The framework lessons (4 and 5) use a second folder, examples/spring-labs, with the same rules.
cd examples/backend
./gradlew :labs:agent-loop:test # the tests of lesson 2's lab
./gradlew -q :labs:agent-loop:run # the three runs shown in lesson 2
What "working code" means here. Each lab is compiled with --release 25 -Xlint:all -Werror (a compiler warning fails the build), has JUnit tests, and has a Demo whose printed output is saved as a golden file. Every Java listing in a lesson is a verbatim excerpt of a file that was compiled and tested, and every output block is a real run's output, pasted unchanged. A listing that was not compiled says so.
The model in every lab is a script: a list of replies that is played back in order. That keeps the output identical on every machine. Here is the first run of lesson 2's lab, so you can see what the output looks like.
Expected output, captured from a real run (examples/golden/agent-loop.txt, JDK 25, no network):
step 1 model asks for get_alert(alert_id=A-1042)
step 1 tool get_alert -> alert A-1042: checkout-api p99 latency 4200 ms (SLO 800 ms), error rate 6.1%, firing since 02:47 UTC
step 2 model asks for query_metric(metric=db_pool_in_use, service=payments-gateway)
step 2 tool query_metric -> db pool in use 50 of 50 since 02:44, 14 of 50 at 02:30
step 2 model asks for search_logs(service=payments-gateway, text=deploy)
step 2 tool search_logs -> 02:41:05 INFO deploy v412 started (previous version v411) | 02:41:40 INFO deploy v412 reported healthy
step 3 model asks for search_runbook(topic=pool)
step 3 tool search_runbook -> Connection pool exhaustion: 1) check for a deploy in the last hour, 2) if there is one, roll it back (needs on-call approval), 3) if not, restart the service (needs on-call approval).
step 4 final Likely cause: the payments-gateway deploy v412 at 02:41 exhausted its database pool (50 of 50 in use). Suggested action: roll back to v411, which needs on-call approval.
stop: FINAL_ANSWER after 4 model calls
Read it top to bottom: the model asks, a tool answers, and the next ask builds on the answer. The same story as the four tabs at 02:47, in ten lines. Step through it:
What a scripted model cannot show
Be clear about what the labs prove and what they do not.
Figure 9. What is real in a lab and what is scripted
How to read this: everything inside the large box is code you can read and run. Only the model on the left is a stand-in.
A scripted model cannot show you:
- Real decisions. A real model chooses its own steps, may skip a useful tool or repeat a useless one, and varies from run to run. The script always does what it was written to do.
- How likely a failure is. Run 3 shows that the budget stops a looping model. It does not tell you how often a real model loops.
- Wording effects. How a tool description changes what a real model picks is something only experiments with the real model can show, and lesson 12 explains how to run them.
- Latency and price. A script answers instantly and for free.
What it can show, honestly, is what your code does when the model misbehaves: when it asks for an unknown tool, sends bad arguments, repeats itself or never stops. The labs script those cases on purpose, and the tests prove your code copes.
Picture it: a flight simulator. It trains you on the cockpit and on what to do when an engine fails, and it cannot tell you what the weather will be tomorrow. The scripted model plays the same role: it trains your code, not your forecast.
On call, 3 a.m.: Sam at Parcelo showed a Friday demo in which the assistant found the cause in four neat steps. Monday's real incident went differently: the model asked for a log search with a service name that did not exist, twice. The loop returned "unknown service" as a result each time, so the run carried on and the third guess was right. Sam had only tested the happy script. Now the tests script the bad guesses too. Invented example.
Remember this:
- An agent is a model, tools, a loop, a goal and a stop rule.
- A tool call is a request your code may refuse, never an action the model performs.
- Prefer one call, then a workflow, and build an agent only when the steps cannot be known in advance.
- Every loop needs a budget, and every change to the world needs a gate.
- In the labs the model is a script. The loop, validation and tools are real.
Architect's notes
- Start at the bottom of the ladder. One call is the cheapest, fastest and easiest to test. Move up only when a real task forces you to.
- Cost grows with steps. Every step is another model call, and each call resends the conversation so far. Lesson 13 measures this.
- Autonomy needs a read-only default. Give an agent tools that look before tools that change anything, and put a person in front of every change.
- Ask how you will know it is right. If you cannot test or review the result, an agent produces confident text you cannot check.
- A framework is optional. Spring AI and LangChain4j save typing and add conventions. Knowing the plain loop first tells you what they do for you.
- Plan for the model changing. Keep the model behind one interface, as
ChatModeldoes, so that swapping or mocking it touches one class.
Common mistakes
- Building an agent for a fixed process. If the steps never change, write a workflow. Fix: run the task through the chart in Figure 4 before you write a loop.
- No step budget. The loop can run until your money does. Fix: always set a maximum number of steps and a stop reason (lesson 2).
- Giving write tools on day one. A wrong guess then changes production. Fix: start read-only and add gated changes later (lesson 11).
- Trusting the model's arguments. They are generated text, not checked input. Fix: validate before running (lessons 2 and 3).
- Reading a scripted demo as proof. A demo shows the plumbing, not the model's judgement. Fix: measure the real model on real tasks with evals (lesson 12).
- Hiding the loop behind a framework too early. When something breaks you cannot read what happened. Fix: build the plain loop first, then adopt a framework with the trace on.
Key takeaways
- An agent is a loop in which a model chooses the next step; tools, memory, guardrails and observability are the engineering around it.
- The ladder is single call, workflow, agent. Each step up costs speed, money and testability.
- A tool call is a request. Your code validates it, may refuse it, and runs it.
- Java's types, interfaces and virtual threads suit agents that must be tested, observed and deployed.
- This course runs every lab with a scripted model: reproducible, free and honest about its limits.
Practice exercises
- Starter. Run
./gradlew -q :labs:agent-loop:runfromexamples/backend. Find the line of Run 1 where the model first uses what an earlier tool returned. - Intermediate. Take five tasks from your own work and run each through Figure 4. Write down the exit it reaches and the one fact that decides it. Be ready to find that most tasks need no agent.
- Advanced. In a scratch copy of
examples/backend/labs/agent-loop/src/main/java/buildingai/labs/agent/Demo.java, add a fourth run in which the scripted model asks forsearch_runbook(topic=queue)and then answers. Predict the trace first, then run it and compare.
Related reading
- Next: The agent loop in plain Java, then Designing tools an agent can use safely.
- Later in this course: Guardrails, Testing and evals and the capstone.
- Theory behind the loop and its budgets: Agents, Tools and MCP: Architecture for AI Architects.
- Agents with Spring AI and MCP: Spring AI MCP and Agents.
- A wider view: Building Enterprise AI Agents.