Most AI examples end the same way: the model returns a paragraph of text, and the application has to read that paragraph to find what it needs. A rating, a sentiment, a title. The developer then writes parsing code, hopes the model keeps the same format next time, and adds exceptions for the day it does not. In a Java application this gets fragile quickly, because text is the one thing a compiler cannot check for you.

This article shows a better approach using LangChain4j and Claude. Instead of asking for text, the method returns a Java record. The framework asks the model for structured data, maps the answer to the record fields, and gives the application a typed object it can use directly. The complete example is in the repository 03-structured-outputs, and this article walks through the code, the design choices, and the failure case you have to plan for.

The problem with free text

Imagine a service that receives movie reviews from users and must store a rating, a sentiment, and a short summary for each one. With free text, the prompt might ask the model to "write the rating, the sentiment and a summary". A typical answer looks like this:

text
The reviewer gives it about eight out of ten. It sounds positive overall,
and the summary is that the visuals and the score are excellent.

Every part of that answer is correct for a human reader and difficult for a program. "About eight" is not an integer. "Positive overall" might be POSITIVE, or positive, or Positive. The summary is mixed into the sentence. You can write a regular expression, but it will break the first time the model changes its wording, and models do change their wording.

The solution is to move the shape of the answer out of the prompt and into the type system. The application already knows what it needs, so it should declare that shape once and let the framework enforce it.

Records as the return type

A Java record is a compact way to declare an immutable data carrier. For this example, the record has four fields:

java
public record MovieReview(String title, int rating, String sentiment, String summary) {
}

The important detail is the type of each field. rating is an int, not a String. The application never has to parse a number out of a sentence, because the framework has to produce one before the method returns.

LangChain4j lets you describe the work as an interface. An AI Service is an interface whose methods represent interactions with the model. The method signature says what goes in and what comes out:

java
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); 

}

Read the interface as a contract. The caller passes a String with the review text and receives a MovieReview. The method does not return a String, so there is no text to parse. The @SystemMessage annotation carries the instructions that describe each field, which matters more than it might seem at first, as the next section explains.

Describing the fields

The model needs to know what each field means. Without instructions, a sentiment field could contain "mixed", "somewhat positive", or "3/5 stars". The @SystemMessage in the example narrows each field:

rating is an integer from 1 to 10.
sentiment is one of three values: POSITIVE, NEUTRAL, or NEGATIVE.
summary is one sentence in English.

These rules do two jobs. They guide the model toward values the record can hold, and they document the contract for the next developer who reads the code. A good system message is part of the API, so treat it with the same care as a method signature.

Making the extraction deterministic

Extraction is not a creative task. Given the same review, you want the same record every time. The example configures the model with a temperature of zero:

java
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(apiKey)
.modelName(MODEL_NAME)
.temperature(0.0)
.maxTokens(512)
.build();

A temperature of 0.0 reduces the randomness in the output. It does not make the model infallible, but it makes the behavior more stable between runs, which is what you want when the output feeds a database or a downstream service. The maxTokens limit keeps the response short, which is appropriate for a record with four small fields.

The model name is also a declared constant, claude-haiku-5-5, so changing the model later is a one-line change. A smaller, faster model is a sensible choice for extraction tasks like this one, where the output is short and the structure is well defined.

Putting it together

The main method creates the model, builds the AI Service, and calls it with a review:

java
ReviewExtractor extractor = AiServices.create(ReviewExtractor.class, model);

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 line that matters most is AiServices.create. It produces an implementation of ReviewExtractor that sends the system message and the user text to the model, asks for structured data, and returns a populated MovieReview. The caller never sees the JSON, the HTTP request, or the parsing. It sees a record.

The output for this review is what a human reader would expect: the title, a rating in the middle of the scale, a sentiment that reflects the mixed opinion, and a one-sentence summary. The important point is not the specific values, which depend on the model, but that every value has the right type and the right range before it reaches your code.

To run the example, set the API key and execute the Maven goal from the project root:

bash
export ANTHROPIC_API_KEY=your-key-here
mvn -q compile exec:java

The project requires JDK 21 and Maven 3.9 or later. The dependency is langchain4j-anthropic in its 1.24.1 version, declared in pom.xml.

What happens when the model cannot fit the record

Structured output does not mean the model always succeeds. If the model returns something that cannot be mapped to the record, for example a rating of "about eight" where the record expects an int, LangChain4J raises an error instead of quietly returning a broken object. This is the behavior you want, because a bad object that reaches the database is harder to fix than an exception at the boundary.

The example stops there on purpose, because the next question is what your application should do in that case. There are three common options, and most real systems use a combination of them.

Retry. Call the model again with the same input. This works well for transient problems and occasional formatting slips. Limit the number of attempts, and log each failure so you can see how often it happens.

Validate. After the record is created, check the business rules that the type system cannot express. A rating must be between 1 and 10. A summary must not be empty. Validation is cheap, and it turns a silent quality problem into an explicit error.

