Decision provider contract
This page is for provider authors implementing the Decision operation.
Implementing a Decision provider
Require an AI version that includes the Decision operation. A Decision provider:
- Implements
Drupal\ai\OperationType\Decision\DecisionInterfacealongside the normal AI provider interface and base class. That means three methods:getDecisionCapabilities(),validateDecisionInput()anddecision(DecisionInput $input, string $model_id, array $tags = []): DecisionOutput. - Returns
decisionfromgetSupportedOperationTypes(). - May add a
decisionentry todefinitions/api_defaults.yml. Itsconfigurationoptions appear in the Explorer and Automator forms, and itsinputtext documents the request. The entry is optional. - Maps wire formats inside the provider, in both directions.
Callers should go through the AI provider manager's proxy, so events, early
validation, guardrails and logging run. The test-only ai_decision_test
module (tests/modules/ai_decision_test) demonstrates a provider without
authentication or HTTP calls.
Capability contract
DecisionInterface requires both getDecisionCapabilities(string $model_id) and
validateDecisionInput(DecisionInput $input, string $model_id): void. The immutable
DecisionCapabilities declaration contains explicit AiModelCapability enum
cases and nullable minChoiceOptions, maxChoiceOptions, maxScoreLevels,
maxQuestions and maxFiles limits.
Null means unknown, not unlimited. Resolve aliases using provider-owned metadata
without recursive filtered discovery or inference.
The constructor rejects inconsistent declarations with
InvalidArgumentException:
- Only Decision cases may be declared, and at least one of the noul, choice
and score question types is required. Box questions need an image, so
DecisionBoxdoes not count as that question type. - Each feature needs its prerequisite:
DecisionNoulCriterianeedsDecisionNoul.DecisionStructuredNoulCriterianeedsDecisionNoulCriteria.DecisionChoiceDescriptionsneedsDecisionChoice.DecisionStructuredChoiceDescriptionsneedsDecisionChoiceDescriptions.DecisionStructuredScoreLevelsneedsDecisionScore.DecisionBoxneedsDecisionImageFiles.maxChoiceOptionsneeds choice support and must be at least 1.minChoiceOptionsneeds choice support, must be at least 1 and must not exceedmaxChoiceOptionswhen both are known. Declare it for models that reject a choice question with too few options, so the validator, the forms and the shared contract suite know the smallest request the model takes. Leaving it undeclared promises that the model accepts a single option: the contract suite then sends one-option choice questions and expects them to be accepted.maxScoreLevelsneeds score support and must be at least 2.maxQuestionsmust be at least 1. A value above 1 requiresDecisionMultipleQuestions, andmaxQuestions: 1must not declare it.maxFilesneedsDecisionImageFilesand must be at least 1.
The validator derives the required capabilities from the request itself:
| Capability | Required when the request has |
|---|---|
DecisionNoul, DecisionChoice, DecisionScore, DecisionBox |
A question of that type |
DecisionMultipleQuestions |
More than one question |
DecisionStructuredState |
Array state |
DecisionStructuredInstructions |
A question whose instructions are an array |
DecisionNoulCriteria |
A noul question with true/false descriptions |
DecisionStructuredNoulCriteria |
A noul true/false description given as an array |
DecisionChoiceDescriptions |
A choice option with a description. Options built with ChoiceQuestion::fromOptions() have none. |
DecisionStructuredChoiceDescriptions |
A choice description given as an array |
DecisionStructuredScoreLevels |
A score level given as an array |
DecisionImageFiles |
One or more image files (MIME type image/*) |
DecisionRefusals is an output capability: no request requires it. Declare it
only when your API can decline an individual question while answering the
others. It allows RefusalAnswer in responses (see
Returning answers); for models that don't declare it, a
refusal is broken output.
For example, a provider supporting only basic noul requests can implement:
public function getDecisionCapabilities(string $model_id): DecisionCapabilities {
return new DecisionCapabilities([AiModelCapability::DecisionNoul], maxQuestions: 1);
}
public function validateDecisionInput(DecisionInput $input, string $model_id): void {
DecisionRequestValidator::validate($input, $this->getDecisionCapabilities($model_id), $this->getPluginId(), $model_id);
// Check any additional provider restrictions here, without inference.
}
Import DecisionCapabilities from Drupal\ai\OperationType\Decision\Value, the
validator from Drupal\ai\OperationType\Decision, and the enum from
Drupal\ai\Enum. At the start of every decision() implementation, call
$this->validateDecisionInput($input, $model_id) on the final request before
transport. The interface cannot force this call: provider tests must exercise
direct and proxied calls and assert zero transport requests on rejection.
Bridges from other operations must check their generated Decision input too.
validateDecisionInput() follows AI's validate{Operation}Input() convention
(see Validating operation input).
Before dispatching PreGenerateResponseEvent, the proxy calls it on the same
configured provider instance. Unsupported requests therefore cannot trigger paid
pre-generation guardrails. A rejection dispatches one AiExceptionEvent with
request metadata and no pre/post-generation event. Existing exception recovery
subscribers may provide a replacement output, whose validity they own.
Providers must still validate inside their operation method: subscribers can change input or configuration after the early check.
DecisionRequestValidator::validate() runs its checks in this order:
- The input's structural and JSON-content checks (
DecisionInput::validate()), including that every file has contents and a MIME type. - A request must have at least one question.
- Every file must be an image.
- Every derived capability must be declared.
- Counts must be within the declared question, choice, level and file limits. Choice options have a known minimum as well as a known maximum.
- A box question needs at least one image file.
Invalid content, unknown question types, empty requests, files that are not
images, counts outside known limits and box questions without an image raise
AiBadRequestException. Unsupported features raise
AiMissingFeatureException. Messages name the provider, the model and, where
relevant, the question ID. Existing proxy exception events handle these errors.
Building a question or input directly still throws InvalidArgumentException
for structural errors, and typed answer validation and guardrails still apply.
Do not change input, drop criteria, flatten unsupported fields, split questions,
or truncate options to fit a model.
Send DecisionInput::getFiles() in order, with their MIME types, in the
model's wire form: for example multipart file parts, or data URLs in JSON.
Never drop or reorder files, or re-encode them with loss. Reject formats or
sizes the model cannot take in validateDecisionInput(), before transport.
Use DecisionRequestValidator::getRequiredCapabilities($input) with AI's existing
capability-array discovery methods. Implement strict isUsable() and
getConfiguredModels() filters: every requested feature must be declared for the
model. Neither method may run inference; isUsable() should not need model
discovery either. For example:
public function getConfiguredModels(?string $operation_type = NULL, array $capabilities = []): array {
// listModels() stands for the provider's own model lookup.
$models = $this->listModels($operation_type);
if ($operation_type === 'decision' && $capabilities !== []) {
$models = array_filter($models, fn (string $id): bool => $this->getDecisionCapabilities($id)->supports($capabilities), ARRAY_FILTER_USE_KEY);
}
return $models;
}
Forms list models with AiProviderPluginManager::getModelsWithCapabilities(),
directly or through the ai_provider_configuration element's #capabilities.
Unlike the proxy's getConfiguredModels(), it lists a manually configured
model only when the provider declares it, or when the model's stored settings
enable each capability. Providers that accept model IDs outside their own
discovery can override modelSupportsCapabilities() to vouch for them.
Validation rechecks the model's profile, and numeric counts are checked against
the actual request. Providers can inherit the offline contract test suite below
instead of copying these assertions.
A future failover caller must validate each candidate against the unchanged input. AI does not implement failover. Declared compatibility establishes field semantics, not equivalent scores, accuracy or calibration. Evaluate intended fallback models on representative data before reusing thresholds.
Returning answers
decision() returns new DecisionOutput($response, $raw, $metadata):
$rawis the decoded wire response.$metadataholds provider details, such as the resolved model.$responseisnew DecisionResponse($answers, $model, $usage):$answersis keyed by the request's question IDs. Cast IDs to strings, and never renumber numeric-looking IDs.$modelis the model that actually answered, for example a resolved alias; fall back to the requested ID.$usageis aTokenUsageDto. Leave counts the API doesn't report asNULL, never zero. AI Logging reads it throughDecisionOutput::getTokenUsage().
Build answers with the typed constructors (NoulAnswer, ChoiceAnswer,
ScoreAnswer, BoxAnswer, RefusalAnswer) or with AnswerFactory::fromArray() from these
normalized shapes:
| Type | Normalized answer |
|---|---|
noul |
['type' => 'noul', 'noul' => 0.93] (probability that the statement is true) |
choice |
['type' => 'choice', 'choice' => 'billing', 'probabilities' => ['billing' => 0.8, 'sales' => 0.2], 'confidence' => 0.8] |
score |
['type' => 'score', 'score' => 1.35, 'legend' => ['Calm', 'Frustrated', 'Angry'], 'probabilities' => [0.1, 0.45, 0.45], 'confidence' => 0.6] |
box |
['type' => 'box', 'box' => ['top' => 0.25, 'bottom' => 0.82, 'left' => 0.44, 'right' => 0.84], 'confidence' => 0.92]. Edges are fractions of the image size from its top-left corner: left and right of the width, top and bottom of the height. Convert other coordinate systems, such as pixels or center and size, to these edges. |
refusal |
['type' => 'refusal'], for a question of any type, only from models that declare DecisionRefusals |
Pass the wire answer as the raw argument, so callers can reach it through
getRaw(). The factory keeps the array it was given.
Map your model's uncertainty into the shared values as they are defined here,
so that isLikely(), isConfident() and every consumer handle it without
provider-specific code:
confidencesays how concentrated a choice or score distribution is: 1.0 when all probability is on one option, lower as it spreads.- A noul probability near 0.5 means the model cannot tell.
For example, a model that reports a separate "unknown" probability u can
renormalize choice and score probabilities over the real options, scale
confidence by 1 - u, and report a noul as P(true) + u / 2, splitting the
unknown share evenly so that a fully unknown statement lands at 0.5. This is
what imajev does. Describe your mapping in your module's documentation so
callers can choose thresholds.
Don't apply decision policy: return an answer for every question, keep the
chosen option, and leave thresholds and abstaining to callers. Keep the
original fields, such as an unknown probability, an abstention flag or a
calibration version, unchanged in raw.
The one exception is a question the API itself declined. If the model declares
DecisionRefusals, return a RefusalAnswer for it, with the wire answer as
raw, and keep the other answers. Never fabricate probabilities for a refused
question, and never turn low confidence into a refusal. Bridges from other
operations, such as text classification or moderation built on Decision, must
handle a refusal explicitly and never read it as a negative answer: a
moderation bridge should fail closed and treat the input as flagged.
A refusal is always about one question. When the API blocks the whole request,
for example because its own safety filter rejects the input, throw
AiUnsafePromptException with the API's reason code and message in the
exception message. Check for the block before building answers, so that a
response without answers isn't reported as broken output, and map a block that
arrives as an HTTP error the same way. Never return answers for a blocked
request, and never turn the block into refusals: the model doesn't need to
declare DecisionRefusals for this. AiDecisionBlockedException is reserved
for AI's guardrails, which supply its phase and results.
Check every answer against its question with
AnswerValidation::forQuestion($answer, $question, $allow_refusal), passing
whether the model declares DecisionRefusals, for example
$this->getDecisionCapabilities($model_id)->has(AiModelCapability::DecisionRefusals):
- Answer types must match their questions. A refusal is valid for any question
type, but only when
$allow_refusalis TRUE. - Choice probabilities must cover exactly the requested option keys.
- Score probabilities and legend must cover exactly the requested levels, and the legend must repeat the requested level descriptions unchanged, whether they are strings or structured.
Report a missing answer, or any InvalidArgumentException from answer
construction or validation, as AiBrokenOutputException. On proxied calls AI
also checks the typed answers after generation, including refusals against the
model's declaration, but direct calls rely on the provider's own checks.
Rounded answers
Adapters whose wire format rounds probabilities should explicitly supply
Drupal\ai\OperationType\Decision\Value\AnswerPrecision:
$precision = new AnswerPrecision(probabilityDecimals: 2, scoreDecimals: 2);
$answer = AnswerFactory::fromArray($normalized_wire_answer, $precision);
The optional trailing argument is also accepted by ChoiceAnswer and
ScoreAnswer constructors and factories. Decimal counts range from 0 to 15;
a null score precision means the score is exact. Each rounding interval is
half a unit in the last declared decimal place, clipped to the probability
range. Validation requires a feasible normalized distribution and winner or
weighted mean within those intervals. It does not rewrite reported values.
Zero totals, nonfinite values, missing candidates/levels and impossible means
still fail. Raw payloads and normalized array shapes are unchanged.
Precision is trusted adapter metadata, never read from response data. Providers
that omit it retain the existing fixed tolerances. Use getPrecision() when
reconstructing a typed answer that already carries a declaration.
Contract tests
Provider modules can inherit the offline Decision requirements from
Drupal\Tests\ai\Kernel\OperationType\Decision\DecisionProviderContractTestBase.
The suite loads the real provider through Drupal's plugin manager, exercising
both direct and proxied calls. It needs a kernel-test database, but no API
credentials or live inference service.
The test helpers ship with drupal/ai; Drupal's core PHPUnit bootstrap
automatically loads the Drupal\Tests\ai namespace. No production autoloader
changes or separate test package are needed.
Adopting the suite
Create a concrete class in your provider's tests/src/Kernel directory extending
DecisionProviderContractTestBase. Add your provider to the inherited module
list (system, user, file, key, ai) and implement these five protected
methods:
| Method | Fixture contract |
|---|---|
getProviderId(): string |
Real plugin ID. The base creates the proxy and obtains the underlying plugin itself. |
getModelFixtures(): array |
Complete mocked catalog: model ID to expected DecisionCapabilities, including advertised aliases. Declare capabilities and limits explicitly, independently of the provider implementation. |
configureContractProvider(): void |
Install provider config and dummy credentials, and replace its transport. Called after kernel setup and AI config installation. Mock discovery separately and fail unexpected requests. |
queueDecisionResponse(array $response): void |
Queue a response with model, optional usage (input, output, total) and answers keyed by question ID. Translate normalized fields to wire names only. Preserve missing fields and malformed values. |
getCapturedDecisionRequests(): array |
Chronological inference requests, each containing model and input in DecisionInput::toArray() format. Decode wire names and aliases back to the public API; preserve all input fields. Files go under files in order, each with mime_type and base64 contents; filename is not compared. Exclude model discovery. |
The smallest complete adapter is TestDecisionProviderContractTest. Its five hooks configure the existing test provider using Drupal state. The additional fault tests verify that the inherited assertions actually fail when validation is skipped or input is changed.
TypeSafe's TypeSafeAiDecisionContractTest demonstrates external adoption with
mocked Guzzle transport, model discovery, credentials and wire-format mapping.
Keep assertions about your actual endpoint, headers and wire encoding in your
provider tests: a decoder in a contract adapter cannot independently prove its
own wire-format translation.
Record attempted inference at the mock transport boundary, including calls that throw, so failures cannot disappear from the request counter. Disable inference response caching in the fixture configuration: each queued case must exercise the real provider parser.
Add both your module's test group and ai_decision_contract to the concrete
class. Follow the examples' PHPUnit attributes and matching docblock annotations
for Drupal 10/11 compatibility. The normal module test run then includes the
inherited tests; a separate CI job is unnecessary.
What is checked
- Decision operation registration, model profiles, aliases, and strict filtering requiring every requested capability. Declaration and discovery never infer.
- Every question type, structured state/instructions, descriptions, criteria,
and multiple questions. Unsupported features fail with
AiMissingFeatureException. - Image files, one and two, in order: a 300 × 300 PNG and a 300 × 300
baseline JPEG, which every known image model accepts. Models that do not
declare
DecisionImageFilesreject them withAiMissingFeatureException; files that are not images fail withAiBadRequestExceptionfor every model. - Box questions with an image. Models that declare
DecisionBoxreturn the edges unchanged, including a box rounded to equal edges, and reject a box question without an image withAiBadRequestException. Malformed boxes (missing or out-of-range edges, inverted edges, a missing confidence) raiseAiBrokenOutputException. - Declared count boundaries, overflows and shortfalls, including
maxFilesandminChoiceOptions. Empty execution and invalid content introduced through references fail withAiBadRequestException. - Validation and rejection never perform inference. Direct calls are tested so proxy validation cannot hide a provider that omits its own checks.
- Validation/execution preserve input. Successful transport preserves state, questions and criteria without splitting, flattening or truncation.
- Typed responses preserve answers, model IDs and usage. Missing usage remains
unknown. Malformed answers, incomplete distributions, invalid totals,
inconsistent winners/scores and changed legends raise
AiBrokenOutputException, including on direct calls. Values rounded for transport (a 0.99 total, a score 0.01 from the rounded mean) are accepted unchanged: under the provider's declaredAnswerPrecision, or withinAnswerValidation::TOLERANCEwithout one. - Models that declare
DecisionRefusalsaccept a response that refuses one question and answers the others; the refusal is reported byisRefused()and the typed getter throwsAiDecisionRefusedException. Any other model rejects a refusal withAiBrokenOutputException. - The suite has no case for a block by the provider's own filter, because APIs
report it differently and many never block. A provider that can be blocked
tests its own mapping to
AiUnsafePromptException. - Numeric-looking identifiers remain distinct when answers arrive in a
different order. Proxy success events retain caller tags and request context;
provider-thrown errors produce exception events. A request the proxy rejects
during early validation produces one
AiExceptionEventand no pre-generation event.
Assertions include model, invocation mode and scenario in failure messages.
Each case uses fresh inputs, and expected capabilities are not obtained from
the provider under test. Never mock decision(), validateDecisionInput() or
getDecisionCapabilities() in a provider's contract adapter.
Models need not support all features. Unsupported cases test rejection instead
of being silently skipped. A NULL count limit is unknown and generates no
synthetic boundary: it is not a promise of unlimited capacity. Known maxima
generate maximum and maximum-plus-one inputs, and a known choice minimum above
one generates minimum and minimum-minus-one inputs. Every generated choice
question uses the declared minimum number of options, or one option when the
minimum is unknown. Choose representative model fixtures that can be exercised
within the test runner's memory limits.
The fixtures use short generic instructions and criteria. If a provider has additional field restrictions, add provider-specific tests and adjust fixture content without weakening shared assertions or advertising unsupported shapes.
Classification/moderation bridges, authentication, retry/cache behavior,
logging storage, calibration and detailed guardrails remain in their existing
test suites. Discovery HTTP calls are allowed through the configured mock;
they do not count as inference. Proxy-added manual models are outside the
provider filtering assertions; forms exclude undeclared ones through
getModelsWithCapabilities().
Running tests
From the Drupal Composer project root, with SIMPLETEST_DB and
BROWSERTEST_OUTPUT_DIRECTORY configured for an isolated test environment:
vendor/bin/phpunit -c web/core/phpunit.xml.dist \
--group ai_decision_contract \
web/modules/contrib/ai/tests/src/Kernel/OperationType/Decision
vendor/bin/phpunit -c web/core/phpunit.xml.dist \
--group ai_decision_contract \
web/modules/contrib/ai_provider_typesafeai/tests/src/Kernel
Adjust the provider path for your installation. Also run the complete Decision and provider unit/kernel suites and your existing coding-standard/static checks. Exercise both supported Drupal major versions when changing this shared test interface. Provider authors own their expected profiles and wire fixtures; AI owns the common assertions and scenario catalog.