Skip to content

Decision Call

Decision

Decision calls ask typed noul (true/false), choice, score and box questions about shared state. Providers return probabilities that calling code can use to make decisions.

The operation is part of the AI module. Install a provider that implements Decision, then choose the operation's default provider and model in the AI settings. For example, TypeSafe AI Provider connects Jev to this API.

Question Answer
noul Probability that the statement is true, with no separate confidence
choice Chosen option, probability per option, confidence
score Probability-weighted level, probability per level, confidence
box Edges of a box around one target in an image file, confidence

The question types and answer keys follow the SystemOne protocol, where a "noul" is a true/false judgment answered with the probability of true. See TypeSafe's System One concepts and the SystemOne protocol glossary.

A request contains text or structured state and one or more questions keyed by caller-defined IDs. Each question supplies its own instructions and criteria. Keep related independent questions in one request when they judge the same state. Providers map the normalized contract to their own wire formats. Question IDs correlate answers with questions; providers control whether IDs reach a model.

Example normalized Decision call

use Drupal\ai\OperationType\Decision\DecisionInput;
use Drupal\ai\OperationType\Decision\Value\ChoiceQuestion;
use Drupal\ai\OperationType\Decision\Value\NoulQuestion;
use Drupal\ai\OperationType\Decision\Value\ScoreQuestion;

$manager = \Drupal::service('ai.provider');
$default = $manager->getDefaultProviderForOperationType('decision');
if (empty($default['provider_id']) || empty($default['model_id'])) {
  throw new \RuntimeException('Configure a default Decision provider and model.');
}
$provider = $manager->createInstance($default['provider_id']);
$input = new DecisionInput(
  ['ticket' => ['message' => 'I was charged twice. Please refund the duplicate.']],
  [
    'refund_requested' => new NoulQuestion('Is the customer asking for money back in `ticket.message`?'),
    'team' => new ChoiceQuestion('Which team should handle `ticket`?', [
      'billing' => 'Charges, invoices, refunds or subscriptions',
      'technical' => 'Bugs, errors or integration problems',
      'sales' => 'Pricing, plans or account questions',
    ]),
    'frustration' => new ScoreQuestion('How frustrated does the customer appear in `ticket.message`?', [
      'Calm and matter-of-fact',
      'Frustrated but civil',
      'Very angry or threatening to leave',
    ]),
  ],
);
$response = $provider->decision($input, $default['model_id'], ['my_module'])->getNormalized();
$refund_likely = $response->getNoul('refund_requested')->isLikely(0.7);
$team = $response->getChoice('team');
$needs_review = !$team->isConfident(0.8);
$frustration = $response->getScore('frustration');
$frustration_value = $frustration->isConfident(0.6) ? $frustration->getScore() : NULL;
$tokens = $response->getUsage()->input;

decision() requires a DecisionInput. Construct one directly, or use DecisionInput::fromArray() / DecisionInput::fromString() for normalized array or JSON definitions. A noul question can be represented as ['type' => 'noul', 'instructions' => '...'], with optional 'criteria' => ['true' => '...', 'false' => '...']. Its normalized answer is ['type' => 'noul', 'noul' => 0.93], read with getProbability() or isLikely(). isLikely($threshold) is TRUE only when the probability exceeds the threshold, so a tie at exactly 0.5 (an undecided or unanswerable question) is not likely. Choice and score answers both provide getConfidence() and isConfident(), whose minimums are inclusive; noul answers have no confidence.

Providers map their model's uncertainty into these shared values: a low confidence, or a noul probability near 0.5, means the model cannot tell. The helpers above therefore work the same way on every model, though how probabilities are calibrated still varies, so validate thresholds per model. Some models also return extra per-answer fields, for example imajev's unknown_probability and abstained. They are available unchanged through AnswerInterface::getRaw(); their meaning is provider-specific, and AI core does not interpret them. Normalized answer arrays may gain optional keys in later releases, so ignore keys you don't recognize.

Structured state, instructions and criteria must use PHP arrays containing only arrays, JSON scalars and NULL. Nested PHP objects (including JsonSerializable), resources, non-finite numbers and invalid UTF-8 are rejected; decode JSON with associative arrays. This keeps guardrail inspection and the serialized request consistent. Content is checked again before execution.

Keep thresholds and actions in calling code. Confidence describes distribution concentration, not factual correctness or permission to act. A common pattern is tiered: act automatically at high confidence, ask for review or confirmation in the middle, and abstain or route to a person at low confidence. Set each threshold by what a wrong action would cost: a read-only suggestion can accept less certainty than a refund or a deletion. For noul answers, apply the same idea to the probability, keeping undecided values near 0.5 out of automatic actions. Invalid or incomplete answers raise AiBrokenOutputException; missing probabilities are not replaced with zero. Model calibration and useful thresholds must be validated for the intended application. Implementing Decision does not itself guarantee calibrated probabilities.

