DEV Community

Said Olano
Said Olano

Posted on

Spring AI's Model Layer: One API, Any Provider, Zero Rewrites

Spring AI's Model Layer: One API, Any Provider, Zero Rewrites

If you have built an AI feature in Java, you have probably felt the same pain I did. You write the integration against one provider's SDK, the product works, and then a business decision, a price change, or a compliance requirement forces you to move to another model. Suddenly the code you thought was "done" is full of provider-specific request objects, response parsers, and retry rules.

Spring AI tackles this problem directly. Its model layer gives you a single, portable API for the kinds of models most applications use: chat, embeddings, images, audio, moderation, and decision models. Underneath, it connects to many providers, including OpenAI, Anthropic, Google GenAI, Google Vertex AI, Amazon Bedrock, Mistral AI, Ollama, DeepSeek, and any OpenAI-compatible endpoint.

The practical promise is simple: you change configuration, not your application code. In this article I will explain how the model layer is organized, show how it fits with ChatClient, and walk through a small Spring Boot service that can switch providers without a single line of business logic changing.

The big picture

It helps to see Spring AI as a set of layers, each with a clear responsibility:

  • Models abstract the provider. You depend on a model interface such as ChatModel or EmbeddingModel, not on a vendor SDK.
  • ChatClient is the friendly, fluent entry point for talking to a chat model. It supports prompts, structured output, tool calling, and advisors that wrap each call.
  • Data and retrieval provide vector stores, document readers, and RAG building blocks, using one portable API across many vector databases.
  • Agents and protocols sit on top, for workflows that need planning, tools, and communication between agents.

This article focuses on the bottom layer, the model layer, because it is the foundation everything else depends on.

Six model APIs, one vocabulary

The model layer does not treat "AI" as a single thing. It defines one API per kind of model:

Model API What it does Typical use
Chat Text in, text out Assistants, summarization, extraction
Embedding Text in, numeric vector out Semantic search, RAG, clustering
Image Text in, image out Generating visuals, thumbnails
Audio Speech and audio processing Transcription, text to speech
Moderation Classify content for policy violations Filtering user input and output
Decision Choose among options with a model Routing and classification decisions

Each API has a consistent set of concepts: a model interface, options (such as the model name or temperature), and a response type. Once you learn one, the others feel familiar.

Why provider portability matters

Provider portability is more than a nice abstraction. It gives you concrete advantages:

  1. Cost control. You can route simple tasks to a cheaper model and reserve a premium model for hard ones.
  2. Resilience. If one provider has an outage or rate limits you, you can switch to another without a code release.
  3. Privacy and locality. You can run a local model with Ollama during development or for sensitive data, and use a hosted model in production.
  4. Evaluation. You can compare providers on the same prompts and pick the one that fits your quality bar.
  5. Negotiation and lock-in. Your architecture does not depend on one vendor's roadmap.

None of these advantages exists if your business code calls a vendor SDK directly. The abstraction is what makes them cheap to exercise.

Setting up the project

Start with a Spring Boot project and add the Spring AI starter for the provider you want to use first. Spring AI publishes a bill of materials (BOM), so you should manage the version through the BOM rather than hard-coding it on each dependency. The exact coordinates depend on the Spring AI version you target, so check the official reference documentation for the current setup.

