Articles AI

Spring AI structured output: call an LLM from Java

To get structured output from an LLM with Spring AI, describe the answer as a Java record and end the ChatClient call with .entity(MyRecord.class) instead of .content(). Spring AI generates a JSON schema from the record, adds it to the prompt, and deserializes the model’s JSON reply into the record. The call works with every chat model Spring AI supports, and it is a request, not a guarantee: the model can still return something that does not parse.

The code below was compiled and run on Spring AI 2.1.0 with Spring Boot 4.2.0 and JDK 25. No real model was called. Every prompt, schema, log line and exception shown as output comes from a stub ChatModel that returns canned text, and the JSON replies are examples written by hand.

Which dependency do you need to call an LLM from Java with Spring AI?

Import the Spring AI BOM and add one model starter. Since Spring AI 1.0 the starters are named spring-ai-starter-model-<provider> (openai, anthropic, ollama, mistral-ai, google-genai and others). Tutorials that use spring-ai-openai-spring-boot-starter predate that rename.

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>2.1.0</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>
</dependencies>

Configuration is per provider. For the OpenAI starter the reference lists these properties:

spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.openai.chat.model=gpt-4o-mini
spring.ai.openai.chat.temperature=0

Keep the key in an environment variable, never in the repository. Everything after this point is provider-neutral: the Java code does not change when you swap the starter.

How do you call the model and get a String?

The starter auto-configures a ChatClient.Builder bean. Inject it, build a ChatClient once, and use the fluent API:

@Service
public class TriageService {

    private final ChatClient chatClient;

    public TriageService(ChatClient.Builder builder) {
        this.chatClient = builder
                .defaultSystem("You triage customer support tickets.")
                .defaultOptions(ChatOptions.builder().temperature(0.0).maxTokens(500))
                .build();
    }

    public String summarize(String ticket) {
        return chatClient.prompt()
                .user(u -> u.text("Summarize this ticket in one sentence: {ticket}")
                        .param("ticket", ticket))
                .call()
                .content();
    }
}

content() returns the reply as plain text. Passing the ticket through param keeps the template and the user’s text apart.

How do you map the LLM response to a Java record?

Define the shape you want as a record:

public record TicketTriage(
        Category category,
        @JsonPropertyDescription("1 is the most urgent, 5 the least") int priority,
        String summary,
        List<String> tags) {

    public enum Category { BUG, BILLING, FEATURE_REQUEST }
}

Then replace content() with entity(...):

TicketTriage triage = chatClient.prompt()
        .user(u -> u.text("Triage this ticket: {ticket}").param("ticket", ticket))
        .call()
        .entity(TicketTriage.class);

Suppose the model answers with this JSON (an example reply, fed in through the stub):

{"category":"BILLING","priority":2,
 "summary":"Customer was charged twice for the March invoice.","tags":["invoice","refund"]}

The call then returns:

TicketTriage[category=BILLING, priority=2, summary=Customer was charged twice for the March invoice., tags=[invoice, refund]]

For a generic type such as a list, pass a ParameterizedTypeReference:

List<TicketTriage> all = chatClient.prompt()
        .user(u -> u.text("Triage each of these tickets: {tickets}").param("tickets", tickets))
        .call()
        .entity(new ParameterizedTypeReference<List<TicketTriage>>() {});

entity exists only after call(). A streamed response arrives in chunks, and parsing needs the whole text.

What does Spring AI send to the model?

entity(Class) uses a BeanOutputConverter. It builds a JSON schema from the type and produces format instructions. You can print them yourself with new BeanOutputConverter<>(TicketTriage.class).getFormat():

