Integrating LLM Providers with Spring AI – Gemini, Claude and Ollama

Integrating Large Language Model (LLM) providers with Spring AI revolves around a unified programming model that separates application logic from provider-specific SDKs. By relying on Spring Boot auto-configuration, starters, and standardized interfaces like ChatClient and ChatModel, developers can connect to cloud APIs (Google Gemini, Anthropic Claude) or local runtimes (Ollama) and switch between them primarily through configuration changes.

1. Core Integration Architecture

Regardless of whether you connect to Gemini, Claude, or Ollama, Spring AI standardizes the integration pipeline into four stages:
  1. Spring AI BOM (Bill of Materials): Manages compatible versions across all Spring AI modules and vendor starters.

  2. Provider Starter Dependency: Adding a specific starter (e.g., for Google GenAI, Anthropic, or Ollama) triggers Spring Boot auto-configuration to instantiate the underlying HTTP client, authentication handler, and ChatModel bean.

  3. Externalized Configuration (application.properties / application.yml): Stores API keys, base URLs, default model IDs, and inference parameters (temperature, top-p, max tokens).

  4. Unified Execution (ChatClient): The application injects ChatClient.Builder to send prompts, stream responses, map outputs to Java POJOs, or invoke tools without knowing which vendor executes the request behind the scenes.

2. Google Gemini Integration

Spring AI supports Google Gemini through two distinct deployment paths depending on whether you are prototyping or deploying to enterprise cloud infrastructure:

Deployment Modes

  • Google GenAI (Gemini Developer API): Ideal for rapid prototyping and standard API integration using an API key generated from Google AI Studio.

    • Starter Module: spring-ai-starter-model-google-genai

    • Key Configuration Properties: API key (spring.ai.google.genai.api-key), model selection (such as gemini-2.5-flash or gemini-2.5-pro), temperature, top-K, candidate count, and server-side Google Search grounding flags.

  • Vertex AI Gemini: Designed for production workloads running on Google Cloud Platform (GCP), utilizing Google Cloud IAM credentials, project IDs, and regional endpoints.

    • Starter Module: spring-ai-starter-model-vertex-ai-gemini

    • Key Configuration Properties: GCP Project ID, location/region, safety threshold settings (e.g., blocking levels for harmful categories), and model options.

Capabilities Supported

  • Multimodal Inputs: Native handling of text alongside images, audio, video, and PDF documents.

  • Grounding & Search: Built-in support for enabling Google Search retrieval directly through configuration properties.

  • Tool Calling & Structured Output: Supports function calling modes (AUTO, ANY, VALIDATED, NONE) and direct mapping to Java records/classes.

3. Anthropic Claude Integration

Spring AI connects to Anthropic’s Claude family (such as Claude Sonnet, Opus, and Haiku models) via Anthropic’s REST APIs, or through cloud intermediaries like Amazon Bedrock and Google Vertex AI.

Direct Anthropic API Setup

  • Starter Module: spring-ai-starter-model-anthropic (formerly spring-ai-anthropic-spring-boot-starter)

  • Authentication: Configured via an Anthropic Console API key (spring.ai.anthropic.api-key), typically injected via environment variables.

  • Key Configuration Properties:

    • Base URL (defaults to Anthropic’s official API endpoint)

    • Model identifier (e.g., claude-sonnet-4-20250514 or latest Claude 3.x/4.x variants)

    • Maximum tokens (max-tokens is required by Anthropic’s API specification), temperature, and top-P.

Capabilities Supported

  • Extended Thinking & Reasoning: Supports Anthropic’s reasoning budgets and system prompt instructions.

  • Vision & Document Analysis: Accepts image and PDF payloads within user messages.

  • Prompt Caching & Tool Use: Integrates Anthropic’s native tool-calling protocol with Spring AI’s @Tool / function-calling callbacks.

4. Ollama Integration (Local & Self-Hosted LLMs)

Ollama allows developers to download and run open-weight models—such as Llama, Mistral, Gemma, DeepSeek, and Qwen—locally on developer workstations or private servers over HTTP.

