API reference¶
Running¶
Task
¶
A prompt template plus the answer schema.
Templates use $name or ${name} placeholders, filled from the run's grid.
Write a literal dollar sign as $$. Braces need no escaping, so JSON examples
can go straight into a prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
str | Sequence[str]
|
The prompt. Pass a list of phrasings to ask the same question
several ways; each sample then records its phrasing as
|
required |
schema
|
type[BaseModel]
|
A pydantic model describing the answer. |
required |
system
|
str | None
|
Optional system prompt. It can use placeholders too. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a template has an invalid placeholder. |
Mix
¶
A population of models: each sample's model is drawn at random by weight.
A mix counts as one entry in models, so n is the number of samples drawn
from the mix per grid cell. Each sample's coords["model"] is the label of the
model that was drawn.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Mapping[Client, float]
|
|
required |
label
|
str
|
Name for the mix, used in sample seeds. Defaults to |
'mix'
|
run
¶
run(
task: Task,
models: Models,
n: int = 20,
*,
grid: Grid | None = None,
temperature: float | None = None,
max_tokens: int | None = None,
seed: int = 0,
concurrency: int = 8,
max_retries: int = 2,
backoff: float = 1.0,
cache: Cache | None = None,
progress: bool = False,
) -> ResultSet
Sample task across models and grid cells and return every answer.
Works in scripts and in notebooks. In a notebook it runs on a helper thread;
use await ep.arun(...) if you prefer the notebook's own event loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
Task
|
The question and its answer schema. |
required |
models
|
Models
|
A client, an |
required |
n
|
int
|
Samples per model (or per mix) for every grid cell and template variant. |
20
|
grid
|
Grid | None
|
|
None
|
temperature
|
float | None
|
Sent to the provider if set. Some models don't accept it. |
None
|
max_tokens
|
int | None
|
Most tokens per answer, thinking or reasoning included. |
None
|
seed
|
int
|
Base seed. Each sample's seed comes from it, the cell, the model and the sample index, and identifies the sample in the cache. Change it to draw a fresh set of samples. |
0
|
concurrency
|
int
|
Most calls in flight at once. |
8
|
max_retries
|
int
|
Extra tries for failures worth retrying (rate limits, server and connection errors). Refusals and invalid answers are kept, not retried. |
2
|
backoff
|
float
|
Base delay in seconds between tries, doubled each time, with
jitter. A provider's |
1.0
|
cache
|
Cache | None
|
A |
None
|
progress
|
bool
|
Print a progress line to stderr. |
False
|
Returns:
| Type | Description |
|---|---|
ResultSet
|
A |
arun
async
¶
arun(
task: Task,
models: Models,
n: int = 20,
*,
grid: Grid | None = None,
temperature: float | None = None,
max_tokens: int | None = None,
seed: int = 0,
concurrency: int = 8,
max_retries: int = 2,
backoff: float = 1.0,
cache: Cache | None = None,
progress: bool = False,
) -> ResultSet
Sample task across models and grid cells. The async version of run.
In a notebook, rs = await ep.arun(...) runs on the notebook's own event loop.
See run for the arguments.
plan
¶
plan(
task: Task,
models: Models,
n: int = 20,
*,
grid: Grid | None = None,
seed: int = 0,
) -> list[PlannedCall]
Expand a run into its calls without making them. len(plan(...)) is the call count.
Each entry of models gets n samples per grid cell and per template variant.
PlannedCall
dataclass
¶
PlannedCall(
coords: dict[str, Any],
values: dict[str, Any],
variant: int,
client: Client,
index: int,
seed: int,
)
One call a run will make. ep.plan returns a list of these.
Attributes:
| Name | Type | Description |
|---|---|---|
coords |
dict[str, Any]
|
Where the sample sits: grid labels, |
values |
dict[str, Any]
|
The values that fill the template's placeholders. |
variant |
int
|
Index of the template used. |
client |
Client
|
The model to call. |
index |
int
|
Sample index within the cell and model (or mix). |
seed |
int
|
The sample's seed, which identifies it in the cache. |
Results¶
ResultSet
¶
Every record from a run, with summaries by field.
rs["field"] gives a FieldView. Iterating gives the records.
filter
¶
Keep records matching a predicate and/or exact values.
rs.filter(lambda r: r.meta.latency_s < 5) or rs.filter(model="a", role="b").
Names are looked up like Record.get.
group_by
¶
Group on coords, answer fields or metadata, for example "model" or "role".
summary
¶
Default summary of each field. Text fields are left out unless named.
usage
¶
usage() -> Info
Call counts, errors, tokens, cost and latency.
Token, cost and latency totals count only calls made in this run, not cache hits.
FieldView
¶
Summaries of one answer field. Which methods work depends on the field's kind.
A summary that doesn't fit the kind raises KindError. Failed calls and
None answers count as missing.
values
¶
The answers, one per record. Missing ones are left out unless asked for.
counts
¶
Count of each level, including levels nobody picked.
For multi-select fields: how many answers selected each option.
freq
¶
freq() -> Shares
Share choosing each level, with 95% Wilson intervals.
For multi-select fields: share of answers that selected each option, so shares can add up to more than 1.
numbers
¶
Answers as floats. Ordinal levels that aren't numbers become ranks 0..k-1.
quantiles
¶
Quantiles of the answers, as {q: value}.
sample
¶
Up to k answers chosen at random. Works for every kind.
diff
¶
diff(other: FieldView) -> Differences | Interval
This field minus the same field in another set of results.
Categorical and multi-select fields: the difference in share for each level (Newcombe intervals). Boolean: difference in rate. Ordinal and numeric: difference in means (bootstrap interval).
array
¶
Answers encoded for numeric work, one row per record.
| Kind | Encoding | Missing |
|---|---|---|
| categorical | integer code into spec.levels |
-1 |
| boolean | 0 or 1 | -1 |
| ordinal | the level if numeric, else its rank | NaN |
| numeric | float | NaN |
| multi-select | 0/1 matrix, one column per option | all 0 |
| text | object array | None |
Grouped
¶
Results split into groups. grouped["field"] summarizes a field per group.
Attributes:
| Name | Type | Description |
|---|---|---|
keys |
The names grouped by. |
|
groups |
|
GroupedField
¶
Record
dataclass
¶
Record(
output: BaseModel | None,
meta: ResponseMeta,
coords: dict[str, Any],
sample_index: int,
prompt: str,
system: str | None = None,
raw_text: str | None = None,
error: str | None = None,
error_kind: str | None = None,
)
A single sample.
Attributes:
| Name | Type | Description |
|---|---|---|
output |
BaseModel | None
|
The validated schema instance, or |
meta |
ResponseMeta
|
Call metadata. |
coords |
dict[str, Any]
|
Where the sample sits in the run: |
sample_index |
int
|
Index of the sample within its cell and model. |
prompt |
str
|
The prompt that was sent. |
system |
str | None
|
The system prompt that was sent, if any. |
raw_text |
str | None
|
The model's raw text, when the provider returned one. Kept for failed calls too, so you can see what an invalid answer looked like. |
error |
str | None
|
Error message, or |
error_kind |
str | None
|
Short error label, for example |
get
¶
Look up a value by name.
Plain names are searched in order: answer fields, then coords, then metadata.
Prefix a name to pick the place explicitly: "output.model",
"coords.model", "meta.usage.output_tokens". Dotted paths reach into
metadata, for example "usage.output_tokens" or "raw.seed_sent".
Raises:
| Type | Description |
|---|---|
KeyError
|
If the name is not found. |
ResponseMeta
dataclass
¶
ResponseMeta(
provider: str,
model: str,
resolved_model: str | None = None,
request_id: str | None = None,
temperature: float | None = None,
seed: int | None = None,
max_tokens: int | None = None,
usage: Usage = Usage(),
stop_reason: str | None = None,
latency_s: float | None = None,
cost_usd: float | None = None,
created_at: datetime = (lambda: now(UTC))(),
cache_hit: bool = False,
attempts: int = 1,
raw: dict[str, Any] = dict(),
)
Normalized call metadata. Provider-specific extras go in raw.
provider
instance-attribute
¶
provider: str
Provider name, for example "anthropic", "openai" or "fake".
resolved_model
class-attribute
instance-attribute
¶
resolved_model: str | None = None
The model or snapshot the provider says it used.
temperature
class-attribute
instance-attribute
¶
temperature: float | None = None
Temperature sent to the provider. None means the provider default.
seed
class-attribute
instance-attribute
¶
seed: int | None = None
This sample's seed. It identifies the sample for the cache; most providers ignore it.
cost_usd
class-attribute
instance-attribute
¶
cost_usd: float | None = None
Cost of the call, if the client was given pricing.
cache_hit
class-attribute
instance-attribute
¶
cache_hit: bool = False
True when this record came from the cache instead of a new call.
attempts
class-attribute
instance-attribute
¶
attempts: int = 1
Number of tries the call took, including the successful one.
raw
class-attribute
instance-attribute
¶
Provider-specific extras, such as the full usage object and whether the seed was sent.
from_dict
classmethod
¶
from_dict(d: dict[str, Any]) -> ResponseMeta
Rebuild metadata from to_dict() output. Unknown keys are ignored.
Usage
dataclass
¶
Usage(
input_tokens: int | None = None,
output_tokens: int | None = None,
reasoning_tokens: int | None = None,
cached_input_tokens: int | None = None,
)
Token counts reported by the provider. None means the provider did not report it.
Display and statistics¶
Interval
dataclass
¶
Shares
¶
Differences
¶
ByGroup
¶
Bases: _TableDict
One result per group, as {group: result}. Returned by grouped field methods.
Attributes:
| Name | Type | Description |
|---|---|---|
group_keys |
The names the results were grouped by. |
Summary
¶
Bases: _TableDict
Default summary of each field, as {field: {statistic: value}}.
Info
¶
Bases: _TableDict
Named values, such as usage() totals.
Clients¶
Client
¶
Client(
model: str,
*,
label: str | None = None,
pricing: tuple[float, float] | None = None,
max_concurrency: int | None = None,
)
Base class for model integrations.
Subclasses set provider, implement agenerate, and fill ResponseMeta with
whatever the provider returns. Anything without a normalized slot goes in
meta.raw. To mark a failure as worth retrying, raise
epluribus.errors.ProviderError(..., retryable=True); other exceptions are
recorded and not retried.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
The provider's model name. |
required |
label
|
str | None
|
How the model appears in results ( |
None
|
pricing
|
tuple[float, float] | None
|
|
None
|
max_concurrency
|
int | None
|
Most calls in flight to this client at once, across a run.
|
None
|
default_max_tokens
class-attribute
instance-attribute
¶
default_max_tokens: int = 1024
max_tokens for a run that doesn't set it.
agenerate
async
¶
agenerate(
prompt: str,
schema: type[BaseModel],
*,
system: str | None = None,
temperature: float | None = None,
seed: int | None = None,
max_tokens: int = 1024,
) -> Generation
Make one call and return the validated answer with its metadata.
check
¶
check(*, temperature: float | None = None) -> None
Raise ValueError before a run starts if the settings can't work with this client.
settings
¶
Client settings that change the answer, such as a reasoning effort level.
They are part of the cache key, so changing one makes new calls.
cache_identity
¶
Everything about the client that belongs in the cache key.
cost
¶
Cost in USD from pricing, or None if pricing or token counts are missing.
pause
¶
pause(seconds: float) -> None
Hold new calls to this client for seconds (after a rate-limit response).
begin_run
¶
Note that a run using this client started on the running event loop.
end_run
async
¶
Note that a run ended. After the last one on this loop, close what loop_local opened.
Connections an SDK client keeps open would otherwise be left behind when the event loop closes. Clients passed in by the caller are never closed here.
Generation
dataclass
¶
Generation(
output: BaseModel,
meta: ResponseMeta,
raw_text: str | None = None,
)
What a client returns for one successful call.
FakeClient
¶
Bases: Client
Produces valid answers for any schema without calling a model.
Each fake model leans towards some options. The leanings are a stable function
of the label, the system prompt, the prompt and the option, so different fake
models and different prompts give different distributions. A higher
temperature flattens the leanings; a lower one sharpens them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
Model name. Also the label unless |
'fake-1'
|
error_rate
|
float
|
Share of calls that fail with a retryable |
0.0
|
latency
|
float
|
Upper bound on the simulated delay, in seconds. |
0.005
|
**kw
|
Any
|
Passed to |
{}
|
AnthropicClient
¶
AnthropicClient(
model: str,
*,
effort: str | None = None,
sdk_client: Any = None,
extra_params: dict[str, Any] | None = None,
**kw: Any,
)
Bases: Client
A Claude model.
Answers use the API's native structured outputs (output_config.format), so the
model's reply is constrained to the schema's JSON shape. The SDK drops
constraints the API can't enforce, such as ge/le, from the schema it sends;
epluribus still validates them, and an answer that breaks one is recorded as
invalid_output with its raw text.
Current Claude models think before they answer, and thinking tokens count
against max_tokens and are billed as output. The default max_tokens is
16,000 so that thinking doesn't cut answers off. For polls, effort="low" is
usually enough and costs less.
Current Claude models don't accept temperature, so leave it unset. To vary
answers, sweep personas or phrasings with a grid, or use several templates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
Model ID, for example |
required |
effort
|
str | None
|
Optional effort level ( |
None
|
sdk_client
|
Any
|
An |
None
|
extra_params
|
dict[str, Any] | None
|
Extra keyword arguments for |
None
|
**kw
|
Any
|
Passed to |
{}
|
OpenAIClient
¶
OpenAIClient(
model: str,
*,
effort: str | None = None,
sdk_client: Any = None,
extra_params: dict[str, Any] | None = None,
**kw: Any,
)
Bases: Client
An OpenAI model.
Answers use strict structured outputs (text.format with a JSON schema), and
responses are not stored on OpenAI's side (store=False) unless you pass
extra_params={"store": True}.
Reasoning models reject temperature; with those, leave it unset and use
effort instead. Reasoning tokens count against max_tokens, so the default
is 16,000. OpenAI's Responses API has no seed parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
Model name. |
required |
effort
|
str | None
|
Optional reasoning effort for reasoning models, for example |
None
|
sdk_client
|
Any
|
An |
None
|
extra_params
|
dict[str, Any] | None
|
Extra keyword arguments for |
None
|
**kw
|
Any
|
Passed to |
{}
|
Caches¶
Cache
¶
Bases: Protocol
What run needs from a cache. Implement it to plug in your own store.
get
¶
get(key: str, schema: type[BaseModel]) -> Generation | None
The stored generation for key, rebuilt as schema, or None.
MemoryCache
¶
A cache that lasts as long as the Python process.
DiskCache
¶
A cache in a SQLite file, so answers survive restarts and can be shared.
Answers are stored as JSON and rebuilt with the run's schema, so the file holds no pickled code. A stored answer that no longer validates against the schema is treated as a miss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The SQLite file. Parent directories are created if needed. |
'.epluribus-cache.sqlite'
|
Schema introspection¶
schema_specs
¶
Infer a FieldSpec for every field of a pydantic model.
FieldSpec
dataclass
¶
FieldSpec(
name: str,
kind: Kind,
levels: tuple[Any, ...] | None = None,
lo: float | None = None,
hi: float | None = None,
integer: bool = False,
optional: bool = False,
description: str | None = None,
)
What epluribus knows about one answer field.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Field name. |
kind |
Kind
|
How the field is summarized. |
levels |
tuple[Any, ...] | None
|
Categories or ordinal levels, in order. |
lo |
float | None
|
Lower bound, if declared. |
hi |
float | None
|
Upper bound, if declared. |
integer |
bool
|
True for |
optional |
bool
|
True if the field accepts |
description |
str | None
|
The field's description, if any. |
Ordinal
dataclass
¶
Errors¶
Exceptions raised by epluribus and by its clients.
Clients turn provider failures into these classes so that the sampler can decide
whether to retry. Every failed call still becomes a Record with error and
error_kind set; a run never stops because one call failed.
KindError
¶
Bases: EpluribusError, TypeError
An aggregation does not fit the field's kind, for example mean() on a categorical.
CallError
¶
CallError(
message: str,
*,
kind: str | None = None,
retryable: bool | None = None,
retry_after: float | None = None,
raw_text: str | None = None,
status_code: int | None = None,
)
Bases: EpluribusError
A model call failed.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
A short label stored on the record as |
retryable |
bool
|
Whether the sampler should try the call again. |
retry_after |
Seconds the provider asked us to wait, if it said. |
|
raw_text |
The model's text, when there was one. Kept for inspection. |
ProviderError
¶
InvalidOutputError
¶
InvalidOutputError(
message: str,
*,
kind: str | None = None,
retryable: bool | None = None,
retry_after: float | None = None,
raw_text: str | None = None,
status_code: int | None = None,
)
Bases: CallError
The model answered, but the answer does not match the schema.
Not retried by default: the invalid answer is a sample like any other, and
retrying only the failures would bias the results. raw_text holds the answer.