Spring AI Integration
Use when integrating LLMs, chat clients, embeddings, RAG pipelines, or AI agents into Spring Boot. Covers Spring AI 2.0 ChatClient, prompt templates, embeddings, vector stores, and structured output. Use when user mentions Spring AI, LLM, ChatGPT, Claude, RAG, embeddings.
View SKILL.mdDependencies
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>2.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Choose your model provider — pattern is spring-ai-starter-model-<provider> -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-anthropic</artifactId>
</dependency>
<!-- OR -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
<!-- For RAG / vector search -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-pgvector</artifactId>
</dependency>
<!-- QuestionAnswerAdvisor lives here — 2.0 renamed spring-ai-advisors-vector-store -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-vector-store-advisor</artifactId>
</dependency>
</dependencies>
Version pairing matters. Spring Boot 4 requires Spring AI 2.0 (
spring-ai-bom2.0.0); the 1.x line targets Boot 3 only. Starter coordinates followspring-ai-starter-model-<provider>(e.g.-model-anthropic,-model-openai) andspring-ai-starter-vector-store-<store>. Agents trained on pre-1.0 Spring AI emitspring-ai-<x>-spring-boot-starter— those names resolve to nothing in Maven Central. Also gone in 2.0:spring-ai-starter-model-azure-openai(use the OpenAI starter with an Azure base URL instead).
ChatClient — Basic Usage
@Service
@RequiredArgsConstructor
public class DocumentSummaryService {
private final ChatClient chatClient;
public String summarize(String conversationId, String content) {
return chatClient.prompt()
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
.user(u -> u.text("Summarize the following document in 3 bullet points:\n\n{content}")
.param("content", content))
.call()
.content();
}
// With system prompt
public String analyzeFinancial(String conversationId, String document, String language) {
return chatClient.prompt()
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
.system("You are a financial analyst. Respond in {language}.")
.system(s -> s.param("language", language))
.user(document)
.call()
.content();
}
}
Every call using the configured memory advisor must provide a user- or session-scoped
ChatMemory.CONVERSATION_ID. Never use one shared conversation ID for all users.
ChatClient Bean Configuration
@Configuration
public class AiConfig {
@Bean
public ChatMemory chatMemory() {
// InMemoryChatMemory is long gone. Use MessageWindowChatMemory —
// it caps history to a sliding window and defaults to an in-memory repository.
return MessageWindowChatMemory.builder()
.maxMessages(20)
.build();
}
@Bean
public ChatClient chatClient(ChatClient.Builder builder, ChatMemory chatMemory) {
return builder
.defaultSystem("You are a helpful assistant for an e-commerce platform.")
.defaultAdvisors(
MessageChatMemoryAdvisor.builder(chatMemory).build(), // builder, not new(...)
new SimpleLoggerAdvisor() // logs prompts/responses
)
.build();
}
}
// 2.0: the conversation id is REQUIRED on every call that goes through a memory advisor.
// ChatMemory.DEFAULT_CONVERSATION_ID is removed — omitting the param throws IllegalArgumentException.
public String chat(String sessionId, String message) {
return chatClient.prompt()
.user(message)
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, sessionId))
.call()
.content();
}
Prompt Templates (externalized)
// src/main/resources/prompts/analyze-order.st
// Analyze this order and identify any anomalies:
// Customer: {customerEmail}
// Items: {items}
// Total: {total}
// Flag any unusual patterns.
@Service
@RequiredArgsConstructor
public class OrderAnalysisService {
private final ChatClient chatClient;
@Value("classpath:prompts/analyze-order.st")
private Resource promptTemplate;
public String analyzeOrder(String conversationId, Order order) {
return chatClient.prompt()
.advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
.user(u -> u.text(promptTemplate)
.param("customerEmail", order.getCustomerEmail()) // must match {customerEmail} in the .st
.param("items", order.getItems().toString())
.param("total", order.getTotal()))
.call()
.content();
}
}
Structured Output
// Define the target record
public record OrderClassification(
String category,
String priority,
List<String> tags,
boolean requiresManualReview
) {}
@Service
public class OrderClassifier {
public OrderClassification classify(String orderDescription) {
return chatClient.prompt()
.user("Classify this order: " + orderDescription)
.call()
.entity(OrderClassification.class); // Spring AI handles JSON parsing
}
}
RAG Pipeline
@Configuration
public class RagConfig {
// No manual VectorStore bean — the spring-ai-starter-vector-store-pgvector
// starter auto-configures one. Just inject it. (The old `new PgVectorStore(...)`
// constructor is removed; if you must build one, use PgVectorStore.builder(...).)
@Bean
public ChatClient ragChatClient(ChatClient.Builder builder, VectorStore vectorStore) {
return builder
.defaultAdvisors(
QuestionAnswerAdvisor.builder(vectorStore)
.searchRequest(SearchRequest.builder().topK(5).build()) // builder, not defaults().withTopK()
.build()
)
.build();
}
}
@Service
@RequiredArgsConstructor
public class KnowledgeService {
private final VectorStore vectorStore;
private final ChatClient ragChatClient;
// Ingest documents
public void ingest(List<String> documents) {
List<Document> docs = documents.stream()
.map(content -> new Document(content))
.toList();
vectorStore.add(docs);
}
// Query with RAG
public String ask(String question) {
return ragChatClient.prompt()
.user(question)
.call()
.content();
}
}
Streaming Responses
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> stream(@RequestParam String prompt) {
return chatClient.prompt()
.user(prompt)
.stream()
.content();
}
application.yml
spring:
ai:
anthropic:
api-key: ${ANTHROPIC_API_KEY}
chat:
# 2.0 flattened the properties — the old chat.options.* nesting is dead
model: ${ANTHROPIC_MODEL}
max-tokens: 2048
temperature: 0.7 # 2.0 removed the 0.7 default — set it explicitly if you rely on it
# OR for OpenAI:
openai:
api-key: ${OPENAI_API_KEY}
chat:
model: ${OPENAI_MODEL}
vectorstore:
pgvector:
initialize-schema: true
dimensions: 1536
Gotchas
- Agent binds
.param("customer", ...)when the.stfile says{customerEmail}— the default renderer fails with "Not all variables were replaced"; keep param names and template placeholders identical - Agent uses Spring AI 1.x (
spring-ai-bom1.0.x) on Spring Boot 4 — 1.x targets Boot 3 only; Boot 4 requires Spring AI 2.0 - Agent uses pre-1.0 artifact names (
spring-ai-anthropic-spring-boot-starter) — the pattern isspring-ai-starter-model-anthropic - Agent configures
spring.ai.anthropic.chat.options.model— 2.0 flattened properties; drop the.optionssegment (spring.ai.anthropic.chat.model) - Agent passes built options to
.options(...)— 2.0 takes the builder:.options(AnthropicChatOptions.builder().maxTokens(2048)), no.build() - Agent writes
new MessageChatMemoryAdvisor(new InMemoryChatMemory())— both long removed; useMessageChatMemoryAdvisor.builder(chatMemory)+MessageWindowChatMemory - Agent omits the conversation id on a memory-advisor call — mandatory in 2.0 (
ChatMemory.DEFAULT_CONVERSATION_IDremoved); passa.param(ChatMemory.CONVERSATION_ID, ...)or getIllegalArgumentException - Agent uses
PromptChatMemoryAdvisor— removed in 2.0; useMessageChatMemoryAdvisor - Agent adds
spring-ai-advisors-vector-storeforQuestionAnswerAdvisor— renamed tospring-ai-vector-store-advisorin 2.0 - Agent writes
SearchRequest.defaults().withTopK(n)— useSearchRequest.builder().topK(n).build() - Agent hardcodes API keys — always use environment variables /
${...} - Agent hardcodes provider model IDs - configure them externally because model catalogs change
- Agent builds prompts with string concatenation — use
.param()template variables - Agent puts prompts inline in code — externalize to
src/main/resources/prompts/ - Agent ignores structured output — use
.entity(MyClass.class)instead of parsing manually - Agent uses
.entity(List.class)for a list — generics erase; passnew ParameterizedTypeReference<List<X>>() {} - Agent skips error handling for API calls — wrap in try/catch, handle
NonTransientAiException(don't retry) vsTransientAiException(retry) - Agent uses wrong model string — verify model names against provider docs
Examples & templates
bad-ai-service.javaexamples
// ❌ BAD — hardcoded key, string concatenation, inline prompts, no error handling
@Service
public class OrderAnalysisService {
// ❌ Hardcoded API key in source code — should be in environment variable
private static final String API_KEY = "sk-ant-abc123...";
@Autowired
private ChatClient.Builder chatClientBuilder; // builds new client per call — wasteful
public String analyzeOrder(Order order) {
ChatClient client = chatClientBuilder.build(); // should be injected as singleton
// ❌ String concatenation for prompt — use .param() with templates
String prompt = "Analyze this order: " +
"Customer: " + order.getCustomerEmail() + ", " +
"Items: " + order.getItems() + ", " +
"Total: " + order.getTotal();
// ❌ Inline prompt with no externalization
String response = client.prompt()
.user(prompt) // raw concatenated string
.call()
.content(); // returns raw String, not structured
// ❌ Manual JSON parsing instead of .entity()
try {
JsonMapper mapper = JsonMapper.builder().build(); // should be injected — Boot 4 exposes a Jackson 3 JsonMapper bean
return mapper.readTree(response)
.get("analysis").asText();
} catch (Exception e) {
return "Error"; // swallows exception, no logging
}
}
// ❌ No Flux/streaming for long responses — blocks thread
// ❌ No observability — can't track token usage or latency
// ❌ No fallback behavior when AI service is unavailable
}good-ai-service.javaexamples
// ✅ GOOD — injected ChatClient, externalized prompts, structured output, error handling
@Service
@Slf4j
public class OrderAnalysisService {
// One-shot analysis: a stateless client built from the auto-configured (prototype)
// ChatClient.Builder. The shared ChatClient bean carries MessageChatMemoryAdvisor,
// which needs a per-user conversation id — without one, Spring AI 2 rejects the
// call and 1.x silently pools every user into one shared chat history.
private final ChatClient chatClient;
public OrderAnalysisService(ChatClient.Builder builder) {
this.chatClient = builder.build();
}
// Externalized prompt template loaded from classpath:prompts/analyze-order.st
@Value("classpath:prompts/analyze-order.st")
private Resource analyzePrompt;
public OrderAnalysis analyzeOrder(Order order) {
try {
return chatClient.prompt()
.user(u -> u
.text(analyzePrompt)
.param("customerEmail", order.getCustomerEmail())
.param("items", order.getItems().toString())
.param("total", order.getTotal().toString()))
.call()
.entity(OrderAnalysis.class); // structured output — auto-parsed to record
} catch (Exception e) {
log.error("AI analysis failed for order {}", order.getId(), e);
return OrderAnalysis.fallback("Analysis unavailable");
}
}
// Streaming for long responses
public Flux<String> streamRecommendations(UUID customerId, List<Order> history) {
return chatClient.prompt()
.system("You are a product recommendation engine.")
.user(u -> u
.text("Based on order history: {history}, suggest products.")
.param("history", history.toString()))
.stream()
.content();
}
public record OrderAnalysis(
String riskLevel,
String summary,
List<String> recommendations
) {
public static OrderAnalysis fallback(String reason) {
return new OrderAnalysis("UNKNOWN", reason, List.of());
}
}
}AiServiceTemplate.javatemplates
package com.example.ai.service;
import lombok.extern.slf4j.Slf4j;
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;
import reactor.core.publisher.Flux;
import java.util.List;
@Slf4j
@Service
public class AiServiceTemplate {
// One-shot analysis: a stateless client built from the auto-configured (prototype)
// ChatClient.Builder. The shared ChatClient bean carries MessageChatMemoryAdvisor,
// which needs a per-user conversation id — without one, Spring AI 2 rejects the
// call and 1.x silently pools every user into one shared chat history.
private final ChatClient chatClient;
public AiServiceTemplate(ChatClient.Builder builder) {
this.chatClient = builder.build();
}
@Value("classpath:prompts/analyze-order.st")
private Resource analyzePrompt;
/**
* Simple prompt with structured output — auto-parsed to Java record.
*/
public OrderAnalysis analyzeOrder(String customerEmail, String items, String total) {
try {
return chatClient.prompt()
.user(u -> u
.text(analyzePrompt)
.param("customerEmail", customerEmail)
.param("items", items)
.param("total", total))
.call()
.entity(OrderAnalysis.class);
} catch (Exception e) {
log.error("AI analysis failed", e);
return OrderAnalysis.fallback("Service unavailable");
}
}
/**
* Streaming response for long-form content.
*/
public Flux<String> streamAnalysis(String context) {
return chatClient.prompt()
.system("You are a business analyst specializing in e-commerce orders.")
.user(context)
.stream()
.content();
}
/**
* Structured list output — Spring AI parses JSON array into List.
*/
public List<ProductRecommendation> getRecommendations(String orderHistory) {
try {
return chatClient.prompt()
.system("Recommend products based on order history. Return as JSON array.")
.user(orderHistory)
.call()
.entity(new org.springframework.core.ParameterizedTypeReference<>() {});
} catch (Exception e) {
log.error("Recommendation generation failed", e);
return List.of();
}
}
public record OrderAnalysis(String riskLevel, String summary, List<String> recommendations) {
public static OrderAnalysis fallback(String reason) {
return new OrderAnalysis("UNKNOWN", reason, List.of());
}
}
public record ProductRecommendation(String productName, String reason, double confidence) {}
}analyze-order.sttemplates
You are an e-commerce order analyst. Analyze the following order for risk and provide recommendations.
Customer: {customerEmail}
Items: {items}
Total: {total}
Respond with a JSON object containing:
- riskLevel: one of LOW, MEDIUM, HIGH
- summary: a one-sentence analysis of the order
- recommendations: an array of actionable suggestions (max 3)
Focus on:
1. Unusual order patterns (high value, bulk quantities)
2. Customer behavior signals
3. Inventory or fulfillment considerationsVerification scope
- Compiled sources
- No
- Runtime checks
- No provider or conversation tests
Coverage describes checked-in fixtures, not a guarantee for every snippet or project.
Coverage matrix & agent evidenceADD TO YOUR AGENTInstall Boot 4 skills
Install Boot 4 skills
claude plugin marketplace add rrezartprebreza/spring-boot-skills
claude plugin install spring-boot-4-skills@spring-boot-skillscodex plugin marketplace add rrezartprebreza/spring-boot-skills
codex plugin add spring-boot-4-skills@spring-boot-skills