|
This version is still in development and is not considered stable yet. For the latest stable version, please use Spring AI 2.1.0! |
AI Concepts
This page explains the ideas that Spring AI is built on. Each section describes one concept in general terms, then names the part of Spring AI that implements it. You don’t need a background in machine learning to follow it.
Models
An AI model is a program that has learned patterns from a large amount of data, and uses them to produce an output for a new input. The models that Spring AI works with are pre-trained: a provider has already trained them, and you use them through an API, without training anything yourself.
Models differ in what they take in and what they return:
Chat models, also called large language models (LLMs), are the most versatile, and most of Spring AI is built around them. The other types do one job each, and are often faster and cheaper for that job.
In Spring AI: each model type has a portable API, such as ChatModel or EmbeddingModel, implemented for many providers.
See Model APIs and Model Providers.
Messages and Roles
A chat model does not receive a single string. It receives a list of messages, and each message has a role:
-
The system message tells the model how to behave, for example which tone to use or which rules to follow.
-
User messages hold what the user asks.
-
Assistant messages hold earlier answers of the model, so that it can continue a conversation.
-
Tool messages hold the results of tool calls that the model asked for.
A message can hold more than text. A user message can contain images, audio or documents for a multimodal model. An assistant message can contain reasoning, which some models produce before they answer, and requests to call tools. Spring AI keeps these as an ordered list of parts in each message.
In Spring AI: SystemMessage, UserMessage, AssistantMessage and ToolResponseMessage, and their message parts.
Prompts and Prompt Templates
The prompt is everything that is sent to the model in one request: the messages and the options, such as the model name or the temperature.
The wording of a prompt has a large effect on the answer. Writing prompts that work well is called prompt engineering, and the techniques change as models improve. A well-known example is that adding "Let’s think step by step" to a question made models better at reasoning tasks (Kojima et al., 2022).
Most prompts have a fixed part and a part that changes with each request. A prompt template holds the fixed part, with placeholders for the rest:
Tell me a {adjective} joke about {topic}.
A template is like a view in Spring MVC: a map of values fills the placeholders, and the result is the text that is sent to the model.
In Spring AI: PromptTemplate, rendered by a TemplateRenderer, which is based on StringTemplate by default.
See Prompts and Templates and Prompt Engineering Patterns.
Tokens and the Context Window
Models do not read words, but tokens: pieces of words. In English, a token is about three quarters of a word on average, so 100 words are roughly 130 tokens.
Tokens matter for two reasons:
-
Cost. Hosted models charge by the number of tokens, for both the input and the output.
-
The context window. A model can only take a limited number of tokens in one request. The limit depends on the model, and ranges from a few thousand to a million tokens or more.
A long conversation, a large document or many tools can fill the context window. An application then has to choose what to send: the relevant parts of a document, the recent part of a conversation, or the tools that a task needs.
In Spring AI: the token usage of each call is in the response metadata and in the metrics. Compaction keeps a conversation within the context window, retrieval selects the relevant parts of your documents, and tool search selects the relevant tools.
Streaming
A chat model produces its answer token by token, and a long answer can take many seconds. Instead of waiting for the whole answer, an application can stream it: it receives the answer in small pieces as they are produced, and can show them to the user at once.
In Spring AI: ChatClient has a stream() method next to call(), which returns a reactive Flux.
Chat, text-to-speech and transcription models can stream.
See Responses and Streaming.
Embeddings
An embedding is a list of numbers, a vector, that represents the meaning of a piece of text or an image. An embedding model computes it.
Texts with a similar meaning get vectors that are close to each other. By measuring the distance between two vectors, an application can find out how similar two texts are, even when they use different words. This is the basis of semantic search, of recommendations, and of retrieval augmented generation.
You don’t need to know how the numbers are computed to use embeddings. It is enough to know that closeness of vectors means similarity of meaning.
In Spring AI: the EmbeddingModel computes embeddings, and a VectorStore stores them and finds the ones closest to a query.
Structured Output
A chat model answers with text. An application often needs data instead: a Java object, a list or a map.
There are two ways to get data from a model:
-
Format instructions. The application adds a description of the expected format, such as a JSON schema, to the prompt, and converts the text of the answer. This works with any model, but the model can still answer in another format.
-
Native structured output. Many providers can constrain the answer to a JSON schema themselves.
In both cases, the application can validate the answer against the schema, and ask the model to correct an invalid answer.
In Spring AI: ChatClient returns Java types with .entity(…).
See Structured Output, Provider-Native Structured Output and Schema Validation and Self-Correction.
Bringing Your Data and APIs to the Model
A model only knows what was in its training data. Its knowledge ends at a cutoff date, and it has never seen data that is not public, such as the documents and databases of your company. It also cannot act on its own: it cannot look something up or change anything.
There are three ways to change this:
-
Fine-tuning trains the model further on your data. It needs machine learning expertise and a lot of computing power, and many models do not offer it.
-
Adding context to the prompt gives the model the information that a request needs, together with the request. This is the most common approach, and retrieval augmented generation is its main technique.
-
Tool calling lets the model ask your application to run code, to fetch information or to take an action.
Retrieval Augmented Generation
Retrieval augmented generation (RAG) adds the parts of your documents that are relevant to a question to the prompt. It has two phases:
-
Ingestion, done ahead of time. Read the documents, split them into chunks, compute the embedding of each chunk, and store the chunks in a vector store. A chunk should keep related content together, such as a whole paragraph or a whole table, and be small compared with the context window.
-
Retrieval, done for each question. Find the chunks whose embeddings are closest to the question, add them to the prompt, and let the model answer from them.
In Spring AI: the ETL pipeline does the ingestion, and the QuestionAnswerAdvisor and RetrievalAugmentationAdvisor do the retrieval.
See Retrieval Augmented Generation and the Chat with Your Documents tutorial.
Tool Calling
Tool calling lets a model use your code. The application describes its tools to the model: a name, a description and the schema of the parameters of each tool. When the model needs a tool, it does not answer, but asks for the tool to be called, with the arguments it chose. The application runs the tool and sends the result back, and the model continues, until it can give a final answer.
The model never runs code itself. It only asks, and your application decides what runs.
In Spring AI: a tool is a method annotated with @Tool, passed to ChatClient with .tools(…).
The ToolCallingAdvisor runs the loop of calls for you.
See Tool Calling and the Give the Model Tools tutorial.
The Model Context Protocol
The Model Context Protocol (MCP) is an open standard for offering tools, resources and prompts to AI applications. A program that offers them is an MCP server, and an AI application uses them through an MCP client. With MCP, a tool is written once and can be used by any application that speaks the protocol.
In Spring AI: MCP clients make the tools of MCP servers available as Spring AI tools, and MCP servers expose your own tools, resources and prompts. See Model Context Protocol, and its diagram of clients and servers in a Spring AI application.
Advisors
Many applications need the same steps around a model call: add the conversation history, add retrieved documents, run tools, log the request, or check the answer. An advisor is a component that runs before and after a model call, and can change the request and the response. Advisors are chained, much like servlet filters, so that each one adds a single concern.
In Spring AI: memory, RAG, tool calling and guardrails are all implemented as advisors, and you can write your own. See Advisors.
Memory and Sessions
A model is stateless: it does not remember earlier requests. To hold a conversation, the application stores what was said, and sends the relevant part of it with every new request.
A session holds one conversation, as a log of the messages and events that happened in it. When the conversation grows too long for the context window, the application compacts it, for example by keeping only the recent turns or by summarizing older ones.
In Spring AI: session memory stores conversations, compacts them, and lets the model search them. See Memory and the A Conversational App with Sessions tutorial.
Agents
An agent is an application in which the model decides what to do next. It calls a tool, reads the result, and decides on the next step, in a loop that ends when the task is done. Because the model takes actions, an agent often asks a person to approve the ones that matter. Everything around the model that makes this work, from the loop and the tools to memory and checks, is the agent’s harness: Agent = Model + Harness.
A workflow is the opposite approach: the application decides the steps, and calls the model at fixed points. Many applications combine the two.
In Spring AI: agents are built from the blocks on this page.
For an agent built on a ChatClient, the backbone of its harness is the client’s advisor chain.
See The Agent Harness, Workflow Pattern Examples and Tool Call Confirmation.
Evaluating and Guarding Output
A model’s answers are not deterministic, and they can be wrong. Two practices help:
-
Evaluation checks the quality of answers, usually in tests. A common technique is to ask another model whether an answer is relevant to the question, or supported by the retrieved documents.
-
Guardrails check input and output while the application runs, and stop what should not pass, such as a prompt injection or harmful content. A moderation or decision model can do this check faster and more cheaply than a chat model.
In Spring AI: the Evaluator API, with the RelevancyEvaluator and the FactCheckingEvaluator, see Evaluation and Testing.
For guardrails, see Guardrails.
Observability
An AI application is harder to understand than most applications: answers vary, calls are slow and cost money, and an agent can take many steps. Observability makes this visible, with metrics such as the duration and the token usage of each call, and traces that follow a request through the model, the advisors, the tools and the vector store.
In Spring AI: metrics and traces through Micrometer, for ChatClient, the advisors, the models, the tools and the vector stores.
See Observability.