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:

The model types of Spring AI, with their input and output Chat models take text, plus images, audio or documents and return text, reasoning, tool calls. Embedding models take text, or images and return a vector of numbers. Image models take text and return images. Text to speech models take text and return audio. Transcription models take audio and return text. Moderation models take text and return flagged categories, with scores. Decision models take a question, its outcomes, an input and return the chosen outcome, with likelihoods. Input Model type Output Text, plus images, audio or documents Chat Text, reasoning, tool calls Text, or images Embedding A vector of numbers Text Image Images Text Text to speech Audio Audio Transcription Text Text Moderation Flagged categories, with scores A question, its outcomes, an input Decision The chosen outcome, with likelihoods

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.

A sentence split into tokens The sentence 'Spring AI turns your prompt into tokens.' has 7 words and is split into 9 tokens: Spring, AI, turns, your, prompt, into, tok, ens and the full stop. Each model uses its own tokenizer. Spring AI turns your prompt into tokens. Spring ␣AI ␣turns ␣your ␣prompt ␣into ␣tok ens . 7 words, 9 tokens Illustrative: each model splits text with its own tokenizer, and ␣ marks a space that belongs to a token.

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.

Texts, their embeddings, and their distance in the vector space An embedding model turns each text into a vector of numbers. 'A cat sits on the mat' and 'A kitten naps on a rug' get vectors that are close together in the vector space, because their meaning is similar. 'Stock prices fell today' is far from both. Texts Vectors Vector space Embedding model A cat sits on the mat [0.21, -0.43, 0.88, …] A kitten naps on a rug [0.19, -0.40, 0.85, …] Stock prices fell today [-0.72, 0.35, 0.05, …] cat kitten stocks close: similar meaning far: different meaning

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.

Structured output with format instructions The converter adds format instructions, such as a JSON schema, to your request. The chat model answers with text in that format, and the converter turns the text into a Java object. With native structured output, the provider constrains the answer to the schema. Structured output converter Add format instructions Convert text to Java type Your requestuser text Request + format instructionse.g. a JSON schema Chat modelanswers with text Text answer{"name": "Ada", "year": 1815} Java objectPerson(Ada, 1815) With native structured output, the provider constrains the answer to the schema instead of relying on the instructions.

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:

  1. 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.

  2. 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.

Retrieval augmented generation: ingestion and retrieval Ahead of time, documents are read, split into chunks, embedded and stored in a vector store. For each question, the chunks closest to the question are retrieved from the vector store and added to the prompt, and the chat model answers from them. Ingestion: ahead of time Retrieval: for each question DocumentsPDF, HTML, … ReadDocumentReader Split into chunksTextSplitter EmbedEmbeddingModel Vectorstore Questionfrom the user Searchsimilar chunks Prompt the question + the retrieved chunks + “answer from this context” Chat model Answer chunks closest to the question

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 tool calling loop 1: The application sends a prompt and its tools through Spring AI. 2: Spring AI sends the messages and the tool definitions to the model. 3: The model asks for a tool call with arguments. 4 and 5: Spring AI runs the tool and gets the result. 6: Spring AI sends the result to the model. Steps 3 to 6 repeat while the model asks for tools. 7: The model gives its final answer. 8: Spring AI returns the response to the application. Your application Spring AI Tool AI model 1 prompt + tools chatClient.prompt(…).tools(…) 2 messages + tool definitions name, description, input schema 3 call a tool tool name + arguments 4 run the tool with the arguments 5 result 6 messages + tool result 7 final answer 8 response repeats while the model asks for tools

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.