Skip to content

Documentation navigation

Decision Examples

Runnable public SDK examples for categorical decisions and declared workflows.

#Decision Examples

These examples use maivn.decisions (maivn 2.2.0 or later) and your ordinary MAIVN_API_KEY in the process environment. Enabled terminal calls contact the platform, so they are not free offline demonstrations. Set DecisionConfig(enabled=False) to run the code path against your fallback only.

Run the Python blocks in order in one script, because later blocks reuse the first definitions. Use async terminal methods from an async event loop. The guide explains privacy and fallback rules and where cost can change. The complete reference covers every exported type and option, plus the platform limits and error codes.

#Define an authorized request and fallback

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.

Python
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.

#Ordered native batch

Python
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 returns results in input order. native_batch=True combines questions with identical state, private_data and images into one platform call, splitting at max_batch_questions (32 by default). If any member of a shared packet is not approved by authorize, that packet falls back without dispatch. A native packet has one token receipt. The first member owns it, and followers expose usage_scope='batch' and usage_owner=False. See ordered and native batches.

#Gate and review an invocation

Agent.decide and Swarm.decide return a DecisionInvocationBuilder, which composes with the structured-output, event and follow-up builders.

Python
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)

A require gate skips the invocation only when an accepted primary answer differs from the required choice. Any fallback preserves the normal invocation, even when its value differs. After stages annotate the completed response and cannot have require. invoke returns a DecisionInvocationResult with status (completed or skipped), response, the nested decisions and skipped_by. Stage names, question factories and map_input are covered in before and after an invocation. Any-of choices, OR and nested gates are in the decision gate examples.

stream forwards ordinary invocation events and adds decision.stage.started, decision.stage.completed and decision.plan.completed. The final event's outcome holds the typed result locally and is excluded from serialized event data.

Python
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)

#Prepare explicit arguments

Python
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. prepared.values holds only accepted primary mappings. A fallback leaves the field absent so your existing preparation continues, and prepared.decisions keeps every result. It does not register a tool or inject arguments into one.

#More patterns

See function and local-tool dependencies and optional candidate matching for complete runnable patterns. Matching stays disabled until explicitly enabled. Duplicate questions in the batch example illustrate receipt ownership. Use distinct instructions for useful application questions.

#Categorize a public image

Images need maivn 2.3.0 or later.

Python
from pathlib import Path
from maivn.decisions import DecisionChoice, DecisionImage, DecisionRequest

image_question = DecisionRequest(
    name='public-package',
    state='Does the photographed public demonstration package have visible damage?',
    images=(DecisionImage.from_bytes(Path('public-package.png').read_bytes(), 'image/png'),),
    instructions='Choose yes only when damage is visible; otherwise choose no.',
    choices=(
        DecisionChoice(key='yes', description='Visible damage'),
        DecisionChoice(key='no', description='No visible damage'),
    ),
    privacy='public',
)
# Reuse a DecisionClient whose authorize callback reviews this exact image
# and whose fallback handles unavailable or uncertain image decisions.
result = decisions.decide(image_question)

The same ordinary mAIvn API key authenticates image decisions. The platform chooses an authorized image-capable profile, and the caller supplies no provider credential or model selector. Only submit images approved as public. private_data cannot redact pixels and is blocked when images are present. Native finite-tool planning can also use supported inline images from eligible ordinary messages. See the image contract for its limits and fallback behavior.