Integrating Jev via REST with Java and Spring RestClient

by Horațiu Dan

From the Playground to code

A previous article introduced TypeSafe Jev, a System One model that answers questions about a piece of text with typed values and probabilities instead of generated prose. It covered the three primitives, noul (a yes/no probability), choice (one option out of a fixed set) and score (a position on an ordered scale) and tuned a set of three questions about code review comments in the TypeSafe Playground.

This article moves the same questions into a Java application. The integration is deliberately plain: no SDK, no AI framework, just the HTTP API and Spring’s RestClient. The result is a small Spring Boot 4 project with four parts, each of which gets a section below:

  • a handful of Java records that mirror the request and response JSON
  • a RestClient bean configured from application.yaml
  • a thin JevClient that sends a state and a map of questions in one call
  • a CommandLineRunner that asks the three code review questions about three comments and prints the answers

Every snippet below is taken unchanged from the accompanying project, jev-spring-intro (Resource 6). It is built with Spring Boot 4.1 on Java 25, although Java 21 is the practical minimum here.

The REST contract

Everything the client needs is one endpoint, authenticated with the API key as a bearer token (Reference 1).

POST https://api.typesafe.ai/v1/systemone

The request body has three members: the model name, the state to judge and a questions object keyed by names that the caller picks. The response echoes the model that actually served the call and returns an answers object with the same keys, plus a usage object with the token counts.

MemberRequestResponse
modelModel name, for example jev-latestConcrete version that answered, for example jev-1.13.0
stateAny JSON value: a string, an object, an arrayNot returned
questions / answersQuestion name mapped to a question with a type, instructions and criteriaQuestion name mapped to an answer with the same type
usageNot sentinput_tokens and output_tokens

The type discriminator is what makes the contract typed:

  • A noul question comes back as {"type": "noul", "noul": 0.95}.
  • A choice question comes back with the “winning” choice, a probabilities map over every option and a confidence.
  • A score question comes back with the weighted score, a legend that maps each level index to its description, the probabilities per level and a confidence.

On the Java side this discriminator maps naturally onto a sealed interface with one record per type, which is the subject of the next sections.

Project setup

The project is a standard Spring Boot application with a single production dependency, the RestClient starter. Spring Boot 4 split the former web starter into smaller pieces, so a client-only application no longer pulls in an embedded server or Spring MVC.

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.1.1</version>
</parent>
<properties>
<java.version>25</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-restclient</artifactId>
</dependency>
</dependencies>

The connection settings live in application.yaml. The API key is read from the TYPESAFE_API_KEY environment variable, the same one the previous article recommended for the Playground key, so it never lands in the repository. The model is jev-latest, an alias that the API resolves to a concrete version. The response’s own model field reports which one actually answered.

jev:
base-url: https://api.typesafe.ai
api-key: ${TYPESAFE_API_KEY:}
model: jev-latest

A small record binds these three values. @ConfigurationPropertiesScan on the application class registers it, so there is no extra configuration class.

@ConfigurationProperties(prefix = "jev")
public record JevProperties(String baseUrl, String apiKey, String model) {}

Modelling the contract in Java

The JSON contract maps onto four records and two sealed interfaces. Records are immutable, serialize with Jackson without any configuration and allow validation in a compact constructor, so an invalid request fails in the application before any HTTP call is made.

Questions

Question is a sealed interface with one record per primitive. The @JsonTypeInfo annotation tells Jackson to write a type property and each @JsonTypeName supplies its value, so a Question.Noul serializes with "type": "noul" without the record having to carry that field. The compact constructors enforce what the API would otherwise reject: a noul needs exactly the true and false criteria, a choice needs at least one option and a score needs at least one level.

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(Question.Noul.class),
@JsonSubTypes.Type(Question.Choice.class),
@JsonSubTypes.Type(Question.Score.class)
})
public sealed interface Question {
@JsonTypeName("noul")
record Noul(String instructions, Map<String, String> criteria) implements Question {
public Noul {
if (instructions == null || instructions.isEmpty()) {
throw new IllegalArgumentException("instructions shall not be null or empty");
}
if (criteria == null || criteria.size() != 2 ||
!criteria.keySet().containsAll(Set.of("true", "false"))) {
throw new IllegalArgumentException("criteria keys must be \"true\" and \"false\"");
}
}
}
@JsonTypeName("choice")
record Choice(String instructions, Map<String, String> criteria) implements Question {
// validation omitted
}
@JsonTypeName("score")
record Score(String instructions, List<String> criteria) implements Question {
// validation omitted
}
}

The three records differ only in the shape of criteria: a map with two fixed keys, a map of option names to descriptions and an ordered list of levels. That difference is exactly the one the previous article’s primitives section described, now enforced by the compiler.

Request

JevRequest is the body of the POST. The state is typed as Object on purpose: the API accepts any JSON value, so a caller can pass a string, a record or a map and Jackson serializes whatever it gets. The questions map uses names chosen by the caller. These names are not seen by the model, which is why the keys here are only used to look the answers up later.

public record JevRequest(String model, Object state, Map<String, Question> questions) {
public JevRequest {
if (model == null || model.isEmpty()) {
throw new IllegalArgumentException("model shall not be null or empty");
}
if (state == null) {
throw new IllegalArgumentException("state shall not be null");
}
if (questions == null || questions.isEmpty()) {
throw new IllegalArgumentException("questions shall not be null or empty");
}
}
}

Answers

Answer mirrors Question on the way back. Here Jackson reads the type property instead of writing it, so the subtype names are declared in @JsonSubTypes and Jackson picks the record to instantiate. Each record holds exactly the fields the API documents for that type, with Map<String, Double> for the probability distributions and Map<String, String> for the score legend, whose keys are the level indexes as strings.

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Answer.Noul.class, name = "noul"),
@JsonSubTypes.Type(value = Answer.Choice.class, name = "choice"),
@JsonSubTypes.Type(value = Answer.Score.class, name = "score")
})
public sealed interface Answer {
record Noul(double noul) implements Answer {}
record Choice(String choice,
Map<String, Double> probabilities,
double confidence) implements Answer {}
record Score(double score,
Map<String, String> legend,
Map<String, Double> probabilities,
double confidence) implements Answer {}
}

JevResponse wraps the answers and the usage. Jackson’s default naming is camel case, so the two token counts carry a @JsonProperty to match the API’s snake case. The three accessors at the bottom are a convenience: when the caller knows which type a question had, response.noul("blocking") saves a cast at every call site.

public record JevResponse(String model, Map<String, Answer> answers, Usage usage) {
public record Usage(@JsonProperty("input_tokens") int inputTokens,
@JsonProperty("output_tokens") int outputTokens) {
}
public Answer.Noul noul(String questionId) {
return (Answer.Noul) answers.get(questionId);
}
public Answer.Choice choice(String questionId) {
return (Answer.Choice) answers.get(questionId);
}
public Answer.Score score(String questionId) {
return (Answer.Score) answers.get(questionId);
}
}

The client: Spring RestClient

RestClient is the synchronous, fluent HTTP client that Spring Framework 6.1 introduced as the successor of RestTemplate (Reference 2). Spring Boot auto-configures a RestClient.Builder with the application’s Jackson ObjectMapper and its HTTP settings already applied (Reference 3), so the only thing left to do is to inject the builder and fix the parts that are the same for every call: the base URL and the authorization header.

@Component
public class JevClient {
private final JevProperties properties;
private final RestClient restClient;
public JevClient(JevProperties properties,
RestClient.Builder builder) {
this.properties = properties;
this.restClient = builder
.baseUrl(properties.baseUrl())
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + properties.apiKey())
.build();
}
public JevResponse ask(Object state, Map<String, Question> questions) {
return restClient.post()
.uri("/v1/systemone")
.contentType(MediaType.APPLICATION_JSON)
.body(new JevRequest(properties.model(), state, questions))
.retrieve()
.body(JevResponse.class);
}
}

The whole integration is the ask method. It builds a JevRequest from the configured model, the caller’s state and the caller’s questions, posts it as JSON and asks RestClient to deserialize the body into a JevResponse. Jackson handles the type discriminators in both directions, so a caller receives a Map<String, Answer> whose values are already Answer.Noul, Answer.Choice or Answer.Score instances.

Asking the three questions from Java

PrimitivesRunner is a CommandLineRunner that repeats the Playground experiment from the previous article in code. The three code review comments become the states and the three questions, a noul, a choice and a score, are declared once as a Map<String, Question> and sent with every comment. The Map.of and List.of literals read almost like the JSON they produce.

private static final List<String> REVIEW_COMMENTS = List.of(
"This builds the SQL query by concatenating `userId` from the request, which allows SQL injection. "
+ "Please switch to a PreparedStatement before we merge.",
"Nit: I'd rename `tmp` to `pendingOrders` so the loop reads better. Not a blocker.",
"Did you even run this? The cache is never invalidated, so users will see stale prices."
);
private static final Map<String, Question> QUESTIONS = Map.of(
// Noul: the probability that a yes/no condition holds
"blocking", new Question.Noul(
"Does this code review comment require a change before the pull request can be merged?",
Map.of("true", "Points out a defect or risk that must be fixed, or explicitly asks for a change before merging",
"false", "An optional suggestion, nit, question or praise that does not block the merge")),
// Choice: exactly one option, with a probability distribution over all of them
"category", new Question.Choice(
"What is the main concern of this code review comment?",
Map.of("bug", "Incorrect behavior, a logic error or a missing case",
"security", "A vulnerability such as injection, leaked secrets or missing authorization",
"performance", "Speed, memory or resource usage",
"readability", "Naming, formatting, structure or style",
"other", "Anything else, such as tests, documentation or a question")),
// Score: a position on ordered levels; the value can fall between two levels
"tone", new Question.Score(
"How constructive is the tone of this code review comment towards the author?",
List.of("Hostile: insults or mocks the author",
"Curt: dismissive or sarcastic, no explanation",
"Neutral: states the problem without explaining or suggesting a fix",
"Constructive: explains the problem and suggests a fix",
"Very constructive: explains the problem, suggests a fix and is encouraging")));

The run loop is one call per comment.

@Override
public void run(String... args) {
StringBuilder out = new StringBuilder("\nJev primitives playground\n");
for (String comment : REVIEW_COMMENTS) {
JevResponse response = jevClient.ask(comment, QUESTIONS);
out.append("\n\"").append(comment).append("\"\n");
out.append(describe("blocking", response));
out.append(describe("category", response));
out.append(describe("tone", response));
out.append(" tokens %d in, %d out%n".formatted(
response.usage().inputTokens(), response.usage().outputTokens()));
}
log.info(out.toString());
}
private static String describe(String questionId, JevResponse response) {
var answer = response.answers().get(questionId);
return switch (answer) {
case Answer.Noul noul ->
" %-9s noul %.2f%n"
.formatted(questionId, noul.noul());
case Answer.Choice choice ->
" %-9s choice %s (confidence %.2f) %s%n"
.formatted(questionId, choice.choice(), choice.confidence(), choice.probabilities());
case Answer.Score score ->
" %-9s score %.2f / %d (confidence %.2f) %s%n"
.formatted(questionId, score.score(), score.legend().size() - 1, score.confidence(), score.probabilities());
};
}

This is the division of labor the previous article described. Jev supplies three judgments per comment; the Java code decides what to do with them. In a real tool the describe method would be replaced by rules such as if (response.noul("blocking").noul() > 0.8) to hold a merge, or a check on score.confidence() to send ambiguous cases to a person. The thresholds live in code, where they can be tested and tuned.

Running it

With the API key exported, the application starts, runs the three requests and stops. Against the version that jev-latest resolved to, it printed the following.

export TYPESAFE_API_KEY=...
./mvnw spring-boot:run

Jev primitives playground
"This builds the SQL query by concatenating `userId` from the request, which allows SQL injection. Please switch to a PreparedStatement before we merge."
blocking noul 0.98
category choice security (confidence 1.00) {bug=0.0, security=1.0, performance=0.0, readability=0.0, other=0.0}
tone score 3.03 / 4 (confidence 0.97) {0=0.0, 1=0.0, 2=0.0, 3=0.97, 4=0.03}
tokens 605 in, 84 out
"Nit: I'd rename `tmp` to `pendingOrders` so the loop reads better. Not a blocker."
blocking noul 0.04
category choice readability (confidence 1.00) {bug=0.0, security=0.0, performance=0.0, readability=1.0, other=0.0}
tone score 3.45 / 4 (confidence 0.62) {0=0.0, 1=0.0, 2=0.0, 3=0.55, 4=0.45}
tokens 596 in, 86 out
"Did you even run this? The cache is never invalidated, so users will see stale prices."
blocking noul 0.86
category choice bug (confidence 0.99) {bug=0.99, security=0.0, performance=0.0, readability=0.0, other=0.01}
tone score 1.30 / 4 (confidence 0.72) {0=0.02, 1=0.72, 2=0.21, 3=0.05, 4=0.0}
tokens 593 in, 84 out

The numbers match the Playground results of the previous article to within a few hundredths:

  • the SQL injection comment is blocking, security and constructive
  • the naming nit is not blocking, readability and split between Constructive and Very constructive
  • the stale cache comment is blocking, a bug and curt

The nit’s tone is the case the previous article warned about (Reference 4): a score of 3.45 says little on its own, and the 0.62 confidence is what tells code that the comment sits between two levels rather than firmly on one.

The small differences, for example 0.04 instead of 0.05 for the nit’s blocking, are the expected variation between runs and between the model versions behind jev-preview and jev-latest.

Each request costs about 600 input tokens, almost all of them the question definitions, which is the price of sending the full criteria on every call.

Conclusion

Integrating Jev from Java needs no SDK. One endpoint, one bearer header and a request body with three members are enough, and Spring’s RestClient reduces the call to a handful of fluent lines.

The work that remains is modelling, which has been easily addressed with Java records and sealed interfaces, which fit the contract closely.

The questions tuned in the Playground moved into code unchanged and returned the same judgments, which is the workflow the previous article suggested: design and tune in the Playground, then ship the JSON as Java literals.

From here the natural next steps are to wrap the typed answers in domain rules with explicit thresholds, to add error handling and timeouts on the builder for production use and to keep the questions under test so that a reworded criterion is a deliberate change rather than an accident.

References

[1] – TypeSafe HTTP API

[2] – Spring Framework RestClient

[3] – Spring Boot Calling REST Services

[4] – TypeSafe Primitives (Questions) and Confidence

[5] – The previous article, Introducing TypeSafe Jev: Typed Judgments as Programming Primitives

[6] – Article source code

[7] – Picture was taken in Zakynthos, Greece

Hosted Code Interpreter in Spring AI: Letting OpenAI Write and Run the Python via the Responses API

by Horațiu Dan

LLMs are good at explaining how to compute something and surprisingly unreliable at actually computing it. Ask for an estimate that involves a division, a rounding rule and a confidence interval and the response will be convincing while the numbers are not quite right. The standard fix is to let the model write code and have something else execute it.

OpenAI’s hosted Code Interpreter does exactly that, inside a single API request: the model writes Python, OpenAI runs it in a sandboxed container, the printed output is fed back to the model and the model answers using the real result. Nothing executes on our side.

Spring AI 2.1.0-RC1 adds first-class support for this capability through its new OpenAI Responses chat model. This article shows how little is needed to turn it on in a Spring Boot application and why it requires the Responses API rather than Chat Completions. Finally, it walks through one full request and response as captured by a custom logging advisor, so that the generated Python, its execution output and the final answer are all visible.

The complete POC is a small command-line application. Its only job is to send one problem statement to the model and print the solution.

Setting it up

Three things are needed: the dependency, four configuration properties and an ordinary ChatClient.

Dependency

The project builds on Spring Boot 4.1.2 with Java 25 and imports the Spring AI BOM at version 2.1.0-RC1. The single runtime dependency is the OpenAI starter.

<properties>
<java.version>25</java.version>
<spring-ai.version>2.1.0-RC1</spring-ai.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

Configuration

This is the whole of application.properties file.

spring.ai.openai.api-key=${OPEN_AI_API_KEY}
# use responses API
spring.ai.openai.chat.api=responses
# enable code interpreter
spring.ai.openai.responses.hosted-tools.code-interpreter.enabled=true
# readable reasoning: ask OpenAI for reasoning summaries (auto | concise | detailed)
spring.ai.openai.responses.reasoning-summary=auto
# return what the hosted code interpreter printed
spring.ai.openai.responses.include=code_interpreter_call.outputs

  • spring.ai.openai.chat.api=responses switches the auto-configured ChatModel from the Chat Completions endpoint to the Responses endpoint. With responses, Spring AI creates an OpenAiResponsesChatModel bean instead of an OpenAiChatModel.
  • spring.ai.openai.responses.hosted-tools.code-interpreter.enabled=true declares the code interpreter as a tool on every request. The property’s own description in the configuration metadata reads “Let OpenAI run Python in a sandboxed container inside the request.”
  • spring.ai.openai.responses.reasoning-summary=auto asks OpenAI to return summaries of the model’s reasoning. OpenAI never returns the raw reasoning text, so a summary is the only readable form we can get.
  • spring.ai.openai.responses.include=code_interpreter_call.outputs asks for the outputs of the interpreter run, meaning what the Python printed, to be included in the response. Without it, the response says the code ran but doesn’t carry what it produced.

The same thing can be done in code, per request, with:

OpenAiResponsesChatOptions.builder()
.hostedTools(HostedTool.CodeInterpreter.of())
.build()

The HostedTool sealed interface also types web search, file search, MCP servers and image generation, plus a Raw escape hatch for tools Spring AI does not type yet. The CodeInterpreter record takes an optional container id, exposed as spring.ai.openai.responses.hosted-tools.code-interpreter.container-id, to reuse a container across requests.

The client and the problem

The service is a plain ChatClient. Nothing in it mentions tools, Python or the Responses API.

@Service
public class ProblemSolver {
private final ChatClient chatClient;
public ProblemSolver(ChatClient.Builder chatClientBuilder) {
chatClient = chatClientBuilder
.defaultSystem("You are a helpful problem solver. " +
"Provide elegant, meaningful solutions to the requested problems.")
.defaultAdvisors(new CustomLoggingAdvisor())
.build();
}
public String solve(String problem) {
return chatClient.prompt()
.user(problem)
.call()
.content();
}
}

A CommandLineRunner sends one problem at startup and logs the answer. The problem is a classic estimation task: how many identical objects fit in a container, given the volumes and a packing density.

private static final String PROBLEM = """
Use Python to estimate the quantity of similarly shaped objects inside a container.
Optionally report a lower and upper confidence bound based on uncertainty in the measurements.
The program shall print the results to the console.
Input:
container_volume = 540.0 # cm^3
object_volume = 1.25 # cm^3
packing_density = 0.64 # between 0 and 1
Output:
estimated_count
""";

The prompt says “Use Python” and “print the results to the console”. That is the nudge that makes the model reach for the interpreter rather than answer from arithmetic in its head.

Why the Responses API and not Chat Completions

Chat Completions has no notion of a tool that the provider runs for you. Normally, every tool is a function the application declares, the model requests and the application executes before sending the result back in a second round trip. Hosted tools such as code interpreter, web search, file search and image generation exist only on the Responses API, which is where OpenAI lands new capability.

There is a harder constraint too. Starting with GPT-5.4, Chat Completions no longer supports tool calling combined with a reasoning effort other than none.

In Spring AI, flipping spring.ai.openai.chat.api to responses is enough to swap the implementation underneath the same ChatClient. The code in ProblemSolver does not change.

Hosted tools are deliberately not modelled as ToolCallbacks. There is nothing for the application to run, so their calls never surface as tool calls and never trigger the client-side tool-calling loop. Instead, each hosted tool call appears in the response transcript as its own item. A summary of them is placed on the generation metadata under the key openai.responses.hosted_tool_calls, as a list of type, id and status entries.

The request builder applies exactly three framework-level defaults, all for correctness:

  • store: false is always sent. The model is stateless by design and it is also what makes OpenAI return the encrypted reasoning blob instead of keeping it server-side.
  • include always contains reasoning.encrypted_content and anything we configure is merged with it rather than overriding it. That is why the code_interpreter_call.outputs value in our properties file is added to, not replacing, the default.
  • Function tool schemas are sent with strict: false unless told otherwise.

Everything else defers to the provider default unless set.

The CustomLoggingAdvisor

To see what actually travels over the wire in domain terms, the project registers a CallAdvisor. Advisors wrap the call to the model. This one runs at LOWEST_PRECEDENCE, so it is the innermost advisor and sees the final prompt going out and the raw ChatResponse coming back, before any other advisor touches either.

@Override
public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) {
log.info("\n{}", formatRequest(request.prompt()));
long start = System.nanoTime();
ChatClientResponse response = chain.nextCall(request);
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
log.info("\n{}", formatResponse(response.chatResponse(), elapsedMs));
return response;
}

The request side prints the model, the options class, temperature and max tokens, then each message with its type (see formatRequest()). The response side prints the elapsed time, the model that answered, the token usage, then the interesting part – the assistant message broken down into its parts (see formatResponse()).

In Spring AI 2.x an AssistantMessage is a list of MessageParts. The hierarchy is sealed, which lets the advisor classify each part with an exhaustive pattern-matching switch:

private String category(MessagePart part) {
return switch (part) {
case TextPart _ -> "TEXT";
case ReasoningPart _ -> "REASONING";
case ToolCallPart _ -> "TOOL_CALL";
case ToolResultPart _ -> "TOOL_RESULT";
case MediaPart _ -> "MEDIA";
case UnknownPart u -> "PROVIDER(" + u.kind() + ")";
};
}

The advisor first prints the order in which the parts arrived, then groups them by category. The order matters: for the Responses API each output item becomes exactly one part, in transcript order, so the Order: line is a faithful record of what the model did during the request.

The code interpreter call arrives as an UnknownPart. That is the type Spring AI uses for any item a server-side tool produced or any item type the SDK does not model yet.

It carries the provider (openai.responses), the item’s type as its kind and the whole item as JSON in rawJson(). The advisor parses that JSON and when it finds a code field, renders the Python and each entry of outputs:

if (node.has("code")) {
sb.append('\n').append("Code:\n").append(indent(node.get("code").asString(), 2));
JsonNode outputs = node.get("outputs");
if (outputs != null && outputs.isArray()) {
sb.append('\n').append("Outputs (").append(outputs.size()).append("):");
for (JsonNode output : outputs) {
String type = output.path("type").asString("?");
String body = output.has("logs") ? output.get("logs").asString()
: output.has("url") ? output.get("url").asString()
: output.toPrettyString();
sb.append('\n').append(indent("[" + type + "]\n" + indent(body, 2), 2));
}
}
return sb.toString();
}

