trybench-sdk 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.
- trybench_sdk-0.1.0/LICENSE +201 -0
- trybench_sdk-0.1.0/MANIFEST.in +2 -0
- trybench_sdk-0.1.0/PKG-INFO +155 -0
- trybench_sdk-0.1.0/README.md +139 -0
- trybench_sdk-0.1.0/examples/simulate_refund.py +30 -0
- trybench_sdk-0.1.0/pyproject.toml +24 -0
- trybench_sdk-0.1.0/setup.cfg +4 -0
- trybench_sdk-0.1.0/src/bench_sdk/__init__.py +6 -0
- trybench_sdk-0.1.0/src/bench_sdk/client.py +290 -0
- trybench_sdk-0.1.0/src/bench_sdk/evaluation.py +258 -0
- trybench_sdk-0.1.0/src/bench_sdk/py.typed +0 -0
- trybench_sdk-0.1.0/src/trybench_sdk.egg-info/PKG-INFO +155 -0
- trybench_sdk-0.1.0/src/trybench_sdk.egg-info/SOURCES.txt +16 -0
- trybench_sdk-0.1.0/src/trybench_sdk.egg-info/dependency_links.txt +1 -0
- trybench_sdk-0.1.0/src/trybench_sdk.egg-info/top_level.txt +1 -0
- trybench_sdk-0.1.0/tests/fixtures/privacy.json +17 -0
- trybench_sdk-0.1.0/tests/test_client.py +165 -0
- trybench_sdk-0.1.0/tests/test_evaluation.py +210 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: trybench-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Trace AI applications and test their behavior with Bench
|
|
5
|
+
Author: Bench
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Documentation, https://docs.usebench.ai/sdk/python
|
|
8
|
+
Project-URL: Repository, https://github.com/trybench/bench-sdk
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# Bench Python SDK · Beta
|
|
18
|
+
|
|
19
|
+
**Beta, version 0.1.0.** Pin versions and test upgrades in staging.
|
|
20
|
+
|
|
21
|
+
Trace Python applications, agents and tools without changing their behavior.
|
|
22
|
+
Python 3.10+. No third-party runtime dependencies. Apache-2.0.
|
|
23
|
+
|
|
24
|
+
Install with `python -m pip install trybench-sdk`. The Python import is `bench_sdk`.
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
import os
|
|
28
|
+
from bench_sdk import Bench
|
|
29
|
+
|
|
30
|
+
bench = Bench(
|
|
31
|
+
api_key=os.environ["BENCH_API_KEY"],
|
|
32
|
+
repository="your-team/your-app",
|
|
33
|
+
branch="main",
|
|
34
|
+
environment="staging",
|
|
35
|
+
system_name="Support agent",
|
|
36
|
+
endpoint=os.environ.get("BENCH_API_BASE_URL", "https://api.trybench.ai"),
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
with bench.trace("support-request", kind="AGENT") as span:
|
|
41
|
+
# Call your existing application here.
|
|
42
|
+
result = handle_request()
|
|
43
|
+
span.set_output(result)
|
|
44
|
+
finally:
|
|
45
|
+
# Deliver success and failure events after this application's work finishes.
|
|
46
|
+
bench.shutdown()
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Use the same `with bench.trace(...)` around `await agent.ainvoke(...)` in an
|
|
50
|
+
async application, then `await bench.aflush()`. Context is preserved across
|
|
51
|
+
await points and inherited by nested tasks. Wrap tools in nested spans with
|
|
52
|
+
`kind="TOOL"`. Separate requests started outside a parent get separate trace IDs.
|
|
53
|
+
|
|
54
|
+
Works with explicit wrappers around Deep Agents, LangGraph, LangChain, model
|
|
55
|
+
clients and custom Python code. It does not automatically instrument framework
|
|
56
|
+
internals or consume a streaming result; keep the span open while reading the stream.
|
|
57
|
+
|
|
58
|
+
Inputs, outputs and custom attributes are omitted by default. With permission,
|
|
59
|
+
set `capture_content=True`, pass `input=...` and call `span.set_output(...)`.
|
|
60
|
+
Built-in matching removes common secrets, emails, supported phone numbers, IPv4
|
|
61
|
+
addresses, card patterns and sensitive structured fields before transmission.
|
|
62
|
+
Add a `redact(value)` callback for application-specific data. These rules do not
|
|
63
|
+
recognize every personal detail in free text.
|
|
64
|
+
|
|
65
|
+
Set `component_id` to a real prompt component from Bench to link the event to
|
|
66
|
+
its criteria. Use operational attributes such as `gen_ai.usage.input_tokens`
|
|
67
|
+
and `gen_ai.usage.output_tokens` for usage counts. Never invent component IDs.
|
|
68
|
+
|
|
69
|
+
The queue defaults to 200 spans. Flush explicitly at request or process lifecycle
|
|
70
|
+
boundaries. Transient delivery failures retry once with unchanged IDs, then drop
|
|
71
|
+
the batch. `bench.stats` reports queued and dropped spans. `on_error(message)`
|
|
72
|
+
receives a fixed message, without content or keys. A telemetry failure does not
|
|
73
|
+
replace an application exception. This is a bounded queue, not durable storage.
|
|
74
|
+
|
|
75
|
+
## Test your application
|
|
76
|
+
|
|
77
|
+
`await bench.evaluate_system(...)` calls your application's request handler with
|
|
78
|
+
pinned cases. It captures the real nested tool/model traces, compares the final
|
|
79
|
+
output and independently observed state, and returns a redacted report locally.
|
|
80
|
+
Use a test database and test service credentials.
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
report = await bench.evaluate_system(
|
|
84
|
+
source_revision=os.environ["GIT_COMMIT_SHA"], # Full 40-character commit SHA
|
|
85
|
+
context_revision="refund-policy-v1",
|
|
86
|
+
cases=[{
|
|
87
|
+
"id": "outside-refund-policy", "split": "regression",
|
|
88
|
+
"input": {"days": 45}, "expected_output": {"refunded": False},
|
|
89
|
+
"forbidden_tools": ["issue-refund"],
|
|
90
|
+
}],
|
|
91
|
+
run=lambda request, context: handle_request(request),
|
|
92
|
+
)
|
|
93
|
+
assert report["summary"]["status"] == "completed"
|
|
94
|
+
assert all(case["status"] == "passed" for case in report["cases"])
|
|
95
|
+
# Explicit upload, only when you want this report saved in Bench:
|
|
96
|
+
await bench.publish_system_evaluation(int(os.environ["BENCH_SYSTEM_ID"]), report)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`run(input, context)` and `observe(context)` may be synchronous or asynchronous.
|
|
100
|
+
When a case has `expected_state`, supply `observe` to read the authoritative test
|
|
101
|
+
state. Context provides `case_id`, `cancelled`, `signal`, `deadline` and
|
|
102
|
+
`raise_if_cancelled()`. Inputs are JSON snapshots; changes inside the application
|
|
103
|
+
do not change the case's assertions.
|
|
104
|
+
|
|
105
|
+
`await bench.simulate_system(...)` accepts the same revisions and cases, plus
|
|
106
|
+
`create_session(initial_state, context)`. Cases use
|
|
107
|
+
`input={"initial_state": {...}, "turns": [...]}` and require `expected_state`.
|
|
108
|
+
Return an object with `turn(message, context)`, `observe()` and `close()` methods.
|
|
109
|
+
A fresh session receives 1 to 20 scripted customer turns. Bench snapshots observed
|
|
110
|
+
state before closing the session. `context.turn_index` identifies the turn.
|
|
111
|
+
|
|
112
|
+
Both helpers use a 30-second timeout per case, configurable with `timeout` up to
|
|
113
|
+
300 seconds. Pass a `threading.Event` as `cancel_event` to stop the suite. Missing
|
|
114
|
+
assertions, missing state, unfinished traces and timeouts remain incomplete.
|
|
115
|
+
Callbacks must honor cancellation; Python cannot forcibly stop a synchronous
|
|
116
|
+
thread. Await all child work and isolate external side effects. These helpers
|
|
117
|
+
are local execution, not a process sandbox or a hosted verification claim.
|
|
118
|
+
|
|
119
|
+
Tests record redacted content even when production capture is metadata-only, so
|
|
120
|
+
use synthetic inputs. Reports are not uploaded and paid checks are not started
|
|
121
|
+
unless you take a separate explicit action. Automatic framework adapters are
|
|
122
|
+
coming soon.
|
|
123
|
+
|
|
124
|
+
Run checks from this directory:
|
|
125
|
+
|
|
126
|
+
```sh
|
|
127
|
+
PYTHONPATH=src python -m unittest discover -s tests -v
|
|
128
|
+
python -m build
|
|
129
|
+
python -m twine check dist/*
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
See [Bench documentation](https://docs.usebench.ai/sdk/python) and the repository's
|
|
133
|
+
[publishing guide](../PUBLISHING.md).
|
|
134
|
+
|
|
135
|
+
## Latency, tool calls and cost
|
|
136
|
+
|
|
137
|
+
Every recorded call carries start/end timestamps, status, parent span ID and an
|
|
138
|
+
automatically measured `bench.duration_ms` from a monotonic clock. Wrap each tool
|
|
139
|
+
execution, including retries, with a TOOL span to retain its individual timing.
|
|
140
|
+
Use `gen_ai.operation.name=execute_tool` and `gen_ai.tool.name` for tool identity.
|
|
141
|
+
Production sampling can omit traces; a rate of 1 records each instrumented call.
|
|
142
|
+
The bounded delivery queue is not a guarantee against network or process loss.
|
|
143
|
+
|
|
144
|
+
Add `gen_ai.provider.name`, `gen_ai.request.model`, `gen_ai.response.model`,
|
|
145
|
+
`gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` when your provider
|
|
146
|
+
returns them. Add `bench.cost.usd` for the cost of that individual call and
|
|
147
|
+
`bench.cost.source` as `reported` or `estimated`. For estimates, also include
|
|
148
|
+
`bench.cost.pricing_version`. These fields survive metadata-only capture, so you
|
|
149
|
+
can measure usage without recording prompts or responses. Missing cost is unknown,
|
|
150
|
+
not zero. Do not repeat a child cost on its parent or count overlapping token
|
|
151
|
+
categories twice. The SDK does not guess provider prices or a tool's own charges.
|
|
152
|
+
|
|
153
|
+
The `gen_ai.*` names follow selected OpenTelemetry conventions. `bench.cost.*` and
|
|
154
|
+
`bench.duration_ms` are Bench extensions. Events currently use Bench JSON over
|
|
155
|
+
HTTPS; this release is not an OTLP exporter or collector.
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# Bench Python SDK · Beta
|
|
2
|
+
|
|
3
|
+
**Beta, version 0.1.0.** Pin versions and test upgrades in staging.
|
|
4
|
+
|
|
5
|
+
Trace Python applications, agents and tools without changing their behavior.
|
|
6
|
+
Python 3.10+. No third-party runtime dependencies. Apache-2.0.
|
|
7
|
+
|
|
8
|
+
Install with `python -m pip install trybench-sdk`. The Python import is `bench_sdk`.
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
import os
|
|
12
|
+
from bench_sdk import Bench
|
|
13
|
+
|
|
14
|
+
bench = Bench(
|
|
15
|
+
api_key=os.environ["BENCH_API_KEY"],
|
|
16
|
+
repository="your-team/your-app",
|
|
17
|
+
branch="main",
|
|
18
|
+
environment="staging",
|
|
19
|
+
system_name="Support agent",
|
|
20
|
+
endpoint=os.environ.get("BENCH_API_BASE_URL", "https://api.trybench.ai"),
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
with bench.trace("support-request", kind="AGENT") as span:
|
|
25
|
+
# Call your existing application here.
|
|
26
|
+
result = handle_request()
|
|
27
|
+
span.set_output(result)
|
|
28
|
+
finally:
|
|
29
|
+
# Deliver success and failure events after this application's work finishes.
|
|
30
|
+
bench.shutdown()
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Use the same `with bench.trace(...)` around `await agent.ainvoke(...)` in an
|
|
34
|
+
async application, then `await bench.aflush()`. Context is preserved across
|
|
35
|
+
await points and inherited by nested tasks. Wrap tools in nested spans with
|
|
36
|
+
`kind="TOOL"`. Separate requests started outside a parent get separate trace IDs.
|
|
37
|
+
|
|
38
|
+
Works with explicit wrappers around Deep Agents, LangGraph, LangChain, model
|
|
39
|
+
clients and custom Python code. It does not automatically instrument framework
|
|
40
|
+
internals or consume a streaming result; keep the span open while reading the stream.
|
|
41
|
+
|
|
42
|
+
Inputs, outputs and custom attributes are omitted by default. With permission,
|
|
43
|
+
set `capture_content=True`, pass `input=...` and call `span.set_output(...)`.
|
|
44
|
+
Built-in matching removes common secrets, emails, supported phone numbers, IPv4
|
|
45
|
+
addresses, card patterns and sensitive structured fields before transmission.
|
|
46
|
+
Add a `redact(value)` callback for application-specific data. These rules do not
|
|
47
|
+
recognize every personal detail in free text.
|
|
48
|
+
|
|
49
|
+
Set `component_id` to a real prompt component from Bench to link the event to
|
|
50
|
+
its criteria. Use operational attributes such as `gen_ai.usage.input_tokens`
|
|
51
|
+
and `gen_ai.usage.output_tokens` for usage counts. Never invent component IDs.
|
|
52
|
+
|
|
53
|
+
The queue defaults to 200 spans. Flush explicitly at request or process lifecycle
|
|
54
|
+
boundaries. Transient delivery failures retry once with unchanged IDs, then drop
|
|
55
|
+
the batch. `bench.stats` reports queued and dropped spans. `on_error(message)`
|
|
56
|
+
receives a fixed message, without content or keys. A telemetry failure does not
|
|
57
|
+
replace an application exception. This is a bounded queue, not durable storage.
|
|
58
|
+
|
|
59
|
+
## Test your application
|
|
60
|
+
|
|
61
|
+
`await bench.evaluate_system(...)` calls your application's request handler with
|
|
62
|
+
pinned cases. It captures the real nested tool/model traces, compares the final
|
|
63
|
+
output and independently observed state, and returns a redacted report locally.
|
|
64
|
+
Use a test database and test service credentials.
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
report = await bench.evaluate_system(
|
|
68
|
+
source_revision=os.environ["GIT_COMMIT_SHA"], # Full 40-character commit SHA
|
|
69
|
+
context_revision="refund-policy-v1",
|
|
70
|
+
cases=[{
|
|
71
|
+
"id": "outside-refund-policy", "split": "regression",
|
|
72
|
+
"input": {"days": 45}, "expected_output": {"refunded": False},
|
|
73
|
+
"forbidden_tools": ["issue-refund"],
|
|
74
|
+
}],
|
|
75
|
+
run=lambda request, context: handle_request(request),
|
|
76
|
+
)
|
|
77
|
+
assert report["summary"]["status"] == "completed"
|
|
78
|
+
assert all(case["status"] == "passed" for case in report["cases"])
|
|
79
|
+
# Explicit upload, only when you want this report saved in Bench:
|
|
80
|
+
await bench.publish_system_evaluation(int(os.environ["BENCH_SYSTEM_ID"]), report)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`run(input, context)` and `observe(context)` may be synchronous or asynchronous.
|
|
84
|
+
When a case has `expected_state`, supply `observe` to read the authoritative test
|
|
85
|
+
state. Context provides `case_id`, `cancelled`, `signal`, `deadline` and
|
|
86
|
+
`raise_if_cancelled()`. Inputs are JSON snapshots; changes inside the application
|
|
87
|
+
do not change the case's assertions.
|
|
88
|
+
|
|
89
|
+
`await bench.simulate_system(...)` accepts the same revisions and cases, plus
|
|
90
|
+
`create_session(initial_state, context)`. Cases use
|
|
91
|
+
`input={"initial_state": {...}, "turns": [...]}` and require `expected_state`.
|
|
92
|
+
Return an object with `turn(message, context)`, `observe()` and `close()` methods.
|
|
93
|
+
A fresh session receives 1 to 20 scripted customer turns. Bench snapshots observed
|
|
94
|
+
state before closing the session. `context.turn_index` identifies the turn.
|
|
95
|
+
|
|
96
|
+
Both helpers use a 30-second timeout per case, configurable with `timeout` up to
|
|
97
|
+
300 seconds. Pass a `threading.Event` as `cancel_event` to stop the suite. Missing
|
|
98
|
+
assertions, missing state, unfinished traces and timeouts remain incomplete.
|
|
99
|
+
Callbacks must honor cancellation; Python cannot forcibly stop a synchronous
|
|
100
|
+
thread. Await all child work and isolate external side effects. These helpers
|
|
101
|
+
are local execution, not a process sandbox or a hosted verification claim.
|
|
102
|
+
|
|
103
|
+
Tests record redacted content even when production capture is metadata-only, so
|
|
104
|
+
use synthetic inputs. Reports are not uploaded and paid checks are not started
|
|
105
|
+
unless you take a separate explicit action. Automatic framework adapters are
|
|
106
|
+
coming soon.
|
|
107
|
+
|
|
108
|
+
Run checks from this directory:
|
|
109
|
+
|
|
110
|
+
```sh
|
|
111
|
+
PYTHONPATH=src python -m unittest discover -s tests -v
|
|
112
|
+
python -m build
|
|
113
|
+
python -m twine check dist/*
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
See [Bench documentation](https://docs.usebench.ai/sdk/python) and the repository's
|
|
117
|
+
[publishing guide](../PUBLISHING.md).
|
|
118
|
+
|
|
119
|
+
## Latency, tool calls and cost
|
|
120
|
+
|
|
121
|
+
Every recorded call carries start/end timestamps, status, parent span ID and an
|
|
122
|
+
automatically measured `bench.duration_ms` from a monotonic clock. Wrap each tool
|
|
123
|
+
execution, including retries, with a TOOL span to retain its individual timing.
|
|
124
|
+
Use `gen_ai.operation.name=execute_tool` and `gen_ai.tool.name` for tool identity.
|
|
125
|
+
Production sampling can omit traces; a rate of 1 records each instrumented call.
|
|
126
|
+
The bounded delivery queue is not a guarantee against network or process loss.
|
|
127
|
+
|
|
128
|
+
Add `gen_ai.provider.name`, `gen_ai.request.model`, `gen_ai.response.model`,
|
|
129
|
+
`gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` when your provider
|
|
130
|
+
returns them. Add `bench.cost.usd` for the cost of that individual call and
|
|
131
|
+
`bench.cost.source` as `reported` or `estimated`. For estimates, also include
|
|
132
|
+
`bench.cost.pricing_version`. These fields survive metadata-only capture, so you
|
|
133
|
+
can measure usage without recording prompts or responses. Missing cost is unknown,
|
|
134
|
+
not zero. Do not repeat a child cost on its parent or count overlapping token
|
|
135
|
+
categories twice. The SDK does not guess provider prices or a tool's own charges.
|
|
136
|
+
|
|
137
|
+
The `gen_ai.*` names follow selected OpenTelemetry conventions. `bench.cost.*` and
|
|
138
|
+
`bench.duration_ms` are Bench extensions. Events currently use Bench JSON over
|
|
139
|
+
HTTPS; this release is not an OTLP exporter or collector.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Run locally: python python/examples/simulate_refund.py. No upload or model call."""
|
|
2
|
+
import asyncio
|
|
3
|
+
from bench_sdk import Bench
|
|
4
|
+
|
|
5
|
+
async def main():
|
|
6
|
+
bench = Bench(api_key="bench_sk_local_example", repository="example/refunds", branch="test")
|
|
7
|
+
class Session:
|
|
8
|
+
def __init__(self, state, fixed):
|
|
9
|
+
self.state, self.fixed = state, fixed
|
|
10
|
+
def turn(self, message, context):
|
|
11
|
+
with bench.trace("refund", kind="TOOL") as span:
|
|
12
|
+
if not self.fixed or self.state["refunds"] == 0:
|
|
13
|
+
self.state["refunds"] += 1
|
|
14
|
+
span.set_output("Refunded")
|
|
15
|
+
return "Refunded"
|
|
16
|
+
def observe(self):
|
|
17
|
+
return self.state
|
|
18
|
+
def close(self):
|
|
19
|
+
self.state["refunds"] = 0
|
|
20
|
+
cases = [{"id":"refund-retry", "input":{"initial_state":{"refunds":0}, "turns":["Refund order A", "Retry that refund"]}, "expected_output":"Refunded", "expected_state":{"refunds":1}}]
|
|
21
|
+
options = dict(source_revision="a"*40, context_revision="refund-policy-v1", cases=cases)
|
|
22
|
+
before = await bench.simulate_system(**options, create_session=lambda state, ctx: Session(state,False))
|
|
23
|
+
after = await bench.simulate_system(**options, create_session=lambda state, ctx: Session(state,True))
|
|
24
|
+
assert before["summary"]["score"] == 0 and after["summary"]["score"] == 100
|
|
25
|
+
assert before["suite_hash"] == after["suite_hash"]
|
|
26
|
+
print({"before":before["summary"], "after":after["summary"]})
|
|
27
|
+
await bench.aflush()
|
|
28
|
+
|
|
29
|
+
if __name__ == "__main__":
|
|
30
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.3"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "trybench-sdk"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Trace AI applications and test their behavior with Bench"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{name = "Bench"}]
|
|
14
|
+
classifiers = ["Development Status :: 4 - Beta", "Programming Language :: Python :: 3", "Operating System :: OS Independent"]
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Documentation = "https://docs.usebench.ai/sdk/python"
|
|
18
|
+
Repository = "https://github.com/trybench/bench-sdk"
|
|
19
|
+
|
|
20
|
+
[tool.setuptools.packages.find]
|
|
21
|
+
where = ["src"]
|
|
22
|
+
|
|
23
|
+
[tool.setuptools.package-data]
|
|
24
|
+
bench_sdk = ["py.typed"]
|