epluribus 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 cldixon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.4
2
+ Name: epluribus
3
+ Version: 0.1.0
4
+ Summary: Sample LLMs many times on a structured question and summarize the answers by type.
5
+ Keywords: llm,sampling,structured-outputs,simulation,polling,evaluation
6
+ Author: cldixon
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Typing :: Typed
22
+ Requires-Dist: numpy>=1.26
23
+ Requires-Dist: pydantic>=2.7,<3
24
+ Requires-Dist: anthropic>=2.12,<3 ; extra == 'anthropic'
25
+ Requires-Dist: openai>=3.57,<4 ; extra == 'openai'
26
+ Requires-Dist: pandas>=2.0 ; extra == 'pandas'
27
+ Requires-Python: >=3.11
28
+ Project-URL: Homepage, https://github.com/cldixon/epluribus
29
+ Project-URL: Documentation, https://cldixon.github.io/epluribus/
30
+ Project-URL: Repository, https://github.com/cldixon/epluribus
31
+ Project-URL: Issues, https://github.com/cldixon/epluribus/issues
32
+ Project-URL: Changelog, https://github.com/cldixon/epluribus/releases
33
+ Provides-Extra: anthropic
34
+ Provides-Extra: openai
35
+ Provides-Extra: pandas
36
+ Description-Content-Type: text/markdown
37
+
38
+ # epluribus
39
+
40
+ [![CI](https://github.com/cldixon/epluribus/actions/workflows/ci.yml/badge.svg)](https://github.com/cldixon/epluribus/actions/workflows/ci.yml)
41
+ [![PyPI](https://img.shields.io/pypi/v/epluribus)](https://pypi.org/project/epluribus/)
42
+ [![Python](https://img.shields.io/pypi/pyversions/epluribus)](https://pypi.org/project/epluribus/)
43
+
44
+ *Out of many, one.* Sample LLMs many times on a structured question. Get every answer with its call metadata, plus summaries that fit each answer's type, with intervals.
45
+
46
+ Documentation: <https://cldixon.github.io/epluribus/>
47
+
48
+ ## Install
49
+
50
+ ```sh
51
+ uv add "epluribus[anthropic]" # or epluribus[openai]
52
+ ```
53
+
54
+ ## Use
55
+
56
+ ```python
57
+ from typing import Literal
58
+
59
+ from pydantic import BaseModel, Field
60
+
61
+ import epluribus as ep
62
+ from epluribus.clients.anthropic import AnthropicClient
63
+
64
+
65
+ class Vote(BaseModel):
66
+ choice: Literal["approve", "reject", "abstain"] # categorical
67
+ confidence: int = Field(ge=1, le=5) # ordinal
68
+ reason: str # text: kept, not summarized
69
+
70
+
71
+ task = ep.Task(
72
+ "You are $role. The council votes on converting a garage into housing. How do you vote?", Vote
73
+ )
74
+ models = [
75
+ AnthropicClient("claude-sonnet-5-5", effort="low"),
76
+ AnthropicClient("claude-haiku-5-5", effort="low"),
77
+ ]
78
+
79
+ rs = ep.run(task, models, n=30, grid={"role": ["a retiree", "a cyclist"]})
80
+
81
+ rs["choice"].freq() # shares with 95% intervals
82
+ rs.group_by("model", "role")["confidence"].mean() # means with bootstrap intervals
83
+ rs.usage() # calls, tokens, cost, errors
84
+ df = rs.to_pandas() # one row per sample, with metadata
85
+ ```
86
+
87
+ Use `ep.FakeClient("model-a")` instead of a real client to try everything offline.
88
+
89
+ - **The schema decides the summaries.** The pydantic model is the answer format sent to the model and the rule for how each field is summarized.
90
+ - **Intervals by default**, always with `n`.
91
+ - **Every sample is kept**, with its prompt, model snapshot, tokens, latency and cost.
92
+ - **Failures are data.** Refusals and invalid answers are recorded, not retried.
93
+ - **Cheap reruns.** A disk cache keyed on each sample; raising `n` only makes the new calls.
94
+ - **No logprobs needed**, so it works with frontier APIs.
95
+
96
+ Simulated answers show a model's tendencies. They are not real voters or customers.
97
+
98
+ ## Develop
99
+
100
+ ```sh
101
+ uv sync --all-groups
102
+ uv run ruff check . && uv run ruff format --check .
103
+ uv run ty check
104
+ uv run pytest # offline; also runs every docs example
105
+ uv run pytest -m live # real APIs; needs keys and costs a few cents
106
+ uv run zensical serve # docs at http://localhost:8000
107
+ ```
108
+
109
+ To release, merge a PR that bumps `version` in `pyproject.toml`. The release workflow sees the
110
+ new version, publishes it to PyPI, and creates the `vX.Y.Z` tag and GitHub release.
111
+
112
+ Design notes and the roadmap are in [`design/`](design/).
113
+
114
+ ## License
115
+
116
+ MIT.
@@ -0,0 +1,79 @@
1
+ # epluribus
2
+
3
+ [![CI](https://github.com/cldixon/epluribus/actions/workflows/ci.yml/badge.svg)](https://github.com/cldixon/epluribus/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/epluribus)](https://pypi.org/project/epluribus/)
5
+ [![Python](https://img.shields.io/pypi/pyversions/epluribus)](https://pypi.org/project/epluribus/)
6
+
7
+ *Out of many, one.* Sample LLMs many times on a structured question. Get every answer with its call metadata, plus summaries that fit each answer's type, with intervals.
8
+
9
+ Documentation: <https://cldixon.github.io/epluribus/>
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ uv add "epluribus[anthropic]" # or epluribus[openai]
15
+ ```
16
+
17
+ ## Use
18
+
19
+ ```python
20
+ from typing import Literal
21
+
22
+ from pydantic import BaseModel, Field
23
+
24
+ import epluribus as ep
25
+ from epluribus.clients.anthropic import AnthropicClient
26
+
27
+
28
+ class Vote(BaseModel):
29
+ choice: Literal["approve", "reject", "abstain"] # categorical
30
+ confidence: int = Field(ge=1, le=5) # ordinal
31
+ reason: str # text: kept, not summarized
32
+
33
+
34
+ task = ep.Task(
35
+ "You are $role. The council votes on converting a garage into housing. How do you vote?", Vote
36
+ )
37
+ models = [
38
+ AnthropicClient("claude-sonnet-5-5", effort="low"),
39
+ AnthropicClient("claude-haiku-5-5", effort="low"),
40
+ ]
41
+
42
+ rs = ep.run(task, models, n=30, grid={"role": ["a retiree", "a cyclist"]})
43
+
44
+ rs["choice"].freq() # shares with 95% intervals
45
+ rs.group_by("model", "role")["confidence"].mean() # means with bootstrap intervals
46
+ rs.usage() # calls, tokens, cost, errors
47
+ df = rs.to_pandas() # one row per sample, with metadata
48
+ ```
49
+
50
+ Use `ep.FakeClient("model-a")` instead of a real client to try everything offline.
51
+
52
+ - **The schema decides the summaries.** The pydantic model is the answer format sent to the model and the rule for how each field is summarized.
53
+ - **Intervals by default**, always with `n`.
54
+ - **Every sample is kept**, with its prompt, model snapshot, tokens, latency and cost.
55
+ - **Failures are data.** Refusals and invalid answers are recorded, not retried.
56
+ - **Cheap reruns.** A disk cache keyed on each sample; raising `n` only makes the new calls.
57
+ - **No logprobs needed**, so it works with frontier APIs.
58
+
59
+ Simulated answers show a model's tendencies. They are not real voters or customers.
60
+
61
+ ## Develop
62
+
63
+ ```sh
64
+ uv sync --all-groups
65
+ uv run ruff check . && uv run ruff format --check .
66
+ uv run ty check
67
+ uv run pytest # offline; also runs every docs example
68
+ uv run pytest -m live # real APIs; needs keys and costs a few cents
69
+ uv run zensical serve # docs at http://localhost:8000
70
+ ```
71
+
72
+ To release, merge a PR that bumps `version` in `pyproject.toml`. The release workflow sees the
73
+ new version, publishes it to PyPI, and creates the `vX.Y.Z` tag and GitHub release.
74
+
75
+ Design notes and the roadmap are in [`design/`](design/).
76
+
77
+ ## License
78
+
79
+ MIT.
@@ -0,0 +1,139 @@
1
+ [project]
2
+ name = "epluribus"
3
+ version = "0.1.0"
4
+ description = "Sample LLMs many times on a structured question and summarize the answers by type."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ dependencies = [
10
+ "numpy>=1.26",
11
+ "pydantic>=2.7,<3",
12
+ ]
13
+ keywords = [
14
+ "llm",
15
+ "sampling",
16
+ "structured-outputs",
17
+ "simulation",
18
+ "polling",
19
+ "evaluation",
20
+ ]
21
+ classifiers = [
22
+ "Development Status :: 3 - Alpha",
23
+ "Intended Audience :: Developers",
24
+ "Intended Audience :: Science/Research",
25
+ "Operating System :: OS Independent",
26
+ "Programming Language :: Python :: 3",
27
+ "Programming Language :: Python :: 3 :: Only",
28
+ "Programming Language :: Python :: 3.11",
29
+ "Programming Language :: Python :: 3.12",
30
+ "Programming Language :: Python :: 3.13",
31
+ "Programming Language :: Python :: 3.14",
32
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
33
+ "Topic :: Software Development :: Libraries :: Python Modules",
34
+ "Typing :: Typed",
35
+ ]
36
+
37
+ [[project.authors]]
38
+ name = "cldixon"
39
+
40
+ [project.optional-dependencies]
41
+ anthropic = ["anthropic>=2.12,<3"]
42
+ openai = ["openai>=3.57,<4"]
43
+ pandas = ["pandas>=2.0"]
44
+
45
+ [project.urls]
46
+ Homepage = "https://github.com/cldixon/epluribus"
47
+ Documentation = "https://cldixon.github.io/epluribus/"
48
+ Repository = "https://github.com/cldixon/epluribus"
49
+ Issues = "https://github.com/cldixon/epluribus/issues"
50
+ Changelog = "https://github.com/cldixon/epluribus/releases"
51
+
52
+ [dependency-groups]
53
+ dev = [
54
+ "anthropic>=2.12,<3",
55
+ "openai>=3.57,<4",
56
+ "pandas>=2.0",
57
+ "pytest>=8.3",
58
+ "pytest-cov>=6.0",
59
+ "ruff>=0.15",
60
+ "ty>=0.0.80",
61
+ ]
62
+ docs = [
63
+ "zensical>=0.0.67",
64
+ "mkdocstrings-python>=1.18",
65
+ ]
66
+
67
+ [build-system]
68
+ requires = ["uv_build>=0.9,<0.14"]
69
+ build-backend = "uv_build"
70
+
71
+ [tool.ruff]
72
+ line-length = 100
73
+ target-version = "py311"
74
+ extend-exclude = ["design"]
75
+
76
+ [tool.ruff.lint]
77
+ select = [
78
+ "E",
79
+ "W",
80
+ "F",
81
+ "I",
82
+ "B",
83
+ "UP",
84
+ "SIM",
85
+ "RUF",
86
+ "N",
87
+ "C4",
88
+ "PT",
89
+ "PL",
90
+ "PERF",
91
+ "S",
92
+ "DTZ",
93
+ "PTH",
94
+ "RET",
95
+ ]
96
+ ignore = [
97
+ "PLR0913",
98
+ "PLR2004",
99
+ "S311",
100
+ ]
101
+
102
+ [tool.ruff.lint.per-file-ignores]
103
+ "tests/**" = [
104
+ "S101",
105
+ "PLR2004",
106
+ "PLC0415",
107
+ ]
108
+ "examples/**" = ["T20"]
109
+
110
+ [tool.ruff.format]
111
+ docstring-code-format = true
112
+
113
+ [tool.ty.src]
114
+ exclude = ["design"]
115
+
116
+ [tool.pytest.ini_options]
117
+ testpaths = ["tests"]
118
+ addopts = [
119
+ "-ra",
120
+ "--strict-markers",
121
+ "--strict-config",
122
+ "-m",
123
+ "not live",
124
+ ]
125
+ markers = ["live: calls real provider APIs (needs API keys and costs money)"]
126
+ filterwarnings = ["error"]
127
+
128
+ [tool.coverage.run]
129
+ source = ["epluribus"]
130
+ branch = true
131
+
132
+ [tool.coverage.report]
133
+ show_missing = true
134
+ skip_covered = true
135
+ exclude_also = [
136
+ "if TYPE_CHECKING:",
137
+ "@overload",
138
+ "raise NotImplementedError",
139
+ ]
@@ -0,0 +1,100 @@
1
+ [project]
2
+ name = "epluribus"
3
+ version = "0.1.0"
4
+ description = "Sample LLMs many times on a structured question and summarize the answers by type."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "cldixon" }]
9
+ requires-python = ">=3.11"
10
+ dependencies = [
11
+ "numpy>=1.26",
12
+ "pydantic>=2.7,<3",
13
+ ]
14
+ keywords = ["llm", "sampling", "structured-outputs", "simulation", "polling", "evaluation"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Intended Audience :: Science/Research",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
26
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
27
+ "Topic :: Software Development :: Libraries :: Python Modules",
28
+ "Typing :: Typed",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ anthropic = ["anthropic>=2.12,<3"]
33
+ openai = ["openai>=3.57,<4"]
34
+ pandas = ["pandas>=2.0"]
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/cldixon/epluribus"
38
+ Documentation = "https://cldixon.github.io/epluribus/"
39
+ Repository = "https://github.com/cldixon/epluribus"
40
+ Issues = "https://github.com/cldixon/epluribus/issues"
41
+ Changelog = "https://github.com/cldixon/epluribus/releases"
42
+
43
+ [dependency-groups]
44
+ dev = [
45
+ "anthropic>=2.12,<3",
46
+ "openai>=3.57,<4",
47
+ "pandas>=2.0",
48
+ "pytest>=8.3",
49
+ "pytest-cov>=6.0",
50
+ "ruff>=0.15",
51
+ "ty>=0.0.80",
52
+ ]
53
+ docs = [
54
+ "zensical>=0.0.67",
55
+ "mkdocstrings-python>=1.18",
56
+ ]
57
+
58
+ [build-system]
59
+ requires = ["uv_build>=0.9,<0.14"]
60
+ build-backend = "uv_build"
61
+
62
+ [tool.ruff]
63
+ line-length = 100
64
+ target-version = "py311"
65
+ extend-exclude = ["design"]
66
+
67
+ [tool.ruff.lint]
68
+ select = [
69
+ "E", "W", "F", "I", "B", "UP", "SIM", "RUF", "N", "C4", "PT", "PL", "PERF", "S", "DTZ", "PTH", "RET",
70
+ ]
71
+ ignore = [
72
+ "PLR0913", # Keyword-heavy public signatures are intentional.
73
+ "PLR2004",
74
+ "S311", # Sampling randomness, not cryptography.
75
+ ]
76
+
77
+ [tool.ruff.lint.per-file-ignores]
78
+ "tests/**" = ["S101", "PLR2004", "PLC0415"]
79
+ "examples/**" = ["T20"]
80
+
81
+ [tool.ruff.format]
82
+ docstring-code-format = true
83
+
84
+ [tool.ty.src]
85
+ exclude = ["design"]
86
+
87
+ [tool.pytest.ini_options]
88
+ testpaths = ["tests"]
89
+ addopts = ["-ra", "--strict-markers", "--strict-config", "-m", "not live"]
90
+ markers = ["live: calls real provider APIs (needs API keys and costs money)"]
91
+ filterwarnings = ["error"]
92
+
93
+ [tool.coverage.run]
94
+ source = ["epluribus"]
95
+ branch = true
96
+
97
+ [tool.coverage.report]
98
+ show_missing = true
99
+ skip_covered = true
100
+ exclude_also = ["if TYPE_CHECKING:", "@overload", "raise NotImplementedError"]
@@ -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
+ ]
@@ -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"]