Decision Services
Decision Services are experimental and may change in future releases.
Decision models answer typed questions about some input (state): yes/no questions, questions choosing one of several options, and so on. Decision Services let you use them through a plain Java interface: you declare what you want to know as methods, and LangChain4j implements the interface for you.
enum Team {
@Description("Payments, payouts, invoices, refunds") BILLING,
@Description("Problems using the product") SUPPORT,
@Description("Pricing, upgrades, new accounts") SALES
}
interface SupportDesk {
@Decide("Is this message spam?")
boolean isSpam(String message);
@Decide("Which team should handle this ticket?")
Team route(String ticket);
}
SupportDesk supportDesk = DecisionServices.create(SupportDesk.class, decisionModel);
boolean spam = supportDesk.isSpam("Congratulations! You won a free cruise!"); // true
Team team = supportDesk.route("I was charged twice this month"); // BILLING
Any DecisionModel can be used, for example TypeSafe.
DecisionServices.builder(SupportDesk.class) offers more options, such as thresholds.
Decision Services are not related to the decision services of DMN (Decision Model and Notation), as found in Drools, Kogito or Camunda: they answer questions with a decision model, and can be called like any other Java service.
A decision service interface can also be an agent of an agentic system: annotated with @Agent as well, its method
reads its arguments from the AgenticScope and writes its typed answer back to it, where the other agents can read
it together with its probabilities. See decision agents.
Maven dependency
Decision Services are part of the langchain4j module; add it next to the module of your DecisionModel:
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j</artifactId>
<version>1.24.1</version>
</dependency>
Decision Services send the names of the method parameters to the model, so compile your code with the
-parameters option (or name each parameter with @V, see Parameters):
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<parameters>true</parameters>
</configuration>
</plugin>
The @Description annotation used on enum constants is dev.langchain4j.model.output.structured.Description.
How it works
For every call, the Decision Service:
- Sends the method parameters to the model as the input (state), keyed by parameter name,
for example
{"message": "Congratulations! You won a free cruise!"}. - Asks the question(s) derived from the method's return type and the
@Decideannotation. Each question is named after the method, or after the field for methods returning an object, and the model sees these names, so choose meaningful ones. - Converts the answer(s) back to the return type.
All methods are checked when build() is called, so a misconfigured method
(an unsupported return type, a missing @Decide, etc.) fails immediately with an explanation, not on the first call.
Return types
| Return type | Question | Result |
|---|---|---|
boolean / Boolean | yes/no | true if the probability of "yes" reaches the threshold |
YesNoAnswer | yes/no | the probability of "yes" |
| an enum | choice between the enum constants | the chosen constant |
Choice<E> (E is an enum) | choice between the enum constants | the chosen constant and the probability of each constant |
Scale<E> (E is an enum) | position on an ordered scale, whose levels are the enum constants | the mean level, the most likely level and the probability of each level |
| a class or record whose fields have the types above | one question per field, all in a single call | an instance with every field set |
Any of these can also be wrapped in DecisionResult<T>
and/or CompletableFuture<T> or CompletionStage<T>.
Yes/no questions
interface Moderation {
@Decide("Is this message spam?")
boolean isSpam(String message);
@Decide("Is this message spam?")
YesNoAnswer spamProbability(String message);
}
YesNoAnswer spam = moderation.spamProbability(message);
spam.probability(); // 0.97
spam.isYes(0.9); // true
Return YesNoAnswer when you want to decide on the threshold in your own code,
or to evaluate several thresholds without calling the model again.
Choice questions
The constants of an enum are the options.
The model sees the name of each constant together with its @Description (or only the name, when the constant has no
@Description), so choose names and descriptions that explain what each option covers:
@Decide("Which team should handle this ticket?")
Choice<Team> routeWithProbabilities(String ticket);
Choice<Team> choice = supportDesk.routeWithProbabilities(ticket);
choice.value(); // BILLING
choice.probabilities(); // {BILLING=0.88, SUPPORT=0.1, SALES=0.02}
choice.probabilityOf(Team.SUPPORT); // 0.1
choice.margin(); // 0.78, the difference between the two most likely constants
choice.confidence(); // provided by some models, see below
A small margin means that the model hesitated between two options, which is a good signal to escalate:
Choice<Team> choice = supportDesk.routeWithProbabilities(ticket);
if (choice.margin() < 0.2) {
humanQueue.add(ticket);
} else {
assign(ticket, choice.value());
}
confidence() is computed differently by each model, so prefer probabilities for thresholds
(see Probabilities and confidence).
Scale questions
When the options are ordered (severity, urgency, frustration, quality), return Scale<E>.
The levels are the enum constants, from the first declared (lowest) to the last (highest).
Each level is labeled with the name of the constant, and described with its @Description, if any:
enum Severity {
@Description("Cosmetic issue, no impact") LOW,
@Description("A feature is degraded, a workaround exists") MEDIUM,
@Description("A feature is broken for some customers") HIGH,
@Description("Outage or data loss") CRITICAL
}
interface IncidentTriage {
@Decide("How severe is this incident?")
Scale<Severity> severity(String incident);
}
Scale<Severity> severity = incidentTriage.severity(report);
severity.mean(); // 2.3, from 0 (LOW) to 3 (CRITICAL)
severity.mostLikely(); // HIGH
severity.probabilities(); // {LOW=0.02, MEDIUM=0.1, HIGH=0.46, CRITICAL=0.42}
severity.probabilityOf(Severity.CRITICAL); // 0.42
severity.probabilityAtLeast(Severity.HIGH); // 0.88
mean() is the probability-weighted average of the level indexes, so it can fall between two levels.
It is useful to compare inputs or to follow a trend over time, for example the average frustration of customers.
probabilityAtLeast(level) is useful to act on a level or anything above it, for example to page the on-call
engineer when an incident is likely to be at least of high severity:
if (severity.probabilityAtLeast(Severity.HIGH) > 0.5) {
pageOnCall(report);
}
A plain enum return type is always a choice question, where the order of the constants does not matter.
Several questions in one call
When a method returns a class or a record, every field becomes a question, and all questions are answered in a single call to the model:
record Triage(
@Decide("Which team should handle this ticket?") Team team,
@Decide("Does this need attention today?") boolean urgent,
@Decide("Does the customer ask for money back?") YesNoAnswer refund) {}
interface SupportDesk {
Triage triage(String ticket);
}
Triage triage = supportDesk.triage("I was charged twice and our payroll runs today!");
triage.team(); // BILLING
triage.urgent(); // true
triage.refund().probability(); // 0.99
Every field needs a question in @Decide; a field without it fails when build() is called.
To keep a field that is not a question, declare it transient.
@Decide on the method itself is not supported for such methods.
A regular class works as well, as long as it is a top-level or static nested class with a no-argument constructor and non-final fields:
class Triage {
@Decide("Which team should handle this ticket?")
Team team;
@Decide("Does this need attention today?")
boolean urgent;
}
Parameters
All parameters are sent to the model as the input (state), keyed by parameter name.
Parameters that are null are left out, so the model cannot tell a null value from a missing parameter.
Triage triage(String ticket, Customer customer);
// input: {"ticket": "...", "customer": {"plan": "enterprise", "openTickets": 3}}
The names help the model understand what each value means, so choose them well.
Objects are converted to maps using their Java field names, except contents such as images (see Images).
All fields are sent, so to control exactly what the model sees (and to avoid sending personal data it does not
need), pass a small record containing only the relevant fields, rather than, for example, a JPA entity.
If all parameters sent to the model are null, the call fails with an IllegalArgumentException.
Parameter names are only available at runtime when the code is compiled with the -parameters option
(projects based on Spring Boot or Quarkus usually enable it). Otherwise, name the parameters with @V:
Triage triage(@V("ticket") String ticket, @V("plan") String plan);
If a name is not available, build() fails and explains both options.
Images
Parameters of type Image, Audio, Video or PdfFile, or of a Content type, such as ImageContent, or
collections or arrays of them, are sent as contents, for example images, if the decision model supports them
(for example OpenAI, or Ollama with
a vision model such as Clef):
interface DamageInspector {
@Decide("Is the item visibly damaged?")
boolean isDamaged(ImageContent photo, String comment);
}
Audio, video and PDF files are sent the same way, as AudioContent, VideoContent and PdfFileContent parameters
or as Audio, Video and PdfFile parameters, to decision models that take them, such as
Google AI Gemini.
Like the other parameters, contents are sent under the names of their parameters (see
Images), and each decision model sends them in the form its API expects.
Images are sent as ImageContents with the AUTO detail level, so that the model provider chooses it; to choose
another detail level, pass an ImageContent. Audio, Video and PdfFile are sent as AudioContent, VideoContent
and PdfFileContent.
A decision model that does not support a kind of content throws an UnsupportedFeatureException without calling the
model.
Model name and other parameters
A parameter of type DecisionRequestParameters is not sent as part of the input.
Instead, it sets the parameters of the call, for example the model to use:
@Decide("Which team should handle this ticket?")
Team route(String ticket, DecisionRequestParameters parameters);
Team team = supportDesk.route(ticket, DecisionRequestParameters.builder()
.modelName("jev-1.13.0")
.build());
Rules and criteria
Often the answer depends on rules: what counts as spam, what a community allows, when a ticket is urgent. The model uses such rules wherever they appear, in the question or in the input, so Decision Services have no separate attributes for them. Use whichever is simpler:
- Rules that never change belong in the question. Java text blocks keep longer questions readable:
@Decide("""
Is this comment spam?
Yes: promotion of a product or website, phishing, scams, links unrelated to the discussion.
No: a genuine opinion, question or complaint, even if it is rude.""")
boolean isSpam(String comment);
- Rules that differ per call (per customer, per tenant, loaded from a database or from configuration) are passed as a parameter, and are sent as part of the input:
@Decide("Does the post violate the community rules?")
boolean violates(String post, String communityRules);
moderation.violates(post, community.rules());
Whichever you choose, give the model the rules themselves, not only a label:
a parameter plan = "enterprise" does not tell the model what the enterprise plan guarantees,
while urgentWhen = "any broken feature, or anything affecting invoices" does.
The DecisionModel API also accepts the criteria of a yes/no question
separately (yesWhen and noWhen), including structured criteria.
Thresholds
A boolean result is true when the probability of "yes" is greater than or equal to a threshold.
The threshold is 0.5 by default and can be configured with a ThresholdProvider.
It receives a ThresholdContext describing the question:
serviceInterface()andmethod(): the service and the method that is invoked;questionName(): the name of the method, or the name of the field for methods returning an object;modelName(): the model that answered, as reported by the provider (for example a pinned version rather than an alias), so that each model version can have its own thresholds. If the provider does not report it, the requested model name.
It is called on every invocation, so the thresholds can come from configuration that changes at runtime. It can be called concurrently, and for asynchronous methods on the thread that completes the call to the model, so it must be thread-safe and must not block:
SupportDesk supportDesk = DecisionServices.builder(SupportDesk.class)
.decisionModel(decisionModel)
.thresholdProvider(context -> config.getDouble( // e.g. SupportDesk.isSpam=0.9
context