With Maven, the shape looks like this:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>${spring-ai.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Notice that the starter is provider-specific, but the code you write against it is not. That distinction is the heart of the design.

Configuration decides the provider

Provider settings live in application.yml. Credentials come from environment variables, never from source code:

spring:
  ai:
    openai:
      api-key: ${OPENAI_API_KEY}
      chat:
        options:
          model: gpt-4o-mini
          temperature: 0.2
Enter fullscreen mode Exit fullscreen mode

Switching to Anthropic is a configuration change, not a code change:

spring:
  ai:
    anthropic:
      api-key: ${ANTHROPIC_API_KEY}
      chat:
        options:
          model: claude-sonnet-4-5
          temperature: 0.2
Enter fullscreen mode Exit fullscreen mode

Model names change over time, so treat the values above as examples and check the current model list in each provider's documentation before you deploy.

For local development, you can use Ollama and keep everything on your machine:

spring:
  ai:
    ollama:
      base-url: http://localhost:11434
      chat:
        options:
          model: llama3.1
Enter fullscreen mode Exit fullscreen mode

Spring profiles make this even cleaner. Keep application-local.yml pointing at Ollama, application-prod.yml pointing at a hosted provider, and select the profile at startup with SPRING_PROFILES_ACTIVE.

A provider-agnostic service

Now the important part: the service code. Spring Boot auto-configures a ChatClient.Builder when a chat model is on the classpath. Your service depends only on that builder:

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;

@Service
public class SupportAssistant {

    private final ChatClient chatClient;

    public SupportAssistant(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    public String answer(String customerQuestion) {
        return chatClient.prompt()
                .system("""
                        You are a concise support assistant for a digital bank.
                        Answer in the same language as the customer.
                        If you are not sure, say so and suggest contacting support.
                        """)
                .user(customerQuestion)
                .call()
                .content();
    }
}
Enter fullscreen mode Exit fullscreen mode

This class does not mention OpenAI, Anthropic, or Ollama. Whichever provider is active at startup, the same code runs. That is the portability promise in practice.

Structured output: from text to Java objects

Free text is hard to use in a backend. Often you want a typed object. Spring AI can ask the model for JSON that maps to a Java record and convert the result for you:

import java.util.List;

public record TicketSummary(String category, String priority, List<String> keyPoints) {}
Enter fullscreen mode Exit fullscreen mode
public TicketSummary summarize(String ticketText) {
    return chatClient.prompt()
            .system("Classify the support ticket and extract the key points.")
            .user(ticketText)
            .call()
            .entity(TicketSummary.class);
}
Enter fullscreen mode Exit fullscreen mode

Structured output reduces brittle string parsing, which is one of the most common sources of production bugs in LLM integrations. It does not remove the need for validation. Treat the model's output as untrusted input: check ranges, enum values, and required fields before you act on it.

Embeddings: the other half of retrieval

Chat gets the attention, but embeddings are what make retrieval work. An EmbeddingModel turns text into a vector, and you store those vectors in a vector store. Here is a minimal example that embeds two texts and compares them with cosine similarity:

import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.stereotype.Service;

@Service
public class SimilarityService {

    private final EmbeddingModel embeddingModel;

    public SimilarityService(EmbeddingModel embeddingModel) {
        this.embeddingModel = embeddingModel;
    }

    public double similarity(String first, String second) {
        float[] a = embeddingModel.embed(first);
        float[] b = embeddingModel.embed(second);
        return cosine(a, b);
    }

    private double cosine(float[] a, float[] b) {
        double dot = 0, normA = 0, normB = 0;
        for (int i = 0; i < a.length; i++) {
            dot += a[i] * b[i];
            normA += a[i] * a[i];
            normB += b[i] * b[i];
        }
        return dot / (Math.sqrt(normA) * Math.sqrt(normB));
    }
}
Enter fullscreen mode Exit fullscreen mode

In a real system you would not compare two texts on every request. You would embed your documents once, store them in a vector store such as PGVector, Redis, Elasticsearch, or Qdrant, and query by similarity. The point here is that the embedding code is the same regardless of which provider generates the vectors.

One caution: vectors from different embedding models are not compatible. If you switch the embedding provider, you must re-embed your corpus. Keep the embedding model choice as a deliberate decision, not a casual configuration tweak.

Testing without calling a real provider

Tests that call a live model are slow, expensive, and non-deterministic. Because your code depends on abstractions, you can test it with a fake. For example, a unit test can stub the model response and assert how your service builds the prompt and handles the answer. Keep a small number of integration tests that use a real or local model, and run them separately from your fast build.

This is also where the portability pays off in your test strategy: you can run the same integration suite against Ollama in CI and against a hosted provider in a nightly job.

Production concerns you should not skip

Switching providers is easy. Running them reliably is not. A few practices make a real difference:

  • Set timeouts and retries. Model calls can be slow. Define explicit timeouts and a bounded retry policy, and avoid retrying on errors that will not succeed on a second attempt.
  • Log carefully. Prompts and responses may contain personal data. Redact sensitive content and make logging levels configurable.
  • Track cost and latency per provider. Observability is part of the design. Spring AI exposes metrics and traces for the client, models, and vector stores, so connect them to your monitoring stack.
  • Control the prompt. Keep system prompts in version control and review them like code. A small wording change can alter behavior significantly.
  • Plan for model changes. Providers deprecate models. Pin the model name in configuration, and have a process for testing a replacement before you switch.
  • Guard the output. Use validation and, where needed, moderation models before you show or act on a response.

Common pitfalls

A few mistakes I see often:

  1. Leaking provider types into business code. If you import a vendor class into a service, you have lost portability. Keep provider-specific code in configuration.
  2. Assuming identical behavior. Providers differ in how they handle system prompts, token limits, and structured output. Test each provider you support.
  3. Mixing embedding models. Changing the embedding model silently breaks retrieval quality until you re-index.
  4. Hard-coding credentials. Use environment variables or a secrets manager.
  5. Skipping evaluation. Without a set of representative prompts and expected outcomes, you cannot tell whether a provider switch made things better or worse.

Where to go next

The model layer is the foundation, not the whole building. Once you are comfortable with it, the next steps are:

  • Add a vector store and build a small RAG pipeline with a document reader and a retrieval step.
  • Use advisors to add memory, logging, or safety checks around each call.
  • Introduce tool calling so the model can invoke your Java services.
  • Explore agent patterns such as chaining, routing, and orchestrator-workers when a single call is not enough.

Conclusion

Spring AI's model layer solves a problem that every Java team building AI features will eventually face: how to avoid being locked into one provider. By separating model APIs from provider implementations, and by letting configuration choose the provider, it gives you a clean path to switch models, control costs, run locally, and evaluate options without rewriting your business logic.

If you are starting an AI feature in a Spring Boot application, begin with the model abstraction, keep provider details in configuration, and invest early in tests and observability. Your future self, the one who needs to change providers on a Friday afternoon, will be grateful.

Have you already built an AI feature in Java? I would like to hear which provider you started with and what made you consider switching.

Top comments (0)