Skip to main content

Spring AI ChatClient: API, Features, and Usage

1. Introduction to Spring AI ChatClient​

Calling a large language model directly through provider SDKs presents a recurring set of engineering challenges: each provider exposes different request shapes, different response envelopes, different streaming semantics, and different error taxonomies. A service written against one provider's SDK is, by construction, difficult to port to another. Prompt assembly, conversation history, retrieval augmentation, and tool execution are likewise left to application code, producing duplicated infrastructure across services.

Spring AI addresses this with two complementary abstractions. ChatModel provides the provider-level contract — the lowest common denominator for sending messages to a model and receiving a response. ChatClient sits one layer above it, offering an application-facing fluent API for constructing prompts, invoking chat models, and handling responses. It does not replace ChatModel; it composes it, adding the ergonomics, advisor pipeline, and response-mapping capabilities that real applications require.

ChatClient is best understood as a stateless request orchestrator. It assembles a Prompt from declarative components, runs the request through an ordered advisor chain, delegates to a ChatModel, and exposes the result in a form suited to the caller — raw text, a typed Java object, a ChatResponse with metadata, or a reactive stream of chunks.

Typical scenarios where ChatClient is the appropriate entry point include:

  • Any Spring Boot service that needs to call an LLM and consume the result in application code.
  • Applications that require conversation memory, retrieval-augmented generation (RAG), or tool execution as cross-cutting concerns.
  • Systems that must map model output to domain types rather than raw strings.
  • Architectures that need to keep provider-specific configuration isolated from business logic.

2. ChatClient Architecture and Core Components​

The ChatClient API is composed of a small number of collaborating types, each with a distinct responsibility.

ComponentResponsibility
ChatClientApplication-facing fluent API; assembles prompts, invokes the advisor chain, exposes response extraction methods
ChatClient.BuilderMutable builder for constructing a ChatClient with defaults (system text, options, advisors, tools, template renderer)
ChatModelProvider-level abstraction; executes the actual request against the model backend
PromptImmutable representation of the request: a list of Message objects plus ChatOptions
Message / SystemMessage / UserMessageTyped message representations with role semantics
ChatOptionsModel parameters (model name, temperature, max tokens, and provider-specific options)
ChatResponseFramework-level response envelope containing Generation objects and metadata
ChatClientResponseApplication-level response wrapper that additionally carries the advisor context
AdvisorInterceptor that participates in request processing and can modify the prompt, context, or response

The relationship between these components can be visualized as follows:

The request path is layered: the application interacts only with ChatClient; ChatClient constructs a Prompt and passes it through the advisor chain; the terminal advisor invokes ChatModel; ChatModel translates the Prompt into a provider-specific request. This separation means that application code never depends on provider types, and provider-specific behavior is confined to the ChatModel implementation.

It is important to distinguish the application-facing API (ChatClient) from the model abstraction (ChatModel). ChatClient is concerned with how a request is described and what the caller receives back. ChatModel is concerned with how a request is transmitted to a specific provider and how the provider's response is normalized. Provider-specific implementation details — authentication, endpoint configuration, wire format — belong to the ChatModel and its auto-configuration, not to ChatClient.

For a source-code-level walkthrough of these relationships, see the ChatClient Source Code Analysis and ChatModel Source Code Analysis.

3. ChatClient vs ChatModel​

The existence of both ChatClient and ChatModel is a deliberate architectural choice, not redundancy. They serve different callers with different concerns.

DimensionChatClientChatModel
Abstraction levelApplication-levelProvider-level
Primary responsibilityPrompt construction, advisor orchestration, response mappingModel invocation and provider translation
API styleFluent, declarativeImperative, message-oriented
Prompt constructionSystem/user/template builderCaller supplies a Prompt
Advisor integrationFirst-class; client-level and request-levelNot involved; advisors operate above the model
Application integrationDesigned for injection into services and controllersInjected when provider-level control is required
Typical use casesBusiness services, RAG endpoints, agent entry pointsCustom model wrappers, provider-specific tuning, framework extensions

Application developers should prefer ChatClient for essentially all business logic. It provides the default system text, the advisor pipeline that carries memory and RAG, the structured-output mapping, and the fluent syntax that keeps prompt assembly readable. ChatModel is appropriate when a developer is building infrastructure — a custom advisor, a provider adapter, or a diagnostic tool — that operates below the application surface.

