ChatModel and ChatClient represent two distinct layers of abstraction for interacting with Large Language Models. ChatModel serves as the foundational, low-level provider interface, while ChatClient sits directly on top of it as a high-level, fluent API designed for application development.1. Architectural Relationship
-
ChatModel (The Engine): Acts as the low-level contract that bridges Spring AI with specific LLM vendor APIs (such as
OpenAiChatModel,AnthropicChatModel,OllamaChatModel, or Google GenAI). It encapsulates HTTP communication, authentication, request serialization, and response parsing for a given provider. -
ChatClient (The Steering Wheel & Dashboard): Acts as a high-level fluent facade built on top of
ChatModel(conceptually mirroring Spring’sRestClientandWebClient). Rather than communicating with an LLM directly,ChatClientassembles prompts, applies middleware advisors, delegates execution to the underlyingChatModel, and formats the returned output.
2. Deep Dive: The ChatModel API
ChatModel is an interface (extending Spring AI’s generic Model and StreamingModel interfaces) auto-wired into the Spring context whenever a provider starter is included.Core Responsibilities & Components
-
Request Encapsulation (
Prompt): Accepts aPromptobject composed of a list of typedMessageobjects (SystemMessage,UserMessage,AssistantMessage,ToolResponseMessage) alongside runtimeChatOptions(such as temperature, max tokens, or model overrides). -
Execution Modes:
-
Synchronous (
call): Sends a blocking request and returns a completeChatResponse. -
Reactive Streaming (
stream): Returns a reactive stream (Flux<ChatResponse>) that emits partial response chunks token-by-token as the LLM generates them.
-
-
Rich Response Structure (
ChatResponse&Generation): Returns aChatResponsewrapper containing one or moreGenerationcandidates alongsideChatResponseMetadata, which exposes:-
Exact model version used
-
Token consumption metrics (prompt tokens, completion tokens, total tokens)
-
Finish reason categories (
COMPLETED,TRUNCATED,TOOL_CALL,FILTERED,OTHER,UNSPECIFIED) -
Rate-limit headers and provider-specific metadata
-
3. Deep Dive: The ChatClient API
ChatClient is the primary recommended entry point for building AI features in Spring Boot applications. It is instantiated either via an auto-configured ChatClient.Builder (ideal for setting application-wide defaults) or programmatically via ChatClient.create(chatModel).Core Capabilities
-
Fluent Prompt Construction: Provides a readable, chained builder syntax (
prompt(),system(),user(),messages()) for assembling multi-role conversations, loading external prompt template resources, and customizing template delimiters (e.g., switching from{}to<>when prompts contain raw JSON). -
Middleware Interception (Advisors API): Supports pluggable
Advisorchains that intercept outgoing prompts and incoming responses to transparently handle cross-cutting concerns—such as injecting conversation memory, performing Retrieval-Augmented Generation (RAG) context injection, and logging requests. -
Structured Output Mapping (
.entity()): Automatically instructs the LLM on expected schemas and converts raw text responses directly into strongly typed Java records, POJOs, or parameterized collections. It also supports schema validation with automatic retry-on-failure and native provider-enforced structured outputs. -
Built-In Tool & Memory Attachment: Allows attaching Java tools/functions (
.tools()) and passing contextual metadata (toolContext) directly within the fluent chain. -
Flexible Response Extraction: Following
.call()or.stream(), developers can extract plain strings (.content()), mapped Java objects (.entity()), or drop down to the underlying.chatResponse()when token usage or finish-reason metadata is needed.
4. ChatModel vs. ChatClient Comparison
| Dimension | ChatModel | ChatClient |
| Abstraction Level | Low-level provider contract | High-level fluent application API |
| Instantiation | Auto-wired directly as a provider bean | Built via injected ChatClient.Builder or ChatClient.create() |
| Advisors (RAG & Memory) | Not supported natively; requires manual wiring | Built-in support via .advisors() |
| Structured Output | Manual parsing of raw text from ChatResponse |
Built-in automatic conversion via .entity() |
| Prompt Templates | Requires manual PromptTemplate instantiation |
Native inline or resource-based templating |
| Multiple Candidates | Directly exposes List<Generation> from a single call |
Optimized around single primary responses (unless inspecting ChatResponse) |
| Primary Use Case | Framework extensions, custom model wrappers, or fine-grained multi-candidate control | Standard business logic, chatbots, RAG pipelines, agents, and structured extraction |
5. Multi-Model & Multi-Client Patterns
-
Multiple
ChatClientBeans on OneChatModel: A singleChatModel(e.g., Gemini or Ollama) can back multiple specializedChatClientbeans—such as one configured with a strict system persona and RAG advisor for customer support, and another configured with zero memory for stateless text summarization. -
Multiple
ChatModelBeans in One Application: When an application integrates multiple LLM providers simultaneously (such as Claude and Ollama), each provider registers its ownChatModelimplementation. By disabling default single-client auto-configuration, developers can construct separateChatClientinstances bound to eachChatModeland inject them using@Qualifierannotations to route requests dynamically.
Hands-on Experiment: Smart Customer Support Chatbot using ChatModel and ChatClient
Aim: To build a Spring Boot application that uses the Spring AI ChatModel API and the ChatClient API to answer customer questions and to classify complaints into support tickets stored in MySQL.
Description: ChatModel is the low-level interface that sends a prompt to an LLM and returns its response. ChatClient is a higher-level fluent API built on top of it, with a builder style for prompts, system messages, advisors and response handling. They are used to keep chatbot code short, readable and independent of any one provider. Together they cover simple one-shot calls, default system instructions and conversation-style interactions.
Software/Tools Required
- JDK 17
- Spring Boot 3.x (3.4.x for Spring AI 1.0)
- Maven
- MySQL 8.x
- IDE (IntelliJ IDEA, Eclipse or VS Code)
- Postman
- GeminiAI API key (environment variable
GeminiAI_API_KEY)
Step-by-Step Application Development
Step 1: Generate the Project via Spring Initializr
- Project: Maven, Language: Java, Spring Boot: 3.4.x (Spring AI 1.1.0 needs 3.4+)
- Group:
com.example, Artifact:support-chatbot - Packaging: Jar, Java: 17
- Dependencies: Spring Web, Spring Data JPA, MySQL Driver, GeminiAI
Step 2: Project Structure
support-chatbot
├── pom.xml
└── src/main
├── java/com/example/supportchatbot
│ ├── SupportChatbotApplication.java
│ ├── entity (Ticket)
│ ├── repository (TicketRepository)
│ ├── service (SupportService)
│ └── controller (SupportController)
└── resources/application.properties
Step 3: Create the files according to the project structure
package com.example.supportchatbot.entity;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "support_tickets")
public class Ticket {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String customerName;
@Column(nullable = false, columnDefinition = "TEXT")
private String message;
// BILLING, TECHNICAL, DELIVERY, ACCOUNT or OTHER (decided by the AI)
private String category;
// HIGH, MEDIUM or LOW (decided by the AI)
private String priority;
// POSITIVE, NEUTRAL or NEGATIVE (decided by the AI)
private String sentiment;
@Column(columnDefinition = "TEXT")
private String suggestedReply;
private String status = "OPEN";
private LocalDateTime createdAt = LocalDateTime.now();
public Ticket() {
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getCustomerName() { return customerName; }
public void setCustomerName(String customerName) { this.customerName = customerName; }
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; }
public String getPriority() { return priority; }
public void setPriority(String priority) { this.priority = priority; }
public String getSentiment() { return sentiment; }
public void setSentiment(String sentiment) { this.sentiment = sentiment; }
public String getSuggestedReply() { return suggestedReply; }
public void setSuggestedReply(String suggestedReply) { this.suggestedReply = suggestedReply; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public LocalDateTime getCreatedAt() { return createdAt; }
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
}
package com.example.supportchatbot.repository;
import com.example.supportchatbot.entity.Ticket;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface TicketRepository extends JpaRepository<Ticket, Long> {
List<Ticket> findAllByOrderByIdDesc();
List<Ticket> findByPriorityOrderByIdDesc(String priority);
}
package com.example.supportchatbot.service;
import com.example.supportchatbot.entity.Ticket;
import com.example.supportchatbot.repository.TicketRepository;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.metadata.Usage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.stereotype.Service;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Service
public class SupportService {
// Structured output: Spring AI converts the AI's JSON reply into this record
public record TicketAnalysis(String category, String priority, String sentiment, String suggestedReply) {
}
private final ChatModel chatModel; // low-level API
private final ChatClient chatClient; // high-level fluent API
private final TicketRepository ticketRepository;
// Both ChatModel and ChatClient.Builder are auto-configured by the OpenAI starter
public SupportService(ChatModel chatModel,
ChatClient.Builder builder,
TicketRepository ticketRepository) {
this.chatModel = chatModel;
this.chatClient = builder.build();
this.ticketRepository = ticketRepository;
}
// 1) ChatModel API: we build the Prompt ourselves and read the full ChatResponse
public Map<String, Object> askWithChatModel(String message) {
Prompt prompt = new Prompt(List.of(
new SystemMessage("You are a polite customer support agent for ShopEasy, an online store. "
+ "Keep answers short and helpful."),
new UserMessage(message)));
ChatResponse response = chatModel.call(prompt);
String reply = response.getResult().getOutput().getText();
Usage usage = response.getMetadata().getUsage();
Map<String, Object> result = new LinkedHashMap<>();
result.put("api", "ChatModel");
result.put("model", response.getMetadata().getModel());
result.put("reply", reply);
result.put("promptTokens", usage.getPromptTokens());
result.put("completionTokens", usage.getCompletionTokens());
result.put("totalTokens", usage.getTotalTokens());
return result;
}
// 2) ChatClient API: fluent calls with a system template and parameters
public Map<String, Object> askWithChatClient(String customerName, String message) {
String reply = chatClient.prompt()
.system(s -> s.text("You are a polite customer support agent for {company}. "
+ "The customer's name is {name}. Greet them by name and keep the answer short.")
.param("company", "ShopEasy")
.param("name", customerName))
.user(message)
.call()
.content();
Map<String, Object> result = new LinkedHashMap<>();
result.put("api", "ChatClient");
result.put("customerName", customerName);
result.put("reply", reply);
return result;
}
// 3) ChatClient structured output: the AI classifies the complaint and a ticket is saved in MySQL
public Ticket createTicket(String customerName, String message) {
TicketAnalysis analysis = chatClient.prompt()
.system("You analyse customer support messages. "
+ "category must be one of BILLING, TECHNICAL, DELIVERY, ACCOUNT, OTHER. "
+ "priority must be one of HIGH, MEDIUM, LOW. "
+ "sentiment must be one of POSITIVE, NEUTRAL, NEGATIVE. "
+ "suggestedReply is a short, polite reply to the customer.")
.user(message)
.call()
.entity(TicketAnalysis.class);
Ticket ticket = new Ticket();
ticket.setCustomerName(customerName);
ticket.setMessage(message);
ticket.setCategory(analysis.category());
ticket.setPriority(analysis.priority());
ticket.setSentiment(analysis.sentiment());
ticket.setSuggestedReply(analysis.suggestedReply());
return ticketRepository.save(ticket);
}
public List<Ticket> getAllTickets() {
return ticketRepository.findAllByOrderByIdDesc();
}
public List<Ticket> getTicketsByPriority(String priority) {
return ticketRepository.findByPriorityOrderByIdDesc(priority.toUpperCase());
}
public Ticket getTicket(Long id) {
return ticketRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Ticket not found with id " + id));
}
}
package com.example.supportchatbot.controller;
import com.example.supportchatbot.entity.Ticket;
import com.example.supportchatbot.service.SupportService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/support")
public class SupportController {
private final SupportService supportService;
public SupportController(SupportService supportService) {
this.supportService = supportService;
}
// ChatModel API demo
@PostMapping("/chatmodel")
public Map<String, Object> chatModel(@RequestBody Map<String, String> request) {
return supportService.askWithChatModel(request.get("message"));
}
// ChatClient API demo
@PostMapping("/chatclient")
public Map<String, Object> chatClient(@RequestBody Map<String, String> request) {
return supportService.askWithChatClient(
request.getOrDefault("customerName", "Customer"), request.get("message"));
}
// ChatClient structured output demo: AI classifies the message and a ticket is saved
@PostMapping("/tickets")
public Ticket createTicket(@RequestBody Map<String, String> request) {
return supportService.createTicket(
request.getOrDefault("customerName", "Customer"), request.get("message"));
}
@GetMapping("/tickets")
public List<Ticket> getAllTickets() {
return supportService.getAllTickets();
}
@GetMapping("/tickets/priority/{priority}")
public List<Ticket> getByPriority(@PathVariable String priority) {
return supportService.getTicketsByPriority(priority);
}
@GetMapping("/tickets/{id}")
public Ticket getTicket(@PathVariable Long id) {
return supportService.getTicket(id);
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Map<String, String>> handleNotFound(IllegalArgumentException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", ex.getMessage()));
}
}
package com.example.supportchatbot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SupportChatbotApplication {
public static void main(String[] args) {
SpringApplication.run(SupportChatbotApplication.class, args);
}
}
application.properties
spring.application.name=support-chatbot
server.port=8080
# MySQL (create the database first: CREATE DATABASE support_db;)
spring.datasource.url=jdbc:mysql://localhost:3306/support_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.ai.google.genai.api-key=gemini-api-key
spring.ai.google.genai.chat.options.model=gemini-3.8-flash
spring.ai.google.genai.chat.options.temperature=0.7
spring.ai.retry.max-attempts=5
spring.ai.retry.backoff.initial-interval=2000ms
spring.ai.retry.backoff.multiplier=2
spring.ai.retry.backoff.max-interval=15000ms
Code language: PHP (php)
Step 4: Run the Application and test the below CURD operations
POST Payloads and URLs (use Postman)
| # | Method | URL | Body |
|---|---|---|---|
| 1 | POST | http://localhost:8080/api/support/chatmodel |
{"message":"Where is my order #1234? It was due yesterday."} |
| 2 | POST | http://localhost:8080/api/support/chatclient |
{"customerName":"Ravi","message":"How can I return a damaged product?"} |
| 3 | POST | http://localhost:8080/api/support/tickets |
{"customerName":"Ravi","message":"I was charged twice for my order and nobody is replying. This is very frustrating!"} |
| 4 | POST | http://localhost:8080/api/support/tickets |
{"customerName":"Anita","message":"Please tell me how to change my delivery address."} |
| 5 | GET | http://localhost:8080/api/support/tickets |
none |
| 6 | GET | http://localhost:8080/api/support/tickets/1 |
none |
| 7 | GET | http://localhost:8080/api/support/tickets/priority/HIGH |
none |
below is the sample post payload from postman,

