Spring AI

models-spring-ai implements Spring AI’s blocking and streaming ChatModel contract over a Models TextGenerationModel. Both paths use the same in-process tokenizer, chat template, generation loop, sampler, and selected backend as plain Java.

Compatibility CI exercises Spring AI 1.1.4, 1.1.8, and 2.0.0. The application normally selects the Spring AI version through its Spring AI BOM; the Models adapter does not impose a provider or hosted model client.

Spring Boot’s development launch optimization limits HotSpot to the C1 compiler. That is useful for fast application startup, but it prevents the Vector API inference kernels from reaching their optimized form. Disable launch optimization when running an in-process model with bootRun, spring-boot:run, or an IntelliJ Spring Boot run configuration. See Development launchers for the exact settings. Packaged applications started with java -jar do not receive this development-only option.

Dependencies

dependencies {
    implementation("org.springframework.ai:spring-ai-model:2.0.0")
    implementation("org.modeljars:modeljars:0.1.78")
    implementation(
        "org.modeljars.huggingface:" +
            "ggml-org.qwen3-0.6b-gguf.q4_0:" +
            "3.0.0-q4_0.1"
    )
    implementation("com.integrallis:models-spring-ai:0.5.20")
}

Route Local And Hosted Models

RoutedSpringAiChatModel binds ordinary Spring AI ChatModel clients to a provider-neutral ModelFleet. A fleet can contain a local ModelsSpringAiChatModel, hosted provider clients, and private gateways. The selected delegate receives the original Prompt, including its tools, options, and metadata. Blocking and streaming calls support ordered failover; streaming changes providers only before the first fragment is emitted. See Model Routing for configuration, live feedback, and conversation continuity.

Blocking Chat

The adapter maps Spring AI system, user, assistant, and tool messages to the selected Models chat template. Message text remains ordinary text and cannot inject template control tokens.

import static org.modeljars.catalog.Qwen3_0_6b_Q4_0.MODEL;

import com.integrallis.models.api.SamplingOptions;
import com.integrallis.models.spring.ai.ModelsSpringAiChatModel;
import java.util.List;
import org.modeljars.ModelJars;

var defaults = SamplingOptions.builder()
    .temperature(0.0f)
    .maxTokens(128)
    .stopSequences(List.of("</answer>"))
    .build();

try (var runtime = ModelJars.openRuntime(MODEL)) {
    var model = new ModelsSpringAiChatModel(
        runtime.model(),
        runtime.descriptor().alias(),
        runtime.chatTemplate(),
        defaults,
        runtime.descriptor().capabilities());

    String answer = model.call("Answer using only the supplied context.");
    System.out.println(answer);
}

Use the chat template recorded by the exact qualified ModelJar rather than selecting one from the architecture name.

Observability

Pass the application’s ObservationRegistry to keep local blocking and streaming inference on Spring AI’s standard gen_ai.client.operation surface:

var model = new ModelsSpringAiChatModel(
    runtime.model(),
    runtime.descriptor().alias(),
    runtime.chatTemplate(),
    defaults,
    observationRegistry,
    runtime.descriptor().capabilities());

The adapter reports gen_ai.system=integrallis, the Models runtime identity as the request and response model, the operation duration, and failures. Every ChatResponse carries the same model identity. A completed Models runtime generation also reports exact counts through Spring AI’s Usage: prompt tokens are counted after applying the qualified chat template, and completion tokens are the non-terminal tokens generated by the runtime.

ChatResponse response = model.call(new Prompt("Name one JVM language."));
var usage = response.getMetadata().getUsage();

System.out.printf(
    "prompt=%d completion=%d total=%d%n",
    usage.getPromptTokens(),
    usage.getCompletionTokens(),
    usage.getTotalTokens());

Custom TextGenerationModel implementations that only invoke the legacy TokenStream.onComplete() callback remain compatible and retain Spring AI’s empty-usage behavior. Exact counts are reported by Models runtime generations.

Pass the selected catalog alias explicitly when the model file’s embedded metadata is generic or ambiguous. Constructors without that argument retain the runtime’s modelName() for source compatibility.

setObservationConvention(…​) accepts an application-specific Spring AI ChatModelObservationConvention. Constructors without an ObservationRegistry retain their source-compatible no-op behavior.

Tool Calling