An output of type logs is what the program printed to stdout.

An output of type image carries a URL, which is how a plot made with matplotlib would come back.

Reasoning parts are rendered from their summary and the size of the opaque encrypted payload is reported rather than its content, since it is not meant to be read.

Walking through a run

What follows is the advisor’s output for one real run of the application, lightly trimmed. The generated Python is about 130 lines, so only its shape is quoted. The numbers are reproduced exactly. See Resource 4 for the full version of the generated code.

The request

>>> REQUEST
Model: gpt-5-mini
Options type: OpenAiResponsesChatOptions
Temperature: -
Max tokens: -
Messages: 2
[1] SYSTEM
You are a helpful problem solver. Provide elegant, meaningful solutions to the requested problems.
[2] USER
Use Python to estimate the quantity of similarly shaped objects inside a container.
...

The options class confirms the endpoint swap: an OpenAiResponsesChatOptions instance, not the Chat Completions one. No model was configured, so the framework default gpt-5-mini is used. Temperature and max tokens are unset and therefore left to the provider.

The two messages are what the ChatClient assembled from the default system text and the user prompt. On the wire they do not travel as a messages array. The Responses request builder puts the first system message into the top-level instructions field and the user message into the input list. The code interpreter tool is not visible here because it is not a message. It is added to the request’s tools array by the request builder from the enabled hosted tools.

The response header

<<< RESPONSE (44092 ms)
Model: gpt-5-mini-2025-08-07
TOKENS
Prompt (input): 3242
Completion (output): 4081
Total: 7323
ASSISTANT MESSAGE PARTS (3 total)
Order: REASONING -> PROVIDER(code_interpreter_call) -> TEXT

Forty-four seconds for one call is quite a lot, but this is the honest cost of what happened:

  • the model reasoned
  • wrote a program
  • OpenAI started a container and ran a 200,000-sample Monte Carlo simulation (Resource 3)
  • the model then wrote its answer.

All of that is one HTTP request from the application’s point of view. The model name in the response is the dated snapshot that served the request.

The token figures also tell a story. Our two messages are a few hundred tokens, yet the input count is in the thousands, because a hosted tool call is a multi-step exchange on OpenAI’s side and the interpreter’s output is fed back to the model as input within the same request. The output count covers the reasoning, the generated code and the final text.

The Order: line is the transcript. Three output items came back and became three parts in that exact order:

  • the model thought
  • then it ran code
  • then it answered

There was no second reasoning item after the execution. The model went straight from the interpreter’s output to its text.

The reasoning part

>> REASONING [1]
#1 (part 1 of 3)
Summary:
**Estimating object count in containers**
I'm tasked with creating Python code to estimate the number of similarly shaped
objects in a container using the formula container_volume × packing_density /
object_volume. I need to report confidence bounds based on uncertainties and use
the first-order propagation of uncertainty. ... **Creating estimation code**
... **Building estimation code with options**
I need to use `python_user_visible` to run the code and show outputs ...
... **Implementing Monte Carlo sampling**
...
Opaque payload: provider=openai.responses, kind=encrypted_content, 11768 chars

This is what reasoning-summary=auto produces. One reasoning item carried four summary entries, which Spring AI joins into a single summary() string without a separator, which is why the bold headings run into the preceding sentence.

The summary is readable enough to see the model’s plan. The basic formula, first-order error propagation using partial derivatives and a Monte Carlo check, with the decision to demonstrate both with example uncertainties since the prompt made the bounds optional and gave none.

One detail gives away the mechanics. The model refers to a tool named python_user_visible. The reasoning is deciding to call the hosted tool.

The ReasoningPart.text() is empty because OpenAI does not return raw reasoning. What it does return is the encrypted blob, here quite a long one, held in the part’s payload.

The code interpreter part

>> PROVIDER [1]
#1 (part 2 of 3)
Provider: openai.responses
Kind: code_interpreter_call
Code:
# Estimate number of similarly shaped objects in a container
# Shows point estimate and optional confidence bounds (analytic propagation + Monte Carlo)
import math
import numpy as np
from scipy.stats import norm
def estimate_count(container_volume,
object_volume,
packing_density,
container_unc=None,
object_unc=None,
packing_unc=None,
ci=0.95,
mc_samples=200000,
random_seed=0):
...
N = (container_volume * packing_density) / object_volume
...
sigma_N_analytic = math.sqrt(
(dN_dVc * sigma_Vc)**2 +
(dN_dp * sigma_p )**2 +
(dN_dvo * sigma_vo)**2
)
...
rng = np.random.default_rng(random_seed)
...
container_volume = 540.0 # cm^3
object_volume = 1.25 # cm^3
packing_density = 0.64 # between 0 and 1
...
container_unc = 5.0 # cm^3 (std dev)
object_unc = 0.05 # cm^3 (std dev)
packing_unc = 0.02 # absolute (std dev)
...
Outputs (1):
[logs]
Point estimate (no uncertainties):
estimated_count = 276.480
Estimate with uncertainty propagation and Monte Carlo (example uncertainties):
point estimate = 276.480
analytic std dev (approx) = 14.266
analytic 95% CI = (248.520, 304.440)
Monte Carlo mean = 276.962
Monte Carlo std dev = 14.298
Monte Carlo 95% CI = (250.222, 306.285)
Monte Carlo samples used = 200000

This is the part the whole setup exists for. It arrived as an UnknownPart whose kind is code_interpreter_call, the item type OpenAI assigns to a hosted interpreter run.

The advisor found the code field in the raw JSON and printed it, followed by the single logs output.

The program is a reasonable piece of engineering, not a one-liner. In the end its execution prints both the plain estimate and the uncertainty-aware one.

The [logs] block is stdout from the container. These numbers were computed by numpy and scipy, not predicted by the model.

This output only came back to us because of include=code_interpreter_call.outputs. Without it the item would still report that code ran, but the outputs array would be absent.

On the other hand, note what is empty:

 >> TOOL CALLS [0]
     (none)

  >> TOOL RESULTS [0]
     (none)

Nothing was asked of the JVM. No ToolCallPart was produced, no function ran locally and Spring AI’s tool-calling loop never engaged. The entire execution happened between the model and OpenAI’s container.

The text part

 >> TEXT [1]
     #1 (part 3 of 3)
        I ran a short Python program that computes the estimated count and — if you provide
        measurement uncertainties — returns approximate confidence bounds using both analytic
        (first-order) uncertainty propagation and a Monte Carlo simulation.

        Point estimate:
        - estimated_count = 276.480

        Results (95% CI shown):
        - analytic 95% CI ≈ (248.520, 304.440)
        - Monte Carlo mean ≈ 276.962
        - Monte Carlo 95% CI ≈ (250.222, 306.285)

        Code (you can copy and run; change the uncertainty values or CI/confidence level as needed):
        ...

This is the string that content() returns to ProblemSolver.solve() and that the runner logs as the solution. Obviously, every figure in it matches the [logs] output perfectly, because the model wrote the answer after reading the execution result.

The final text is the only one of the three parts that a plain content() call exposes. The reasoning and the interpreter runs are present on the ChatResponse as parts and in the generation metadata, but an application has to look for them, which is exactly what the advisor does.

Takeaways

The hosted code interpreter turns “write me a program” into “run me a program” without any execution plumbing on our side. No local Python, no sandbox, no tool-calling loop. In Spring AI 2.1.0-RC1 enabling it is one property to pick the Responses endpoint and one to switch the tool on. Two more properties, for reasoning summaries and interpreter outputs, make the result readable.

The Responses model keeps the familiar ChatClient surface while exposing the richer transcript as typed message parts. A small advisor that walks those parts is the cheapest way to see what the model reasoned, what it executed and what it concluded.

Natural next steps are reusing a container across requests through spring.ai.openai.responses.hosted-tools.code-interpreter.container-id and asking for a chart, which would come back as an image output with a URL in the same code_interpreter_call item.

Resources

[1] – Spring AI 2.1 reference, OpenAI Responses chat model

[2] – OpenAI, Code Interpreter tool guide

[3] – Monte Carlo Method

[4] – Project sample code is here.

Introducing TypeSafe Jev: Typed Judgments as Programming Primitives

by Horațiu Dan

What is TypeSafe Jev?

Jev is a model that answers questions about text with typed values and probabilities instead of generated output. It is TypeSafe’s flagship model and the first of its System One models, a class of models built “to make fast, structured decisions that software can use directly” (Reference 2).

A general-purpose LLM such as GPT or Claude also understands natural language, but it answers by generating text. When a program needs a decision, the usual pattern is to prompt for JSON, parse the reply, validate it and handle the cases where the model wrote something else. Jev removes that step. You send a state (the data to judge) and a set of named questions and each answer comes back in the exact type the question declared.

The differences that matter for a developer:

  • No text generation. Jev does not write replies, produce code or explain its reasoning. It returns a decision and the probabilities behind it.
  • Typed contract. The question type fixes the shape of the answer, so there is nothing to parse and no output format variation.
  • Calibrated probabilities. The models are trained so that their probabilities “reflect uncertainty” against real outcomes. Code can further set thresholds and route low-confidence cases to humans.
  • Parallel, independent questions. Questions in one request are evaluated separately and in parallel. Adding questions “barely changes the response time” and avoids context-rot (Reference 1).

The division of labor is simple. Your code owns the workflow, rules and calculations. Jev supplies the semantic judgment that ordinary code cannot. Ultimately the code decides.

The three primitives: noul, choice and score

Every question has a type, instructions (the question itself) and where the type needs it, criteria (the possible answers). The question name is a key for your code only. It is not sent to the model, so the instructions must carry the full meaning (Reference 3).

PrimitiveAskscriteriaReturns
noulDoes a condition hold?Optional object with true and false descriptionsnoul: probability of yes, 0 to 1
choiceWhich one of a fixed set of options applies?Required map of option name to descriptionchoice, probabilities per option, confidence
scoreWhere does the state sit on an ordered scale?Required ordered list of levels (up to 10)score, legend, probabilities per level, confidence

Noul (Reference 4) is a yes/no question that returns the probability that the answer is yes. Phrase the question so a high value means yes, ask one condition per noul and set thresholds in code according to the cost of being wrong. For multi-label problems, ask one noul per label in the same request.

Choice (Reference 4) picks exactly one option from the set you define. The full distribution shows how the options compete and confidence summarizes how concentrated it is. Include a catch-all option for when nothing fits.

Score (Reference 4) places the state on ordered levels numbered from 0. The score is the probability-weighted average of the level numbers, so it can fall between levels:

The model judges each level on its own and does not see its number, so each level should describe a concrete situation rather than a degree like “moderately”. Because different distributions can give the same score, read probabilities and confidence alongside it.

Confidence on choice and score describes how peaked the answer is, not whether it is correct (Reference 5).

Experimenting in the Playground

The fastest way to try Jev is the TypeSafe Playground (Reference 7), which runs real requests from the browser without any code. You need a TypeSafe account and an API key, which you generate in the console. Keep the same key for later API or SDK work, ideally in a TYPESAFE_API_KEY environment variable.

A typical session:

  1. Open the Playground and log in.
  2. Paste the text to evaluate as the state.
  3. Add a question: give it a name, pick the type (noul, choice or score), write the instructions and, where needed, the criteria. The questions editor also accepts JSON, so you can paste a whole questions object directly.
  4. Add more questions of any mix. They all run against the same state in one request.
  5. Run it and read every answer side by side: the value, the probability distribution and, for choice and score, the confidence.

The Playground is ideal for tuning questions before writing code. Change one word in an instruction or a criterion, rerun, and see how the probabilities move. Once the questions behave, the same JSON goes unchanged into a call as the one below (Reference 6).

POST https://api.typesafe.ai/v1/systemone

From code, the same request is a single HTTP call. The example below sends a request containing only the blocking question:

curl https://api.typesafe.ai/v1/systemone \
-H "Authorization: Bearer $TYPESAFE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "jev-preview",
"state": "This builds the SQL query by concatenating `userId` from the request, which allows SQL injection. Please switch to a PreparedStatement before we merge.",
"questions": {
"blocking": {
"type": "noul",
"instructions": "Does this code review comment require a change before the pull request can be merged?"
}
}
}'

The response holds one entry per question under answers, for example "blocking": {"type": "noul", "noul": 0.98}.

Additionally, GET /v1/models lists the available model names.

Concrete example: Analyzing code review comments

Three code review comments go to Jev in three separate requests, each asking the same three questions:

  • is it blocking (noul)
  • what is it about (choice)
  • how constructive is it (score)

A tool built on these answers could hold a merge until blocking comments are resolved, label comments by topic or flag a hostile tone to the other team members.

The states (the comments)

RequestState
a“This builds the SQL query by concatenating userId from the request, which allows SQL injection. Please switch to a PreparedStatement before we merge.”
b“Nit: I’d rename tmp to pendingOrders so the loop reads better. Not a blocker.”
c“Did you even run this? The cache is never invalidated, so users will see stale prices.”

The questions

All three requests share this questions object. Only the state changes.

{
"blocking": {
"type": "noul",
"instructions": "Does this code review comment require a change before the pull request can be merged?",
"criteria": {
"true": "Points out a defect or risk that must be fixed, or explicitly asks for a change before merging",
"false": "An optional suggestion, nit, question or praise that does not block the merge"
}
},
"category": {
"type": "choice",
"instructions": "What is the main concern of this code review comment?",
"criteria": {
"bug": "Incorrect behavior, a logic error or a missing case",
"security": "A vulnerability such as injection, leaked secrets or missing authorization",
"performance": "Speed, memory or resource usage",
"readability": "Naming, formatting, structure or style",
"other": "Anything else, such as tests, documentation or a question"
}
},
"tone": {
"type": "score",
"instructions": "How constructive is the tone of this code review comment towards the author?",
"criteria": [
"Hostile: insults or mocks the author",
"Curt: dismissive or sarcastic, no explanation",
"Neutral: states the problem without explaining or suggesting a fix",
"Constructive: explains the problem and suggests a fix",
"Very constructive: explains the problem, suggests a fix and is encouraging"
]
}
}

The three primitives each do a different job here. Blocking is a yes/no condition, so it is a noul with a threshold set in code. Category is one of five exclusive options, with other as the catch-all. Tone is ordered, so it is a score from 0 (hostile) to 4 (very constructive).

Expected results

Requestblocking (noul)category (choice)tone (score, 0–4)
aHigh, near 1: a vulnerability and an explicit “before we merge”securityAbout 3, Constructive: explains the risk and names the fix
bLow, near 0: labelled a nit and “Not a blocker”readabilityAbout 3, Constructive: suggests a rename and says why
cHigh: stale prices are a real defect even without an explicit requestbugLow, about 1, Curt: the opening question is sarcastic and no fix is offered

Comment c is the interesting one. It mixes a valid bug report with a dismissive tone and Jev should separate the two: blocking and bug on one side, a low tone score on the other.

Actual results

Request a, the SQL injection comment:

Jev matched all three predictions. blocking is 98% true, category is security at 100%, and tone scores 3.04: 96% Constructive and 4% Very constructive, with 97% confidence. All three runs used the jev-preview model.

Request b, the naming nit:

blocking is 5% true and category is readability at 100%, as expected. tone scores 3.44, higher than predicted: probability splits 56% Constructive and 44% Very constructive, so confidence drops to 63%. The friendly “Not a blocker” reads to Jev as partly encouraging, and the split is an honest signal that this comment sits between two levels.

Request c, the stale cache comment:

Jev separated the defect from the tone, as expected. blocking is 87% true and category is bug at 100%, while tone scores 1.3: 72% Curt, 20% Neutral, 6% Constructive and 2% Hostile, with 72% confidence. The spread went toward Neutral rather than Hostile, so Jev reads the comment as sarcastic but not insulting. The lower blocking value (87% versus 98% for request a) also fits, since this comment reports a defect without explicitly asking for a change.

Conclusion

Jev turns a semantic judgment into a function call with a typed return value. Three primitives cover most needs: noul for conditions, choice for categories and score for degrees. Each answer comes with probabilities that code can threshold, combine or escalate.

The code review example shows the pattern in miniature: one request, three independent judgments, no parsing. The Playground is the quickest way to design and tune such questions before moving them into an application. As with any model, validate the answers and thresholds on your own data before relying on them.

Resources

[1] – TypeSafe Introduction

[2] – TypeSafe System One

[3] – TypeSafe Primitives (Questions)

[4] – TypeSafe Noul, Choice and Score

[5] – TypeSafe Confidence

[6] – TypeSafe HTTP API

[7] – TypeSafe Playground and API keys

[8] – The picture was taken in Zakynthos, Greece

Spring AI on Local LLMs

by Horațiu Dan

Why running it locally

The usual reason given is privacy and it’s a real one. A prompt sent to a local model never leaves the machine, which changes the conversation with your security people from a negotiation into a non-event. But three other reasons matter more day to day.

  1. Cost goes to zero at the margin. Iterating on a prompt means running it fifty times. Against a hosted API that is a line item and a rate limit. Against a local model, it’s free.
  2. Tests stop depending on the Internet. A build that reaches a hosted endpoint is a build that fails when someone modifies a key or a region has a bad afternoon.
  3. You learn where the abstraction leaks. Spring AI presents one ChatClient over every provider. Running a small local model is the fastest way to find out which parts of that promise hold and which parts quietly assume you are talking to a frontier model.

The honest cost is quality and speed. An 8-billion-parameter model on a laptop isn’t a frontier model and the numbers later in this article are not flattering. That trade is fine for development, prompt iteration and tests, while it’s a decision to deliberately make for production.

The starting point

The initial set-up is the following:

  • Java 25 (Temurin)
  • Spring Boot 4.1.1
  • Spring AI 2.0.1
  • Local LLM runtime and model (details in the next section)

Additionally, a freshly generated Spring Boot project, the state you get from start.spring.io before anything interesting has happened. Web MVC, Actuator, DevTools, their test companions and the Spring AI BOM:

XML
<properties>
<java.version>25</java.version>
<spring-ai.version>2.0.1</spring-ai.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

One note on the parent: Spring AI 2.0 is built against Spring Boot 4.x and Spring Framework 7. If you are coming from Spring AI 1.x on Boot 3, this is not a version bump you can do in isolation, package names moved on both sides.

Getting a model onto the machine

In this article, Ollama is the choice: it downloads models, manages their lifecycle and serves them over HTTP on port 11434. Let’s take it step-by-step.

  • Install Ollama

The Windows installer is a one-liner in PowerShell:

PowerShell
irm https://ollama.com/install.ps1 | iex
# >>> Downloading Ollama for Windows...
# ######################################## 100.0%
# >>> Installing Ollama...
# >>> Install complete. Run 'ollama' from the command line.

  • Run Ollama the first time

ollama run pulls the model if it is missing, loads it and takes you into an interactive prompt. The daemon keeps serving on port 11434 after you leave it:

PowerShell
ollama run llama3.1
# pulling manifest
# pulling 667b0c1932bc: 100% ▕████████████████████████████████████████▏ 4.9 GB
# pulling 0ba8f0e314b4: 100% ▕████████████████████████████████████████▏ 12 KB
# pulling 455f34728c9b: 100% ▕████████████████████████████████████████▏ 487 B
# verifying sha256 digest
# writing manifest
# success

The one-line Windows command below confirms the model is present:

PowerShell
ollama list
# NAME ID SIZE MODIFIED
# llama3.1:latest 46e0c10c039e 4.9 GB 12 days ago

The detail that matters for Spring AI is that Ollama serves two APIs at once. Its native API lives under /api and an OpenAI-compatible one lives under /v1. Prove the second is alive before you write any Java, as it saves you from debugging a Spring context when the problem is a daemon:

PowerShell
curl http://localhost:11434/v1/models
# {"object":"list","data":[{"id":"llama3.1:latest","object":"model","created":1788341287,"owned_by":"library"}]}

Two ways to wire it up

Spring AI ships both a dedicated Ollama starter and an OpenAI one that will successfully talk to anything speaking the OpenAI protocol. Both work against the same daemon. Putting both on the classpath and choosing between them with a property is a good way to feel the difference:

XML
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>

Two starters on the classpath would normally mean two competing ChatModel beans. Spring AI resolves that with spring.ai.model.chat property, which names the provider that is currently chosen. The other starter’s auto-configuration backs off.

# Specifies the used starter
spring.ai.model.chat=ollama
# Native Ollama starter (active when spring.ai.model.chat=ollama)
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.model=llama3.1
spring.ai.ollama.chat.temperature=0.7
# OpenAI-compatible route (active when spring.ai.model.chat=openai)
# Ollama does not check the API key, but the starter requires one to be set.
spring.ai.openai.api-key=ollama
# The /v1 must be part of the base-url: the underlying openai-java client
# appends only /chat/completions, so omitting it yields a 404.
spring.ai.openai.base-url=http://localhost:11434/v1
spring.ai.openai.chat.model=llama3.1
spring.ai.openai.chat.temperature=0.7

A note is worth making on spring.ai.openai.api-key=ollama. Ollama ignores the value entirely, but the starter refuses to configure itself without one, so it needs a placeholder. Any non-empty string does the job.

Another aspect worth noting is the base URL needs its own /v1.

The natural thing to write is spring.ai.openai.base-url=http://localhost:11434, on the assumption that the client appends the full /v1/chat/completions path. It does not. Spring AI 2.0 delegates to the official openai-java SDK (4.49.0 here), which appends only /chat/completions. Get this wrong and every call comes back as:

com.openai.errors.NotFoundException: 404: 404

No hostname, no path, no hint, just the status code twice. The fix is to make /v1 part of the base URL, as above. The same applies to any other OpenAI-compatible server you point this at.

Flipping to the OpenAI-compatible route needs no code change at all:

./mvnw spring-boot:run -Dspring-boot.run.arguments=--spring.ai.model.chat=openai

Both spring.ai.ollama.chat.temperature and spring.ai.ollama.chat.options.temperature are valid, although the latter is deprecated. The starter’s configuration metadata registers both spellings, so your IDE will not flag either. Pick one and be consistent, because a typo in this family of properties fails silently rather than at startup.

One client, built once

With a provider configured, Spring AI auto-configures a ChatClient.Builder. The temptation is to build a client inside the controller. Resist it, the client carries defaults that belong to the application, not to one endpoint, and ChatClient is thread-safe and meant to be built once and shared. So it becomes a bean:

