epluribus 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
epluribus/__init__.py ADDED
@@ -0,0 +1,76 @@
1
+ """epluribus: sample LLMs many times on a structured question and summarize the answers by type.
2
+
3
+ Provider clients load their SDK when imported, so import them from their modules:
4
+
5
+ from epluribus.clients.anthropic import AnthropicClient
6
+ from epluribus.clients.openai import OpenAIClient
7
+ """
8
+
9
+ from importlib.metadata import PackageNotFoundError, version
10
+
11
+ from .cache import Cache, DiskCache, MemoryCache
12
+ from .clients.base import Client, Generation
13
+ from .clients.fake import FakeClient
14
+ from .display import ByGroup, Differences, Info, Shares, Summary
15
+ from .errors import (
16
+ CallError,
17
+ EpluribusError,
18
+ InvalidOutputError,
19
+ KindError,
20
+ ProviderError,
21
+ RefusalError,
22
+ TruncatedError,
23
+ )
24
+ from .fields import Categorical, FieldSpec, Kind, Numeric, Ordinal, Text, schema_specs
25
+ from .records import Record, ResponseMeta, Usage
26
+ from .results import FieldView, Grouped, GroupedField, ResultSet
27
+ from .sampler import Mix, PlannedCall, Task, arun, plan, run
28
+ from .stats import Interval
29
+
30
+ try:
31
+ __version__ = version("epluribus")
32
+ except PackageNotFoundError: # pragma: no cover - running from a source tree
33
+ __version__ = "0.0.0"
34
+
35
+ __all__ = [
36
+ "ByGroup",
37
+ "Cache",
38
+ "CallError",
39
+ "Categorical",
40
+ "Client",
41
+ "Differences",
42
+ "DiskCache",
43
+ "EpluribusError",
44
+ "FakeClient",
45
+ "FieldSpec",
46
+ "FieldView",
47
+ "Generation",
48
+ "Grouped",
49
+ "GroupedField",
50
+ "Info",
51
+ "Interval",
52
+ "InvalidOutputError",
53
+ "Kind",
54
+ "KindError",
55
+ "MemoryCache",
56
+ "Mix",
57
+ "Numeric",
58
+ "Ordinal",
59
+ "PlannedCall",
60
+ "ProviderError",
61
+ "Record",
62
+ "RefusalError",
63
+ "ResponseMeta",
64
+ "ResultSet",
65
+ "Shares",
66
+ "Summary",
67
+ "Task",
68
+ "Text",
69
+ "TruncatedError",
70
+ "Usage",
71
+ "__version__",
72
+ "arun",
73
+ "plan",
74
+ "run",
75
+ "schema_specs",
76
+ ]
epluribus/cache.py ADDED
@@ -0,0 +1,119 @@
1
+ """Caches keyed on everything that defines a call, including the sample's seed.
2
+
3
+ Same key, same stored answer: rerunning a sweep costs nothing, and raising `n` or
4
+ adding grid values only makes the new calls. Failed calls are never cached.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import sqlite3
11
+ import threading
12
+ from collections.abc import Generator
13
+ from contextlib import closing, contextmanager
14
+ from pathlib import Path
15
+ from typing import Protocol, runtime_checkable
16
+
17
+ from pydantic import BaseModel
18
+
19
+ from .clients.base import Generation
20
+ from .records import ResponseMeta
21
+
22
+
23
+ @runtime_checkable
24
+ class Cache(Protocol):
25
+ """What `run` needs from a cache. Implement it to plug in your own store."""
26
+
27
+ def get(self, key: str, schema: type[BaseModel]) -> Generation | None:
28
+ """The stored generation for `key`, rebuilt as `schema`, or `None`."""
29
+ ...
30
+
31
+ def set(self, key: str, gen: Generation) -> None:
32
+ """Store a successful generation."""
33
+ ...
34
+
35
+
36
+ class MemoryCache:
37
+ """A cache that lasts as long as the Python process."""
38
+
39
+ def __init__(self) -> None:
40
+ self._d: dict[str, Generation] = {}
41
+
42
+ def get(self, key: str, schema: type[BaseModel]) -> Generation | None:
43
+ return self._d.get(key)
44
+
45
+ def set(self, key: str, gen: Generation) -> None:
46
+ self._d[key] = gen
47
+
48
+ def clear(self) -> None:
49
+ """Remove every entry."""
50
+ self._d.clear()
51
+
52
+ def __len__(self) -> int:
53
+ return len(self._d)
54
+
55
+ def __repr__(self) -> str:
56
+ return f"MemoryCache({len(self)} entries)"
57
+
58
+
59
+ class DiskCache:
60
+ """A cache in a SQLite file, so answers survive restarts and can be shared.
61
+
62
+ Answers are stored as JSON and rebuilt with the run's schema, so the file holds
63
+ no pickled code. A stored answer that no longer validates against the schema is
64
+ treated as a miss.
65
+
66
+ Args:
67
+ path: The SQLite file. Parent directories are created if needed.
68
+ """
69
+
70
+ def __init__(self, path: str | Path = ".epluribus-cache.sqlite") -> None:
71
+ self.path = Path(path)
72
+ self.path.parent.mkdir(parents=True, exist_ok=True)
73
+ self._lock = threading.Lock()
74
+ with self._connect() as db:
75
+ db.execute(
76
+ "CREATE TABLE IF NOT EXISTS generations ("
77
+ "key TEXT PRIMARY KEY, output TEXT NOT NULL, meta TEXT NOT NULL, raw_text TEXT)"
78
+ )
79
+
80
+ @contextmanager
81
+ def _connect(self) -> Generator[sqlite3.Connection]:
82
+ # A short-lived connection per operation: nothing to close, safe across threads.
83
+ with self._lock, closing(sqlite3.connect(self.path)) as db, db:
84
+ yield db
85
+
86
+ def get(self, key: str, schema: type[BaseModel]) -> Generation | None:
87
+ with self._connect() as db:
88
+ row = db.execute(
89
+ "SELECT output, meta, raw_text FROM generations WHERE key = ?", (key,)
90
+ ).fetchone()
91
+ if row is None:
92
+ return None
93
+ output_json, meta_json, raw_text = row
94
+ try:
95
+ output = schema.model_validate_json(output_json)
96
+ except ValueError:
97
+ return None
98
+ meta = ResponseMeta.from_dict(json.loads(meta_json))
99
+ return Generation(output=output, meta=meta, raw_text=raw_text)
100
+
101
+ def set(self, key: str, gen: Generation) -> None:
102
+ meta_json = json.dumps(gen.meta.to_dict(), default=str)
103
+ with self._connect() as db:
104
+ db.execute(
105
+ "INSERT OR REPLACE INTO generations VALUES (?, ?, ?, ?)",
106
+ (key, gen.output.model_dump_json(), meta_json, gen.raw_text),
107
+ )
108
+
109
+ def clear(self) -> None:
110
+ """Remove every entry."""
111
+ with self._connect() as db:
112
+ db.execute("DELETE FROM generations")
113
+
114
+ def __len__(self) -> int:
115
+ with self._connect() as db:
116
+ return db.execute("SELECT COUNT(*) FROM generations").fetchone()[0]
117
+
118
+ def __repr__(self) -> str:
119
+ return f"DiskCache({str(self.path)!r}, {len(self)} entries)"
@@ -0,0 +1,13 @@
1
+ """Model clients.
2
+
3
+ `Client` and `FakeClient` load with the package. Provider clients load their SDK
4
+ when imported, so import them from their modules:
5
+
6
+ from epluribus.clients.anthropic import AnthropicClient
7
+ from epluribus.clients.openai import OpenAIClient
8
+ """
9
+
10
+ from .base import Client, Generation
11
+ from .fake import FakeClient
12
+
13
+ __all__ = ["Client", "FakeClient", "Generation"]
@@ -0,0 +1,76 @@
1
+ """Shared helpers for SDK-backed clients (Anthropic and OpenAI use the same error shapes)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import email.utils
6
+ import time
7
+ from collections.abc import Mapping
8
+ from typing import Any
9
+
10
+ from ..errors import ProviderError
11
+
12
+ _RETRYABLE_STATUS = {408, 409, 429}
13
+
14
+
15
+ def retry_after(headers: Mapping[str, str] | None) -> float | None:
16
+ """Seconds to wait from `retry-after-ms` or `retry-after` (seconds or an HTTP date)."""
17
+ if not headers:
18
+ return None
19
+ ms = headers.get("retry-after-ms")
20
+ if ms:
21
+ try:
22
+ return max(0.0, float(ms) / 1000)
23
+ except ValueError:
24
+ pass
25
+ value = headers.get("retry-after")
26
+ if not value:
27
+ return None
28
+ try:
29
+ return max(0.0, float(value))
30
+ except ValueError:
31
+ pass
32
+ try:
33
+ when = email.utils.parsedate_to_datetime(value)
34
+ except (TypeError, ValueError):
35
+ return None
36
+ return max(0.0, when.timestamp() - time.time())
37
+
38
+
39
+ def translate(e: Exception, sdk: Any) -> Exception:
40
+ """Map an SDK exception to a `ProviderError`, or return it unchanged if it isn't one."""
41
+ if isinstance(e, sdk.APIStatusError):
42
+ status = e.status_code
43
+ headers = getattr(e.response, "headers", None)
44
+ if status == 429:
45
+ kind = "rate_limit"
46
+ elif status >= 500:
47
+ kind = "server"
48
+ elif status in (401, 403):
49
+ kind = "auth"
50
+ elif status == 404:
51
+ kind = "not_found"
52
+ else:
53
+ kind = "bad_request"
54
+ should = headers.get("x-should-retry") if headers else None
55
+ retryable = status >= 500 or status in _RETRYABLE_STATUS
56
+ if should in ("true", "false"):
57
+ retryable = should == "true"
58
+ return ProviderError(
59
+ f"{type(e).__name__} ({status}): {getattr(e, 'message', e)}",
60
+ kind=kind,
61
+ retryable=retryable,
62
+ retry_after=retry_after(headers),
63
+ status_code=status,
64
+ )
65
+ if isinstance(e, (sdk.APITimeoutError, sdk.APIConnectionError)):
66
+ return ProviderError(f"{type(e).__name__}: {e}", kind="connection", retryable=True)
67
+ return e
68
+
69
+
70
+ def dump(obj: Any) -> Any:
71
+ """`model_dump()` for SDK objects, `None` stays `None`."""
72
+ if obj is None:
73
+ return None
74
+ if hasattr(obj, "model_dump"):
75
+ return obj.model_dump(mode="json", exclude_none=True)
76
+ return obj
@@ -0,0 +1,165 @@
1
+ """Claude models through the Anthropic Messages API.
2
+
3
+ Install the extra first: `pip install "epluribus[anthropic]"`.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import time
9
+ from typing import Any
10
+
11
+ from pydantic import BaseModel
12
+
13
+ from ..errors import RefusalError, TruncatedError
14
+ from ..records import ResponseMeta, Usage
15
+ from ._sdk import dump, translate
16
+ from .base import Client, Generation
17
+
18
+ try:
19
+ import anthropic
20
+ except ImportError as e: # pragma: no cover - exercised only without the extra
21
+ msg = 'AnthropicClient needs the anthropic SDK: pip install "epluribus[anthropic]"'
22
+ raise ImportError(msg) from e
23
+
24
+
25
+ class AnthropicClient(Client):
26
+ """A Claude model.
27
+
28
+ Answers use the API's native structured outputs (`output_config.format`), so the
29
+ model's reply is constrained to the schema's JSON shape. The SDK drops
30
+ constraints the API can't enforce, such as `ge`/`le`, from the schema it sends;
31
+ epluribus still validates them, and an answer that breaks one is recorded as
32
+ `invalid_output` with its raw text.
33
+
34
+ Current Claude models think before they answer, and thinking tokens count
35
+ against `max_tokens` and are billed as output. The default `max_tokens` is
36
+ 16,000 so that thinking doesn't cut answers off. For polls, `effort="low"` is
37
+ usually enough and costs less.
38
+
39
+ Current Claude models don't accept `temperature`, so leave it unset. To vary
40
+ answers, sweep personas or phrasings with a grid, or use several templates.
41
+
42
+ Args:
43
+ model: Model ID, for example `"claude-opus-5-5"` or `"claude-haiku-5-5"`.
44
+ effort: Optional effort level (`"low"`, `"medium"`, `"high"`, `"xhigh"`,
45
+ `"max"`). Lower effort is cheaper and faster.
46
+ sdk_client: An `anthropic.AsyncAnthropic` to use. By default one is made
47
+ for each event loop, with the SDK's own retries off: epluribus retries
48
+ and records the attempts itself.
49
+ extra_params: Extra keyword arguments for `messages.create`, for example
50
+ `{"thinking": {"type": "adaptive"}}`. They are part of the cache key.
51
+ **kw: Passed to `Client` (`label`, `pricing`, `max_concurrency`).
52
+ """
53
+
54
+ provider = "anthropic"
55
+ default_max_tokens = 16_000
56
+
57
+ def __init__(
58
+ self,
59
+ model: str,
60
+ *,
61
+ effort: str | None = None,
62
+ sdk_client: Any = None,
63
+ extra_params: dict[str, Any] | None = None,
64
+ **kw: Any,
65
+ ) -> None:
66
+ super().__init__(model, **kw)
67
+ self.effort = effort
68
+ self.extra_params = dict(extra_params or {})
69
+ self._sdk_client = sdk_client
70
+
71
+ def settings(self) -> dict[str, Any]:
72
+ return {"effort": self.effort, "extra_params": self.extra_params}
73
+
74
+ def check(self, *, temperature: float | None = None) -> None:
75
+ if temperature is not None:
76
+ msg = (
77
+ "The Anthropic API no longer accepts `temperature`. Leave it unset, and "
78
+ "add variety with a grid of personas or phrasings, or several templates."
79
+ )
80
+ raise ValueError(msg)
81
+
82
+ def _sdk(self) -> Any:
83
+ if self._sdk_client is not None:
84
+ return self._sdk_client
85
+ return self.loop_local(lambda: anthropic.AsyncAnthropic(max_retries=0))
86
+
87
+ def request(
88
+ self, prompt: str, schema: type[BaseModel], *, system: str | None, max_tokens: int
89
+ ) -> dict[str, Any]:
90
+ """The keyword arguments sent to `messages.create`."""
91
+ output_config: dict[str, Any] = {
92
+ "format": {"type": "json_schema", "schema": anthropic.transform_schema(schema)}
93
+ }
94
+ if self.effort is not None:
95
+ output_config["effort"] = self.effort
96
+ kwargs: dict[str, Any] = {
97
+ "model": self.model,
98
+ "max_tokens": max_tokens,
99
+ "messages": [{"role": "user", "content": prompt}],
100
+ "output_config": output_config,
101
+ }
102
+ if system:
103
+ kwargs["system"] = system
104
+ extra = dict(self.extra_params)
105
+ if "output_config" in extra:
106
+ output_config.update(extra.pop("output_config"))
107
+ kwargs.update(extra)
108
+ return kwargs
109
+
110
+ async def agenerate(
111
+ self,
112
+ prompt: str,
113
+ schema: type[BaseModel],
114
+ *,
115
+ system: str | None = None,
116
+ temperature: float | None = None,
117
+ seed: int | None = None,
118
+ max_tokens: int = 1024,
119
+ ) -> Generation:
120
+ self.check(temperature=temperature)
121
+ kwargs = self.request(prompt, schema, system=system, max_tokens=max_tokens)
122
+ t0 = time.perf_counter()
123
+ try:
124
+ resp = await self._sdk().messages.create(**kwargs)
125
+ except Exception as e:
126
+ raise translate(e, anthropic) from e
127
+ latency = time.perf_counter() - t0
128
+
129
+ text = "".join(b.text for b in resp.content if b.type == "text") or None
130
+ if resp.stop_reason == "refusal":
131
+ details = dump(getattr(resp, "stop_details", None)) or {}
132
+ category = details.get("category")
133
+ msg = f"the model declined to answer (category: {category})"
134
+ raise RefusalError(msg, raw_text=text)
135
+ if resp.stop_reason == "max_tokens":
136
+ msg = (
137
+ f"answer cut off at max_tokens={max_tokens}. Thinking counts against this "
138
+ "limit: raise max_tokens or lower effort."
139
+ )
140
+ raise TruncatedError(msg, raw_text=text)
141
+ output = self.validate(schema, text)
142
+
143
+ u = resp.usage
144
+ details = getattr(u, "output_tokens_details", None)
145
+ usage = Usage(
146
+ input_tokens=u.input_tokens,
147
+ output_tokens=u.output_tokens,
148
+ reasoning_tokens=getattr(details, "thinking_tokens", None),
149
+ cached_input_tokens=getattr(u, "cache_read_input_tokens", None),
150
+ )
151
+ meta = ResponseMeta(
152
+ provider=self.provider,
153
+ model=self.model,
154
+ resolved_model=resp.model,
155
+ request_id=getattr(resp, "_request_id", None) or resp.id,
156
+ temperature=None,
157
+ seed=seed,
158
+ max_tokens=max_tokens,
159
+ usage=usage,
160
+ stop_reason=resp.stop_reason,
161
+ latency_s=latency,
162
+ cost_usd=self.cost(usage),
163
+ raw={"message_id": resp.id, "usage": dump(u), "seed_sent": False},
164
+ )
165
+ return Generation(output=output, meta=meta, raw_text=text)
@@ -0,0 +1,146 @@
1
+ """The client interface. A client turns a prompt and a schema into a `Generation`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import time
7
+ import weakref
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass
10
+ from typing import Any, TypeVar
11
+
12
+ from pydantic import BaseModel, ValidationError
13
+
14
+ from ..errors import InvalidOutputError
15
+ from ..records import ResponseMeta, Usage
16
+
17
+ T = TypeVar("T")
18
+
19
+
20
+ @dataclass
21
+ class Generation:
22
+ """What a client returns for one successful call."""
23
+
24
+ output: BaseModel
25
+ meta: ResponseMeta
26
+ raw_text: str | None = None
27
+
28
+
29
+ class Client:
30
+ """Base class for model integrations.
31
+
32
+ Subclasses set `provider`, implement `agenerate`, and fill `ResponseMeta` with
33
+ whatever the provider returns. Anything without a normalized slot goes in
34
+ `meta.raw`. To mark a failure as worth retrying, raise
35
+ `epluribus.errors.ProviderError(..., retryable=True)`; other exceptions are
36
+ recorded and not retried.
37
+
38
+ Args:
39
+ model: The provider's model name.
40
+ label: How the model appears in results (`coords["model"]`). Defaults to `model`.
41
+ pricing: `(input_usd, output_usd)` per million tokens, used for `cost_usd`.
42
+ Reasoning tokens are counted as output tokens.
43
+ max_concurrency: Most calls in flight to this client at once, across a run.
44
+ `None` means only the run's `concurrency` limit applies.
45
+ """
46
+
47
+ provider: str = "base"
48
+ default_max_tokens: int = 1024
49
+ """`max_tokens` for a run that doesn't set it."""
50
+
51
+ def __init__(
52
+ self,
53
+ model: str,
54
+ *,
55
+ label: str | None = None,
56
+ pricing: tuple[float, float] | None = None,
57
+ max_concurrency: int | None = None,
58
+ ) -> None:
59
+ self.model = model
60
+ self.label = label or model
61
+ self.pricing = pricing
62
+ self.max_concurrency = max_concurrency
63
+ self._cooldown_until = 0.0
64
+ self._limiters: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Semaphore] = (
65
+ weakref.WeakKeyDictionary()
66
+ )
67
+ self._per_loop: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, Any] = (
68
+ weakref.WeakKeyDictionary()
69
+ )
70
+
71
+ async def agenerate(
72
+ self,
73
+ prompt: str,
74
+ schema: type[BaseModel],
75
+ *,
76
+ system: str | None = None,
77
+ temperature: float | None = None,
78
+ seed: int | None = None,
79
+ max_tokens: int = 1024,
80
+ ) -> Generation:
81
+ """Make one call and return the validated answer with its metadata."""
82
+ raise NotImplementedError
83
+
84
+ def check(self, *, temperature: float | None = None) -> None:
85
+ """Raise `ValueError` before a run starts if the settings can't work with this client."""
86
+
87
+ def settings(self) -> dict[str, Any]:
88
+ """Client settings that change the answer, such as a reasoning effort level.
89
+
90
+ They are part of the cache key, so changing one makes new calls.
91
+ """
92
+ return {}
93
+
94
+ def cache_identity(self) -> dict[str, Any]:
95
+ """Everything about the client that belongs in the cache key."""
96
+ return {"provider": self.provider, "model": self.model, **self.settings()}
97
+
98
+ def cost(self, usage: Usage) -> float | None:
99
+ """Cost in USD from `pricing`, or `None` if pricing or token counts are missing."""
100
+ if not self.pricing or usage.input_tokens is None or usage.output_tokens is None:
101
+ return None
102
+ pin, pout = self.pricing
103
+ return (usage.input_tokens * pin + usage.output_tokens * pout) / 1_000_000
104
+
105
+ # --- rate limiting --------------------------------------------------------
106
+
107
+ def limiter(self) -> asyncio.Semaphore | None:
108
+ """This client's concurrency limit for the running event loop."""
109
+ if self.max_concurrency is None:
110
+ return None
111
+ loop = asyncio.get_running_loop()
112
+ if loop not in self._limiters:
113
+ self._limiters[loop] = asyncio.Semaphore(self.max_concurrency)
114
+ return self._limiters[loop]
115
+
116
+ def pause(self, seconds: float) -> None:
117
+ """Hold new calls to this client for `seconds` (after a rate-limit response)."""
118
+ self._cooldown_until = max(self._cooldown_until, time.monotonic() + seconds)
119
+
120
+ async def wait_ready(self) -> None:
121
+ """Wait out any pause set by `pause`."""
122
+ while (delay := self._cooldown_until - time.monotonic()) > 0:
123
+ await asyncio.sleep(delay)
124
+
125
+ # --- helpers for subclasses -----------------------------------------------
126
+
127
+ def loop_local(self, factory: Callable[[], T]) -> T:
128
+ """One object per event loop, for SDK clients whose connections belong to a loop."""
129
+ loop = asyncio.get_running_loop()
130
+ if loop not in self._per_loop:
131
+ self._per_loop[loop] = factory()
132
+ return self._per_loop[loop]
133
+
134
+ @staticmethod
135
+ def validate(schema: type[BaseModel], text: str | None) -> BaseModel:
136
+ """Parse the model's JSON text into `schema`, or raise `InvalidOutputError`."""
137
+ if not text:
138
+ raise InvalidOutputError("the model returned no text", raw_text=text)
139
+ try:
140
+ return schema.model_validate_json(text)
141
+ except ValidationError as e:
142
+ msg = f"answer does not match {schema.__name__}: {e.error_count()} error(s); {e}"
143
+ raise InvalidOutputError(msg, raw_text=text) from e
144
+
145
+ def __repr__(self) -> str:
146
+ return f"{type(self).__name__}({self.label!r})"