Choice and score answers validate probability totals, the chosen winner and the probability-weighted score. Providers that round values for transport can declare an AnswerPrecision when constructing answers. Validation then checks whether normalized probabilities within those rounding intervals can produce the reported winner or score. This supports diffuse distributions where many rounded values together exceed a fixed sum tolerance. All-zero distributions and nonfinite or out-of-range values are always rejected.

Without an explicit precision declaration, the existing 0.02 total/winner tolerance and score tolerance of 0.02 times the scale range still apply. Values are never renormalized or replaced to repair an invalid answer. Read getScore() as the provider-reported score. Code that needs the exact mean of the returned probabilities can compute it from getProbabilities(). getPrecision() exposes the adapter's declaration; pass it separately when reconstructing an answer. toArray() and raw payloads keep their existing shape.

The current contract supports text or structured state, optionally with image files, and noul, choice, score and box questions. Choice questions need at least one option and score questions need at least two levels. Minimum and maximum counts and supported field shapes belong to the selected provider/model; shared values impose no provider-specific limits. Score levels may be plain strings or structured arrays (for example what and examples keys). Providers echo them back in the answer legend unchanged; ScoreAnswer::getLevelDescription() renders either form as text.

Refusals

Models that declare DecisionRefusals may decline an individual question, while the other questions in the request are still answered. The refused question's answer is a RefusalAnswer, normalized as ['type' => 'refusal']; any provider detail is available through getRaw(). Check for a refusal before reading a typed answer:

if ($response->isRefused('team')) {
  // No answer: route to a person, or keep the current value.
}
else {
  $team = $response->getChoice('team');
}

getRefusals() lists the refused question ids. getNoul(), getChoice(), getScore() and getBox() throw \UnexpectedValueException when an answer is missing or of another type. For a refused question they throw AiDecisionRefusedException, a subclass whose questionId property names the question, so existing catch blocks keep working. A refusal is never a negative answer: don't read it as false, as one of the options or as the lowest level. Models that don't declare DecisionRefusals never refuse; a refusal from them raises AiBrokenOutputException.

Files

Models that declare DecisionImageFiles also judge image files sent with the request. Files are ordered and providers keep that order. By convention the first file is the reference and the second the target, so questions can refer to "the photo" or "the second photo".

use Drupal\ai\OperationType\GenericType\ImageFile;

$input = new DecisionInput(
  ['listing' => ['title' => "Men's suede boat shoes", 'color' => 'red']],
  ['color_matches' => new NoulQuestion('The product in the photo matches `listing.color`.')],
);
$input->setFile(new ImageFile(file_get_contents($photo_path), 'image/jpeg', 'listing.jpg'));
// Or several, in order: $input->setFiles([$reference, $target]);
// $input->addFile($another) appends one.

getFile() returns the first file and getFiles() all of them; setFile(NULL) removes them. Each file needs contents and a MIME type. Only images are supported: other file types raise AiBadRequestException, and a model that does not declare DecisionImageFiles raises AiMissingFeatureException, before any request is sent. DecisionCapabilities::$maxFiles is the model's known file limit.

toArray() lists files under files, each with its filename, mime_type and base64 contents, and fromArray() accepts the same shape. toString(), which AI Logging stores, lists each file's name, MIME type and size but never its contents, so fromString() returns the request without its files.

Box questions

Models that declare DecisionBox answer box questions: where one target is in an image file. The answer is the smallest box around the target, given as four edges in fractions of the image size, measured from its top-left corner: left and right of the width, top and bottom of the height. DecisionBox requires DecisionImageFiles, and a box question in a request without an image file raises AiBadRequestException before any request is sent.

use Drupal\ai\OperationType\Decision\Value\BoxQuestion;
use Drupal\ai\OperationType\GenericType\ImageFile;

$input = new DecisionInput('A kitchen counter.', [
  'mug_present' => new NoulQuestion('Is there a coffee mug in the photo?'),
  'mug' => new BoxQuestion('the coffee mug in the photo'),
]);
$input->setFile(new ImageFile(file_get_contents($photo_path), 'image/jpeg', 'kitchen.jpg'));
$response = $provider->decision($input, $model_id, ['my_module'])->getNormalized();

if ($response->getNoul('mug_present')->isLikely(0.8)) {
  $mug = $response->getBox('mug');
  // ['left' => 264, 'top' => 100, 'right' => 504, 'bottom' => 328] for a
  // 600 × 400 photo.
  $crop = $mug->toPixels(600, 400);
  $sure = $mug->isConfident(0.6);
}

