# fastdecisions


Pass shared evidence (text, JSON, [`aidialog.msg_parts.Msg`](https://AnswerDotAI.github.io/aidialog/msg_parts.html#msg) histories, or media) alongside canonical [`noul`](types.html#noul), [`choice`](types.html#choice), [`score`](types.html#score), or [`box`](types.html#box) questions via [`adecide`](core.html#adecide), [`decide`](core.html#decide), or [`Decider`](core.html#decider), and swap providers with `model=`. Each adapter runs on `fastspec.OpenAPIClient` with offline bundled specs.

## APIError

``` python
def APIError(
    message:str, *, provider:str='', model:str='', endpoint:str='', status_code=None, error_type:str='', code=None,
    request_id:str='', retryable=None, raw=None, response=None
):
```

*Structured API error with optional context.*

### APIError.with_context

``` python
def with_context(
    *, provider:str='', model:str='', endpoint:str=''
)->APIError:
```

*Return a copy with missing context fields filled.*

## adecide

``` python
async def adecide(
    state, # Text, JSON dict/list, `Msg`, `list[Msg]`, or `aidialog.msg_parts` media
    questions, # `{name: question}` dict (strings = `noul`), or a single question/string (under `'answer'`)
    model:str=None, # Model name, alias, or `'provider/model'` (defaults to `api_name`'s default model or `jev`)
    api_name:str=None, # Explicit registered provider name overriding model inference (accepts `'typesafe'` -> `'jev'`)
    api_key:str=None, # Explicit API key overriding environment variable
    oauth_token:str=None, # Explicit OAuth bearer token (mutually exclusive with `api_key`)
    base_url:str=None, # Override provider base URL (skips env keys unless credentials are passed)
    xtra_body:dict=None, # Extra raw JSON fields merged into the request body
    xtra_hdrs:dict=None, # Extra HTTP headers merged onto the request
    retries:int=2, # Max retries on retryable `APIError`s
    retry_delay:float=0.5, # Initial exponential backoff delay in seconds
    timeout:float=60.0, # Request timeout in seconds
    **kwargs
)->fastdecisions.types.Decision: # Provider options (`long_context`, `resolution`, `detail`, `prompt_cache_key`, etc.)
```

*Evaluate canonical decision `questions` against `state` using Jev, Gemini, or OpenAI.*

## decide

``` python
def decide(
    state, # Text, JSON dict/list, `Msg`, `list[Msg]`, or `aidialog.msg_parts` media
    questions, # `{name: question}` dict (strings = `noul`), or a single question/string
    model:str=None, # Model name, alias, or `'provider/model'` (defaults to `api_name`'s default model or `jev`)
    *, api_name:str=None, api_key:str=None, oauth_token:str=None, base_url:str=None, xtra_body:dict=None,
    xtra_hdrs:dict=None, retries:int=2, retry_delay:float=0.5, timeout:float=60.0, **kwargs
)->fastdecisions.types.Decision:
```

*Synchronous wrapper around [`adecide`](core.html#adecide) via `run_sync` (works in both scripts and notebooks).*

## Decider

``` python
def Decider(
    questions, # `{name: question}` dict (strings = `noul`), or single question/string
    model:str=None, # Model name, alias, or `'provider/model'` (defaults to `api_name`'s default model or `jev`)
    **kwargs
):
```

*Reusable decision evaluator bound to a fixed question set and model, tracking cumulative usage and cost.*

### Decider.batch

``` python
async def batch(
    states, # Sequence of states (or a single state) to evaluate concurrently
    max_concurrency:int=8, # Maximum in-flight requests (must be >= 1)
    return_exceptions:bool=False, # Return exceptions inline instead of cancelling and raising?
    **kwargs
)->list: # Per-batch overrides forwarded to `adecide`
```

*Evaluate `self.questions` across `states` concurrently, preserving input order.*

## noul

``` python
def noul(
    instructions=None, # Yes/no question or statement to evaluate
    *, true=None, # Optional description of what counts as yes/true
    false=None, # Optional description of what counts as no/false
    criteria:dict=None, # Optional explicit `{'true': ..., 'false': ...}` mapping
)->dict:
```

*Build a Jev [`noul`](types.html#noul) (yes/no probability) question dictionary.*

## choice

``` python
def choice(
    criteria, # Mapping `{option: description_or_None}` or sequence of at least 2 option names
    instructions=None, # Question guiding the selection
)->dict:
```

*Build a Jev [`choice`](types.html#choice) (single-select classification) question dictionary.*

## score

``` python
def score(
    criteria, # Ordered rubric list of level descriptions, or `{label: description}` mapping
    instructions=None, # Question describing what to rate
)->dict:
```

*Build a Jev [`score`](types.html#score) (ordered rubric rating) question dictionary.*

## box

``` python
def box(
    instructions=None, # Description of what to locate in the image (Jev 1.14+ only)
)->dict:
```

*Build a Jev [`box`](types.html#box) (spatial bounding box) question dictionary.*

## Decision

``` python
def Decision(
    model:str, # Model name returned by the provider (or requested when omitted)
    answers:dict, # `{question_name: Answer}` mapping
    usage:fastdecisions.utils.Usage=None, # Normalized token usage
    api_name:str=None, # Registered provider name, e.g. 'jev', 'gemini', 'openai'
    raw:dict=None, # Full provider response dict
):
```

*Read-only mapping of normalized decision answers alongside model, usage, and raw metadata.*

### Decision.cost

``` python
def cost()->float:
```

*Estimated USD cost using `usage`, [`get_model_info`](utils.html#get_model_info), and [`calc_cost`](utils.html#calc_cost).*

## NoulAnswer

``` python
def NoulAnswer(
    noul:float, # Probability of yes/true, in [0, 1]
    confidence:float=None, # Confidence in [0.5, 1]; defaults to `max(noul, 1 - noul)`
    raw:dict=None, # Original provider answer dict
):
```

*Calibrated yes/no probability answer (`type='noul'`).*

## ChoiceAnswer

``` python
def ChoiceAnswer(
    choice:str, # Selected option name
    confidence:float, # Confidence in [0, 1]
    probabilities:dict, # `{option: probability}` mapping
    raw:dict=None, # Original provider answer dict
):
```

*Single-select classification answer (`type='choice'`).*

## ScoreAnswer

``` python
def ScoreAnswer(
    score:float, # Expected score (probability-weighted average of zero-based rubric indices)
    confidence:float, # Confidence in [0, 1]
    probabilities:dict, # `{level_index_str: probability}` mapping
    legend:dict, # `{level_index_str: criterion}` rubric mapping
    raw:dict=None, # Original provider answer dict
):
```

*Ordered rubric rating answer (`type='score'`).*

## BoxAnswer

``` python
def BoxAnswer(
    box, # `BoxCoordinates` or dict with `top`, `bottom`, `left`, `right`
    confidence:float=None, # Confidence in [0, 1], or None when omitted
    raw:dict=None, # Original provider answer dict
):
```

*Spatial bounding-box answer (`type='box'`).*

## RefusalAnswer

``` python
def RefusalAnswer(
    raw:dict=None, # Original provider answer dict
):
```

*Per-question refusal answer (`type='refusal'`), returned by OpenAI when an individual question is refused.*

## Usage

``` python
def Usage(
    prompt_tokens:int=0, # Input token count
    completion_tokens:int=0, # Output token count (usually 0 for decision models)
    total_tokens:int=0, # Total token count
    cached_tokens:int=0, # Input tokens served from cache
    cache_creation_tokens:int=0, # Input tokens written to cache
    reasoning_tokens:int=0, # Reasoning tokens if reported
    raw:dict=None, # Original provider usage dict
):
```

*Normalized token usage across decision providers.*

## Provider

``` python
def Provider(
    name:str, # Canonical provider name, e.g. 'jev', 'gemini', 'openai'
    spec:fastspec.spec.SpecParser, # Parsed `fastspec` specification
    env:str, # Environment variable holding the default API key
    auth, # `'bearer'`, a header name (e.g. `'x-goog-api-key'`), or callable `(api_key, oauth_token) -> dict`
    op:str, # Dotted `OpenAPIClient` operation path, e.g. `'systemone.evaluate'` or `'decisions.evaluate'`
    mk_payload, # Callable `(state, questions, model=..., **kwargs) -> dict`
    req_hdrs=None, # Optional callable `(body, headers=None, **kwargs) -> dict`
    norm_response=None, # Callable `(resp, model=None, questions=None) -> Decision`
    default_model:str=None, # Default model used when `decide()`/`adecide()` omits `model`
    opt_keys:tuple=(), # Provider-specific kwarg names accepted by `mk_payload` or `req_hdrs`
    base_url:str=None, # Default base URL; defaults to `spec.base_url`
):
```

*Declarative provider definition bundling spec, auth, payload translation, response normalization, and default model.*

### Provider.op_fn

``` python
def op_fn(
    cli:fastspec.oapi.OpenAPIClient
):
```

*Return the bound `OpenAPIClient` operation callable named by `self.op`.*

## register_provider

``` python
def register_provider(
    p:fastdecisions.utils.Provider
)->fastdecisions.utils.Provider:
```

*Register `p` in `providers` under `p.name` and return it.*

## ContextWindowExceededError

``` python
def ContextWindowExceededError(
    message:str, *, provider:str='', model:str='', endpoint:str='', status_code=None, error_type:str='', code=None,
    request_id:str='', retryable=None, raw=None, response=None
):
```

*Raised when a provider rejects a request for exceeding its token limit.*
