Spring AI ChatClient– Response Types Explained

 Spring AI ChatClient– Response Types Explained 


Whenyou invoke .call() on a ChatClient, there are different ways to get the result, depending on what you want to do with it


Streaming Responses

•  To stream reponses, we can use. stream() instead of. call() 

• Good for real-time or chunked responses (like streaming output to UI.



Structured Output Converter in Spring AI


Why DoWe Need Structured Output?

LLMs typically return plain text responses. But in real-world apps, we often need structured data like,

• JSON

• XML

• JavaClasses (POJOs)

Structured data is easier to parse, use, and integrate in applications.

What is a Structured Output Converter ?

Before sending prompt to LLM:

➤Addsformatting instructions to guide the model.

➤Ensures it replies in a parseable format.

After getting response from LLM:

➤Converts raw text into a Java object, like Map, List, or custom class


Structured Output Converter in Spring AI

Example: Convert reponse to a Java object
CountryCities countryCities = this.chatClient.prompt()
.user(question)
.call()
.entity(CountryCities.class);

Example: Convert reponse to a list of Java objects
List<CountryCities> countryCitiesList =
this.chatClient.prompt()
.user(question).call()
.entity(new ParameterizedTypeReference
<List<CountryCities>>() {});

We use ParameterizedTypeReference> because Java's type erasure removes generic type information like List at runtime, making it impossible to use List.class. ParameterizedTypeReference preserves this type info so Spring can correctly deserialize the LLM response into a list of CountryCities objects.



Example: Convert reponse to a Map
Map<String, List<String>> countryMapList =
this.chatClient.prompt()
.user(question).call()
.entity(new ParameterizedTypeReference
<Map<String, List<String>>>() {});

• Spring AI’s StructuredOutputConverter helps convert raw LLM text responses into structured Java data like objects, lists, or maps. 

 • We can use its implementations as well like BeanOutputConverter, ListOutputConverter, and MapOutputConverter, add format instructions before the AI call and parse the response after, making it easier to work with typed data in your applications.




Comments

Popular posts from this blog

Async/await

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java