Simple definition#
Spring AI is the Spring project for building AI applications in Java. It gives you portable APIs for chat, embeddings, images, audio and vector stores across many providers, plus higher-level building blocks — a fluent ChatClient, advisors for RAG and memory, tool calling, MCP, structured output and observability — all configured the Spring Boot way.
It plays the role in Java that LangChain or LlamaIndex play in Python, with Spring idioms: auto-configuration, dependency injection, Micrometer observability and starters.
Why architects use it#
- Provider portability — switch between Anthropic, OpenAI, Google, Amazon Bedrock, Azure OpenAI, Mistral, Ollama and more mostly through configuration.
- Fits existing Java estates — security, transactions, data access, messaging and observability you already run.
- Enterprise patterns built in — RAG advisors, chat memory repositories, MCP client and server starters, evaluation helpers.
Core abstractions#
flowchart TB
APP["Your service / controller"] --> CC["ChatClient<br/>fluent API"]
CC --> ADV["Advisor chain<br/>memory, RAG, logging, safeguards,<br/>tool calling, custom"]
ADV --> CM["ChatModel<br/>portable interface"]
CM --> P1["AnthropicChatModel"]
CM --> P2["OpenAiChatModel"]
CM --> P3["Bedrock / Google GenAI /<br/>Ollama / Mistral ..."]
CC -.-> TOOLS["Tools<br/>@Tool methods, MCP tool callbacks"]
ADV -.-> VS["VectorStore<br/>pgvector, OpenSearch, Redis ..."]
VS -.-> EM["EmbeddingModel"]
ADV -.-> MEM["ChatMemory<br/>JDBC, Redis, Cassandra ..."]
| Abstraction | Purpose |
|---|---|
ChatModel / StreamingChatModel |
Low-level portable interface to a chat LLM |
ChatClient |
High-level fluent API: prompts, options, advisors, tools, structured output |
Prompt, Message, PromptTemplate |
Messages with roles; templates with variables |
ChatOptions |
Portable options (model, temperature, max tokens) or provider-specific options |
EmbeddingModel |
Text → vectors |
VectorStore |
Store and search embeddings with metadata filters |
Advisor |
Interceptors around the model call (like servlet filters or AOP) |
ToolCallback / @Tool |
Functions the model can call |
ChatMemory |
Conversation history management |
Getting started#
Add the BOM and a model starter (Maven):
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>2.0.x</version> <!-- use the latest 2.0 release -->
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-anthropic</artifactId>
</dependency>
spring.ai.anthropic.api-key=${ANTHROPIC_API_KEY}
spring.ai.anthropic.chat.model=claude-sonnet-4-5
Swap spring-ai-starter-model-anthropic for -openai, -bedrock-converse, -google-genai, -ollama and so on to change providers.
ChatClient: the fluent API#
@RestController
class SupportController {
private final ChatClient chatClient;
SupportController(ChatClient.Builder builder) {
this.chatClient = builder
.defaultSystem("""
You are a concise support assistant for ACME Retail.
Answer in at most 120 words. If unsure, say you don't know.
""")
.build();
}
@GetMapping("/ask")
String ask(@RequestParam String question) {
return chatClient.prompt()
.user(question)
.call()
.content();
}
}
prompt()starts a request;.system(),.user(),.messages()add content..call()is synchronous;.stream()returns a reactiveFlux..content()returns text;.chatResponse()returns metadata (token usage, finish reason);.entity(...)returns a Java object.
Prompt templates#
String answer = chatClient.prompt()
.user(u -> u
.text("Summarise the following incident for {audience} in 3 bullet points:\n{incident}")
.param("audience", "executives")
.param("incident", incidentText))
.call()
.content();
Templates use the StringTemplate engine by default. Keep templates in files (for example classpath:/prompts/summarise.st) so they are versioned and reviewed.
Streaming#
@GetMapping(value = "/ask/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> stream(@RequestParam String question) {
return chatClient.prompt().user(question).stream().content();
}
Options per request#
chatClient.prompt()
.user(question)
.options(ChatOptions.builder().temperature(0.1).maxTokens(400).build())
.call()
.content();
Structured output#
Map model output straight into Java types. Spring AI generates a JSON Schema from the type, adds format instructions (or uses the provider’s native structured output), and parses the response.
record InvoiceData(String supplier, LocalDate invoiceDate, String currency,
BigDecimal total, List<LineItem> lines) {}
record LineItem(String description, int quantity, BigDecimal amount) {}
InvoiceData invoice = chatClient.prompt()
.system("Extract invoice data. Use ISO dates and 3-letter currency codes.")
.user(invoiceText)
.call()
.entity(InvoiceData.class);
For generic types use .entity(new ParameterizedTypeReference<List<LineItem>>() {}). Always validate business rules after parsing (totals add up, dates plausible); see structured output. Spring AI 2.0 also includes a StructuredOutputValidationAdvisor that can validate against the schema and retry.
Advisors: the interception chain#
Advisors wrap every call, like servlet filters. They can modify the request (add memory, retrieved documents, safety rules), the response, or both.
sequenceDiagram
participant App
participant M as MessageChatMemoryAdvisor
participant Q as QuestionAnswerAdvisor (RAG)
participant L as SimpleLoggerAdvisor
participant CM as ChatModel
App->>M: request
M->>M: add conversation history
M->>Q: request
Q->>Q: vector search, add documents to prompt
Q->>L: request
L->>CM: log + call model
CM-->>L: response
L-->>Q: log response
Q-->>M: response (+ retrieved docs in context)
M->>M: save user + assistant messages
M-->>App: response
Built-in advisors include:
| Advisor | Purpose |
|---|---|
MessageChatMemoryAdvisor |
Adds and saves conversation history (memory) |
VectorStoreChatMemoryAdvisor |
Retrieves relevant past messages from a vector store |
QuestionAnswerAdvisor |
Simple RAG over a VectorStore (RAG) |
RetrievalAugmentationAdvisor |
Modular RAG: query transformers, retrievers, augmenters |
ToolCallingAdvisor |
Runs the tool-calling loop inside the advisor chain so other advisors can observe each iteration |
SafeGuardAdvisor |
Blocks requests containing sensitive words |
SimpleLoggerAdvisor |
Logs requests and responses (debugging) |
StructuredOutputValidationAdvisor |
Validates structured output and retries |
Advisor order is controlled by getOrder(); lower values run first on the way in. You can write your own (for example PII masking, tenant tagging, cost accounting) by implementing CallAdvisor and StreamAdvisor.
Using several models#
@Configuration
class ChatClients {
@Bean ChatClient fastClient(AnthropicChatModel model) { // small model: routing, classification
return ChatClient.builder(model)
.defaultOptions(ChatOptions.builder().model("claude-haiku-4-5").build())
.build();
}
@Bean ChatClient smartClient(AnthropicChatModel model) { // stronger model: complex answers
return ChatClient.builder(model)
.defaultOptions(ChatOptions.builder().model("claude-sonnet-4-5").build())
.build();
}
}
This is the basis for routing and cascades inside a Java service. For company-wide routing and quotas, point the model’s base URL at your AI gateway.
How Spring AI maps to the enterprise stack#
| Stack layer | Spring AI feature |
|---|---|
| Models | Model starters for major providers, local models via Ollama |
| Gateway | Base URL / OpenAI-compatible client pointing at the gateway |
| Knowledge | ETL pipeline (DocumentReader, TextSplitter, VectorStore) |
| Orchestration | ChatClient, advisors, tools, MCP client and server |
| Memory | ChatMemory + JDBC/Redis/Cassandra/Mongo/Neo4j repositories |
| LLMOps | Micrometer observations, OpenTelemetry tracing, evaluators |
Common mistakes#
Review questions#
What is Spring AI and why use it? A Spring project that provides portable abstractions over AI models and vector stores plus higher-level features — ChatClient, advisors, RAG, tools, MCP, memory, structured output and observability — with Spring Boot auto-configuration. It lets Java teams build AI features in their existing stack and switch providers with little code change.
What is the difference between ChatModel and ChatClient?
ChatModel is the low-level portable interface to a provider’s chat API. ChatClient is the high-level fluent API on top, adding prompt templates, default options, advisors, tool calling and structured output.
What are advisors in Spring AI? Interceptors in a chain around each model call that can modify requests and responses — used for chat memory, RAG, logging, safeguards, tool-calling loops and custom cross-cutting concerns such as PII masking.
How do you get structured output in Spring AI?
Call .entity(MyRecord.class) (or with a ParameterizedTypeReference). Spring AI derives a JSON Schema from the type, instructs the model or uses native structured output, and converts the response. Validate business rules afterwards.
Summary#
- Spring AI gives Java teams portable model APIs and enterprise building blocks.
ChatClientis the main API: prompts, templates, options, streaming,.entity()for structured output.- Advisors form an interception chain for memory, RAG, tools, logging and custom concerns.
- Configure several
ChatClients for routing; point at an AI gateway for central control.