aix.sampling¶
Repeated sampling: n answers to one prompt, drawn as fast as the provider allows.
Asking the same question several times is the basic variance-reduction (and
stability-measurement) tool for LLM judgements. sample() does it in one of
two ways and records which, because they are not the same statistical object:
"provider_n"– one request withnchoices (one prompt evaluation,ndecodes). Cheapest, and used when LiteLLM reports the model supportsn."independent"–nseparate requests, run concurrently. Works with every provider; each sample also gets its ownusage.
If a provider silently returns fewer choices than asked, the shortfall is drawn
independently and the batch is marked "mixed".
>>> answers = sample("Is a tomato a fruit? Answer yes or no.", n=5)
>>> answers.texts
('Yes', 'Yes', 'Yes', 'yes', 'Yes')
>>> answers.strategy, answers.usage.total_tokens
('provider_n', 52)
Functions
|
Draw |
|
|
|
|
|
Forget which models were found to refuse a provider-side |
Classes
|
One drawn answer. |
|
Exceptions
|
A request inside |
- class aix.sampling.Sample(text, payload, finish_reason=None, usage=None, strategy='independent', seed=None, error=None, system_fingerprint=None)[source]¶
Bases:
objectOne drawn answer.
- payload¶
parse(text)when aparsefunction was given, elsetext;Noneif the request or the parsing failed (seeerror).- Type:
- finish_reason¶
Why this choice stopped.
"length"= truncated,"content_filter"= refused/filtered; check it before treating the payload as a judgement.
- usage¶
Tokens for the request that produced only this sample, or
Nonewhen it shared a provider-sidenrequest (whose usage cannot be split per choice; seeSamples.usage).
- error¶
The exception this sample’s request raised (with
on_error="record") or thatparseraised on its text.
- system_fingerprint¶
The serving backend’s fingerprint for its request, when reported. Seeded samples are only comparable across equal fingerprints (see
aix.supports()for whetherseedis honoured at all).
- class aix.sampling.Samples(samples=(), *, strategy, usage=None, n_requests=0, n_usage_reports=0, fallback_error=None)[source]¶
Bases:
listThe list of
Samplereturned bysample(), plus batch facts.It is a plain
listotherwise: slicing or concatenating gives alistwithout the batch attributes, which describe the whole draw only.- strategy¶
"provider_n","independent"or"mixed"(providerntopped up with independent calls).
- usage¶
Total tokens over every request that reported usage, or
Noneif none did. Comparen_requestswithn_usage_reportsto see whether it is complete.
- n_requests¶
How many requests were made (schema repair requests included).
- n_usage_reports¶
How many of them reported usage (a completion’s repair requests are counted with it when it reported usage). A provider request refused with a 400 (see
fallback_error) reports none.
- fallback_error¶
With
strategy="auto": the error that made the provider-sidenrequest fall back to independent requests (LiteLLM refusingn, or the provider rejecting it with a 400), elseNone.
- exception aix.sampling.SamplingError(message, *, samples=None)[source]¶
Bases:
ExceptionA request inside
sample()failed (withon_error="raise").No request is launched after the first failure, and the ones already in flight are awaited, so the work already paid for is not lost:
samplesholds every request that was made, failed ones included (as samples whoseerroris set) – possibly fewer thann. The first failure is__cause__.
- aix.sampling.check_positive_int(name, value)[source]¶
int(value)if it is a positive integer (not a bool), elseValueError.>>> check_positive_int("n", 3) 3 >>> check_positive_int("n", 0) Traceback (most recent call last): ... ValueError: n must be a positive integer, got 0
- Return type:
- aix.sampling.concurrent_map(func, items, *, concurrency)[source]¶
[func(x) for x in items], run on up toconcurrencythreads, in order.Fails fast like the serial loop would: once a call raises, calls not yet started are cancelled (those already running finish), and the first exception in item order propagates.
>>> concurrent_map(lambda x: x * x, range(5), concurrency=3) [0, 1, 4, 9, 16]
- Return type:
list[R]
- aix.sampling.forget_n_refusals(model=None)[source]¶
Forget which models were found to refuse a provider-side
n.sample(strategy="auto")remembers, per resolved model id (and endpoint kwargs) and for the life of the process, that a provider refusednwith a 400 and a plain request then succeeded. That is a heuristic: a 400 caused byncombined with another argument is remembered too. Call this if a provider has since started acceptingn.model=Noneforgets every model.>>> forget_n_refusals()
- Return type:
- aix.sampling.sample(prompt, *, n, temperature=None, seed=None, concurrency=None, model=None, strategy='auto', parse=None, response_schema=None, on_error='raise', api_key=None, **kwargs)[source]¶
Draw
nanswers toprompt, each with its finish reason and usage.- Parameters:
prompt (
Union[str,Iterable[dict]]) – A string or a list of message dicts, as foraix.chat().n (
int) – How many samples to draw.temperature (
float) – Sampling temperature (None= configured default). At0the samples mostly coincide, which is rarely what you want here.seed (
int) – Base seed. A provider-sidenrequest sends it as is; each independent request sends a seed derived from(seed, index)so independent samples are not forced identical and runs with different base seeds do not overlap. Support is provider-dependent.concurrency (
int) – Max simultaneous independent requests (None= configchat.sample_concurrency).model (
str) – Model id or alias (None= configured default).strategy (
Literal['auto','provider','independent']) –"auto"(providernwhen supported, else independent; also falls back to independent if LiteLLM or the provider refusesn– for a provider 400 the first independent request is sent alone as a probe, and if it fails too the original 400 is raised; seeSamples.fallback_error),"provider"(force onenrequest) or"independent".n=1is always a single plain request, recorded"independent".response_schema (
Union[dict,type]) – A JSON Schema dict or Pydantic model class, enforced and validated per request as inaix.complete(); each payload is the validated value, and a choice still invalid after repairs records itsSchemaValidationErroraserror. Exclusive withparse.parse (
Callable[[str],Any]) – Optionaltext -> payload(e.g.json.loads). A failure is recorded on that sample (payload=None,error=...), not raised.on_error (
Literal['raise','record']) – When a request fails:"raise"(default) raisesSamplingErroronce the launched requests finish, carrying the partial batch;"record"returns the batch with the failure on that sample’serror.api_key (
str) – Explicit API key, as foraix.chat().**kwargs – Passed to every request (e.g.
max_tokens,response_format).
- Return type:
- Returns:
Samples– a list ofSamplewith batch.strategy,.usage,.n_requests.- Raises:
ValueError – For a non-positive
n/concurrency, an unknownstrategy/on_error, or a reserved kwarg (messages,stream).SamplingError – A request failed and
on_error="raise".