Java
@Configuration
public class ChatConfig {
@Bean
public ChatMemory chatMemory() {
return MessageWindowChatMemory.builder()
.maxMessages(10)
.build();
}
@Bean
public ChatClient chatClient(ChatClient.Builder builder,
@Value("classpath:/prompts/system-prompt.st") Resource systemPrompt,
ChatMemory chatMemory) {
return builder
.defaultSystem(systemPrompt)
.defaultAdvisors(new SimpleLoggerAdvisor(Ordered.LOWEST_PRECEDENCE),
MessageChatMemoryAdvisor.builder(chatMemory).build())
.build();
}
}

Three decisions are packed into those twenty lines.

Prompts live in files

defaultSystem() accepts a Resource, so the system prompt is a StringTemplate file under src/main/resources/prompts rather than a string literal in Java. It reads better, diffs better and can be edited without recompiling:

You are a generalist. Answer as briefly and precisely as you can both general and specific questions.

A system prompt is worth setting even for a toy. Small local models are chatty by default and briefly in the system message is the difference between a sentence and five paragraphs of preamble.

Memory is an advisor

Every ChatClient call is stateless unless something makes it otherwise. MessageChatMemoryAdvisor is that something. Before each call, it loads the history for a conversation and appends it to the prompt and after each call it stores the new user and assistant messages. The store behind it here is MessageWindowChatMemory, an in-memory map keyed by conversation id that keeps the last ten messages and drops the oldest when the window fills. Which conversation a request belongs to is decided per call, in the next chapter.

Logging sits closest to the model

SimpleLoggerAdvisor logs the request and the response at DEBUG. Its position in the chain is set by the order argument and Ordered.LOWEST_PRECEDENCE puts it last, after the memory advisor has done its work, so what it logs is the prompt the model actually receives, history and format instructions included. It stays quiet until you switch its logger on:

logging.level.org.springframework.ai.chat.client.advisor=DEBUG

That one line is the most useful debugging aid in this article. When a model misbehaves, the first question is always “what did it actually see?” and this answers it.

The endpoint

The controller is thin. It resolves a conversation id from an optional header, delegates to a service and echoes the id back so the caller can continue the same conversation on the next request:

Java
@RestController
@RequestMapping("/api")
class ChatController {
private final ChatService chatService;
public ChatController(ChatService chatService) {
this.chatService = chatService;
}
@GetMapping("/v{version}/chat")
public ResponseEntity<Response> chat(@RequestParam String message,
@RequestHeader(value = "X-Conversation-Id", required = false) String conversationId) {
String id = conversationId == null ? UUID.randomUUID().toString() : conversationId;
var response = chatService.respond(message, id);
return ResponseEntity.ok()
.header("X-Conversation-Id", id)
.body(response);
}
}

The v{version} segment is not a hand-rolled convention. Spring Framework 7 has first-class API versioning and Boot 4 configures it from properties:

spring.mvc.apiversion.use.path-segment=1
spring.mvc.apiversion.supported=1.0
spring.mvc.apiversion.default=1.0

The first line tells MVC that the version is the path segment at index 1, in /api/v1/chat that is v1, and the default parser understands the leading v. The second lists what the application supports, so a request for /api/v2/chat is rejected before any controller runs. The third is the version assumed when a request carries none.

The service is where the ChatClient fluent API earns its keep. One chained call covers the prompt template, the conversation, the tools and the output type:

Java
@Service
public class ChatService {
private final ChatClient chatClient;
private final Resource userPrompt;
private final TenantService tenantService;
public ChatService(ChatClient chatClient,
@Value("classpath:/prompts/user-prompt.st") Resource userPrompt,
TenantService tenantService) {
this.chatClient = chatClient;
this.userPrompt = userPrompt;
this.tenantService = tenantService;
}
public Response respond(String message, String conversationId) {
return chatClient.prompt()
.user(userSpec ->
userSpec.text(userPrompt)
.param("message", message))
.advisors(advisorSpec ->
advisorSpec.param(ChatMemory.CONVERSATION_ID, conversationId))
.tools(tenantService)
.call()
.entity(Response.class);
}
}

Line by line, the user message is a template with a {message} placeholder, filled with .param(), which keeps user input out of the template’s structure and the template itself readable:

Provide a short, to-the-point answer to the below message:
{message}

The advisors() block hands the conversation id to the previously mentioned memory advisor, under the well-known key ChatMemory.CONVERSATION_ID. Two requests with the same X-Conversation-Id header share history. A request without the header starts a fresh conversation and is told its id in the response. tools() and entity() get their own chapters.

GET /api/v1/chat?message=In one sentence, what is quantization of an LLM?
LLAMA3.1:
Quantization of a large language model (LLM) refers to the process of approximating its weights and
activations with lower-precision data types (such as integers or fixed-point numbers) to reduce memory
usage and computational overhead, while minimizing the impact on model performance.

If you are running with DevTools and edit application.properties or a prompt file under src/main/resources, nothing happens until the file is copied into target/classes. DevTools watches the build output, not the source tree. A rebuild in your IDE triggers it, editing the file in a plain text editor doesn’t and you’ll spend a while wondering why your fixed base URL is still returning 404.

Answers as Java records

Text is informative, but typed objects are the reason to put a model behind a Spring service. entity() takes a class, derives a JSON schema from it, appends format instructions to the prompt and parses what comes back. The endpoint returns this:

Java
public record Response(
@JsonPropertyDescription("""
The category of the request message. \
SPECIFIC when the message refers to a particular tenant, identified by its unique identifier, \
so that answering requires the tenant information tool. \
GENERAL for any other message, such as general knowledge or technical questions \
that can be answered without tenant data.""")
ResponseCategory category,
@JsonPropertyDescription("The actual response message text")
String text) {
}
public enum ResponseCategory {
GENERAL,
SPECIFIC
}

The @JsonPropertyDescription annotations are not decoration. They flow into the generated schema and the schema is what the model reads, so a description is the only place a field’s meaning gets explained. The enum becomes an enum constraint in the schema, which is why the model reliably answers with one of the two constants rather than a synonym. The category description is deliberately a paragraph, not a label.

Giving the model a tool

A model knows nothing about your data specifics (tenants’ information as part of this experiment). Tool calling is how it asks. You describe a method, the model decides whether to call it and with what arguments, Spring AI executes it and feeds the result back and the model writes its answer from that. The description is the interface, it’s all the model sees:

Java
@Service
public class TenantService {
private static final Logger logger = LoggerFactory.getLogger(TenantService.class);
private final Map<String, String> tenantInfo = Map.of(
"TNG", "Tenant TNG is a well known TEM services provider.",
"FED", "Tenant FED is Roger Federer's foundation.",
"DJO", "Tenant DJO is Novak Djokovic's foundation."
);
@Tool(name = "get-tenant-info-by-id",
description = "Retrieve additional information by tenant id")
public String infoByTenantId(@ToolParam(description = "The unique identifier of a tenant") String tenantId) {
logger.info("Retrieving additional info for tenant with id {}", tenantId);
return tenantId == null ? "N/A" : tenantInfo.getOrDefault(tenantId, "N/A");
}
}

Passing the bean to .tools(tenantService) in the service is all the registration there is. Spring AI scans it for @Tool methods and builds the JSON schema for their parameters from the @ToolParam descriptions. The log line is deliberate. Whether the model decided to call the tool and what it passed, is otherwise invisible.

The null guard matters too. A model that decides to call the tool but fails to extract an argument sends nothing for tenantId and a Map.getOrDefault(null, …) on an immutable map throws. Returning "N/A" instead lets the model explain the gap in its own words, which is exactly what happens in the first test case below.

Testing without a model

A local model makes tests possible offline, but it does not make them good tests. The output varies run to run and every assertion becomes a guess about phrasing. For anything that checks your code rather than the model’s, replace the ChatModel bean with a mock. Spring AI‘s auto-configuration builds the ChatClient.Builder from whatever ChatModel is in the context, so a @MockitoBean is enough to take the daemon out of the picture entirely:

Java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
class ChatControllerTests {
@MockitoBean
private ChatModel chatModel;
@Autowired
private MockMvcTester mvc;
@BeforeEach
void init() {
// ChatClient copies the model's defaults into every request, so a bare mock does not work
when(chatModel.getOptions())
.thenReturn(ChatOptions.builder().build());
}
@Test
void chat() {
var message = "Local models keep your prompts on your own machine.";
var modelOutput = """
{"category": "GENERAL", "text": "%s"}
""".formatted(message);
var response = new ChatResponse(List.of(new Generation(new AssistantMessage(modelOutput))));
when(chatModel.call(any(Prompt.class)))
.thenReturn(response);
assertThat(mvc.get()
.uri("/api/v1/chat")
.param("message", "Why run locally?"))
.hasStatusOk()
.bodyJson()
.convertTo(Response.class)
.isEqualTo(new Response(ResponseCategory.GENERAL, message));
}
}

The mock returns the JSON a model would return and the test asserts that your controller, service, template and record mapping serve it back as a Response. The model’s ability to produce that JSON is a separate question and not one a unit test should be asking.

Two things are quietly bypassed here and it is worth knowing which. Tool execution happens inside the concrete ChatModel implementation, so a mocked model never calls TenantService. The tool is registered but inert. The memory advisor, on the other hand, is real, it runs, stores the exchange in the in-memory window under a freshly generated conversation id and does no harm.

A note on the chatModel mock is worth making. If only mocking ChatModel and stubbing just call(), the first request fails with:

NullPointerException: Cannot invoke "ChatOptions.mutate()" because the return value of "ChatModel.getOptions()" is null

ChatClient reads the model’s default options and merges them into every request. Mockito returns null for the unstubbed getter and the merge breaks. One line in a @BeforeEach fixes it, but the stack trace points into Spring AI internals rather than at your test, so it costs more time than it should.

Testing the integration

With the application started, four requests on the same conversation exercise the whole chain: template, memory, tool, structured output. The X-Conversation-Id header ties them together. What each one did is known from the log line in TenantService and from the advisor log previously switched on.

Use case 1. Ask by “id”:

curl -G http://localhost:8080/api/v1/chat -H "X-Conversation-Id: 123-1bc-981"
--data-urlencode "message=Provide info for tenant with id FED"
# {"category":"GENERAL","text":"Tenant information not available"}

The tool was invoked, but with no tenantId. The model recognised that the question needed the tool and then failed to map "FED" onto the parameter, so the method returned N/A and the model paraphrased it.

Use case 2. Same question, phrased with the parameter’s own description:

curl -G http://localhost:8080/api/v1/chat -H "X-Conversation-Id: 123-1bc-981"
--data-urlencode "message=Provide info for tenant with unique identifier FED"
# {"category":"GENERAL","text":"Tenant FED is Roger Federer's foundation."}

Tool invoked, tenantId mapped to FED, correct answer. The only change was “id” becoming “unique identifier”, the exact words in the @ToolParam description.

Use case 3. The winning phrasing, different tenant:

curl -G http://localhost:8080/api/v1/chat -H "X-Conversation-Id: 123-1bc-981"
--data-urlencode "message=Provide info for tenant with unique identifier DJO"
# {"category":"GENERAL","text":"Tenant DJO is an abbreviation for DJ Okaya."}

The tool was not invoked. The model answered from nothing, fluently and wrongly.

Use case 4. The identical request, sent again:

curl -G http://localhost:8080/api/v1/chat -H "X-Conversation-Id: 123-1bc-981"
--data-urlencode "message=Provide info for tenant with unique identifier DJO"
# {"category":"GENERAL","text":"Tenant DJO is Novak Djokovic's foundation."}

This time the tool was invoked, tenantId mapped to DJO, and the answer is right. Nothing changed between use cases 3 and 4 except the conversation history being one exchange longer.

Four requests, one tool, three different behaviors: called without arguments, called correctly and not called at all, the last two for the same input. The temperature of 0.7 explains some of the variance, but the deeper issue is that an 8-billion-parameter model is weak at the two judgement calls tool use requires: should I call this and what goes in the parameter.

Two mitigations are visible in the results. Wording the user’s request in the same vocabulary as the @ToolParam description made the difference between use cases 1 and 2, so descriptions should use the words users will use. And the null guard in TenantService turned a would-be exception into a polite non-answer. Neither makes use case 3 go away, that probably needs a lower temperature, a system prompt that instructs the model to always use the tool for tenant questions, or a bigger model.

What it actually feels like

Measured on a laptop, Intel Core Ultra 7 155H, 32 GB RAM, RTX 500 Ada, running llama3.1 8B through the endpoint above:

  • 14.2s – first request after startup, three-bullet answer
  • 11.3s – same request, model already warm

Double-digit seconds for a paragraph and a tool call adds a second round trip to the model on top. That’s workable for development and unacceptable for a request a user is waiting on, which is the honest headline: local models are a development and testing tool at this size.

The quality gap is sharper than the speed gap and it’s worth seeing rather than being told about. Asked a question about the very tool serving it:

GET /api/v1/chat?message=In one sentence: what is Ollama?
LLAMA3.1:
Ollama is a brand of vegan, plant-based egg substitute made from a combination of pea protein,
potato starch and other ingredients.

Confident, fluent, well-formed and entirely invented. The model’s training data predates the tool it’s running inside. Put that next to "DJ Okaya" from before and the pattern is clear. This is the most useful thing about developing against a small local model, the failure modes you will eventually have to design around are loud here instead of rare. Whatever guardrails, validation and grounding your application needs in production, you will notice you need them on day one.

Resources

[1] – POC code is here

[2] – The picture was taken in Zakynthos, Greece

How to Correctly Implement ‘Sneaky Throws’ in Java

by Horațiu Dan

If you ask Java developers about the concept of ‘Sneaky Throws‘, I am almost sure there will be a couple of opinions that are quite differently expressed, but similar in their meaning. Some will sum it up as being able to throw checked exceptions without declaring them explicitly, others will amend that it means writing functional style code (lambdas) and being allowed to call methods that throw checked exceptions. Most probably, it will be surely mentioned there’s a Lombok annotation called exactly @SneakyThrows that solves the problem immediately when put on a method. Last but not least, to outline it in a more pragmatic and plastic manner, it will be said the concept allows tricking the Java compiler to treat checked exceptions as runtime ones.

All these are valid points of view and in order to clarify the concept, this article aims to provide a straight-forward, yet useful approach to dealing with methods that throw checked exceptions.

Let’s jump right in and imagine the following situation. The team is requested to enhance the currently delivered application and implement new functionalities.  This obviously happens on a ‘sprint-ly’ basis.  Nevertheless, the project has been successfully developed for quite a while now, it also deals with legacy code and moreover, developers are interacting with other parts of code that were written, let’s say, in a less fortunate manner. Such an example is the class below.

public class TwoDigitsInteger {

    private final Integer value;

    public TwoDigitsInteger(Integer value) {
        this.value = value;
    }

    public boolean isValid() throws NotSetException {
        if (value == null) {
            throw new NotSetException("Number value not set.");
        }
        return value >= 10 && value <= 99;
    }

    public Integer getValue() throws NotSetException {
        if (value == null) {
            throw new NotSetException("Number value not set.");
        }
        return value;
    }
}

Just as its name suggests, it models a two-digits integer number. Instances of this class are immutable, the value is set upon construction, and it declares two methods, one for reading the value – getValue() – and another one for validating it – isValid(). We’re not going to further elaborate on the quality of the code as it helps in the experiment done. The main issue here, the plot of this article, is the fact that both methods declare a NotSetException as they might throw it under certain circumstances and even that might be fine unless this Exception hadn’t been a checked one.

public class NotSetException extends Exception {

    public NotSetException(String message) {
        super(message);
    }
}

One option (and definitely the one worth taking into account) is to profit and consider the moment a good opportunity to refactor this ‘legacy’ code and at least make the Exception a runtime one. A few unit tests can be written (in case these are missing), then the implementation improved and focus can be moved on the newly requested features.

Nevertheless, for the sake of the experiment in this article, it’s assumed the TwoDigitsInteger class is kept as it currently is and the Exception remains checked.

Exception Function

Let’s consider a very simple scenario, there is a collection of TwoDigitsIntegers and the intent is to create a string expression that outlines the sum of the numbers.

List<TwoDigitsInteger> numbers = List.of(new TwoDigitsInteger(10), 
			new TwoDigitsInteger(25),
			new TwoDigitsInteger(37));

If writing the code as in the test below,

@Test
void sumExpression() {
	String result = numbers.stream()
			.map(TwoDigitsInteger::getValue)
			.map(String::valueOf)
			.collect(Collectors.joining("+"));

	Assertions.assertEquals("10+25+37", result);
}

the Java compiler will complain saying – Unhandled exception: com.hcd.utilities.NotSetException – as the getValue() method declares a checked Exception and obviously it cannot be used inside a stream.

To solve the issue, a try-catch is needed, which makes the code quite difficult to read (and ugly). Not to mention that we’re modifying the state of joiner as we loop the collection.

@Test
void sumExpression1() {
	StringJoiner joiner = new StringJoiner("+");
	for (TwoDigitsInteger number : numbers) {
		try {
			joiner.add(String.valueOf(number.getValue()));
		} catch (NotSetException e) {
			throw new RuntimeException(e);
		}
	}
	String result = joiner.toString();

	Assertions.assertEquals("10+25+37", result);
}

In order to overcome this and allow having a fluent API even in situations where checked Exceptions are present, the following ExceptionFunction interface is created.

@FunctionalInterface
public interface ExceptionFunction<T, R, E extends Exception> {
		 
    R apply(T t) throws E; 
}

It is general enough, it represents a function that accepts one argument (of type T), produces a result (of type R) and when applied, an Exception subclass (of type E) might be thrown. Implementers shall define a single method, which effectively applies the function.

Additionally, the following class is defined.

public final class ExceptionWrapper {
				    
	public static <T, R, E extends Exception> Function<T, R> apply(ExceptionFunction<T, R, E> function) {
		return t -> {
			try {
				return function.apply(t);
			} catch (Exception e) {				  
				throw new RuntimeException(e);
			}
		};
	}
	
	ExceptionWrapper() {
    	throw new UnsupportedOperationException("No need to be called.");
    }
}

When the ExceptionWrapper#apply() method is called, in case an Exception is thrown, it is wrapped into a RuntimeException one and thrown further irrespective of the type of the initial one (the checked Exception case is obviously covered as well, so we’re good). The ExceptionFunction passed as a parameter represents the initial call that is wrapped to overcome the problem.

The previously discussed test is modified to use the ExceptionWrapper#apply() method. Not only that it now compiles and runs successfully, but the code readability is definitely improved.

@Test
void sumExpression() {
	String result = numbers.stream()
			.map(ExceptionWrapper.apply(TwoDigitsInteger::getValue))
			.map(String::valueOf)
			.collect(Collectors.joining("+"));

	Assertions.assertEquals("10+25+37", result);
}

Exception Predicate

Let’s now consider another straight-forward scenario, one in which we want to count only the valid two-digits integers that are found in a designated range. Also, for the sake of this experiment, it’s assumed the previous TwoDigitsInteger class is used.

As in the previous case, the following piece of code that would do the job doesn’t compile because of the same reason – Unhandled exception: com.hcd.utilities.NotSetException – as the isValid() method declares a checked exception and it cannot be used inside a stream.

long count = IntStream.range(0, 150)
		.mapToObj(TwoDigitsInteger::new)
		.filter(TwoDigitsInteger::isValid)
		.count();

Again, assuming the TwoDigitsInteger is needed, one would have to loop through the numbers, check them in a try-catch for checked NotSetExceptions as isValid() declares it, then pack the Exception as a RuntimeException one and throw it further, finally count the valid number. This is already way too complicated even when only enumerating the steps in natural language.

To be able to keep the API fluid and use streams when performing checks that declare checked Exception, the next interface is declared.

@FunctionalInterface
public interface ExceptionPredicate<T, E extends Exception> {

    boolean test(T t) throws E; 
}

It represents a predicate (a boolean-valued function) of one argument that might throw an Exception subclass. The method evaluates the predicate on the given argument and returns true if the input argument matches, or false otherwise.

In addition, the following method is added to the ExceptionWrapper class, very similar to the apply() one.

public static <T, E extends Exception> Predicate<T> test(ExceptionPredicate<T, E> predicate) {
	return t -> {
		try {
			return predicate.test(t);
		} catch (Exception e) {				  
			throw new RuntimeException(e);
		}
	};
}

When called, it effectively applies the provided predicate. In case an Exception is thrown, it is wrapped into a RuntimeException one and thrown further.

To initial code can now be rewritten as below and successfully compiled and executed.

@Test
void count() {
	long count = IntStream.range(0, 150)
		.mapToObj(TwoDigitsInteger::new)
		.filter(ExceptionWrapper.test(TwoDigitsInteger::isValid))
		.count();

	Assertions.assertEquals(90, count);
}

Take-Aways

Although simple and to-the-point the presented solution comes in very handy especially when dealing with functions that declare checked Exceptions and are further used in the code that we produce. For sure, other ready-to-use alternatives already exist, an example being the Lombok @SneakyThrows annotation. Personally, I have very rarely included the Lombok library in any of my projects and as Java introduced the records, this becomes even more unlikely to happen in the future. That being said, the structures described in this article are very helpful, light-weight and easy to understand and use when needed.

ExceptionWrapper, ExceptionFunction and ExceptionPredicate source code is part of the asentinel-orm open-source project. To use it, one may either declare the Maven dependency in their pom.xml file (version 1.72.2 is the latest at the moment of this writing)

<dependency>
    <groupId>com.asentinel.common</groupId>
    <artifactId>asentinel-common</artifactId>
    <version>1.72.2</version>
</dependency>

or use it directly if considering there’s too much overhead to include the whole library.

Resources

[1] – asentinel-orm open-source ORM project is here

[2] – the picture was taken at ‘Harry Potter Warner Bros. Studios’, near London

Thoughts on Developing with A(ccelerated) I(nference)

by Horațiu Dan

AI stands for Artificial Intelligence, yet I prefer the term Dr. Venkat Subramaniam used in one of his talks: Accelerated Inference. To my mind it is far more accurate, so I have embraced it.

And “accelerated” is precisely the point. With AI, generating code has become cheap, it is no longer the bottleneck of software development. What has become expensive, and what this article is really about, is everything around it: aligning outcomes with intent, owning what we ship, and exercising the judgment that no amount of acceleration can replace.

A Brief History

The main structures underlying modern AI are neural networks and transformers – statistical models capable of replicating patterns. The former have been around for much longer than many people today assume; the latter are comparatively new.

The field’s milestones trace a recurring cycle of bold ideas, disillusionment, and breakthroughs driven by new algorithms, more data, and faster hardware: from the first mathematical model of an artificial neuron (1943) and the perceptron (1958), through the first “AI winter” (1969) and the backpropagation revival (1986), to AlexNet’s deep learning breakthrough (2012) and the Transformer architecture (2017) that underpins all modern large language models.

