pijev 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.
- pijev-0.1.0/LICENSE +202 -0
- pijev-0.1.0/PKG-INFO +244 -0
- pijev-0.1.0/README.md +231 -0
- pijev-0.1.0/pijev/__init__.py +178 -0
- pijev-0.1.0/pijev/py.typed +0 -0
- pijev-0.1.0/pijev.egg-info/PKG-INFO +244 -0
- pijev-0.1.0/pijev.egg-info/SOURCES.txt +11 -0
- pijev-0.1.0/pijev.egg-info/dependency_links.txt +1 -0
- pijev-0.1.0/pijev.egg-info/requires.txt +1 -0
- pijev-0.1.0/pijev.egg-info/top_level.txt +1 -0
- pijev-0.1.0/pyproject.toml +23 -0
- pijev-0.1.0/setup.cfg +4 -0
- pijev-0.1.0/tests/test_symmetry.py +128 -0
pijev-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
pijev-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pijev
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Permutation Invariant Jev — third-party permutation averaging for TypeSafe Choice
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Repository, https://github.com/TypeLLM/pijev
|
|
7
|
+
Project-URL: Issues, https://github.com/TypeLLM/pijev/issues
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: typesafe-sdk<0.8,>=0.7.1
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# pijev — Permutation Invariant Jev
|
|
15
|
+
|
|
16
|
+
**Better Jev probabilities with theoretical guarantees—all with a one-line import change.**
|
|
17
|
+
|
|
18
|
+
pijev turns Jev's option-order variations into a single averaged prediction, with
|
|
19
|
+
Brier score and log loss guaranteed no worse than the average across the included
|
|
20
|
+
orderings. All permutations run in one `system_one` request. Keep the same calls
|
|
21
|
+
and official response types; pijev handles the rest.
|
|
22
|
+
|
|
23
|
+
## Problem: Jev's decision is not permutation invariant
|
|
24
|
+
|
|
25
|
+
The same options can receive different probabilities when reordered. This official
|
|
26
|
+
SDK call sends two Choices with identical instructions and descriptions, but
|
|
27
|
+
opposite option orders:
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from typesafe_sdk import Choice, TypeSafeClient
|
|
31
|
+
|
|
32
|
+
instructions = "Which team should handle this support ticket? Choose the best primary team."
|
|
33
|
+
|
|
34
|
+
with TypeSafeClient() as client:
|
|
35
|
+
response = client.system_one(
|
|
36
|
+
state={
|
|
37
|
+
"ticket": "Since upgrading my plan yesterday, I cannot access the "
|
|
38
|
+
"dashboard. The payment went through, but the page says "
|
|
39
|
+
"my subscription is inactive. Please fix this."
|
|
40
|
+
},
|
|
41
|
+
questions={
|
|
42
|
+
"forward": Choice(
|
|
43
|
+
instructions=instructions,
|
|
44
|
+
criteria={
|
|
45
|
+
"billing": "Payments, charges, invoices, and refunds.",
|
|
46
|
+
"technical": "Product failures, errors, and troubleshooting.",
|
|
47
|
+
"account": "Login, account access, and account settings.",
|
|
48
|
+
},
|
|
49
|
+
),
|
|
50
|
+
"reverse": Choice(
|
|
51
|
+
instructions=instructions,
|
|
52
|
+
criteria={
|
|
53
|
+
"account": "Login, account access, and account settings.",
|
|
54
|
+
"technical": "Product failures, errors, and troubleshooting.",
|
|
55
|
+
"billing": "Payments, charges, invoices, and refunds.",
|
|
56
|
+
},
|
|
57
|
+
),
|
|
58
|
+
},
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
print(response.choices["forward"].probabilities)
|
|
62
|
+
print(response.choices["reverse"].probabilities)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
One request, two questions, one shared state. A live `jev-1.13.0` run returned:
|
|
66
|
+
|
|
67
|
+
| Option | billing → technical → account | account → technical → billing |
|
|
68
|
+
| --- | ---: | ---: |
|
|
69
|
+
| billing | 0.43 | 0.63 |
|
|
70
|
+
| technical | 0.21 | 0.10 |
|
|
71
|
+
| account | 0.36 | 0.27 |
|
|
72
|
+
|
|
73
|
+
Both selected `billing`, but its probability changed by **20 percentage points**.
|
|
74
|
+
This run also changes question IDs and does not control model randomness; see the
|
|
75
|
+
[experiment details](https://github.com/TypeLLM/pijev/blob/main/examples/README.md).
|
|
76
|
+
|
|
77
|
+
## How pijev works
|
|
78
|
+
|
|
79
|
+
pijev treats option order as a nuisance variable: evaluate different orderings,
|
|
80
|
+
align predictions by label, and average their probabilities. The highest mean
|
|
81
|
+
probability determines the returned choice.
|
|
82
|
+
|
|
83
|
+
For three options, there are six permutations. Here is a separate live
|
|
84
|
+
`jev-1.13.0` run with **all six in one request**. A = account, B = billing,
|
|
85
|
+
T = technical.
|
|
86
|
+
|
|
87
|
+
| Option | A → B → T | A → T → B | B → A → T | B → T → A | T → A → B | T → B → A | pijev mean |
|
|
88
|
+
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
|
89
|
+
| billing | 0.58 | 0.64 | 0.58 | 0.46 | 0.47 | 0.60 | **0.5550** |
|
|
90
|
+
| technical | 0.17 | 0.08 | 0.11 | 0.23 | 0.12 | 0.12 | 0.1383 |
|
|
91
|
+
| account | 0.25 | 0.28 | 0.31 | 0.31 | 0.41 | 0.28 | 0.3067 |
|
|
92
|
+
|
|
93
|
+
The `pijev mean` column averages all six predictions: `billing` receives **0.555**,
|
|
94
|
+
compared with 0.46–0.64 across individual orderings.
|
|
95
|
+
[Reproduce this run](https://github.com/TypeLLM/pijev/blob/main/examples/compare_all_orders.py) · [Recorded results](https://github.com/TypeLLM/pijev/blob/main/examples/six_orders_result.json)
|
|
96
|
+
|
|
97
|
+
Ask once using the same SDK interface; pijev handles the six-question batch and
|
|
98
|
+
returns one aggregated answer:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from pijev import Choice, TypeSafeClient
|
|
102
|
+
|
|
103
|
+
with TypeSafeClient() as client:
|
|
104
|
+
response = client.system_one(
|
|
105
|
+
state={
|
|
106
|
+
"ticket": "Since upgrading my plan yesterday, I cannot access the "
|
|
107
|
+
"dashboard. The payment went through, but the page says "
|
|
108
|
+
"my subscription is inactive. Please fix this."
|
|
109
|
+
},
|
|
110
|
+
questions={
|
|
111
|
+
"team": Choice(
|
|
112
|
+
instructions="Which team should handle this support ticket? "
|
|
113
|
+
"Choose the best primary team.",
|
|
114
|
+
criteria={
|
|
115
|
+
"billing": "Payments, charges, invoices, and refunds.",
|
|
116
|
+
"technical": "Product failures, errors, and troubleshooting.",
|
|
117
|
+
"account": "Login, account access, and account settings.",
|
|
118
|
+
},
|
|
119
|
+
),
|
|
120
|
+
},
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
answer = response.choices["team"]
|
|
124
|
+
print(answer.choice)
|
|
125
|
+
print(answer.probabilities)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
The result is an official `SystemOneResponse` with your original question names.
|
|
129
|
+
Live results may differ from the recorded run.
|
|
130
|
+
|
|
131
|
+
## Usage
|
|
132
|
+
|
|
133
|
+
Install from PyPI:
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
pip install pijev
|
|
137
|
+
export TYPESAFE_API_KEY=your-key
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Change only the import:
|
|
141
|
+
|
|
142
|
+
```diff
|
|
143
|
+
-from typesafe_sdk import TypeSafeClient, Choice, Noul, Score
|
|
144
|
+
+from pijev import TypeSafeClient, Choice, Noul, Score
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Set an optional permutation budget:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
client = TypeSafeClient(n_permutations=16, seed=42)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
The default is **up to 8 distinct permutations per Choice**. Smaller sets use all
|
|
154
|
+
permutations; larger sets use uniform sampling without replacement. Set
|
|
155
|
+
`n_permutations="all"` for full enumeration. The seed controls local sampling only.
|
|
156
|
+
Batches are capped at 720 expanded questions and remain subject to server limits.
|
|
157
|
+
|
|
158
|
+
Async usage works the same way: import `AsyncTypeSafeClient` from `pijev`, then use
|
|
159
|
+
`async with` and `await client.system_one(...)` as usual.
|
|
160
|
+
|
|
161
|
+
## Guaranteed Better Calibration
|
|
162
|
+
|
|
163
|
+
Permutation averaging has a **proper-scoring-loss guarantee**, not an unconditional
|
|
164
|
+
calibration guarantee. Let $p^{(m)}$ be the label-aligned probability vector for
|
|
165
|
+
permutation $m$, and let $y$ be the same correct answer under every ordering. Define
|
|
166
|
+
|
|
167
|
+
$$
|
|
168
|
+
\bar p = \frac{1}{M}\sum_{m=1}^{M}p^{(m)}.
|
|
169
|
+
$$
|
|
170
|
+
|
|
171
|
+
For any loss convex in the predicted probabilities, Jensen's inequality gives
|
|
172
|
+
|
|
173
|
+
$$
|
|
174
|
+
L(\bar p,y) \leq \frac{1}{M}\sum_{m=1}^{M}L(p^{(m)},y).
|
|
175
|
+
$$
|
|
176
|
+
|
|
177
|
+
This holds for the actual set of predictions being averaged, including a sampled
|
|
178
|
+
subset of permutations. Two useful cases are:
|
|
179
|
+
|
|
180
|
+
- **Log loss:** $-\log\bar p_y \leq \frac{1}{M}\sum_m -\log p_y^{(m)}$.
|
|
181
|
+
- **Brier score:** writing $e_y$ for the one-hot correct answer, the improvement
|
|
182
|
+
equals the disagreement removed by averaging:
|
|
183
|
+
|
|
184
|
+
$$
|
|
185
|
+
\frac{1}{M}\sum_m\|p^{(m)}-e_y\|_2^2 - \|\bar p-e_y\|_2^2
|
|
186
|
+
= \frac{1}{M}\sum_m\|p^{(m)}-\bar p\|_2^2 \geq 0.
|
|
187
|
+
$$
|
|
188
|
+
|
|
189
|
+
The guarantee compares the average prediction with **randomly choosing one of the
|
|
190
|
+
included predictions**. Brier improvement is strict when those predictions differ.
|
|
191
|
+
For uniform sampling and a fixed predictor, the same inequality holds in expectation
|
|
192
|
+
against a uniformly random ordering. Full enumeration gives the group average;
|
|
193
|
+
see [Chen, Dobriban, and Lee](https://jmlr.csail.mit.edu/papers/v21/20-163.html)
|
|
194
|
+
for related symmetry-averaging theory.
|
|
195
|
+
|
|
196
|
+
## Cost analysis
|
|
197
|
+
|
|
198
|
+
For $K$ options and budget $B$, pijev evaluates $M=\min(B,K!)$ permutations in
|
|
199
|
+
**one HTTP request**. Multiple Choices contribute their own permutations;
|
|
200
|
+
Noul and Score each add one unchanged question.
|
|
201
|
+
|
|
202
|
+
| Workload | Questions in one request |
|
|
203
|
+
| --- | ---: |
|
|
204
|
+
| 3 options, default budget 8 | 6 |
|
|
205
|
+
| 10 options, default budget 8 | 8 |
|
|
206
|
+
| Two Choices with 3 options each | 12 |
|
|
207
|
+
| 3 options plus one Noul | 7 |
|
|
208
|
+
|
|
209
|
+
The state is sent once. For state size $S$ and question size $Q$, request content
|
|
210
|
+
is approximately $S+MQ$, versus $M(S+Q)$ for separate calls, excluding protocol
|
|
211
|
+
overhead. This is a payload estimate; use `response.usage` for reported tokens.
|
|
212
|
+
|
|
213
|
+
At TypeSafe's [published rate](https://typesafe.ai/blog/introducing-system-one-models-and-jev)
|
|
214
|
+
of **$0.042 per million input tokens, with free output tokens** (checked 2026-09-22):
|
|
215
|
+
|
|
216
|
+
$$
|
|
217
|
+
C = \frac{T}{10^6}\times 0.042
|
|
218
|
+
$$
|
|
219
|
+
|
|
220
|
+
Here, $C$ is the estimated cost in USD and $T$ is `response.usage.input_tokens`.
|
|
221
|
+
|
|
222
|
+
| Recorded run | Input tokens | Estimated cost |
|
|
223
|
+
| --- | ---: | ---: |
|
|
224
|
+
| Two permutations | 475 | $0.00001995 |
|
|
225
|
+
| All six permutations | 835 | $0.00003507 |
|
|
226
|
+
|
|
227
|
+
These estimates use reported usage and the published rate, not invoice charges.
|
|
228
|
+
One request still contains multiple decisions; latency and billing depend on the
|
|
229
|
+
backend, and retries may add requests.
|
|
230
|
+
|
|
231
|
+
## Notes
|
|
232
|
+
|
|
233
|
+
- Only Choice answers are averaged. Noul and Score pass through unchanged.
|
|
234
|
+
- `confidence` is the selected label's mean probability, **not Jev's native
|
|
235
|
+
confidence score**.
|
|
236
|
+
- Sampling approximates full permutation averaging; it does not guarantee exact
|
|
237
|
+
order invariance or better calibration. The live examples demonstrate probability
|
|
238
|
+
differences, not accuracy or calibration gains.
|
|
239
|
+
- Official interface: [TypeSafe Python SDK](https://github.com/typesafe-ai/typesafe-sdk-python).
|
|
240
|
+
This is a third-party extension, not an official TypeSafe project.
|
|
241
|
+
|
|
242
|
+
## License
|
|
243
|
+
|
|
244
|
+
[Apache License 2.0](https://github.com/TypeLLM/pijev/blob/main/LICENSE).
|
pijev-0.1.0/README.md
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
# pijev — Permutation Invariant Jev
|
|
2
|
+
|
|
3
|
+
**Better Jev probabilities with theoretical guarantees—all with a one-line import change.**
|
|
4
|
+
|
|
5
|
+
pijev turns Jev's option-order variations into a single averaged prediction, with
|
|
6
|
+
Brier score and log loss guaranteed no worse than the average across the included
|
|
7
|
+
orderings. All permutations run in one `system_one` request. Keep the same calls
|
|
8
|
+
and official response types; pijev handles the rest.
|
|
9
|
+
|
|
10
|
+
## Problem: Jev's decision is not permutation invariant
|
|
11
|
+
|
|
12
|
+
The same options can receive different probabilities when reordered. This official
|
|
13
|
+
SDK call sends two Choices with identical instructions and descriptions, but
|
|
14
|
+
opposite option orders:
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
from typesafe_sdk import Choice, TypeSafeClient
|
|
18
|
+
|
|
19
|
+
instructions = "Which team should handle this support ticket? Choose the best primary team."
|
|
20
|
+
|
|
21
|
+
with TypeSafeClient() as client:
|
|
22
|
+
response = client.system_one(
|
|
23
|
+
state={
|
|
24
|
+
"ticket": "Since upgrading my plan yesterday, I cannot access the "
|
|
25
|
+
"dashboard. The payment went through, but the page says "
|
|
26
|
+
"my subscription is inactive. Please fix this."
|
|
27
|
+
},
|
|
28
|
+
questions={
|
|
29
|
+
"forward": Choice(
|
|
30
|
+
instructions=instructions,
|
|
31
|
+
criteria={
|
|
32
|
+
"billing": "Payments, charges, invoices, and refunds.",
|
|
33
|
+
"technical": "Product failures, errors, and troubleshooting.",
|
|
34
|
+
"account": "Login, account access, and account settings.",
|
|
35
|
+
},
|
|
36
|
+
),
|
|
37
|
+
"reverse": Choice(
|
|
38
|
+
instructions=instructions,
|
|
39
|
+
criteria={
|
|
40
|
+
"account": "Login, account access, and account settings.",
|
|
41
|
+
"technical": "Product failures, errors, and troubleshooting.",
|
|
42
|
+
"billing": "Payments, charges, invoices, and refunds.",
|
|
43
|
+
},
|
|
44
|
+
),
|
|
45
|
+
},
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
print(response.choices["forward"].probabilities)
|
|
49
|
+
print(response.choices["reverse"].probabilities)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
One request, two questions, one shared state. A live `jev-1.13.0` run returned:
|
|
53
|
+
|
|
54
|
+
| Option | billing → technical → account | account → technical → billing |
|
|
55
|
+
| --- | ---: | ---: |
|
|
56
|
+
| billing | 0.43 | 0.63 |
|
|
57
|
+
| technical | 0.21 | 0.10 |
|
|
58
|
+
| account | 0.36 | 0.27 |
|
|
59
|
+
|
|
60
|
+
Both selected `billing`, but its probability changed by **20 percentage points**.
|
|
61
|
+
This run also changes question IDs and does not control model randomness; see the
|
|
62
|
+
[experiment details](https://github.com/TypeLLM/pijev/blob/main/examples/README.md).
|
|
63
|
+
|
|
64
|
+
## How pijev works
|
|
65
|
+
|
|
66
|
+
pijev treats option order as a nuisance variable: evaluate different orderings,
|
|
67
|
+
align predictions by label, and average their probabilities. The highest mean
|
|
68
|
+
probability determines the returned choice.
|
|
69
|
+
|
|
70
|
+
For three options, there are six permutations. Here is a separate live
|
|
71
|
+
`jev-1.13.0` run with **all six in one request**. A = account, B = billing,
|
|
72
|
+
T = technical.
|
|
73
|
+
|
|
74
|
+
| Option | A → B → T | A → T → B | B → A → T | B → T → A | T → A → B | T → B → A | pijev mean |
|
|
75
|
+
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
|
76
|
+
| billing | 0.58 | 0.64 | 0.58 | 0.46 | 0.47 | 0.60 | **0.5550** |
|
|
77
|
+
| technical | 0.17 | 0.08 | 0.11 | 0.23 | 0.12 | 0.12 | 0.1383 |
|
|
78
|
+
| account | 0.25 | 0.28 | 0.31 | 0.31 | 0.41 | 0.28 | 0.3067 |
|
|
79
|
+
|
|
80
|
+
The `pijev mean` column averages all six predictions: `billing` receives **0.555**,
|
|
81
|
+
compared with 0.46–0.64 across individual orderings.
|
|
82
|
+
[Reproduce this run](https://github.com/TypeLLM/pijev/blob/main/examples/compare_all_orders.py) · [Recorded results](https://github.com/TypeLLM/pijev/blob/main/examples/six_orders_result.json)
|
|
83
|
+
|
|
84
|
+
Ask once using the same SDK interface; pijev handles the six-question batch and
|
|
85
|
+
returns one aggregated answer:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from pijev import Choice, TypeSafeClient
|
|
89
|
+
|
|
90
|
+
with TypeSafeClient() as client:
|
|
91
|
+
response = client.system_one(
|
|
92
|
+
state={
|
|
93
|
+
"ticket": "Since upgrading my plan yesterday, I cannot access the "
|
|
94
|
+
"dashboard. The payment went through, but the page says "
|
|
95
|
+
"my subscription is inactive. Please fix this."
|
|
96
|
+
},
|
|
97
|
+
questions={
|
|
98
|
+
"team": Choice(
|
|
99
|
+
instructions="Which team should handle this support ticket? "
|
|
100
|
+
"Choose the best primary team.",
|
|
101
|
+
criteria={
|
|
102
|
+
"billing": "Payments, charges, invoices, and refunds.",
|
|
103
|
+
"technical": "Product failures, errors, and troubleshooting.",
|
|
104
|
+
"account": "Login, account access, and account settings.",
|
|
105
|
+
},
|
|
106
|
+
),
|
|
107
|
+
},
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
answer = response.choices["team"]
|
|
111
|
+
print(answer.choice)
|
|
112
|
+
print(answer.probabilities)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
The result is an official `SystemOneResponse` with your original question names.
|
|
116
|
+
Live results may differ from the recorded run.
|
|
117
|
+
|
|
118
|
+
## Usage
|
|
119
|
+
|
|
120
|
+
Install from PyPI:
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
pip install pijev
|
|
124
|
+
export TYPESAFE_API_KEY=your-key
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Change only the import:
|
|
128
|
+
|
|
129
|
+
```diff
|
|
130
|
+
-from typesafe_sdk import TypeSafeClient, Choice, Noul, Score
|
|
131
|
+
+from pijev import TypeSafeClient, Choice, Noul, Score
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Set an optional permutation budget:
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
client = TypeSafeClient(n_permutations=16, seed=42)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
The default is **up to 8 distinct permutations per Choice**. Smaller sets use all
|
|
141
|
+
permutations; larger sets use uniform sampling without replacement. Set
|
|
142
|
+
`n_permutations="all"` for full enumeration. The seed controls local sampling only.
|
|
143
|
+
Batches are capped at 720 expanded questions and remain subject to server limits.
|
|
144
|
+
|
|
145
|
+
Async usage works the same way: import `AsyncTypeSafeClient` from `pijev`, then use
|
|
146
|
+
`async with` and `await client.system_one(...)` as usual.
|
|
147
|
+
|
|
148
|
+
## Guaranteed Better Calibration
|
|
149
|
+
|
|
150
|
+
Permutation averaging has a **proper-scoring-loss guarantee**, not an unconditional
|
|
151
|
+
calibration guarantee. Let $p^{(m)}$ be the label-aligned probability vector for
|
|
152
|
+
permutation $m$, and let $y$ be the same correct answer under every ordering. Define
|
|
153
|
+
|
|
154
|
+
$$
|
|
155
|
+
\bar p = \frac{1}{M}\sum_{m=1}^{M}p^{(m)}.
|
|
156
|
+
$$
|
|
157
|
+
|
|
158
|
+
For any loss convex in the predicted probabilities, Jensen's inequality gives
|
|
159
|
+
|
|
160
|
+
$$
|
|
161
|
+
L(\bar p,y) \leq \frac{1}{M}\sum_{m=1}^{M}L(p^{(m)},y).
|
|
162
|
+
$$
|
|
163
|
+
|
|
164
|
+
This holds for the actual set of predictions being averaged, including a sampled
|
|
165
|
+
subset of permutations. Two useful cases are:
|
|
166
|
+
|
|
167
|
+
- **Log loss:** $-\log\bar p_y \leq \frac{1}{M}\sum_m -\log p_y^{(m)}$.
|
|
168
|
+
- **Brier score:** writing $e_y$ for the one-hot correct answer, the improvement
|
|
169
|
+
equals the disagreement removed by averaging:
|
|
170
|
+
|
|
171
|
+
$$
|
|
172
|
+
\frac{1}{M}\sum_m\|p^{(m)}-e_y\|_2^2 - \|\bar p-e_y\|_2^2
|
|
173
|
+
= \frac{1}{M}\sum_m\|p^{(m)}-\bar p\|_2^2 \geq 0.
|
|
174
|
+
$$
|
|
175
|
+
|
|
176
|
+
The guarantee compares the average prediction with **randomly choosing one of the
|
|
177
|
+
included predictions**. Brier improvement is strict when those predictions differ.
|
|
178
|
+
For uniform sampling and a fixed predictor, the same inequality holds in expectation
|
|
179
|
+
against a uniformly random ordering. Full enumeration gives the group average;
|
|
180
|
+
see [Chen, Dobriban, and Lee](https://jmlr.csail.mit.edu/papers/v21/20-163.html)
|
|
181
|
+
for related symmetry-averaging theory.
|
|
182
|
+
|
|
183
|
+
## Cost analysis
|
|
184
|
+
|
|
185
|
+
For $K$ options and budget $B$, pijev evaluates $M=\min(B,K!)$ permutations in
|
|
186
|
+
**one HTTP request**. Multiple Choices contribute their own permutations;
|
|
187
|
+
Noul and Score each add one unchanged question.
|
|
188
|
+
|
|
189
|
+
| Workload | Questions in one request |
|
|
190
|
+
| --- | ---: |
|
|
191
|
+
| 3 options, default budget 8 | 6 |
|
|
192
|
+
| 10 options, default budget 8 | 8 |
|
|
193
|
+
| Two Choices with 3 options each | 12 |
|
|
194
|
+
| 3 options plus one Noul | 7 |
|
|
195
|
+
|
|
196
|
+
The state is sent once. For state size $S$ and question size $Q$, request content
|
|
197
|
+
is approximately $S+MQ$, versus $M(S+Q)$ for separate calls, excluding protocol
|
|
198
|
+
overhead. This is a payload estimate; use `response.usage` for reported tokens.
|
|
199
|
+
|
|
200
|
+
At TypeSafe's [published rate](https://typesafe.ai/blog/introducing-system-one-models-and-jev)
|
|
201
|
+
of **$0.042 per million input tokens, with free output tokens** (checked 2026-09-22):
|
|
202
|
+
|
|
203
|
+
$$
|
|
204
|
+
C = \frac{T}{10^6}\times 0.042
|
|
205
|
+
$$
|
|
206
|
+
|
|
207
|
+
Here, $C$ is the estimated cost in USD and $T$ is `response.usage.input_tokens`.
|
|
208
|
+
|
|
209
|
+
| Recorded run | Input tokens | Estimated cost |
|
|
210
|
+
| --- | ---: | ---: |
|
|
211
|
+
| Two permutations | 475 | $0.00001995 |
|
|
212
|
+
| All six permutations | 835 | $0.00003507 |
|
|
213
|
+
|
|
214
|
+
These estimates use reported usage and the published rate, not invoice charges.
|
|
215
|
+
One request still contains multiple decisions; latency and billing depend on the
|
|
216
|
+
backend, and retries may add requests.
|
|
217
|
+
|
|
218
|
+
## Notes
|
|
219
|
+
|
|
220
|
+
- Only Choice answers are averaged. Noul and Score pass through unchanged.
|
|
221
|
+
- `confidence` is the selected label's mean probability, **not Jev's native
|
|
222
|
+
confidence score**.
|
|
223
|
+
- Sampling approximates full permutation averaging; it does not guarantee exact
|
|
224
|
+
order invariance or better calibration. The live examples demonstrate probability
|
|
225
|
+
differences, not accuracy or calibration gains.
|
|
226
|
+
- Official interface: [TypeSafe Python SDK](https://github.com/typesafe-ai/typesafe-sdk-python).
|
|
227
|
+
This is a third-party extension, not an official TypeSafe project.
|
|
228
|
+
|
|
229
|
+
## License
|
|
230
|
+
|
|
231
|
+
[Apache License 2.0](https://github.com/TypeLLM/pijev/blob/main/LICENSE).
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Drop-in TypeSafe clients with batched permutation averaging for Choice."""
|
|
2
|
+
from collections.abc import Mapping
|
|
3
|
+
from itertools import permutations
|
|
4
|
+
from math import factorial, fsum, isclose, isfinite
|
|
5
|
+
from random import Random
|
|
6
|
+
from typing import Any, Literal, TypeVar, overload
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
|
|
9
|
+
import httpx2
|
|
10
|
+
from typesafe_sdk import * # Re-export the official public types.
|
|
11
|
+
from typesafe_sdk import __all__ as _sdk_exports
|
|
12
|
+
from typesafe_sdk import TypeSafeClient as _Client, AsyncTypeSafeClient as _AsyncClient
|
|
13
|
+
|
|
14
|
+
__all__ = list(_sdk_exports)
|
|
15
|
+
ResponseT = TypeVar("ResponseT", bound=BaseModel)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _validate_budget(budget):
|
|
19
|
+
if budget != "all" and (type(budget) is not int or budget <= 0):
|
|
20
|
+
raise ValueError("n_permutations must be a positive integer or 'all'")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _prepare(questions, budget, seed):
|
|
24
|
+
expanded, groups = {}, {}
|
|
25
|
+
# Reserve all original names, including names resembling generated IDs.
|
|
26
|
+
reserved = set(questions)
|
|
27
|
+
for name, question in questions.items():
|
|
28
|
+
if isinstance(question, Choice):
|
|
29
|
+
choice = question
|
|
30
|
+
elif isinstance(question, Mapping) and question.get("type") == "choice":
|
|
31
|
+
choice = Choice.model_validate(question)
|
|
32
|
+
else:
|
|
33
|
+
expanded[name] = question
|
|
34
|
+
continue
|
|
35
|
+
labels = tuple(sorted(choice.criteria))
|
|
36
|
+
if not labels:
|
|
37
|
+
raise ValueError("Choice criteria must not be empty")
|
|
38
|
+
total = factorial(len(labels))
|
|
39
|
+
count = total if budget == "all" else min(budget, total)
|
|
40
|
+
if len(expanded) + count > 720:
|
|
41
|
+
raise ValueError("At most 720 expanded questions per request")
|
|
42
|
+
if count == total:
|
|
43
|
+
orders = permutations(labels)
|
|
44
|
+
else:
|
|
45
|
+
rng, selected = Random(seed), {}
|
|
46
|
+
while len(selected) < count:
|
|
47
|
+
selected[tuple(rng.sample(labels, len(labels)))] = None
|
|
48
|
+
orders = selected
|
|
49
|
+
names = []
|
|
50
|
+
for order in orders:
|
|
51
|
+
key = f"__pijev_{len(expanded)}"
|
|
52
|
+
while key in reserved:
|
|
53
|
+
key += "_"
|
|
54
|
+
reserved.add(key)
|
|
55
|
+
item = choice.model_copy(deep=True)
|
|
56
|
+
item.criteria = {label: item.criteria[label] for label in order}
|
|
57
|
+
expanded[key] = item
|
|
58
|
+
names.append(key)
|
|
59
|
+
groups[name] = (labels, names)
|
|
60
|
+
if len(expanded) > 720:
|
|
61
|
+
raise ValueError("At most 720 expanded questions per request")
|
|
62
|
+
return expanded, groups
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _aggregate(response, questions, groups, response_model):
|
|
66
|
+
answers = {}
|
|
67
|
+
for name in questions:
|
|
68
|
+
if name not in groups:
|
|
69
|
+
if name not in response.answers:
|
|
70
|
+
raise ValueError(f"Backend did not return answer {name!r}")
|
|
71
|
+
answers[name] = response.answers[name].model_dump(mode="json")
|
|
72
|
+
continue
|
|
73
|
+
labels, names = groups[name]
|
|
74
|
+
rows = []
|
|
75
|
+
for key in names:
|
|
76
|
+
if key not in response.choices:
|
|
77
|
+
raise ValueError(f"Backend did not return Choice answer {key!r}")
|
|
78
|
+
raw = response.choices[key].probabilities
|
|
79
|
+
if set(raw) != set(labels):
|
|
80
|
+
raise ValueError("Backend probabilities must contain exactly the requested labels")
|
|
81
|
+
if any(not isfinite(p) or not 0 <= p <= 1 for p in raw.values()):
|
|
82
|
+
raise ValueError("Backend probabilities must be finite and between 0 and 1")
|
|
83
|
+
mass = fsum(raw.values())
|
|
84
|
+
if not isclose(mass, 1.0, rel_tol=0, abs_tol=1e-3):
|
|
85
|
+
raise ValueError("Backend probabilities must sum to approximately 1")
|
|
86
|
+
rows.append({label: raw[label] / mass for label in labels})
|
|
87
|
+
means = {label: fsum(row[label] for row in rows) / len(rows) for label in labels}
|
|
88
|
+
winner = max(labels, key=means.__getitem__)
|
|
89
|
+
answers[name] = ChoiceAnswer(choice=winner, probabilities=means,
|
|
90
|
+
confidence=means[winner]).model_dump(mode="json")
|
|
91
|
+
body = response.model_dump(mode="json")
|
|
92
|
+
body["answers"] = answers
|
|
93
|
+
raw = response.raw_http_response
|
|
94
|
+
# Parse through the official response decoder, including custom typed fields.
|
|
95
|
+
# This response represents the transformed body, with actual request metadata.
|
|
96
|
+
headers = {k: v for k, v in raw.headers.items()
|
|
97
|
+
if k.lower() not in {"content-length", "content-encoding"}}
|
|
98
|
+
transformed = httpx2.Response(raw.status_code, headers=headers, json=body,
|
|
99
|
+
request=raw.request)
|
|
100
|
+
target = response_model or SystemOneResponse
|
|
101
|
+
if issubclass(target, SystemOneResponse):
|
|
102
|
+
return target.from_http_response(transformed)
|
|
103
|
+
return target.model_validate_json(transformed.content)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _request_inputs(state, questions, extra_body, budget, seed):
|
|
107
|
+
# Match the SDK's documented extra_body last-write-wins semantics.
|
|
108
|
+
extra = dict(extra_body or {})
|
|
109
|
+
state = extra.pop("state", state)
|
|
110
|
+
questions = extra.pop("questions", questions)
|
|
111
|
+
expanded, groups = _prepare(questions, budget, seed)
|
|
112
|
+
return state, questions, expanded, groups, extra
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class TypeSafeClient(_Client):
|
|
116
|
+
"""Official sync client interface; Choice permutations share one request."""
|
|
117
|
+
|
|
118
|
+
def __init__(self, *args: Any, n_permutations: int | Literal["all"] = 8,
|
|
119
|
+
seed: int | None = None, **kwargs: Any) -> None:
|
|
120
|
+
_validate_budget(n_permutations)
|
|
121
|
+
super().__init__(*args, **kwargs)
|
|
122
|
+
self.n_permutations, self.seed = n_permutations, seed
|
|
123
|
+
|
|
124
|
+
@overload
|
|
125
|
+
def system_one(self, state: JSONContent, questions: Questions, *,
|
|
126
|
+
response_model: type[ResponseT], **kwargs: Any) -> ResponseT: ...
|
|
127
|
+
|
|
128
|
+
@overload
|
|
129
|
+
def system_one(self, state: JSONContent, questions: Questions, *,
|
|
130
|
+
response_model: None = None, **kwargs: Any) -> SystemOneResponse: ...
|
|
131
|
+
|
|
132
|
+
def system_one(self, state: JSONContent, questions: Questions, *,
|
|
133
|
+
model: str | None = None, retry: RetryPolicy | None = None,
|
|
134
|
+
timeout: float | httpx2.Timeout | None = None,
|
|
135
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
136
|
+
extra_body: Mapping[str, JSONValue | None] | None = None,
|
|
137
|
+
response_model: type[ResponseT] | None = None) -> SystemOneResponse | ResponseT:
|
|
138
|
+
_validate_budget(self.n_permutations)
|
|
139
|
+
state, original, expanded, groups, extra = _request_inputs(
|
|
140
|
+
state, questions, extra_body, self.n_permutations, self.seed)
|
|
141
|
+
result = super().system_one(
|
|
142
|
+
state, expanded, model=model, retry=retry, timeout=timeout,
|
|
143
|
+
extra_headers=extra_headers, extra_body=extra,
|
|
144
|
+
response_model=None if groups else response_model)
|
|
145
|
+
return _aggregate(result, original, groups, response_model) if groups else result
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class AsyncTypeSafeClient(_AsyncClient):
|
|
149
|
+
"""Official async client interface with the same aggregation as sync."""
|
|
150
|
+
|
|
151
|
+
def __init__(self, *args: Any, n_permutations: int | Literal["all"] = 8,
|
|
152
|
+
seed: int | None = None, **kwargs: Any) -> None:
|
|
153
|
+
_validate_budget(n_permutations)
|
|
154
|
+
super().__init__(*args, **kwargs)
|
|
155
|
+
self.n_permutations, self.seed = n_permutations, seed
|
|
156
|
+
|
|
157
|
+
@overload
|
|
158
|
+
async def system_one(self, state: JSONContent, questions: Questions, *,
|
|
159
|
+
response_model: type[ResponseT], **kwargs: Any) -> ResponseT: ...
|
|
160
|
+
|
|
161
|
+
@overload
|
|
162
|
+
async def system_one(self, state: JSONContent, questions: Questions, *,
|
|
163
|
+
response_model: None = None, **kwargs: Any) -> SystemOneResponse: ...
|
|
164
|
+
|
|
165
|
+
async def system_one(self, state: JSONContent, questions: Questions, *,
|
|
166
|
+
model: str | None = None, retry: RetryPolicy | None = None,
|
|
167
|
+
timeout: float | httpx2.Timeout | None = None,
|
|
168
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
169
|
+
extra_body: Mapping[str, JSONValue | None] | None = None,
|
|
170
|
+
response_model: type[ResponseT] | None = None) -> SystemOneResponse | ResponseT:
|
|
171
|
+
_validate_budget(self.n_permutations)
|
|
172
|
+
state, original, expanded, groups, extra = _request_inputs(
|
|
173
|
+
state, questions, extra_body, self.n_permutations, self.seed)
|
|
174
|
+
result = await super().system_one(
|
|
175
|
+
state, expanded, model=model, retry=retry, timeout=timeout,
|
|
176
|
+
extra_headers=extra_headers, extra_body=extra,
|
|
177
|
+
response_model=None if groups else response_model)
|
|
178
|
+
return _aggregate(result, original, groups, response_model) if groups else result
|
|
File without changes
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pijev
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Permutation Invariant Jev — third-party permutation averaging for TypeSafe Choice
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Repository, https://github.com/TypeLLM/pijev
|
|
7
|
+
Project-URL: Issues, https://github.com/TypeLLM/pijev/issues
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: typesafe-sdk<0.8,>=0.7.1
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# pijev — Permutation Invariant Jev
|
|
15
|
+
|
|
16
|
+
**Better Jev probabilities with theoretical guarantees—all with a one-line import change.**
|
|
17
|
+
|
|
18
|
+
pijev turns Jev's option-order variations into a single averaged prediction, with
|
|
19
|
+
Brier score and log loss guaranteed no worse than the average across the included
|
|
20
|
+
orderings. All permutations run in one `system_one` request. Keep the same calls
|
|
21
|
+
and official response types; pijev handles the rest.
|
|
22
|
+
|
|
23
|
+
## Problem: Jev's decision is not permutation invariant
|
|
24
|
+
|
|
25
|
+
The same options can receive different probabilities when reordered. This official
|
|
26
|
+
SDK call sends two Choices with identical instructions and descriptions, but
|
|
27
|
+
opposite option orders:
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from typesafe_sdk import Choice, TypeSafeClient
|
|
31
|
+
|
|
32
|
+
instructions = "Which team should handle this support ticket? Choose the best primary team."
|
|
33
|
+
|
|
34
|
+
with TypeSafeClient() as client:
|
|
35
|
+
response = client.system_one(
|
|
36
|
+
state={
|
|
37
|
+
"ticket": "Since upgrading my plan yesterday, I cannot access the "
|
|
38
|
+
"dashboard. The payment went through, but the page says "
|
|
39
|
+
"my subscription is inactive. Please fix this."
|
|
40
|
+
},
|
|
41
|
+
questions={
|
|
42
|
+
"forward": Choice(
|
|
43
|
+
instructions=instructions,
|
|
44
|
+
criteria={
|
|
45
|
+
"billing": "Payments, charges, invoices, and refunds.",
|
|
46
|
+
"technical": "Product failures, errors, and troubleshooting.",
|
|
47
|
+
"account": "Login, account access, and account settings.",
|
|
48
|
+
},
|
|
49
|
+
),
|
|
50
|
+
"reverse": Choice(
|
|
51
|
+
instructions=instructions,
|
|
52
|
+
criteria={
|
|
53
|
+
"account": "Login, account access, and account settings.",
|
|
54
|
+
"technical": "Product failures, errors, and troubleshooting.",
|
|
55
|
+
"billing": "Payments, charges, invoices, and refunds.",
|
|
56
|
+
},
|
|
57
|
+
),
|
|
58
|
+
},
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
print(response.choices["forward"].probabilities)
|
|
62
|
+
print(response.choices["reverse"].probabilities)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
One request, two questions, one shared state. A live `jev-1.13.0` run returned:
|
|
66
|
+
|
|
67
|
+
| Option | billing → technical → account | account → technical → billing |
|
|
68
|
+
| --- | ---: | ---: |
|
|
69
|
+
| billing | 0.43 | 0.63 |
|
|
70
|
+
| technical | 0.21 | 0.10 |
|
|
71
|
+
| account | 0.36 | 0.27 |
|
|
72
|
+
|
|
73
|
+
Both selected `billing`, but its probability changed by **20 percentage points**.
|
|
74
|
+
This run also changes question IDs and does not control model randomness; see the
|
|
75
|
+
[experiment details](https://github.com/TypeLLM/pijev/blob/main/examples/README.md).
|
|
76
|
+
|
|
77
|
+
## How pijev works
|
|
78
|
+
|
|
79
|
+
pijev treats option order as a nuisance variable: evaluate different orderings,
|
|
80
|
+
align predictions by label, and average their probabilities. The highest mean
|
|
81
|
+
probability determines the returned choice.
|
|
82
|
+
|
|
83
|
+
For three options, there are six permutations. Here is a separate live
|
|
84
|
+
`jev-1.13.0` run with **all six in one request**. A = account, B = billing,
|
|
85
|
+
T = technical.
|
|
86
|
+
|
|
87
|
+
| Option | A → B → T | A → T → B | B → A → T | B → T → A | T → A → B | T → B → A | pijev mean |
|
|
88
|
+
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
|
89
|
+
| billing | 0.58 | 0.64 | 0.58 | 0.46 | 0.47 | 0.60 | **0.5550** |
|
|
90
|
+
| technical | 0.17 | 0.08 | 0.11 | 0.23 | 0.12 | 0.12 | 0.1383 |
|
|
91
|
+
| account | 0.25 | 0.28 | 0.31 | 0.31 | 0.41 | 0.28 | 0.3067 |
|
|
92
|
+
|
|
93
|
+
The `pijev mean` column averages all six predictions: `billing` receives **0.555**,
|
|
94
|
+
compared with 0.46–0.64 across individual orderings.
|
|
95
|
+
[Reproduce this run](https://github.com/TypeLLM/pijev/blob/main/examples/compare_all_orders.py) · [Recorded results](https://github.com/TypeLLM/pijev/blob/main/examples/six_orders_result.json)
|
|
96
|
+
|
|
97
|
+
Ask once using the same SDK interface; pijev handles the six-question batch and
|
|
98
|
+
returns one aggregated answer:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from pijev import Choice, TypeSafeClient
|
|
102
|
+
|
|
103
|
+
with TypeSafeClient() as client:
|
|
104
|
+
response = client.system_one(
|
|
105
|
+
state={
|
|
106
|
+
"ticket": "Since upgrading my plan yesterday, I cannot access the "
|
|
107
|
+
"dashboard. The payment went through, but the page says "
|
|
108
|
+
"my subscription is inactive. Please fix this."
|
|
109
|
+
},
|
|
110
|
+
questions={
|
|
111
|
+
"team": Choice(
|
|
112
|
+
instructions="Which team should handle this support ticket? "
|
|
113
|
+
"Choose the best primary team.",
|
|
114
|
+
criteria={
|
|
115
|
+
"billing": "Payments, charges, invoices, and refunds.",
|
|
116
|
+
"technical": "Product failures, errors, and troubleshooting.",
|
|
117
|
+
"account": "Login, account access, and account settings.",
|
|
118
|
+
},
|
|
119
|
+
),
|
|
120
|
+
},
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
answer = response.choices["team"]
|
|
124
|
+
print(answer.choice)
|
|
125
|
+
print(answer.probabilities)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
The result is an official `SystemOneResponse` with your original question names.
|
|
129
|
+
Live results may differ from the recorded run.
|
|
130
|
+
|
|
131
|
+
## Usage
|
|
132
|
+
|
|
133
|
+
Install from PyPI:
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
pip install pijev
|
|
137
|
+
export TYPESAFE_API_KEY=your-key
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Change only the import:
|
|
141
|
+
|
|
142
|
+
```diff
|
|
143
|
+
-from typesafe_sdk import TypeSafeClient, Choice, Noul, Score
|
|
144
|
+
+from pijev import TypeSafeClient, Choice, Noul, Score
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Set an optional permutation budget:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
client = TypeSafeClient(n_permutations=16, seed=42)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
The default is **up to 8 distinct permutations per Choice**. Smaller sets use all
|
|
154
|
+
permutations; larger sets use uniform sampling without replacement. Set
|
|
155
|
+
`n_permutations="all"` for full enumeration. The seed controls local sampling only.
|
|
156
|
+
Batches are capped at 720 expanded questions and remain subject to server limits.
|
|
157
|
+
|
|
158
|
+
Async usage works the same way: import `AsyncTypeSafeClient` from `pijev`, then use
|
|
159
|
+
`async with` and `await client.system_one(...)` as usual.
|
|
160
|
+
|
|
161
|
+
## Guaranteed Better Calibration
|
|
162
|
+
|
|
163
|
+
Permutation averaging has a **proper-scoring-loss guarantee**, not an unconditional
|
|
164
|
+
calibration guarantee. Let $p^{(m)}$ be the label-aligned probability vector for
|
|
165
|
+
permutation $m$, and let $y$ be the same correct answer under every ordering. Define
|
|
166
|
+
|
|
167
|
+
$$
|
|
168
|
+
\bar p = \frac{1}{M}\sum_{m=1}^{M}p^{(m)}.
|
|
169
|
+
$$
|
|
170
|
+
|
|
171
|
+
For any loss convex in the predicted probabilities, Jensen's inequality gives
|
|
172
|
+
|
|
173
|
+
$$
|
|
174
|
+
L(\bar p,y) \leq \frac{1}{M}\sum_{m=1}^{M}L(p^{(m)},y).
|
|
175
|
+
$$
|
|
176
|
+
|
|
177
|
+
This holds for the actual set of predictions being averaged, including a sampled
|
|
178
|
+
subset of permutations. Two useful cases are:
|
|
179
|
+
|
|
180
|
+
- **Log loss:** $-\log\bar p_y \leq \frac{1}{M}\sum_m -\log p_y^{(m)}$.
|
|
181
|
+
- **Brier score:** writing $e_y$ for the one-hot correct answer, the improvement
|
|
182
|
+
equals the disagreement removed by averaging:
|
|
183
|
+
|
|
184
|
+
$$
|
|
185
|
+
\frac{1}{M}\sum_m\|p^{(m)}-e_y\|_2^2 - \|\bar p-e_y\|_2^2
|
|
186
|
+
= \frac{1}{M}\sum_m\|p^{(m)}-\bar p\|_2^2 \geq 0.
|
|
187
|
+
$$
|
|
188
|
+
|
|
189
|
+
The guarantee compares the average prediction with **randomly choosing one of the
|
|
190
|
+
included predictions**. Brier improvement is strict when those predictions differ.
|
|
191
|
+
For uniform sampling and a fixed predictor, the same inequality holds in expectation
|
|
192
|
+
against a uniformly random ordering. Full enumeration gives the group average;
|
|
193
|
+
see [Chen, Dobriban, and Lee](https://jmlr.csail.mit.edu/papers/v21/20-163.html)
|
|
194
|
+
for related symmetry-averaging theory.
|
|
195
|
+
|
|
196
|
+
## Cost analysis
|
|
197
|
+
|
|
198
|
+
For $K$ options and budget $B$, pijev evaluates $M=\min(B,K!)$ permutations in
|
|
199
|
+
**one HTTP request**. Multiple Choices contribute their own permutations;
|
|
200
|
+
Noul and Score each add one unchanged question.
|
|
201
|
+
|
|
202
|
+
| Workload | Questions in one request |
|
|
203
|
+
| --- | ---: |
|
|
204
|
+
| 3 options, default budget 8 | 6 |
|
|
205
|
+
| 10 options, default budget 8 | 8 |
|
|
206
|
+
| Two Choices with 3 options each | 12 |
|
|
207
|
+
| 3 options plus one Noul | 7 |
|
|
208
|
+
|
|
209
|
+
The state is sent once. For state size $S$ and question size $Q$, request content
|
|
210
|
+
is approximately $S+MQ$, versus $M(S+Q)$ for separate calls, excluding protocol
|
|
211
|
+
overhead. This is a payload estimate; use `response.usage` for reported tokens.
|
|
212
|
+
|
|
213
|
+
At TypeSafe's [published rate](https://typesafe.ai/blog/introducing-system-one-models-and-jev)
|
|
214
|
+
of **$0.042 per million input tokens, with free output tokens** (checked 2026-09-22):
|
|
215
|
+
|
|
216
|
+
$$
|
|
217
|
+
C = \frac{T}{10^6}\times 0.042
|
|
218
|
+
$$
|
|
219
|
+
|
|
220
|
+
Here, $C$ is the estimated cost in USD and $T$ is `response.usage.input_tokens`.
|
|
221
|
+
|
|
222
|
+
| Recorded run | Input tokens | Estimated cost |
|
|
223
|
+
| --- | ---: | ---: |
|
|
224
|
+
| Two permutations | 475 | $0.00001995 |
|
|
225
|
+
| All six permutations | 835 | $0.00003507 |
|
|
226
|
+
|
|
227
|
+
These estimates use reported usage and the published rate, not invoice charges.
|
|
228
|
+
One request still contains multiple decisions; latency and billing depend on the
|
|
229
|
+
backend, and retries may add requests.
|
|
230
|
+
|
|
231
|
+
## Notes
|
|
232
|
+
|
|
233
|
+
- Only Choice answers are averaged. Noul and Score pass through unchanged.
|
|
234
|
+
- `confidence` is the selected label's mean probability, **not Jev's native
|
|
235
|
+
confidence score**.
|
|
236
|
+
- Sampling approximates full permutation averaging; it does not guarantee exact
|
|
237
|
+
order invariance or better calibration. The live examples demonstrate probability
|
|
238
|
+
differences, not accuracy or calibration gains.
|
|
239
|
+
- Official interface: [TypeSafe Python SDK](https://github.com/typesafe-ai/typesafe-sdk-python).
|
|
240
|
+
This is a third-party extension, not an official TypeSafe project.
|
|
241
|
+
|
|
242
|
+
## License
|
|
243
|
+
|
|
244
|
+
[Apache License 2.0](https://github.com/TypeLLM/pijev/blob/main/LICENSE).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
typesafe-sdk<0.8,>=0.7.1
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pijev
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pijev"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Permutation Invariant Jev — third-party permutation averaging for TypeSafe Choice"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
dependencies = ["typesafe-sdk>=0.7.1,<0.8"]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Repository = "https://github.com/TypeLLM/pijev"
|
|
17
|
+
Issues = "https://github.com/TypeLLM/pijev/issues"
|
|
18
|
+
|
|
19
|
+
[tool.setuptools]
|
|
20
|
+
packages = ["pijev"]
|
|
21
|
+
|
|
22
|
+
[tool.setuptools.package-data]
|
|
23
|
+
pijev = ["py.typed"]
|
pijev-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import unittest
|
|
4
|
+
|
|
5
|
+
import httpx2
|
|
6
|
+
from pydantic import BaseModel
|
|
7
|
+
from typesafe_sdk import SystemOneResponse, ChoiceAnswer
|
|
8
|
+
from pijev import AsyncTypeSafeClient, Choice, Noul, Score, TypeSafeClient
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Tests(unittest.TestCase):
|
|
12
|
+
def setUp(self):
|
|
13
|
+
self.bodies = []
|
|
14
|
+
self.bad = None
|
|
15
|
+
self.omit = False
|
|
16
|
+
|
|
17
|
+
def handle(self, request):
|
|
18
|
+
body = json.loads(request.content)
|
|
19
|
+
self.bodies.append(body)
|
|
20
|
+
answers = {}
|
|
21
|
+
for name, q in reversed(list(body['questions'].items())):
|
|
22
|
+
if q['type'] == 'choice':
|
|
23
|
+
labels = list(q['criteria'])
|
|
24
|
+
probs = dict(zip(labels, [2 / (len(labels) + 1)] + [1 / (len(labels) + 1)] * (len(labels) - 1)))
|
|
25
|
+
answers[name] = dict(type='choice', choice=labels[0], confidence=0.99,
|
|
26
|
+
probabilities=self.bad if self.bad is not None else probs)
|
|
27
|
+
elif q['type'] == 'noul':
|
|
28
|
+
answers[name] = dict(type='noul', noul=0.7)
|
|
29
|
+
else:
|
|
30
|
+
answers[name] = dict(type='score', score=0.7, confidence=0.8,
|
|
31
|
+
legend={'0': 'low', '1': 'high'}, probabilities={'0': 0.3, '1': 0.7})
|
|
32
|
+
if self.omit:
|
|
33
|
+
answers.pop(next(iter(answers)))
|
|
34
|
+
return httpx2.Response(200, headers={'x-typesafe-request-id': 'test-id'}, json={
|
|
35
|
+
'model': 'mock', 'usage': {'input_tokens': 10, 'output_tokens': len(answers)}, 'answers': answers})
|
|
36
|
+
|
|
37
|
+
def client(self, **kwargs):
|
|
38
|
+
client = TypeSafeClient(api_key='test', transport=httpx2.MockTransport(self.handle), **kwargs)
|
|
39
|
+
self.addCleanup(client.close)
|
|
40
|
+
return client
|
|
41
|
+
|
|
42
|
+
def test_drop_in_mixed_batch_and_metadata(self):
|
|
43
|
+
q = Choice(criteria={'b': ['B'], 'a': {'hint': 'A'}}, instructions='pick')
|
|
44
|
+
before = q.model_dump()
|
|
45
|
+
result = self.client().system_one('state', {'category': q, '__pijev_0': Noul(), 'rating': Score(criteria=['low', 'high'])})
|
|
46
|
+
self.assertIs(type(result), SystemOneResponse)
|
|
47
|
+
self.assertEqual(result.choices['category'].probabilities, {'a': 0.5, 'b': 0.5})
|
|
48
|
+
self.assertEqual(result.choices['category'].choice, 'a')
|
|
49
|
+
self.assertEqual(result.choices['category'].confidence, 0.5)
|
|
50
|
+
self.assertEqual(result.nouls['__pijev_0'].noul, 0.7)
|
|
51
|
+
self.assertEqual(result.scores['rating'].score, 0.7)
|
|
52
|
+
self.assertEqual(list(result.answers), ['category', '__pijev_0', 'rating'])
|
|
53
|
+
self.assertEqual(set(result.model_dump()), {'answers', 'model', 'usage'})
|
|
54
|
+
self.assertEqual(result.request_id, 'test-id')
|
|
55
|
+
self.assertEqual(result.usage.output_tokens, 4)
|
|
56
|
+
self.assertEqual(result.raw_http_response.json()['answers'], result.model_dump(mode='json')['answers'])
|
|
57
|
+
self.assertEqual(len(self.bodies), 1)
|
|
58
|
+
self.assertEqual(len(self.bodies[0]['questions']), 4)
|
|
59
|
+
self.assertEqual(q.model_dump(), before)
|
|
60
|
+
|
|
61
|
+
def test_three_options_one_call_six_questions(self):
|
|
62
|
+
result = self.client().system_one(state='x', questions={'q': Choice(criteria=dict.fromkeys('abc'))})
|
|
63
|
+
self.assertEqual(len(self.bodies), 1)
|
|
64
|
+
self.assertEqual(len(self.bodies[0]['questions']), 6)
|
|
65
|
+
for p in result.choices['q'].probabilities.values():
|
|
66
|
+
self.assertAlmostEqual(p, 1 / 3)
|
|
67
|
+
|
|
68
|
+
def test_seed_and_multiple_choices(self):
|
|
69
|
+
client = self.client(seed=42)
|
|
70
|
+
q = {'type': 'choice', 'criteria': dict.fromkeys('abcd')}
|
|
71
|
+
a = client.system_one('x', {'q': q, 'second': Choice(criteria={'only': None})})
|
|
72
|
+
q['criteria'] = dict.fromkeys('dcba')
|
|
73
|
+
b = client.system_one('x', {'q': q, 'second': Choice(criteria={'only': None})})
|
|
74
|
+
self.assertEqual(a.answers, b.answers)
|
|
75
|
+
self.assertEqual(self.bodies[0], self.bodies[1])
|
|
76
|
+
orders = [tuple(q['criteria']) for q in self.bodies[0]['questions'].values()]
|
|
77
|
+
self.assertEqual(len(set(orders)), 9)
|
|
78
|
+
|
|
79
|
+
def test_custom_response_models(self):
|
|
80
|
+
class Typed(SystemOneResponse):
|
|
81
|
+
category: ChoiceAnswer
|
|
82
|
+
class Plain(BaseModel):
|
|
83
|
+
answers: dict[str, ChoiceAnswer]
|
|
84
|
+
for target in [Typed, Plain]:
|
|
85
|
+
result = self.client().system_one('x', {'category': Choice(criteria=dict.fromkeys('ab'))}, response_model=target)
|
|
86
|
+
self.assertIsInstance(result, target)
|
|
87
|
+
self.assertEqual(result.answers['category'].probabilities, {'a': 0.5, 'b': 0.5})
|
|
88
|
+
if target is Typed:
|
|
89
|
+
self.assertEqual(result.category, result.answers['category'])
|
|
90
|
+
|
|
91
|
+
def test_extra_body_override_and_passthrough(self):
|
|
92
|
+
client = self.client()
|
|
93
|
+
result = client.system_one('old', {'old': Noul()}, extra_body={
|
|
94
|
+
'state': 'new', 'model': 'chosen', 'questions': {'q': Choice(criteria=dict.fromkeys('ab'))}})
|
|
95
|
+
self.assertEqual(list(result.answers), ['q'])
|
|
96
|
+
self.assertEqual(self.bodies[0]['state'], 'new')
|
|
97
|
+
self.assertEqual(self.bodies[0]['model'], 'chosen')
|
|
98
|
+
result = client.system_one('x', {'n': Noul()})
|
|
99
|
+
self.assertEqual(result.nouls['n'].noul, 0.7)
|
|
100
|
+
self.assertEqual(list(self.bodies[1]['questions']), ['n'])
|
|
101
|
+
|
|
102
|
+
def test_validation(self):
|
|
103
|
+
for budget in [0, -1, True, 1.5, 'bad']:
|
|
104
|
+
with self.subTest(budget=budget), self.assertRaises(ValueError):
|
|
105
|
+
self.client(n_permutations=budget)
|
|
106
|
+
with self.assertRaises(ValueError):
|
|
107
|
+
self.client(n_permutations='all').system_one('x', {'q': Choice(criteria=dict.fromkeys('abcdefgh'))})
|
|
108
|
+
self.assertEqual(self.bodies, [])
|
|
109
|
+
for bad in [{'a': 1.0}, {'a': -0.1, 'b': 1.1}, {'a': 0.0, 'b': 0.0}]:
|
|
110
|
+
self.bad = bad
|
|
111
|
+
with self.assertRaises(ValueError):
|
|
112
|
+
self.client().system_one('x', {'q': Choice(criteria=dict.fromkeys('ab'))})
|
|
113
|
+
self.bad, self.omit = None, True
|
|
114
|
+
with self.assertRaises(ValueError):
|
|
115
|
+
self.client().system_one('x', {'q': Choice(criteria=dict.fromkeys('ab'))})
|
|
116
|
+
|
|
117
|
+
def test_async(self):
|
|
118
|
+
async def run():
|
|
119
|
+
async with AsyncTypeSafeClient(api_key='test', transport=httpx2.MockTransport(self.handle)) as client:
|
|
120
|
+
return await client.system_one('x', {'q': Choice(criteria=dict.fromkeys('ab'))})
|
|
121
|
+
result = asyncio.run(run())
|
|
122
|
+
self.assertIs(type(result), SystemOneResponse)
|
|
123
|
+
self.assertEqual(result.choices['q'].probabilities, {'a': 0.5, 'b': 0.5})
|
|
124
|
+
self.assertEqual(len(self.bodies), 1)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
if __name__ == '__main__':
|
|
128
|
+
unittest.main()
|