Internally, ChatClient always delegates to a ChatModel. Every call() and stream() invocation terminates in a ChatModel request. The two APIs are complementary: ChatClient supplies the application semantics, and ChatModel supplies the provider execution.

4. Creating and Configuring ChatClient​

4.1 Using Spring Boot Auto-Configuration​

Spring Boot auto-configuration provides a prototype ChatClient.Builder bean for every auto-configured ChatModel. The recommended pattern is constructor injection of the builder:

@RestController
class MyController {

private final ChatClient chatClient;

public MyController(ChatClient.Builder chatClientBuilder) {
this.chatClient = chatClientBuilder.build();
}

@GetMapping("/ai")
String generation(String userInput) {
return this.chatClient.prompt()
.user(userInput)
.call()
.content();
}
}

This pattern is documented as the simplest supported creation path. The builder is a prototype bean, meaning each injection site receives its own instance and can customize defaults independently.

4.2 Creating ChatClient Programmatically​

When a ChatModel is available but the auto-configured builder is not desired — for example, in tests or in applications with multiple models — ChatClient can be created programmatically:

ChatModel chatModel = ...; // obtained from configuration or another bean

ChatClient chatClient = ChatClient.create(chatModel);

// Or, with explicit builder for defaults:
ChatClient client = ChatClient.builder(chatModel)
.defaultSystem("You are a concise Java expert.")
.build();

ChatClient.create(ChatModel) and ChatClient.builder(ChatModel) are the two documented programmatic entry points. create is appropriate for a stateless client with no defaults; builder is required whenever defaults must be applied.

4.3 Configuring a Reusable ChatClient Bean​

Exposing a configured ChatClient as a Spring bean centralizes default behavior and avoids repeated builder calls across services:

@Configuration
class AiConfig {

@Bean
ChatClient chatClient(ChatClient.Builder builder) {
return builder
.defaultSystem("""
You are a backend engineering assistant.
Answer concisely and prefer concrete examples.
""")
.defaultAdvisors(new SimpleLoggerAdvisor())
.build();
}
}

This approach has three benefits: dependency injection provides a single configured client to every consumer; default system instructions and advisors are applied uniformly; and changes to defaults require editing one class rather than every call site.

4.4 Using Multiple Chat Models​

Applications frequently need more than one model — a reasoning-capable model for complex tasks and a faster, cheaper model for routine ones, or separate models for different business domains. When multiple ChatClient instances are required, disable the builder auto-configuration:

spring:
ai:
chat:
client:
enabled: false

Then create clients manually from the available ChatModel beans:

@Configuration
class MultiModelConfig {

@Bean
ChatClient fastClient(@Qualifier("openAiChatModel") ChatModel model) {
return ChatClient.builder(model)
.defaultOptions(ChatOptions.builder().model("gpt-4o-mini").build())
.build();
}

@Bean
ChatClient reasoningClient(@Qualifier("anthropicChatModel") ChatModel model) {
return ChatClient.builder(model)
.defaultOptions(ChatOptions.builder().model("claude-sonnet-4-5").build())
.build();
}
}

Provider-specific behavior does not disappear when switching models through configuration. Temperature ranges, structured-output support, and tool-calling semantics remain provider-dependent, so multi-model boundaries should be explicit in the service layer rather than hidden behind a single default client.

5. Understanding the ChatClient Fluent API​

The fluent API is the central programming model. ChatClient exposes three documented entry points for starting a request:

Entry pointPurpose
prompt()Start a new request specification with no initial content
prompt(String content)Start a request with the string as user content
prompt(Prompt prompt)Start from an existing Prompt object

The returned ChatClientRequestSpec supports method chaining for system text, user messages, options, tools, advisors, and template parameters.

Basic request​

String answer = chatClient.prompt()
.user("What is a virtual thread?")
.call()
.content();

System instruction plus user input​

String answer = chatClient.prompt()
.system("You are a JVM performance engineer. Prefer measurable claims.")
.user(userQuestion)
.call()
.content();

Starting from an existing Prompt​

Prompt prompt = new Prompt(List.of(
new SystemMessage("You are a code reviewer."),
new UserMessage("Review this method: " + codeSnippet)
));