In other words, AI as a concept is not new at all. What is new is that today almost everyone, technical or not, has an opinion about AI and how it is changing the way we work.

On one hand, this is perfectly normal: the world isn’t what it used to be, the available tools are different and more powerful, and certain problems can now be solved much faster. On the other hand, in this new and fashionable landscape, people should strive to form objective opinions first, filter them through their own judgment, and only then express and apply what proves useful. From individual to individual, hasn’t this always been the case with everything else?

Habits Worth Keeping (and Acquiring)

When it comes to people, the recommendations on how to act when ‘newness’ emerges haven’t changed from what we’ve been used to. Certain responsibilities and habits should be kept, others adapted and continually improved, while new ones acquired. Regarding software engineers, I feel slightly more entitled to an opinion, thus here are a few pieces of advice I have compiled and consider them worth having close.

  • Before writing code, strive to turn incomplete and ambiguous requirements into a comprehensible starting point – understand not just how to build something, but why and who it serves to.
  • Before writing code, know when to use a certain algorithm or design, why it matters, and how it fits into the large application you are building.
  • Before merging in your code, have it reviewed first by yourself, then by at least one human programmer
  • Get used to a shift in thinking. Engineers are used to predictable results; LLMs produce variable output. A switch from deterministic to probabilistic thinking may be needed.
  • Before merging AI-generated code, review every line in detail and thoroughly understand why each decision was made – transform the changes into fully owned ones, as if you had written them yourself. (sounds familiar, doesn’t it?)
  • Before merging AI-generated code, make sure it meets the project’s coding standards and remains human-readable, and improve it where possible.
  • Sharpen your code-reading and reviewing skills. They were always a plus; now that AI agents are programming buddies producing large volumes of output, they are essential.
  • Avoid “prompt-and-pray vibe coding.” Use AI thoughtfully, maintain rigorous standards, and don’t short-circuit your own learning.
  • Use AI as a force multiplier to amplify your existing skills – knowledge, experience, problem-solving as a professional, and above all objective, constructive judgment as a human being.
  • Validate both directions. Check not only what AI agents produce as output, but also what they consume as “trusted” input.
  • Co-build abstractions. Use LLMs to help build an abstraction, then use that abstraction to communicate with the LLM more effectively and solve problems in a more deterministic manner.
  • Keep delivering reliable, maintainable software, but pay closer attention to how you spend your time building it.

Some of these points are about AI; some are not. Some have been acknowledged for ages; others emerged recently and will be assimilated sooner or later.

From Writing Code to Solving Problems

One thing is certain: with AI, the software development approach and mindset are fundamentally different. In this shift, I believe software engineers have a great opportunity – to move their attention even further from writing code to solving problems, and to spend their energy on more meaningful challenges. Oleg Koverznev puts the thesis I opened with even more sharply: “… code generation is cheap and no longer a bottleneck, the real challenge is aligning outcomes with intent, along with managing the growing operational and economic complexity of agent-driven work”.

AI’s instant output tends to fuel our impatient expectations for immediate results. It can make us feel productive and efficient, but let’s hold on for a moment, resist the rush, and ask whether the outcome has real value, whether it actually produces impact.

Going deeper, there is an idea I find helpful in sustaining this point of view. Luciano Floridi – a leading figure in the philosophy of information and digital ethics, widely influential in AI ethics – has a thesis (sometimes referred to as Floridi’s Conjecture) that can be summarized as follows:

As the complexity of a system increases, the ethical significance of its interactions also increases, while the ability to fully predict or control its behavior decreases.

In this view, advanced information technologies are re-ontologizing our world, reshaping the very fabric of reality and our place within it, rather than simply serving as tools within an unchanged reality. Applied to AI, the conjecture suggests that a fully autonomous system cannot have great scope and great certainty at the same time; AI agents will therefore always require human oversight. Yet more and more, out of convenience, people tend toward fully embracing agent autonomy, when it would be wiser to remain in the loop: tempered and watchful.

Language, Thought, and Staying Sane

Science in general and AI in this particular context is not a magic trick, but a special way of using human intelligence. We embrace science and AI not when we put on a white coat, but when we start practicing a set of canons of thought, many of which have to do with the use of natural language, which is after all, the main medium of AI-human interaction.

New technologies change what we understand by “knowledge” and “truth.” They alter the deeply rooted habits of thought that give us a sense of the world, of the natural order of things, of what is reasonable, necessary, inevitable, or real. The actual magnitude of the effect varies from person to person. But as Neil Postman observed, a new technology doesn’t merely add or subtract something – it changes everything. It redefines the words by which we guide our lives: freedom, truth, intelligence, reality, wisdom, memory, history. And it never stops to warn us, and we never stop to ask. We keep rushing.

Conclusion

In these days when AI seems to be the solution for almost everything, I consider it very important to keep improving our reading, writing, and technical skills, our natural language, and our critical thinking and to apply them wisely. To be respectful to ourselves and to others. To value truth more than mere correctness and, why not, to become good bullshit detectors as well. In a world where consumerism is amplified as never before, where objects are overvalued and abundant, and where speed is prized over competence and quality, remaining sane is a real virtue.

Improving our human virtues is a continuous and tedious process, but a rewarding, fundamental, and safe one in the long run. Let’s not change the world, let’s change ourselves.

Exploring A Few Java 25 Language Enhancements

by Horațiu Dan

Although Java 26 was released in mid March this year, Java 25 is the latest LTS version available and thus I chose to focus my attention on it in the first place.

Irrespective of whether certain Java 25 language improvements are still available as preview features or not, this article is briefly outlining a few. The main purpose is to first make the developers aware that Java is continuously refined and evolved by its API contributors and secondly, to raise the curiosity and interest of exploring these enhancements in detail.

Out of the bunch of features proposed in JDK 25 [Resource 1], the following five language enhancements are briefly explored here:

  • JEP 512 – Compact source files and instance main methods
  • JEP 513 – Flexible Constructor Bodies
  • JEP 507 – Primitive Types in Patterns, instanceof and switch
  • JEP 506 – Scoped Values
  • JEP 502 – Stable Values

Compact Source Files and Instance Main Methods (JEP 512)

After its initial proposal as part of JDK 21 as JEP 445 – ‘Unnamed Classes and Instance main Methods‘, this feature has been gradually improved in the next releases based on the feedback received and it was finalized in JDK 25.

The goal is clear – Simplify Java’s entry point for beginner developers and inside small programs — reducing boilerplate and ceremony — while remaining fully compatible with the standard Java language and toolchain.

Let’s imagine we quickly want to write a small program that:

  • prompts the user and keeps reading their input in a loop
  • if the user types exit (case-insensitive), it prints “Goodbye!” and ends
  • otherwise, it prints the length of the entered string

The code for this resides directly in a package, in a file called CompactSourceFile.java file, whose content looks as below:

static final String EXIT = "exit";
String prompt(String exit) {
return "Enter a string (or '" + exit + "' to quit): ";
}
void main() {
while (true) {
String input = IO.readln(prompt(EXIT));
if (EXIT.equalsIgnoreCase(input)) {
IO.println("Goodbye!");
break;
}
IO.println("Length: " + input.length());
}
}

Suggestive and to the point – no class declaration, just the aimed simple piece of code.

If run and after providing a few prompts, the output is as expected:

Enter a string (or 'exit' to quit): joke
Length: 4
Enter a string (or 'exit' to quit): meeting
Length: 7
Enter a string (or 'exit' to quit): exit
Goodbye!

A few observations are worth making:

  • The need for an explicit class declaration is removed
  • Although not visible, the compiler implicitly declares a class that is final and part of an unnamed package
  • The traditional public static void main(String[] args) is replaced with a simpler enough instance method that is a clearly defined program entry point
  • The program entry-point still needs to be named main() as the JVM  looks for such a launchable method
  • All fields and methods belong to the implicit class, just as in the regular case
  • The simple program focuses directly on its purpose without additional details
  • It’s experimental, it’s straight-forward, if it turns into a real application though, it’s advisable to preserve the object oriented structure and all known best practices

Flexible Constructor Bodies (JEP 513)

Until JDK 25, one clear rule regarding constructors was that no statements could be written before super() or this() calls. For the sake of expressivity and readability, JEP 513 relaxes this constraint, while the existing code continues to compile and function correctly and moreover, the object’s safety is 100% preserved.

In Java, when an object instance is constructed, there are two stages that happen one before and one after the hierarchy of constructor chaining begins its execution. During the former, the memory is allocated and the instance fields are initialized, then during the latter, once the this() and super() calls complete, the rest of the object is basically constructed. This process is mainly a safety wise one, that is to ensure the inherited object parts are completely initialized before any child related code is run. Joshua Bloch has already advised in his ‘Effective Java’ book to prevent this reference to escape “too early”. The result – objects are not partially constructed at any moment.

Simply put, starting with Java 25, statements are now allowed to be executed before this() or super() as part of constructor bodies and still, internally without making any compromises in regard to object core safety while building it.

Observations:

  • Allowed statements – only those that don’t depend on instance state and are guaranteed to be safe:
    • manipulation of locally declared variables that live on the stack
    • constructor parameter validation
  • Syntax is made more permissive, the object safety is preserved

Let’s have a small example where we minimally model a Car through an approximate length and the number of wheels, where the former is inherited from a Vehicle super class.

static class Vehicle {
private final long length;
Vehicle(long length) {
if (length < 0) {
throw new IllegalArgumentException("Length must be positive");
}
this.length = length;
}
Vehicle(double length) {
long round = Math.round(length);
this(round);
}
public long length() {
return length;
}
}
static class Car extends Vehicle {
private final int wheels;
Car(double length, int wheels) {
if (wheels < 0) {
throw new IllegalArgumentException("Wheels must be positive");
}
super(length);
this.wheels = wheels;
}
public int wheels() {
return wheels;
}
}
void main() {
var car = new Car(4.6d, 4);
IO.println("Car is about " + car.length() +
" meters long and has " + car.wheels() + " wheels.");
}

If we run it, the following output is observed – Car is about 5 meters long and has 4 wheels.

First, one may observe that the Vehicle#length is first rounded as its kept as a long value (line 13) then passed to the other constructor. Secondly, the number of wheels is validated before the super constructor is invoked (line 30), then set.

Let’s now model a motorcycle using records.

record Moto(long length, int wheels) {
Moto {
if (length < 0) {
throw new IllegalArgumentException("Length must be positive");
}
if (wheels < 0) {
throw new IllegalArgumentException("Wheels must be positive");
}
}
Moto(double length, int wheels) {
long round = Math.round(length);
this(round, wheels);
}
}
void main() {
var moto1 = new Moto(3, 2);
IO.println("Moto 1 is about " + moto1.length() +
" meters long and has " + moto1.wheels() + " wheels.");
var moto2 = new Moto(2.1d, 2);
IO.println("Moto 2 is about " + moto2.length() +
" meters long and has " + moto2.wheels() + " wheels.");
}

While before Java 25, the parameters’ validation is allowed in canonical record constructors (line 2), the ability is now extended for non-canonical constructors as well (line 12) and moreover the this() call is allowed.

If we run it, moto1 is constructed using only the canonical constructor, while moto2 via both and the output is obviously the one below.

Moto 1 is about 3 meters long and has 2 wheels.
Moto 2 is about 2 meters long and has 2 wheels.

Regarding enums, let’s consider the following experimental code.

enum Bike {
CITY(12),
MOUNTAIN("10");
private final int weight;
Bike(int weight) {
if (weight < 0) {
throw new IllegalArgumentException("Weight must be positive");
}
this.weight = weight;
}
Bike(String description) {
int weight = Integer.parseInt(description);
this(weight);
}
public int weight() {
return weight;
}
}
void main() {
IO.println("Bike is " + Bike.MOUNTAIN.weight() + " kg heavy.");
}

While validation as in the first constructor has been allowed prior to Java 25, additional operations before calling this() are now permitted as well.

To conclude, at class, record or enum level, the way the constructors can now be written is cleaned and improved, while the object safety is still preserved without any compromises.

Primitive Types in Patterns, instanceof and switch (JEP 507)

In general, pattern matching is a language procedure that basically combines a few steps into a feature that facilitates testing a particular value. The focus is on what is being checked and not necessarily on the mean of doing it. In addition to situations where pattern matching is applied in case of instanceof and switch constructs, Java 25 allows using it with primitives – byte, short, int, long, float, double, char, boolean are now part of this model. The reference type boundary is now extended, making the feature uniform and more intuitive as the applicability restrictions have been reduced significantly.

Let’s consider the following examples:

void main() {
Number doubleBoxed = 3.99;
if (doubleBoxed instanceof int i) {
IO.println("'num' fits in int: " + i);
} else {
IO.println("'num' does NOT fit losslessly in int (value=" + doubleBoxed + ")");
}
IO.println(describe(Byte.MAX_VALUE));
IO.println(describe(Short.MAX_VALUE));
IO.println(describe(42));
IO.println(describe(Integer.MAX_VALUE));
IO.println(describe(Long.MAX_VALUE));
IO.println(describe(3.14f));
IO.println(describe(2.718281828459045));
}
static String describe(Number n) {
return switch (n) {
case byte b -> n + " fits in byte → " + b;
case short s -> n + " fits in short → " + s;
case int i -> n + " fits in int → " + i;
case long l -> n + " fits in long → " + l;
case float f -> n + " fits in float → " + f;
case double d -> n + " fits in double → " + d;
case null, default -> n + " unknown numeric type";
};
}

If run, it produces the below output:

'num' does NOT fit losslessly in int (value=3.99)
127 fits in byte → 127
32767 fits in short → 32767
42 fits in int → 42
2147483647 fits in int → 2147483647
9223372036854775807 fits in long → 9223372036854775807
3.14 fits in float → 3.14
2.718281828459045 fits in double → 2.718281828459045

Observations:

  • describe() allows to easily describe a Number as the most compact type it fits into (line 19)
  • A Number reference can now be pattern-matched directly to a primitive (line 20)
  • The feature enables safe, lossless narrowing checks without manual casting or range checks

Going deeper with the exploration, what I personally find interesting regarding this feature is the deep nested patterns.

The below example allows introspecting the object and directly matching the content.

record Age(int years) {}
record Wine(String name, Age age) {}
void analyze(Object value) {
IO.println("Analyzing - " + value);
if (value instanceof Wine(String name, Age(int years))) {
IO.println("Wine: " + name + " (" + years + " years old)");
} else {
IO.println("Not a wine");
}
}
void main() {
var value1 = new Wine("Merlot", new Age(10));
analyze(value1);
var value2 = "Cabernet Sauvignon";
analyze(value2);
}

If run, the result is again obvious, but the code is clean, concise and very expressive.

Analyzing Wine[name=Merlot, age=Age[years=10]]
Wine: Merlot (10 years old)
Analyzing Cabernet Sauvignon
Not a wine

To conclude, beginning with Java 25 in regard to the current state of the pattern matching feature, code has a great chance to become cleaner and safer as a whole.

Scoped Values (JEP 506)

As Project Loom brought the virtual threads in Java, that definitely made room for another enhancement – passing immutable context between and across threads in a more structured, predictable and safer way. ScopedValues are a finalized feature in Java 25 and allow exactly this, within the boundaries of a precise execution scope.

To better understand them let’s refer to the following simple example:

static final ScopedValue<User> USER = ScopedValue.newInstance();
record User(int id, String name) {}
static void handleFurther() {
IO.println("handleFurther - start for " + USER.get());
ScopedValue.where(USER, new User(2, "AD"))
.run(() -> {
IO.println("handleFurther - something specific for " + USER.get());
});
IO.println("handleFurther - finished for " + USER.get());
}
static void handle() {
IO.println("handle - start for " + USER.get());
handleFurther();
IO.println("handle - finished for " + USER.get());
}
void main() {
ScopedValue.where(USER, new User(1, "HCD"))
.run(() -> {
IO.println("main - before handling - " + USER.get());
handle();
IO.println("main - after handling - " + USER.get());
});
//handle();
}

The spot for the shared User is first created as USER.

The context passed during the execution (and not as a parameter of the methods engaged) is the User instance. It might be seen as the “current” user.

Once the instance is bound (line 23), its scope is clearly defined in the main() method and passed throughout the execution – to handle() and further to handleFurther(). Access is read-only, it cannot be changed.

If during the execution flow it is re-set, as in handleFurther(), that is, a new (nested) sub scope is created and once this sub scope ends, the previous outer scope is continued.

If run, the code produces the below output:

main - before handling - User[id=1, name=HCD]
handle - start for User[id=1, name=HCD]
handleFurther - start for User[id=1, name=HCD]
handleFurther - something specific for User[id=2, name=AD]
handleFurther - finished for User[id=1, name=HCD]
handle - finished for User[id=1, name=HCD]
main - after handling - User[id=1, name=HCD]

which exemplifies even clearer what has been already stated.

In case handle() would be called outside the scope (line 30) and the code re-run, a clear exception is thrown upon reaching this point – Exception in thread "main" java.util.NoSuchElementException: ScopedValue not bound.

Key points:

  • where(…).run(…) – binds the value for the duration of the lambda, then unbinds it automatically – there’s no need for manual cleanup.
  • Immutable within scope – once bound, it cannot be changed (but can be re-bound in a nested scope).
  • Cheap with virtual threads – no copying, just a reference.
  • Easy to reason about – the value is always what was bound at the top of the current scope
  • Good alternative to ThreadLocal which has unbounded lifetime, is mutable and pretty hard to reason about as its value can be changed anywhere in the call stack.
  • Works beautifully with Structured Concurrency (JEP 505) – child tasks automatically share the parent’s scoped values without copying.

To conclude, scoped variables contribute a lot to the concurrency cleanness and safety and helps preventing issues as memory leaks or stale data leaking.

Stable Values (JEP 502)

I see this enhancement as enforced effective immutability – both at instance and object level. If prior to Java 25 we created an instance, declared it final, initialized it and documented that it shall remain unchanged, the reality was sometimes different, as some “content” of the instance was still mutable. StableValue feature allows constructing immutable instances by all means so that once initialized, the object content is guaranteed to remain unchanged as well.

StableValues are a JVM enhancement that offers a way of achieving thread-safety and deep immutability, an alternative to accomplishing this via combining locks, synchronization, volatile variables and Atomic references.

The behavior is thread-safe by design, detail ensured by the JVM’s internal handling of StableValues.

Let’s examine the following code:

static class User {
private final StableValue<String> id = StableValue.of();
private final String name;
public User(String name) {
this.name = name;
}
public String id() {
return id.orElseSet(() -> UUID.randomUUID().toString());
}
public String name() {
return name;
}
@Override
public String toString() {
return name + " (" + id() + ")";
}
}
private record Task(CountDownLatch latch, Runnable runnable) implements Runnable {
@Override
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
runnable.run();
}
}
void main() {
var user1 = new User("HCD");
IO.println("Created " + user1);
var user2 = new User("Andrei");
IO.println("Created " + user2);
IO.println("User's unique identifiers are: " + user1.id() + ", " + user2.id());
}

Observations:

  • A User is simply described by two attributes – while the name is provided at construction time, the id represents an internal unique identifier.
  • id is declared as a StableValue and is lazily initialized when the value is read (if in a concurrent context, by the first thread that performs the action)   
  • Once initialized, this value is deeply immutable, it cannot be changed and remains as such until the object is destroyed

If run, the output is the following:

Created HCD (477a7dc1-c71f-4189-8c58-13994148ff95)
Created Andrei (47647539-9cbe-4890-af23-050ee1fe9379)
User's unique identifiers are: 477a7dc1-c71f-4189-8c58-13994148ff95, 47647539-9cbe-4890-af23-050ee1fe9379

It’s clear the ids are set when needed and their values persist whenever read subsequently.

One last observation is worth making regarding the User#id attribute – as a StableValue, it’s automatically thread-safe and lock-free. To demonstrate this let’s run the next piece of code.

