Metadata-Version: 2.5
Name: idia
Version: 0.4.0
Summary: Ask judgement models many closed questions about one input, packed into calls within each provider's limits, and get their probabilities back, with retries, limits and provenance handled once.
Project-URL: Homepage, https://github.com/CRSiegfried/idia
Project-URL: Documentation, https://github.com/CRSiegfried/idia/tree/main/docs/spec
Project-URL: Repository, https://github.com/CRSiegfried/idia
Project-URL: Issues, https://github.com/CRSiegfried/idia/issues
Project-URL: Changelog, https://github.com/CRSiegfried/idia/blob/main/CHANGELOG.md
Author-email: Christopher Siegfried <160437306+CRSiegfried@users.noreply.github.com>
License-Expression: MIT
License-File: LICENSE
Keywords: calibrated probabilities,classification,judgement model,llm,provider
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: MacOS
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.11
Provides-Extra: cloudflare
Requires-Dist: httpx2>=2.16; extra == 'cloudflare'
Provides-Extra: gliner
Requires-Dist: gliner2[local]>=2.0.0; extra == 'gliner'
Requires-Dist: protobuf>=4; extra == 'gliner'
Requires-Dist: sentencepiece>=0.2; extra == 'gliner'
Requires-Dist: torch>=2.1; extra == 'gliner'
Provides-Extra: openai
Requires-Dist: httpx2>=2.16; extra == 'openai'
Requires-Dist: openai>=3.35.1; extra == 'openai'
Provides-Extra: system-one
Requires-Dist: httpx2>=2.16; extra == 'system-one'
Description-Content-Type: text/markdown

# idia

idia is a Python library for putting closed questions (yes or no, one label of a set, a level on a scale, a value found in the input) to judgement models, which return probabilities and typed values instead of prose. You write one request: an input and the questions about it. idia checks it against the provider's limits before any call, packs the questions into calls as full as those limits allow, retries inside one deadline, and returns the answers together in one response, each as the provider gave it, with a record of which model took each call.

