What you'll learn: how Spring AI's ChatClient replaces the hand-written loop of lesson 2 with annotated tools, memory, record output, human approval and call limits, and how to prove each of those with tests that need no API key.
The loop you wrote, and the loop you can borrow
In lesson 2 you wrote about 60 lines of Java: ask the model, run the tools it requests, hand back the results, repeat. It works, and you now know exactly what it does. It also has no memory, no way to pause for a human, and nothing that turns the final answer into a Java object. Most Spring teams will not rebuild all of that for every service.
Spring AI ships those parts. This lesson maps each part of your plain loop to the Spring AI concept that replaces it, then builds the same Parcelo investigation on top of a real ChatClient. The single idea: the loop is still there, it just lives in the framework, so what you control is the tools, the limits and the gates around it.
NOTE
Invented example. Parcelo is a made-up delivery company. Its services, alerts and incident are the fixed data of the course labs. Nothing here is a real measurement.
WARNING
The model in this lab is a script.ScriptedChatModel plays back a fixed list of replies so the output is the same on every run and no API key is needed. The framework around it (ChatClient, tool calling, memory, approvals, limits) is real Spring AI code. A real model chooses its own tool calls and varies between runs, and this lab says nothing about how well a real model would investigate.
The idea in one picture
Figure 1. What Spring AI runs for you inside one call
How to read this: follow the moving packets. Your code makes one call. Inside it the advisor sends the messages and tool definitions to the model, receives a tool request, hands it to the manager, and goes round again until the model answers without a tool request.
TIP
Picture it: a waiter between a table and a kitchen. The diner (the model) says what they want, the waiter (the advisor) carries the order to the kitchen (your tool methods), brings the plate back, and asks whether anything else is wanted. The restaurant's owner sees one order in and one meal out. Where it stops: a model sometimes orders a dish that is not on the menu.
From your 60 lines to Spring AI: a map
Every part of the plain loop has a counterpart. Knowing the map is what makes the framework feel small instead of magic.
In the plain loop (lesson 2)
In Spring AI 2.1.0
What to know
ChatModel.reply(conversation, tools)
ChatModel.call(Prompt)
Spring AI's own interface. Each provider has an implementation; the labs use a fake one.
The Message list
The messages of a Prompt
System, user, assistant and tool-response messages.
Tool, ToolSpec
ToolCallback, ToolDefinition
Built from an annotated method, so the schema cannot drift from the signature.
The Tools registry
defaultTools(...) and .tools(...)
Defaults apply to every call, per-call tools add to them.
The for loop in Agent.run
ToolCallingAdvisor
Registered for you by ChatClient (it can be switched off).
runTool and error results
ToolCallingManager
A tool that throws becomes a result the model reads, by default.
maxSteps
Tool call limits on the manager
Per tool and in total, per turn. The reference documents no separate step counter.
Trace
A Micrometer observation named spring.ai.tool
One per tool execution.
Nothing
Session memory, entity(...), requiresConfirmation
New capabilities, covered below.
Two rows deserve a second look. The step budget is different in kind: maxSteps capped the number of model calls, while Spring AI caps how often tools are called in a turn. And the approval gate that lesson 2 left for later is a built-in feature, switched on by one attribute.
Figure 2. One tool call, as the framework performs it
sequenceDiagram
accTitle: One tool call inside a ChatClient call
accDescr: Your code calls the ChatClient. The ToolCallingAdvisor sends the prompt and tool definitions to the chat model. The model replies with a request for get_alert. The advisor asks the ToolCallingManager to run it, the manager calls the getAlert method, and the result goes back to the advisor. The advisor sends a second prompt with the tool result and the model answers in text, which returns to your code.
participant App as Your code
participant Adv as ToolCallingAdvisor
participant Model as ChatModel
participant Mgr as ToolCallingManager
participant Tool as ParceloTools
App->>Adv: prompt().user(goal).call()
Adv->>Model: messages and tool definitions
Model-->>Adv: asks for get_alert
Adv->>Mgr: executeToolCalls
Mgr->>Tool: getAlert("A-1042")
Tool-->>Mgr: alert text
Mgr-->>Adv: history with the tool result
Adv->>Model: second prompt, 4 messages
Model-->>Adv: final answer
Adv-->>App: content()
How to read this: the two arrows into the model are the two model calls. Everything between them happens inside one call() of yours. The chain of other advisors between the advisor and the model is left out.
Build it: tools as annotated methods
In the plain lab a tool was a ToolSpec (name, description, typed parameters) plus a lambda. In Spring AI the same information comes from one annotated method. The name and description come from @Tool, the parameter name and type from the signature, and @ToolParam adds a description.
@Tool(name = "get_alert", description = "Returns the text of one alert by its id.")public String getAlert(@ToolParam(description = "The alert id, for example A-1042") String alertId) {
calls.add("get_alert(alertId=" + alertId + ")");
Stringalert= ALERTS.get(alertId);
if (alert == null) thrownewIllegalArgumentException("no alert with id " + alertId);
return ran("get_alert", "alert " + alertId + ": " + alert);
}
Read it as a normal method with three extras. calls.add(...) and ran(...) are the lab's own bookkeeping, so tests can see what the framework called. The IllegalArgumentException is deliberate: by default Spring AI sends the message of a RuntimeException back to the model as the tool's result, so the model can read what went wrong and try again, like the error results of lesson 2.
The lab copies the few lines of Parcelo data into this bean on purpose. The Spring workspace is a separate Gradle build and cannot depend on the plain-Java lab, so the data is repeated and must stay equal to Parcelo.java.
Figure 3. From a method to what the model reads
A tool method becomes a tool definition that travels in the request options@Tool method to ToolCallback (ToolCallbacks.from); ToolCallback to ToolDefinition (describes); ToolDefinition to Request options (defaultTools); Request options to ChatModel (each call)@Tool method: your Java@Tool methodyour JavaToolCallback: wraps the methodToolCallbackwraps the methodToolDefinition: name, text, schemaToolDefinitionname, text,schemaRequest options: carry the toolsRequestoptionscarry the toolsChatModel: reads the textChatModelreads the textToolCallbacks.fromdescribesdefaultToolseach call
How to read this: the model never sees your Java method. It sees the definition: a name, a description and a JSON schema, sent inside the request options on every call.
The definition is plain data, so the lab prints it. Compare it with the schema line of lesson 2: same idea, but the property is named alertId (the Java parameter) instead of alert_id, because here the signature is the source of truth.
Expected output, captured from a real run (examples/spring-labs/golden/agent-spring-ai.txt):
The tool the model reads (what Spring AI builds from the get_alert method):
name: get_alert
description: Returns the text of one alert by its id.
input schema: {"$schema" : "https://json-schema.org/draft/2020-12/schema","type" : "object","properties" : {"alertId" : {"type" : "string","description" : "The alert id, for example A-1042"}},"required" : [ "alertId" ],"additionalProperties" : false}
TIP
Picture it: a job card pinned above a workstation: the title, one sentence on what the job does, and a list of the slots you must fill in. The model reads only the card. If you write "does stuff" on it, the model will use the tool badly, however clean your method is.
Build it: the chat client and the fake model
A ChatClient is the object an application calls. You build it once from a model, a system prompt and the tools, and the tool-calling loop comes with it.
defaultTools takes the bean itself: Spring AI scans it for @Tool methods. Defaults apply to every request from this client, so only safe tools belong there. The reference advises adding risky tools per request, which is what the approval section does with roll_back.
Now the stand-in for the model. It implements Spring AI's ChatModel interface and plays back a script, one reply per call, and it records every prompt it receives.
@Overridepublic ChatResponse call(Prompt prompt) {
received.add(prompt);
Function<Prompt, ChatResponse> next = script.poll();
if (next == null) thrownewIllegalStateException("the script has no reply left for call " + received.size());
// ...return reply;
}
The number of entries in received is the number of model calls, which is exactly what the tests count. One more method is easy to miss.
A ChatClient starts from the model's options and puts the tool definitions into them. If the options are not tool-capable, there is nowhere to put the tools.
In the lab's first version this method was missing: call() returned the model's tool request unexecuted (content() was empty text) and no tool ran. A test (aClientWithoutToolOptionsNeverRunsTheLoop) now keeps that visible. The lab did not check any real provider's integration, so treat this as a reminder that the loop depends on the model integration, not only on your tools.
TIP
Picture it: a crash-test dummy. The car (Spring AI, with its real brakes and airbags) is tested for real; the dummy only sits where a driver would sit. You learn nothing about how people drive, and everything about whether the car protects them. That is the honest claim of this lab.
Run it: the loop Spring AI runs for you
From examples/spring-labs:
./gradlew :labs:agent-spring-ai:test# 26 tests, including the golden comparison
./gradlew :labs:agent-spring-ai:test -PwriteGolden # rewrite golden/agent-spring-ai.txt from a run
The first test of the lab is the one to read before the output. It asserts the two facts the framework hides from you: the tool was called with the arguments the model sent, and the model was called twice.
@TestvoidtheFrameworkRunsTheToolAndCallsTheModelTwice() {
ScriptedChatModelmodel= ScriptedChatModel.of(
askFor(call("c1", "get_alert", "{\"alertId\":\"A-1042\"}")),
say("checkout-api is slow."));
Stringanswer= investigator.client(model).prompt().user(AgentReport.GOAL).call().content();
assertThat(answer).isEqualTo("checkout-api is slow.");
assertThat(model.received()).as("one call to ask, one call after the tool result").hasSize(2);
assertThat(tools.calls()).containsExactly("get_alert(alertId=A-1042)");
}
Your code makes one call(). The model is called twice, and the tool method runs once with A-1042. The loop is invisible in your own code, which is the point and also the hazard, so the report records it from the edges: the fake model logs what it is sent and what it replies, and the tools log what they return. This is Run 1, the same four-step investigation as lesson 2.
Expected output, captured from a real run (examples/spring-labs/golden/agent-spring-ai.txt):
Run 1. Spring AI runs the loop: the model asks for tools, the framework runs them
model 1 is sent [SYSTEM, USER]
model 1 asks for get_alert({"alertId":"A-1042"})
tool get_alert -> alert A-1042: checkout-api p99 latency 4200 ms (SLO 800 ms), error rate 6.1%, firing since 02:47 UTC
model 2 is sent [SYSTEM, USER, ASSISTANT, TOOL]
model 2 asks for query_metric({"service":"payments-gateway","metric":"db_pool_in_use"})
model 2 asks for search_logs({"service":"payments-gateway","text":"deploy"})
tool query_metric -> db pool in use 50 of 50 since 02:44, 14 of 50 at 02:30
tool search_logs -> 02:41:05 INFO deploy v412 started (previous version v411) | 02:41:40 INFO deploy v412 reported healthy
model 3 is sent [SYSTEM, USER, ASSISTANT, TOOL, ASSISTANT, TOOL]
model 3 asks for search_runbook({"topic":"pool"})
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).
model 4 is sent [SYSTEM, USER, ASSISTANT, TOOL, ASSISTANT, TOOL, ASSISTANT, TOOL]
model 4 answers: 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.
model calls: 4
tool methods that ran: 4
Read it top to bottom. The model is called four times and answers on the fourth. Model call 2 asks for two tools in one reply, and the framework runs both before calling the model again. Look at the list in brackets on each is sent line: it grows by an assistant message and a tool message per round, because the whole conversation is sent every time. Spring AI keeps that list for you, as your conversation variable did in lesson 2.
One Spring AI run, step by step (interactive when JavaScript is on)
Investigation
1. Ask. Model call 1 is sent [SYSTEM, USER] and asks for get_alert with alertId A-1042.
2. First tool. The framework runs get_alert: alert A-1042, checkout-api p99 latency 4200 ms (SLO 800 ms), error rate 6.1%, firing since 02:47 UTC.
3. Two tools at once. Model call 2 is sent [SYSTEM, USER, ASSISTANT, TOOL] and asks for query_metric and search_logs in one reply.
4. Both results. query_metric returns db pool in use 50 of 50 since 02:44, 14 of 50 at 02:30. search_logs returns the deploy v412 lines from 02:41.
5. Runbook. Model call 3 is sent six messages and asks for search_runbook with topic pool.
6. Answer. Model call 4 is sent eight messages and answers: the deploy v412 exhausted the pool, roll back to v411, which needs on-call approval. 4 model calls, 4 tool methods ran.
Approval
1. Request. Request A: model call 1 asks for roll_back with service payments-gateway and version v411.
2. Pause. The reply is paused, waiting for a decision on c1. Rollbacks run so far: none.
3. Allow. The engineer decides allow c1. The tool roll_back runs: rollback of payments-gateway to v411 started.
4. Continue. Model call 2 is sent [SYSTEM, USER, ASSISTANT, TOOL] and answers that payments-gateway is being rolled back to v411.
5. Deny. Request B: the decision is deny c1 with the message: The on-call engineer said no: wait for the service owner. The model reads that message as the tool result. Rollbacks run: none.
Call limit
1. Loop. A script asks for get_alert three times. The limit is 2 calls per tool.
2. THROW. With THROW the run ends after 3 model calls, get_alert ran 2 times, and the finish reason is toolCallLimitExceeded.
3. RETURN_ERROR_RESPONSE. With RETURN_ERROR_RESPONSE there are 4 model calls and get_alert still ran only 2 times. The model reads the limit message as the tool result and answers.
Under the hood: what the framework sends and loops over
Three details of Run 1 are worth knowing, because they are where problems hide.
The conversation is a list that grows. The bracketed lists are the messages of each model call. System and user messages open it; each round adds the model's tool request (an assistant message) and the tool results (a tool message). The first call sends 2 messages and the fourth sends 8, so the cost of a run grows with every step.
Figure 4. The same conversation, sent four times
Each model call re-sends the whole conversation, which grows by two messages per roundModel call 1 to Model call 2 (+ request, result); Model call 2 to Model call 3 (+ request, result); Model call 3 to Model call 4 (+ request, result); Model call 4 to Final answerModel call 1: 2 messagesModel call 12 messagesModel call 2: 4 messagesModel call 24 messagesModel call 3: 6 messagesModel call 36 messagesModel call 4: 8 messagesModel call 48 messagesFinal answer: no tool requestFinal answerno tool request+ request, result+ request, result+ request, result
How to read this: follow the packets left to right. The counts come from the Run 1 output above. Nothing is ever removed unless you configure it.
A tool result travels as JSON. Your method returns a String, but Spring AI's default result converter turns the result into JSON before it goes back to the model, so the text arrives with quotes around it. A test asserts it (aToolResultTravelsBackToTheModelAsJson). It is harmless, and it is the kind of difference you only see by looking at the messages, not at the method.
A tool that throws is not a crash. Another test (aToolThatThrowsBecomesAResultTheModelCanRead) calls get_alert with an unknown id. The exception message goes back to the model as the result and the run continues. The reference documents the rule: a RuntimeException's message goes to the model, while checked exceptions and errors always propagate to your code. Setting spring.ai.tools.throw-exception-on-error=true makes every tool error throw to the caller instead.
NOTE
On call, 3 a.m.: Imani Okoye at Parcelo, an invented delivery company, ships a TriageDesk prototype on Spring AI. A tool throws a SQLException (a checked exception) when the metrics database is slow. She expected the model to read an error and retry. Instead the whole request failed with a stack trace. She wraps it in an IllegalStateException("metrics database is slow, try again later"), and the slowdown becomes a message the model can use. Invented example.
Structured output: the answer as a record
An agent's final answer is usually text for a person. When a program reads it (a ticket system, a dashboard), you want fields. entity(...) asks Spring AI to do the conversion: it adds the JSON Schema of your record to the prompt and parses the reply.
It is the same call as before with entity(Triage.class) at the end instead of content(). Tools and structured output work together: the agent investigates, and its last message is the record. In Run 2 the scripted model asks for one tool and then replies with JSON text. The report prints the first lines the framework added to the user message.
Expected output, captured from a real run (examples/spring-labs/golden/agent-spring-ai.txt):
Run 2. Structured output: the final answer arrives as a Java record
model 1 is sent [SYSTEM, USER]
model 1 asks for get_alert({"alertId":"A-1042"})
tool get_alert -> alert A-1042: checkout-api p99 latency 4200 ms (SLO 800 ms), error rate 6.1%, firing since 02:47 UTC
model 2 is sent [SYSTEM, USER, ASSISTANT, TOOL]
model 2 answers: {"likelyCause":"payments-gateway deploy v412 exhausted its database pool","suggestedAction":"roll back to v411","needsApproval":true}
the question was one line; Spring AI added 22 lines to the user message, starting with:
Your response should be in JSON format.
Do not include any explanations, only provide a RFC8259 compliant JSON response following this format without deviation.
entity(Triage.class) returned: Triage[likelyCause=payments-gateway deploy v412 exhausted its database pool, suggestedAction=roll back to v411, needsApproval=true]
The 22 lines are an instruction to the model plus the JSON Schema of Triage. That is all structured output is by default: a polite request in the prompt and a parser on the way back. It is best-effort, as a real model may ignore it.
A test shows what happens when the reply is not JSON: entity throws, so your code finds out instead of getting a half-filled record. The reference also documents validateSchema() and useProviderStructuredOutput() on the entity call for more reliability; the lab does not exercise them, because a scripted model cannot show whether a provider's structured mode helps.
Memory: sessions
Everything so far forgets. A second question starts a new conversation. In Spring AI 2.1.0 the reference marks MessageChatMemoryAdvisor and the ChatMemory API as deprecated since 2.1.0 and to be removed in 3.0.0, and points to session memory instead. The lab uses the replacement: SessionAdvisors, from the spring-ai-session-advisor module.
The advisor stores each turn in a SessionService and replays it on the next call. Every call must say which session it belongs to; a call with no session id is refused (a test checks it). The id should come from your server, per user and per conversation, never from the client.
client.prompt().user("What is alert A-1042?").advisors(SessionAdvisors.session("oncall-7")).call().content();
Figure 5. Where the memory lives
A session advisor loads earlier turns and saves new ones around each callYour code to Spring AI ChatClient (prompt, id); Spring AI ChatClient to Session store (save turn); Session store to Spring AI ChatClient (load history); Spring AI ChatClient to ChatModel (history, tools)Your code: session id per userYour codesession id peruserSpring AI ChatClient: session advisorSpring AIChatClientsession advisorSession store: in memory hereSession storein memory hereChatModel: sees the historyChatModelsees the historyprompt, idsave turnload historyhistory, tools
How to read this: the store sits beside the call, not inside the model. The model sees only what the advisor chooses to send.
Run 3 asks two questions in one session. The scripted model answers the first after a tool call and the second directly.
Expected output, captured from a real run (examples/spring-labs/golden/agent-spring-ai.txt):
Run 3. Memory: a second question in the same session sees the first conversation
turn 1: What is alert A-1042?
model 1 is sent [SYSTEM, USER]
model 1 asks for get_alert({"alertId":"A-1042"})
tool get_alert -> alert A-1042: checkout-api p99 latency 4200 ms (SLO 800 ms), error rate 6.1%, firing since 02:47 UTC
model 2 is sent [SYSTEM, USER, ASSISTANT, TOOL]
model 2 answers: Alert A-1042 is about checkout-api: its p99 latency is 4200 ms.
turn 2: Which service was it?
model 3 is sent [SYSTEM, USER, ASSISTANT, TOOL, ASSISTANT, USER]
model 3 answers: It was checkout-api.
events stored for session oncall-7: [USER, ASSISTANT (tool call), TOOL, ASSISTANT, USER, ASSISTANT]
Read the is sent line of model call 3. Turn 2 was a one-line question, yet the model is sent six messages: the whole of turn 1 including the tool request and the tool result, then the new question. So in this version the memory stores tool calls and their results too, and a long session with chatty tools is a long prompt.
The reference describes compaction (a trigger plus a strategy that shrinks old turns) for exactly this; the lab does not run it. The lab uses the in-memory repository, which the reference describes as meant for tests and demos: sessions vanish on restart and are not shared between instances. A real service needs a persistent repository, and the JDBC module is the one the reference names.
TIP
Picture it: the case notes a nurse hands over at shift change. The next nurse does not remember the patient, but the notes say what was tried, what the tests showed and what was decided. Where it stops: notes can be wrong or too long to read, and a model reads every word of them on every call and pays for each word.
Approvals and limits
Some tools should never run on the model's say-so alone. Rolling back a production service is one. Spring AI 2.1.0 has a feature for this: mark the tool with requiresConfirmation = true.
@Tool(name = "roll_back", description = "Rolls a service back to an earlier version.", requiresConfirmation = true)public String rollBack(
@ToolParam(description = "Service name") String service,
@ToolParam(description = "Version to return to, for example v411") String version) {
When the model asks for this tool, the manager does not run it. It throws an internal exception that the advisor catches, and your call() returns an ordinary response whose metadata lists the ids of the calls that wait for a decision. The loop keeps no state while it waits: the pause is a response and the resume is a request. Your application shows the waiting call to a person, collects one ToolCallDecision per call (allow, or deny with a message), and resumes.
Three things to notice. roll_back is added with .tools(changes) for this request only, so it is never a default tool. The pause needs chatResponse(), because content() returns empty text for a paused reply and gives no sign of the pause. And resume hands the same manager the decisions: it runs the allowed calls, turns denied ones into a message for the model, and returns the history to continue with.
Figure 6. The states of an approval
stateDiagram-v2
accTitle: States of a tool call that needs approval
accDescr: The model asks for a tool marked requiresConfirmation. The run is paused with nothing executed. A person then allows or denies each call. Allowed calls run and denied calls become a message. The results go to the model, which continues. A pause nobody resolves leaves tool calls without results, which most providers reject.
[*] --> Requested: model asks for roll_back
Requested --> Paused: manager throws, nothing runs
Paused --> Decided: person allows or denies each call
Paused --> Abandoned: nobody decides
Decided --> Continuing: results or deny message go to the model
Continuing --> [*]
Abandoned --> [*]
How to read this: nothing between Requested and Decided executes any tool. Abandoned is the state to design for: the reference warns that an unresolved pause leaves tool calls with no results, and most providers reject that conversation.
Run 4 puts both outcomes through the real manager: Request A is allowed, Request B is denied.
Expected output, captured from a real run (examples/spring-labs/golden/agent-spring-ai.txt):
Run 4. A tool that needs approval pauses the loop, once allowed and once denied
Request A: the on-call engineer allows the call
model 1 is sent [SYSTEM, USER]
model 1 asks for roll_back({"service":"payments-gateway","version":"v411"})
paused, waiting for a decision on [c1]; rollbacks run so far: []
decision: allow c1
tool roll_back -> rollback of payments-gateway to v411 started
model 2 is sent [SYSTEM, USER, ASSISTANT, TOOL]
model 2 answers: payments-gateway is being rolled back to v411.
rollbacks run: [roll_back(service=payments-gateway, version=v411)]
Request B: the on-call engineer denies the call
model 1 is sent [SYSTEM, USER]
model 1 asks for roll_back({"service":"payments-gateway","version":"v411"})
paused, waiting for a decision on [c1]
decision: deny c1 with the message "The on-call engineer said no: wait for the service owner."
model 2 is sent [SYSTEM, USER, ASSISTANT, TOOL]
model 2 answers: I did not roll back. The on-call engineer asked me to wait for the service owner.
the tool message the model read: The on-call engineer said no: wait for the service owner.
rollbacks run: []
Read Request A: the line "rollbacks run so far: []" is printed while the reply is paused, which is the proof that nothing ran. After the decision, roll_back runs once. In Request B the tool never runs: the model reads the deny message in the place where a tool result would be. The model's wording in "answers" is scripted, so this run proves the mechanics, not that a real model would respond sensibly to a refusal.
WARNING
The framework does not decide who may approve. The reference says it does not authenticate approvers, so your application must check that the person deciding is allowed to. Read the paused reply from trusted storage, never from a client request: a client that can edit it can run any tool with any arguments. Resuming twice runs the tools twice, so make a resume idempotent. Treat a deny message as untrusted input, since the model reads it as a tool result. The guardrails lesson goes deeper.
TIP
Picture it: a bank teller who can prepare a large transfer but needs a manager's countersignature. The paperwork sits in a drawer; the teller does not hold the customer at the counter waiting. Later a manager signs or refuses, and the teller continues. The drawer is your "trusted storage", and the rule that the manager must be a manager is yours to write: the form does not check the signature.
Limits on the loop
The plain lab capped model calls with maxSteps. Spring AI caps tool calls per turn on the ToolCallingManager: per tool and in total, with documented defaults of 40 calls per tool and 150 in total, and a choice of what happens when a limit is hit.
You give the advisor your own manager, and your advisor replaces the automatic one. Run 5 uses a model that asks for get_alert over and over, the same shape as lesson 2's Run 3, with a limit of two calls per tool.
Expected output, captured from a real run (examples/spring-labs/golden/agent-spring-ai.txt):
Run 5. A model that never stops is cut off by the call limit, in two ways
limit 2 per tool, onLimitExceeded THROW
model calls: 3, get_alert ran 2 times
finish reason: toolCallLimitExceeded
response text: Tool call limit (2) exceeded for tool 'get_alert'. No further calls to this tool are allowed in this turn.
limit 2 per tool, onLimitExceeded RETURN_ERROR_RESPONSE
model calls: 4, get_alert ran 2 times
the tool message the model read on its last call: Tool call limit (2) exceeded for tool 'get_alert'. No further calls to this tool are allowed in this turn.
final answer: I could not read the alert a third time, so here is what I know: checkout-api is slow.
With THROW the run ends: your code gets a normal-looking response whose finish reason is toolCallLimitExceeded, so you must check it, because the text is a message, not an answer.
With RETURN_ERROR_RESPONSE the third request is not run; the model reads the limit message as the tool result and the loop continues, so a real model has a chance to wrap up. In both runs get_alert ran exactly twice. The scripted answer in the second run is not evidence that a real model would wrap up well.
Figure 7. A gate in front of every tool call
The tool-calling manager counts calls in the turn and stops or tells the modelChatModel to Tool manager (tool request); Tool manager to @Tool method (under limit); Tool manager to Stop the run (over limit); Tool manager to Tell the model (over limit)ChatModel: asks again and againChatModelasks again andagainTool manager: limit per toolTool managerlimit per tool@Tool method: runs@Tool methodrunsStop the run: THROW settingStop the runTHROW settingTell the model: error resultTell the modelerror resulttool requestunder limitover limitover limit
How to read this: under the limit the call runs. Over it, the setting chooses between the two red paths. The count covers the current turn only, from the last user message onward.
TIP
Picture it: the fuse box of a house. A kettle that draws too much current trips its circuit, and the rest of the house keeps its light. THROW is the trip: everything stops and someone must reset it. RETURN_ERROR_RESPONSE is closer to a smart plug that switches off the kettle and sends you a message. Where it stops: a fuse reacts to current, while these limits count calls, so a tool that is slow but called once is not limited at all.
NOTE
On call, 3 a.m.: Tomasz Brandt at Parcelo, an invented delivery company, leaves his assistant on the framework defaults and sees a night's bill at three times the usual. The model had called a search tool many times with slightly different words, always under the default of 40 calls per tool. He sets maxCallsPerTool to 5 for it and maxTotalToolCalls to 20, with RETURN_ERROR_RESPONSE. The next night's bill is normal. Invented example.
Observability hook
The plain loop had a Trace. In Spring AI every tool execution is wrapped in a Micrometer observation named spring.ai.tool, and the reference says it records the tool name, the definition metadata and the execution duration, plus tracing context when a tracer is present. Tool arguments and results are exported as span attributes only if you enable it, and that is off by default. The lab attaches the smallest possible listener: it records the tool name of each finished observation.
The registry is handed to the manager with ToolCallingManager.builder().observationRegistry(...). The handler filters by name inside onStop: the first version filtered in supportsContext and saw no observation at all, so the name is evidently not set yet at that moment. In a real service you would not write this handler: Micrometer's metrics and tracing set-up consumes the same observation.
Expected output, captured from a real run (examples/spring-labs/golden/agent-spring-ai.txt):
Run 6. The observation Spring AI records for each tool call
observations named spring.ai.tool: 2
tool of each observation, in order: [get_alert, search_runbook]
For a first look without any set-up, the reference also names a debug log: logging.level.org.springframework.ai=DEBUG. The lab did not run it, so check the output in your own application. A different, important hook is the advisor chain. A custom advisor placed with an order inside the tool-calling advisor sees every iteration, as the reference's "Observing the Loop" section shows. The lab does not implement one; the stretch exercise does.
Break it
Two experiments, both really run on 2026-12-03 and restored afterwards.
Take away requiresConfirmation = true and the description of getAlert's parameter. 7 of the 26 tests fail: the four approval tests that need a pause, the test that reads the schema, and both golden comparisons. Without the attribute nothing pauses, so a request for roll_back is no longer put in front of a person. The safety was one attribute wide.
Remove the getOptions() override from the fake model. The model's request for get_alert comes back from your call() unexecuted: content() is empty text and no tool runs. Nothing throws. This is the quiet failure to watch for when you integrate a model: if tools never run, check that the model integration advertises tool-capable options before you suspect your tools.
In practice: Parcelo
TriageDesk, Parcelo's invented on-call assistant, is the capstone of the course. On Spring AI its shape is the lab scaled up: a controller receives the alert, a ChatClient with read-only default tools investigates, and a rollback is requested per call with approval.
Figure 8. TriageDesk on Spring AI (educational reference design)
TriageDesk: read-only investigation, a persisted pause, a human decision, a resumeAlert webhook to Spring Boot app; Spring Boot app to Spring AI ChatClient (goal); Spring AI ChatClient to ChatModel (messages, tools); Spring AI ChatClient to Pending store (paused reply); Pending store to Engineer (show the call); Engineer to Spring Boot app (decision)Alert webhook: A-1042Alert webhookA-1042Spring Boot app: controllerSpring BootappcontrollerSpring AI ChatClient: read-only toolsSpring AIChatClientread-only toolsPending store: trusted storagePending storetrusted storageEngineer: allow or denyEngineerallow or denyChatModel: any providerChatModelany providergoalmessages, toolspaused replyshow the calldecision
How to read this: the green nodes are your responsibility, not the framework's: where the paused reply is stored, who may approve, and making sure a resume happens once. This is an educational reference design, not a real company's system.
Notice what the design asks of you. The investigation is read-only by construction: the four tools are default tools, and roll_back is added only on the request that may need it. The pause is a stored response, so the approver can take minutes or hours without holding a thread. And the resume goes back through the same ToolCallingManager that paused, so the confirmation policy is the same in both directions.
Architect's notes
When is Spring AI the right tool and when is the plain loop?
Use Spring AI when you already run Spring Boot and the agent is one more feature of a service. Tools become beans, configuration, observability and tests are the ones your team knows, and you get memory, structured output, approval and limits without writing them.
Keep the plain loop when the loop is the product. If you need a custom stopping rule, unusual message handling or a runtime that is not Spring, 60 lines you own can be cheaper than a framework you must understand. The advisor hooks (ToolCallingAdvisor can be subclassed) cover many variations, but they are Spring-shaped.
Pin versions and read the upgrade notes. This lesson found a memory API deprecated in the same release line it was written for. Spring AI's AI-specific parts move quickly, so isolate them behind one class like Investigator.
The loop is hidden, so record it. Add an observation or a debug trace from day one. When a run costs too much or answers badly, the list of messages per model call is the evidence you need, and the framework does not print it unless you ask.
Gates and limits are configuration, not behaviour you can assume. Defaults of 40 calls per tool and 150 in total are generous for a cost cap. Decide the numbers from your own measurements.
Do not assume validation. The plain lab checked tool arguments against the spec before running anything. This lab did not test what Spring AI does with arguments that break the schema, so validate inside the tool method the way you would at any API boundary.
Test against a fake model, then against the real one. The scripted model proves your wiring and your gates. It cannot show whether a real model picks the right tool; for that you need the evaluations of the testing lesson.
Common mistakes
Putting every tool in defaultTools, including the risky ones. Fix: add destructive tools per request, and mark them requiresConfirmation.
Reading a paused reply with content(). Fix: use chatResponse() and check for waiting calls; content() returns empty text and hides the pause.
Keeping the paused reply on the client. Fix: store it on the server. A reply a user can edit is a tool call a user can choose.
Trusting the default limits. Fix: set maxCallsPerTool and maxTotalToolCalls from your budget, and decide between THROW and RETURN_ERROR_RESPONSE.
Treating a THROW limit as an answer. Fix: check the finish reason before showing the text to anyone.
Using the deprecated chat memory in new code. Fix: use session memory (SessionAdvisors) and pass a session id on every call.
Throwing checked exceptions from tools. Fix: wrap them in a RuntimeException with a message the model can act on.
IMPORTANT
Remember this:
The loop moved into the framework, and you still own the tools, the limits and the gates.
A tool is one annotated method; its description is part of the prompt.
Mark risky tools requiresConfirmation, add them per request, and decide who may approve.
Limits count tool calls per turn: choose them, and choose what happens when they trip.
The model here was a script: the lab proves the framework, not the model.
Key takeaways
ChatClient plus defaultTools gives you the tool-calling loop; you wrote the same loop by hand in lesson 2.
The model is called once per round and receives the whole conversation each time.
entity(Triage.class) turns the final answer into a record by adding the schema to the prompt and parsing the reply.
Session memory stores tool calls and results as well as the questions.
requiresConfirmation pauses the loop with nothing executed; your application stores the pause, collects decisions and resumes.
Tool call limits are per turn, per tool and in total; THROW and RETURN_ERROR_RESPONSE behave very differently.
Practice exercises
Starter. In AgentLoopTest, add a test that asks for query_metric with an unknown service and assert what the model reads back as the tool result. Run ./gradlew :labs:agent-spring-ai:test.
Intermediate. In Approvals.java, add a method that denies every waiting call with the message "The user moved on." and test it with ApprovalLimitsObservationTest.java. This is the cleanup the reference suggests for abandoned pauses.
Advanced. Replace the confirmation flag with a ToolCallConfirmationPolicy that pauses only when roll_back targets payments-gateway, using the call's arguments, and write a test for both paths. Then subclass ToolCallingAdvisor to record each tool intent before it runs, using the reference's ToolCallingAdvisor page as the guide.
Version note
This lesson was compiled and run on 2026-12-03 against Spring Boot 4.1.2, Spring AI 2.1.0 (artifacts spring-ai-client-chat and spring-ai-session-advisor, versions from the Spring AI BOM 2.1.0) and a Java 25 language level, with JDK 27 on the author's machine. Spring AI 2.1.0 declares Spring Framework 7.1.0; the Boot 4.1.2 build resolved Spring Framework 7.0.10, and all 26 tests of the lab passed on that combination, so it works for what this lab uses. Other parts of Spring AI were not tested with it.
Three details differ from older articles you may find. MessageChatMemoryAdvisor and ChatMemory are deprecated since 2.1.0 and slated for removal in 3.0.0. requiresConfirmation and ToolCallDecision are in 2.1.0 and are the supported way to pause for approval. And a ChatModel must return tool-capable options from getOptions() for the ChatClient to carry tools. Re-check the reference before relying on any of this in a later version.
Lesson 4 of 15 · Agentic AI for Java Developers: Build and Ship Agents
Build a tested Spring AI agent in Java: @Tool methods, the tool-calling loop, memory, record output, human approval and call limits, with no API key.
In the rest of this lesson
Under the hood: what the framework sends and loops over
Structured output: the answer as a record
Memory: sessions
Approvals and limits
Observability hook
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.