stochast 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,20 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: astral-sh/setup-uv@v3
14
+ with:
15
+ version: "latest"
16
+ - run: uv sync --python 3.11
17
+ - run: uv run ruff check .
18
+ - run: uv run ruff format --check .
19
+ - run: uv run mypy stochast
20
+ - run: uv run pytest
@@ -0,0 +1,218 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ # Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ # poetry.lock
109
+ # poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ # pdm.lock
116
+ # pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ # pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+ # Temporary file for partial code execution
204
+ tempCodeRunnerFile.py
205
+
206
+ # Ruff stuff:
207
+ .ruff_cache/
208
+
209
+ # PyPI configuration file
210
+ .pypirc
211
+
212
+ # Marimo
213
+ marimo/_static/
214
+ marimo/_lsp/
215
+ __marimo__/
216
+
217
+ # Streamlit
218
+ .streamlit/secrets.toml
stochast-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Victor Hugo Braz
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,89 @@
1
+ Metadata-Version: 2.5
2
+ Name: stochast
3
+ Version: 0.1.0
4
+ Summary: A testing tool for LLM agents that reports statistics instead of verdicts.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: httpx>=0.27
9
+ Requires-Dist: pydantic>=2.0
10
+ Requires-Dist: rich>=13.0
11
+ Requires-Dist: typer>=0.12
12
+ Description-Content-Type: text/markdown
13
+
14
+ # Stochast
15
+
16
+ A testing tool for LLM agents that reports pass rates instead of pass/fail verdicts. Agents are
17
+ non-deterministic: the same prompt can take a different tool-call path on every run, so a single
18
+ pass or fail tells you almost nothing. Stochast runs a scenario N times and reports how often it
19
+ passed.
20
+
21
+ ```python
22
+ # scenarios.py
23
+ from stochast import scenario, expect
24
+ from stochast.adapters.openai import OpenAIAdapter, ToolSpec
25
+
26
+
27
+ def lookup_order(order_id: int) -> dict:
28
+ return {"order_id": order_id, "status": "shipped"}
29
+
30
+
31
+ def build_adapter():
32
+ return OpenAIAdapter(
33
+ model="gpt-4o-mini",
34
+ api_key="sk-...",
35
+ tools=[
36
+ ToolSpec(
37
+ name="lookup_order",
38
+ description="Look up an order by id",
39
+ parameters={
40
+ "type": "object",
41
+ "properties": {"order_id": {"type": "integer"}},
42
+ "required": ["order_id"],
43
+ },
44
+ handler=lookup_order,
45
+ )
46
+ ],
47
+ )
48
+
49
+
50
+ @scenario(runs=20)
51
+ def refund_status_lookup(agent):
52
+ result = agent.run("What's the status of order 4471?")
53
+ expect.tool_called(result, "lookup_order")
54
+ expect.output_contains(result, "4471")
55
+ ```
56
+
57
+ ```
58
+ stochast run scenarios.py --adapter scenarios:build_adapter
59
+ ```
60
+
61
+ ```
62
+ refund_status_lookup (20 runs)
63
+ pass rate: 18/20 (90%)
64
+ ```
65
+
66
+ Every run is persisted as JSON under `stochast-results/` for later inspection.
67
+
68
+ ## Retry policy
69
+
70
+ Stochast retries transport errors (timeouts, connection failures, 429s, 5xxs) with backoff,
71
+ because those are infrastructure problems. It never retries anything else: a model calling the
72
+ wrong tool or giving a bad answer is data, and retrying it would silently destroy the measurement
73
+ you're trying to take.
74
+
75
+ ## Status
76
+
77
+ Early and incomplete. Currently implemented: the `@scenario` decorator, an OpenAI-compatible
78
+ tool-calling adapter, a concurrent runner with the retry policy above and Ctrl-C-safe partial
79
+ results, and two assertions (`tool_called`, `output_contains`). Confidence intervals, the full
80
+ assertion vocabulary, tool-path frequency tables, cost/latency percentiles, and A/B comparison are
81
+ planned but not yet built.
82
+
83
+ ## Install
84
+
85
+ ```
86
+ pip install stochast
87
+ ```
88
+
89
+ Requires Python 3.11+.
@@ -0,0 +1,76 @@
1
+ # Stochast
2
+
3
+ A testing tool for LLM agents that reports pass rates instead of pass/fail verdicts. Agents are
4
+ non-deterministic: the same prompt can take a different tool-call path on every run, so a single
5
+ pass or fail tells you almost nothing. Stochast runs a scenario N times and reports how often it
6
+ passed.
7
+
8
+ ```python
9
+ # scenarios.py
10
+ from stochast import scenario, expect
11
+ from stochast.adapters.openai import OpenAIAdapter, ToolSpec
12
+
13
+
14
+ def lookup_order(order_id: int) -> dict:
15
+ return {"order_id": order_id, "status": "shipped"}
16
+
17
+
18
+ def build_adapter():
19
+ return OpenAIAdapter(
20
+ model="gpt-4o-mini",
21
+ api_key="sk-...",
22
+ tools=[
23
+ ToolSpec(
24
+ name="lookup_order",
25
+ description="Look up an order by id",
26
+ parameters={
27
+ "type": "object",
28
+ "properties": {"order_id": {"type": "integer"}},
29
+ "required": ["order_id"],
30
+ },
31
+ handler=lookup_order,
32
+ )
33
+ ],
34
+ )
35
+
36
+
37
+ @scenario(runs=20)
38
+ def refund_status_lookup(agent):
39
+ result = agent.run("What's the status of order 4471?")
40
+ expect.tool_called(result, "lookup_order")
41
+ expect.output_contains(result, "4471")
42
+ ```
43
+
44
+ ```
45
+ stochast run scenarios.py --adapter scenarios:build_adapter
46
+ ```
47
+
48
+ ```
49
+ refund_status_lookup (20 runs)
50
+ pass rate: 18/20 (90%)
51
+ ```
52
+
53
+ Every run is persisted as JSON under `stochast-results/` for later inspection.
54
+
55
+ ## Retry policy
56
+
57
+ Stochast retries transport errors (timeouts, connection failures, 429s, 5xxs) with backoff,
58
+ because those are infrastructure problems. It never retries anything else: a model calling the
59
+ wrong tool or giving a bad answer is data, and retrying it would silently destroy the measurement
60
+ you're trying to take.
61
+
62
+ ## Status
63
+
64
+ Early and incomplete. Currently implemented: the `@scenario` decorator, an OpenAI-compatible
65
+ tool-calling adapter, a concurrent runner with the retry policy above and Ctrl-C-safe partial
66
+ results, and two assertions (`tool_called`, `output_contains`). Confidence intervals, the full
67
+ assertion vocabulary, tool-path frequency tables, cost/latency percentiles, and A/B comparison are
68
+ planned but not yet built.
69
+
70
+ ## Install
71
+
72
+ ```
73
+ pip install stochast
74
+ ```
75
+
76
+ Requires Python 3.11+.
@@ -0,0 +1,47 @@
1
+ [project]
2
+ name = "stochast"
3
+ version = "0.1.0"
4
+ description = "A testing tool for LLM agents that reports statistics instead of verdicts."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ requires-python = ">=3.11"
8
+ dependencies = [
9
+ "pydantic>=2.0",
10
+ "typer>=0.12",
11
+ "rich>=13.0",
12
+ "httpx>=0.27",
13
+ ]
14
+
15
+ [project.scripts]
16
+ stochast = "stochast.cli:app"
17
+
18
+ [build-system]
19
+ requires = ["hatchling"]
20
+ build-backend = "hatchling.build"
21
+
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["stochast"]
24
+
25
+ [dependency-groups]
26
+ dev = [
27
+ "pytest>=8.0",
28
+ "ruff>=0.6",
29
+ "mypy>=1.10",
30
+ ]
31
+
32
+ [tool.ruff]
33
+ line-length = 100
34
+ target-version = "py311"
35
+
36
+ [tool.ruff.lint]
37
+ select = ["E", "F", "I", "UP", "B"]
38
+
39
+ [tool.ruff.lint.flake8-bugbear]
40
+ extend-immutable-calls = ["typer.Argument", "typer.Option"]
41
+
42
+ [tool.mypy]
43
+ python_version = "3.11"
44
+ strict = true
45
+
46
+ [tool.pytest.ini_options]
47
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ from stochast import expect
2
+ from stochast.scenario import scenario
3
+
4
+ __all__ = ["scenario", "expect"]
@@ -0,0 +1,27 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any, Protocol, runtime_checkable
5
+
6
+ from stochast.records import ToolCall
7
+
8
+
9
+ @dataclass
10
+ class AgentResult:
11
+ output: str
12
+ tool_calls: list[ToolCall] = field(default_factory=list)
13
+ prompt_tokens: int = 0
14
+ completion_tokens: int = 0
15
+ raw_messages: list[dict[str, Any]] = field(default_factory=list)
16
+
17
+
18
+ @runtime_checkable
19
+ class AgentAdapter(Protocol):
20
+ def run(self, prompt: str) -> AgentResult: ...
21
+
22
+
23
+ # Raised by an adapter for infrastructure failures (timeouts, connection
24
+ # errors, 429/5xx responses). The runner retries these; every other
25
+ # exception is treated as model behaviour and is never retried.
26
+ class TransportError(Exception):
27
+ pass
@@ -0,0 +1,153 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import time
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass
7
+ from typing import Any, cast
8
+
9
+ import httpx
10
+
11
+ from stochast.adapters import AgentResult, TransportError
12
+ from stochast.records import ToolCall
13
+
14
+
15
+ @dataclass
16
+ class ToolSpec:
17
+ name: str
18
+ description: str
19
+ parameters: dict[str, Any]
20
+ handler: Callable[..., Any]
21
+
22
+ # Renders this tool in the OpenAI chat-completions `tools` wire format.
23
+ def to_openai_format(self) -> dict[str, Any]:
24
+ return {
25
+ "type": "function",
26
+ "function": {
27
+ "name": self.name,
28
+ "description": self.description,
29
+ "parameters": self.parameters,
30
+ },
31
+ }
32
+
33
+
34
+ class OpenAIAdapter:
35
+ def __init__(
36
+ self,
37
+ model: str,
38
+ tools: list[ToolSpec] | None = None,
39
+ system_prompt: str | None = None,
40
+ api_key: str | None = None,
41
+ base_url: str = "https://api.openai.com/v1",
42
+ max_tool_iterations: int = 10,
43
+ seed: int | None = None,
44
+ timeout: float = 30.0,
45
+ client: httpx.Client | None = None,
46
+ ) -> None:
47
+ self.model = model
48
+ self.tools = tools or []
49
+ self.system_prompt = system_prompt
50
+ self.api_key = api_key
51
+ self.base_url = base_url.rstrip("/")
52
+ self.max_tool_iterations = max_tool_iterations
53
+ self.seed = seed
54
+ self._handlers = {tool.name: tool.handler for tool in self.tools}
55
+ self._client = client or httpx.Client(timeout=timeout)
56
+
57
+ def close(self) -> None:
58
+ self._client.close()
59
+
60
+ # Drives the chat-completions tool-calling loop for a single prompt,
61
+ # executing any requested tools locally, until the model answers
62
+ # without requesting further tool calls or max_tool_iterations is hit.
63
+ def run(self, prompt: str) -> AgentResult:
64
+ messages: list[dict[str, Any]] = []
65
+ if self.system_prompt:
66
+ messages.append({"role": "system", "content": self.system_prompt})
67
+ messages.append({"role": "user", "content": prompt})
68
+
69
+ tool_calls: list[ToolCall] = []
70
+ prompt_tokens = 0
71
+ completion_tokens = 0
72
+
73
+ for _ in range(self.max_tool_iterations):
74
+ response = self._complete(messages)
75
+ usage = response.get("usage") or {}
76
+ prompt_tokens += usage.get("prompt_tokens", 0)
77
+ completion_tokens += usage.get("completion_tokens", 0)
78
+
79
+ message = response["choices"][0]["message"]
80
+ messages.append(message)
81
+
82
+ requested_calls = message.get("tool_calls") or []
83
+ if not requested_calls:
84
+ return AgentResult(
85
+ output=message.get("content") or "",
86
+ tool_calls=tool_calls,
87
+ prompt_tokens=prompt_tokens,
88
+ completion_tokens=completion_tokens,
89
+ raw_messages=messages,
90
+ )
91
+
92
+ for call in requested_calls:
93
+ tool_calls.append(self._execute_tool_call(call, messages))
94
+
95
+ return AgentResult(
96
+ output=messages[-1].get("content") or "",
97
+ tool_calls=tool_calls,
98
+ prompt_tokens=prompt_tokens,
99
+ completion_tokens=completion_tokens,
100
+ raw_messages=messages,
101
+ )
102
+
103
+ # Sends one chat-completions request, translating network-level and
104
+ # 429/5xx failures into TransportError so the runner knows to retry.
105
+ def _complete(self, messages: list[dict[str, Any]]) -> dict[str, Any]:
106
+ payload: dict[str, Any] = {"model": self.model, "messages": messages}
107
+ if self.tools:
108
+ payload["tools"] = [tool.to_openai_format() for tool in self.tools]
109
+ if self.seed is not None:
110
+ payload["seed"] = self.seed
111
+
112
+ try:
113
+ response = self._client.post(
114
+ f"{self.base_url}/chat/completions",
115
+ json=payload,
116
+ headers={"Authorization": f"Bearer {self.api_key}"},
117
+ )
118
+ except httpx.TransportError as exc:
119
+ raise TransportError(str(exc)) from exc
120
+
121
+ if response.status_code == 429 or response.status_code >= 500:
122
+ raise TransportError(f"{response.status_code}: {response.text}")
123
+ response.raise_for_status()
124
+ return cast(dict[str, Any], response.json())
125
+
126
+ # Runs one model-requested tool call locally and records its outcome,
127
+ # appending the tool's response (or its error) back into the transcript.
128
+ def _execute_tool_call(self, call: dict[str, Any], messages: list[dict[str, Any]]) -> ToolCall:
129
+ name = call["function"]["name"]
130
+ arguments = json.loads(call["function"]["arguments"] or "{}")
131
+ handler = self._handlers.get(name)
132
+
133
+ start = time.monotonic()
134
+ error: str | None = None
135
+ result: Any = None
136
+ try:
137
+ if handler is None:
138
+ raise LookupError(f"no handler registered for tool {name!r}")
139
+ result = handler(**arguments)
140
+ except Exception as exc:
141
+ error = str(exc)
142
+ duration_ms = (time.monotonic() - start) * 1000
143
+
144
+ messages.append(
145
+ {
146
+ "role": "tool",
147
+ "tool_call_id": call["id"],
148
+ "content": f"Error: {error}" if error else json.dumps(result),
149
+ }
150
+ )
151
+ return ToolCall(
152
+ name=name, arguments=arguments, result=result, error=error, duration_ms=duration_ms
153
+ )