String review = chatClient.prompt(prompt).call().content();

Combining messages explicitly​

String answer = chatClient.prompt()
.messages(
new SystemMessage("You are a database architect."),
new UserMessage("Compare B-tree and LSM-tree indexes.")
)
.call()
.content();

The fluent API is intentionally a request specification, not a builder of a persistent prompt. Each prompt() call starts a fresh specification, and the terminal call() or stream() consumes it. Reusing a specification across requests is not the intended pattern; defaults should be applied at the client level instead.

6. Prompt Construction and Template Variables​

Spring AI prompts are collections of Message objects. ChatClient provides conveniences for constructing them, but the underlying model remains the message list: system messages carry behavioral instructions, user messages carry the request, and both can contain template placeholders resolved at runtime.

Template variables are supplied through a lambda that exposes text() and param():

String answer = chatClient.prompt()
.user(u -> u.text("Summarise the following document in {language}: {doc}")
.param("language", "German")
.param("doc", documentText))
.call()
.content();

The default template syntax uses {} placeholders. This has an important consequence: prompts that contain literal JSON will be interpreted as templates. Curly braces in JSON payloads must be escaped or handled through a custom TemplateRenderer that uses a different delimiter. Spring AI allows a TemplateRenderer to be configured on the builder, which is the appropriate place to change delimiter behavior globally.

Note also that advisors may perform their own template processing with a separate renderer configuration. An advisor’s template handling should not be assumed to inherit the ChatClient builder’s renderer; this distinction matters when building custom advisors that inject context.

7. Default Configuration and Request-Level Overrides​

ChatClient.Builder exists primarily to define reusable defaults. The documented configuration categories are:

  • Default system text
  • Default user content
  • Default model options
  • Default tools
  • Default tool context
  • Default advisors
  • Default template renderer

Request-level settings can extend or replace these defaults. The replacement-versus-addition distinction differs by category:

ConfigurationClient-level defaultRequest-level behavior
System messagedefaultSystem(...).system(...) replaces the default for that request
User messagedefaultUser(...).user(...) adds or replaces request user content
Model optionsdefaultOptions(...).options(...) merges; request-level values take precedence
ToolsdefaultTools(...).tools(...) adds to the default tool set
AdvisorsdefaultAdvisors(...).advisors(...) adds to the default chain
Template rendererdefaultTemplateRenderer(...)Not typically overridden per request

For advisors and tools, the request-level methods are additive: a request-level advisor is appended to the client-level chain, and request-level tools are made available alongside default tools. For options, the request-level ChatOptions is merged over the defaults, so a request can change temperature without restating the model name. For system text, .system(...) on the request replaces the client default for that invocation.

This asymmetry is intentional. Advisors and tools are compositional — adding a RAG advisor to one request should not remove logging or memory advisors. System instructions, by contrast, are often task-specific and should be replaceable when a particular request needs different behavior.

8. Synchronous Model Invocation​

The synchronous lifecycle has four steps: construct the prompt, invoke call(), retrieve the response, and process the result.

@Service
class SummaryService {

private final ChatClient chatClient;

SummaryService(ChatClient chatClient) {
this.chatClient = chatClient;
}

String summarise(String document) {
return chatClient.prompt()
.system("Summarise technical documents in three bullet points.")
.user(document)
.call()
.content();
}
}

The terminal call() returns a CallResponseSpec, which exposes four commonly used extraction methods:

MethodReturnsWhen to use
content()StringThe caller needs the assistant text only
chatResponse()ChatResponseThe caller needs generations, finish reason, or token metadata
chatClientResponse()ChatClientResponseThe caller also needs advisor context
entity(Class<T>)TThe caller needs a typed domain object

These return types are not interchangeable. content() may return null when the model produces no textual content, whereas ChatModel.call(String) returns an empty string in the equivalent situation. Code that consumes content() should guard against null explicitly rather than assuming the two paths behave identically.

chatResponse() is the appropriate choice when usage statistics or finish reasons matter — for cost accounting, truncation detection, or audit logging. chatClientResponse() is needed when downstream code must inspect the advisor context that accompanied the response.

9. Streaming Responses with ChatClient​

Streaming is exposed through stream() rather than call(). The response is a reactive Flux:

@Service
class StreamingChatService {

private final ChatClient chatClient;

StreamingChatService(ChatClient chatClient) {
this.chatClient = chatClient;
}

Flux<String> stream(String question) {
return chatClient.prompt()
.user(question)
.stream()
.content();
}
}

A Spring WebFlux controller can expose this directly as Server-Sent Events:

@RestController
class StreamingController {

private final StreamingChatService service;

StreamingController(StreamingChatService service) {
this.service = service;
}

@GetMapping(value = "/ai/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> stream(@RequestParam String question) {
return service.stream(question);
}
}

The streaming path differs from the synchronous path in several architecturally significant ways:

  • Time to first token. Streaming delivers the first chunk as soon as the model emits it, which improves perceived responsiveness even when total generation time is unchanged.
  • Connection lifetime. The HTTP connection remains open for the duration of generation. Proxies, load balancers, and client timeouts must be configured accordingly.
  • Error handling. An error can occur after partial output has been delivered. The caller has already received data, so recovery cannot simply be a retry that restarts the stream; it must account for the partial result.
  • Cancellation. Subscriber cancellation must propagate to the underlying model request. Blocking operations inside a reactive pipeline prevent this and should be avoided.
  • Backpressure. A slow consumer can apply backpressure to the stream. The model provider does not necessarily honour backpressure, so buffering behavior should be understood before relying on it.

The critical distinction is between consuming a reactive stream and blocking for a final result. Calling .block() on the stream inside a WebFlux request handler defeats the purpose of streaming and can exhaust the event loop. For callers that genuinely need the complete text, use call().content() instead of streaming and blocking.

10. Structured Output and Java Object Mapping​

ChatClient can map model output directly to Java types through the entity() family of methods:

record Recipe(String name, List<String> ingredients, int prepMinutes) {}

Recipe recipe = chatClient.prompt()
.user("Give me a recipe for a simple tomato soup.")
.call()
.entity(Recipe.class);

Generic types are supported through ParameterizedTypeReference:

List<Recipe> recipes = chatClient.prompt()
.user("Give me three soup recipes.")
.call()
.entity(new ParameterizedTypeReference<List<Recipe>>() {});

Three modes of structured output exist, and they are not equivalent:

ModeMechanismTrade-off
Plain textcontent()No schema guarantee; caller parses manually
Converter-basedentity(Class<T>) using a StructuredOutputConverterFramework generates format instructions and parses the result; depends on model compliance
Provider-nativeProvider structured-output feature where supportedStronger schema enforcement; provider-specific and not universally available

The converter-based path is portable across providers but relies on the model following format instructions. It can fail when the model emits invalid JSON, omits required fields, or produces a schema-incompatible response. Provider-native structured output can enforce schema more reliably but is not available on every model and is not interchangeable across providers. entity() also supports supplying a custom converter when a non-default mapping strategy is required.

For an internal walkthrough of the conversion pipeline, see the Structured Output Source Code Analysis.

11. Integrating Advisors with ChatClient​

Advisors are the mechanism by which Spring AI makes cross-cutting AI concerns composable. An advisor participates in request processing, can inspect and modify the prompt, can contribute execution context, and can post-process the response.

ChatClient exposes advisors at two levels:

  • Client-level defaults through defaultAdvisors(...) on the builder
  • Request-level additions through .advisors(...) on the request specification

Advisor ordering determines execution sequence. When multiple advisors are registered, each has a precedence that controls whether it wraps or is wrapped by the others. Ordering matters materially: a memory advisor that must see the final assembled prompt should not be positioned inside an advisor that rewrites the prompt afterward.

A simplified request flow through multiple advisors:

Practical uses of advisors through ChatClient include logging and inspection, chat memory, retrieval-augmented generation, context injection, and request/response processing. The Advisor Source Code Analysis covers the internal advisor contract; at the ChatClient level, the relevant concern is registration and ordering.

12. Chat Memory and Conversation Context​

A chat model invocation is stateless unless conversation context is explicitly supplied. Each call() or stream() sends only the messages in that request; the model has no recollection of previous calls. Conversation continuity is therefore an application-level concern, handled in Spring AI through ChatMemory and a memory advisor.