![Eight questions about one message, drawn as small one-eyed hexagons, are packed into three calls, sent to a provider in turn with one retry, and come back as one response](https://raw.githubusercontent.com/CRSiegfried/idia/main/docs/assets/demo.svg)

*Eight questions about one support message, each drawn as a small idia, go to a provider that takes three questions per call. idia packs them into three calls that each carry the message, and sends the calls in turn. The second call gets a 429 and is retried. One answer breaks a rule and comes back as a fault, and the other seven stand. Everything returns in one response. The provider is a stand-in with canned answers; the groups, the retry and the fault are drawn from a run of idia by [draw.py](docs/assets/demo/draw.py), and [triage.py](docs/assets/demo/triage.py) prints the same run in a terminal.*

## TL;DR

- A request is one input and any number of closed questions about it. Each question has a key and one of five kinds: `noul` (yes or no), `choice`, `score`, `extraction` or `box`.
- Every provider declares its limits in a `Capabilities` record. idia checks the request against it first and raises `DoesNotFit` before any call for a request it can't split to fit. It doesn't truncate.
- When the questions overflow a limit, idia packs them in order into several calls that each repeat the input, and merges the answers. One deadline covers every call, retry and rate-limit wait of the request.
- Probabilities come back as the provider returned them. An answer that breaks a rule, such as probabilities that don't sum to 1, becomes a `Fault` for that one question.
- The response holds one outcome per call: the provider, the model it reported, the attempts, the prompt sent and the usage.
- The core has no dependencies, and each provider is an optional extra. Python 3.11 to 3.14, MIT.

## Install

```sh
pip install "idia @ git+https://github.com/CRSiegfried/idia@v0.4.0"
```

That is the core, which is enough for the example below. idia installs from its git tag until it is on a package index. To call a provider, name its extra, as in `idia[cloudflare]`. The [providers](#providers) table lists them.

## Try it without keys

This runs as it is, with no API key. A scripted leaf answers in place of a model.

Every provider declares what it takes in a `Capabilities` record. A provider that ships with idia brings its own. The scripted leaf has no API behind it, so the example declares one, with a limit of two questions per call:

<!-- demo -->
<details>
<summary>The stand-in's capabilities record, with every field stated</summary>

```python
from idia import UNBOUNDED, Capabilities, Rounding

RECORD = Capabilities(
    kinds=frozenset({"noul", "choice", "score"}),
    modalities=frozenset({"text"}),
    max_questions=2,  # two questions per call
    max_text_parts=UNBOUNDED,
    max_input_tokens=8192,
    max_labels=20,
    max_levels=10,
    calibrated=True,
    rounding=Rounding(probability_decimals=2, score_decimals=None),
    image_carriers=frozenset(),
    max_question_tokens=UNBOUNDED,
    max_body_bytes=UNBOUNDED,
    max_images=0,
    max_images_per_question=0,
    max_image_bytes=UNBOUNDED,
    max_total_image_bytes=UNBOUNDED,
    max_total_options=UNBOUNDED,
    min_levels=None,
    min_image_side=None,
    max_image_side=None,
    max_image_pixels=None,
    max_image_tiles=None,
    image_tile_side=None,
    image_media_types=None,
    value_types=frozenset(),
    list_value_types=frozenset(),
    key_patterns=(),
    recounts_state_per_question=False,
    returns_refusal=False,
    snapshot_pinnable=True,
    carries_noul_descriptions=True,
    carries_structured_instructions=True,
    truncates_silently=False,
    confidence={},
    opt_in_features=frozenset(),
    enabled_features=frozenset(),
    feature_kinds={},
    feature_modalities={},
)
```

</details>

Three questions about one message go in one request:

```python
import asyncio

from idia import Deadline, Dispatcher, Label, LabelAnswer, NoulAnswer, Question, Request
from idia import State, TextPart
from idia.providers.scripted import Scripted

TOPICS = ("billing", "shipping", "other")
LEVELS = ("low", "medium", "high")

request = Request(
    state=State(parts=(TextPart(text="The invoice is overdue and I want a refund."),)),
    questions=(
        Question(key="complaint", kind="noul", instruction="Is this a complaint?"),
        Question(
            key="topic",
            kind="choice",
            instruction="What is it about?",
            labels=tuple(Label(name=name) for name in TOPICS),
        ),
        Question(
            key="urgency",
            kind="score",
            instruction="How urgent is it?",
            labels=tuple(Label(name=name) for name in LEVELS),
        ),
    ),
    deadline=Deadline.after(30),  # seconds from now, for the whole request
)

# What the stand-in model answers, one item per call.
leaf = Scripted(
    capabilities=RECORD,
    script=[
        {
            "complaint": NoulAnswer(probability=0.93),
            "topic": LabelAnswer(
                probabilities=(("billing", 0.81), ("shipping", 0.07), ("other", 0.12))
            ),
        },
        {"urgency": LabelAnswer(probabilities=(("low", 0.1), ("medium", 0.3), ("high", 0.6)))},
    ],
)


async def main() -> None:
    async with Dispatcher(leaf) as provider:
        response = await provider.answer(request)
    print("complaint", response.answers["complaint"].probability)
    print("topic", dict(response.answers["topic"].probabilities))
    print("urgency", dict(response.answers["urgency"].probabilities))
    for outcome in response.outcomes:
        print(outcome.provider, outcome.model_reported, outcome.keys, outcome.attempts)


asyncio.run(main())
```

It prints:

```text
complaint 0.93
topic {'billing': 0.81, 'shipping': 0.07, 'other': 0.12}
urgency {'low': 0.1, 'medium': 0.3, 'high': 0.6}
scripted scripted-1 ('complaint', 'topic') 1
scripted scripted-1 ('urgency',) 1
```
<!-- /demo -->

The request held three questions and the record allows two per call, so idia made two calls. Each call carried the message, and the answers came back in one response under the keys the questions had.

The last two lines are the outcomes, one per call: the leaf that took it, the model it reported, the questions it held and the attempts it took.

To ask a real model, install a provider's extra, export its credentials, and use `idia.provider("cloudflare-clef")` in place of `Dispatcher(leaf)`. The request and the shape of the response stay the same. Clef takes 64 questions per call, so there these three go in one.

## Why it exists

Judgement models answer a closed question with probabilities, quickly and cheaply enough that my assistant's workflows now ask more than a hundred of them. A workflow asks many of those questions about the same input, and asked one per call, each question sends the whole input again.

The providers also differ in their APIs, in their limits on what one call may hold and in their errors. Pydantic AI, the Vercel AI SDK and LiteLLM now reach judgement models too, for the label kinds. As of November 2026, none of them packs questions into calls by the provider's limits, holds every retry and wait to one deadline, keeps the good answers when one comes back broken, or handles extraction beside the label kinds. Hence, idia.

It does the checking, packing and retrying in one place and leaves the answers alone. It doesn't renormalize, round or correct a probability, and it says on each outcome whether the provider claims its probabilities are calibrated. It depends on no decision engine. [ommat](https://github.com/CRSiegfried/ommat) is the engine I use it with.

## The vocabulary

- **State**: the input the questions are about, as text, JSON or image parts.
- **Question**: a key, a kind and an instruction. A `noul` is yes or no, a `choice` picks one label, a `score` picks a level on an ordered scale, an `extraction` reads a typed value or a list of values out of the input, and a `box` finds a region of an image.
- **Request**: one state, its questions and a deadline.
- **Leaf**: the code that sends one call to one provider. It doesn't retry.
- **Provider**: what you call `answer` on. `idia.provider(name)` builds one, and a `Dispatcher` makes one from any leaf.
- **Capabilities**: the record of a provider's kinds and limits that every request is checked against.
- **Outcome**: what happened to one call, including which questions it held, who answered, the attempts and any error.

## How a request runs

1. You build a `Request` and await `provider.answer(request)`.
2. idia checks the request against the provider's `Capabilities`. A kind the provider lacks, too many labels on one question or an input too long for one call raises `DoesNotFit`, and no call is made.
3. A request that fits whole is one call. Otherwise the questions are packed in order into calls as full as the limits allow, and each call repeats the state. To keep calls smaller than the model takes, pass `max_input_tokens=` to `idia.provider` or a `Dispatcher`: it lowers the model's input-token limit and never raises it.
4. The calls run at the same time; `ConcurrencyLimit(n)` caps how many are in flight. A retryable error is retried with backoff, up to three attempts by default, and every wait counts against the request's deadline.
5. Each answer is checked against the rules for its kind. One that fails is a `Fault` under its key, and the other answers in the call are unaffected.
6. You get a `Response` with the answers under your keys and one outcome per call. If no call answered, `answer` raises `RequestFailed`, which carries the same response.

## Providers

`idia.provider(name)` builds a provider by name, and `idia.provider_names()` lists the names.

| Name | Extra | Kinds | Claims calibrated |
|---|---|---|---|
| `system-one` | `system-one` | `noul`, `choice`, `score`; with `images=True`, `box` too on `jev-1.14.0` and `jev-preview` | yes |
| `openai-decisions` | `openai` | `noul`, `choice`, `score` | no |
| `openai-chat` | `openai` | `noul`, `choice`, `score` | no |
| `cloudflare-clef` | `cloudflare` | `noul`, `choice`, `score` | no |
| `cloudflare-clairic` | `cloudflare` | `extraction` | no |
| `gliner` | `gliner` | `extraction` of text | no |

Install the extra for the provider you call:

```sh
pip install "idia[cloudflare] @ git+https://github.com/CRSiegfried/idia@v0.4.0"
```

System One sends its long-context header by default, so a request may run to 262,144 input tokens, and one question with the state to the same; pass `long_context=False` for the smaller limits, 65,536 and 32,768. Answers are least steady near the long-context limit: to keep requests smaller, give the dispatcher a lower limit, `idia.provider("system-one", max_input_tokens=64_000)`.

Each provider reads its credentials from the environment unless you pass them. System One, TypeSafe's judgement-model API, reads `TYPESAFE_API_KEY`. OpenAI reads `OPENAI_API_KEY`. Cloudflare reads `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN`. idia reads no `.env` file.

`openai-chat` reads label probabilities from a chat model's logprobs. It needs `model=` and takes one question per call, so it gains nothing from packing. `gliner` runs GLiNER2 in your process on torch and must load its weights before its first call: build it with `idia.leaf("gliner")`, `await leaf.load()`, and wrap it in `Dispatcher(leaf)`, since `idia.provider("gliner")` refuses a leaf not loaded. It asks each label in a row of its own, since a label's answer depends on the other labels sharing its pass, batching up to 8 on texts of up to 1,000 tokens and running a pass per label on longer ones; size its deadline for that. The [providers spec](docs/spec/providers.md) has each provider's options, limits and models.

## Is it for you?

It fits when:

- you ask several closed questions about the same input and want the probabilities, so your code can set its own thresholds;
- you call more than one judgement-model provider, or expect to change provider, and want to keep one request shape;
- you need to show afterwards which model answered a question, what was sent and how many attempts it took.

It doesn't fit when:

- you ask only yes-or-no, choice or score questions of one provider, or you already run Pydantic AI, the Vercel AI SDK or a LiteLLM proxy. Their judgement-model support covers that, with agents, tracing or a gateway that idia lacks;
- you want generated text, tool calls or an agent loop. idia asks closed questions and does nothing else;
- later questions depend on earlier answers. idia asks the questions it is given, and an engine such as [ommat](https://github.com/CRSiegfried/ommat) decides which to ask;
- you need answer caching, evaluation or calibration. idia has none of them, and it passes on a provider's calibration claim without testing it.

## Also included

### A router and a fallback

`Router` sends each question to a provider by its kind, and `Fallback` tries providers in turn when one fails. `idia.cloudflare.cloudflare()` is a router over Clef and Clairic, so one request can hold label questions and extractions. The [dispatch spec](docs/spec/dispatch.md#router-and-fallback) describes both.

### Rate and concurrency limits

A `Dispatcher` takes a `RateLimiter` and a `ConcurrencyLimit`, and two dispatchers whose providers share a vendor's rate limit can share one `RateLimiter`. Time spent waiting on either counts against the request's deadline. See [the retry policy and the limits](docs/spec/dispatch.md#the-retry-policy-and-the-limits).

### Leaves for tests

`Scripted` answers from a script, as in the example above. `Recorded` wraps a real leaf, saves its calls to a JSON file and replays them later without calling it. Both ship in the core and are described in the [test-doubles spec](docs/spec/test-doubles.md). A recorded log holds your inputs as written, so store it as carefully as you store them.

### A leaf of your own

A leaf is a class with four attributes and one `call` method, and it can sit over an HTTP API or a model in your own process. `idia.conformance` is a test suite that holds a leaf to the same rules as the ones idia ships. [Write a leaf](docs/how-to/write-a-leaf.md) builds one from start to finish.

### Deciding with ommat

[ommat](https://github.com/CRSiegfried/ommat) is a decision engine for workflows that put many small, closed questions to a model. Its `ommat[idia]` extra binds an idia provider as the source of its answers. See ommat's tutorial, [Decide with real models through idia](https://github.com/CRSiegfried/ommat/blob/main/docs/tutorials/decide-with-idia.md).

### A skill for coding agents

[skills/idia](skills/idia/SKILL.md) tells a coding agent when to use idia, the core pattern and the pitfalls. From a clone at v0.4.0, for Claude Code:

```sh
cp -r skills/idia ~/.claude/skills/
```

## Docs

- [Ask a provider](docs/tutorials/ask-a-provider.md): the tutorial, with live calls to Clef and Clairic.
- [Write a leaf](docs/how-to/write-a-leaf.md): a provider of your own, tested with the conformance suite.
- [Add a provider to idia](docs/how-to/add-a-provider-to-idia.md): what a leaf needs to ship in idia itself.
- [Vocabulary](docs/spec/vocabulary.md): every shape, from `State` to `Response`, and the validation rules.
- [Providers](docs/spec/providers.md): each provider's request, limits and models.
- [Fit](docs/spec/fit.md): the checks before a call, packing and state overflow.
- [Dispatch](docs/spec/dispatch.md): the deadline, retries, limits, outcomes, the router and the fallback.
- [The spec](docs/spec/README.md): the index of the normative description.
- [CHANGELOG.md](CHANGELOG.md): each release.

## Status

idia is pre-release, an alpha at 0.4.0, with one maintainer. Before 1.0 a minor release may break the API, and the changelog lists each break. A public name, one in `idia.__all__` or in the `__all__` of a module [CONTRIBUTING.md](CONTRIBUTING.md#ground-rules-for-changes) lists, is removed or changed only after one minor release in which it raises a `DeprecationWarning`. A new `Capabilities` field is required, so a release that adds one breaks a record written by hand.

It is pure Python. Its tests run on macOS and Linux, and Windows is untested. The tests replay recorded exchanges with each provider and make no live call, so a provider that has changed its API since a recording was made can fail in ways the tests don't show.

The calls of one request run at the same time. To ask about many inputs at once, await several `answer` calls on one provider, which shares its rate and concurrency limits between them.

## Contributing

Issues first: see [CONTRIBUTING.md](CONTRIBUTING.md), which also has the development setup and the checks. Report vulnerabilities privately, as [SECURITY.md](SECURITY.md) describes.

## License

MIT. See [LICENSE](LICENSE).

## The name

Idia and Ommat come from *ommatidia*, the thousands of small hexagonal eyes that make up a compound eye and combine into one picture. *Ommat-* is the Greek stem for "eye", *-idia* "little ones". Many small, cheap questions add up to one full picture. Idia puts them to the models; Ommat is the engine that asks them.

```text
                 ______            ______            ______
                /      \          /      \          /      \
               / (o)    \        /  (o)   \        /    (o) \
               \        /        \        /        \        /
                \______/          \______/          \______/


                          ______            ______
                         /      \          /      \
                        /   (o)  \        /  (o)   \
                        \        /        \        /
                         \______/          \______/
```
