Turn the 60-line agent loop into a LangChain4j AiServices interface with annotated tools, chat memory and typed answers, tested offline with a fake model.
What you'll learn: how the 60-line agent loop of lesson 2 becomes a LangChain4j AiServices interface with annotated tools, memory and a typed answer, how to run it offline, and when the framework is worth its weight.
The morning after the Parcelo incident (an invented delivery company), you have the agent loop from lesson 2 working. Sixty lines of plain Java, and you understand every one of them. Then a teammate asks why you are not using LangChain4j, a Java library that offers to write that loop for you.
It is a fair question, so this lesson answers it with a lab. You write an interface and annotate some methods. The library writes the rest of the cycle. The single idea: LangChain4j is your agent loop with the plumbing done for you. You describe tools and one method, and it runs the ask, run-tools, answer cycle.
The model in this lab is a script. It implements LangChain4j's real ChatModel interface and plays back fixed replies, so every run is identical and needs no API key or network. The framework code around it is the real library. A real model chooses its own steps and varies between runs, and the lab does not test that.
The idea in one picture
Figure 1. You write an interface; the library writes the agent behind it
How to read this: follow the moving packets out of your code and into the proxy. The proxy is the only thing you talk to. It sends messages to the model, runs the tool methods the model asks for, and keeps the conversation in memory.
TIP
Picture it: an order form in a restaurant. You fill in the form (the interface), hand it over, and a plate arrives. The kitchen (the proxy) decides how to cook it. The analogy stops at the kitchen: here the "chef" in the middle is a language model, and it decides which tools to use on its own.
From the 60-line loop to LangChain4j
Lesson 2 built the loop by hand. Every part of it has a counterpart in LangChain4j 1.24.1. The table lists what I read in the library's classes and sources, and which lab file shows it.
Part of the loop in lesson 2
In LangChain4j 1.24.1
Where to see it
The conversation list (Instruction, User, Assistant, ToolResult)
the ChatModel interface: a model implements doChat(ChatRequest) and returns a ChatResponse holding an AiMessage
ScriptedChatModel
A Tool with a ToolSpec (name, description, typed parameters)
an annotated method (@Tool, @P); the library builds a ToolSpecification from it by reflection
ParceloTools
The Tools registry that refuses unknown names
tools(...) on the builder, and hallucinatedToolNameStrategy for names that are not registered
Runs 2 and 3
Agent.run, the loop
an internal loop in the proxy (the ToolService class)
Under the hood
AgentConfig.maxSteps
maxToolCallingRoundTrips(int), default 100
Run 6
The system prompt
@SystemMessage on the interface method
IncidentAssistant
Validate arguments against the spec before running
not done for object parameters: a missing String arrives as null
Run 3
The Trace
beforeToolExecution and afterToolExecution hooks, plus our model that narrates each call
Scenarios
The list that is the agent's memory
ChatMemory, optional: with none, every call starts fresh
Run 4
Two rows deserve a second look. The validation row is the one place where the framework does less than your 60 lines: lesson 2's loop checks arguments against the spec, and LangChain4j hands the raw value to your method. And memory is opt-in: lesson 2's loop always kept the list, because it was local to one run.
NOTE
On call, 3 a.m.: Dana, an on-call engineer at Parcelo, wired up a first assistant in an afternoon and went home pleased. At 03:12 the model asked for a tool called fetch_dashboard. Nobody had written one. The library's default was to throw, so the whole call died with a runtime exception and the incident got no answer at all. Dana added a handler for unknown tool names the next morning. Invented example.
Build it: tools are annotated methods
A tool is an ordinary Java method with two kinds of label. @Tool gives the tool its name and its description. @P names each parameter and describes it. The model reads these labels and never sees your code.
The four Parcelo read-only tools of lesson 2 are re-implemented here as methods of one class. This lab is a separate Gradle build, so it cannot reuse the plain-Java lab's classes. The data is the same invented incident: the payments-gateway deploy at 02:41 that filled a database pool and slowed checkout-api.
@Tool(name = "get_alert", value = "Returns the text of one alert by its id.")public String getAlert(@P(name = "alert_id", description = "The alert id, for example A-1042") String alertId) {
calls.add("get_alert(" + alertId + ")");
require("alert_id", alertId);
Stringalert= ALERTS.get(alertId);
if (alert == null) thrownewIllegalArgumentException("no alert with id " + alertId);
return"alert " + alertId + ": " + alert;
}
Notice three things:
name = "get_alert" is explicit, so the tool keeps the snake_case name of lesson 2. Without it, the method name getAlert would be used.
@P(name = "alert_id", ...) sets the parameter name the model sees. The docs recommend setting name because Java only keeps real parameter names if the code is compiled with the -parameters flag; the library even logs a warning when it finds arg0 instead of a name.
The method checks its own argument (require). Hold on to that: Run 3 shows why.
/**
* LangChain4j 1.24.1 passes {@code null} to a tool method when the model leaves out a String argument (it throws only for
* primitive parameters), so a tool has to check its own arguments. The message is what the model will read.
*/privatestaticvoidrequire(String name, String value) {
if (value == null || value.isBlank()) thrownewIllegalArgumentException("missing required argument '" + name + "'");
}
The library turns the annotations into a ToolSpecification. This is the text the lab prints for get_alert, which is what the model is sent:
Expected output, captured from a real run (the tool specification built from the annotated method):
What the framework sends the model for get_alert (made from the annotated method):
{"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"]}}
Compare it with the tool in lesson 2: the description, the parameter and the required list are the same, character for character. The annotations carry the same information the hand-written ToolSpec did.
Figure 2. A tool request, and the three doors it can fail at
How to read this: the top row is the happy path and the packet runs along it. The red dashed arrows are the three failures. Each one meets a handler, and the "default" under its name is what LangChain4j 1.24.1 does when you configure nothing.
TIP
Picture it: labels on the drawers of a workshop. The model walks along the wall, reads "get_alert: returns the text of one alert" and asks you to open that drawer. It never looks inside. If the label is vague, it picks the wrong drawer, so write labels for a stranger.
Build it: the interface, the fake model and the wiring
The whole agent interface is one method with a system message:
@SystemMessage("You are an on-call assistant. Find the likely cause of the alert with the tools, then answer in two sentences. "
+ "You may only read. Never change anything.")
String investigate(String question);
There is no class that implements IncidentAssistant. At run time the library creates one (a Java dynamic proxy) and sends the method call through the loop you wrote by hand in lesson 2.
The model needs to be something LangChain4j can call. ChatModel is an interface whose one method a model has to provide is doChat. A real provider module implements it with an HTTP call; ours returns the next scripted reply and records the request it got:
/** The one method a model has to implement: take the conversation and the tool list, return the next message. */@Overridepublic ChatResponse doChat(ChatRequest request) {
requests.add(request);
AiMessagereply= script.apply(request);
narrator.accept("call " + requests.size() + ", " + request.messages().size() + " messages sent -> " + describe(reply));
return ChatResponse.builder().aiMessage(reply).build();
}
A script entry is a plain AiMessage: either text (the end of the loop) or a tool request with an id, a name and the arguments as JSON text. That JSON text is what a real model produces too:
/** A reply that asks for one tool. {@code argumentsJson} is the JSON text a real model would produce. */publicstatic AiMessage asksFor(String id, String tool, String argumentsJson) {
return AiMessage.from(request(id, tool, argumentsJson));
}
Now the wiring for Run 1. The script is the same investigation as in lesson 2: the alert, then two lookups in one reply, then the runbook, then the answer.
static Run investigate() {
List<String> trace = newArrayList<>();
ParceloToolstools=newParceloTools();
ScriptedChatModelmodel= ScriptedChatModel.of(
asksFor("c1", "get_alert", "{\"alert_id\":\"A-1042\"}"),
asksForAll(
request("c2", "query_metric", "{\"service\":\"payments-gateway\",\"metric\":\"db_pool_in_use\"}"),
request("c3", "search_logs", "{\"service\":\"payments-gateway\",\"text\":\"deploy\"}")),
asksFor("c4", "search_runbook", "{\"topic\":\"pool\"}"),
says("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."))
.narratedTo(line -> trace.add(" " + line));
IncidentAssistantassistant= AiServices.builder(IncidentAssistant.class)
.chatModel(model)
.tools(tools)
.afterToolExecution(run -> trace.add(" tool " + run.request().name() + " -> " + run.result()))
.build();
Stringanswer= assistant.investigate("Alert A-1042 is firing. What is going on?");
trace.add(" answer: " + answer);
returnnewRun(trace, model, tools, answer);
}
The builder is the whole configuration: chatModel (who answers), tools (what they may call), and afterToolExecution (a hook we use to print each result). Everything after build() is one ordinary method call.
TIP
Picture it: a flight simulator. The cockpit, the dials and the controls are the real aircraft's. Only the weather is scripted. Our ScriptedChatModel is the scripted weather: AiServices, the tools and the memory are the real library, and the "sky" is a list of replies.
Run it
The lab lives in the spring-labs workspace, so the commands run from there. A test (GoldenRunTest) runs all the scenarios and compares what they print with the golden file.
Expected output, captured from a real run (Run 1; the model is a script):
Run 1. The model investigates and answers
call 1, 2 messages sent -> asks for get_alert {"alert_id":"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
call 2, 4 messages sent -> asks for query_metric {"service":"payments-gateway","metric":"db_pool_in_use"} and 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
call 3, 7 messages sent -> 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).
call 4, 9 messages sent -> final answer
answer: 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.
Read it top to bottom. Each "call" line is the model's side: how many messages the proxy sent and what came back. Each "tool" line is the library running one of your methods. Look at the message counts: 2, 4, 7, 9. They are exactly the counts of lesson 2's Run 1. The two loops send the same conversation, one with 60 lines of your code and one with a library.
The assistant, step by step (interactive when JavaScript is on)
Run 1: the investigation
1. First model call. The proxy sends 2 messages (system message and question) plus the tool specifications. The script replies with a request: get_alert with {"alert_id":"A-1042"}.
2. A tool runs. The library finds get_alert, reads the JSON and calls your method. It returns: alert A-1042: checkout-api p99 latency 4200 ms (SLO 800 ms), error rate 6.1%, firing since 02:47 UTC.
3. Two requests in one reply. Call 2 sends 4 messages. The reply asks for query_metric and search_logs together. Both run: the pool is 50 of 50 in use since 02:44, and the logs show deploy v412 started at 02:41:05.
4. The runbook. Call 3 sends 7 messages and asks for search_runbook with {"topic":"pool"}. The runbook says to check for a deploy and roll it back, which needs on-call approval.
5. The answer. Call 4 sends 9 messages and the script replies with text instead of a request. The loop ends and investigate() returns that text: the v412 deploy exhausted the database pool.
Run 2: bad calls
1. An unknown tool. Call 1 asks for fetch_dashboard. No such tool is registered, so the name strategy returns the text: unknown tool 'fetch_dashboard'. Available tools: get_alert, query_metric, search_logs, search_runbook.
2. Broken JSON. Call 2 asks for get_alert with arguments that stop after the colon. The arguments handler returns the parser's first line: Unexpected end-of-input within/between Object entries.
3. A missing argument. Call 3 asks for get_alert with {}. The library calls the method anyway, and the method's own check answers: missing required argument 'alert_id'.
4. A tool that throws. Call 4 asks for alert A-9999. The method throws and the execution handler returns its message: no alert with id A-9999.
5. Recovery. Call 5 asks for query_metric for checkout-api and gets p99 latency 4200 ms. Call 6 is the final answer: checkout-api p99 latency is 4200 ms, far above its 800 ms SLO.
The first run has no failures, so it only proves the happy path. A real incident is full of the other kind, which is the next section.
When a tool call goes wrong
Models make three kinds of mistake with tools: they ask for a tool that does not exist, they send arguments that do not parse, and they send arguments that parse but make no sense. Lesson 2's loop turned every one of them into a result the model could read. LangChain4j gives you a handler for each, and its defaults differ from lesson 2's.
Figure 3. A tool request arrives: which door does it take?
flowchart TD
accTitle: The decisions the proxy makes for each tool request
accDescr: A tool request first checks whether the tool name is registered. An unknown name goes to the hallucinated tool name strategy, which throws by default. A known name has its JSON arguments read next. Unreadable JSON goes to the arguments error handler, which throws by default. Readable arguments call the Java method. If the method throws, the execution error handler sends the message to the model by default. Otherwise the result text goes back to the model.
Start(["Tool request from the model"])
Q1{"Is the name a registered tool?"}
Q2{"Is the JSON readable?"}
Q3{"Does the method throw?"}
A1["Name strategy: default throws"]
A2["Arguments handler: default throws"]
A3["Execution handler: default sends the message to the model"]
OK["Result text goes back to the model"]
Start --> Q1
Q1 -->|"no"| A1
Q1 -->|"yes"| Q2
Q2 -->|"no"| A2
Q2 -->|"yes"| Q3
Q3 -->|"yes"| A3
Q3 -->|"no"| OK
How to read this: start at the top and follow yes or no. Each box that mentions a default is a place where you choose between ending the call and telling the model what went wrong.
Run 2 configures all three handlers to send the problem back to the model as text. The configuration is the interesting part:
Each handler receives the exception and a context, and returns the text the model will read. The ready-made sendExceptionMessageToLlm() handlers do that with the exception's message; we wrap them only to print a trace line.
Expected output, captured from a real run (Run 2; the model is a script):
Run 2. Bad tool calls come back as results and the model recovers
call 1, 2 messages sent -> asks for fetch_dashboard {"name":"checkout"}
tool fetch_dashboard -> unknown tool 'fetch_dashboard'. Available tools: get_alert, query_metric, search_logs, search_runbook
call 2, 4 messages sent -> asks for get_alert {"alert_id":
arguments error get_alert -> Unexpected end-of-input within/between Object entries
call 3, 6 messages sent -> asks for get_alert {}
tool error get_alert -> missing required argument 'alert_id'
call 4, 8 messages sent -> asks for get_alert {"alert_id":"A-9999"}
tool error get_alert -> no alert with id A-9999
call 5, 10 messages sent -> asks for query_metric {"service":"checkout-api","metric":"p99_latency_ms"}
tool query_metric -> p99 latency 4200 ms now, 610 ms at 02:30, rising since 02:44
call 6, 12 messages sent -> final answer
answer: checkout-api p99 latency is 4200 ms, far above its 800 ms SLO.
Read it against Figure 3. Call 1 is the unknown tool: the strategy answers with a list of valid names. Call 2 is the broken JSON, which the arguments handler explains. Calls 3 and 4, the missing argument and the exception thrown by your method, both reach the execution handler. After four mistakes the scripted model recovers and answers. Each mistake cost one more model call, and the conversation grew each time: 2, 4, 6, 8, 10, 12 messages.
Run 3 shows what happens with no handlers at all:
Expected output, captured from a real run (Run 3; nothing configured):
Run 3. With no handlers configured, the same mistakes end the call with an exception
unknown tool name: RuntimeException: The LLM is trying to execute the 'fetch_dashboard' tool, but no such tool exists. Most likely, it is a hallucination. You can override this default strategy by setting the hallucinatedToolNameStrategy on the AiService (model calls: 1)
arguments not JSON: RuntimeException: com.fasterxml.jackson.core.io.JsonEOFException: Unexpected end-of-input within/between Object entries (model calls: 1)
argument left out: the tool method was called with alert_id = null
An unknown tool name ends the whole investigate() call with an exception, after one model call. The message even tells you which setting to use.
Arguments that are not JSON also end the call. The message is a JSON parser's.
A missing argument does not fail at all. The library called the method with null. The 1.24.1 source only throws when a missing parameter is a primitive such as int. For a String the value arrives as null, whatever @P(required = ...) says. That is why ParceloTools checks its own arguments. Without the check, my first run of this lab sent the model a message about a null key in a hash map, which is not a message anyone wants to feed an agent.
WARNING
The handlers above hand an exception's message to the model, and then to whatever the model writes next. A parser's error message, a stack detail or a SQL error can leak internal details into a conversation. The LangChain4j docs carry the same warning: exception messages are written for developers, and sending them on may expose internal details to the provider, the chat memory and your logs. Write the messages your tools throw for the model to read, and use sendGenericMessageToLlmUnlessVisibleToLlm or your own handler when you cannot trust the exception text. The docs also say the defaults are planned to change in an upcoming release (for tool exceptions, to failing the call unless the exception says what the model may be told), so set the handlers you rely on explicitly.
NOTE
On call, 3 a.m.: Lena wrote a tool that looked up an alert by id and forgot to check for a missing id. The model left the id out once. LangChain4j called her method with null, the lookup threw, and the model received a message about hash codes and a null key. It could not make sense of that and asked for the same call again. Lena added one line to her tool that said what was missing. Invented example, but the hash-code message is the one my first run of this lab produced.
Memory and typed answers
By default every call is a fresh start: two messages, the system message and the question. To keep a conversation, give the builder a ChatMemory. Run 4 asks two questions through one memory.
ChatMemorymemory= MessageWindowChatMemory.withMaxMessages(20);
ScriptedChatModelmodel= ScriptedChatModel.of(
asksFor("c1", "get_alert", "{\"alert_id\":\"A-1042\"}"),
says("checkout-api is slow: p99 latency 4200 ms."),
asksFor("c2", "get_alert", "{\"alert_id\":\"A-1043\"}"),
says("inventory-sync has a queue backlog of 18000."))
.narratedTo(line -> trace.add(" " + line));
IncidentAssistantassistant= AiServices.builder(IncidentAssistant.class)
.chatModel(model)
.chatMemory(memory)
.tools(newParceloTools())
.build();
Expected output, captured from a real run (Run 4; the model is a script):
Run 4. Chat memory: the second question arrives with the first one's messages
question 1
call 1, 2 messages sent -> asks for get_alert {"alert_id":"A-1042"}
call 2, 4 messages sent -> final answer
question 2
call 3, 6 messages sent -> asks for get_alert {"alert_id":"A-1043"}
call 4, 8 messages sent -> final answer
memory now holds 9 messages: [SYSTEM, USER, AI, TOOL_EXECUTION_RESULT, AI, USER, AI, TOOL_EXECUTION_RESULT, AI]
Question 2 arrives with 6 messages, not 2: the five stored by question 1 (system message, question, the tool request, the tool result, the answer) plus the new question. The memory ends with 9 messages, and the tool request and result are stored with the rest. That is the same growing list you saw in lesson 2, now owned by the library.
Figure 4. What the model receives for the second question
How to read this: the proxy adds the stored history in front of the new question and sends all six messages. After the answer comes back, the proxy stores the new messages, and the window drops the oldest ones when there are too many.
MessageWindowChatMemory.withMaxMessages(n) keeps the last n messages. The 1.24.1 source and the memory docs agree on the rules that matter. The system message is kept when old messages are evicted. If an AiMessage with tool requests is evicted, the tool results left without it go too, because some providers reject a result with no request. And a message counts as one however long it is, which the docs call suited to prototypes; a token-based window exists for real budgets. The lab's test aSmallWindowForgetsTheOldestMessagesButKeepsTheSystemMessage proves the first rule.
TIP
Picture it: a whiteboard with room for ten lines. To write a new line you wipe the oldest one, except the title at the top, which stays pinned. The analogy has one trap: a tool call uses several lines at once (the request and each result), so ten lines can hold less than one investigation.
NOTE
On call, 3 a.m.: Ravi's assistant remembered the last ten messages. One investigation used nine, because every tool request and result is a message. By the time he asked a follow-up, the alert id from his first question had been wiped from the whiteboard, and the model asked him what alert he meant. Ravi raised the window and started trimming tool output. Invented example.
The other feature is the return type. Declare a record, and the library asks the model for JSON and parses the answer into it:
@Description("The result of an incident investigation")publicrecordDiagnosis(
@Description("the most likely cause, one sentence") String likelyCause,
@Description("the suggested next action") String suggestedAction,
@Description("true when the action needs on-call approval")boolean needsApproval) {}
@SystemMessage("You are an on-call assistant. Use the tools to find the likely cause of the alert. You may only read.")
Diagnosis diagnose(String question);
Expected output, captured from a real run (Run 5; the model is a script):
Run 5. A typed answer: the model replies with JSON and AiServices returns a record
call 1, 2 messages sent -> asks for search_runbook {"topic":"pool"}
call 2, 4 messages sent -> final answer
the user message the model received:
| Alert A-1042 is firing. What is the cause?
| You must answer strictly in the following JSON format: {
| "likelyCause": (the most likely cause, one sentence; type: string),
| "suggestedAction": (the suggested next action; type: string),
| "needsApproval": (true when the action needs on-call approval; type: boolean)
| }
returned: Diagnosis[likelyCause=payments-gateway deploy v412 exhausted the database pool, suggestedAction=roll back payments-gateway to v411, needsApproval=true]
Look at "the user message the model received". The library appended format instructions to your question, built from the record and its @Description annotations. Our fake model does not advertise the JSON-schema capability, so the library falls back to the prompt. Per the 1.24.1 source, a model that does advertise it (RESPONSE_FORMAT_JSON_SCHEMA) gets a JSON schema response format instead. Either way your code receives a Diagnosis, and a real model that answers with something else is the reader's problem to test (lesson 12).
Under the hood: what AiServices does with an interface
Everything above is one method call. This is the path through the library, read from the 1.24.1 sources and confirmed by the runs.
Figure 5. One call to investigate, message by message
sequenceDiagram
accTitle: One call to the assistant, message by message
accDescr: Your code calls investigate on the proxy. The proxy sends the system message, the question and the tool specifications to the chat model. The model replies with a request for get_alert. The proxy calls the Java method and sends the result back to the model with the earlier messages. The model replies with final text and the proxy returns it to your code.
participant U as Your code
participant P as Assistant proxy
participant M as ChatModel
participant T as ParceloTools
U->>P: investigate("Alert A-1042 is firing...")
P->>M: chat(system, question, tool specs)
M-->>P: AiMessage: request get_alert
P->>T: getAlert("A-1042")
T-->>P: result text
P->>M: chat(system, question, request, result, tool specs)
M-->>P: AiMessage: final text
P-->>U: the String answer
How to read this: time runs downward. The two arrows between proxy and model are the two model calls of a one-tool run; everything between them is the loop that lesson 2 wrote by hand.
build() creates a proxy.AiServices uses a Java dynamic proxy (Proxy.newProxyInstance) that implements your interface. A call to investigate is intercepted; there is no generated source file to look at.
Tool specifications come from reflection. For each object given to tools(...), the library finds the @Tool methods and builds a ToolSpecification from the method's name, the annotations and the parameter types. It also remembers how to call each method.
The messages are assembled. The system message (from @SystemMessage), the stored memory if there is any, and your question become the list sent to the model. For a record return type, format instructions are added to the question.
The model is called, and the loop starts. The request carries the messages and the tool specifications. If the reply has no tool requests, the loop ends. If it has some, each is looked up, its JSON is read, the method runs, and a ToolExecutionResultMessage is added to the conversation. Then the model is called again.
A round-trip counter guards the loop. The counter is checked for every reply the model sends. When it is spent, the call throws, which is Run 6. The method's documentation says the limit counts replies that contain tool calls, but the 1.24.1 loop also checks it for the reply that would have been the final answer: with a limit of 3, two tool replies and an answer succeed, while three tool replies and an answer throw (a lab test checks both). Treat the limit as one more than the tool rounds you want to allow.
The last text is converted to your return type and returned from the method.
Expected output, captured from a real run (Run 6; the model is a script):
Run 6. A model that never stops is cut off by maxToolCallingRoundTrips
RuntimeException: Something is wrong, exceeded 3 tool calling round trips (maxToolCallingRoundTrips)
model calls: 4, tool calls that ran: 3
The scripted model asks for get_alert every time and never answers. With maxToolCallingRoundTrips(3) the tools ran three times and the model was called four times before the exception. The fourth reply is the one that was refused: the library receives it, finds the counter spent and throws. That is the step limit of lesson 2 in one builder method, with a default of 100. With a growing conversation, 100 round trips is a cost problem long before it is a safety net, so set your own.
Figure 6. The loop inside the proxy, with its budget
How to read this: the packet goes messages, model, tools and round again. Every reply passes the counter. The red dashed arrow is the way out when the model never settles on an answer.
A note on logging, because you will see it: the lab prints SLF4J: No SLF4J providers were found on standard error. LangChain4j logs through SLF4J and the lab does not add a logging backend. A real application adds one, and then the library's warning about a tool error that went to the model becomes visible in your logs.
The experimental agentic module
LangChain4j also has a module named langchain4j-agentic, and it is worth knowing what it is and what it is not. Here is what I could verify. The bill of materials pins it to 1.24.1-beta34, a beta version next to the stable 1.24.1 of the core. The official agents page says: "the whole module has to be considered experimental and is subject to change in future releases."
The page describes agents declared as interfaces with an @Agent method, a shared state object called AgenticScope, and workflows that combine agents: sequential, loop, parallel, conditional, and a supervisor that asks a chat model which sub-agent to run next.
This lesson builds no lab for it. A module that its own documentation calls experimental is a poor foundation for a course exercise, and the patterns it names are the ones the course builds in plain Java: workflows and multi-agent. Read it as a roadmap, and pin the beta version exactly if you try it.
LangChain4j and Spring AI side by side
Lesson 4 builds the same assistant with Spring AI. Here is a comparison drawn only from facts I verified: LangChain4j 1.24.1 by running it and reading its sources, Spring AI 2.1.0 by reading its published sources and POM files (I did not run it for this lesson). Where I did not check something, the table says nothing.
Question
LangChain4j 1.24.1
Spring AI 2.1.0
How is a tool declared?
@Tool(name, value) on a method, @P(name, description) on parameters
@Tool(name, description, returnDirect, requiresConfirmation, resultConverter) on a method, @ToolParam(description, required) on parameters
How are tools attached?
AiServices.builder(...).tools(Object...)
tools(Object...) on the ChatClient request
How do I get a typed answer?
the return type of the interface method
entity(Class) on the call
Is memory on by default?
no: you pass a ChatMemory; MessageWindowChatMemory.withMaxMessages(n) has no default size
a MessageWindowChatMemory exists with a default of 20 messages (DEFAULT_MAX_MESSAGES)
What happens when a tool throws?
default: the exception message goes to the model (and a warning is logged)
default: for a RuntimeException cause the message goes to the model; a cause that is not a RuntimeException is rethrown
What limits the loop?
maxToolCallingRoundTrips, counted in model replies, default 100
DefaultToolCallingManager has default limits of 40 calls per tool and 150 tool calls in total, counted in calls
Can a tool require a person's confirmation?
not as a setting: I found nothing like it in the langchain4j and langchain4j-core sources
@Tool(requiresConfirmation = true), added in 2.1.0: the loop pauses on such a call
What else must be on the classpath?
the Gradle runtime classpath of this lab has no Spring jar: Jackson, SLF4J, OpenNLP, Mutiny Zero and JSpecify
the POMs of spring-ai-model and spring-ai-client-chat list spring-messaging, spring-context and Reactor
How stable is the agent layer?
langchain4j-agentic is beta and documented as experimental
not checked
Three of these rows are differences that affect design. Rounds versus calls means a limit of 100 in LangChain4j is not comparable to a limit of 150 in Spring AI. The confirmation setting is the biggest gap if you plan write tools, and the guardrails lesson shows how to build a gate yourself. And the error defaults are not the same, so a lab that passes on one framework tells you nothing about the other.
The older post Spring AI vs LangChain4j compares them by stack and taste, which is the right frame for the first decision. Its description of LangChain4j's "chain" primitives is out of date against 1.24.1: the ConversationalChain class is documented in its own source with "Chains are not going to be developed further, it is recommended to use AiServices instead."
When plain Java beats both
A framework is a trade. You give up some control and some understanding, and you get less code. Here is how I weigh it for an agent with a handful of tools.
Plain Java wins when you want to own the details. Lesson 2's loop validates arguments against the spec, truncates tool output, and traces every step in a format you chose. In LangChain4j you can add all of these, but you work through hooks and handlers rather than editing the loop.
Plain Java wins when the framework is moving faster than your release cycle. In this lesson alone, the docs list a @Tool(description = ...) field that the 1.24.1 class does not have, and maxSequentialToolsInvocations is deprecated in favour of maxToolCallingRoundTrips. Neither is a flaw, but both are the cost of a fast-moving API.
A framework wins when you would otherwise write provider code. The BOM lists separate modules for OpenAI, Anthropic, Ollama, Mistral, Bedrock and Azure OpenAI. HTTP clients, streaming, JSON schemas per provider and memory stores are real work that you do not have to do.
A framework wins when the agent is one feature of a bigger service that already uses its conventions, which is the argument for Spring AI inside a Spring Boot application.
Figure 7. A rule of thumb for choosing (this course's judgement, not a law)
flowchart TD
accTitle: Choosing between plain code, a plain Java loop, Spring AI and LangChain4j
accDescr: First ask whether the steps can be written down in advance. If so, write plain workflow code without an agent. If not, ask whether one agent with a few tools is enough and whether you want to read every line. If so, use the plain Java loop. If not, ask whether the service is a Spring Boot application. If so, use Spring AI. If not, use LangChain4j. In every case add budgets and tests.
Start(["A task for a model with tools"])
Q1{"Can you write the steps down in advance?"}
Q2{"A few tools, and you want to read every line?"}
Q3{"Is the service a Spring Boot application?"}
A1["Plain workflow code, no agent"]
A2["Plain Java loop, lesson 2"]
A3["Spring AI, lesson 4"]
A4["LangChain4j, this lesson"]
Z["Either way: budgets, handlers and tests"]
Start --> Q1
Q1 -->|"yes"| A1
Q1 -->|"no"| Q2
Q2 -->|"yes"| A2
Q2 -->|"no"| Q3
Q3 -->|"yes"| A3
Q3 -->|"no"| A4
A2 --> Z
A3 --> Z
A4 --> Z
How to read this: start at the top and follow yes or no. The bottom box is common to all three agent routes.
TIP
Picture it: a nail gun against a hammer. For a shed, the nail gun is faster and the hammer teaches you where the nails go. Learn the hammer first (lessons 1 and 2). Then reach for the nail gun when you have a house to build, and keep the hammer in the truck for the places the gun cannot reach.
Break it
I ran each of these experiments on this lab, restored the code and re-ran the tests.
1. Delete the argument check. In ParceloTools.getAlert, delete the line require("alert_id", alertId); and run ./gradlew :labs:agent-langchain4j:test. badCallsComeBackAsTextAndTheModelRecovers fails. When I wrote the new output to the golden file to see it, exactly one line had changed. Where the model used to read missing required argument 'alert_id', it now read Cannot invoke "Object.hashCode()" because "pk" is null. LangChain4j passed null, a map lookup threw, and the library did what it was configured to do: it sent that message to the model. Nothing in the framework warned you.
2. Lower the round-trip limit. In Scenarios.stubborn() change maxToolCallingRoundTrips(3) to 1. The run now ends with exceeded 1 tool calling round trips, after 2 model calls and 1 tool call. The pattern from Run 6 holds: the tools run as many times as the limit, and the model is called once more than that. GoldenRunTest fails, because it compares the whole report with the golden file. AssistantTest still passes: its round-trip test builds its own assistant.
3. Take the memory away. In Scenarios.memory() delete the line .chatMemory(memory). The second question now sends 2 messages instead of 6 (call 3, 2 messages sent), and the memory object you kept a reference to stays empty (memory now holds 0 messages). Only the golden comparison and a test that looks at the messages sent would notice: the assistant itself does not complain, it forgets and answers every question as if it were the first. That silence is why memoryCarriesTheFirstQuestionIntoTheSecond is worth having.
Restore each change and run the tests again before you move on.
In practice: Parcelo
In the running example, TriageDesk is the on-call assistant that investigates alerts. With LangChain4j, its read side is exactly what this lab built: one interface, one class of read-only tool methods, a memory per on-call engineer, and a typed Diagnosis for the dashboard.
Figure 8. TriageDesk's read side, and the side that needs a person
How to read this: the solid path is what the lab implements. The dashed arrow is the part of the story that stays outside the model's reach: a proposed fix goes to a person, and only an approved fix reaches the tools that change production.
Two design decisions follow from the lab. First, the assistant gets only the four read tools. restart_service and roll_back exist in Parcelo's plain-Java lab, but they are not methods of ParceloTools, so the model cannot call them: Run 2 shows what a request for an unregistered tool does. Second, the final answer says "roll back to v411, which needs on-call approval" and stops there. Putting the approval in code, not in the prompt, is the subject of lesson 11.
Architect's notes
Keep the interface thin. The @Tool methods are an API for a model, so they should be few, narrow and well described. Do not expose your service layer by annotating every method.
Treat the handlers as part of the design. Decide, tool by tool, whether a failure should end the call or be explained to the model. Set the choice in code; the docs say the defaults may change.
Own your argument checks. For object parameters the library does not enforce required, so every tool validates its own input and throws a message written for a model to read.
Budget the loop explicitly.maxToolCallingRoundTrips defaults to 100, and each round trip resends the whole conversation. A cap near what your task needs is cheaper and safer. Count the cost with the LLM cost estimator.
Memory is per conversation, not per application. One chatMemory(...) is shared by every call on that assistant. Use a memory provider keyed by a memory id when several users share the service, and watch what you keep, because messages can contain customer data.
A fake model proves the plumbing. These tests show that tools run with the right arguments and the model is called the expected number of times. They say nothing about how a real model chooses. Pair them with evaluations (lesson 12).
Pin versions. The stable core and the beta agent module share one release number in the BOM and move at different speeds.
Common mistakes
Mistake
Fix
Relying on @P(required = true) to reject a missing argument
The 1.24.1 source passes null for a missing String. Check every argument in the tool and throw a clear message.
Leaving out @P(name = ...) and compiling without -parameters
The model sees arg0. Name every parameter, as ParceloTools does.
Leaving all error defaults and a model asks for an unknown tool
The whole call throws (Run 3). Set hallucinatedToolNameStrategy, or catch the exception on purpose.
Sending raw exception messages to the model
Write messages for the model, or use a generic message for errors you cannot control.
A window of messages that is too small
A tool request and its result are two messages. Size the window by what one investigation uses, or keep a summary.
One chatMemory(...) shared by every user
Use chatMemoryProvider and @MemoryId so each conversation has its own memory.
Keeping the default of 100 round trips
Set maxToolCallingRoundTrips to what your task needs.
Reading a passing fake-model test as proof about a real model
The script chose every step. Add evaluations against a real model before you trust the behaviour.
IMPORTANT
Remember this:
An AiServices interface is the 60-line loop with the plumbing done for you: the same messages, the same tool calls, the same step limit.
The library does not validate missing arguments for object parameters. Your tool must.
Every error default is a decision. Unknown tool names and unreadable arguments end the call unless you say otherwise.
A memory is a window of messages, and tool calls use several of them.
A fake model proves the plumbing, never the model.
Key takeaways
AiServices.builder(...) turns an interface into an agent: a proxy that sends messages, runs your @Tool methods and returns the final text.
The loop is the same as lesson 2: the lab's message counts (2, 4, 7, 9) match the plain-Java run.
Annotations build the tool specification the model reads; the description and parameters are the same as the hand-written ones.
Unknown tool names, unreadable arguments and tool exceptions each have a handler, and the defaults differ per kind.
A missing String argument arrives as null in 1.24.1, so tools validate their own input.
Memory is optional and windowed; typed answers come from the return type.
langchain4j-agentic is a beta, experimental module and this lesson builds no lab for it.
Practice exercises
Starter. In Scenarios.stubborn() change maxToolCallingRoundTrips(3) to 1. Predict the model-call count and the tool-call count, run ./gradlew :labs:agent-langchain4j:test, and fix the assertion in AssistantTest.theRoundTripLimitStopsAModelThatNeverAnswers after you understand the numbers.
Intermediate. Replace the single chatMemory(...) in Scenarios.memory() with a chatMemoryProvider and a @MemoryId parameter on a new interface method, so that two on-call engineers get separate histories. Write a test that asks a question as each engineer and checks the messages sent to the model.
Advanced. Run the same investigation through the plain-Java Agent of lesson 2 and through IncidentAssistant, and write a test that compares the two traces line by line (tool names, arguments and message counts). List every difference you find in how the two handle a missing argument, then decide which behaviour you want in production.
Compiled and run against LangChain4j 1.24.1 on 2026-12-03, through the bill of materials dev.langchain4j:langchain4j-bom:1.24.1 (Maven Central lists it as the latest release, last updated 2026-11-26) and the modules langchain4j and langchain4j-core, both stable at 1.24.1. Java: JDK 25 with --release 25. Spring AI facts in the comparison come from the 2.1.0 sources on Maven Central, read, not run.
Where the docs and the library differ, the library won. The Tools page describes a description field on @Tool; the 1.24.1 @Tool annotation has value (and name, returnBehavior, searchBehavior, metadata). maxSequentialToolsInvocations exists in 1.24.1 but is marked deprecated in favour of maxToolCallingRoundTrips. langchain4j-agentic is pinned to 1.24.1-beta34 by the BOM and described as experimental by its docs. Re-check all of this against the release you use.
Enroll to keep reading
Lesson 5 of 15 · Agentic AI for Java Developers: Build and Ship Agents
Turn the 60-line agent loop into a LangChain4j AiServices interface with annotated tools, chat memory and typed answers, tested offline with a fake model.
In the rest of this lesson
Run it
When a tool call goes wrong
Memory and typed answers
Under the hood: what AiServices does with an interface
The experimental agentic module
LangChain4j and Spring AI side by side
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.