What you'll learn: how an agent works line by line: why the message list is the memory, what a model's reply really is, how tools are described and validated, why an error becomes a result, and how a step budget guarantees that the loop ends.
Sixty lines that every agent is built on
Open the source of any agent framework and you will find the same few lines somewhere in the middle: ask the model, run what it asked for, give it the results, ask again. Everything else (memory stores, planners, "crews", graphs) is built around that loop. If you can read it, no framework is a black box.
This lesson walks through the whole loop in plain Java, with no framework, no network and no API key. The single idea: the loop is small, so most of the work is making each part of it safe.
NOTE
Invented example. Parcelo is a made-up delivery company. The alert, the services and every number in this lesson are the fixed data of the lab agent-loop, not real measurements. The model is a script that plays back fixed replies, so the output is the same every time.
The idea in one picture
Figure 1. The loop, with its budget gate
How to read this: follow the packet round the ring on the right. The run ends in only two ways: a final answer at the top, or the red dashed path when the budget is spent.
Messages are the memory
A chat model has no memory between calls. Each call stands alone: it reads the messages you send and writes the next one. If the model "remembers" that it already read the alert, it is because your code sent the alert text again. So the agent's memory is simply a list of messages, resent in full on every call.
publicsealedinterfaceMessage {
/** Standing instructions from the developer (the system prompt). */recordInstruction(String text)implementsMessage {}
/** What the user (or the calling system) asked for. */recordUser(String text)implementsMessage {}
/** The model's turn: either some text, or a request to run tools (or both). */recordAssistant(String text, List<ToolCall> toolCalls)implementsMessage {
public Assistant {
toolCalls = List.copyOf(toolCalls);
}
}
/** The result of one tool call, sent back so the model can see what happened. An error is a result too. */recordToolResult(String callId, String toolName, String content, boolean error)implementsMessage {}
}
Instruction is your standing rule for the model (the system prompt): "you may only read, never change anything".
User is the goal.
Assistant is the model's own turn: some text, or a request for tools.
ToolResult is what a tool returned, tied to the request by an id.
Sealed again: the compiler knows these four are all there is.
TIP
Picture it: a case file passed across a desk. The colleague on the other side forgets everything the moment you leave, so each time you return you hand over the whole file, with every earlier note and every tool result in it, and they write the next note. Where the picture stops: a real colleague would get tired of rereading; a model just gets slower and costlier as the file grows, which is why lesson 6 is about keeping it short.
You can watch the file grow. The lab's Demo wraps the model in a small lambda that records how many messages each call received.
Figure 2. The conversation list grows with every step
How to read this: each arrow is one trip round the loop. Call 1 sends the instruction and the goal. Call 2 adds the model's request and one result. Call 3 adds a request for two tools and two results. Call 4 adds one request and one result.
A reply is a final answer or a tool request
The loop needs only one thing from a model, and it is one method.
reply takes the conversation and the list of tools on offer, and returns a ModelReply: either a FinalAnswer or a ToolRequest (you saw both in lesson 1). A request holds one or more ToolCalls.
Nothing has run yet: the model only asks. The id exists because one reply may request several tools at once, and each result has to be matched to its request. In a real system a class behind ChatModel would call an HTTP API and turn its JSON into these types. In the labs a ScriptedModel hands back the next prepared reply and ignores the conversation, which is exactly what a real model would not do.
Tools are text the model reads
How does a model know it may ask for get_alert? You tell it, in words. A tool has a spec (name, description, typed parameters) and some code. The model never sees your Java method, only the spec.
publicstatic Tool getAlert() {
returnnewFunctionTool(
newToolSpec("get_alert", "Returns the text of one alert by its id.",
List.of(ToolSpec.required("alert_id", Type.STRING, "The alert id, for example A-1042"))),
args -> {
Stringid= (String) args.get("alert_id");
Stringalert= ALERTS.get(id);
if (alert == null) thrownewIllegalArgumentException("no alert with id " + id);
return"alert " + id + ": " + alert;
});
}
The spec can print what would be sent to a model. Here is the real output for this tool.
Expected output, captured from a real run (examples/golden/agent-loop.txt):
The tool the model reads (what is sent for get_alert):
{"name":"get_alert","description":"Returns the text of one alert by its id.","parameters":{"type":"object","properties":{"alert_id":{"type":"string","description":"The alert id, for example A-1042"}},"required":["alert_id"]}}
Figure 3. What the model sees of a tool
How to read this: only the top path reaches the model. The red dashed path from the code is blocked: the model cannot read, run or change your Java.
Two things to notice. The description is prompt text: "Returns the text of one alert by its id" is what the model uses to decide when to call it, and the example in the parameter ("for example A-1042") is a hint about the format. Lesson 3 turns that into design rules. And the schema is sent on every call, so every tool you add costs a little on every step.
TIP
Picture it: a restaurant menu. The guest (the model) orders from the menu, in the words printed there. The kitchen (your code) is out of sight, and a dish that is not on the menu cannot be ordered. Where the picture stops: a model may still try to order something that is not on the menu, which is why the next section exists.
Validate before you run
The model's arguments are generated text. It may leave out a required one, send a number where a string is expected, or invent an extra one. The spec doubles as a checklist, and the loop checks it before anything runs.
public Optional<String> validate(Map<String, Object> arguments) {
for (Param p : params) {
Objectvalue= arguments.get(p.name());
if (value == null) {
if (p.required()) return Optional.of("missing required argument '" + p.name() + "'");
continue;
}
if (!p.type().accepts(value)) {
return Optional.of("argument '" + p.name() + "' must be " + p.type().json + ", got " + value.getClass().getSimpleName());
}
}
for (String given : arguments.keySet().stream().sorted().toList()) {
if (params.stream().noneMatch(p -> p.name().equals(given))) {
return Optional.of("unknown argument '" + given + "'");
}
}
return Optional.empty();
}
It returns an Optional<String>: empty when the call is fine, otherwise a sentence that names the problem ("missing required argument 'alert_id'"). The sentence is written for the model, because the model is the one who will read it and try again. This check only covers shape (present, right type, no extras). Lesson 3 adds checks of meaning, such as ranges and allowed values.
TIP
Picture it: the pass in a restaurant kitchen. Before an order goes to the stove, someone checks the ticket: is there a table number, is the dish on the menu? A bad ticket goes back to the waiter with a note, not onto the grill. Where the picture stops: the waiter here is a model that can read the note and fix its own ticket.
Errors are observations, not crashes
Now the part that makes the loop robust. runTool is the only place a tool runs, and every way it can fail ends the same way: as a ToolResult the model can read.
/** Runs one requested tool. Every failure becomes a result the model can read, so the loop never crashes on a bad call. */private Message.ToolResult runTool(int step, ToolCall call, Trace trace) {
Optional<Tool> tool = tools.find(call.name());
if (tool.isEmpty()) {
return failed(step, call, "unknown tool '" + call.name() + "'. Available tools: " + String.join(", ", tools.names()), trace);
}
Optional<String> problem = tool.get().spec().validate(call.arguments());
if (problem.isPresent()) {
return failed(step, call, "invalid arguments: " + problem.get(), trace);
}
try {
Stringoutput= tool.get().execute(call.arguments());
trace.add(step, Trace.Kind.TOOL, call.name() + " -> " + output);
returnnewMessage.ToolResult(call.id(), call.name(), output, false);
} catch (Exception e) {
return failed(step, call, "the tool failed: " + e.getMessage(), trace);
}
}
privatestatic Message.ToolResult failed(int step, ToolCall call, String message, Trace trace) {
trace.add(step, Trace.Kind.TOOL_ERROR, call.name() + " -> " + message);
returnnewMessage.ToolResult(call.id(), call.name(), message, true);
}
Read it in four steps: unknown tool, invalid arguments, run it, or the tool threw. The first three failures each produce a sentence; a successful run produces error = false. The catch turns any exception into "the tool failed: ..." so that a bug in a tool, or a bad id, cannot take the whole agent down.
Figure 4. What happens to one requested tool call
flowchart TD
accTitle: What happens to one requested tool call
accDescr: The model asks for a tool. If the tool is not registered the loop returns an error result that lists the available tools. If the arguments do not match the spec it returns an error result that says what is wrong. Otherwise it runs the tool. If the tool throws, it returns an error result with the message. Otherwise it returns the output. Every result is added to the conversation for the next model call.
Start(["Model asks for a tool"])
Q1{"Is the tool registered?"}
Q2{"Do the arguments match the spec?"}
Run["Run the tool"]
Q3{"Did it throw?"}
E1["Error result: unknown tool, lists the available tools"]
E2["Error result: invalid arguments, says what is wrong"]
E3["Error result: the tool failed, with the message"]
Ok["Result with the tool output"]
Back["Result added to the conversation"]
Start --> Q1
Q1 -->|"no"| E1
Q1 -->|"yes"| Q2
Q2 -->|"no"| E2
Q2 -->|"yes"| Run
Run --> Q3
Q3 -->|"yes"| E3
Q3 -->|"no"| Ok
E1 --> Back
E2 --> Back
E3 --> Back
Ok --> Back
How to read this: there are four exits and they all lead to the same place. The model sees what went wrong on its next call, and a model can often fix a call it is told is wrong.
TIP
Picture it: a satnav. Take a wrong turn and it does not shut down; it says "recalculating" and offers a new route. An error result is the loop saying "that did not work, here is why, try again". Where the picture stops: a satnav always finds a route. A model may keep failing, which is the reason for the budget in the next section.
NOTE
On call, 3 a.m.: Raj at Parcelo wrote his first loop with a plain method call: tools.get(name).run(args). One night the model asked for a tool called fetch_dashboard, which did not exist. The map lookup returned null, the loop threw a null pointer exception, and the whole investigation died with the alert still firing. He rewrote the lookup so that an unknown name returns "unknown tool 'fetch_dashboard'. Available tools: ..." as a result. The next run recovered by itself. Invented example.
The loop itself
Everything above comes together in Agent.run. It is short enough to read in one go.
public AgentResult run(String goal) {
List<Message> conversation = newArrayList<>();
conversation.add(newMessage.Instruction(config.systemPrompt()));
conversation.add(newMessage.User(goal));
Tracetrace=newTrace();
for (intstep=1; step <= config.maxSteps(); step++) {
ModelReplyreply= model.reply(List.copyOf(conversation), tools.specs());
switch (reply) {
case ModelReply.FinalAnswer done -> {
conversation.add(newMessage.Assistant(done.text(), List.of()));
trace.add(step, Trace.Kind.FINAL, done.text());
returnnewAgentResult(AgentResult.Stop.FINAL_ANSWER, done.text(), step, conversation, trace);
}
case ModelReply.ToolRequest request -> {
conversation.add(newMessage.Assistant("", request.calls()));
for (ToolCall call : request.calls()) {
trace.add(step, Trace.Kind.MODEL, "asks for " + call.describe());
conversation.add(runTool(step, call, trace));
}
}
}
}
trace.add(config.maxSteps(), Trace.Kind.STOP, "step limit of " + config.maxSteps() + " reached without a final answer");
returnnewAgentResult(AgentResult.Stop.STEP_LIMIT, "", config.maxSteps(), conversation, trace);
}
Line by line:
The first lines create the conversation with the instruction and the goal. That list is the memory.
The for loop is the budget. It runs at most config.maxSteps() times, so there is no way to loop forever.
model.reply(List.copyOf(conversation), ...) hands the model an unmodifiable copy, so a model implementation cannot change the agent's memory behind its back.
switch (reply) has exactly two cases, and the compiler insists on both. A FinalAnswer is added to the conversation and returned. A ToolRequest is added as an Assistant message, then each call is traced, run and its result appended.
After the loop, a run that never answered is closed with a stop reason of STEP_LIMIT and an empty answer.
The settings are one more small record, with the only rule that matters here.
publicrecordAgentConfig(String systemPrompt, int maxSteps) {
public AgentConfig {
if (maxSteps < 1) thrownewIllegalArgumentException("maxSteps must be at least 1");
}
The same exchange as a sequence, for one round trip:
Figure 5. One tool-call exchange
sequenceDiagram
accTitle: One tool-call exchange
accDescr: The agent loop sends the conversation and the tool specs to the model. The model replies with a tool request. The loop validates the arguments, runs the tool and gets its output. The loop sends the conversation again, now including the tool result, and the model replies with a final answer or the next tool request.
autonumber
participant A as Agent loop
participant M as Model
participant T as Tool
A->>M: conversation (2 messages) and the tool specs
M-->>A: tool request, id c1, get_alert with alert_id A-1042
Note over A: validate the arguments against the spec
A->>T: execute with alert_id A-1042
T-->>A: alert text
A->>M: conversation (4 messages), now with the result for c1
M-->>A: final answer, or the next tool request
How to read this: the model talks only to the loop, never to the tool. The second request is bigger than the first because the list grew by the model's request and the tool's result.
TIP
Picture it: a taxi with a spending limit. The driver may keep taking turns while the meter is below the cap, and the ride ends at the cap whether or not you have arrived. maxSteps is the cap. A real driver would tell you when the money was nearly gone; this loop just stops, which is why lesson 13 adds budgets you can see.
NOTE
On call, 3 a.m.: Ana at Parcelo tested an early agent without a step limit, "because the model always answers in the end". Overnight a flaky log service began returning empty results, and the model kept asking for the same search, hoping for a different answer. Nothing stopped it until someone opened the provider's usage page in the morning. Ana added maxSteps and a test with a model that never answers, like Run 3 below. Invented example.
Run it
From examples/backend, with JDK 25 or newer:
./gradlew :labs:agent-loop:test# 17 tests
./gradlew -q :labs:agent-loop:run # the three runs below
Demo runs the loop three times. Each run gives the model a different script, so you can see three different endings. The model is a script: it plays back prepared replies and does not read the conversation.
Run 1: an investigation
Run 1 is the happy path. The script asks for the alert, then for a metric and some logs in one reply, then for the runbook, then answers.
ScriptedModelscript= ScriptedModel.of(
ModelReply.call("c1", "get_alert", Map.of("alert_id", Parcelo.ALERT_ID)),
ModelReply.calls(
newToolCall("c2", "query_metric", Map.of("service", "payments-gateway", "metric", "db_pool_in_use")),
newToolCall("c3", "search_logs", Map.of("service", "payments-gateway", "text", "deploy"))),
ModelReply.call("c4", "search_runbook", Map.of("topic", "pool")),
ModelReply.say("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."));
Expected output, captured from a real run (examples/golden/agent-loop.txt):
Run 1. The model investigates and answers
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
messages sent to the model on each call: [2, 4, 7, 9]
Read the trace from the top. Step 1: the model asks, a tool answers. Step 2: the model asked for two tools in one reply, so there are two model lines and two tool lines under step 2, and the loop ran them one after the other (lesson 10 runs them in parallel).
The last line is the one from Figure 2: the model saw 2, then 4, then 7, then 9 messages. The step 4 reply is the final answer, so the run stops as FINAL_ANSWER after 4 model calls.
How were those sizes counted? A lambda wraps the script and records conversation.size() before passing the call on.
Run 2 scripts a model that makes three mistakes in a row and then recovers.
Expected output, captured from a real run (examples/golden/agent-loop.txt):
Run 2. Bad tool calls come back as error results and the model recovers
step 1 model asks for fetch_dashboard(name=checkout)
step 1 error fetch_dashboard -> unknown tool 'fetch_dashboard'. Available tools: get_alert, query_metric, search_logs, search_runbook
step 2 model asks for get_alert()
step 2 error get_alert -> invalid arguments: missing required argument 'alert_id'
step 3 model asks for get_alert(alert_id=A-9999)
step 3 error get_alert -> the tool failed: no alert with id A-9999
step 4 model asks for query_metric(metric=p99_latency_ms, service=checkout-api)
step 4 tool query_metric -> p99 latency 4200 ms now, 610 ms at 02:30, rising since 02:44
step 5 final checkout-api p99 latency is 4200 ms, far above its 800 ms SLO.
stop: FINAL_ANSWER after 5 model calls
Each mistake is a different kind of error, and each one is a result: an unknown tool (the answer even lists the tools that exist), a missing argument, and a tool that ran and failed because there is no alert A-9999. Nothing crashed. At step 4 the model asks for something valid and the run ends normally after 5 model calls.
Run 3: a model that never stops
Run 3 scripts the worst case, a model that asks for the same thing forever.
Expected output, captured from a real run (examples/golden/agent-loop.txt):
Run 3. A model that never stops is cut off by the step limit
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 get_alert(alert_id=A-1042)
step 2 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 3 model asks for get_alert(alert_id=A-1042)
step 3 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 3 stop step limit of 3 reached without a final answer
stop: STEP_LIMIT after 3 model calls
The loop does not know the model is stuck. It only knows that step 3 was the last one allowed, so it stops as STEP_LIMIT after 3 model calls. Notice what it does not do: it does not notice that the three calls are identical. The lab's README suggests detecting that as a stretch exercise.
Replay the first two runs step by step:
The loop, step by step (interactive when JavaScript is on)
Run 1: the investigation
1. Call 1, 2 messages. The model receives the instruction and the goal (2 messages) and asks for get_alert(alert_id=A-1042). The loop runs it. The conversation now has 4 messages.
2. Call 2, 4 messages. The model asks for two tools in one reply: query_metric (db pool in use 50 of 50 since 02:44) and search_logs (deploy v412 started at 02:41:05, previous version v411). Two results are appended and the conversation reaches 7 messages.
3. Call 3, 7 messages. The model asks for search_runbook(topic=pool). The runbook says to check for a deploy and roll it back, which needs on-call approval. The conversation has 9 messages.
4. Call 4, 9 messages. The model sends a final answer: the payments-gateway deploy v412 at 02:41 exhausted its database pool, and the suggested action is a rollback to v411 with approval. The run stops as FINAL_ANSWER after 4 model calls.
Run 2: three bad calls
1. Unknown tool. The model asks for fetch_dashboard(name=checkout). The loop returns an error result: unknown tool 'fetch_dashboard', and lists the available tools: get_alert, query_metric, search_logs, search_runbook.
2. Missing argument. The model asks for get_alert() with no arguments. The loop refuses before running it: invalid arguments: missing required argument 'alert_id'.
3. The tool fails. The model asks for get_alert(alert_id=A-9999). The arguments are valid, so the tool runs and throws; the loop returns: the tool failed: no alert with id A-9999.
4. A good call. The model asks for query_metric(metric=p99_latency_ms, service=checkout-api) and gets p99 latency 4200 ms now, 610 ms at 02:30, rising since 02:44.
5. Answer. The model answers: checkout-api p99 latency is 4200 ms, far above its 800 ms SLO. The run stops as FINAL_ANSWER after 5 model calls.
Under the hood
What does a model call look like when it is not a script? The details differ between providers, so this is schematic JSON, not any vendor's exact format. The shape is common to most chat APIs with tool calling.
A request carries the whole conversation and the tools on offer:
{"messages":[{"role":"system","content":"You are an on-call assistant. ..."},{"role":"user","content":"Alert A-1042 is firing. What is going on?"}],"tools":[{"name":"get_alert","description":"Returns the text of one alert by its id.","parameters":{"type":"object","properties":{"alert_id":{"type":"string"}},"required":["alert_id"]}}]}
A reply either carries text or asks for tools, and usually says which of the two it is:
In the next request the same list is sent again, now followed by the model's tool request and a message that carries the result under the same id ("role": "tool", "tool_call_id": "c1", the text). Three details are worth knowing.
The arguments are text before they are data. Some APIs deliver them as a string of JSON that you parse yourself, others as an object. Either way they came from a model, so parse defensively and validate. That is what ToolSpec.validate is for.
The finish reason matters. A reply that stops because it ran out of room is not a final answer. A loop that treats every non-tool reply as "done" will mistake a cut-off answer for a complete one. Check your provider's documentation for the exact field and values.
Cost grows with the list. Every request resends everything so far, so later steps are bigger than earlier ones. That is why Figure 2 matters for your bill, and why lesson 13 measures it.
Figure 6. The same exchange over HTTP
How to read this: the packets trace one model call. Only the box in the middle of the top row knows about HTTP. The loop works with typed messages and typed replies.
Break it
The lab's tests are what keep the loop honest. Try breaking it to see which test notices. I copied the lab to a scratch folder for these experiments, so the real lab stays untouched.
Delete the validation check. In Agent.runTool, change if (problem.isPresent()) { to if (false) {. One test fails, AgentTest.invalidArgumentsAreRefusedBeforeTheToolRuns: it expected invalid arguments: argument 'alert_id' must be string, got Integer but the result was the tool failed: class java.lang.Integer cannot be cast to class java.lang.String .... The tool ran with a number where it expected text and failed inside. A tool that did not happen to fail would simply have run with whatever the model invented.
Give the model the real list. In Agent.run, replace List.copyOf(conversation) with conversation. One test fails, AgentTest.toolResultsGoBackToTheModelBeforeItsNextTurn, with expected: <2> but was: <5>. The test kept the list that call 1 received, and because it was the agent's own list it kept growing after the call. This is exactly the bug a copy prevents.
Take away the budget. The lab's README suggests removing the upper bound of the for loop. Without a bound the code after the loop becomes unreachable, which Java rejects, so I replaced step <= config.maxSteps() with step <= 1_000_000_000. The test theStepLimitStopsAModelThatNeverAnswers never reported a result: I stopped waiting after two minutes, and Gradle reported that the test process had failed unexpectedly. That is a model that never answers, with nothing to stop it.
In experiments 1 and 2 the other 16 tests stayed green. Restore each change and the whole suite passes again.
In practice: Parcelo
Replay Run 1 as an investigation and the four tools become an evidence chain, with each answer shaping the next question.
Figure 7. The evidence chain of Run 1
How to read this: the number on each box is the step of Run 1 that fetched it (steps 2 asked for two tools at once). The model could name the cause on call 4 because by then the list held all four results.
TriageDesk in lesson 15 is this loop with more tools, a gate in front of the two that change production, and tracing. It is not a different kind of program.
Architect's notes
Own the loop, even if you adopt a framework. The framework's loop is this loop with options. You should be able to say where its step limit, its validation and its error handling are.
Budgets are part of the design. Choose maxSteps from the longest legitimate task you expect, plus a little. Lesson 13 adds token and time budgets, and a stop reason that is not just "ran out".
The conversation is the cost. It is resent on every call, so a long run costs more per step than a short one. Plan to trim or summarise it (lesson 6).
Do not trust the model to stop itself. The model decides when to answer, and your loop decides when it has had enough.
Turn failures into results, but log them. The model needs to read an error, and you need to count them. A model that fails often on one tool is telling you that its description is unclear.
Run tools one at a time until you have to do otherwise. The lab runs several requested calls in order. Parallel calls bring timeouts and cancellation, which lesson 10 handles.
Common mistakes
No step budget. The loop runs until the money does. Fix: a maxSteps in the config, and a stop reason in the result.
Letting an exception escape. One bad guess kills the run. Fix: catch around the tool call and return an error result, as runTool does.
Running the tool before checking the arguments. Generated text reaches your code. Fix: validate against the spec first.
Handing the model your mutable list. An implementation can change the agent's memory. Fix: pass a copy, as List.copyOf does.
Treating any non-tool reply as the final answer. A cut-off reply looks like one. Fix: check the provider's finish reason before you return the text.
Vague errors. "Invalid input" gives the model nothing to fix. Fix: name the argument and the rule, as validate does.
IMPORTANT
Remember this:
The message list is the agent's memory, and it is resent in full on every call.
A model's reply is a final answer or a tool request. Nothing has run until your code runs it.
Validate the arguments, then run, and return every failure as a result the model can read.
The step budget is what guarantees the loop ends.
Key takeaways
The agent loop is about sixty lines: ask, run the requested tools, append the results, repeat.
A chat model has no memory, so the conversation list is resent each time and grows with every step.
A tool is a spec the model reads plus code it never sees. The description is prompt text.
Arguments are generated text. Check them first, and make every error a sentence the model can act on.
maxSteps ends every run, either with a final answer or with STEP_LIMIT.
Practice exercises
Starter. Run ./gradlew :labs:agent-loop:test and read AgentTest in examples/backend/labs/agent-loop/src/test/java/buildingai/labs/agent/AgentTest.java. Which test proves that results go back to the model before its next turn?
Intermediate. In a scratch copy, add a Stop.NO_PROGRESS to AgentResult.java that ends the run when the model asks for the same tool with the same arguments twice in a row, and make Run 3 end that way. Write a test for it.
Advanced. Write a ChatModel in Demo.java that prints the tool names it receives and the last message of the conversation it is given, and use it in Run 2. What does the model see after the unknown-tool error?
Lesson 2 of 15 · Agentic AI for Java Developers: Build and Ship Agents
Build the loop at the heart of every AI agent in plain Java: messages as memory, tool requests, validation, errors as results and a hard step budget.
In the rest of this lesson
Validate before you run
Errors are observations, not crashes
The loop itself
Run it
Under the hood
Break it
Enrolling is free. It unlocks every lesson in Agentic AI for Java Developers: Build and Ship Agents, tracks your progress across devices and keeps your quiz scores. The newsletter is optional.
Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.
Get new articles by email
Free. We email a confirmation link first, and you can unsubscribe from any email.