Setup & Lifecycle Management

  • Starter Module: spring-ai-starter-model-ollama (formerly spring-ai-ollama-spring-boot-starter)

  • Connection Configuration:

    • Base URL: Points to the local or remote Ollama server (defaults to http://localhost:11434).

    • Model Selection: Specifies any pulled model tag (e.g., llama3.2, mistral, gemma3, nomic-embed-text).

    • Automatic Model Pull Strategy: Spring AI includes a pull-model-strategy property (never, when_missing, or always) that can automatically instruct the Ollama server to download a missing model on application startup.

Key Advantages & Capabilities

  • Data Privacy & Air-Gapped Execution: Prompts and enterprise documents never leave local infrastructure.

  • Zero API Token Cost: Eliminates per-token billing during development, automated integration testing, and high-volume internal batch processing.

  • Dual Chat & Embedding Support: Ollama can simultaneously serve a chat model for text generation and a dedicated local embedding model for Retrieval-Augmented Generation (RAG).

5. Provider Comparison Matrix

Feature / Aspect Google Gemini Anthropic Claude Ollama (Local)
Hosting Model Cloud (Google AI Studio / Vertex AI) Cloud (Anthropic API / Bedrock / Vertex) Local machine or private on-prem server
Authentication API Key or Google Cloud IAM API Key (x-api-key) None by default (local HTTP)
Cost Model Free tier (AI Studio) + Pay-per-token Pay-per-token Free (uses local CPU/GPU compute)
Data Privacy Cloud-processed under Google terms Cloud-processed under Anthropic terms 100% local; data never leaves host
Primary Strengths Massive context windows, native multimodal, Google Search grounding Complex reasoning, coding precision, instruction following Offline dev, zero cost, strict data compliance, model experimentation

6. Multi-Provider Strategies in a Single Application

In production Spring Boot applications, teams frequently configure multiple LLM providers simultaneously:
  • Environment-Based Switching (Spring Profiles): Use application-dev.yml configured with Ollama for free offline development, and application-prod.yml configured with Gemini or Claude for production scale.

  • Model Routing & Fallbacks: Spring AI allows disabling single-model auto-configuration (spring.ai.model.chat=none) so multiple ChatModel beans (GoogleGenAiChatModel, AnthropicChatModel, OllamaChatModel) can coexist in the Spring context. Applications can then dynamically route simple queries to a fast local model, route complex reasoning tasks to Claude or Gemini Pro, or fail over automatically if a cloud provider experiences an outage.

  • Per-Request Option Overrides: While defaults live in properties files, runtime call options (GoogleGenAiChatOptions, AnthropicChatOptions, OllamaChatOptions) allow overriding the specific model version or temperature on a per-request basis.


Hands-on Experiment: Multi-Model AI Chat Application using Gemini, Claude and Ollama

Aim: To build a Spring Boot application that integrates four LLM providers through Spring AI, sends the same prompt to one or all of them, and stores each answer and its response time in MySQL.

Description: This topic shows how one Spring Boot application can connect to several large language model providers. Each provider (OpenAI, Gemini, Claude, or Ollama for local models) has its own starter dependency, API key or endpoint, and model settings. Because Spring AI exposes a common API, switching or combining providers needs configuration changes rather than a rewrite. It is used to compare model quality, control cost, and run private models locally alongside cloud ones.

Software/Tools Required

  • JDK 17
  • Spring Boot 3.x (3.4.x for Spring AI 1.0)
  • Maven
  • MySQL 8.x
  • IDE (IntelliJ IDEA, Eclipse or VS Code)
  • Postman
  • API keys for the providers you want to test (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY)
  • Ollama installed locally (optional) with ollama pull llama3.2

Step-by-Step Application Development

Step 1: Generate the Project via Spring Initializr

  • Project: Maven, Language: Java, Spring Boot: 3.4.x (Spring AI 1.0 needs 3.4+)
  • Group: com.example, Artifact: multi-model-chat
  • Packaging: Jar, Java: 17
  • Dependencies: Spring Web, Spring Data JPA, MySQL Driver, OpenAI, Anthropic Claude, Ollama

Step 2: Project Structure

multi-model-chat
├── pom.xml
└── src/main
    ├── java/com/example/multimodelchat
    │   ├── MultiModelChatApplication.java
    │   ├── entity       (ChatLog)
    │   ├── repository   (ChatLogRepository)
    │   ├── service      (MultiModelService)
    │   └── controller   (ChatController)
    └── resources/application.properties

Step 3: Github Link:

Step 4: Download the application from above github link, then test the below CURD operations

POST Payloads and URLs (use Postman)

# Method URL Body
1 GET http://localhost:8080/api/chat/providers none
2 POST http://localhost:8080/api/chat/openai {"message":"Explain Spring AI in two lines"}
3 POST http://localhost:8080/api/chat/claude {"message":"Explain Spring AI in two lines"}
4 POST http://localhost:8080/api/chat/gemini {"message":"Explain Spring AI in two lines"}
5 POST http://localhost:8080/api/chat/ollama {"message":"Explain Spring AI in two lines"}
6 POST http://localhost:8080/api/chat/compare {"message":"Give 3 tips to learn Java faster"}
7 GET http://localhost:8080/api/chat/logs none
8 GET http://localhost:8080/api/chat/logs/claude none
Scroll to Top