Every developer who has shipped a production LLM feature in Java has written the same fragile hack: ask a full conversational ChatModel to “Respond ONLY with YES or NO, do not explain,” wrap the response in .trim().toUpperCase(), and cross your fingers that the model does not reply "Sure! Here is the answer: YES."
Using a generative chat model for bounded classification, routing, guardrails, or RAG document screening is slow, expensive, and statistically uncalibrated. Even when the model outputs valid JSON, you get a bare string with no confidence probability—so you cannot distinguish a 51% guess from a 99% certainty.
Enter the DecisionModel API in Spring AI 2.1 (landed in 2.1.0-RC2). Instead of coaxing free-form text out of a chat completion endpoint, DecisionModel evaluates a closed set of outcomes—boolean, multiple-choice, or ordinal scale—and returns calibrated probabilities you can threshold directly in Java. Better still, it runs locally at zero API cost using Ollama’s d1-omni:600m model and plugs straight into Spring AI’s Modular RAG pipeline and tool-search advisor.
Building on our earlier guides to Mastering RAG with Spring AI and running Ollama locally with Docker Compose, let’s build a complete Spring Boot 4.2 + Spring AI 2.1 decision pipeline.
1. The DecisionModel Contract and Three Question Primitives
Spring AI 2.1 models decisions with the same clean symmetry we already know from ChatModel and EmbeddingModel: you construct a DecisionPrompt, call decisionModel.call(prompt), and inspect a typed DecisionResponse.
Every DecisionPrompt carries input data (plain text, structured fields, or a conversation) paired with one or more named questions drawn from three primitives:
| Question Type | What It Returns | Best Production Use Cases |
|---|---|---|
YesNoQuestion | Calibrated probability of yes, checked with isYes(double threshold) | Prompt-injection guardrails, policy checks, defect detection, tool applicability |
ChoiceQuestion | Winning option (getValue()) plus per-option probability distribution | Intent routing, support ticket triage, agent handoff selection |
ScoreQuestion | Nearest level on an ordered ordinal scale (getNearestLevel()) | Customer sentiment, rubric grading, severity/priority scoring |
Out of the box, Spring AI 2.1 ships three provider implementations:
| Implementation | Artifact | Default Model / Protocol | Best Fit |
|---|---|---|---|
OpenAiDecisionModel | spring-ai-starter-model-openai | gpt-6-luna (OpenAI Decisions API) | Cloud-managed high-accuracy classification |
OllamaDecisionModel | spring-ai-starter-model-ollama | d1-omni:600m (/v1/systemone, Ollama 0.40.4+) | Fast, private, zero-API-cost local routing & guardrails |
SystemOneDecisionModel | spring-ai-systemone | TypeSafe Java SDK 0.4.0 (jev-latest / laya-serve) | Self-hosted dedicated decision inference clusters |
Every DecisionModel call automatically emits Micrometer observations under the decision operation name via spring-ai-autoconfigure-model-decision-observation, giving you latency and token visibility in Prometheus or OpenTelemetry right alongside your chat models.
2. Gradle and application.yml Setup (Local Ollama d1-omni:600m)
Using OllamaDecisionModel with the compact d1-omni:600m model keeps routing latency low and avoids paying frontier LLM rates just to classify incoming requests. Note that Ollama 0.40.4+ is recommended, and Spring AI can pull the model automatically at startup if it is missing.
// build.gradle.kts
ext["springAiVersion"] = "2.1.0-RC2"
dependencyManagement {
imports {
mavenBom("org.springframework.ai:spring-ai-bom:${property("springAiVersion")}")
}
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-webmvc")
implementation("org.springframework.ai:spring-ai-starter-model-ollama")
implementation("org.springframework.ai:spring-ai-starter-vector-store-pgvector")
implementation("org.springframework.ai:spring-ai-starter-tool-search-advisor")
}
# application.yml
spring:
ai:
model:
decision: ollama
ollama:
base-url: http://localhost:11434
init:
pull-model-strategy: when_missing
decision:
include: true
decision:
options:
model: d1-omni:600m
chat:
client:
tool-search-advisor:
tool-index-type: decision
decision:
applicability-threshold: 0.75
minimum-relevance: 0.60
3. Deterministic Routing and Thresholded Decisions in Java
Because a single DecisionPrompt accepts multiple named questions, you can evaluate defect status, routing topic, and customer sentiment in one round-trip—and only automate high-risk actions when the model clears your confidence bar (for example, 0.90).
package com.ghostprogrammer.ai.decision;
import org.springframework.ai.decision.ChoiceQuestion;
import org.springframework.ai.decision.DecisionModel;
import org.springframework.ai.decision.DecisionPrompt;
import org.springframework.ai.decision.DecisionResponse;
import org.springframework.ai.decision.ScoreQuestion;
import org.springframework.ai.decision.YesNoQuestion;
import org.springframework.stereotype.Service;
@Service
public class SupportTriageService {
private final DecisionModel decisionModel;
public SupportTriageService(DecisionModel decisionModel) {
this.decisionModel = decisionModel;
}
public TriageDecision classifyTicket(String customerMessage) {
DecisionResponse response = decisionModel.call(DecisionPrompt.builder()
.text(customerMessage)
.question("defect", YesNoQuestion.builder()
.text("Does the customer report a hardware or product defect?")
.whenYes("Part of the received item does not work as expected")
.whenNo("The item works, or the message is about shipping, billing, or general questions")
.build())
.question("topic", ChoiceQuestion.builder()
.text("Which support queue owns this request?")
.option("delivery", "Tracking, delays, or missing packages")
.option("product", "Damaged, broken, or defective items")
.option("account", "Login, billing, address, or payment details")
.option("other", "Anything that does not match the queues above")
.build())
.question("satisfaction", ScoreQuestion.of(
"How satisfied is the customer?",
"unhappy", "neutral", "happy"))
.build());
// Only trigger automated RMA workflows when confidence >= 90%
boolean autoApproveRma = response.getYesNo("defect").isYes(0.90);
String targetQueue = response.getChoice("topic").getValue();
int sentimentLevel = response.getScore("satisfaction").getNearestLevel();
return new TriageDecision(autoApproveRma, targetQueue, sentimentLevel);
}
public record TriageDecision(boolean autoApproveRma, String queue, int sentimentLevel) {}
}
Notice how clean that contract is. There is no JSON schema prompt engineering, no fallback try/catch for malformed Markdown fences, and no ambiguity about whether "maybe" counts as true. If isYes(0.90) returns false on a borderline 0.68 score, your Java code routes the ticket to a human reviewer instead of firing an automated refund.
4. Virtual-Thread RAG Guardrails and Reranking
Where DecisionModel really earns its keep in enterprise systems is inside Modular RAG. Vector similarity search is notoriously bad at two things: distinguishing topically similar chunks from chunks that actually answer the question, and spotting indirect prompt injections hidden inside retrieved documents.
Spring AI 2.1 ships two built-in DocumentPostProcessor implementations backed by DecisionModel:
DecisionDocumentFilter: Screens each retrieved candidate document for prompt injection, contradictions, and relevance before it ever enters your system prompt.DecisionDocumentReranker: Reorders the surviving chunks by asking theDecisionModelhow directly each chunk answers the user query.
Both fan out per-document evaluations concurrently over any Executor—making Java Virtual Threads a natural fit—and allow you to choose between fail-open (default, keeping documents the model could not judge while logging the count) and fail-closed (dropping unjudged documents for high-security pipelines).
@Configuration
public class SecureRagConfig {
@Bean
RetrievalAugmentationAdvisor secureRagAdvisor(
VectorStore vectorStore,
DecisionModel decisionModel) {
Executor virtualThreadExecutor = Executors.newVirtualThreadPerTaskExecutor();
DecisionDocumentFilter injectionAndRelevanceFilter = DecisionDocumentFilter.builder()
.decisionModel(decisionModel)
.executor(virtualThreadExecutor)
.failClosed(true) // Drop chunks that fail screening in high-security apps
.build();
DecisionDocumentReranker reranker = DecisionDocumentReranker.builder()
.decisionModel(decisionModel)
.executor(virtualThreadExecutor)
.build();
return RetrievalAugmentationAdvisor.builder()
.documentRetriever(VectorStoreDocumentRetriever.builder()
.vectorStore(vectorStore)
.topK(12)
.build())
.documentPostProcessors(injectionAndRelevanceFilter, reranker)
.build();
}
}
Because each retrieved chunk is evaluated in parallel on a virtual thread against a local 600M-parameter decision model, screening 12 candidate chunks adds minimal wall-clock latency while dramatically tightening RAG precision and security.
5. Stopping Wrong-Tool Hallucinations with DecisionToolIndex
If you have ever registered 30+ tools on an agent and watched a vector-based tool retriever faithfully hand the LLM the “nearest” database tool for a simple greeting, you will love DecisionToolIndex.
Introduced alongside regex, lucene, and vector strategies in spring-ai-starter-tool-search-advisor, DecisionToolIndex (tool-index-type: decision in the YAML above) makes a single DecisionModel call that asks two questions simultaneously:
- Which indexed tool best serves this request?
- Does any tool apply at all?
When the applicability probability falls below your configured applicability-threshold, DecisionToolIndex returns an empty set—keeping tool schemas out of the prompt completely and preventing unnecessary tool calls.
6. Production Tuning Notes
Before pushing DecisionModel into production, keep three operational details in mind:
- Tune thresholds against a labeled golden set: Start conservative (
0.85–0.90for irreversible actions like refunds or deletes;0.65–0.75for routing or filtering) and log raw probabilities via Micrometer/OTel so you can calibrate false positives vs. false negatives with real traffic. - Pair local decisions with frontier generation: Using local
OllamaDecisionModel(d1-omni:600m) for triage, RAG filtering, and tool indexing while reserving Claude, OpenAI, or Gemini strictly for final synthesis cuts token spend and shrinks attack surface simultaneously. - Choose fail-closed intentionally: Fail-open makes sense for internal developer search tools where availability beats strictness; fail-closed is the right call whenever RAG ingests untrusted web pages, emails, or external issue trackers.
Conclusion
The DecisionModel API represents a major maturation step for Spring AI. Not every AI problem is a chat completion problem—and by separating calibrated classification from open-ended text generation, Spring AI 2.1 gives Java architects deterministic routing, virtual-thread RAG guardrails, and smarter tool search that can run right on your own hardware.
Discover more from GhostProgrammer - Jeff Miller
Subscribe to get the latest posts sent to your email.