When a ChatClient request declares Spring AI tools, the adapter renders their names, descriptions, and input schemas into the selected Models chat template. Model output is scanned back into Spring AI AssistantMessage tool calls. The ChatClient executes the registered Java callback. Generative chat models receive that result for a follow-up answer. Needle 2 is an action-selection model, so it cannot write a conversational answer after the tool runs. Register a typed result renderer for each Needle tool. The adapter converts Spring AI’s serialized callback result back to that Java type and invokes the renderer, without exposing JSON parsing to application code. Needle action selection always uses deterministic decoding; a chat-oriented temperature configured on the adapter or request cannot turn an applicable action into a sampled refusal.

Pass the ModelJar descriptor capabilities when constructing the adapter. This makes an artifact that was qualified for chat, but not tool calling, fail before generation instead of silently attempting an unsupported workflow.

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

record Weather(String zipcode, String conditions, int temperature) {}

@Service
class WeatherTools {
    @Tool(
        name = "get-weather-for-zipcode",
        description = "Gets weather for a given zipcode")
    Weather getWeatherForZipcode(
        @ToolParam(description = "The zipcode to get weather for")
        String zipcode) {
        return new Weather(zipcode, "Raining cats and dogs", 78);
    }

}

@Bean
ApplicationRunner weatherDemo(WeatherTools weatherTools) {
    return args -> {
        try (var runtime = ModelJars.openRuntime(MODEL)) {
            var model = new ModelsSpringAiChatModel(
                runtime.model(),
                runtime.descriptor().alias(),
                runtime.chatTemplate(),
                defaults,
                runtime.descriptor().capabilities())
                .withToolResultRenderer(
                    "get-weather-for-zipcode",
                    Weather.class,
                    weather -> "The weather in %s is %s with a temperature of %d°F."
                        .formatted(
                            weather.zipcode(),
                            weather.conditions(),
                            weather.temperature()));

            var chatClient = ChatClient.builder(model)
                .defaultTools(weatherTools)
                .build();

            String answer = chatClient.prompt()
                .user("What is the weather for 88252?")
                .call()
                .content();
            System.out.println(answer);
        }
    };
}

defaultTools(…​) and per-request .tools(…​) use the same adapter path. For Needle 2, answer is the text returned by the registered typed renderer. For a qualified generative tool-calling model, it is the model’s follow-up response after seeing the tool result; no result renderer is needed. Qwen3 1.7B Q8_0 is qualified for that workflow. Release verification runs the full ChatClient loop against its pinned weights, asserts that the Java method receives exactly "88252", and checks that the model’s final answer mentions both the rain and 78°F without exposing protocol tokens. The corresponding Needle test verifies the typed renderer path against the pinned CACT artifact. When no tool applies, Needle’s private reasoning and protocol are removed and the adapter returns No applicable tool is available.; customize that text with withNoApplicableToolResponse(…​). Machine-to-machine callers that really want Spring’s serialized callback value can opt in with withRawToolResults(). Do not use ChatClient.call().entity(…​) to recover a Needle callback result: that API adds structured-output instructions to the original model request. A typed tool-result renderer runs only after Spring has invoked the selected tool.

GPT-OSS uses the Harmony protocol. The adapter recognizes both recipient positions permitted by Harmony, renders current constrained-JSON call history, addresses named tool results back to the assistant, and returns only the completed final-channel text. The exact hyphenated weather example above is covered against the pinned official GPT-OSS 20B checkpoint. That checkpoint demonstrates adapter compatibility but remains outside the ModelJars catalog until its Java prefill meets the performance gate.

The same execution path is covered for blocking and streaming ChatClient requests. Streaming with declared tools buffers generated text until the tool call is complete, because Spring AI can only act on a complete request.

Calling the lower-level ChatModel.call(Prompt) API returns an AssistantMessage containing the parsed tool calls; it does not execute Java callbacks. Use ChatClient when the application wants Spring AI to own the tool-execution loop.

When the wrapped model exposes a contrastive head and more than five tools are declared, the adapter retrieves the five most relevant schemas before it renders the prompt. Schema vectors are cached in a bounded per-adapter index; subsequent requests embed the user query without re-embedding an unchanged tool catalog. The selected schemas also define the decoding constraint.

Schema-Constrained Tool Decoding

If the wrapped Models runtime implements ConstrainedTextGenerationModel, the Spring AI adapter compiles supported tool input schemas into a token constraint and passes it into the generation loop. Sampling then admits only tokens that keep the output on a valid tool-call string. This changes tool calling from "ask the model to follow the schema" to "prevent invalid enumerable tool-call syntax from being decoded" for the supported schema subset.

For ChatML and Llama 3, the Spring AI adapter constrains finite tool-call spaces:

  • tool syntax must be one of the non-array-wrapped Models JSON formats, such as ChatML or Llama 3 JSON-native tool calls

  • argument properties must be string enum values, or absent

  • every required property must be one of those enumerable properties

  • the compiled call set is capped to keep decoding checks bounded