@Bean
ChatClient chatClient(ChatClient.Builder builder, ChatMemory chatMemory) {
return builder
.defaultAdvisors(
MessageChatMemoryAdvisor.builder(chatMemory).build()
)
.build();
}

When a memory advisor is registered, the request must identify the conversation. This is done through the advisor context:

String answer = chatClient.prompt()
.user(question)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
.call()
.content();

Omitting the conversation identifier when the memory advisor requires one is a common source of runtime failures. The memory advisor needs to know which conversation history to load and update; without an identifier, it cannot resolve the correct history.

Context-window management is a separate concern from memory storage. As conversation history grows, it will eventually exceed the model’s context limit. Spring AI provides window-based memory implementations that bound the number of retained messages, and these implementations apply eviction policies. The eviction policy matters: naive truncation can split a multi-message turn, so implementations that snap eviction boundaries to user-message boundaries exist specifically to avoid this class of bug.

For production deployments, in-memory storage should not be treated as a default. A ChatMemoryRepository backed by a shared store is required for distributed applications, and the choice of store carries operational implications — retention, isolation between tenants, and the ability to inspect or delete conversation data.

For the memory implementation internals, see the Memory Source Code Analysis.

13. Tool Calling Through ChatClient​

Tool calling allows the model to request execution of application-provided functions. Through ChatClient, tools can be registered as client-level defaults or supplied per request.

class WeatherTools {

@Tool(description = "Get the current weather for a city")
String weather(@ToolParam(description = "City name") String city) {
return weatherClient.current(city);
}
}

String answer = chatClient.prompt()
.user("What is the weather in Amsterdam?")
.tools(new WeatherTools())
.call()
.content();

Tools are objects whose methods carry @Tool; parameters can be documented with @ToolParam so the model can populate them correctly. ChatClient also accepts ToolCallback instances and ToolCallbackProvider implementations directly, which is the appropriate form when tools are not expressed as annotated methods.

The responsibilities in a tool-calling interaction are divided as follows:

  1. The application registers tools on the request or client.
  2. The model may emit a tool-call instruction in its response.
  3. The application executes the requested tool through the configured mechanism.
  4. The tool result is fed back into the ongoing interaction.
  5. The model produces the final response.

In Spring AI 2.0, the tool-execution loop is no longer built into individual ChatModel implementations. It is handled at the ChatClient level through ToolCallingAdvisor, which is registered as an advisor and manages the iteration until no further tool calls remain. This is an architectural consolidation: tool execution is treated as orchestration rather than as a provider capability.

Tool calling carries security obligations that belong to the application, not the framework:

  • Input validation. Tool parameters are model-generated and must be treated as untrusted input.
  • Authorization. The model’s request to invoke a tool does not confer permission to do so; the application must enforce access control.
  • Least privilege. Only tools appropriate to the current request should be registered. Request-level .tools(...) exists for exactly this reason.
  • Audit logging. Tool invocations that affect business state should be logged with sufficient context for investigation.
  • No unrestricted internal access. A tool that proxies arbitrary internal service calls effectively grants the model access to those services.

Not every provider supports tool calling identically. Some providers differ in parallel tool-call behavior, result formatting, or whether tool use is available at all. Portability of the application code does not guarantee portability of tool-calling behavior.

14. ChatClient in a Spring Boot Application​

The following example illustrates the full programming model in a realistic service, deliberately focused on ChatClient usage rather than on installation or environment setup.

Configuration:

@Configuration
class ChatConfig {

@Bean
ChatClient chatClient(ChatClient.Builder builder, ChatMemory chatMemory) {
return builder
.defaultSystem("You are a support assistant. Be concise and factual.")
.defaultAdvisors(
MessageChatMemoryAdvisor.builder(chatMemory).build()
)
.build();
}
}

Service:

@Service
class SupportService {

private final ChatClient chatClient;

SupportService(ChatClient chatClient) {
this.chatClient = chatClient;
}

String ask(String conversationId, String question) {
return chatClient.prompt()
.user(question)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
.call()
.content();
}
}

Controller:

@RestController
@RequestMapping("/support")
class SupportController {

private final SupportService supportService;

SupportController(SupportService supportService) {
this.supportService = supportService;
}

@PostMapping("/ask")
String ask(@RequestParam String conversationId, @RequestBody String question) {
return supportService.ask(conversationId, question);
}
}