void main() {
var user = new User("Concurrent User");
var latch = new CountDownLatch(1);
try (ExecutorService exec = Executors.newVirtualThreadPerTaskExecutor()) {
Future<?> result1 = exec.submit(new Task(latch,
() -> IO.println("Task1 - Id: " + user.id() +
" at " + System.currentTimeMillis())));
Future<?> result2 = exec.submit(new Task(latch,
() -> IO.println("Task2 - Id: " + user.id() +
" at " + System.currentTimeMillis())));
Future<?> result3 = exec.submit(new Task(latch,
() -> IO.println("Task3 - Id: " + user.id() +
" at " + System.currentTimeMillis())));
latch.countDown();
result1.get();
result2.get();
result3.get();
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
}

Task 1, 2 and 3 are created and set to read the id of the user created in advance, then executed in parallel. The below output demonstrates that in this particular run, Task 3 is the one that sets the id, and then Task 1 and 2 are using the same value.

Task3 - Id: f7e12b49-5c21-4898-883b-12013824a683 at 1773834965123
Task1 - Id: f7e12b49-5c21-4898-883b-12013824a683 at 1773834965123
Task2 - Id: f7e12b49-5c21-4898-883b-12013824a683 at 1773834965123

StableValue also comes with quite a few higher-level helper methods (function(), intFunction(), list(), map(), supplier()), each of them useful and suitable in various scenarios.

Below is an example of how the Singleton pattern could be implemented.

record User(int id, String name) {}
static class UserService {
public UserService() {
IO.println("UserService created");
}
public void register(User user) {
IO.println("Registered " + user);
}
}
static UserService getInstance() {
return USER_SERVICE_INSTANCE.orElseSet(UserService::new);
}
private static final StableValue<UserService> USER_SERVICE_INSTANCE = StableValue.of();
void main() {
getInstance().register(new User(1, "HCD"));
getInstance().register(new User(2, "Andrei"));
}

The aim is to have a single instance of the UserService that can be used to register users via the designated method. If we run it, the output is the one below.

UserService created
Registered User[id=1, name=HCD]
Registered User[id=2, name=Andrei]

which clearly shows the constructor is called only once.

To conclude, the StableValue enhancement ensures immutability enforced at JVM level – once the value is set, it’s stable and visible to all threads.

Conclusions

This article briefly covered a few Java 25 language enhancements, hoping that the straight-to-the-point examples presented offer a starting point for further deep-diving into these features.

Whether you have already migrated to the latest LTS or not, whether you have started exploring the latest additions and improvements, I consider this worth doing  whatsoever.

At JavaOne ’26, during one of the opening keynotes, I remarked this quote – “Java is everywhere AI needs to be”. I couldn’t agree more. In a world where apparently everybody is preoccupied by the “Accelerated Inference”, let’s remain optimistic on what the future will bring and continue to build and consolidate our Java foundation by exploring the new additions, trying to stay-up-to-date and embracing them gradually in our personal and professional projects.

Resources

[1] – JDK 25

[2] – Sample code is available here.

LLM Observability with Spring AI and Langfuse

by Horațiu Dan

Large Language Models are non-deterministic, opaque and billed per token. The moment you put one behind a real endpoint you start asking the same questions you ask of any production system – what did it actually receive, what did it answer, how long did it take, how much did it cost – plus a few that are unique to LLMs: which user asked, what was the full prompt after memory and system instructions were merged and is the model drifting?

Langfuse [Resource 1] is an open-source LLM engineering platform built to answer exactly those questions. While a previous article [Resource 4] explained how LLM engineering concerns as debugging, cost tracking or prompt organization can be addressed in a POC built with LangGraph and LangChain, the current one continues the experiment and presents how Langfuse could be of help in case of Spring AI projects.

Spring AI [Resource 2] is Spring’s abstraction over chat models and it ships with first-class Micrometer [Resource 3] observations. The two meet over OpenTelemetry (OTLP): Spring AI emits a span for every model call, OpenTelemetry ships those spans to Langfuse‘s OTLP ingestion endpoint, then Langfuse reconstructs them into traces you can search, filter and cost-attribute.

This article walks through building that integration end to end:

  1. Bootstrapping the Spring AI project
  2. Writing a minimal ChatAssistant that uses a ChatClient
  3. Adding the needed OpenTelemetry dependencies
  4. Configuring the Langfuse OTLP export
  5. Enriching spans with an ObservationFilter (prompts, completions, user/session IDs)

The full reference is the langfuse-spring-ai project [Resource 5], built with Java 25, Spring Boot 4.1.0, Spring AI 2.0.0.

Setting-Up the Spring AI Project

Spring AI is consumed through a BOM and a model starter. The BOM aligns all org.springframework.ai artifact version, while the starter (spring-ai-starter-model-openai) auto-configures a ChatClient.Builder, an OpenAiChatModel, and the supporting beans from a handful of properties.

Start from start.spring.io (or add the dependencies by hand) with Spring Web, OpenAI, and Actuator. The core of the pom.xml looks like this:

<properties>
<java.version>25</java.version>
<spring-ai.version>2.0.0</spring-ai.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

As the application class is the standard Spring Boot entry point, no AI-specific wiring is required, because the starter does it:

@SpringBootApplication
public class LangfuseSpringAiApplication {
static void main(String[] args) {
SpringApplication.run(LangfuseSpringAiApplication.class, args);
}
}

Configuration goes in application.yaml. The only mandatory AI property is the API key and it should never be committed. Read it from the environment instead. The project imports an optional .env file for local development and resolves the key from a placeholder:

spring:
config:
import: optional:file:.env[.properties]
application:
name: langfuse-spring-ai
ai:
openai:
api-key: ${OPEN_AI_API_KEY}

The spring.application.name matters more than it looks: it becomes the OpenTelemetry service.name resource attribute, which is how Langfuse labels the application a trace came from.

At this point you have a Spring Boot app that can talk to an OpenAI-compatible model (e.g. gpt-5-mini). Nothing is observable yet.

A Minimal ChatAssistant

Spring AI’s central abstraction is the ChatClient, a fluent wrapper around the underlying ChatModel. The key reason to use it (rather than calling the model API directly) is that every call through a ChatClient is automatically instrumented. That instrumentation is what we later ship to Langfuse, so going through the abstraction is not optional polish, it is the integration point.

The ChatAssistant builds a ChatClient from the auto-configured builder, gives it a default system prompt and attaches a memory advisor so the conversation has context across turns.

@Service
public class ChatAssistant {
private static final String DEFAULT_CONVERSATION_ID = "default";
private final ChatClient chatClient;
private final ChatMemory chatMemory;
public ChatAssistant(ChatClient.Builder chatClientBuilder,
ChatMemory chatMemory) {
this.chatMemory = chatMemory;
chatClient = chatClientBuilder
.defaultSystem("You are a helpful assistant. Provide short, meaningful answers.")
.defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
.build();
}
public String ask(String question) {
return chatClient.prompt()
.user(question)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, DEFAULT_CONVERSATION_ID))
.call()
.content();
}
public void clearConversation() {
chatMemory.clear(DEFAULT_CONVERSATION_ID);
}
}

As there is no UI in place for this experiment, a thin REST controller exposes the assistant and allows using it via HTTP directly. Note the userId and sessionId optional request parameters, they are not used by the model at all, but they exist purely so we can attribute traces to a user and a session in Langfuse. We’ll return to how they reach the span later in the article.

@RestController
@RequestMapping("/chat")
public class ChatController {
private static final Logger log = LoggerFactory.getLogger(ChatController.class);
private final ChatAssistant chatAssistant;
public ChatController(ChatAssistant chatAssistant) {
this.chatAssistant = chatAssistant;
}
@GetMapping
public String chat(@RequestParam("question")
String question,
@RequestParam(value = "userId", required = false, defaultValue = "421981")
String userId,
@RequestParam(value = "sessionId", required = false, defaultValue = "chat-123-abc")
String sessionId) {
if (!StringUtils.hasText(question)) {
return "Please ask a question.";
}
log.info("USER:\n\t {}", question);
UserSessionContext.set(userId, sessionId);
try {
var answer = chatAssistant.ask(question);
log.info("ASSISTANT:\n\t {}", answer);
return answer;
} finally {
UserSessionContext.clear();
}
}
@GetMapping("/clear")
public String clear() {
chatAssistant.clearConversation();
return "Conversation cleared.";
}
}

GET /chat?question=What is your cut-off date? now returns a model answer. If runnig the code and invoking the call, one may observe the following in the logs:

10:29:38.915 [http-nio-8080-exec-1] INFO c.h.langfusespringai.ChatController - USER:
What is your cut-oo-date?
10:29:43.523 [http-nio-8080-exec-1] INFO c.h.langfusespringai.ChatController - ASSISTANT:
My knowledge cutoff is June 2024. I don’t have reliable information about events or developments after that and can’t browse the web in real time.

Functionally complete, the small application works but it’s still a black box.

Adding the OpenTelemetry Dependencies

Spring AI produces observations through Micrometer’s ObservationRegistry. An observation is an abstract recording of “something happened”; it needs a backend to be turned into a concrete span and exported somewhere. For Langfuse, that path is:

Spring AI ChatModel
│ (Micrometer Observation)
▼
Micrometer Observation API
│ micrometer-tracing-bridge-otel ← turns observations into OTel spans
▼
OpenTelemetry SDK
│ opentelemetry-exporter-otlp ← serializes spans as OTLP
▼
Langfuse OTLP endpoint /api/public/otel

Three dependencies make this happen, plus Actuator (which contributes the ObservationRegistry and management infrastructure):

<!-- Management endpoints + the ObservationRegistry that observations are recorded into -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Spring Boot's OpenTelemetry tracing auto-configuration -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-opentelemetry</artifactId>
</dependency>
<!-- OTel starter: SDK auto-config driven by `otel.*` / `OTEL_*` properties -->
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-spring-boot-starter</artifactId>
</dependency>
<!-- Bridge: convert Micrometer observations into OpenTelemetry spans -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-bridge-otel</artifactId>
</dependency>
<!-- The OTLP wire exporter -->
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-otlp</artifactId>
</dependency>

The OTel instrumentation versions are aligned with their own BOM, kept separate from the Spring AI BOM:

<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-bom</artifactId>
<version>2.28.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>

Why both spring-boot-starter-opentelemetry and the OTel spring-boot-starter? The Spring Boot starter wires Micrometer tracing into Spring’s observation infrastructure, while the OpenTelemetry instrumentation starter brings the OTel SDK autoconfiguration that reads the otel.exporter.otlp.* properties we set in the next section.

Together they let you configure the export with plain OTel-style properties while keeping Spring AI’s Micrometer observations as the source of truth.

Configuring the Langfuse Integration

Langfuse exposes a standard OTLP/HTTP ingestion endpoint. To send traces there you need two things: the endpoint URL and a Basic auth header built from your Langfuse public/secret key pair.

Generating the auth header

Langfuse authenticates OTLP ingestion with HTTP Basic auth, where the username is the public key and the password is the secret key (both from your Langfuse project settings). The header value is the base64 encoding of public_key:secret_key:

# Base64 of "<langfuse-public-key>:<langfuse-secret-key>".
# Generate (PowerShell):
# [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("pk-lf-xxxx:sk-lf-xxxx"))
# Generate (bash):
# echo -n "pk-lf-xxxx:sk-lf-xxxx" | base64

Store that result in LANGFUSE_AUTH (and the key itself never goes near the YAML).

Before moving further, let’s quickly recall how one can get the Langfuse project keys that compound the authorization header. Upon accessing https://cloud.langfuse.com/ (the cloud version here, similarly when self-hosted), then the newly created project (langfuse-spring-ai) that resides in the configured organization (here hcd), navigate to Project Settings – API Keys and generate a pair of such keys.

The OTLP exporter configuration

Set the following in application.yml file.

