Output conversion lets Spring AI instruct an LLM to format generated text and then map the response into a Java object or list. Calling entity(Answer.class) replaces manual content extraction and object construction with framework-assisted parsing. section 3.4 section 3.4.2
The conversion flow adds two behaviors:
- Derives formatting instructions and a JSON schema from the requested Java type. section 3.4.2
- Parses the generated JSON response into the requested object or collection. section 3.4.2
- Requires caution because some LLMs may ignore formatting instructions. section 3.4.2
Answer and song-list responses
A board-game service can return Answer.class directly. A song endpoint can request a List<String>, instructing the model to return only song titles, then expose the converted list as JSON. section 3.4.2
Listing 3.5 Obtaining an Answer object as the LLM result
package com.example.boardgamebuddy;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
@Service
public class SpringAiBoardGameService implements BoardGameService {
private final ChatClient chatClient;
private final GameRulesService gameRulesService;
public SpringAiBoardGameService(
ChatClient.Builder chatClientBuilder,
GameRulesService gameRulesService) {
this.chatClient = chatClientBuilder.build();
this.gameRulesService = gameRulesService;
}
@Value("classpath:/promptTemplates/systemPromptTemplate.st")
Resource promptTemplate;
@Override
public Answer askQuestion(Question question) {
var gameRules = gameRulesService.getRulesFor(question.gameTitle());
return chatClient.prompt()
.system(systemSpec -> systemSpec
.text(promptTemplate)
.param("gameTitle", question.gameTitle())
.param("rules", gameRules))
.user(question.question())
.call()
.entity(Answer.class); #1
}
}
Inspect the service implementation that obtains an Answer object from ChatClient. section 3.4.2
