Decisions API
Categorical decision requests, results, and explicitly declared workflows.
#Decisions API
Categorical decisions and explicitly declared workflows from maivn.decisions.
Decisions need maivn 2.2.0 or later and a platform deployment that serves the decisions API. Image evidence, DecisionApp and decision_run need maivn 2.3.0 or later.
The SDK uses your ordinary MAIVN_API_KEY and the single MAIVN_BASE_URL (default https://api.maivn.io). The platform selects the decision model from its signed catalog. There is no developer decision-provider key, model selector or separate service origin. Declaring a request, stage or decorator performs no inference.
See the Decisions guide for design and privacy rules and Decision examples for application patterns. The Python blocks below reuse the quick-start definitions in order.
#Quick start
maivn.decisions answers categorical questions through the mAIvn platform and falls back to your own baseline when a decision is unavailable, refused or not confident enough. The SDK never calls a decision model directly. Requests go to POST /v1/decisions with the same API key and MAIVN_BASE_URL as every other call. The platform chooses the decision model, shields explicitly marked private values and bills the call to your project.
from maivn.decisions import (
DecisionAnswer, DecisionChoice, DecisionClient, DecisionConfig, DecisionRequest,
)
question = DecisionRequest(
name='urgent',
state='Public bulletin: planned API maintenance on Saturday.',
instructions='Does this bulletin need immediate action?',
privacy='public',
choices=(
DecisionChoice(key='yes', description='Immediate action'),
DecisionChoice(key='no', description='No immediate action'),
),
)
async def baseline(request: DecisionRequest) -> DecisionAnswer:
return DecisionAnswer(value='yes', provider='local', token_category=None)
decisions = DecisionClient(
fallback=baseline,
config=DecisionConfig(min_confidence=0.8),
authorize=lambda request: request == question,
)
result = decisions.decide(question)
print(result.value, result.source, result.primary.status)Only requests declared privacy='public' and approved by authorize are sent. Mark private values inside otherwise public text with DecisionRequest(..., private_data={'customer_name': 'Priya Raman'}). The platform replaces them with placeholders before the decision model sees anything. A placeholder verdict is resolved locally and must still match a declared choice. Raw marked values reach the platform shield, never the decision model. Plain unmarked text receives no automatic redaction. Your fallback receives the original request and must enforce your application's privacy policy. Pass client=Client(...) to reuse an existing client's settings. Without one, the client reads MAIVN_BASE_URL and MAIVN_API_KEY on first use.
#The platform endpoint
Every primary attempt is one POST /v1/decisions call authenticated with your API key. The tenant comes from the key, never from the request body. No request field selects a model, tier or provider. The platform resolves the decision model from its active signed catalog and reports the model it served in each response. When the catalog has no eligible model for the request (for example, no image-capable profile for a request with images), the call answers unavailable and your fallback runs.
Limits the platform enforces on one call:
Each call also passes the same plan-limit check as other metered calls (tokens and spend), without counting a run start. A refusal there is the typed HTTP 429 that metered calls return.
Error responses:
A successful response has status of decided, refused or unavailable, the served model, one answer per question in order, and a usage receipt. Each answer is accepted, invalid or refused, and unknown token counts stay null. An answer is refused when its question failed the platform's private-value check. A whole-call refused means the shield failed or the check rejected the state or every question. The platform records no question or answer text on the run trace.
The SDK maps platform outcomes to a DecisionStatus and then to your fallback. A refused call becomes blocked, an unavailable call stays unavailable, a malformed response becomes invalid, an HTTP timeout becomes timeout, and any other HTTP failure becomes unavailable. You never see the HTTP error itself, only the fallback result.
#Decision-only run lifecycle
Use decision_run from maivn.decisions to group decisions into a durable trace. decision_run(name, *, client=None) opens POST /v1/decisions/runs and links decisions made inside the context to the returned session_id. The run name is 1 to 120 characters.
from maivn.decisions import decision_run
with decision_run('bulletin-triage') as run:
result = decisions.decide(question)
print(run.session_id)The context manager closes the run on exit through POST /v1/decisions/runs/{session_id}/complete, with {'status': 'completed'} on normal exit or {'status': 'failed'} when an exception escapes. Use async with decision_run(...) and await decisions.adecide(...) in async code. Completion failure is logged without masking the caller's exception. Applications that need explicit completion confirmation can call the authenticated HTTP completion route with the original run ID and a completed or failed status.
The platform keeps decision-only runs in its event log. A run left open for 10 minutes is closed as failed. A project is capped at about 32 open decision runs (a soft cap, and a further open answers HTTP 429 rate_limited). Closing a run twice answers HTTP 409 run_not_running.
DecisionApp(run, *, name=None) wraps a no-argument callable that returns report text, synchronously or as an awaitable. execute(*, client=None) and aexecute(*, client=None) run it inside a decision_run and return a DecisionAppResult(text, session_id). The run name defaults to the callable's name. DecisionClient(..., session_id=...) links its decisions to a specific run. Without it, decisions link to the open decision_run, or to the agent run whose local tool is executing.
Decision-only run IDs belong to the durable decision-run ledger. They are not ordinary in-process invocation handles. Generic Client.cancel(session_id) / acancel uses POST /v1/sessions/{session_id}/cancel, which deliberately returns HTTP 404 for a decision-only run. GET /v1/sessions/{session_id}/result also returns HTTP 404. Those responses do not mean the decision run was closed. Close it through the decision completion route (normally via context exit), not the ordinary session result or cancellation APIs. Decision traces and retained events use the existing authenticated session trace and event APIs.
#Decision token usage
Decision workflows report two separate categories: decision for platform decisions and llm for ordinary model invocations, including model fallbacks. Use the additive token_usage_by_category property on a decision result, builder outcome, argument preparation, matching result, or decorated call. For a list of decisions, use:
from maivn.decisions import summarize_decision_usage
usage = summarize_decision_usage([result])
print(usage.decision.input_tokens)
print(usage.llm.input_tokens)summarize_decision_usage(results, *, llm_usage=None, llm_invoked=False) also accepts the usage mapping of an ordinary invocation (llm_usage) or a flag that one ran without a count (llm_invoked), and adds it to the llm category. Blocked and disabled attempts add nothing.
Native batch followers do not count the shared receipt again. Missing counts remain None, and known_input_tokens and known_output_tokens retain the observed subtotal. A skipped agent invocation contributes zero invocation tokens while its decision receipts remain visible. Declared local fallbacks use DecisionAnswer(..., token_category=None). A decision-model backup declares token_category='decision'. Ordinary model fallbacks default to llm.
These counts are not interchangeable billing units. LLM invocation counts mirror the existing public SDK input and output surface. Provider totals and cache counts remain available through provider_usage. Price each capability with its applicable provider tariff and retain costs separately. The existing token_usage property keeps its original behavior.
#Decision reference and workflows
All symbols below are imported from maivn.decisions. These workflows are opt-in. Creating a request, builder or decorator performs no inference. Synchronous execution methods run outside an active event loop, so use their async counterparts inside async applications. The examples below reuse question, baseline and decisions from the quick start. They make platform calls when executed unless a feature is explicitly disabled.
#Requests, routing and results
Request and answer models are strict, reject extra fields and are immutable. private_data accepts a mapping or tuple of key/value pairs: up to 64 unique keys, each following the choice-key bounds, with string values of 1–4,096 characters. Mappings become sorted immutable pairs, and request.private_values returns a detached dictionary.
DecisionClient(fallback=..., config=..., authorize=..., client=None, session_id=None) requires an async fallback returning DecisionAnswer and a synchronous authorization callback. Only an exact True approves a complete request. Authorization errors, private or unknown privacy, image evidence combined with private_data, or a disabled client prevent primary dispatch. Approval is a local export permission, not a substitute for declaring private values. No vendor key or decision-model identifier is needed. An existing Client can supply the authenticated platform transport.
Use decide(request) / await adecide(request) for one question. Confidence below the threshold, refusal, malformed or out-of-choice answers, timeout and platform failure use the fallback at most once per question. Its returned value must be a declared choice. Invalid fallback answers raise ValueError, and fallback exceptions propagate. Cancellation propagates rather than starting another route. Request validation errors also propagate. Your fallback is not subject to the primary attempt's timeout.
with_fallback(callback) creates a client sharing the route, authorization and configuration with a different fallback. The original client is unchanged.
#Ordered and native batches
batch_requests = (question, question.model_copy(update={'name': 'urgent_again'}))
batch_client = DecisionClient(
fallback=baseline, config=DecisionConfig(),
authorize=lambda request: request in batch_requests,
)
results = batch_client.batch(batch_requests, max_concurrency=2, native_batch=True)
print([result.source for result in results])batch / abatch return results in input order. max_concurrency=4 bounds outstanding work by default and must be a positive integer. native_batch=False runs scalar decisions. True combines questions with identical state, private_data and images, splitting at max_batch_questions. native_batch_question_limit reports that limit (one when the primary is disabled). Approve every full request in your authorization policy. If any member of a shared packet is not approved, that packet falls back without dispatch. Private or unknown requests fall back individually. On caller cancellation or failure, outstanding batch tasks are cancelled and drained.
A native packet has one token receipt. The first member owns it. Followers expose usage_scope='batch', the batch size and usage_owner=False, without duplicating usage. Aggregate the whole result collection to retain the owned receipt.
#Before and after an invocation
Agent.decide and Swarm.decide return a DecisionInvocationBuilder. The same operation composes with their structured-output, event and follow-up builders. Stage names and question labels start with a letter and contain letters, digits, underscores, dots or hyphens, up to 128 characters. Stage names must be unique.
from maivn import Agent
plan = (
Agent(name='Bulletin assistant')
.decide(
'triage', client=decisions, questions={'urgent': question},
require={'urgent': 'yes'},
)
.decide('review', questions={'urgent': question}, at='after')
)
outcome = plan.invoke('Summarize the public maintenance bulletin.')
print(outcome.status, outcome.skipped_by)
if outcome.response is not None:
print(outcome.response.response)Each .decide(name, *, client=None, questions, at='before', require=None, max_concurrency=4, native_batch=False) stage has 1–32 questions. require is a mapping or one gate expression (see Gate expressions). A stage with no client reuses the previous stage's client. DecisionQuestion values are requests or synchronous factories taking DecisionContext. Each factory must explicitly construct its own request. The context holds the original input (also original_input), output (absent before invocation), and prior nested decisions[stage][question]. Context does not authorize exporting input or output.
A require gate skips invocation only when an accepted primary answer differs from the required choice. Any fallback preserves normal invocation, even when its value differs. A mapping requires every listed question (an implicit AND), and a mapping value may be a collection meaning any of those choices. After stages annotate the completed response and cannot have require. .map_input(mapper) explicitly changes invocation input after before stages. Without it, decisions do not change messages.
invoke / ainvoke return DecisionInvocationResult. Its status is completed or skipped, response is an InvokeResponse or None, decisions is the nested result mapping, skipped_by identifies a blocking stage and skipped_gate holds the part of that stage's gate that was false (None when completed). batch / abatch accept an iterable of inputs and max_concurrency=4, preserve order and share a bound across decisions and invocations. Invocation keyword arguments pass through to the bound scope.
.structured_output(Model), .events(include=None, exclude=None, on_event=None, auto_verbose=True) and .allow_followup_questions(**kwargs) retain the decision stages and configure the existing invocation wrappers.
stream / astream forward ordinary invocation events and add decision.stage.started, decision.stage.completed and decision.plan.completed. These are DecisionStreamEvent values, which are stream events with an extra outcome field. The final event's outcome holds the typed result locally and is excluded from serialized event data, so read it before discarding the event.
from maivn.decisions import DecisionStreamEvent
for event in plan.stream('Summarize the public maintenance bulletin.'):
if isinstance(event, DecisionStreamEvent) and event.outcome is not None:
print(event.outcome.status)#Typed argument preparation
from maivn.decisions import DecisionArgument, DecisionArgumentPreparer
prepared = DecisionArgumentPreparer(decisions).prepare([
DecisionArgument(
name='notify', question=question, values={'yes': True, 'no': False},
),
])
# Preserve the existing value when the optional decision falls back.
notify = prepared.values.get('notify', True)
print(notify, prepared.decisions['notify'].source)DecisionArgument(name, question, values) maps every choice exactly once to a boolean or string, and its name must be a valid Python identifier, excluding keywords. DecisionArgumentPreparer.prepare / aprepare accept unique named arguments, max_concurrency=4 and native_batch=False. DecisionArgumentPreparation.values contains only accepted primary mappings. Fallbacks leave the field absent so your existing argument preparation can continue. .decisions retains every result. It does not register a tool or automatically inject arguments into one.
#Function and local tool dependencies
from maivn.decisions import (
DecisionResults, DecisionStep, decision_flow, depends_on_decision,
)
@depends_on_decision(
client=decisions,
decisions=[DecisionStep(
'triage', questions={'urgent': question}, require={'urgent': 'yes'},
)],
arg_name='decision_results',
)
def notify_bulletin(message: str, decision_results: DecisionResults) -> str:
return message
call = decision_flow(notify_bulletin).invoke({'message': 'Maintenance bulletin'})
print(call.status, call.value)depends_on_decision(*, client, decisions, arg_name=None, max_concurrency=4, state=None, native_batch=False) declares metadata. Direct Python calls keep their original behavior. Use decision_flow(function) (a DecisionFunction) or register the decorated function as an SDK-local tool to execute its dependencies. A tool's injected decision parameter is hidden from its public input schema.
DecisionStep(name, *, questions, after=(), require=None, client=None, max_concurrency=4) declares a stage. require takes the same mappings and gate expressions as .decide. after names a predecessor or tuple of predecessors within the same decorator group. Unknown predecessors and cycles are rejected, and ready steps can run concurrently. A step may override its client. Factories receive a local snapshot of bound function arguments, including defaults, through DecisionContext.input. The optional synchronous state mapper narrows this snapshot once per factory stage, and its result must support deep copying. A factory explicitly chooses which content goes into its exported request before authorization. Static requests need no input snapshot. arg_name injects nested results into a parameter annotated exactly as DecisionResults. The caller must not supply that hidden parameter.
Managed invoke / ainvoke accept a mapping of function arguments, and batch / abatch accept iterables of mappings with max_concurrency=4. DecisionCallResult contains status (completed or skipped), the native return value (or None when skipped), nested decisions, skipped_by, skipped_gate and category token usage. Gates apply the same accepted-primary, three-valued rule as invocation builders. Fallbacks preserve function execution, and errors from the function propagate. DecisionResults is the mapping type stage -> question -> DecisionResult.
#Gate expressions
from maivn.decisions import all_of, any_of, match
gate = all_of(
match('kind', 'bug'),
any_of(match('severity', {'high', 'critical'}), match('vip', 'yes')),
)
plan = agent.decide('triage', client=decisions, questions=triage_questions, require=gate)require= takes a mapping or one DecisionGate built from:
Expressions nest, are immutable and hashable, and compare by value (match('severity', {'high', 'critical'}) == match('severity', ['critical', 'high'])).
Gates stay fail-open with three values. A match is true when an accepted primary answer is one of its values, false when an accepted primary answer is another value, and unknown otherwise: a fallback for any reason (disabled, unauthorized, refused, malformed, low confidence, unavailable, timeout). all_of is false when any part is false and any_of is false only when every part is false. A stage skips only when its whole gate is false, so any_of of a false part and an unknown part runs the invocation. A mapping gate behaves exactly as before.
Declaration rejects, before any decision call: a question the stage does not declare, a value that is not a declared choice of a static request (factory requests are checked when they are built, before dispatch), all_of() or any_of() with no parts, a match with no values or non-string values, and any gate on an at='after' stage. An empty mapping still means no gate.
When a stage skips, skipped_by is the stage name and skipped_gate is the narrowest false part: the match or any_of that failed inside an all_of, or the whole any_of. Streams carry it on the final event's local outcome; serialized event data is unchanged. Gates are evaluated locally and add nothing to decision requests.
#Optional candidate matching
Matching operates on an already authorized, retrieved candidate set. It neither retrieves records nor grants access to them. It is disabled by default, with no primary call while disabled.
from maivn.decisions import (
DecisionCandidateMatcher, DecisionMatchCandidate, DecisionMatchConfig,
DecisionMatchRequest, candidate_match_questions,
)
match_request = DecisionMatchRequest(
query='When is maintenance?',
candidates=(DecisionMatchCandidate(key='bulletin', text=question.state),),
baseline_keys=('bulletin',),
privacy='public',
)
# Review the complete generated requests before enabling platform matching.
approved = candidate_match_questions(match_request)
match_client = DecisionClient(
fallback=baseline, config=DecisionConfig(),
authorize=lambda request: request in approved,
)
matcher = DecisionCandidateMatcher(match_client, DecisionMatchConfig())
match_result = matcher.match(match_request)
print(match_result.selected_keys, match_result.reason) # ('bulletin',), disabledDecisionMatchCandidate has a unique local key (1–512 characters) and excerpt (1–1,200 characters). DecisionMatchRequest has query (1–16,384 characters), a tuple of up to 16 candidates, unique baseline_keys from those candidates, privacy='unknown', and max_results=5 (1–16). DecisionMatchConfig defaults to enabled=False, max_candidates=5 (1–16), max_state_characters=8192 (1–16,384 serialized characters), and timeout_seconds=1.0 (positive finite).
candidate_match_questions(request) constructs public-only questions for a local authorization allowlist. It raises ValueError for private or unknown input. Source keys and baseline keys stay local, and the model sees synthetic candidate labels and bounded text. There is no private_data option on matching requests, so use only approved public text or retain the baseline.
match / amatch, and ordered batch / abatch(max_concurrency=4), return DecisionMatchResult(selected_keys, source, reason, decisions, latency_seconds). Source is primary or baseline. Reasons are accepted, blocked, disabled, empty, oversized, rejected, timeout, unavailable or no_match. Selection can change only when every candidate question has an accepted primary yes or no answer and at least one matches. Matches preserve candidate order and are capped at max_results. Any unknown, refusal, malformed answer, timeout, privacy failure or no-match result preserves the exact baseline_keys, without truncating or reordering them. Matching uses its own local abstaining fallback rather than spending the decision client's caller fallback.
#Usage types and privacy guidance
TokenUsageCategory is decision or llm, and TokenUsageByCategory holds one TokenCategoryUsage per category. Each category has input_tokens, output_tokens, total_tokens, known_input_tokens, known_output_tokens, unknown_input_calls and unknown_output_calls. Unknown totals remain None, and known subtotals remain available. summarize_decision_usage(results) accepts a collection of decision results. All workflow outcomes expose token_usage_by_category, and aggregating native receipts counts each owner once. These counters alone do not prove cost savings or production qualification.
Ordinary InvokeResponse.privacy_guidance contains advisory over-redaction suggestions when delivered by the platform. Guidance includes the actual delivered value and does not change redaction or reveal model input. repr=False keeps it out of the response representation, but model_dump() and JSON serialization still include it. Display it only in a trusted developer interface, and do not log or persist the guidance or serialize whole responses into diagnostics. Normalized SDK event builders do not guarantee a guidance field. Decision results have no privacy_guidance field.
#Public image evidence
Categorical requests can include images=(DecisionImage.from_bytes(raw, 'image/png'),). The local authorize(request) callback receives the complete immutable request, including the exact image bytes. Mark images public only after reviewing their pixels, because text private-value shielding cannot redact an image. Requests combining images and private_data retain the caller fallback without a primary send. A fallback receives the original request and must follow the caller's privacy policy.
Images use the same authenticated POST /v1/decisions route and accounting as text. The platform checks the enrolled account's signed profile for the requested image capability before admission. An incompatible model pin keeps the caller fallback and never sends using another provider's credential. The HTTP request limit is 6 MiB. Empty images preserves the text wire format. Native batches share a call only when state, private-data declarations and exact image evidence match. Image bytes are not included in diagnostic reprs.
Native finite-tool planning can also use images from an eligible Invoke request: one user message with text and image blocks, verified inline attachments within the same four-image and size limits, and no private or redacted evidence. The platform checks the enrolled Decision profile before dispatch. An incompatible profile or unsupported message shape skips this preparation, and the ordinary model path retains its existing capability and privacy checks. Supported inline images retain their text and image order in OpenAI Responses requests, including fallback requests.
Decision image validation checks the declared container signature, not full image decoding. Storage-backed attachments, files, audio and other message shapes do not become eligible for native image Decisions through this feature.
#Export index
Every name in maivn.decisions.__all__, grouped by purpose.