otel:
exporter:
otlp:
endpoint: ${LANGFUSE_OTEL_ENDPOINT:https://cloud.langfuse.com/api/public/otel}
protocol: http/protobuf
headers:
Authorization: "Basic ${LANGFUSE_AUTH}"
# Only traces matter to Langfuse - turn off metric/log exporters so the SDK
# doesn't keep POSTing to /v1/metrics and /v1/logs and logging connection warnings.
metrics:
exporter: none
logs:
exporter: none
instrumentation:
spring-webmvc:
enabled: false
spring-web:
enabled: false

A few deliberate choices here:

  • protocol: http/protobuf – Langfuse‘s OTLP endpoint speaks OTLP over HTTP, not gRPC. Using the wrong protocol is the most common reason traces silently never arrive.
  • metrics.exporter: none / logs.exporter: none – Langfuse ingests traces. If you leave the metric and log exporters on, the SDK keeps trying to POST to /v1/metrics and /v1/logs, which Langfuse doesn’t serve, producing a stream of connection warnings. Disabling them keeps the logs clean and the traffic minimal.
  • spring-webmvc / spring-web instrumentation disabled – without this, every request produces an HTTP server span that becomes the parent of the LLM span. The HTTP span carries no LLM semantics and clutters the Langfuse trace list. Disabling it lets the gen_ai chat span stand on its own as the trace root.

The matching Micrometer/management settings on the Spring side:

spring:
ai:
chat:
observations:
# include the prompt content on the observation
log-prompt: true
# include the completion content on the observation
log-completion: true
management:
tracing:
sampling:
# sample every trace - you want all LLM calls in dev
probability: 1.0
observations:
annotations:
enabled: true
enable:
# mirror the OTel side: no HTTP spans
"http.server.requests": false
"http.client.requests": false
otlp:
metrics:
export:
# Micrometer OTLP metrics off - traces only
enabled: false

spring.ai.chat.observations.log-prompt / log-completion tell Spring AI to attach the prompt and completion text to the observation. By default Spring AI omits message content (it can contain sensitive data), so without these flags your Langfuse traces would show timings, token counts and model parameters, but not what was actually “discussed”. Enabling them is what makes the trace useful for debugging prompt quality.

Security note: log-prompt/log-completion put raw user input and model output into your traces. That is exactly what you want in development and for most internal tools, but think carefully before enabling it in environments handling PII or regulated data.

With sampling.probability at 1.0, every call through the ChatClient is now exported to Langfuse. You’ll see traces appear with model, latency and token usage. The last piece is enriching them with prompt/completion text and user/session attributes.

Enriching Spans with an ObservationFilter

Out of the box the Langfuse trace tells you a call happened and how long it took. To make it genuinely useful we want three more things on the span:

  1. The full prompt sent to the model (system + memory + user message, merged).
  2. The completion returned.
  3. The user and session IDs, so Langfuse can group traces by user and conversation.

Micrometer provides exactly the right hook: an ObservationFilter. A filter runs as each observation is recorded and can mutate its Context, adding key/value pairs that become span attributes. Spring AI’s chat observations use a ChatModelObservationContext, which exposes the request and response objects, so the filter can pull content straight out of them.

Carrying user/session across the singleton boundary

The ObservationFilter is a singleton Spring bean, but userId and sessionId arrive as per-request parameters in the controller (an implementation choice as part of this POC). We need to hand those request-scoped values to the singleton while the call runs on the request thread.

A ThreadLocal holder bridges the gap cleanly:

public final class UserSessionContext {
private record UserSession(String userId, String sessionId) {}
private static final ThreadLocal<UserSession> HOLDER = new ThreadLocal<>();
private UserSessionContext() {}
public static void set(String userId, String sessionId) {
HOLDER.set(new UserSession(userId, sessionId));
}
public static Optional<String> userId() {
var current = HOLDER.get();
return current != null ? Optional.of(current.userId()) : Optional.empty();
}
public static Optional<String> sessionId() {
var current = HOLDER.get();
return current != null ? Optional.of(current.sessionId()) : Optional.empty();
}
public static void clear() {
HOLDER.remove();
}
}

The controller (shown the second section above) sets the context before calling the assistant and clears it in a finally block – essential, because thread-pool threads are reused and a leaked ThreadLocal would mis-attribute the next request’s trace.

Because the synchronous ChatClient.call() runs on the same request thread, the ThreadLocal is visible to the filter. If you move to reactive or async execution, swap this for Micrometer’s context-propagation mechanism so the values follow the work across thread boundaries.

The filter

@Component
public class ContentObservationFilter implements ObservationFilter {
@Override
public Observation.Context map(Observation.Context context) {
if (!(context instanceof ChatModelObservationContext observationContext)) {
return context; // not a chat-model observation — leave it untouched
}
// 1. The full prompt: every instruction message merged into one string
List<String> prompts = observationContext.getRequest().getInstructions().stream()
.map(Content::getText)
.toList();
observationContext.addHighCardinalityKeyValue(
KeyValue.of("gen_ai.prompt", ObservabilityHelper.concatenateStrings(prompts))
);
// 2. The completion(s), only present once the response has come back
List<String> completions = Collections.emptyList();
if (observationContext.getResponse() != null) {
completions = observationContext.getResponse().getResults().stream()
.map(generation -> generation.getOutput().getText())
.filter(Objects::nonNull)
.toList();
}
observationContext.addHighCardinalityKeyValue(
KeyValue.of("gen_ai.completion", ObservabilityHelper.concatenateStrings(completions))
);
// 3. User & session attributes that Langfuse uses for grouping
UserSessionContext.userId()
.ifPresent(userId ->
observationContext.addLowCardinalityKeyValue(KeyValue.of("langfuse.user.id", userId)));
UserSessionContext.sessionId()
.ifPresent(sessionId ->
observationContext.addLowCardinalityKeyValue(KeyValue.of("langfuse.session.id", sessionId)));
return observationContext;
}
}

Marking it @Component is all the wiring needed. Spring Boot registers any ObservationFilter bean with the ObservationRegistry automatically.

A few details worth understanding:

  • High vs. low cardinality. Prompt and completion text are unique per call, so they go in as high-cardinality values. User and session IDs have a bounded, repeating set of values and are useful for filtering/aggregation, so they go in as low-cardinality values. The distinction matters for backends that turn low-cardinality keys into metric dimensions; for tracing it primarily signals intent.
  • getResponse() may be null. The filter runs both when the observation starts (no response yet) and when it stops. Guarding the response read avoids an NPE on the opening pass.
  • The langfuse.user.id / langfuse.session.id attribute names are conventions Langfuse recognizes. When it ingests a span carrying these attributes, it populates the trace’s User and Session fields, unlocking the “all traces for user X” and “this conversation” views — plus per-user cost and usage breakdowns.
  • gen_ai.prompt / gen_ai.completion follow the OpenTelemetry GenAI semantic conventions, which Langfuse maps onto its input/output panels.

Putting it Together

With all five pieces in place, a single GET /chat?question=…&userId=…&sessionId=… now does the following:

  1. The controller stashes userId/sessionId in the ThreadLocal and calls the assistant.
  2. ChatAssistant invokes the model through the ChatClient, which records a Micrometer chat observation.
  3. ContentObservationFilter enriches that observation with the merged prompt, the completion, and the user/session IDs.
  4. The Micrometer – OTel bridge turns the observation into a span; the OTLP exporter ships it to Langfuse.
  5. The controller clears the ThreadLocal.

In Langfuse you get a trace per call, complete with model, latency, token usage and cost, the exact prompt and response and the ability to filter and group by user and session. All without the ChatAssistant knowing anything about observability. That separation is the point: the business logic stays clean and observability is layered on through configuration and a single filter bean.

Verifying it works

# Set the environment (don't commit these)
export OPEN_AI_API_KEY=sk-...
export LANGFUSE_AUTH=$(echo -n "pk-lf-xxx:sk-lf-xxx" | base64)
export LANGFUSE_OTEL_ENDPOINT=https://cloud.langfuse.com/api/public/otel
# Run
./mvnw spring-boot:run # Windows: mvnw.cmd spring-boot:run
# Ask a question
curl "http://localhost:8080/chat?question=Explain%20Java%20observability%20in%20one%20sentence&userId=421982&sessionId=chat-321-abc"

Within some time the trace shows up in your Langfuse dashboard, attributed to user 421982 and session chat-321-abc, with the full prompt and completion attached.

Summary

Breaking responsibilities per layers would briefly result in the following:

LayerResponsibility
spring-ai-starter-model-openaiThe ChatClient and auto-instrumented model calls
ChatAssistantBusiness logic — system prompt + chat memory
Actuator + OTel + Micrometer bridge + OTLP exporterTurn observations into exported spans
application.yaml (otel., spring.ai.chat.observations.)Point the export at Langfuse, opt into content logging
ContentObservationFilter + UserSessionContextEnrich spans with prompt, completion, and user/session attributes

The architecture’s strength is that observability is additive. Spring AI emits observations for free, OpenTelemetry is pure configuration and the one piece of code you write — the ObservationFilter — is decoupled from your application logic. Swap the model, change the prompt, or move to a different OTLP backend and the observability layer keeps working unchanged.

Resources

  1. Langfuse Docs
  2. Spring AI Reference
  3. Micrometer
  4. Observability for LLM Applications: Debugging, Cost Tracking and Prompt Organization with Langfuse – article
  5. langfuse-spring-ai project code

Observability for LLM Applications: Debugging, Cost Tracking and Prompt Organization with Langfuse

by Horațiu Dan

LLM-powered applications rarely consist of a single model call. Even modest agents chain several prompts together, possibly route between models and accumulate state along the way. When something goes wrong (a weak answer, an unexpectedly high invoice, a prompt that behaves differently after a “small” tweak) the standard toolbox (logs and a debugger) tells only part of the story. What is actually needed is visibility into every model interaction: the exact rendered prompt, the raw completion, the token counts, the latency and the cost, all correlated to the user and session that produced them.

This article shows how Langfuse [Resource 1] addresses these needs, using a small but representative proof of concept: an article-writing agent built with LangGraph and LangChain. It first introduces Langfuse briefly, then walks through the POC and its set-up, and finally describes how Langfuse was applied to simplify debugging, track costs and organize prompts.

What is Langfuse?

Langfuse is an open-source AI engineering platform that helps teams debug, analyze and iterate on LLM applications. Its core capabilities are:

  • Observability and tracing – every LLM call, chain step and tool invocation is captured as an observation inside a trace. Traces can be grouped into sessions, attributed to users, tagged and enriched with metadata. Agent workflows can be visualized as graphs.
  • Cost and usage monitoring – token usage and model costs are computed per generation and aggregated per trace, user, session, tag or model.
  • Prompt management – prompts are created, versioned and deployed from the Langfuse UI, decoupling prompt iteration from code deployments. A built-in playground allows interactive testing and version comparison.
  • Evaluation – LLM-as-a-judge evaluators, user feedback capture, datasets and experiments support systematic quality assessment.

Langfuse is available as a managed cloud service or self-hosted and provides SDKs for Python and JavaScript along with native integrations for LangChain, LangGraph, the OpenAI SDK and other popular frameworks [Resource 1].

The Proof of Concept

The POC is a deliberately small agent that writes a short article on a user-supplied topic by following a classic write → reflect → revise pattern. It is implemented as a three-node LangGraph state machine:

  1. generate_draft – a generalist writer model produces an initial draft on the topic.
  2. reflect_on_draft – a reviewer model critiques the draft and produces feedback.
  3. revise_draft – the writer refines the original draft through reflection using the feedback.

The state flowing through the graph is an immutable Pydantic model:

Python
class ArticleState(BaseModel):
"""State of the article creation process flow."""
model_config = ConfigDict(validate_assignment=True, frozen=True, extra="forbid")
session_id: str = Field(description="The unique identifier of the session execution")
user_id: str = Field(description="The unique identifier of the user")
topic: str = Field(description="The article topic")
draft: str = Field(description="The initial draft of the article", default="")
reflection: str = Field(description="The feedback on the draft", default="")
revised: str = Field(description="The final revised article", default="")

The graph itself is assembled in a dedicated class, keeping the flow definition separate from the business logic:

Python
class WriteArticleFlow:
"""Builds and compiles the write-reflect-revise article graph."""
def __init__(self) -> None:
self._writer = ArticleWriter()
def build(self) -> CompiledStateGraph:
graph = StateGraph(ArticleState)
graph.add_node("generate_draft", self._generate_draft_node)
graph.add_node("reflect_on_draft", self._reflect_on_draft_node)
graph.add_node("revise_draft", self._revise_draft_node)
graph.add_edge(START, "generate_draft")
graph.add_edge("generate_draft", "reflect_on_draft")
graph.add_edge("reflect_on_draft", "revise_draft")
graph.add_edge("revise_draft", END)
return graph.compile()
def _generate_draft_node(self, state: ArticleState) -> dict:
draft = self._writer.generate_draft(state.topic)
logger.info("Draft:\n%s", draft)
return {"draft": draft}
def _reflect_on_draft_node(self, state: ArticleState) -> dict:
feedback = self._writer.reflect_on_draft(state.draft)
logger.info("Feedback:\n%s", feedback)
return {"reflection": feedback}
def _revise_draft_node(self, state: ArticleState) -> dict:
revised = self._writer.revise_draft(state.draft, state.reflection)
logger.info("Revised:\n%s", revised)
return {"revised": revised}

Each node delegates to an ArticleWriter, which encapsulates the three prompts and runs them through a thin, generic OpenAI client built on LangChain:

Python
class OpenAiClient:
"""Generic client for running prompted LLM chains via OpenAI."""
def __init__(self, api_key: str | None = None) -> None:
self._api_key = SecretStr(api_key or os.environ.get("OPEN_AI_API_KEY", ""))
def run(self, system: str, user: str, variables: dict, model: str = "gpt-4o", temperature: float = 1.0) -> str:
llm = ChatOpenAI(model=model, temperature=temperature, api_key=self._api_key)
prompt = ChatPromptTemplate.from_messages([("system", system), ("human", user)])
chain = prompt | llm | StrOutputParser()
return chain.invoke(variables)

One detail worth noticing related to this POC: the drafting and revising steps use gpt-4o, while the reflection step (a simpler critique task) deliberately runs on the cheaper gpt-4o-mini. This kind of per-step model routing is exactly the sort of decision that cost tracking should validate, as shown later.

Set-Up

The POC targets Python 3.13 and uses the following key dependencies:

  • langgraph – the state-machine orchestration of the flow
  • langchain / langchain-openai – prompt templating and the OpenAI chat model
  • langfuse – the observability SDK (v3) with its LangChain integration
  • pydantic – the validated, immutable flow state
  • python-dotenv – environment configuration

Connecting to Langfuse requires an account (Langfuse Cloud or a self-hosted instance) and a project, from which a public/secret key pair is generated. The SDK is configured entirely through environment variables, loaded here from a .env file:

LANGFUSE_PUBLIC_KEY=pk-lf-...
LANGFUSE_SECRET_KEY=sk-lf-...
LANGFUSE_HOST=https://cloud.langfuse.com # or the self-hosted URL http://localhost:3000
OPEN_AI_API_KEY=sk-...

Since the rest of the application silently degrades when observability is missing, the entry point verifies the Langfuse connection up front and fails fast if the credentials are wrong:

Python
try:
Langfuse()
client = get_client()
authenticated = client.auth_check()
if not authenticated:
raise Exception("Langfuse authentication failed")
except Exception:
logger.error("Langfuse client connection failed", exc_info=True)
raise SystemExit(1)
user_id = input("User Identifier: ").strip()
topic = input("Topic: ").strip()
article = asyncio.run(
compile_article(
ArticleState(session_id=str(uuid.uuid4()), user_id=user_id, topic=topic),
langfuse_client=client,
)
)

Langfuse() initializes the client singleton from the environment variables, get_client() retrieves it, and auth_check() performs an actual round-trip to the configured host. This three-line ritual has saved more debugging time than it appears to – a typo in a key otherwise manifests only as traces quietly never showing up.

The application is then started from the command line; it asks for a user identifier and a topic, generates a fresh session_id and runs the flow as it will be seen below (compile_article() async method).

Applying Langfuse

Instrumenting the Flow

Because the POC is built on LangChain and LangGraph, instrumentation is almost free: Langfuse ships a CallbackHandler that plugs into LangChain‘s standard callback mechanism. Passed once at the graph’s invocation, it automatically traces every chain, prompt rendering and model call executed underneath. No changes to ArticleWriter or OpenAiClient are required:

Python
async def compile_article(initial_state: ArticleState, langfuse_client: Any) -> dict:
langfuse_handler = CallbackHandler()
with propagate_attributes(
session_id=initial_state.session_id,
user_id=initial_state.user_id,
metadata={
"check_toxic_content": str(True)
},
tags=["Article Compilation"],
trace_name=f"article-{initial_state.session_id}",
):
final_state = (
await WriteArticleFlow().build()
.ainvoke(
initial_state,
config=RunnableConfig(callbacks=[langfuse_handler]),
)
)
langfuse_client.flush()
return final_state

Two pieces do the heavy lifting here:

  • CallbackHandler converts LangChain‘s runtime events into Langfuse observations, preserving the hierarchy: the graph invocation becomes the root, each LangGraph node becomes a nested span and each ChatOpenAI call becomes a generation carrying the rendered messages, the completion, the model name, token usage and latency.
  • propagate_attributes enriches everything traced inside its scope with cross-cutting context: the session_id (grouping multiple runs into a Langfuse session), the user_id (enabling per-user analytics), free-form metadata, tags for filtering and a human-readable trace_name.

Finally, flush() is called before the process exits. The SDK batches and ships events asynchronously for performance; in a short-lived CLI process, flushing explicitly guarantees nothing is lost when the interpreter shuts down. In a long-running service this is generally unnecessary.

Simplifying Debugging

With the handler in place, every run of the agent produces a single trace in the Langfuse UI named article-. Opening it shows the full execution tree:

article-3f2a... (trace)
└─ LangGraph
├─ generate_draft
│ └─ ChatOpenAI (gpt-4o) — rendered prompt, completion, tokens, latency
├─ reflect_on_draft
│ └─ ChatOpenAI (gpt-4o-mini) — rendered prompt, completion, tokens, latency
└─ revise_draft
└─ ChatOpenAI (gpt-4o) — rendered prompt, completion, tokens, latency

This transforms debugging in several concrete ways:

  • The intermediate states are visible. When the final article is disappointing, the trace immediately answers the first diagnostic question: was the draft weak, was the reflection unhelpful, or did the revision ignore good feedback? Each node’s input and output is right there – no need to re-run with extra logging.
  • The exact prompts are visible. The trace shows the messages as the model received them, after template variable substitution. Off-by-one formatting issues, missing variables or unexpectedly long interpolated content are spotted at a glance.
  • Latency is broken down per step. The waterfall view shows where time is spent, making it obvious whether a slow run is caused by one model call or distributed across the chain.
  • Failures are contextualized. An exception in any node is recorded on the corresponding span, together with everything that happened before it.

Because traces carry the user_id, session_id and tags propagated earlier, a bug report like “user X got a bad article yesterday” turns into a thirty-second filtered search instead of an archaeology session through application logs.

A complete view of the trace in Langfuse UI is shown below:

Tracking Costs

Each generation captured by the CallbackHandler includes the model name and token usage, from which Langfuse computes the cost using its built-in model price definitions (custom models and prices can be registered as well). No additional code is involved.

For this POC, the dashboard makes the economics of the flow immediately legible:

  • Per trace – what one article costs end to end, split across the three steps.
  • Per model – how spend distributes between gpt-4o and gpt-4o-mini. This directly validates the routing decision described earlier: the reflection step runs at a fraction of the cost of the drafting steps and the dashboard quantifies exactly how much the downgrade saves without having to instrument anything.
  • Per user and per session – because propagate_attributes attaches user_id and session_id to every trace, costs can be aggregated by who triggered them, which is the foundation for quota enforcement or per-customer billing in a real product.
  • Over time – usage dashboards reveal trends and anomalies, such as a prompt change that silently doubled the average completion length (and therefore the output-token bill).

The picture below displays the Langfuse Cost Dashboard.

Organizing Prompts

The reflection and revision steps keep their prompts as string literals inside ArticleWriter. This is fine for a proof of concept, but with a familiar failure mode: every tweak is a code change, a review and a deployment and there is no record of which prompt version produced which output. To show the alternative, the drafting step was migrated to Langfuse-managed prompts.

A prompt named article/generate-draft is created and versioned in the Langfuse UI (as a chat prompt with system and user messages, the {{topic}} variable and optionally a model/temperature config), assigned a deployment label such as production and fetched at runtime instead of being hardcoded:

Python
GENERATE_DRAFT_PROMPT = "article/generate-draft"
def generate_draft(self, topic: str) -> str:
prompt = get_client().get_prompt(GENERATE_DRAFT_PROMPT)
config = prompt.config or {}
return self._client.run_managed_prompt(
prompt,
variables={"topic": topic},
model=config.get("model", "gpt-4o"),
temperature=config.get("temperature", 1.0),
)

get_client() returns the same Langfuse singleton initialized at start-up and get_prompt retrieves the labelled version (the SDK caches it locally, so the network round-trip happens once and runtime coupling to Langfuse availability stays minimal). The prompt’s stored config supplies the model and temperature, so those routing decisions become configuration rather than code, with a safe fallback to the previous defaults.

The client converts the managed prompt into a LangChain template and, crucially, links it back to the generation so the trace records which prompt version was used:

Python
def run_managed_prompt(self, prompt, variables, model="gpt-4o", temperature=1.0) -> str:
llm = ChatOpenAI(model=model, temperature=temperature, api_key=self._api_key)
chat_prompt = ChatPromptTemplate.from_messages(prompt.get_langchain_prompt())
chat_prompt.metadata = {"langfuse_prompt": prompt} # links version to the generation
chain = chat_prompt | llm | StrOutputParser()
return chain.invoke(variables)

prompt.get_langchain_prompt() translates the Langfuse message list (with its {{topic}} placeholders) into LangChain‘s {topic} format and attaching the prompt object under the langfuse_prompt metadata key tells the CallbackHandler to associate this generation with that exact prompt version. The remaining two steps keep using the literal-based run method, so the codebase deliberately shows both patterns side by side.

The benefits of the managed approach compound quickly:

  • Versioning and rollback – every change is recorded; reverting a regression is a label switch, not a redeployment.
  • Traceability – because the prompt is linked to the generations it produced, the trace view shows not just what was sent to the model, but which prompt version it came from, making A/B comparisons measurable rather than anecdotal.
  • Collaboration – non-engineers can iterate on prompt wording in the playground against real traced inputs, without touching the codebase.
  • Config alongside text – model and parameters live with the prompt, so model routing decisions also become configuration rather than code.
  • Migrating the remaining two steps would be mechanical: register article/reflect-on-draft and article/revise-draft in Langfuse and replace their run calls with run_managed_prompt.

Evaluating Output with LLM-as-a-Judge

Tracing, cost tracking and prompt management cover the operational side, but they leave one question unanswered: is the output actually good? is it safe? Langfuse answers this with LLM-as-a-judge evaluators: a separate model scores a trace’s output against a rubric and writes the verdict back onto the trace as a score, where it can be filtered, aggregated and alerted on just like cost.

The POC already plants the hook for exactly this. Looking back at the instrumentation, every trace is tagged with a metadata flag:

Python
with propagate_attributes(
session_id=initial_state.session_id,
user_id=initial_state.user_id,
metadata={"check_toxic_content": str(True)}, # ← per-run evaluation flag
tags=["Article Compilation"],
trace_name=f"article-{initial_state.session_id}",
):
...

check_toxic_content is not consumed by the application code at all – it is a deliberate, per-run feature flag whose only purpose is to tell Langfuse which traces should be put through the toxicity judge. Keeping it in metadata (rather than hardcoding “always evaluate”) means the decision can be driven by anything the caller knows: enable it for untrusted users, for certain topics, for a sampled percentage, or for a higher service tier. All without redeploying.

The evaluator itself is configured entirely in the Langfuse UI, with no further application code:

  1. Create the evaluator. Pick the managed toxicity template (or author a custom LLM-as-a-judge prompt that returns a SAFE / TOXIC verdict plus reasoning) and choose the judge model.
  2. Map the input. Point the evaluator’s input variable at the trace’s final output (the revised article produced by the last node) so it judges what the user actually receives.
  3. Scope it with the flag. Set the evaluator’s target filter so it runs only on traces whose metadata matches the flag:
metadata.check_toxic_content = "True"

Note the value is the string “True“. The code passes str(True), so the filter compares against the stringified form, not a boolean.

Langfuse then runs the judge server-side on every new trace that matches the filter, attaching a toxicity score (e.g. categorical safe/toxic, or a 0–1 value) together with the judge’s rationale. Because scores are first-class trace data, the payoff mirrors the rest of the integration:

  • Filter the trace list to surface every output flagged toxic, with the offending article and the full generation chain one click away.
  • Aggregate the toxicity rate over time, per user or per prompt version – turning “did that prompt change make outputs riskier?” into a measurable line on a dashboard.
  • Alert when the rate crosses a threshold, catching a regression before users report it.

The entire capability cost the application a single line of metadata; the judging logic, model and rollout live as configuration in Langfuse. A natural next step would be to read the score back in-process and gate the response when a draft is judged toxic, but even left purely observational the evaluator converts safety from an assumption into a tracked, queryable metric.

In order to configure it in Langfuse, a new LLM-as-a-judge evaluator needs to be added, after previously setting-up a default LLM connection.

With this in place, if the agent is run again, upon examining the trace, the toxicity “measure” appears.

Conclusion

The POC required exactly one observability-specific construct in application code (a callback handler plus an attribute-propagation scope at the composition root) and in exchange produced complete, queryable visibility into a multi-step, multi-model agent. Debugging moved from log archaeology to inspecting a structured trace; cost analysis came for free from captured token usage and validated a per-step model routing decision; prompt management offers a clear path to take prompts out of the codebase entirely; and a single metadata flag was enough to wire in an LLM-as-a-judge toxicity check, turning output safety into a tracked metric. Across all four dimensions the pattern was the same – minimal, declarative hooks in code, with the heavy lifting handled by Langfuse as configuration. For LLM applications of any non-trivial structure, this combination is hard to argue against. Especially given that Langfuse is open source and can be self-hosted when data governance demands it.

Resources

  1. Langfuse Documentation
  2. Langfuse LangChain / LangGraph Integration
  3. Langfuse Prompt Management
  4. Langfuse LLM-as-a-Judge Evaluation
  5. LangGraph Documentation
  6. POC code is available here

From Prototype to Production: Building Business-Driven Spring AI Applications

by Horațiu Dan

Abstract

Model Context Protocol (MCP) is becoming a standard way when it comes to enhancing AI assistants and agents, nevertheless for many teams aiming to embrace it, it acts as another black box.

This article mainly outlines MCP in its endeavor to enrich the context AI assistants possess, especially when real business insights are needed during the ongoing interactions.

Readers will learn how the protocol has been elevating AI-driven software development so that LLMs can successfully work with concrete business data and provide users accurate and practical pieces of information as needed.

The writing is a more code-centric one, designed as a step-by-step tutorial, where an integration between an AI assistant and clearly focused MCP servers exposing tools is gradually (de-)coded using Java and Spring AI. Several use cases and workflows are exemplified. Moreover, production wise ‘-ilities’ are brought into the picture and discussed, while demonstrating how one might address such concerns without adding unnecessary complexity. 

The concrete implementation aims to follow the plan below:

  • Start with a simple Telecom AI Assistant – an AI Host connected to an LLM
  • Build two independent specialized MCP Servers and integrate them for use over HTTP
  • Secure the MCP client-server communication using API keys
  • Address concerns as chat memory and token consumption monitoring via Advisors

The goal is to have as guidance a few helpful ideas which may be used when building production-ready AI applications.

Introduction

When it was released by Anthropic, MCP was quickly supported by almost all big players in the field as it proposed to solve, with an elegant solution, two of the biggest problems of AI tools: access to specific system’s data and the integration of the existing tool stack. And it did.

With a great deal of enthusiasm, MCP was largely embraced and a lot of such servers were developed and made public as the problem it tried to solve – the data quality – has always been the hidden variable in AI.

Having a plug-and-play architecture, MCP is a key player to enabling AI applications (and agents) to interact seamlessly with external tools and real business data. With MCP, intermediary client and server programs handle the communication between AI systems and external tools or data sources, providing a standardized messaging format and a set of interfaces that developers use for integration. I consider valuable its Write Once, Run Everywhere (WORA) mindset, similar to the one of Java applications.

From a high-level point of view, MCP uses a client-server architecture. As LLMs are text generators, they cannot invoke anything, thus other pieces of software are needed. Mainly, there are two modules involved, the client sends requests to the servers and the servers respond to them.

Main characteristics of the two are depicted in the picture below.

An AI application might use multiple MCP Servers, but each one of these has their own 1:1 dedicated connection.

Integration Workflow

A complete workflow in such an integration when at least one MCP server is involved could be:

  1. A user sends a request to the AI application (AI host)
  2. The Tool Manager has at hand all available MCP servers’ tools’ definitions with the help of the MCP clients
  3. The Tool Manager sends the tools’ definitions to the LLM together with the previously issued user request
  4. The LLM detects a certain MCP server tool is needed and responds suggesting to the MCP client that particular tool call
  5. The designated MCP client triggers the call to the MCP server, which further interrogates the external data source
  6. Once available, the MCP server provides the response back to the MCP client
  7. The MCP client sends the response received to the LLM
  8. The LLM uses the context to generate the actual user response and sends it back to the AI application
  9. The AI application delivers to the user the final response

This type of integration has three main characteristics – pluggable, discoverable and composable (a server might be the client of another server) – which makes it a very versatile and flexible one.

Implementation

The three applications developed by the end of this tutorial are all using Java 25, Spring Boot 3.5.11 and Spring AI 1.1.4. Spring AI is a great way of abstracting the AI providers and workflows.

  • telecom-assistant – a simple web application that integrates an AI chat connected to an OpenAI model (gpt-5), running on port 8080
  • invoice-mcp-server – MCP server exposing invoice-related tools, running on port 8081
  • vendor-mcp-server – MCP server exposing vendor-related tools, running on port 8082

Both MCP servers use MCP Spring Security 0.1.5, while the invoice one uses additionally Asentinel ORM 1.72.1 to connect to a PostgreSQL database that contains the business data.

The versions used are the latest stable ones at the time of this writing.

The desired integration is represented in the following picture:

For simplicity, all three applications are independent modules of the telecom-ai-assistant project. To be sure of the recommended Spring dependencies used, the spring-ai-bom is configured in the parent pom.xml file.

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

Consequently, all children modules will inherit from here. In order to be more meaningful, they are built and enhanced gradually so that at the end of this article the complete implementation is available [Resource 1].

To follow along, it’s advisable to start on branch 1-main, solve the indicated TODOs to accomplish the goals while reading the tutorial (clear explanations are provided) and switch to other branches as further indicated.

By the end, the code will look as the one on the main branch.

Build the AI Host – telecom-assistant

The web application is straight-forward, it has a single page that displays the dialog where users interact with the chosen LLM, which in this case is gpt-5 from Open AI. Thus, the following are set in the application.properties file.

spring.ai.openai.chat.options.model = gpt-5
spring.ai.openai.api-key = ${OPEN_AI_J_API_KEY}
spring.ai.openai.chat.options.temperature = 1

The actual model interaction is carried out from the code via the initial implementation of ChatAssistant service, that declares a ChatClient instance.

@Service
public class ChatAssistant {
private final ChatClient chatClient;
private final ChatMemory chatMemory;
public ChatAssistant(ChatClient.Builder builder, ChatMemory chatMemory) {
this.chatMemory = chatMemory;
chatClient = builder
.defaultSystem("You are a helpful Telecom AI assistant. Provide short, meaningful answers.")
.defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
.build();
}
public String ask(String question) {
return chatClient.prompt()
.user(question)
.call()
.content();
}
public List<ChatMessage> conversationMessages() {
return chatMemory.get(DEFAULT_CONVERSATION_ID).stream()
.filter(msg -> msg.getMessageType() == MessageType.USER ||
msg.getMessageType() == MessageType.ASSISTANT)
.map(msg -> new ChatMessage(msg.getMessageType() == MessageType.USER ? Type.USER : Type.ASSISTANT,
msg.getText()))
.toList();
}
public void clearConversation() {
chatMemory.clear(DEFAULT_CONVERSATION_ID);
}
}

Together with the ChatClient.Builder, a ChatMemory instance is included so that the conversation becomes contextual and the model is aware of the previous messages received and responded to. This is accomplished with the help of a MessageChatMemoryAdvisor, provided when the ChatClient instance is constructed. Details on what advisors are and how they are used, later in the tutorial. For now, a maximum of 50 such messages are kept in memory.

@Bean
public ChatMemory chatMemory() {
return MessageWindowChatMemory.builder()
.maxMessages(50)
.build();
}

conversationMessages() method retrieves the MessageType.USER and MessageType.ASSISTANT for the current conversation and packages them as ChatMessage s for user-friendly display in the UI.

public record ChatMessage(Type type, String content) {
public enum Type {
USER,
ASSISTANT
}
}

clearConversation() method erases the memory for the current conversation.

Once the incipient ChatAssistant class is implemented, it’s further injected into the below ChatController.

@Controller
public class ChatController {
private static final Logger log = LoggerFactory.getLogger(ChatController.class);
private final ChatAssistant assistant;
public ChatController(ChatAssistant assistant) {
this.assistant = assistant;
}
@GetMapping("/")
public String home(Model model) {
model.addAttribute("messages", assistant.conversationMessages());
return "chat";
}
@PostMapping("/chat")
public String chat(@RequestParam("question") String question) {
if (!StringUtils.hasText(question)) {
return "redirect:/";
}
log.info("USER:\n\t{}", question);
var answer = assistant.ask(question);
log.info("ASSISTANT:\n\t{}", answer);
return "redirect:/";
}
@PostMapping("/chat/clear")
public String clear() {
assistant.clearConversation();
return "redirect:/";
}
}

The methods together with the declared mappings are straight-forward, they allow handling the three possible user actions, that is display the page, ask a question and clear the conversation history.

Before running the telecom-assistant for the first time, one shall first create the telecomassist database schema as this is managed dynamically via flyway migrations from this project.

create schema telecomassist;

Once available, upon application start-up, the migrations that reside in telecom-ai-assistant\telecom-assistant\src\main\resources\db\migration, create and seed Vendors, ServiceTypes, Invoices tables with sample data

and also the ServerApiKeys table (holds API keys used later when securing the MCP servers).

When up and running, users may ask questions and the LLM will definitely generate the best answers it could under the circumstances of the available context. When it comes to inquires related to private business data, for instance ‘How many paid invoices are there?’, one can imagine it couldn’t respond meaningfully, although it seems it does its best.

In this regard, additional context related to Invoices and Vendors would be useful to the LLM and thus, two MCP servers are constructed.

Build and Integrate invoice-mcp-server and vendor-mcp-server

The former reads the ‘business’ data from the telecomassist schema that resides in a PostgreSQL database, while the latter, out of simplicity, delivers pieces of info kept in memory. Let’s take them one at a time.

Invoice MCP Server

The pom.xml file inherits from its previously mentioned parent one and declares the following dependencies:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
</dependency>
<dependency>
<groupId>com.asentinel.common</groupId>
<artifactId>asentinel-common</artifactId>
<version>1.72.1</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>

Regarding the first two, as the communication is over HTTP, the WebMVC server transport is used. This starter activates McpWebMvcServerAutoConfiguration and provides HTTP-based transport using Spring MVC and automatically configured endpoints. Concerning the last two, they are needed to access the database, they represent the used ORM and the driver respectively.

The aim is to implement the following three MCP tools and make them available:

  • get-paid-invoices-count – to retrieve the number of paid invoices
  • get-paid-invoices-total-amount – to retrieve the total amount of all paid invoices
  • get-invoices-by-pattern-on-number – to retrieve the invoices whose numbers contain the provided pattern

By reading their names, they seem pretty straight forward from the data retrieval point of view. Yet, several entities and a service are needed so that these could be further used to implement the actual MCP tools.

To model Invoice, Vendor and ServiceType entities, the below simple classes and enums are created.

@Table("Invoices")
public class Invoice {
public static final String COL_NUMBER = "Number";
public static final String COL_STATUS = "Status";
public static final String COL_TOTAL = "Total";
@PkColumn("Id")
private int id;
@Column(value = COL_NUMBER)
private String number;
@Column("Date")
private LocalDate date;
@Child(fkName = "VendorId", fetchType = FetchType.LAZY)
private Vendor vendor;
@Child(fkName = "ServiceTypeId", fetchType = FetchType.LAZY)
private ServiceType serviceType;
@Column(value = COL_STATUS)
private InvoiceStatus status;
@Column("Total")
private double total;
...
}
@Table("Vendors")
public class Vendor {
@PkColumn("id")
private int id;
@Column("name")
private String name;
...
}
@Table("ServiceTypes")
public class ServiceType {
@PkColumn("id")
private int id;
@Column("name")
private String name;
...
}
public enum InvoiceStatus {
UNDER_REVIEW,
APPROVED,
PAID
}

The model is simple. Invoices are from a specific vendor, of a specific serviceType, in a certain status and are described by a number, date and obviously have a total amount. A Vendor is described by its name.

The annotations placed are specific to the Asentinel ORM [Resource 2] and are used to map these to database tables.

Data source related properties are set in application.properties file.

spring.datasource.url = jdbc:postgresql://localhost:5432/postgres?currentSchema=telecomassist
spring.datasource.username = ${POSTGRES_USER}
spring.datasource.password = ${POSTGRES_PASSWORD}

Once these in place, they can be leveraged to configure the data access.

@Configuration
@EnableAsentinelOrm
public class DataAccessConfig {
@Bean
public DataSource dataSource(@Value("${spring.datasource.url}") String url,
@Value("${spring.datasource.username}") String username,
@Value("${spring.datasource.password}") String password) {
return new SingleConnectionDataSource(url, username, password, false);
}
}

@EnableAsentinelOrm annotation detects the underlying database and performs all the necessary infra set-up so that the ORM can be used [Resource 2].

Ultimately, the last step without MCP flavor is completed – an InvoiceService is developed to retrieve the actual data.

@Service
public class InvoiceService {
private final Logger log = LoggerFactory.getLogger(InvoiceService.class);
private final OrmOperations orm;
public InvoiceService(OrmOperations orm) {
this.orm = orm;
}
@Transactional(readOnly = true)
public int countByStatus(InvoiceStatus status) {
log.info("Counting invoices in status '{}'.", status);
return orm.newSqlBuilder(Invoice.class)
.selectK().countId()
.from(EntityDescriptorNodeCallback.rootOnlyQuery())
.where()
.column(Invoice.COL_STATUS).eq(status.name())
.execForInt();
}
@Transactional(readOnly = true)
public Double totalByStatus(InvoiceStatus status) {
log.info("Computing the total amount of invoices in status '{}'.", status);
return orm.newSqlBuilder(Invoice.class)
.selectK().sql("sum").lp().column(Invoice.COL_TOTAL).rp()
.from(EntityDescriptorNodeCallback.rootOnlyQuery())
.where()
.column(Invoice.COL_STATUS).eq(status.name())
.execForObject(Double.class);
}
@Transactional(readOnly = true)
public List<Invoice> findByPattern(String pattern) {
log.info("Retrieving invoices containing '{}' in their number.", pattern);
return orm.newSqlBuilder(Invoice.class)
.select(AutoEagerLoader.forPath(Invoice.class, Vendor.class),
AutoEagerLoader.forPath(Invoice.class, ServiceType.class))
.where()
.column(Invoice.COL_NUMBER).like('%' + pattern + '%')
.exec();
}
}

The API is intuitive and proposes a method for each of the aimed tools.

Once this service is available, it is injected in the InvoiceTools component to complete the implementation.

@Component
public class InvoiceTools {
private final InvoiceService invoiceService;
public InvoiceTools(InvoiceService invoiceService) {
this.invoiceService = invoiceService;
}
@McpTool(name = "get-paid-invoices-count",
description = "Retrieves the number of paid invoices")
public int countPaidInvoices() {
return invoiceService.countByStatus(InvoiceStatus.PAID);
}
@McpTool(name = "get-paid-invoices-total-amount",
description = "Retrieves the total amount of all paid invoices")
public double totalPaidInvoices() {
return invoiceService.totalByStatus(InvoiceStatus.PAID);
}
@McpTool(name = "get-invoices-by-pattern-on-number",
description = "Retrieves the invoices whose numbers contain the provided pattern")
public List<Invoice> invoicesBy(@ToolParam(description = "The pattern used for filtering invoices") String pattern) {
return invoiceService.findByPattern(pattern);
}
}

We specify the name and the description of the tools, together with its parameters, if any. When invoked, the results of each are further sent to the client application and used by the LLM to have a better view of the context.

To configure the MCP Server, a couple more properties prefixed by spring.ai.mcp.server are added into the application.properties file.

spring.ai.mcp.server.name = telecom-invoice-mcp-server
spring.ai.mcp.server.version = 1.0.0
spring.ai.mcp.server.instructions = Instructions - endpoint: /mcp-invoice, type: sync, protocol: streamable
spring.ai.mcp.server.type = sync
spring.ai.mcp.server.protocol = streamable
spring.ai.mcp.server.streamable-http.mcp-endpoint = /mcp-invoice
spring.ai.mcp.server.capabilities.tool = true
spring.ai.mcp.server.capabilities.completion = false
spring.ai.mcp.server.capabilities.prompt = false
spring.ai.mcp.server.capabilities.resource = false

In addition to the server’s name and type, which are obvious, the ones that designate the version and the instructions are pretty important. The version of the instance is sent to clients and used for compatibility checks, while the instructions property provides guidance upon initialization and allows clients to get hints on how to utilize the server.

spring.ai.mcp.server.streamable-http.mcp-endpoint is the server endpoint so that it’s reachable by clients at http://localhost:8081/mcp-invoice.

The last four properties in the above snippet define the server capabilities (here, only tools).

At this point, this server implementation is finalized. Spring AI takes care of all other necessary details. To test it, the MCP Inspector [Resource 3] is used. Its documentation clearly describes the needed prerequisites to run it and provides details on the available configurations.

Once up and running, it can be accessed using the below link.

> npx @modelcontextprotocol/inspector
Starting MCP inspector...
Proxy server listening on localhost:6277
Session token: e25104347279e0404b7b44afb0eb6c8b865c387554dc0afd66ed9aee99d45685
Use this token to authenticate requests or set DANGEROUSLY_OMIT_AUTH=true to disable auth
MCP Inspector is up and running at:
http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=e25104347279e0404b7b44afb0eb6c8b865c387554dc0afd66ed9aee99d45685

Prior to connecting to the running invoice-mcp-server, the transport type is set to be Streamable HTTP and the URL, http://localhost:8081/mcp-invoice. When connected, the tools may be listed, invoked, analyzed.

The below picture exemplifies the execution of get-paid-invoices-total-amount tool, which returns 551.75, result that may be confronted with the actual data to conclude it works correctly.

Vendor MCP Server

Concerning the vendor-mcp-server, the implementation is similar and way simpler as data is delivered from memory.

The endpoint is set in the application.properties

spring.ai.mcp.server.streamable-http.mcp-endpoint = /mcp-vendor

making it reachable at http://localhost:8082/mcp-vendor.

It exposes just one tool – get-vendor-information – thus, the component that configures it looks as below.

@Component
public class VendorTools {
private final VendorService vendorService;
public VendorTools(VendorService vendorService) {
this.vendorService = vendorService;
}
@McpTool(name = "get-vendor-information",
description = "Provides information about the vendor with the provided name")
public String vendorInfo(String name) {
return vendorService.infoByName(name);
}
}

Just as for the previous invoice server, there is a service that actually delivers the data. Here, a dummy, in memory one:

@Service
public class VendorService {
public String infoByName(String name) {
if (name == null) {
name = "";
}
return switch (name.toLowerCase()) {
case "verizon" -> "Leading provider of tech solutions.";
case "vodafone" -> "Specializes in cloud services.";
case "orange" -> "Expert in cybersecurity.";
case "att" -> "Focuses on 5G technology.";
default -> "No info available";
};
}
}

Again, when up and running, it can be tested with the MCP Inspector.

Plugging-in the MCP Servers

Now that the two MCP servers are ready, in order for them to “contribute” together with the LLM, the telecom-assistant needs a few improvements, that allow integrating MCP clients. There are 2 TODOs in the source code (1-main branch) that need to be addressed.

TODO 1. In order to enable the MCP client and configure the MCP servers, the following are added in the application.properties.

spring.ai.mcp.client.name = telecom-mcp-client
spring.ai.mcp.client.version = 1.0.0
spring.ai.mcp.client.request-timeout = 30s
spring.ai.mcp.client.toolcallback.enabled = true
spring.ai.mcp.client.streamable-http.connections.invoice.url = http://localhost:8081
spring.ai.mcp.client.streamable-http.connections.invoice.endpoint = /mcp-invoice
spring.ai.mcp.client.streamable-http.connections.vendor.url = http://localhost:8082
spring.ai.mcp.client.streamable-http.connections.vendor.endpoint = /mcp-vendor

TODO 2. Inside ChatAssistant, when the ChatClient is built, the ToolCallbackProvider instance created by the framework is injected and used and the constructor becomes:

public ChatAssistant(ChatClient.Builder builder,
ToolCallbackProvider toolCallbackProvider,
ChatMemory chatMemory) {
this.chatMemory = chatMemory;
chatClient = builder
.defaultSystem("You are a helpful Telecom AI assistant. Provide short, meaningful answers.")
.defaultToolCallbacks(toolCallbackProvider)
.defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
.build();
log.info("Available tools:\n{}",
Arrays.stream(toolCallbackProvider.getToolCallbacks())
.map(ToolCallback::getToolDefinition)
.map(Object::toString)
.collect(Collectors.joining("\n")));
}

The injected SyncMcpToolCallbackProvider instance automatically discovers and exposes tools from the two MCP servers as Spring AI ToolCallback instances, which are basically the tools whose executions can be triggered by an AI model.

Additionally, although not necessarily needed, the available tools are displayed upon the bean construction.

To check the integration, with the two MCP servers running, the assistant is restarted and the logs analyzed. The connection handshake is carried out, the connections initialized and one can also observe there are four tools available – the ones exposed by the servers:

16:45:38.510 [main] INFO c.h.t.service.ChatAssistant - Available tools:
DefaultToolDefinition[name=get_vendor_information, description=Provides information about the vendor with the provided name, inputSchema={"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}]
DefaultToolDefinition[name=get_paid_invoices_count, description=Retrieves the number of paid invoices, inputSchema={"type":"object","properties":{},"required":[]}]
DefaultToolDefinition[name=get_invoices_by_pattern_on_number, description=Retrieves the invoices whose numbers contain the provided pattern, inputSchema={"type":"object","properties":{"pattern":{"type":"string"}},"required":["pattern"]}]
DefaultToolDefinition[name=get_paid_invoices_total_amount, description=Retrieves the total amount of all paid invoices, inputSchema={"type":"object","properties":{},"required":[]}]

Now, if asking two very specific questions as ‘What’s the total for the paid invoices?’ and ‘Provide a short info for ‘orange’ vendor.’, the servers are invoked and more meaningful answers are provided.

invoice-mcp-server logs display the below details:

DEBUG i.m.spec.McpSchema - Received JSON message: {"jsonrpc":"2.0","method":"tools/call","id":"1bfac8a9-2","params":{"name":"get-paid-invoices-total-amount","arguments":{},"_meta":{}}}
DEBUG i.m.s.t.WebMvcStreamableServerTransportProvider - Streamable session transport 8e9479f8-f7b6-41c6-b5a7-ecc498d1eca8 initialized with SSE builder
INFO c.h.i.service.InvoiceService - Computing the total amount of invoices in status 'PAID'.
DEBUG c.a.c.o.e.t.DefaultEntityDescriptorTreeRepository - getEntityDescriptorTree - The tree for class com.hcd.invoiceserver.domain.Invoice is NOT cached.
DEBUG c.a.common.jdbc.SqlQueryTemplate - query - sql: select sum ( t0.Total ) from Invoices t0 where t0.Status = ?
DEBUG c.a.common.jdbc.SqlQueryTemplate - query - with parameters: ['PAID']
DEBUG i.m.s.t.WebMvcStreamableServerTransportProvider - Message sent to session 8e9479f8-f7b6-41c6-b5a7-ecc498d1eca8 with ID null
DEBUG i.m.s.t.WebMvcStreamableServerTransportProvider - Successfully completed SSE builder for session 8e9479f8-f7b6-41c6-b5a7-ecc498d1eca8
DEBUG i.m.s.t.WebMvcStreamableServerTransportProvider - Request response stream completed for session: 8e9479f8-f7b6-41c6-b5a7-ecc498d1eca8

Similarly, the tool invocation appears in the logs of the vendor-mcp-server:

DEBUG i.m.spec.McpSchema - Received JSON message: {"jsonrpc":"2.0","method":"tools/call","id":"706ed5e6-2","params":{"name":"get-vendor-information","arguments":{"name":"orange"},"_meta":{}}}
DEBUG i.m.s.t.WebMvcStreamableServerTransportProvider - Streamable session transport b2343788-b767-4c5e-9951-18c2c4a128cc initialized with SSE builder
DEBUG i.m.s.t.WebMvcStreamableServerTransportProvider - Message sent to session b2343788-b767-4c5e-9951-18c2c4a128cc with ID null
DEBUG i.m.s.t.WebMvcStreamableServerTransportProvider - Successfully completed SSE builder for session b2343788-b767-4c5e-9951-18c2c4a128cc
DEBUG i.m.s.t.WebMvcStreamableServerTransportProvider - Request response stream completed for session: b2343788-b767-4c5e-9951-18c2c4a128cc

Obviously, each 1:1 info exchange happens in a separate session.

Secure the MCP Client-Server Communication with API Keys

According to the MCP Specification, MCP servers that use HTTP as their transport layer shall be secured with OAuth 2.0 access tokens. There are situations though, in which an infrastructure supporting all the needed entities (authorization servers etc.) is not available and thus, the communication still needs to be secured. This tutorial assumes such a simplified case and exemplifies how an MCP server can be configured to authorize only those MCP clients’ requests that send the proper API key as a designated HTTP header.

The picture below sketches the flow and the requirements to accomplish that.

invoice-mcp-server will keep the API keys in the database, while vendor-mcp-server in memory. We opted for such an approach out of exploratory reasons. The MCP client, that is telecom-assistant will analyze the request towards an MCP server at runtime (if any) and delegate to a chain of resolvers to detect the particular destination and add the appropriate security header. Every MCP server has obviously its own API key id and secret.

It’s now the right moment to switch to the 2-main branch and upon resolving the TODOs in there, this goal will have been fulfilled.

Let’s start with the vendor-mcp-server.

TODO 1. The needed security dependencies are added into the pom.xml file.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springaicommunity</groupId>
<artifactId>mcp-server-security</artifactId>
<version>0.1.5</version>
</dependency>

TODO 2. Since the API keys are stored in memory in this case, they are declared in the application.properties file, still as environmental variables.

api.key.id = ${API_KEY_ID}
api.key.secret = ${API_KEY_SECRET}

TODO 3. The main aspect regarding this enhancement is the security configuration. In this regard, the below @Configuration class is added.

@EnableWebSecurity
@Configuration
public class SecurityConfig {
@Value("${api.key.id}")
private String apiKeyId;
@Value("${api.key.secret}")
private String apiKeySecret;
@Bean
ApiKeyEntityRepository<ApiKeyEntity> apiKeyRepository() {
return new InMemoryApiKeyEntityRepository<>(
List.of(ApiKeyEntityImpl.builder()
.name("API key")
.id(apiKeyId)
.secret(apiKeySecret)
.build()));
}
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.with(McpApiKeyConfigurer.mcpServerApiKey(),
apiKeyConfig -> apiKeyConfig.apiKeyRepository(apiKeyRepository())
.headerName("vendor-x-api-key"))
.build();
}
}

A single ApiKeyEntity instance is constructed and stored as part of an InMemoryApiKeyEntityRepository. Then, when the SecurityFilterChain is built, a SecurityConfigurerAdapter is applied and an McpApiKeyConfigurer is used via which two concerns are addressed. On one hand the expected security header name is set – vendor-x-api-key, while on the other, the repository that stores the server API key.

At this point the MCP server is secured. In order to be able to successfully communicate, an MCP client shall send HTTP requests that contain the required header that has the following form:

"vendor-x-api-key": [api-key-id].[api-key-secret]

where api-key-id and api-key-secret are replaced with the values configured above.

To test this functionality, the MCP Inspector [Resource 3] is used again and additionally, before connecting to the running server, the authentication data is configured – vendor-x-api-key header is set to the known id.secret value.

Switching to the invoice-mcp-server, the enhancements here are a bit more complex as the API keys are store in an external repository.

TODO 4. Again the security dependencies are added in the pom.xml file, as before.

TODO 5. As API keys are stored in the database, more exactly in the ServerApiKeys table, an mapping entity is created.

@Table("ServerApiKeys")
public class ServerApiKey {
public static final String COL_SERVER = "Server";
public static final String COL_KEY_ID = "KeyId";
public static final String ON_CONFLICT_CLAUSE = String.format("(%s,%s)", COL_SERVER, COL_KEY_ID);
@PkColumn("Id")
private int id;
@Column(COL_SERVER)
private String server;
@Column(COL_KEY_ID)
private String keyId;
@Column("KeySecret")
private String keySecret;
...
}

As the Asentinel ORM library is already present in this module’s class-path, it is used to manage these entities, thus the class is decorated with specific annotations.

TODO 6. Just as previously done for the vendor server, the security configuration needs an ApiKeyEntityRepository. The approach here is more general, the interface is implemented and the specific manner is suited.

public class DbApiKeyEntityRepository implements ApiKeyEntityRepository<DbApiKeyEntityRepository.InvoiceApiKeyEntity> {
private final OrmOperations orm;
public DbApiKeyEntityRepository(OrmOperations orm) {
this.orm = orm;
}
@Override
public InvoiceApiKeyEntity findByKeyId(@NonNull String keyId) {
return orm.newSqlBuilder(ServerApiKey.class)
.select()
.where()
.column(ServerApiKey.COL_SERVER).eq("invoice-mcp").and()
.column(ServerApiKey.COL_KEY_ID).eq(keyId)
.execForOptional()
.map(serverApiKey ->
new InvoiceApiKeyEntity(keyId, serverApiKey.getKeySecret()))
.orElse(null);
}
}

As every record (API key) in the table is uniquely identified by Server and KeyId, whenever a request is received, the repository checks it and returns an implementation of the ApiKeyEntity interface, in our case

public static final class InvoiceApiKeyEntity implements ApiKeyEntity {
private final String id;
@Nullable
private String secret;
private InvoiceApiKeyEntity(String id, @Nullable String secret) {
this.id = id;
this.secret = secret;
}
@Override
public String getId() {
return id;
}
@Override
public @Nullable String getSecret() {
return secret;
}
@Override
public void eraseCredentials() {
this.secret = null;
}
@Override
public InvoiceApiKeyEntity copy() {
return new InvoiceApiKeyEntity(id, secret);
}
}

built from the database entity, upon retrieval.

It is a good practice to keep the secret of a ServerApiKey entity encoded in the database. In this tutorial, the default one – bcrypt – is used. To check the repository, the following simple integration test is used.

@SpringBootTest
@Transactional
class DbApiKeyEntityRepositoryTest {
private DbApiKeyEntityRepository apiKeyRepository;
@Autowired
private OrmOperations orm;
private final PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
@BeforeEach
public void setUp() {
apiKeyRepository = new DbApiKeyEntityRepository(orm);
}
@Test
void provisionServerApiKey() {
ServerApiKey serverApiKey = new ServerApiKey();
serverApiKey.setServer("invoice-mcp");
serverApiKey.setKeyId("api-key-id");
serverApiKey.setKeySecret(passwordEncoder.encode("api-key-secret"));
orm.upsert(serverApiKey,
PostgresJdbcFlavor.UPSERT_CONFLICT_PLACEHOLDER, ServerApiKey.ON_CONFLICT_CLAUSE);
DbApiKeyEntityRepository.InvoiceApiKeyEntity apiKey = apiKeyRepository.findByKeyId(serverApiKey.getKeyId());
Assertions.assertNotNull(apiKey);
Assertions.assertEquals(serverApiKey.getKeyId(), apiKey.getId());
Assertions.assertEquals(serverApiKey.getKeySecret(), apiKey.getSecret());
}
}

TODO 7. Once this is completed, the security configuration is set up, just as before. The only difference is that the previously created ApiKeyEntityRepository repository implementation is used and not an in-memory one this time.

@Configuration
@EnableWebSecurity
public class SecurityConfig {
private OrmOperations orm;
@Autowired
public void setOrm(OrmOperations orm) {
this.orm = orm;
}
@Bean
ApiKeyEntityRepository<DbApiKeyEntityRepository.InvoiceApiKeyEntity> apiKeyRepository() {
return new DbApiKeyEntityRepository(orm);
}
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.with(McpApiKeyConfigurer.mcpServerApiKey(),
apiKeyConfig -> apiKeyConfig.apiKeyRepository(apiKeyRepository())
.headerName("invoice-x-api-key"))
.build();
}
}

At this point, the invoice-mcp server is secured as well, it can be checked with the MCP Inspector.

The last step is to enhance the telecom-assistant to be able to send the necessary security pieces of info when needing to perform a particular server interrogation.

TODO 8. The expected API keys’ ids and secrets for the two servers are configured in the application.properties and for convenience, read from environment values. For simplicity, here both read from the same, although in a real implementation would not.

mcp.server.api-key.parameters.invoice.id = ${API_KEY_ID}
mcp.server.api-key.parameters.invoice.secret = ${API_KEY_SECRET}
mcp.server.api-key.parameters.vendor.id = ${API_KEY_ID}
mcp.server.api-key.parameters.vendor.secret = ${API_KEY_SECRET}

Then, mapped into a @ConfigurationProperties annotated class.

@ConfigurationProperties(McpServerApiKeyProperties.CONFIG_PREFIX)
public class McpServerApiKeyProperties {
public static final String CONFIG_PREFIX = "mcp.server.api-key";
private final Map<String, ApiKeyParams> parameters = new HashMap<>();
public Map<String, ApiKeyParams> getParameters() {
return parameters;
}
public record ApiKeyParams(String id, String secret) {}
}

TODO 9. As there are two MCP servers involved, whenever the LLM instructs the AI host that it needs to query one of them, a destination resolving strategy applied at runtime is introduced. It’s implemented as a chain of MCP server resolvers.

The common interface of this chain of responsibility is McpServerResolver. It’s generic and declares two methods as part of the contract it proposes.

public interface McpServerResolver<T> {
Optional<T> resolve(URI uri);
default String id() {
return getClass().getSimpleName();
}
}

The central method that each implementer shall define receives the destination uri and attempts to resolve one of the available servers. If successful, the result is further used.

The second optional method has the particular scope of identifying the current resolver, it has a default implementation and might help down the line during the resolving process (logging etc.).

As the items in the chain here have a similar approach, the next part is an abstract common implementation of the above interface.

abstract class AbstractMcpServerResolver<T> implements McpServerResolver<T> {
private static final Logger log = LoggerFactory.getLogger(AbstractMcpServerResolver.class);
private final McpServerResolver<T> next;
protected AbstractMcpServerResolver(McpServerResolver<T> next) {
this.next = next;
}
@Override
public Optional<T> resolve(URI uri) {
if (uri == null) {
return Optional.empty();
}
log.debug("[{}]: Checking request towards {}.", id(), uri);
Optional<T> result = resolveSpecific(uri);
if (result.isPresent()) {
log.debug("[{}]: Resolved target endpoint {}.", id(), uri);
return result;
}
if (next == null) {
log.debug("[{}]: No next resolver configured.", id());
return Optional.empty();
}
log.debug("[{}]: Target endpoint {} not resolved. Delegating to [{}].", id(), uri, next.id());
return next.resolve(uri);
}
protected abstract Optional<T> resolveSpecific(URI endpoint);
}

The particular action is to be defined by each link in the chain as part of the Optional resolveSpecific(URI endpoint) method. Here the functionality is similar, thus the next common implementation is enough.

public class UrlMcpServerResolver extends AbstractMcpServerResolver<ApiKeyHeader> {
private static final Logger log = LoggerFactory.getLogger(UrlMcpServerResolver.class);
private final URI serverUri;
private final ApiKeyHeader header;
public UrlMcpServerResolver(McpServerResolver<ApiKeyHeader> nextResolver,
String serverUrl,
ApiKeyHeader header) {
super(nextResolver);
this.serverUri = URI.create(serverUrl);
this.header = header;
}
@Override
protected Optional<ApiKeyHeader> resolveSpecific(URI endpoint) {
if (serverUri.equals(endpoint)) {
log.debug("[{}]: Target endpoint {} and config URL {} match.", id(), endpoint, serverUri);
return Optional.of(header);
}
log.debug("[{}]: Target endpoint {} and config URL {} don't match.", id(), endpoint, serverUri);
return Optional.empty();
}
}

TODO 10. The above resolveSpecific() method decides whether the current request is towards a particular server. If successful, an ApiKeyHeader object is returned so that it can be further used.

public record ApiKeyHeader(String name, String value) {}

TODO 11. The last step is the security @Configuration class that glues together the above created pieces.

@Configuration
@EnableConfigurationProperties({McpServerApiKeyProperties.class})
public class SecurityConfig {
private static final Logger log = LoggerFactory.getLogger(SecurityConfig.class);
public McpStreamableHttpClientProperties mcpClientProps;
public McpServerApiKeyProperties mcpServerApiKeys;
@Autowired
public void setMcpClientProps(McpStreamableHttpClientProperties mcpClientProps) {
this.mcpClientProps = mcpClientProps;
}
@Autowired
public void setMcpServerApiKeys(McpServerApiKeyProperties mcpServerApiKeys) {
this.mcpServerApiKeys = mcpServerApiKeys;
}
@Bean
ApiKeyHeader invoiceApiKeyHeader() {
var apiKey = mcpServerApiKeys.getParameters().get("invoice");
return new ApiKeyHeader("invoice-x-api-key",
String.format("%s.%s", apiKey.id(), apiKey.secret()));
}
@Bean
ApiKeyHeader vendorApiKeyHeader() {
var apiKey = mcpServerApiKeys.getParameters().get("vendor");
return new ApiKeyHeader("vendor-x-api-key",
String.format("%s.%s", apiKey.id(), apiKey.secret()));
}
@Bean
McpServerResolver<ApiKeyHeader> serverResolver() {
var mcpProps = mcpClientProps.getConnections();
var mcpInvoice = mcpProps.get("invoice");
var mcpVendor = mcpProps.get("vendor");
return new VendorMcpServerResolver(new InvoiceMcpServerResolver(null,
String.format("%s%s", mcpInvoice.url(), mcpInvoice.endpoint()),
invoiceApiKeyHeader()),
String.format("%s%s", mcpVendor.url(), mcpVendor.endpoint()),
vendorApiKeyHeader());
}
@Bean
McpSyncHttpClientRequestCustomizer requestCustomizer() {
return (builder, method, endpoint, body, context) -> {
log.info("MCP Client request: method={}, endpoint={}, body={}", method, endpoint, body);
serverResolver()
.resolve(endpoint)
.ifPresent(apiKeyHeader -> builder.header(apiKeyHeader.name(), apiKeyHeader.value()));
};
}
}

The McpServerResolver returned by serverResolver() is used by the McpSyncHttpClientRequestCustomizer to analyze the request and add the necessary security header.

Upon reaching this point, the MCP servers are restarted, together with the telecom-assistant. If the prompt in the below screen-shot is issued, obviously the invoice server should be queried and the response is received accordingly.

In the AI host logs, the server resolving process can be depicted.

DEBUG i.m.c.t.HttpClientStreamableHttpTransport - Sending message JSONRPCRequest[jsonrpc=2.0, method=tools/call, id=2902fe67-2, params=CallToolRequest[name=get-invoices-by-pattern-on-number, arguments={pattern=vdf}, meta={}]]
INFO c.h.t.config.SecurityConfig - MCP Client request: method=POST, endpoint=http://localhost:8081/mcp-invoice, body={"jsonrpc":"2.0","method":"tools/call","id":"2902fe67-2","params":{"name":"get-invoices-by-pattern-on-number","arguments":{"pattern":"vdf"},"_meta":{}}}
DEBUG c.h.t.c.r.AbstractMcpServerResolver - [VendorMcpServerResolver]: Checking request towards http://localhost:8081/mcp-invoice.
DEBUG c.h.t.c.r.UrlMcpServerResolver - [VendorMcpServerResolver]: Target endpoint http://localhost:8081/mcp-invoice and config URL http://localhost:8082/mcp-vendor don't match.
DEBUG c.h.t.c.r.AbstractMcpServerResolver - [VendorMcpServerResolver]: Target endpoint http://localhost:8081/mcp-invoice not resolved. Delegating to [InvoiceMcpServerResolver].
DEBUG c.h.t.c.r.AbstractMcpServerResolver - [InvoiceMcpServerResolver]: Checking request towards http://localhost:8081/mcp-invoice.
DEBUG c.h.t.c.r.UrlMcpServerResolver - [InvoiceMcpServerResolver]: Target endpoint http://localhost:8081/mcp-invoice and config URL http://localhost:8081/mcp-invoice match.
DEBUG c.h.t.c.r.AbstractMcpServerResolver - [InvoiceMcpServerResolver]: Resolved target endpoint http://localhost:8081/mcp-invoice.
DEBUG i.m.c.t.HttpClientStreamableHttpTransport - Received SSE stream response, using line subscriber
DEBUG i.m.spec.McpSchema - Received JSON message: {"jsonrpc":"2.0","id":"2902fe67-2","result":{"content":[{"type":"text","text":"[{\"id\":8,\"number\":\"vdf-tf-rev-1\",\"date\":\"2025-05-20\",\"vendor\":{\"id\":2,\"name\":\"Vodafone\"},\"serviceType\":{\"id\":3,\"name\":\"TollFree\"},\"status\":\"UNDER_REVIEW\",\"total\":10.44},{\"id\":7,\"number\":\"vdf-mpls-app-1\",\"date\":\"2025-05-10\",\"vendor\":{\"id\":2,\"name\":\"Vodafone\"},\"serviceType\":{\"id\":4,\"name\":\"MPLS\"},\"status\":\"APPROVED\",\"total\":80.44},{\"id\":6,\"number\":\"vdf-lo-paid-1\",\"date\":\"2025-06-10\",\"vendor\":{\"id\":2,\"name\":\"Vodafone\"},\"serviceType\":{\"id\":5,\"name\":\"Local\"},\"status\":\"PAID\",\"total\":85.44}]"}],"isError":false}}

Enhance the telecom-assistant with Spring AI Advisors

The last part of this tutorial is dedicated to telecom-assistant, without any modifications to the two MCP servers. The aim is to leverage a few Spring AI Advisors (both ready-to-use and custom implemented) and observe how they function and how they could be helpful during the interactions with the LLMs. Personally, I see them as a way of applying Aspect Oriented Programming concepts as part of AI development.

As a matter of fact, if we recollect from the beginning of this tutorial, when the ChatClient was constructed, in order to enable the chat memory and transform a conversation from a stateless into a stateful one, MessageChatMemoryAdvisor was used. Before moving on with the implementation of another two (TokenUsageAdvisor and MessageLoggerAdvisor) and see them in action, a few details in general are worth mentioning.

The central interface to implement is CallAdvisor and its default behavior is as below:

public interface CallAdvisor extends Advisor {
@Override
default ChatClientResponse adviseCall(ChatClientRequest chatClientRequest, CallAdvisorChain callAdvisorChain) {
ChatClientRequest processedChatClientRequest = before(chatClientRequest, callAdvisorChain);
ChatClientResponse chatClientResponse = callAdvisorChain.nextCall(processedChatClientRequest);
return after(chatClientResponse, callAdvisorChain);
}
}

There are three clear steps that are outlined – logic that is executed before the rest of the advisor chain, then the rest of the advisors are called and then, logic executed after. Depending on the advisor type, the before, the after or both parts are addressed, nevertheless, the advisor chain is invoked and the response returned.

One last consideration is regarding the advisors’ order of execution, given by the Ordered#getOrder() method. The ones with higher precedence (lower order value) are executed before the ones with lower precedence (higher order value) when the before() method processes the request and vice-versa when after() processes the response, the ones with lower before those with higher precedence. The picture below visually summarizes this detail.

It’s now a good moment to switch to 3-main branch of the project and address the existing TODOs and complete the implementation.

TODO 1. Add a new advisor that tracks the token usage.

public class TokenUsageAdvisor implements BaseAdvisor {
private static final Logger log = LoggerFactory.getLogger(TokenUsageAdvisor.class);
private final AtomicInteger promptTokenCount = new AtomicInteger(0);
private final AtomicInteger completionTokenCount = new AtomicInteger(0);
private final AtomicInteger totalTokenCount = new AtomicInteger(0);
private final int order;
private final TokenCountEstimator tokenCountEstimator;
public TokenUsageAdvisor(int order) {
this.order = order;
tokenCountEstimator = new JTokkitTokenCountEstimator();
}
@Override
public ChatClientRequest before(ChatClientRequest chatClientRequest, AdvisorChain advisorChain) {
List<Message> messages = chatClientRequest.prompt().getInstructions();
int tokenCount = messages.stream()
.mapToInt(msg -> {
var text = switch (msg) {
case UserMessage userMsg -> userMsg.getText();
case AssistantMessage assistantMsg -> assistantMsg.getText();
case SystemMessage systemMsg -> systemMsg.getText();
default -> "";
};
return tokenCountEstimator.estimate(text);
})
.sum();
log.debug("Request: {} messages ~ {} estimated tokens.", messages.size(), tokenCount);
return chatClientRequest;
}
@Override
public ChatClientResponse after(ChatClientResponse chatClientResponse, AdvisorChain advisorChain) {
Optional.ofNullable(chatClientResponse.chatResponse())
.map(ChatResponse::getMetadata)
.map(ChatResponseMetadata::getUsage)
.ifPresent(usage -> {
int currentPrompt = usage.getPromptTokens();
int currentCompletion = usage.getCompletionTokens();
int currentTotal = usage.getTotalTokens();
log.info("Current tokens - \nPrompt: {} Completion: {} Total: {}",
currentPrompt, currentCompletion, currentTotal);
int accPrompt = promptTokenCount.addAndGet(currentPrompt);
int accCompletion = completionTokenCount.addAndGet(currentCompletion);
int accTotal = totalTokenCount.addAndGet(currentTotal);
log.info("Accumulated tokens - \nPrompt: {} Completion: {} Total: {}",
accPrompt, accCompletion, accTotal);
});
return chatClientResponse;
}
@Override
public int getOrder() {
return order;
}
public int totalTokens() {
return totalTokenCount.get();
}
public void clearUsage() {
promptTokenCount.set(0);
completionTokenCount.set(0);
totalTokenCount.set(0);
}
}

In the before() stage, a JTokkitTokenCountEstimator instance is used to estimate how many tokens the user, assistant and system messages represent. During after(), the actual prompt, completion and total token consumption are accumulated for an objective view on this matter. 

TODO 2. A second additional advisor is added, one that logs the messages in a particular manner. The main ultimate goal is to have a few (3 in the case of this tutorial) and to observe how the execution chain is executed.

public class MessageLoggerAdvisor implements BaseAdvisor {
private static final Logger log = LoggerFactory.getLogger(MessageLoggerAdvisor.class);
private final int order;
public MessageLoggerAdvisor(int order) {
this.order = order;
}
@Override
public ChatClientRequest before(ChatClientRequest chatClientRequest, AdvisorChain advisorChain) {
Prompt prompt = chatClientRequest.prompt();
Object tools = "N/A";
if (prompt.getOptions() instanceof ToolCallingChatOptions toolOptions) {
tools = toolOptions.getToolCallbacks().stream()
.map(callback -> callback.getToolDefinition().name())
.toList();
}
log.info("Tools: {}", tools);
String messages = prompt.getInstructions().stream()
.map(ModelOptionsUtils::toJsonString)
.collect(Collectors.joining("\n"));
log.info("Request:\n{}", messages);
return chatClientRequest;
}
@Override
public ChatClientResponse after(ChatClientResponse chatClientResponse, AdvisorChain advisorChain) {
String messages = Optional.ofNullable(chatClientResponse.chatResponse())
.map(ChatResponse::getResults)
.orElseGet(Collections::emptyList)
.stream()
.map(gen -> ModelOptionsUtils.toJsonString(gen.getOutput()))
.collect(Collectors.joining("\n"));
log.info("Response:\n{}", messages);
return chatClientResponse;
}
@Override
public int getOrder() {
return order;
}
}

Both before() and after() methods log the messages in JSON format and while additionally, before() displays the available tools, obviously exposed by the connected MCP servers.

TODO 3. As the custom advisors are ready, they can be used when the ChatClient is built, in the ChatAssistant constructor.

public ChatAssistant(ChatClient.Builder builder,
ToolCallbackProvider toolCallbackProvider,
ChatMemory chatMemory) {
this.chatMemory = chatMemory;
tokenUsageAdvisor = new TokenUsageAdvisor(1);
chatClient = builder
.defaultSystem("You are a helpful Telecom AI assistant. Provide short, meaningful answers.")
.defaultToolCallbacks(toolCallbackProvider)
.defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build(),
tokenUsageAdvisor,
new MessageLoggerAdvisor(2))
.build();
}

