Spring AI - Chat Models & ChatClient API
Description
Comprehensive guide for implementing and configuring Chat Models and ChatClient APIs in Spring AI. Covers all supported LLM providers (OpenAI, Azure OpenAI, Bedrock, Ollama, etc.), configuration options, response handling, and streaming patterns.
When to Use
- Setting up chat interactions with language models
- Configuring ChatModel or ChatClient beans
- Implementing chat completions with specific providers
- Handling chat options and model parameters
- Working with structured outputs and tool calling
- Streaming chat responses
- Integration with Spring Boot applications
Topics Covered
1. Supported Chat Providers
- OpenAI: GPT-4o, GPT-4, GPT-3.5-turbo, o1-preview, o1-mini
- Azure OpenAI: Full integration with Azure deployments
- Anthropic Claude: Claude 3 Opus, Sonnet, Haiku
- Google Gemini: Gemini Pro, Gemini 2.0
- Amazon Bedrock: Multiple Titan, Claude, and Llama models
- Ollama: Local model inference
- Mistral AI: Open models
- HuggingFace: Community models
- Other providers: Grok, Perplexity, DeepSeek
2. ChatModel API Core
- Request: Prompt + ChatOptions
- Response: ChatResponse (generation + metadata)
- Streaming: Reactive Flux for real-time output
- Call Metrics: Token usage, cost, latency tracking
- Non-streaming vs Streaming: Performance considerations
3. ChatClient Fluent API
- High-level abstraction over ChatModel
- Method chaining for configuration
.user(), .system(), .messages()
.call(), .stream() for execution
.content(), .entity() for results
4. Chat Configuration
- Model/deployment selection
- Temperature, max_tokens, frequency_penalty
- Top_p, top_k sampling parameters
- Stop sequences
- Function calling mode (auto, none, required)
5. Response Handling
- Generation with usage information
- Tool calls in response
- Finish reason interpretation (STOP, LENGTH, TOOL_CALLS, etc.)
- Metadata extraction (model info, timestamps)
6. Structured Output
- Type-safe JSON responses
StructuredOutputConverter (JSON Schema mode)
Jackson and Gson support
- Automatic serialization/deserialization
7. Tool Calling Integration
- Automatic tool detection and binding
- Request model vs response format handling
- Exception handling and retries
- OpenAI, Anthropic, Google, Bedrock support
Code Patterns
Basic ChatModel Usage
@Configuration
public class ChatConfig {
@Bean
public ChatModel chatModel(OpenAiApi openAiApi) {
return new OpenAiChatModel(openAiApi,
OpenAiChatOptions.builder()
.withModel("gpt-4o")
.withTemperature(0.7f)
.build());
}
}
ChatClient with Streaming
chatClient.prompt()
.user("Question: " + userQuery)
.stream()
.content()
.doOnNext(content -> logger.info("Token: {}", content))
.blockLast();
Structured Output
var response = chatClient.prompt()
.user("Generate a person")
.call()
.entity(Person.class);
Configuration via Properties
spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.openai.chat.options.model=gpt-4o
spring.ai.openai.chat.options.temperature=0.7
spring.ai.openai.chat.options.max-tokens=1000
Related Skills
embeddings/SKILL.md - Vector embeddings
rag-retrieval/SKILL.md - RAG patterns
tools-agents/SKILL.md - Tool calling
advisors/SKILL.md - Chain of responsibility patterns
structured-output/SKILL.md - Type-safe responses
References
- API:
/pages/api/chatmodel.adoc, /pages/api/chatclient.adoc
- Providers:
/pages/api/bedrock.adoc, OpenAI, Azure OpenAI docs
- Tools:
/pages/api/tools.adoc, /pages/api/tools-migration.adoc
- Structured Output:
/pages/api/structured-output-converter.adoc
1---2name: spring-ai-chat-models3description: A comprehensive guide for implementing and configuring Chat Models and ChatClient APIs in Spring AI, covering all supported LLM providers.4license: Complete terms in LICENSE.txt5---67# Spring AI - Chat Models & ChatClient API89## Description1011Comprehensive guide for implementing and configuring Chat Models and ChatClient APIs in Spring AI. Covers all supported LLM providers (OpenAI, Azure OpenAI, Bedrock, Ollama, etc.), configuration options, response handling, and streaming patterns.1213## When to Use1415- Setting up chat interactions with language models16- Configuring ChatModel or ChatClient beans17- Implementing chat completions with specific providers18- Handling chat options and model parameters19- Working with structured outputs and tool calling20- Streaming chat responses21- Integration with Spring Boot applications2223## Topics Covered2425### 1. Supported Chat Providers2627- **OpenAI**: GPT-4o, GPT-4, GPT-3.5-turbo, o1-preview, o1-mini28- **Azure OpenAI**: Full integration with Azure deployments29- **Anthropic Claude**: Claude 3 Opus, Sonnet, Haiku30- **Google Gemini**: Gemini Pro, Gemini 2.031- **Amazon Bedrock**: Multiple Titan, Claude, and Llama models32- **Ollama**: Local model inference33- **Mistral AI**: Open models34- **HuggingFace**: Community models35- **Other providers**: Grok, Perplexity, DeepSeek3637### 2. ChatModel API Core3839- **Request**: Prompt + ChatOptions40- **Response**: ChatResponse (generation + metadata)41- **Streaming**: Reactive Flux<ChatResponse> for real-time output42- **Call Metrics**: Token usage, cost, latency tracking43- **Non-streaming vs Streaming**: Performance considerations4445### 3. ChatClient Fluent API4647- High-level abstraction over ChatModel48- Method chaining for configuration49- `.user()`, `.system()`, `.messages()`50- `.call()`, `.stream()` for execution51- `.content()`, `.entity()` for results5253### 4. Chat Configuration5455- Model/deployment selection56- Temperature, max_tokens, frequency_penalty57- Top_p, top_k sampling parameters58- Stop sequences59- Function calling mode (auto, none, required)6061### 5. Response Handling6263- Generation with usage information64- Tool calls in response65- Finish reason interpretation (STOP, LENGTH, TOOL_CALLS, etc.)66- Metadata extraction (model info, timestamps)6768### 6. Structured Output6970- Type-safe JSON responses71- `StructuredOutputConverter` (JSON Schema mode)72- `Jackson` and `Gson` support73- Automatic serialization/deserialization7475### 7. Tool Calling Integration7677- Automatic tool detection and binding78- Request model vs response format handling79- Exception handling and retries80- OpenAI, Anthropic, Google, Bedrock support8182## Code Patterns8384### Basic ChatModel Usage8586```java87@Configuration88public class ChatConfig {89 @Bean90 public ChatModel chatModel(OpenAiApi openAiApi) {91 return new OpenAiChatModel(openAiApi,92 OpenAiChatOptions.builder()93 .withModel("gpt-4o")94 .withTemperature(0.7f)95 .build());96 }97}98```99100### ChatClient with Streaming101102```java103chatClient.prompt()104 .user("Question: " + userQuery)105 .stream()106 .content()107 .doOnNext(content -> logger.info("Token: {}", content))108 .blockLast();109```110111### Structured Output112113```java114var response = chatClient.prompt()115 .user("Generate a person")116 .call()117 .entity(Person.class);118```119120## Configuration via Properties121122```properties123spring.ai.openai.api-key=${OPENAI_API_KEY}124spring.ai.openai.chat.options.model=gpt-4o125spring.ai.openai.chat.options.temperature=0.7126spring.ai.openai.chat.options.max-tokens=1000127```128129## Related Skills130131- `embeddings/SKILL.md` - Vector embeddings132- `rag-retrieval/SKILL.md` - RAG patterns133- `tools-agents/SKILL.md` - Tool calling134- `advisors/SKILL.md` - Chain of responsibility patterns135- `structured-output/SKILL.md` - Type-safe responses136137## References138139- API: `/pages/api/chatmodel.adoc`, `/pages/api/chatclient.adoc`140- Providers: `/pages/api/bedrock.adoc`, OpenAI, Azure OpenAI docs141- Tools: `/pages/api/tools.adoc`, `/pages/api/tools-migration.adoc`142- Structured Output: `/pages/api/structured-output-converter.adoc`