spinf-client 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ # Lint and the test suite on every push and pull request. Two tests compare this repository with its neighbours: the vendored
2
+ # evaluator against spinf-serve's pipeline.py, and the pack evaluator against the spinf/moderation pack files of spinf-prompts;
3
+ # both checkouts are optional (the tests skip without them). SPINF_SERVE_REPO / SPINF_PROMPTS_REPO (repository variables) and
4
+ # SPINF_SERVE_TOKEN / SPINF_PROMPTS_TOKEN (secrets) point a fork or a mirror at its own copies; unset, the public ones are used.
5
+ name: ci
6
+ on:
7
+ push:
8
+ pull_request:
9
+ workflow_dispatch:
10
+ permissions:
11
+ contents: read
12
+ jobs:
13
+ test:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v7
17
+ - uses: actions/checkout@v7
18
+ id: serve
19
+ continue-on-error: true
20
+ with:
21
+ repository: ${{ vars.SPINF_SERVE_REPO || 'spinfinc/spinf-serve' }}
22
+ token: ${{ secrets.SPINF_SERVE_TOKEN || github.token }}
23
+ path: .spinf-serve
24
+ - uses: actions/checkout@v7
25
+ id: prompts
26
+ continue-on-error: true
27
+ with:
28
+ repository: ${{ vars.SPINF_PROMPTS_REPO || 'spinfinc/spinf-prompts' }}
29
+ token: ${{ secrets.SPINF_PROMPTS_TOKEN || github.token }}
30
+ path: .spinf-prompts
31
+ - uses: astral-sh/setup-uv@v10.2.0
32
+ - run: uv sync --frozen
33
+ - run: uv run ruff check . && uv run ruff format --check src tests
34
+ - run: uv run pytest
35
+ env:
36
+ SPINF_SERVE_DIR: ${{ steps.serve.outcome == 'success' && format('{0}/.spinf-serve', github.workspace) || '' }}
37
+ SPINF_PROMPTS_DIR: ${{ steps.prompts.outcome == 'success' && format('{0}/.spinf-prompts', github.workspace) || '' }}
@@ -0,0 +1,7 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ .pytest_cache/
6
+ .ruff_cache/
7
+ tests/.packs/
@@ -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 2026 spinf Inc.
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.
@@ -0,0 +1,206 @@
1
+ Metadata-Version: 2.5
2
+ Name: spinf-client
3
+ Version: 0.3.0
4
+ Summary: Python client for the spinf scoring API, hosted or self-hosted with spinf-serve: scored queries, extraction slots, images and video frames, prompt packs and content moderation
5
+ Project-URL: Homepage, https://spinf.com
6
+ Project-URL: Repository, https://github.com/spinfinc/spinf-client
7
+ Project-URL: Server, https://github.com/spinfinc/spinf-serve
8
+ Project-URL: Packs, https://github.com/spinfinc/spinf-prompts
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.11
16
+ Requires-Dist: httpx>=0.27
17
+ Provides-Extra: media
18
+ Requires-Dist: pillow>=10; extra == 'media'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # spinf-client
22
+
23
+ Python client for the spinf scoring API: scored queries (`{?}` + options), extraction slots (`{*}` text, `{n}` number,
24
+ `{$}` amount), images and video frames, prompt packs and content moderation. One runtime dependency (httpx). The same
25
+ client talks to the hosted API at `api.spinf.com` and to a [spinf-serve](https://github.com/spinfinc/spinf-serve) of your own:
26
+ the request and the response are the same, only the base URL and the key change.
27
+
28
+ ```bash
29
+ pip install "spinf-client[media]" # the media extra adds Pillow for images; video frames also need ffmpeg / ffprobe on PATH
30
+ export SPINF_API_KEY=sk-... # the hosted API
31
+ ```
32
+
33
+ ```python
34
+ from spinf_client import SpinfClient
35
+
36
+ client = SpinfClient() # api.spinf.com, model "spinf-12b"
37
+ client = SpinfClient(base_url="http://localhost:8000", model="spinf/gemma-4-12b-fp8") # your own spinf-serve
38
+ ```
39
+
40
+ A spinf-serve started without `--token` needs no key (`SPINF_API_URL` sets the base URL from the environment); one started
41
+ with a token takes it as `api_key`. The hosted model names (`spinf-12b`, `spinf-31b`) are aliases of the Hub names
42
+ (`spinf/gemma-4-12b-fp8`, `spinf/gemma-4-31b-fp8`) and both work on both. Account, pricing and billing (`client.account()`,
43
+ `client.pricing()`, `billed_tokens()`) and the per-account features (extraction slots, video, the content limit) belong to
44
+ the hosted API; a server of your own has every feature on and no bill.
45
+
46
+ ## Score and extract
47
+
48
+ ```python
49
+ from spinf_client import SpinfClient, answers, query, text
50
+
51
+ client = SpinfClient() # model="spinf-12b" by default (or "spinf-31b", ...)
52
+ out = client.score(
53
+ content=[text("Apple sold 3.5 million iPhones in the quarter, up from 3.1 million.")],
54
+ queries=[
55
+ query("dir", "\n\nDid iPhone sales go{?}", options=[" up", " down"]), # scored
56
+ query("units", "\n\nQ: How many iPhones were sold?\nA:{n}"), # a number
57
+ query("co", '\n\nThe company in this news is "{*}"', top_k=3), # text: in quotes, name the thing
58
+ ],
59
+ )
60
+ answers(out, "units") # {"answers": [{"text": "3.5 million", "p": 0.62, "value": 3500000.0}, ...], "mass": ..., "p_negative": 0.0}
61
+ ```
62
+
63
+ Slots:
64
+
65
+ | slot | the answer | ends |
66
+ |---|---|---|
67
+ | `{*}` | any text; write the template with an opening quote: `... is "{*}"` | at the text after the slot (the closing quote) or a newline |
68
+ | `{n}` | a number: sign or accounting brackets, thousands separators, decimals, `thousand` / `million` / `billion`, `%` | when the next token cannot continue the number |
69
+ | `{$}` | the same with an optional currency symbol (`$ € £ ¥`), returned as `currency` | the same |
70
+
71
+ Each extraction returns the most likely answers (merged over spellings: text by case / punctuation / spaces, numbers by
72
+ value) with their probabilities, `mass` (the probability on all answers found) and, for numbers, `p_negative` (the share
73
+ of the top value's magnitude on its negative: brackets in accounting tables are often ambiguous). `max_tokens` 1-64
74
+ (default 16; up to 100 generated), `top_k` 1-20 (default 5). At most **10 slots per content** (queries × combinations). Extraction slots have
75
+ no empty floor.
76
+
77
+ `generate=True` on a `{*}` slot writes free text instead of searching short answers (a one-sentence summary, a caption):
78
+ greedy by default, or `generate={"temperature": 0.7, "top_p": 0.8, "top_k": 20, "seed": 0, "n": 1}` to sample `n` sequences
79
+ reproducibly; `max_tokens` caps the length (up to 100). Answers come back as `{text, finish}` ("stop" at the closing quote, a newline
80
+ or end of text; "length" at the cap) with no probability; same account feature, billed as a generated slot (2,000 tokens flat against
81
+ 500 for a searched one); no `top_k` / `calibration` with it.
82
+
83
+ Writing extraction templates (what the tests showed):
84
+
85
+ - `{*}`: in quotes, and name what goes there. `The company is "{*}"` reads as an adjective slot ("on track");
86
+ `The company in this news is "{*}"` gives "Apple". Without quotes the model also writes formatting (`<strong>Apple</strong>`).
87
+ - `{n}` / `{$}`: no quotes and no filler; end right at the slot (`\nQ: How many ...?\nA:{n}` or `\nUnits sold: {n}`).
88
+ - One number slot for integers and decimals: check integer-ness on `value`. Use `{$}` on financial content.
89
+ - Take the sign from `p_negative`, not from the top answer.
90
+ - When the answers are a known short list, a scored question (`{?}` + options) is cheaper and has an empty floor.
91
+
92
+ ## Calibrate a field
93
+
94
+ The raw probability ranks right answers above wrong ones but is under-confident by a field-dependent amount. Fit the
95
+ correction once per field on ~50 labelled examples:
96
+
97
+ ```python
98
+ from spinf_client import calibration
99
+
100
+ a, b = calibration.fit(ps, rights) # ps: the top answer's p per example, rights: was it right
101
+ query("amount", "\n\nQ: What was the revenue in 2019?\nA:{$}", calibration=(a, b)) # -> p_calibrated
102
+ ```
103
+
104
+ Without labels, `calibration.DEFAULT_MAPS[model]` is right on average but can be off by ~0.2 on a field.
105
+
106
+ ## Images and video
107
+
108
+ ```python
109
+ from spinf_client import image, video
110
+
111
+ client.score(content=[image("photo.jpg", detail="auto"), text("\n")],
112
+ queries=[query("what", '\nThis is a photo of "{*}"')])
113
+
114
+ # frames are sampled here with ffmpeg (the API never decodes video) and resized to the size the model reads
115
+ part = video("ad.mp4", num_frames=20, detail="low") # or fps=1
116
+ client.score(content=[text("A 31-second TV commercial:\n"), part, text("\n")],
117
+ queries=[query("brand", '\nThe brand featured in this commercial is "{*}"')])
118
+ ```
119
+
120
+ A video is read as Gemma reads video, in place in the content: each frame an image at `detail` (low = up to 70 tokens)
121
+ after its `mm:ss` timestamp (7 text tokens). `media.video_tokens(w, h, n)` gives the content tokens (32 low frames of a
122
+ 16:9 video: 2,399). ~20 low frames were enough for the brand of a Super Bowl ad (0.95 right on the 12B, 0.975 on the
123
+ 31B). The request body is limited to 2 MB: ~80 low frames (~17 KB each as JPEG).
124
+
125
+ ## Content moderation
126
+
127
+ The hosted `spinf/moderation` pack gives every text a calibrated 0–1 score per category (sexual, child safety,
128
+ violence, self-harm, hate, harassment, extremism, weapons, drugs, crime, fraud, hacking, privacy, spam, profanity,
129
+ gore, gibberish, a general score and four topics), its percentile on normal traffic, and a safe / unsafe decision.
130
+ The API does all of it in the call; nothing is computed here unless you ask.
131
+
132
+ ```python
133
+ r = client.moderate("Immigrants are vermin and should be thrown out.")
134
+ r.unsafe, r.flagged # True, ["hate", "general"]
135
+ r.categories["hate"] # Category(score=0.81, percentile=0.999, flagged=True)
136
+ r.top(3), r.decision # the decision as returned: mode, score, threshold, critical, ...
137
+
138
+ rs = client.moderate(posts, context="forum") # "ai" (a message to an assistant, default) or "forum" (a post)
139
+ ```
140
+
141
+ Decide your way (all optional, the pack's defaults otherwise):
142
+
143
+ | argument | what it does |
144
+ |---|---|
145
+ | `mode` | `micro_layer` (default: a small linear layer over the category scores and general reads), `max` (the highest category score against one threshold) or `per_category` (any category over its own threshold) |
146
+ | `threshold` | the one cut of `max` (0–1) or `micro_layer` (the layer's value) |
147
+ | `thresholds` | per category, `{"violence": 0.8, "profanity": None}`; `None` = reported, never decides. They set `flagged` in every mode. Defaults: the score 0.5% of normal traffic reaches |
148
+ | `critical` | categories that make a text unsafe whenever flagged, whatever the mode (default `["selfharm", "child"]`; `[]` = none) |
149
+ | `version` | pin the pack version (`client.list_packs()`) to keep scores comparable over time |
150
+ | `queries` | your own queries, scored in the same pass on the same content (`r.queries`) |
151
+
152
+ Texts are sent in batches of 64 (`batch_size`); the result list keeps their order (`ids=` names them).
153
+
154
+ **Your thresholds from your data** (no retraining; standard library):
155
+
156
+ ```python
157
+ from spinf_client import moderation
158
+
159
+ sample = client.moderate(my_normal_traffic, context="forum") # a few thousand typical texts
160
+ t = moderation.rate_thresholds(sample, rate=0.002) # flag 0.2% of it per category
161
+ t = moderation.fit_thresholds(labelled, labels) # or: best F1 on texts you labelled
162
+ # (labels[i] = {"hate", ...}, empty = fine)
163
+ cut = moderation.best_threshold([r.score for r in res], is_unsafe) # one cut for mode="max" / "micro_layer"
164
+ client.moderate(texts, mode="per_category", thresholds=t)
165
+ ```
166
+
167
+ **Re-decide without scoring again:** score with `include_queries=True` (the pack's raw query results stay on
168
+ `r.raw`), then try other modes, thresholds or critical lists locally:
169
+
170
+ ```python
171
+ pack_file = client.get_pack("spinf/moderation", r.version) # the pack file (keep it; it changes only by version)
172
+ r.redecide(pack_file, mode="max", threshold=0.8, thresholds={"spam": None}, critical=[]) # -> Moderation
173
+ ```
174
+
175
+ The local evaluator (`packs`) is the API's own, in the standard library: a verbatim copy of spinf-serve's
176
+ `spinf_serve/packs/pipeline.py`, kept identical by a test; it reproduces the API's scores to 1e-6.
177
+
178
+ **Edit the pack:** `client.moderate(texts, pack_file=edited)` sends an edited copy's questions as ordinary queries and
179
+ decides here. Thresholds and the critical list are yours to change; any change to the questions, reads or calibration
180
+ breaks the micro-layer's lock (a sha256 over them), and the pack's fallback mode (`per_category`) decides, with a
181
+ `warning` in the decision.
182
+
183
+ **Other packs and your own queries in one call:** `score()` takes `packs=[pack(id, ...)]` next to `queries`; each
184
+ result carries `packs` (`pack_result(out, id)`). `pack()` takes the same decision arguments as `moderate()`.
185
+
186
+ ## Pricing and usage
187
+
188
+ ```python
189
+ from spinf_client import billed_tokens
190
+
191
+ pricing = client.pricing() # what this account can use: models, media rates, extraction, content limit
192
+ m = next(x for x in pricing["models"] if x["model"] == "spinf-12b")
193
+ billed_tokens(m, text_tokens=150, frames={"low": 20}, query_tokens=23, floor_tokens=14, slots_per_content=[1]) # 2687
194
+ ```
195
+
196
+ Billed tokens = text (content text and timestamps) + images and frames at the model's rate per detail + audio per
197
+ second + question and floor tokens + extraction (500 tokens a searched slot, 2,000 a generated one), at least 1,000 a
198
+ call, at the model's price per million. The response's `usage.prompt_tokens_details` reports `text_tokens`, `media`
199
+ (`images`, `video_frames`, `audio_seconds`, `billed_media_tokens`) and `extraction` (`slots`, `generated_slots`,
200
+ `billed_tokens`);
201
+ `usage.billed_tokens` is what is charged. `client.models()` and `client.account()` wrap `GET /v1/models` and
202
+ `GET /v1/account`.
203
+
204
+ Errors raise `SpinfError` (`status`, `code`, `message`, `param`): e.g. `403 feature_not_enabled` (extraction not
205
+ enabled), `403 media_not_allowed` (video not enabled), `400 too_many_extractions`, `400 content_too_long` (over the
206
+ account's content limit), `413 body_too_large`. 429 / 5xx (including `503 warming_up`) and timeouts are retried.
@@ -0,0 +1,186 @@
1
+ # spinf-client
2
+
3
+ Python client for the spinf scoring API: scored queries (`{?}` + options), extraction slots (`{*}` text, `{n}` number,
4
+ `{$}` amount), images and video frames, prompt packs and content moderation. One runtime dependency (httpx). The same
5
+ client talks to the hosted API at `api.spinf.com` and to a [spinf-serve](https://github.com/spinfinc/spinf-serve) of your own:
6
+ the request and the response are the same, only the base URL and the key change.
7
+
8
+ ```bash
9
+ pip install "spinf-client[media]" # the media extra adds Pillow for images; video frames also need ffmpeg / ffprobe on PATH
10
+ export SPINF_API_KEY=sk-... # the hosted API
11
+ ```
12
+
13
+ ```python
14
+ from spinf_client import SpinfClient
15
+
16
+ client = SpinfClient() # api.spinf.com, model "spinf-12b"
17
+ client = SpinfClient(base_url="http://localhost:8000", model="spinf/gemma-4-12b-fp8") # your own spinf-serve
18
+ ```
19
+
20
+ A spinf-serve started without `--token` needs no key (`SPINF_API_URL` sets the base URL from the environment); one started
21
+ with a token takes it as `api_key`. The hosted model names (`spinf-12b`, `spinf-31b`) are aliases of the Hub names
22
+ (`spinf/gemma-4-12b-fp8`, `spinf/gemma-4-31b-fp8`) and both work on both. Account, pricing and billing (`client.account()`,
23
+ `client.pricing()`, `billed_tokens()`) and the per-account features (extraction slots, video, the content limit) belong to
24
+ the hosted API; a server of your own has every feature on and no bill.
25
+
26
+ ## Score and extract
27
+
28
+ ```python
29
+ from spinf_client import SpinfClient, answers, query, text
30
+
31
+ client = SpinfClient() # model="spinf-12b" by default (or "spinf-31b", ...)
32
+ out = client.score(
33
+ content=[text("Apple sold 3.5 million iPhones in the quarter, up from 3.1 million.")],
34
+ queries=[
35
+ query("dir", "\n\nDid iPhone sales go{?}", options=[" up", " down"]), # scored
36
+ query("units", "\n\nQ: How many iPhones were sold?\nA:{n}"), # a number
37
+ query("co", '\n\nThe company in this news is "{*}"', top_k=3), # text: in quotes, name the thing
38
+ ],
39
+ )
40
+ answers(out, "units") # {"answers": [{"text": "3.5 million", "p": 0.62, "value": 3500000.0}, ...], "mass": ..., "p_negative": 0.0}
41
+ ```
42
+
43
+ Slots:
44
+
45
+ | slot | the answer | ends |
46
+ |---|---|---|
47
+ | `{*}` | any text; write the template with an opening quote: `... is "{*}"` | at the text after the slot (the closing quote) or a newline |
48
+ | `{n}` | a number: sign or accounting brackets, thousands separators, decimals, `thousand` / `million` / `billion`, `%` | when the next token cannot continue the number |
49
+ | `{$}` | the same with an optional currency symbol (`$ € £ ¥`), returned as `currency` | the same |
50
+
51
+ Each extraction returns the most likely answers (merged over spellings: text by case / punctuation / spaces, numbers by
52
+ value) with their probabilities, `mass` (the probability on all answers found) and, for numbers, `p_negative` (the share
53
+ of the top value's magnitude on its negative: brackets in accounting tables are often ambiguous). `max_tokens` 1-64
54
+ (default 16; up to 100 generated), `top_k` 1-20 (default 5). At most **10 slots per content** (queries × combinations). Extraction slots have
55
+ no empty floor.
56
+
57
+ `generate=True` on a `{*}` slot writes free text instead of searching short answers (a one-sentence summary, a caption):
58
+ greedy by default, or `generate={"temperature": 0.7, "top_p": 0.8, "top_k": 20, "seed": 0, "n": 1}` to sample `n` sequences
59
+ reproducibly; `max_tokens` caps the length (up to 100). Answers come back as `{text, finish}` ("stop" at the closing quote, a newline
60
+ or end of text; "length" at the cap) with no probability; same account feature, billed as a generated slot (2,000 tokens flat against
61
+ 500 for a searched one); no `top_k` / `calibration` with it.
62
+
63
+ Writing extraction templates (what the tests showed):
64
+
65
+ - `{*}`: in quotes, and name what goes there. `The company is "{*}"` reads as an adjective slot ("on track");
66
+ `The company in this news is "{*}"` gives "Apple". Without quotes the model also writes formatting (`<strong>Apple</strong>`).
67
+ - `{n}` / `{$}`: no quotes and no filler; end right at the slot (`\nQ: How many ...?\nA:{n}` or `\nUnits sold: {n}`).
68
+ - One number slot for integers and decimals: check integer-ness on `value`. Use `{$}` on financial content.
69
+ - Take the sign from `p_negative`, not from the top answer.
70
+ - When the answers are a known short list, a scored question (`{?}` + options) is cheaper and has an empty floor.
71
+
72
+ ## Calibrate a field
73
+
74
+ The raw probability ranks right answers above wrong ones but is under-confident by a field-dependent amount. Fit the
75
+ correction once per field on ~50 labelled examples:
76
+
77
+ ```python
78
+ from spinf_client import calibration
79
+
80
+ a, b = calibration.fit(ps, rights) # ps: the top answer's p per example, rights: was it right
81
+ query("amount", "\n\nQ: What was the revenue in 2019?\nA:{$}", calibration=(a, b)) # -> p_calibrated
82
+ ```
83
+
84
+ Without labels, `calibration.DEFAULT_MAPS[model]` is right on average but can be off by ~0.2 on a field.
85
+
86
+ ## Images and video
87
+
88
+ ```python
89
+ from spinf_client import image, video
90
+
91
+ client.score(content=[image("photo.jpg", detail="auto"), text("\n")],
92
+ queries=[query("what", '\nThis is a photo of "{*}"')])
93
+
94
+ # frames are sampled here with ffmpeg (the API never decodes video) and resized to the size the model reads
95
+ part = video("ad.mp4", num_frames=20, detail="low") # or fps=1
96
+ client.score(content=[text("A 31-second TV commercial:\n"), part, text("\n")],
97
+ queries=[query("brand", '\nThe brand featured in this commercial is "{*}"')])
98
+ ```
99
+
100
+ A video is read as Gemma reads video, in place in the content: each frame an image at `detail` (low = up to 70 tokens)
101
+ after its `mm:ss` timestamp (7 text tokens). `media.video_tokens(w, h, n)` gives the content tokens (32 low frames of a
102
+ 16:9 video: 2,399). ~20 low frames were enough for the brand of a Super Bowl ad (0.95 right on the 12B, 0.975 on the
103
+ 31B). The request body is limited to 2 MB: ~80 low frames (~17 KB each as JPEG).
104
+
105
+ ## Content moderation
106
+
107
+ The hosted `spinf/moderation` pack gives every text a calibrated 0–1 score per category (sexual, child safety,
108
+ violence, self-harm, hate, harassment, extremism, weapons, drugs, crime, fraud, hacking, privacy, spam, profanity,
109
+ gore, gibberish, a general score and four topics), its percentile on normal traffic, and a safe / unsafe decision.
110
+ The API does all of it in the call; nothing is computed here unless you ask.
111
+
112
+ ```python
113
+ r = client.moderate("Immigrants are vermin and should be thrown out.")
114
+ r.unsafe, r.flagged # True, ["hate", "general"]
115
+ r.categories["hate"] # Category(score=0.81, percentile=0.999, flagged=True)
116
+ r.top(3), r.decision # the decision as returned: mode, score, threshold, critical, ...
117
+
118
+ rs = client.moderate(posts, context="forum") # "ai" (a message to an assistant, default) or "forum" (a post)
119
+ ```
120
+
121
+ Decide your way (all optional, the pack's defaults otherwise):
122
+
123
+ | argument | what it does |
124
+ |---|---|
125
+ | `mode` | `micro_layer` (default: a small linear layer over the category scores and general reads), `max` (the highest category score against one threshold) or `per_category` (any category over its own threshold) |
126
+ | `threshold` | the one cut of `max` (0–1) or `micro_layer` (the layer's value) |
127
+ | `thresholds` | per category, `{"violence": 0.8, "profanity": None}`; `None` = reported, never decides. They set `flagged` in every mode. Defaults: the score 0.5% of normal traffic reaches |
128
+ | `critical` | categories that make a text unsafe whenever flagged, whatever the mode (default `["selfharm", "child"]`; `[]` = none) |
129
+ | `version` | pin the pack version (`client.list_packs()`) to keep scores comparable over time |
130
+ | `queries` | your own queries, scored in the same pass on the same content (`r.queries`) |
131
+
132
+ Texts are sent in batches of 64 (`batch_size`); the result list keeps their order (`ids=` names them).
133
+
134
+ **Your thresholds from your data** (no retraining; standard library):
135
+
136
+ ```python
137
+ from spinf_client import moderation
138
+
139
+ sample = client.moderate(my_normal_traffic, context="forum") # a few thousand typical texts
140
+ t = moderation.rate_thresholds(sample, rate=0.002) # flag 0.2% of it per category
141
+ t = moderation.fit_thresholds(labelled, labels) # or: best F1 on texts you labelled
142
+ # (labels[i] = {"hate", ...}, empty = fine)
143
+ cut = moderation.best_threshold([r.score for r in res], is_unsafe) # one cut for mode="max" / "micro_layer"
144
+ client.moderate(texts, mode="per_category", thresholds=t)
145
+ ```
146
+
147
+ **Re-decide without scoring again:** score with `include_queries=True` (the pack's raw query results stay on
148
+ `r.raw`), then try other modes, thresholds or critical lists locally:
149
+
150
+ ```python
151
+ pack_file = client.get_pack("spinf/moderation", r.version) # the pack file (keep it; it changes only by version)
152
+ r.redecide(pack_file, mode="max", threshold=0.8, thresholds={"spam": None}, critical=[]) # -> Moderation
153
+ ```
154
+
155
+ The local evaluator (`packs`) is the API's own, in the standard library: a verbatim copy of spinf-serve's
156
+ `spinf_serve/packs/pipeline.py`, kept identical by a test; it reproduces the API's scores to 1e-6.
157
+
158
+ **Edit the pack:** `client.moderate(texts, pack_file=edited)` sends an edited copy's questions as ordinary queries and
159
+ decides here. Thresholds and the critical list are yours to change; any change to the questions, reads or calibration
160
+ breaks the micro-layer's lock (a sha256 over them), and the pack's fallback mode (`per_category`) decides, with a
161
+ `warning` in the decision.
162
+
163
+ **Other packs and your own queries in one call:** `score()` takes `packs=[pack(id, ...)]` next to `queries`; each
164
+ result carries `packs` (`pack_result(out, id)`). `pack()` takes the same decision arguments as `moderate()`.
165
+
166
+ ## Pricing and usage
167
+
168
+ ```python
169
+ from spinf_client import billed_tokens
170
+
171
+ pricing = client.pricing() # what this account can use: models, media rates, extraction, content limit
172
+ m = next(x for x in pricing["models"] if x["model"] == "spinf-12b")
173
+ billed_tokens(m, text_tokens=150, frames={"low": 20}, query_tokens=23, floor_tokens=14, slots_per_content=[1]) # 2687
174
+ ```
175
+
176
+ Billed tokens = text (content text and timestamps) + images and frames at the model's rate per detail + audio per
177
+ second + question and floor tokens + extraction (500 tokens a searched slot, 2,000 a generated one), at least 1,000 a
178
+ call, at the model's price per million. The response's `usage.prompt_tokens_details` reports `text_tokens`, `media`
179
+ (`images`, `video_frames`, `audio_seconds`, `billed_media_tokens`) and `extraction` (`slots`, `generated_slots`,
180
+ `billed_tokens`);
181
+ `usage.billed_tokens` is what is charged. `client.models()` and `client.account()` wrap `GET /v1/models` and
182
+ `GET /v1/account`.
183
+
184
+ Errors raise `SpinfError` (`status`, `code`, `message`, `param`): e.g. `403 feature_not_enabled` (extraction not
185
+ enabled), `403 media_not_allowed` (video not enabled), `400 too_many_extractions`, `400 content_too_long` (over the
186
+ account's content limit), `413 body_too_large`. 429 / 5xx (including `503 warming_up`) and timeouts are retried.