Your response should be in JSON format.
Do not include any explanations, only provide a RFC8259 compliant JSON response following this format without deviation.
Do not include markdown code blocks in your response.
Remove the ```json markdown from the output.
Here is the JSON Schema instance your output must adhere to:
```{
  "$schema" : "https://json-schema.org/draft/2020-12/schema",
  "type" : "object",
  "properties" : {
    "category" : {
      "type" : "string",
      "enum" : [ "BUG", "BILLING", "FEATURE_REQUEST" ]
    },
    "priority" : {
      "type" : "integer",
      "format" : "int32",
      "description" : "1 is the most urgent, 5 the least"
    },
    "summary" : {
      "type" : "string"
    },
    "tags" : {
      "type" : "array",
      "items" : {
        "type" : "string"
      }
    }
  },
  "required" : [ "category", "priority", "summary", "tags" ],
  "additionalProperties" : false
}```

In the prompt captured by the stub, this text was appended to the end of the user message, right after the ticket. So the schema costs input tokens on every call, and the model is free to ignore it.

Three details of the schema are worth knowing. The enum constants become the allowed values. The @JsonPropertyDescription text lands in description, which is the place to explain a field to the model. And every record component is listed in required. In a second test record, a component annotated with JSpecify @Nullable or @JsonProperty(required = false) dropped out of that list. The reference documents these annotations for tool calling schemas. For structured output it only mentions @JsonPropertyOrder, so treat the rest as observed behaviour of 2.1.0.

Does Spring AI support native structured output and JSON mode?

Yes. Most providers can enforce a JSON schema at the API level, and Spring AI 2 exposes that as a switch on the entity call:

TicketTriage triage = chatClient.prompt()
        .user(u -> u.text("Triage this ticket: {ticket}").param("ticket", ticket))
        .call()
        .entity(TicketTriage.class, spec -> spec
                .useProviderStructuredOutput()
                .validateSchema());

useProviderStructuredOutput() sends the schema as an API field and leaves the format text out of the prompt. The reference lists OpenAI, Anthropic, Google GenAI, Mistral AI and Ollama as supported, and says the switch is silently ignored when the model’s options do not implement StructuredOutputChatOptions. That is what happened with the stub: the prompt still carried the format text. It is off by default because support differs per model. One documented limit: OpenAI rejects a top-level array, so wrap a list in a record. To turn it on for a whole client, register AdvisorParams.ENABLE_NATIVE_STRUCTURED_OUTPUT as a default advisor.

validateSchema() is the second switch. It checks the reply against the schema and, on failure, calls the model again with the error added to the prompt. With a stub whose first reply was {"category":"BUG"}, the log showed:

WARN StructuredOutputValidationAdvisor -- JSON validation failed: SchemaValidation[success=false, errorMessage=required property 'priority' not found; required property 'summary' not found; required property 'tags' not found]

The second prompt contained the line Output JSON validation failed because of: ... and the second reply was accepted. A stub that always returned a bad enum value was called four times (the first attempt plus three repeats) before the parsing exception reached the caller. Each repeat is a paid model call.

What goes wrong with LLM JSON output?

These are the replies the stub was made to return, and what plain entity(TicketTriage.class) did with each:

ReplyResult
JSON cut off mid-stringUnexpectedEndOfInputException
Prose before the JSONStreamReadException
JSON wrapped only in a json code fenceParsed, the fence was stripped
Prose followed by a fenced blockStreamReadException
"category":"PAYMENTS"InvalidFormatException
priority missingMismatchedInputException
summary and tags missingNo error, both are null
An extra fieldNo error, the field is ignored

The exceptions are Jackson 3 types from tools.jackson, thrown unwrapped, and all of them extend the unchecked JacksonException. The message of the truncated reply started with:

tools.jackson.core.exc.UnexpectedEndOfInputException: Unexpected end-of-input: was expecting closing quote for a string value

and the invented enum value:

tools.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `demo.TicketTriage$Category` from String "PAYMENTS": not one of the values accepted for Enum class: [BILLING, BUG, FEATURE_REQUEST]

The dangerous rows are the quiet ones. A missing String becomes null, and a priority of 9 parses without complaint. The schema carries no range, so check the record the way you would check a request body, with Bean Validation. Put @NotNull, @NotBlank, @Min(1) and @Max(5) on the components and validate after the call:

private TicketTriage triageOnce(String ticket) {
    TicketTriage triage = chatClient.prompt()
            .user(u -> u.text("Triage this ticket: {ticket}").param("ticket", ticket))
            .call()
            .entity(TicketTriage.class);
    Set<ConstraintViolation<TicketTriage>> violations = validator.validate(triage);
    if (!violations.isEmpty()) {
        throw new ConstraintViolationException(violations);
    }
    return triage;
}

For a reply with priority 9 and an empty summary the exception message was summary: must not be blank, priority: must be less than or equal to 5.

The rest of the defence is ordinary engineering:

  • Catch JacksonException and ConstraintViolationException, retry once, then fail with a clear error. Do not loop.
  • Use a low temperature for extraction and classification.
  • Set a token limit as a cost cap, but high enough for the largest valid answer. A limit that is too low is the usual cause of truncated JSON.
  • If your model wraps JSON in prose, pass a custom StructuredOutputConverter to entity. The converters page has an example that extracts the fenced block.
  • Treat every field as untrusted input. The ticket text can contain instructions aimed at the model, so a value from the record must never go unchecked into SQL, a shell command or a permission decision.

How do you test Spring AI code without calling a model?

ChatModel has one abstract method, call(Prompt), so a lambda is enough for a stub. Build the service by hand with ChatClient.builder(stub). Here the service takes a Validator as a second constructor argument:

class TriageServiceTest {

    static ChatModel replying(String text) {
        return prompt -> new ChatResponse(List.of(new Generation(new AssistantMessage(text))));
    }

    @Test
    void truncatedJsonFails() {
        ChatModel model = replying("{\"category\":\"BILLING\",\"priority\":2,\"summary\":\"Charged tw");
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        TriageService service = new TriageService(ChatClient.builder(model), validator);

        assertThatThrownBy(() -> service.triage("I was charged twice in March"))
                .isInstanceOf(JacksonException.class);
    }
}

The test needs no network, no API key and no Spring context, and covers your prompt wiring, parsing, validation and retry. What it cannot tell you is how often a real model breaks the format. That takes a separate, small set of calls against the provider.

Summary

  • chatClient.prompt().user(...).call().entity(MyRecord.class) returns a typed record. Use ParameterizedTypeReference for lists.
  • By default the JSON schema travels as text at the end of the user message. Print it with BeanOutputConverter.getFormat() to see what the model sees.
  • useProviderStructuredOutput() moves the schema into the provider API where supported, and validateSchema() adds a retry loop with error feedback.
  • Broken JSON, prose around the JSON and unknown enum values fail with a JacksonException. Missing object fields and out-of-range numbers do not fail, so validate the record.
  • Keep temperature low, cap tokens with room to spare, retry once, and treat the result as untrusted input.
  • Test with a lambda ChatModel that returns canned text.