Most of the "AI integration" code I see in Java projects isn't about AI at all. It's glue: build a prompt string, call an HTTP client, pull text out of a JSON envelope, split it on newlines, parse an integer, and hope the model didn't add "Sure! Here is your result:" at the top.
That code is tedious to write and fragile in production. It also hides the thing you actually care about, which is the shape of the data your application needs.
The project 03-structured-outputs shows a cleaner approach. You declare a Java record, declare an interface method that returns it, and let LangChain4J handle the mapping between the model's answer and your type. The whole example is a single class of about 50 lines.
In this article we'll walk through it piece by piece, look at why the design works, discuss what to watch out for, and then run it.
The Problem: Free Text Is a Bad Return Type
Suppose you want to extract a movie review from a user's comment. The naive version returns a String:
String answer = model.chat("Extract the title, rating and sentiment from: " + text); Now you have a blob of text. To use it you need to:
- Decide on a format (JSON? key-value lines? bullet points?).
- Ask the model to follow that format.
- Write a parser for that format.
- Handle the cases where the model doesn't follow it.
- Convert strings to the types you need, like
intfor the rating.
Every one of those steps is code you have to write, test, and maintain, and none of it is business logic.
The alternative is to make the type system do the work. If the method returns a MovieReview, the compiler and the framework agree on what the data looks like, and the rest of your application never touches raw model text.
What the Project Demonstrates
According to the project's README, the example shows three things:
- A
recordas the return type of an AI Service method. - Instructions in
@SystemMessagethat describe each field. -
temperature(0.0)to make the extraction more deterministic.
It also flags one thing to observe: if the model returns something that cannot be mapped to the record, LangChain4J raises an error. Handling that case (retry, validation, or a fallback) is described as the next step after this example. We'll come back to that in the best practices section.
Project Setup
The project is a plain Maven build targeting JDK 21. The requirements are:
- JDK 21
- Maven 3.9 or later
- An Anthropic API key
There is exactly one dependency, langchain4j-anthropic:
<dependencies> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-anthropic</artifactId> <version>1.24.1</version> </dependency> </dependencies> The compiler release is set to 21 through a property:
<properties> <maven.compiler.release>21</maven.compiler.release> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> And the exec-maven-plugin is configured with the main class, so you can run the example straight from Maven without building a jar:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.5.0</version> <configuration> <mainClass>com.mx.development.jose.said.StructuredOutputsExample</mainClass> </configuration> </plugin> There's no Spring, no extra JSON library declared, and no custom HTTP client in the POM. Everything the example needs comes through the one LangChain4J dependency.
Step 1: Define the Shape of Your Data
The first piece of the example is the record:
public record MovieReview(String title, int rating, String sentiment, String summary) { } This is the contract. Four fields, each with a Java type:
-
titleis aString. -
ratingis anint, so the model's answer has to be mappable to an integer, not "eight out of ten" or "8/10". -
sentimentis aString. -
summaryis aString.
Records are a natural fit for this job. They are immutable and concise, and they have a canonical constructor and accessors generated for you. They represent "a bundle of named values" and nothing else, which is what extracted data is. You don't need getters, setters, builders, or Lombok.
Notice the record is nested inside the example class as public record MovieReview(...). For a demo that keeps everything in one file. In a real application you'd probably give your domain types their own files.
Step 2: Declare the AI Service Interface
Next comes the interface, which is where the "no glue code" promise gets cashed in:
public interface ReviewExtractor { @SystemMessage(""" Extract a movie review from the user's text. rating is an integer from 1 to 10. sentiment is one of: POSITIVE, NEUTRAL, NEGATIVE. summary is one sentence in English. """) MovieReview extract(@UserMessage String text); } There's no implementation class. It's an interface with one method, and two annotations do the work.
@SystemMessage
The system message uses a Java text block to describe the task and each field of the record:
- What to do: "Extract a movie review from the user's text."
-
ratingis an integer from 1 to 10. This gives the model a range and reinforces theinttype. -
sentimentis one ofPOSITIVE,NEUTRAL,NEGATIVE. The field is aStringin the record, but the instructions constrain it to three values. -
summaryis one sentence in English. This constrains length and language.
This is the part developers tend to underestimate. The record tells the framework what type to produce, but the system message tells the model what each field means. A field named rating could be 0–5, 1–10, or 0–100, and the model can't know which you want unless you say so. Describing each field in plain language is cheap and removes a whole class of ambiguity.
@UserMessage
The parameter is annotated with @UserMessage, so the string you pass in becomes the user's message. Your calling code looks like an ordinary method call, with no prompt concatenation.
The return type
MovieReview extract(...) is the line that makes this a structured output example. The method does not return a String. As the class Javadoc puts it:
The method returns a record instead of a String, so LangChain4J asks the model for structured data and maps it to the record fields.
That's the entire mechanism from the point of view of your code: you change the return type, and the framework adapts.
Step 3: Build the Model
Now the main method. First it reads the API key from the environment and fails fast if it's missing:
String apiKey = System.getenv("ANTHROPIC_API_KEY"); if (apiKey == null || apiKey.isBlank()) { throw new IllegalStateException("Set the ANTHROPIC_API_KEY environment variable first."); } This is a good habit. Keeping the key in an environment variable keeps it out of source control, and checking it up front gives you a clear message instead of an authentication error later.
Then it builds the chat model:
AnthropicChatModel model = AnthropicChatModel.builder() .apiKey(apiKey) .modelName(MODEL_NAME) .temperature(0.0) .maxTokens(512) .build(); The model name is held in a constant at the top of the class:
static final String MODEL_NAME = "claude-haiku-5-5"; Three settings are worth noting.
modelName(MODEL_NAME). Pulling the model name into a constant makes it easy to find and change. Model names are the kind of value that changes over time, so you don't want them scattered through your code.
temperature(0.0). Temperature controls how much randomness goes into the model's output. For creative writing you may want it higher. For extraction you want the opposite: the same input should produce the same output as far as possible. The README describes this setting as making the extraction "more deterministic", which is the right way to put it. It reduces variation, but it doesn't make the model a pure function, so don't write tests that assume byte-for-byte identical output.
maxTokens(512). This caps the length of the response. A MovieReview with four short fields doesn't need much room, so 512 is a reasonable ceiling for this task. Setting it explicitly also bounds the cost of a single call.
Step 4: Create the AI Service
Here is the line that replaces all the glue code:
ReviewExtractor extractor = AiServices.create(ReviewExtractor.class, model); AiServices.create takes your interface and the model and returns an object that implements the interface. When you call extract, LangChain4J applies the system message, sends the user message, and maps the response to the return type.
You never write a class that implements ReviewExtractor. The interface is the specification, and the framework supplies the implementation.
Step 5: Call It Like a Normal Method
Finally the example prepares some input text and makes the call:
String text = "I watched Interstellar again last night. The visuals still amaze me, " + "and Hans Zimmer's score is unforgettable, although the middle act drags a little."; MovieReview review = extractor.extract(text); System.out.println("Title: " + review.title()); System.out.println("Rating: " + review.rating()); System.out.println("Sentiment: " + review.sentiment()); System.out.println("Summary: " + review.summary()); The input is an informal comment. It never says "rating" or "sentiment", and it contains no number at all. The model has to infer a title, a 1–10 rating, a sentiment label, and a one-sentence summary.
The result is a MovieReview. You read review.rating() and get an int, so you can compare it, average it, or store it without parsing anything. The program prints four labeled lines, one per field. The exact values come from the model, so I won't promise specific output. What matters is that each field arrives typed and accessible.
Compare this with the string-parsing approach. There's no regex, no Integer.parseInt wrapped in a try/catch, and no JSON tree navigation in your code.
How to Run the Project
Make sure you have JDK 21, Maven 3.9 or later, and an Anthropic API key. Then:
export ANTHROPIC_API_KEY=your-key-here mvn -q compile exec:java The first line sets the environment variable the program reads. The second compiles the project and runs the main class configured in the exec-maven-plugin. The -q flag keeps Maven quiet, so you mostly see the program's own output.
If you forget to set the variable, the program stops immediately with Set the ANTHROPIC_API_KEY environment variable first.
To get a feel for the example, try changing the text string. Give it a negative review, a lukewarm one, or one that never mentions a title, and see how the four fields change. Each of those experiments teaches you something about how much the model relies on your system message.
Best Practices
Here are the practices I'd take from this example into a real codebase. Where I go beyond what the project does, I say so.
1. Make the return type the contract
Use a record (or another dedicated type) for anything the rest of your code consumes. The principle is to convert model output into a typed value at the boundary, so everything downstream deals with real Java types and never with raw text.
2. Describe every field in the system message
The example does this for rating, sentiment, and summary. Define ranges, allowed values, units, language, and length. Whatever isn't specified is left to the model's judgment, and that judgment may vary between calls.
3. Constrain categorical values explicitly
The example tells the model that sentiment is one of POSITIVE, NEUTRAL, NEGATIVE. In the record, though, sentiment is a plain String, so the type itself doesn't enforce those three values. If you rely on them in your code, for example in a switch, validate them. Whether you could express this more strongly in the type itself (for example with a Java enum) is something to check in the LangChain4J documentation for the version you use. The project doesn't do it, so I won't claim how it behaves.
4. Use low temperature for extraction
temperature(0.0) is the right instinct for extraction and classification tasks. You want consistency, not creativity. Keep in mind this makes results more deterministic and doesn't guarantee identical output.
5. Bound the response with maxTokens
A structured result is small. A cap like maxTokens(512) protects you from unexpectedly long responses and keeps per-call cost predictable. Pick a value that comfortably fits your record, and be aware that a record much larger than this example's may need a higher limit.
6. Fail fast on configuration
The API key check at the top of main is simple, but it saves debugging time. Validate required configuration at startup and give the error message something actionable to say.
7. Plan for the failure case
This is the most important one, and the README is upfront about it: if the model returns something that cannot be mapped to the record, LangChain4J raises an error. The example doesn't handle that error, because it's a demo, and the README names handling it (retry, validation, or a fallback) as the next step.
In production you'd think about three things:
- Retry. Because model output can vary, a second attempt may succeed where the first failed. Put a limit on retries so you don't loop and burn money.
- Validation. Even when mapping succeeds, the values might be wrong for your domain. A
ratingof 42 maps to anintjust fine. Check it against the 1–10 range you asked for. - Fallback. Decide what the application does when extraction fails for good: return an error to the caller, queue the item for review, or use a default.
As a purely illustrative sketch using only plain Java (not part of the project), validation of the example's own constraints could look like this:
MovieReview review = extractor.extract(text); if (review.rating() < 1 || review.rating() > 10) { // Decide what makes sense here: retry, fall back, or report an error. throw new IllegalStateException("Rating out of range: " + review.rating()); } This is ordinary defensive programming. The model was told the rating is between 1 and 10, but your code shouldn't simply trust that.
8. Keep prompts next to the code that uses them
Because the instructions live in @SystemMessage on the interface method, the prompt, the parameter, and the return type are all in one place. When you change the record, the instructions are right there to update. That locality is a real maintainability benefit compared with prompts stored in separate files or built by string concatenation scattered across the codebase.
Why This Is the "Clean Way"
Look at what the example doesn't contain:
- No prompt string concatenation.
- No HTTP request or response handling.
- No JSON parsing code.
- No type conversion code.
- No implementation class for the service.
What it does contain is a record that states what you want, an interface method that states how to ask for it, and a builder that states which model and settings to use. Each piece has one job, and the glue is the framework's problem.
That separation also makes the code easier to reason about. If the extraction quality isn't good, you tune the system message. If the data shape changes, you change the record. If you want a different model, you change the builder. These are separate concerns, and they live in separate places.
Where to Go Next
The README points to the natural next step: handling the case where the model's answer can't be mapped to the record. From there, a few directions make sense, all of them extensions of this example rather than things it already does:
- Add validation of the extracted values against the ranges in your system message.
- Add a bounded retry and a defined fallback for mapping failures.
- Try richer records with more fields, and see how the system message needs to grow to describe them.
- Experiment with the input text and see where extraction gets ambiguous.
Closing
Structured outputs turn "ask the model something and parse the reply" into "call a method and get a typed object". In 03-structured-outputs, that takes a four-field record, an interface with @SystemMessage and @UserMessage, a chat model configured with temperature(0.0), and a single call to AiServices.create.
You still need to design for failure, since the model can return something that doesn't fit, but the foundation is clean: your application deals in Java types, and the model-facing text stays in one well-defined place.
Explore the code and run it yourself:
- Source code: https://github.com/josesaid/03-structured-outputs
- Project page: https://josesaid.github.io/03-structured-outputs/
If you try it with your own inputs, I'd like to hear which cases gave you surprising results.
