Skip to main content

Spring AI EmbeddingModel

Banner Spring AI Icon

πŸš€ Spring AI Vector Embeddings – A Fun & Engaging Guide​

Welcome to the Spring AI Vector Embedding tutorial! πŸŽ‰ Here, we'll unravel the mysteries of vectors, embeddings, and how they supercharge semantic searches. Plus, we’ll generate embeddings using popular LLM models like OpenAI and DeepseekAI using Ollama! πŸ€–βœ¨


πŸ€” 1. What is a Vector Embedding?​

Imagine you're in a room full of people speaking different languages. How do you find someone who understands you? Vector embeddings work like a universal translatorβ€”turning words, sentences, and even images into arrays of numbers that capture meaning! πŸ”’πŸ’‘

In AI terms, a vector (or embedding) is a magical array of numbers that represents an object, be it a word, sentence, image, audio snippet, or even a product description. πŸ“¦

Each number in the vector is a component, corresponding to a dimension in hyperspace (yes, like sci-fi πŸš€). More dimensions mean more details about the object!

🌟 Example Time​

Let’s take the word β€œhappiness” and give it some numbers:

[2.5, 1.3, 0.8]
  • 2.5 β†’ Emotional positivity (yay! πŸŽ‰)
  • 1.3 β†’ Emotional intensity (oh wow! πŸ˜ƒ)
  • 0.8 β†’ Context usage (poetry or science? πŸ€”)

Now, here’s the kicker: these numbers don’t mean much alone, but together, they create a powerful representation! 🧠✨


πŸ” 2. Semantic Search: Finding Meaning, Not Just Words​

Ever wondered how Google knows exactly what you're looking for, even when you type weird search queries? That’s semantic search in action! πŸ•΅οΈβ€β™‚οΈπŸ’‘

Instead of matching exact words, semantic search looks at meaning. It uses vector distancesβ€”small distances = high similarity, big distances = low similarity. πŸ”¬

πŸš€ Real-world applications:

  • Google Search 🧐 – Finds the perfect answer, even if your query is gibberish.
  • Netflix & Spotify 🎢 – Suggests movies & songs you actually like.
  • Chatbots & AI Assistants πŸ€– – Understands you better than your best friend!

πŸ— 3. Meet the EmbeddingModel Interface​

Spring AI makes embedding easy with the EmbeddingModel interface! 🎯

Think of it as your personal AI librarian, transforming text into numerical vectors! πŸ“šπŸ”’

public interface EmbeddingModel extends Model<EmbeddingRequest, EmbeddingResponse> {
List<Double> embed(String text);
List<Double> embed(Document document);
EmbeddingResponse embedForResponse(List<String> texts);
EmbeddingResponse call(EmbeddingRequest request);
}

spring-ai-embedding-model

πŸ’‘ The embedForResponse() method gives extra metadata, just in case you want more than just numbers!

⚑ Usage Example​

String text = "...";
List<Double> embeddings = embeddingModel.embed(text);

Or, for more control:

List<Double> embeddings = embeddingModel.call(
new EmbeddingRequest(List.of(text), OpenAiEmbeddingOptions.builder()
.withModel("text-embedding-3-small")
.withUser("jon.snow") // Because he knows nothing, right? πŸ˜†
.build()))
.getResult().getOutput();

πŸš€ 4. EmbeddingModel Implementations​

Spring AI supports tons of embedding models! πŸ† Each has its own implementation class.

ProviderImplementation ClassSupported Models
OpenAIOpenAiEmbeddingModeltext-embedding-ada-002, text-embedding-3-large, text-embedding-3-small
Azure OpenAIAzureOpenAiEmbeddingModeltext-embedding-ada-002
OllamaOllamaEmbeddingModelmistral
PostgresMLPostgresMlEmbeddingModeldistilbert-base-uncased
Mistral AIMistralAiEmbeddingModelmistral-embed
MiniMaxMiniMaxEmbeddingModelembo-01
QianFanQianFanEmbeddingModelbge_large_zh
Amazon BedrockBedrockTitanEmbeddingModelamazon.titan-embed-image-v1

πŸ“œ For the full list, check the official docs!


🎬 5. Let’s Get Our Hands Dirty: DeepseekAI Demo​

We’ll use Ollama’s mxbai-embed-large and nomic-embed-text model to generate vector embeddings. πŸ› βœ¨

πŸ›  5.1. Maven Setup​

First, add the Spring Boot starter dependency:

<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
</dependency>
</dependencies>

πŸ”‘ Don’t forget to add your application properties!

server.port=8084
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.options.model=deepseek-r1:latest
spring.ai.ollama.chat.options.temperature=0.7
spring.ai.ollama.init.pull-model-strategy=always
spring.ai.ollama.init.pull-model-strategy.embedding.additional-models=mxbai-embed-large

πŸŽ› 5.2. DeepseekAiEmbeddingModel Bean​

Spring Boot auto-configures an DeepseekAiEmbeddingModel bean. Just inject it into your class:

@RestController
public class DeepseekAiEmbeddingController {

private final EmbeddingModel embeddingModel;

@Autowired
public DeepseekAiEmbeddingController(EmbeddingModel embeddingModel) {
this.embeddingModel = embeddingModel;
}

@GetMapping("/ai/embedding")
public Map embed(@RequestParam(value = "message", defaultValue = "tell me a joke") String message) {
EmbeddingResponse embeddingResponse = embeddingModel.embedForResponse(List.of(message));
return Map.of("embedding", embeddingResponse);
}

}

πŸ›  Test it with a REST tool! πŸš€

spring-ai-embedding-result


🎯 6. Wrapping It Up​

πŸŽ‰ Here’s what we covered:

βœ… Vectors (embeddings) represent objects in numerical form. βœ… Semantic search finds meaning instead of just words. βœ… The EmbeddingModel interface is your AI magic wand! πŸͺ„ βœ… Spring AI supports multiple embedding models. βœ… We saw a live demo using Deepseek AI with Ollama!

πŸ’‘ What’s next? Start building cool AI-powered apps! πŸš€πŸ’‘

πŸ‘‰ Happy Learning & Happy Coding! 🦾πŸ”₯