The order (priority) of the advisors is set as in the picture above.

Moreover, the tokenUsageAdvisor can be interrogated to further manage the usage.

public void clearConversation() {
chatMemory.clear(DEFAULT_CONVERSATION_ID);
tokenUsageAdvisor.clearUsage();
}
public int totalTokens() {
return tokenUsageAdvisor.totalTokens();
}

TODO 4. The last two methods are called from by the controller as the user interacts with the telecom-assistant UI.

@GetMapping("/")
public String home(Model model) {
model.addAttribute("messages", assistant.conversationMessages());
model.addAttribute("tokens", assistant.totalTokens());
return "chat";
}

Last but not least, the total tokens consumption is added in the top bar of the chat.html.

<div class="text-secondary small" th:text="|Messages: ${#lists.size(messages)}, Tokens: ${tokens}|"></div>

With all three applications up-and-running, let’s issue the following prompt – ‘What’s the vendor of the invoices having ‘vdf’ in their number?’ and then ‘Provide a short info for this vendor.’. The responses are to the point, as in the image below. Obviously, both MCP servers contributed and the chat memory had an important role as well.

One last aspect can be depicted from the logs. The snipped below is captured after the latter prompt was sent.

INFO c.h.t.controller.ChatController - USER:
Provide a short info for this vendor.
DEBUG c.h.t.advisor.TokenUsageAdvisor - Request: 4 messages ~ 41 estimated tokens.
INFO c.h.t.advisor.MessageLoggerAdvisor - Tools: [get_vendor_information, get_paid_invoices_count, get_invoices_by_pattern_on_number, get_paid_invoices_total_amount]
INFO c.h.t.advisor.MessageLoggerAdvisor - Request:
{"messageType":"SYSTEM","metadata":{"messageType":"SYSTEM"},"text":"You are a helpful Telecom AI assistant. Provide short, meaningful answers."}
{"messageType":"USER","metadata":{"messageType":"USER"},"media":[],"text":"What's the vendor of the invoices having 'vdf' in their number?"}
{"messageType":"ASSISTANT","metadata":{"role":"ASSISTANT","messageType":"ASSISTANT","refusal":"","finishReason":"STOP","index":0,"annotations":[],"id":"chatcmpl-DVHi80AIaMxjiCaIFkr5hk4IUBGL5"},"toolCalls":[],"media":[],"text":"Vodafone."}
{"messageType":"USER","metadata":{"messageType":"USER"},"media":[],"text":"Provide a short info for this vendor."}
DEBUG i.m.client.LifecycleInitializer - Joining previous initialization
DEBUG i.m.spec.McpClientSession - Sending message for method tools/call