Fall back. If the extraction keeps failing, store the raw text and mark the review for manual processing. The user still gets a response, and the failure is visible to the team that owns the data.

The key is to decide these rules before the first production incident, not after it. A structured output is only as reliable as the code that handles the cases it cannot produce.

When structured output is the right tool

Not every AI feature should return a record. A chat assistant that answers questions for a person is better off returning free text, because the person is the consumer and free text is the natural format for a conversation. Structured output is the right tool when another part of the system is the consumer: a database, a queue, a rules engine, a dashboard, or another service that expects specific fields.

A simple test helps. Ask who reads the output next. If the answer is a human reading a sentence, keep the text. If the answer is code that will branch on a value, store it, or compare it with another value, use a record. In many real systems both appear in the same flow: the model extracts structured data for the workflow, and then writes a short text for the customer based on that data.

Structured output also makes testing easier. A test can assert that review.rating() equals a number, instead of searching a paragraph for a word. That difference matters when a team grows and the AI behavior has to be checked in a continuous integration pipeline.

Testing the extraction

The model is not a pure function, so you cannot expect the exact same summary text every time. You can, however, test the properties that the application depends on. The type system guarantees the shape of the record, so the tests focus on values and ranges.

A practical approach is to keep a small set of reviews with known expectations, and check each one against the rules in the system message:

java
@test
void extractsRatingWithinRange() {
MovieReview review = extractor.extract(
"A forgettable sequel. Two hours I will not get back.");

assertTrue(review.rating() >= 1 && review.rating() <= 10); assertEquals("NEGATIVE", review.sentiment()); 

}

The assertion on the sentiment is slightly stricter than the rating check, because a clearly negative review should not be labeled as positive. Choose assertions that reflect the business rule, not the exact wording of the model. For example, a review with a clear opinion should not come back as NEUTRAL in most runs, and a review with no opinion at all should.

Include messy inputs in the set. Sarcasm, mixed opinions, very short texts, and reviews written in another language will reveal the weak points of the instructions much faster than clean examples. When a test fails, first check whether the system message is ambiguous. Changing the instructions is often a better fix than adding code around the result.

Run these tests against a real model at least occasionally, because a mocked model cannot tell you whether the instructions still work. Use mocks for the rest of the application logic, and keep the number of live calls small so the test suite stays fast and affordable.

Evolving the record

Records are easy to change, but every change affects the contract. Adding a field is usually safe for the Java code that creates the record, but it changes what the model must produce. Removing a field is also safe for the caller, but it can leave the system message describing something that no longer exists. Keep the record and the system message together, and review both in the same change.

When a field has a fixed set of values, consider an enum instead of a String. For sentiment, an enum with POSITIVE, NEUTRAL and NEGATIVE gives the compiler a way to find every place that handles the value, and it makes an unexpected value a clear error. The system message still matters, because the model must know which values exist, but the enum keeps the rest of the code honest.

When you need several items instead of one, the same idea applies to a collection of records, for example a list of reviews extracted from a single long text. Start with the single record, because it is easier to test and to explain. Move to collections only when the business case requires them, and keep the record definition stable while you do.

Finally, document the reason for each field. A field called rating is clear, but a field called score needs a note about its scale. The record is the first documentation a new developer reads, so let it say what the data means, not only what type it has.

Practices worth keeping

A few habits make this pattern easier to maintain as the application grows. Most of them come down to one idea: treat the boundary between the model and your code as a real interface, with the same discipline you would apply to a network API or a database schema. The record is the contract, the system message is its documentation, and the error handling is its failure mode. When those three pieces are designed deliberately, the AI feature behaves like any other dependency in the system, and the team can reason about it, test it, and change it without fear.

Keep the record small and focused on one task. If you find yourself adding twenty fields, consider whether two smaller extractions would be clearer and more reliable.

Write the system message as documentation. Name the allowed values, state the ranges, and say the language of free-text fields. The next developer will read it, and so will the model.

Use the type system before adding prompt instructions. Choosing int instead of String for a rating removes an entire class of parsing errors. Choosing an enum for sentiment would be even stricter, and it is a natural next step for this example.

Test the extraction with a set of realistic reviews, including messy ones: sarcasm, mixed opinions, very short texts, and texts in other languages. A structured output that works only on clean input is not finished.

Keep the temperature low for extraction and higher for creative tasks. Do not use the same configuration for every AI Service in the application.

Conclusion

Structured outputs move the contract between the model and your application from a fragile text format into a Java type. The method returns a record, the system message describes each field, the temperature keeps the extraction stable, and the framework maps the answer for you. When the model cannot satisfy the contract, the error is explicit, and you decide how to handle it.

The result is code that reads like ordinary Java. The AI part sits behind an interface, and the rest of the application works with typed data. If you are building AI features in a Java system, this is a good first pattern to learn, because almost every later step, from tools to agents, depends on the same idea of asking the model for a shape you can trust.

The full example is available at github.com/josesaid/03-structured-outputs, and the project page is at josesaid.github.io/03-structured-outputs.