Box questions take no criteria. A box is always returned, even when the target is absent, so ask a noul question about whether it is there next to the box question. The box's confidence is not that signal: for an absent target a model may box something similar, and be sure of it. Each box question finds one target; ask one question per target. When the request has several images, name the image to search in the instructions.

getBox() returns the edges keyed top, bottom, left and right, and getConfidence() how sure the model is of the box. Edges may be equal, because rounding for transport can collapse a very thin box, but never inverted. AnswerPrecision does not apply to box answers.

toPixels() converts the edges to pixels for an image of a given size: the image the box refers to, or a copy with the same aspect ratio and orientation. It rounds outward (left and top down, right and bottom up), so the pixel box always contains the answered box and a crop to it never cuts the target off. Right and bottom are exclusive, as in a crop rectangle, so the width is right - left. To crop with Drupal's image toolkit:

$box = $response->getBox('mug')->toPixels($image->getWidth(), $image->getHeight());
$image->crop($box['left'], $box['top'], $box['right'] - $box['left'], $box['bottom'] - $box['top']);

Decision Interfaces & Models

The following files define the methods available when doing a decision call as well as the input and output. Question and answer value objects live in Drupal\ai\OperationType\Decision\Value.

Provider authors should read the Decision provider contract.

Decision guardrails

Drupal's built-in guardrails primarily consume chat inputs. Decision supplies an operation-specific handler through AI's ai.guardrail_operation_handler service tag. It runs only plugins that implement Drupal\ai\Guardrail\DecisionGuardrailInterface and declare the phase through supportsOperation('decision', $phase); the built-in checks below do both. Global guardrail sets and sets attached by callers or automators both apply. No guardrails are enabled automatically.

AI attaches global sets at priority 100. Independent Decision input/output validation runs at 20, and its guardrail handler runs at 10, ahead of ordinary logging and observability subscribers, like AI's ChatGuardrailHandler for chat.

Check Phase Inspected content
RegEx Before and after Before generation: keys and values of the state (numbers included), question instructions and criteria. Afterward: the chosen option and score legends; box answers carry no text. Strings retain their original characters. Question IDs, types, probabilities, scores, confidence, box edges and file contents are not scanned.
Input Length Limit Before Character count of DecisionInput::toString(): the pretty-printed JSON form of the whole input, so state, all questions, indentation and JSON syntax count. Files count by their listed name, type and size, not their contents.
Moderation Before State, question instructions and criteria; structured values are serialized as JSON. Moderation is text-only, so a request with files is stopped, and so is every request with a box question.

Chat message-selection settings do not restrict Decision checks to part of the input. Token-based length limits, topic checks, streaming checks, unsupported phases/plugins, and rewrite results raise AiSetupFailureException when they are in a set the caller attached. Global sets apply to every operation, so such checks there are skipped and logged as a warning instead. All attached pre/post configurations are checked before the Decision provider is called. Custom plugins can implement DecisionGuardrailInterface, declare supported phases in supportsOperation(), and return PassResult or StopResult without mutating data. supportsOperation() may throw AiSetupFailureException to explain a configuration that cannot apply, as the built-ins do for a missing pattern or token counting. Subclasses of the built-in checks inherit their Decision support; override supportsOperation() to opt out. No built-in check inspects file contents; a custom plugin receives the whole input, files included.

Scores aggregate separately for each set and phase. Reaching a set's threshold raises AiDecisionBlockedException, which extends AiUnsafePromptException and exposes phase and results. No synthetic answer is returned.

A provider may also block a whole request with its own safety filter. That raises a plain AiUnsafePromptException carrying the provider's reason, never answers or refusals, so one catch block covers both kinds of block:

try {
  $response = $provider->decision($input, $model_id)->getNormalized();
}
catch (AiUnsafePromptException $e) {
  // Blocked by guardrails or by the provider: nothing was decided.
}

Independent typed answer validation runs even when no guardrails are configured. AI-powered checks share AI's per-fiber recursion protection across operation types; deterministic checks still run on nested requests.

Decision Explorer

If you install the AI API Explorer, you can go to configuration > AI > AI API Explorer > Decision Explorer under /admin/config/ai/explorers/decision_generator. It provides a form for state, questions and provider selection, shows the probabilities and prints the equivalent PHP. Provider selection uses the ai_provider_configuration element: it lists only models declaring what the parsed request needs, and shows the selected model's declared features, Decision limits and any request problems. Incompatible selections and entered criteria are preserved for correction. Changing the model updates that summary without rewriting the request or clearing chosen images. "Default" is resolved to the site default when you ask. Two optional image fields send files with the request, in order. Model filtering cannot see uploads, so image support is checked when you ask, and editing the state or questions clears the chosen images. Box answers show their edges, confidence and the box in pixels for each uploaded image.

Decision field automators

AI Automators provides boolean, list and numeric field rules that use any Decision provider. See Decision rules.