The service constructs the prompt, applies request-level conversation context, invokes the model synchronously, and extracts text. The controller contains no AI-specific logic; it delegates entirely to the service, which is the unit that depends on ChatClient.

15. Error Handling, Observability, and Testing​

Error Handling​

Model provider failures, network errors, rate limits, and timeouts are all normal operating conditions for an AI-backed service. They should be handled explicitly rather than allowed to propagate as generic exceptions.

Retry policy must consider whether an operation is safe to repeat. A failed synchronous text-generation request is generally idempotent and safe to retry. A request that has already executed a tool with side effects is not. Retrying a streamed response after partial delivery requires deciding what to do with the partial output already sent to the caller. These distinctions cannot be resolved by a blanket retry annotation; the retry boundary should align with the operation’s actual side-effect profile.

Invalid or incomplete model output is a separate failure category. When entity() is used, parsing failures and schema violations are expected possibilities, not exceptional defects, and should be handled at the boundary where the typed object is consumed.

For broader patterns, see the Spring AI Error Handling and Retry Strategies article.

Observability​

Spring AI integrates with the Spring observability stack, which means ChatClient invocations can be observed through Micrometer and, when configured, traced through OpenTelemetry. Request and response logging is available but carries a specific risk: prompts frequently contain personal data, credentials embedded in context, or proprietary business content. Logging must be configured with masking or sampling rather than enabled wholesale. Token usage and response metadata are available through ChatResponse and are generally safer to log than prompt content.

The ChatClient observation boundary should not be confused with the underlying model observation. ChatClient observability covers the application-level request, including advisor processing; the model-level observation covers the provider call. Both are useful, and they answer different operational questions.

Testing​

Services that depend on ChatClient can be unit-tested by supplying a mock ChatClient through constructor injection; this isolates prompt assembly and response handling from the model entirely. Integration tests that exercise an actual model should be scoped to the behaviors that require a real model — structured-output compatibility, tool-calling behavior, and provider-specific quirks — rather than duplicating the unit-test coverage.

For a detailed treatment, see the Spring AI Testing Guide.

16. Performance and Production Design Considerations​

ChatClient is a stateless orchestrator, and the dominant cost in any invocation is model inference and network latency. Framework-level overhead should be evaluated in that context rather than optimized in isolation. The practical design considerations are architectural rather than micro-optimizational:

  • Reuse configured clients. A ChatClient bean should be built once and injected. Constructing a new client per request gains nothing and discards configured defaults.
  • Choose invocation mode deliberately. Streaming is appropriate for interactive surfaces where time-to-first-token matters; synchronous invocation is appropriate for background processing where the complete result is required.
  • Bound prompt size. Every token in the prompt is paid for and adds latency. Retrieved context should be limited by relevance rather than included wholesale.
  • Manage conversation growth. Unbounded history increases cost and eventually exceeds context limits. Memory windowing is a production requirement, not an optimization.
  • Isolate provider-specific options. Options that only one provider understands should not leak into shared configuration used by other providers.
  • Separate prompt construction from business logic. Prompt text embedded in service methods is difficult to test, review, and change independently of the logic around it.
  • Account for concurrency. Model calls are I/O-bound; thread-pool sizing should reflect that, and streaming consumers must not block the event loop.

Claims about ChatClient thread safety or throughput should be verified against the source before being relied upon in design; the framework does not document performance characteristics as a contractual guarantee.

17. ChatClient Design Patterns and Best Practices​

The following practices are applicable to enterprise Java applications regardless of provider:

  • Encapsulate ChatClient in dedicated application services. Controllers and domain services should not depend on ChatClient directly; a thin AI service layer concentrates prompt construction, advisor configuration, and response mapping in one place.
  • Centralize common defaults. Default system text, advisors, and options belong in a ChatClient bean, not duplicated at call sites.
  • Keep prompt templates out of business logic where practical. Templates that change independently of logic are better managed as resources or dedicated components.
  • Prefer structured output for typed responses. When the caller needs domain objects, entity() is safer than parsing strings ad hoc.
  • Apply advisors deliberately and manage ordering. Each advisor should have a clear reason for its position in the chain.
  • Use request-level tools for high-risk operations. Tools that can affect business state should be scoped to the requests that legitimately need them.
  • Keep provider-specific options isolated. Provider-specific tuning should be confined to the configuration of the relevant client, not spread across services.
  • Apply observability and masking together. Logging prompt content without masking is an incident waiting to happen.
  • Test model-dependent behavior separately. Unit-test prompt assembly and response handling; reserve real-model tests for compatibility concerns.