Needle 2 has a separate array-aware grammar compiled directly from JSON Schema. It supports objects, arrays, strings, integers, numbers, booleans, nulls, enum, const, oneOf, and anyOf, with an explicit bound on optional-object expansion. The decoder also prevents model protocol markers and JSON closing delimiters from being consumed as plain string content, so malformed output cannot reach a Java tool argument.

For example, this Spring AI input schema can be enforced during decoding:

{
  "type": "object",
  "properties": {
    "mode": {
      "type": "string",
      "enum": ["cool", "heat"]
    }
  },
  "required": ["mode"]
}

With a compatible chat template, the runtime constrains output to valid calls such as:

{"name":"set_mode","arguments":{"mode":"cool"}}

or the template’s tagged equivalent, for example:

<tool_call>{"name":"set_mode","arguments":{"mode":"cool"}}</tool_call>

Schemas that require open text, numbers, arrays, nested objects, conditionals, references, or any other value space the adapter cannot enumerate are not partially constrained. The adapter deliberately falls back to ordinary tool calling for those schemas, leaving the generated call parser and Spring AI tool execution path unchanged. That fallback preserves correctness for ordinary Spring AI applications while keeping the enforced path honest about what it can guarantee.

Request Options

Non-null ChatOptions values override adapter defaults for temperature, top-p, top-k, maximum tokens, and stop sequences. Values absent from the request retain the Models defaults. A request stopSequences list replaces the default list for that generation; repetition penalty and seed remain Models defaults because Spring AI’s common ChatOptions contract does not expose them.

import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.Prompt;
import java.util.List;

var requestOptions = ChatOptions.builder()
    .temperature(0.2)
    .maxTokens(96)
    .stopSequences(List.of("</answer>"))
    .build();
var prompt = new Prompt(
    List.of(new UserMessage("Return one cited sentence.")),
    requestOptions);

ChatResponse response = model.call(prompt);
System.out.println(response.getResult().getOutput().getText());

getOptions() exposes the adapter defaults through Spring AI’s ChatOptions view, including the local Models runtime identity. Per-request overrides do not mutate those defaults.

Streaming Chat

stream(Prompt) returns a Flux<ChatResponse> whose elements contain decoded token fragments in generation order. Models runs blocking inference on Reactor’s bounded-elastic scheduler so subscription does not block the subscriber thread. A generation failure is propagated through the Flux error signal without being wrapped or followed by completion. For ordinary text generation, the terminal response has empty text and carries the complete Spring AI Usage; concatenate text fragments and read usage from that terminal response.

model.stream(new Prompt("List the retrieved facts."))
    .map(response -> response.getResult().getOutput().getText())
    .doOnNext(System.out::print)
    .doOnError(Throwable::printStackTrace)
    .blockLast();

The adapter does not close the underlying TextGenerationModel; the application or Spring bean lifecycle owns it. Apple’s system model implements the same contract, but currently emits its complete response as one streaming element because Apple’s API returns a complete response to the bridge.

Embeddings

ModelsSpringAiEmbeddingModel adapts a Models EmbeddingBackend to Spring AI’s EmbeddingModel.

import com.integrallis.models.api.EmbeddingBackend;
import com.integrallis.models.spring.ai.ModelsSpringAiEmbeddingModel;
import io.micrometer.observation.ObservationRegistry;
import org.springframework.ai.embedding.EmbeddingModel;

@Bean(destroyMethod = "close")
EmbeddingModel localEmbeddingModel(
        EmbeddingBackend backend,
        ObservationRegistry observations) {
    return new ModelsSpringAiEmbeddingModel(
            backend, "embeddinggemma-300m-q8_0", observations);
}

This adapter owns the backend it wraps and closes it. See Embeddings for producing the backend. Passing Spring’s ObservationRegistry records standard gen_ai.client.operation observations for direct, document, and batch embedding calls. The pinned model name and backend dimension are attached to each observation and response. Concurrent framework calls are serialized around the backend because the local encoder reuses mutable scratch state between sequences.

Document Reranking

ModelsSpringAiDocumentReranker implements Spring AI’s DocumentPostProcessor over an in-process cross-encoder. It preserves document identity and metadata, attaches the model’s score, and can keep only the highest-ranked documents. See Reranking for the complete example and qualification gate.

For auto-configuration, named-bean behavior, and combined Models/Vectors setup, continue with Spring Boot. For validation after retrieval, see RAG Validation.