Showing posts with label Ollama. Show all posts
Showing posts with label Ollama. Show all posts

Saturday, December 5, 2026

Run a Local LLM with Spring AI and Ollama: A Java REST Example

Want to call a language model from a Java application without sending each prompt to a hosted model API? In this walkthrough, we will run Qwen 2.5 locally with Ollama, connect it to Spring AI, and expose a small REST endpoint. The same pattern is a starting point for the TrainingHub project used in the Spring AI course.

What you will build: a Spring Boot endpoint that accepts a message, passes it through ChatClient, and returns the model response as JSON.

Request flow: REST client → Spring Boot controller → Spring AI ChatClient → Ollama → local model → JSON response.

1. Prerequisites

  • Java 21 and Maven (or the Maven wrapper generated by Spring Initializr).
  • Ollama installed and running on the same machine.
  • An internet connection and enough disk space for the first model and dependency downloads.

The prompts in this example go to the local Ollama server at localhost. Installing software and downloading the model and Maven dependencies require network access. Local inference does not by itself guarantee privacy: consider logs, other network calls, and how the application is deployed.

2. Download and check the model

Open a terminal and run:

ollama pull qwen2.5:1.5b
ollama list

Check that qwen2.5:1.5b appears in the list. You can also try ollama run qwen2.5:1.5b to chat in the terminal. If Ollama is installed but its server is not running, start the Ollama application; on systems where it is not already running as a service, ollama serve starts the server.

3. Create the Spring Boot project

Open Spring Initializr and generate a Maven project using Java 21, package name com.example.localai and Spring Boot 4.2.0. Download and unzip it, then open the extracted folder containing pom.xml in IntelliJ IDEA as a Maven project. Set the project JDK to 21. Keep the generated application class and Maven wrapper files.

Replace the entire contents of the generated pom.xml with the complete file below, then reload Maven in IntelliJ. Do not paste it inside the existing file: XML can contain only one properties section here. The first dependency enables REST controllers; the second connects Spring AI to Ollama. The BOM manages Spring AI dependency versions.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.2.0</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>localai</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>21</java.version>
        <spring-ai.version>2.1.0</spring-ai.version>
    </properties>
    <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.boot</groupId>
            <artifactId>spring-boot-starter-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-starter-model-ollama</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

The example combines Spring Boot 4.2.0 and Spring AI 2.1.0, as recommended by the Spring AI 2.1 release announcement. Other combinations require checking their compatibility.

4. Configure the local model

Add the following to src/main/resources/application.properties:

spring.ai.model.chat=ollama
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.model=qwen2.5:1.5b
spring.ai.ollama.chat.temperature=0.0

The base URL points to the Ollama server, and the model name must match the one downloaded in step 2. Temperature influences sampling; even with a low value, model responses can vary. Some older Spring AI examples use spring.ai.ollama.chat.options.model; consult the documentation for your exact version. If you run Ollama in Docker or from another host, use the address and exposed port reachable from the application.

5. Add a REST controller

Place the class below under the package containing your Spring Boot application, for example src/main/java/com/example/localai/LocalChatController.java:

package com.example.localai;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/chat")
public class LocalChatController {
    private final ChatClient chatClient;

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

    @PostMapping
    public ChatResponse ask(@RequestBody ChatRequest request) {
        String answer = chatClient.prompt()
                .user(request.message())
                .call()
                .content();
        return new ChatResponse(answer);
    }

    public record ChatRequest(String message) {}
    public record ChatResponse(String answer) {}
}

Spring injects the configured ChatClient.Builder. The controller places the incoming message in the prompt, call() sends it synchronously via Spring AI to Ollama, and content() extracts the text. The response record is serialized to JSON. This deliberately small example omits input validation, authentication and production error handling.

6. Build, run and test

Open a terminal in the extracted project root, the directory containing pom.xml. With the generated Maven wrapper on Windows PowerShell, build and run:

.\mvnw.cmd clean package -DskipTests
java -jar target/localai-0.0.1-SNAPSHOT.jar

On macOS or Linux, use ./mvnw clean package -DskipTests for the first command. If you have Maven installed, mvn clean package -DskipTests works too. The wrapper may need network access to download Maven on its first run. This demonstration skips tests; it does not claim that a test suite passed. The verification below used an installed Maven, not a separately tested wrapper download.

When the application has started and Ollama is running, open a second terminal and send a request. For PowerShell:

$body = @{ message = 'Explain what Spring AI does in one sentence.' } | ConvertTo-Json
Invoke-RestMethod -Uri 'http://localhost:8080/api/chat' -Method Post `
    -ContentType 'application/json' -Body $body

For a Unix-style shell:

curl -X POST http://localhost:8080/api/chat -H 'Content-Type: application/json' -d '{"message":"Explain what Spring AI does in one sentence."}'

Observed result: I compiled the example with Maven 3.9.11, Java 21.0.13.1, Spring Boot 4.2.0 and Spring AI 2.1.0, using a separate initially empty Maven repository. The Qwen model was already available locally and was not downloaded again for this check. mvn clean package -DskipTests finished with BUILD SUCCESS. I started the resulting JAR and sent the PowerShell request above to local Ollama 0.11.10 and qwen2.5:1.5b; the response was:

{"answer":"Spring AI is an open-source framework for building and deploying machine learning models using the Spring ecosystem."}

This is a real model response, not an authoritative definition: it oversimplifies Spring AI. The framework integrates AI capabilities with Spring applications. Responses can vary; the first call may take longer while the model loads. In this environment, Maven initially reported a certificate trust error; using the Windows trusted root store resolved it without disabling TLS verification. This adjustment is environment-specific and is not required for every installation.

Troubleshooting

  • Connection refused: confirm Ollama is running and that the configured host and port are reachable from the Spring application.
  • Model not found: compare the name in ollama list with the model property and pull the matching tag.
  • Download fails with an x509 certificate error: check the machine or corporate proxy trust configuration with your administrator. Do not disable certificate verification.
  • Slow response or memory pressure: start with a small model such as this one and check available RAM; model quality and speed depend on hardware.
  • Wrong setting for your version: compare the properties with the Spring AI reference for the exact release used by your project.

Where to go next

This example makes one local model call. To build a useful assistant, you can add conversation context, retrieval from your own documents, Java tools and approval before changes to business data. The Spring AI with Java course explores these ideas through the TrainingHub project, including RAG, MCP and a Thymeleaf interface.

References: Spring AI Ollama integration · ChatClient reference · Qwen 2.5 model library.