RequirementRecommended ChatClient feature
Consistent personadefaultSystem(...)
Per-task behavior.system(...) on the request
Conversation continuityMemory advisor with conversation ID
Retrieval augmentationRAG advisor
Typed responses.entity(Class<T>)
Restricted tool access.tools(...) at request level
Provider tuningdefaultOptions(...) on the relevant client
Cross-cutting loggingClient-level advisor

18. Common Mistakes and Troubleshooting​

MistakeCauseSymptomRecommended solution
Confusing ChatClient with ChatModelTreating the application API as a provider APIAttempting provider-specific configuration on ChatClientUse ChatClient for application concerns; configure providers on ChatModel
Creating a new client per requestMisunderstanding client lifecycleRepeated default configuration, unnecessary allocationBuild once; inject as a bean
Mixing provider-specific options with portable configurationAssuming all providers accept the same optionsFailures or silently ignored settings when switching providersIsolate provider-specific options in per-provider clients
Blocking inside a reactive handlerCalling .block() on a streamEvent-loop starvation, timeouts under loadReturn Flux to the caller; use call().content() when blocking is genuinely required
Assuming all models support structured outputPortability assumptionParsing failures or unsupported-feature errorsVerify provider capability; fall back to converter-based parsing
Assuming all providers support tool callingPortability assumptionMissing tool-call instructions or different result formatsTest tool behavior per provider; document capability
Ignoring advisor orderingDefaulting to registration order without analysisMemory or RAG advisors operating on incomplete promptsSet precedence deliberately and verify with a logging advisor
Omitting conversation identifiersForgetting memory advisor requirementsMemory not applied, or history attached to the wrong conversationAlways supply ChatMemory.CONVERSATION_ID when memory is enabled
Logging prompt contentEnabling prompt logging without maskingPersonal or proprietary data in logsMask or sample; prefer metadata over content
Treating generated output as valid business dataTrusting model outputBad data persisted or acted uponValidate at the boundary; use entity() with error handling

19. Frequently Asked Questions​

What is Spring AI ChatClient? ChatClient is the application-facing fluent API in Spring AI for building prompts, invoking chat models, and handling responses. It delegates to ChatModel and provides advisors, structured-output mapping, and streaming.

What is the difference between ChatClient and ChatModel? ChatClient is the application-level API for prompt construction and response handling; ChatModel is the provider-level abstraction that executes requests against a specific model backend.

Is ChatClient provider-independent? Application code written against ChatClient is provider-independent, but provider-specific behavior — supported options, structured-output enforcement, tool-calling semantics — is not. Portability is at the API level, not at the behavioral level.

Is ChatClient synchronous or asynchronous? Both. call() is synchronous; stream() returns a reactive Flux for asynchronous, incremental consumption.

How do I stream responses using ChatClient? Use stream() instead of call(). It returns a Flux of content or responses that can be returned directly from a WebFlux controller as Server-Sent Events.

Can ChatClient return a Java object? Yes. entity(Class<T>) and entity(ParameterizedTypeReference<T>) map model output to Java types using a StructuredOutputConverter, with provider-native structured output where supported.

How does ChatClient support tool calling? Tools are registered through defaultTools(...) or request-level .tools(...). In Spring AI 2.0, the execution loop is handled by ToolCallingAdvisor, which is registered as an advisor and manages iteration until no tool calls remain.

How do I integrate chat memory with ChatClient? Register a memory advisor, such as MessageChatMemoryAdvisor, as a client-level default, and pass a conversation identifier through the advisor context on each request.

Can one Spring Boot application use multiple ChatClients? Yes. Disable builder auto-configuration and define separate ChatClient beans backed by different ChatModel beans or different default options.

Should I use ChatClient or call the model provider SDK directly? Use ChatClient when you want portable application code, advisor-based cross-cutting concerns, and Spring Boot integration. Call the provider SDK directly only when you need provider-specific features outside the abstraction’s coverage.