It’s important to observe the order of the advisors’ execution and how the memory is kept from one request to the other.

When the response is received, obviously, the order is reversed.

DEBUG i.m.spec.McpClientSession - Received response: JSONRPCResponse[jsonrpc=2.0, id=ab8da66b-2, result={content=[{type=text, text=Specializes in cloud services.}], isError=false}, error=null]
DEBUG i.m.c.t.HttpClientStreamableHttpTransport - SendMessage finally: onComplete
DEBUG i.m.c.t.HttpClientStreamableHttpTransport - SSE connection established successfully
INFO c.h.t.advisor.MessageLoggerAdvisor - Response:
{"messageType":"ASSISTANT","metadata":{"role":"ASSISTANT","messageType":"ASSISTANT","refusal":"","finishReason":"STOP","index":0,"annotations":[],"id":"chatcmpl-DVHj4OdhPIYHi6yrAYkhSp8uqFQMO"},"toolCalls":[],"media":[],"text":"Vodafone — specializes in cloud services."}
INFO c.h.t.advisor.TokenUsageAdvisor - Current tokens -
Prompt: 542 Completion: 298 Total: 840
INFO c.h.t.advisor.TokenUsageAdvisor - Accumulated tokens -
Prompt: 1235 Completion: 659 Total: 1894
INFO c.h.t.controller.ChatController - ASSISTANT:
Vodafone — specializes in cloud services.

The UI of the conversation looks as below, where the total tokens are displayed as well.

If the user presses the Clear button, the tokens’ counter is reset and the chat memory for the current conversation erased (see the above clearConversation() method).

If sending the prompt ‘Give me a few details about the vendor.’, obviously the LLM is unable to respond.

Going to Production

The POC developed so far is a good start for understanding the concepts behind such an integration so that real production applications could be further created and deployed. To be able to think of such a scenario, several recommendations are worth taking into account. First, one shall be aware of at least a few production-wise ‘-ilities’ such as security, scalability, observability and also to consider the performance aspect. Secondly, when integrating ready-to-use MCP servers, one shall not show blind trust so that no new supply chain risks are created.

Security aspects were already discussed in this tutorial. The communication was secured with API keys, although the desired approach in a production environment is OAuth 2.0. Either way, Spring Security is very helpful when both web applications and MCP client-server communication need to be secured and it’s handful to integrate it in a product that’s already using Spring. Additionally, concerning the data stored in the databases and the conversations held, data encryption shall be leveraged as most vendors offer it transparently.

Regarding scalability, every time an LLM or an SQL database is called via a HTTP request, IO is blocked by the calling thread. Beginning with Java 21, virtual threads are available and scalability of IO-bound services is significantly improved.

When it comes to observability, keeping an eye on the system resources is always recommended. Without any doubt, all requests to an LLM have a cost – either in money or in complexity. Spring Boot provides the actuator metrics endpoint out of the box – http://localhost:8080/actuator/metrics – which offers a great deal of insights, including those related to the token consumption. These metrics can then be forwarded via Micrometer to a time-series database to further monitor the systems via dashboards, hence the visibility is significantly increased.

As for the enhanced performance in general, GraalVM is a great option. Once the SDK is set up and available, applications can be turned into GraalVM native images, then transformed into Docker images, then run in the cloud (Kubernetes, CloudFoundry etc.) or in a virtual machine emulating Linux and great improvements are definitely observed.

Final Thoughts

AI is reshaping software development – stay informed and up-to-date, adapt and use it.

Regarding MCP, it acts as a universal adapter and allows AI assistants to securely access and interact with external systems while maintaining a consistent interface. With MCP, AI development is not fragmented anymore, LLM strengths are applied on real data and great insights are outlined.

This tutorial is a good starting point that showcases how one can start helping users benefit from a cohesive system where individual components integrate seamlessly to deliver meaningful results. Then, imagination can fly freely as a lot of ideas are now just a few “words” distance from being put into practice by wisely using AI as a tool that magnifies our existing skills.

In the end, I would like to conclude with my brief take aways. No Python switch is needed, continue using Java and Spring, as they have already proven they are good candidates when building production-ready software. Moreover, Spring AI is production-ready as well if we design responsively. Last but not least, embrace Embabel Agent Framework that allows implementing agentic flows on the JVM that seamlessly mix LLM-prompt interactions with code and sketches the path towards developing agents as part of an enterprise eco-system.

Resources

[1] – The source code for the Spring AI Telecom Assistant

[2] – asentinel-orm project

[3] – MCP Inspector