solvi 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.
solvi-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.
solvi-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,250 @@
1
+ Metadata-Version: 2.4
2
+ Name: solvi
3
+ Version: 0.1.0
4
+ Summary: Decision systems from a catalog of Python functions and checks: a strategist plans the flow, every answer comes with a quote or formula and a verifiable trace
5
+ Keywords: decision systems,rules,document extraction,ModernBERT,explainability,verification,audit trail
6
+ Author: mxkuzn
7
+ Author-email: mxkuzn <hi@mxkuzn.dev>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Classifier: Topic :: Software Development :: Libraries
16
+ Requires-Dist: numpy
17
+ Requires-Dist: scipy
18
+ Requires-Dist: torch ; extra == 'model'
19
+ Requires-Dist: transformers ; extra == 'model'
20
+ Requires-Python: >=3.10
21
+ Project-URL: Homepage, https://github.com/solvi-ai/solvi
22
+ Project-URL: Documentation, https://github.com/solvi-ai/solvi/blob/main/docs/guide.md
23
+ Project-URL: Issues, https://github.com/solvi-ai/solvi/issues
24
+ Project-URL: Models, https://huggingface.co/solvi-ai
25
+ Provides-Extra: model
26
+ Description-Content-Type: text/markdown
27
+
28
+ # solvi
29
+
30
+ Build decision systems from a catalog of Python functions and checks plus typed questions, and get answers you can verify.
31
+
32
+ ## Why
33
+
34
+ You describe a task with plain Python functions (computations, checks, answer rules) and questions with typed answers
35
+ (yes/no, or a choice from a list). For each request, a strategist plans which functions and checks to run for the asked
36
+ questions. Every answer comes with:
37
+
38
+ - a **confidence** (calibratable per question);
39
+ - a **reason you can check**: the rule inputs, a formula over computed facts, or a quote with character offsets in the
40
+ source document;
41
+ - a **hash-chained trace** of every step, which can be re-executed later to confirm the answer or pinpoint the step that
42
+ was altered.
43
+
44
+ When something cannot be computed, a function fails, or a rule returns an answer outside the allowed options, solvi
45
+ abstains instead of guessing. A failed hard check always overrides any model confidence.
46
+
47
+ And it is fast. The strategist plans a flow over a 10 000-part catalog in about 6 ms and runs only the parts the questions
48
+ need (2.4% of that catalog). Hard checks run first, so a failing one skips the expensive rest; independent slow parts (API
49
+ calls, model inference) run in parallel. On an insurance-claim desk with slow services
50
+ ([examples/09_strategy_at_scale.py](examples/09_strategy_at_scale.py)) a full decision takes 463 ms instead of 1 122 ms for a
51
+ script that computes everything, and 152 ms when an expired policy settles the claim first.
52
+
53
+ ## Install
54
+
55
+ ```bash
56
+ pip install solvi # core: rules, checks, learned answer heads (numpy, scipy)
57
+ pip install "solvi[model]" # + torch, transformers: ModernBERT field extractors for documents
58
+ ```
59
+
60
+ Requires Python 3.10+.
61
+
62
+ ## Quickstart (core only, no model)
63
+
64
+ ```python
65
+ from datetime import date
66
+ from solvi import Answer, Catalog, Question, System
67
+
68
+ cat = Catalog()
69
+
70
+ @cat.fn # argument names = facts it reads; function name = fact it sets
71
+ def days_requested(start, end):
72
+ return (end - start).days + 1
73
+
74
+ @cat.fn
75
+ def remaining_after(balance, days_requested):
76
+ return balance - days_requested
77
+
78
+ @cat.check(hard=True, then={"approve": "reject"}) # if this check is False, "approve" is forced to "reject"
79
+ def enough_balance(remaining_after):
80
+ return remaining_after >= 0
81
+
82
+ @cat.check
83
+ def enough_notice(start, today, days_requested):
84
+ return days_requested < 5 or (start - today).days >= 14
85
+
86
+ @cat.rule("approve")
87
+ def approve(enough_notice):
88
+ return "approve" if enough_notice else "needs_manager"
89
+
90
+ system = System(cat, [Question("approve", "Approve the leave?",
91
+ Answer.choice(["approve", "needs_manager", "reject"]),
92
+ checkpoints=["enough_balance"])])
93
+ res = system.ask({"start": date(2026, 10, 19), "end": date(2026, 10, 23),
94
+ "today": date(2026, 9, 25), "balance": 14})
95
+ print(res["approve"].answer, res["approve"].confidence, res["approve"].why)
96
+ print(res.computed_state)
97
+ print(res.trace.replay(cat))
98
+ ```
99
+
100
+ Output:
101
+
102
+ ```
103
+ approve 1.0 enough_notice = True
104
+ days_requested = 5
105
+ remaining_after = 9
106
+ enough_balance = True
107
+ enough_notice = True
108
+ {'ok': True, 'steps': 5, 'mismatches': []}
109
+ ```
110
+
111
+ With `"balance": 3` the hard check fails and the answer is `reject` with `status == "forced"`, whatever the rule says.
112
+ `solvi.show.show(res, cat)` prints answers, the planned flow, the computed state and the replay result in one go.
113
+
114
+ ## How it works
115
+
116
+ - **Catalog.** `@cat.fn` (computation), `@cat.check` (bool), `@cat.extract` (value from text, returned as a `Quote` with
117
+ offsets) and `@cat.rule(question)` (answer rule). A part's contract is its signature: argument names are the facts it
118
+ reads, the function name is the fact it sets.
119
+ - **Questions.** `Question(name, text, Answer.yes_no() | Answer.choice([...]), checkpoints=[...])`. Questions without a
120
+ rule get a small answer head trained from labeled examples (`system.fit`) or a readable learned rule list
121
+ (`system.learn_rule`).
122
+ - **Strategist.** For each question it walks backwards from the rule's arguments (or the learned features) through the
123
+ catalog signatures to the keys of `init_state`, adds the question's checkpoints and every check that touches a computed
124
+ fact. Everything else in the catalog is not executed; the flow records why each part was taken or skipped.
125
+ - **Execution.** Each part runs once, even if several questions need it. Hard checks and their inputs run first; when one
126
+ fails, the steps only the settled questions needed are skipped (`res.trace.skipped`). With `System(..., workers=8)`
127
+ independent steps run in parallel threads as soon as their inputs are ready. Results go into `computed_state` with their
128
+ provenance; extracted values keep their quote. Each step record is hashed and chained to the previous one in flow order,
129
+ so the trace does not depend on scheduling.
130
+ - **Answers and trace.** `res[q].answer / .confidence / .why / .status` (`ok`, `forced`, `abstain`), plus
131
+ `res.trace.replay(catalog)`, which recomputes every step from recorded inputs and reports mismatches, broken hash links
132
+ and quotes outside the text.
133
+
134
+ ## Extract from documents
135
+
136
+ With `solvi[model]`, fields are found by a fine-tuned ModernBERT extractor. The extracted value is always a span of the
137
+ document, so every answer built on it can be cited.
138
+
139
+ ```python
140
+ from solvi.extract_multi import MultiSpanExtractor
141
+
142
+ ex = MultiSpanExtractor(["total", "date"]) # ModernBERT-large, one pass per document for all fields
143
+ ex.fit(train_docs, train_spans, epochs=4) # train_spans: [{"total": (start, end), "date": (start, end) | None}]
144
+ cat.extract(ex.field("total")) # doc -> Quote(text, start, end, confidence)
145
+ cat.extract(ex.field("date"))
146
+
147
+ @cat.fn
148
+ def amount(total): # extracted values are strings; parse them in ordinary functions
149
+ return float(total.replace(",", ""))
150
+ ```
151
+
152
+ For long documents (contracts), `solvi.extract_long.LongSpanExtractor` reads the whole text in overlapping 1024-token
153
+ windows, takes a field description instead of a fixed field list, and supports "no answer" with a per-field threshold.
154
+ See [docs/guide.md](docs/guide.md#extracting-fields-from-documents).
155
+
156
+ ## Results
157
+
158
+ Same training documents for both sides. The baseline, Laya, is a ModernBERT-large model that answers the typed questions
159
+ directly, fine-tuned with its authors' recipe. Details and caveats: [docs/benchmarks.md](docs/benchmarks.md).
160
+
161
+ | Task (test set) | solvi | Baseline |
162
+ |---|---|---|
163
+ | SROIE receipts, 6 questions (361 receipts) | **97.8%** | 92.6% |
164
+ | SROIE, only 100 labeled training receipts | **95.9%** | 80.0% |
165
+ | CORD receipts, 4 questions (100 receipts) | **98.5%** | 96.0% |
166
+ | CORD, share of questions answered at >= 99% precision | **99.7%** | 14.2% |
167
+ | CUAD contracts, 5 questions (102 contracts, median 33k chars) | **94.8%** | 77.5% (sees first 1024 tokens only) |
168
+
169
+ - Calibrated confidence: ECE 0.008 (SROIE), 0.011 (CORD), 0.027 (CUAD).
170
+ - On the document benchmarks, 100% of answers are backed by a quote at stated offsets, or the system abstains.
171
+ - Speed: about 0.4 ms per decision when no model is involved; about 39 ms per receipt with the one-pass extractor on an
172
+ A100 GPU.
173
+
174
+ ## Speed
175
+
176
+ Strategist on random layered catalogs ([benchmarks/strategist_scale.py](benchmarks/strategist_scale.py), one CPU core):
177
+
178
+ | catalog parts | plan | plan + run + trace | parts run | share of catalog |
179
+ |---:|---:|---:|---:|---:|
180
+ | 100 | 0.2 ms | 1.3 ms | 31 | 31% |
181
+ | 1 000 | 0.7 ms | 2.6 ms | 115 | 12% |
182
+ | 10 000 | 6 ms | 10 ms | 236 | 2.4% |
183
+
184
+ Insurance claim desk with six slow services of 100-300 ms ([examples/09_strategy_at_scale.py](examples/09_strategy_at_scale.py)):
185
+
186
+ | questions asked | script computing everything | solvi, one by one | solvi, `workers=8` |
187
+ |---|---:|---:|---:|
188
+ | fast track? | 1 122 ms | 503 ms | 313 ms |
189
+ | full decision + payout | 1 122 ms | 773 ms | 461 ms |
190
+ | all five questions | 1 122 ms | 1 025 ms | 463 ms |
191
+ | expired policy (hard check settles it) | 1 122 ms | 152 ms | 153 ms |
192
+
193
+ A rule-only decision on a small catalog takes well under a millisecond; on documents the extractor dominates (about 39 ms per
194
+ receipt with the one-pass extractor on an A100).
195
+
196
+ ## When to use it
197
+
198
+ - The answer is a computation or a rule over a few values found in a document or a record: receipts, invoices,
199
+ contracts, requests, orders.
200
+ - You need to show why: auditors, compliance, or a human reviewing low-confidence cases.
201
+ - Some rules are non-negotiable (hard checks), and the rest can be learned from about 100 labeled examples.
202
+
203
+ ## When not to use it
204
+
205
+ - Open-ended free-text questions or generated answers. solvi answers yes/no and choice questions only.
206
+ - New fields with no labeled examples. Extracting a field from its description alone does not work yet (14% and 66% on
207
+ two held-out fields); a universal extractor is coming.
208
+ - No labels at all. Plan on roughly 100 labeled documents (field positions) per task.
209
+ - CPU-only deployment with a quantized model: the int8 ONNX extractor loses up to 12 points on amounts, company
210
+ names and addresses. fp32 on CPU keeps accuracy but takes about 0.7 s per receipt on 2 cores.
211
+
212
+ ## Examples
213
+
214
+ | File | What it shows |
215
+ |---|---|
216
+ | [examples/01_leave_request.py](examples/01_leave_request.py) | Leave request from a plain dict: rules, hard checks, parts the strategist skips |
217
+ | [examples/02_shop_order.py](examples/02_shop_order.py) | Shop order: two rule-based questions plus a "suspicious?" question learned from history with `fit` |
218
+ | [examples/03_invoices.py](examples/03_invoices.py) | Invoice approval from text: regex extractors with quotes, four questions, one learned |
219
+ | [examples/04_refunds.py](examples/04_refunds.py) | Refund e-mails: yes/no learned from examples under a hard "within 30 days" check |
220
+ | [examples/05_tic_tac_toe.py](examples/05_tic_tac_toe.py) | Tic-tac-toe agent: each move is an answer with its reason (win, block, fork, ...); a hard check rejects invalid boards |
221
+ | [examples/06_learned_rules.py](examples/06_learned_rules.py) | `learn_rule`: route parcels to delivery zones from free-form addresses with a readable if-then list learned from labels |
222
+ | [examples/09_strategy_at_scale.py](examples/09_strategy_at_scale.py) | Insurance claim desk: the strategist generates a different plan per question set, hard checks first with early exit, slow services in parallel; timed |
223
+ | [examples/07_receipts_model.py](examples/07_receipts_model.py) | Expense check on a scanned receipt: a receipts-tuned extractor cites each field, rules and a hard check decide (needs `solvi[model]`) |
224
+ | [examples/08_contracts_by_description.py](examples/08_contracts_by_description.py) | Contract review with fields defined only in words: the general extractor reads the whole contract, cites clauses or says "absent" (needs `solvi[model]`) |
225
+
226
+ Run them from a clone: `python examples/01_leave_request.py`.
227
+
228
+ ## More
229
+
230
+ - [docs/guide.md](docs/guide.md): full API walkthrough.
231
+ - [docs/benchmarks.md](docs/benchmarks.md): setups, per-question numbers, caveats.
232
+ - [benchmarks/](benchmarks/): dataset loaders and benchmark scripts (SROIE, CORD, CUAD, Kleister-NDA).
233
+ - Tests: `pytest`.
234
+
235
+ ## License
236
+
237
+ Apache-2.0. See [LICENSE](LICENSE).
238
+
239
+ ## Citation
240
+
241
+ A paper is in preparation. Until then, please cite the repository:
242
+
243
+ ```bibtex
244
+ @software{solvi,
245
+ title = {solvi: verifiable decision systems from catalogs of functions and checks},
246
+ author = {mxkuzn and solvi contributors},
247
+ year = {2026},
248
+ url = {https://github.com/solvi-ai/solvi}
249
+ }
250
+ ```
solvi-0.1.0/README.md ADDED
@@ -0,0 +1,223 @@
1
+ # solvi
2
+
3
+ Build decision systems from a catalog of Python functions and checks plus typed questions, and get answers you can verify.
4
+
5
+ ## Why
6
+
7
+ You describe a task with plain Python functions (computations, checks, answer rules) and questions with typed answers
8
+ (yes/no, or a choice from a list). For each request, a strategist plans which functions and checks to run for the asked
9
+ questions. Every answer comes with:
10
+
11
+ - a **confidence** (calibratable per question);
12
+ - a **reason you can check**: the rule inputs, a formula over computed facts, or a quote with character offsets in the
13
+ source document;
14
+ - a **hash-chained trace** of every step, which can be re-executed later to confirm the answer or pinpoint the step that
15
+ was altered.
16
+
17
+ When something cannot be computed, a function fails, or a rule returns an answer outside the allowed options, solvi
18
+ abstains instead of guessing. A failed hard check always overrides any model confidence.
19
+
20
+ And it is fast. The strategist plans a flow over a 10 000-part catalog in about 6 ms and runs only the parts the questions
21
+ need (2.4% of that catalog). Hard checks run first, so a failing one skips the expensive rest; independent slow parts (API
22
+ calls, model inference) run in parallel. On an insurance-claim desk with slow services
23
+ ([examples/09_strategy_at_scale.py](examples/09_strategy_at_scale.py)) a full decision takes 463 ms instead of 1 122 ms for a
24
+ script that computes everything, and 152 ms when an expired policy settles the claim first.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install solvi # core: rules, checks, learned answer heads (numpy, scipy)
30
+ pip install "solvi[model]" # + torch, transformers: ModernBERT field extractors for documents
31
+ ```
32
+
33
+ Requires Python 3.10+.
34
+
35
+ ## Quickstart (core only, no model)
36
+
37
+ ```python
38
+ from datetime import date
39
+ from solvi import Answer, Catalog, Question, System
40
+
41
+ cat = Catalog()
42
+
43
+ @cat.fn # argument names = facts it reads; function name = fact it sets
44
+ def days_requested(start, end):
45
+ return (end - start).days + 1
46
+
47
+ @cat.fn
48
+ def remaining_after(balance, days_requested):
49
+ return balance - days_requested
50
+
51
+ @cat.check(hard=True, then={"approve": "reject"}) # if this check is False, "approve" is forced to "reject"
52
+ def enough_balance(remaining_after):
53
+ return remaining_after >= 0
54
+
55
+ @cat.check
56
+ def enough_notice(start, today, days_requested):
57
+ return days_requested < 5 or (start - today).days >= 14
58
+
59
+ @cat.rule("approve")
60
+ def approve(enough_notice):
61
+ return "approve" if enough_notice else "needs_manager"
62
+
63
+ system = System(cat, [Question("approve", "Approve the leave?",
64
+ Answer.choice(["approve", "needs_manager", "reject"]),
65
+ checkpoints=["enough_balance"])])
66
+ res = system.ask({"start": date(2026, 10, 19), "end": date(2026, 10, 23),
67
+ "today": date(2026, 9, 25), "balance": 14})
68
+ print(res["approve"].answer, res["approve"].confidence, res["approve"].why)
69
+ print(res.computed_state)
70
+ print(res.trace.replay(cat))
71
+ ```
72
+
73
+ Output:
74
+
75
+ ```
76
+ approve 1.0 enough_notice = True
77
+ days_requested = 5
78
+ remaining_after = 9
79
+ enough_balance = True
80
+ enough_notice = True
81
+ {'ok': True, 'steps': 5, 'mismatches': []}
82
+ ```
83
+
84
+ With `"balance": 3` the hard check fails and the answer is `reject` with `status == "forced"`, whatever the rule says.
85
+ `solvi.show.show(res, cat)` prints answers, the planned flow, the computed state and the replay result in one go.
86
+
87
+ ## How it works
88
+
89
+ - **Catalog.** `@cat.fn` (computation), `@cat.check` (bool), `@cat.extract` (value from text, returned as a `Quote` with
90
+ offsets) and `@cat.rule(question)` (answer rule). A part's contract is its signature: argument names are the facts it
91
+ reads, the function name is the fact it sets.
92
+ - **Questions.** `Question(name, text, Answer.yes_no() | Answer.choice([...]), checkpoints=[...])`. Questions without a
93
+ rule get a small answer head trained from labeled examples (`system.fit`) or a readable learned rule list
94
+ (`system.learn_rule`).
95
+ - **Strategist.** For each question it walks backwards from the rule's arguments (or the learned features) through the
96
+ catalog signatures to the keys of `init_state`, adds the question's checkpoints and every check that touches a computed
97
+ fact. Everything else in the catalog is not executed; the flow records why each part was taken or skipped.
98
+ - **Execution.** Each part runs once, even if several questions need it. Hard checks and their inputs run first; when one
99
+ fails, the steps only the settled questions needed are skipped (`res.trace.skipped`). With `System(..., workers=8)`
100
+ independent steps run in parallel threads as soon as their inputs are ready. Results go into `computed_state` with their
101
+ provenance; extracted values keep their quote. Each step record is hashed and chained to the previous one in flow order,
102
+ so the trace does not depend on scheduling.
103
+ - **Answers and trace.** `res[q].answer / .confidence / .why / .status` (`ok`, `forced`, `abstain`), plus
104
+ `res.trace.replay(catalog)`, which recomputes every step from recorded inputs and reports mismatches, broken hash links
105
+ and quotes outside the text.
106
+
107
+ ## Extract from documents
108
+
109
+ With `solvi[model]`, fields are found by a fine-tuned ModernBERT extractor. The extracted value is always a span of the
110
+ document, so every answer built on it can be cited.
111
+
112
+ ```python
113
+ from solvi.extract_multi import MultiSpanExtractor
114
+
115
+ ex = MultiSpanExtractor(["total", "date"]) # ModernBERT-large, one pass per document for all fields
116
+ ex.fit(train_docs, train_spans, epochs=4) # train_spans: [{"total": (start, end), "date": (start, end) | None}]
117
+ cat.extract(ex.field("total")) # doc -> Quote(text, start, end, confidence)
118
+ cat.extract(ex.field("date"))
119
+
120
+ @cat.fn
121
+ def amount(total): # extracted values are strings; parse them in ordinary functions
122
+ return float(total.replace(",", ""))
123
+ ```
124
+
125
+ For long documents (contracts), `solvi.extract_long.LongSpanExtractor` reads the whole text in overlapping 1024-token
126
+ windows, takes a field description instead of a fixed field list, and supports "no answer" with a per-field threshold.
127
+ See [docs/guide.md](docs/guide.md#extracting-fields-from-documents).
128
+
129
+ ## Results
130
+
131
+ Same training documents for both sides. The baseline, Laya, is a ModernBERT-large model that answers the typed questions
132
+ directly, fine-tuned with its authors' recipe. Details and caveats: [docs/benchmarks.md](docs/benchmarks.md).
133
+
134
+ | Task (test set) | solvi | Baseline |
135
+ |---|---|---|
136
+ | SROIE receipts, 6 questions (361 receipts) | **97.8%** | 92.6% |
137
+ | SROIE, only 100 labeled training receipts | **95.9%** | 80.0% |
138
+ | CORD receipts, 4 questions (100 receipts) | **98.5%** | 96.0% |
139
+ | CORD, share of questions answered at >= 99% precision | **99.7%** | 14.2% |
140
+ | CUAD contracts, 5 questions (102 contracts, median 33k chars) | **94.8%** | 77.5% (sees first 1024 tokens only) |
141
+
142
+ - Calibrated confidence: ECE 0.008 (SROIE), 0.011 (CORD), 0.027 (CUAD).
143
+ - On the document benchmarks, 100% of answers are backed by a quote at stated offsets, or the system abstains.
144
+ - Speed: about 0.4 ms per decision when no model is involved; about 39 ms per receipt with the one-pass extractor on an
145
+ A100 GPU.
146
+
147
+ ## Speed
148
+
149
+ Strategist on random layered catalogs ([benchmarks/strategist_scale.py](benchmarks/strategist_scale.py), one CPU core):
150
+
151
+ | catalog parts | plan | plan + run + trace | parts run | share of catalog |
152
+ |---:|---:|---:|---:|---:|
153
+ | 100 | 0.2 ms | 1.3 ms | 31 | 31% |
154
+ | 1 000 | 0.7 ms | 2.6 ms | 115 | 12% |
155
+ | 10 000 | 6 ms | 10 ms | 236 | 2.4% |
156
+
157
+ Insurance claim desk with six slow services of 100-300 ms ([examples/09_strategy_at_scale.py](examples/09_strategy_at_scale.py)):
158
+
159
+ | questions asked | script computing everything | solvi, one by one | solvi, `workers=8` |
160
+ |---|---:|---:|---:|
161
+ | fast track? | 1 122 ms | 503 ms | 313 ms |
162
+ | full decision + payout | 1 122 ms | 773 ms | 461 ms |
163
+ | all five questions | 1 122 ms | 1 025 ms | 463 ms |
164
+ | expired policy (hard check settles it) | 1 122 ms | 152 ms | 153 ms |
165
+
166
+ A rule-only decision on a small catalog takes well under a millisecond; on documents the extractor dominates (about 39 ms per
167
+ receipt with the one-pass extractor on an A100).
168
+
169
+ ## When to use it
170
+
171
+ - The answer is a computation or a rule over a few values found in a document or a record: receipts, invoices,
172
+ contracts, requests, orders.
173
+ - You need to show why: auditors, compliance, or a human reviewing low-confidence cases.
174
+ - Some rules are non-negotiable (hard checks), and the rest can be learned from about 100 labeled examples.
175
+
176
+ ## When not to use it
177
+
178
+ - Open-ended free-text questions or generated answers. solvi answers yes/no and choice questions only.
179
+ - New fields with no labeled examples. Extracting a field from its description alone does not work yet (14% and 66% on
180
+ two held-out fields); a universal extractor is coming.
181
+ - No labels at all. Plan on roughly 100 labeled documents (field positions) per task.
182
+ - CPU-only deployment with a quantized model: the int8 ONNX extractor loses up to 12 points on amounts, company
183
+ names and addresses. fp32 on CPU keeps accuracy but takes about 0.7 s per receipt on 2 cores.
184
+
185
+ ## Examples
186
+
187
+ | File | What it shows |
188
+ |---|---|
189
+ | [examples/01_leave_request.py](examples/01_leave_request.py) | Leave request from a plain dict: rules, hard checks, parts the strategist skips |
190
+ | [examples/02_shop_order.py](examples/02_shop_order.py) | Shop order: two rule-based questions plus a "suspicious?" question learned from history with `fit` |
191
+ | [examples/03_invoices.py](examples/03_invoices.py) | Invoice approval from text: regex extractors with quotes, four questions, one learned |
192
+ | [examples/04_refunds.py](examples/04_refunds.py) | Refund e-mails: yes/no learned from examples under a hard "within 30 days" check |
193
+ | [examples/05_tic_tac_toe.py](examples/05_tic_tac_toe.py) | Tic-tac-toe agent: each move is an answer with its reason (win, block, fork, ...); a hard check rejects invalid boards |
194
+ | [examples/06_learned_rules.py](examples/06_learned_rules.py) | `learn_rule`: route parcels to delivery zones from free-form addresses with a readable if-then list learned from labels |
195
+ | [examples/09_strategy_at_scale.py](examples/09_strategy_at_scale.py) | Insurance claim desk: the strategist generates a different plan per question set, hard checks first with early exit, slow services in parallel; timed |
196
+ | [examples/07_receipts_model.py](examples/07_receipts_model.py) | Expense check on a scanned receipt: a receipts-tuned extractor cites each field, rules and a hard check decide (needs `solvi[model]`) |
197
+ | [examples/08_contracts_by_description.py](examples/08_contracts_by_description.py) | Contract review with fields defined only in words: the general extractor reads the whole contract, cites clauses or says "absent" (needs `solvi[model]`) |
198
+
199
+ Run them from a clone: `python examples/01_leave_request.py`.
200
+
201
+ ## More
202
+
203
+ - [docs/guide.md](docs/guide.md): full API walkthrough.
204
+ - [docs/benchmarks.md](docs/benchmarks.md): setups, per-question numbers, caveats.
205
+ - [benchmarks/](benchmarks/): dataset loaders and benchmark scripts (SROIE, CORD, CUAD, Kleister-NDA).
206
+ - Tests: `pytest`.
207
+
208
+ ## License
209
+
210
+ Apache-2.0. See [LICENSE](LICENSE).
211
+
212
+ ## Citation
213
+
214
+ A paper is in preparation. Until then, please cite the repository:
215
+
216
+ ```bibtex
217
+ @software{solvi,
218
+ title = {solvi: verifiable decision systems from catalogs of functions and checks},
219
+ author = {mxkuzn and solvi contributors},
220
+ year = {2026},
221
+ url = {https://github.com/solvi-ai/solvi}
222
+ }
223
+ ```