stackone-defender 0.7.2__tar.gz → 0.7.4__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.
- stackone_defender-0.7.4/.release-please-manifest.json +1 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/CHANGELOG.md +26 -0
- stackone_defender-0.7.4/LICENSE +190 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/PKG-INFO +45 -4
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/README.md +41 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/pyproject.toml +26 -3
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/classifiers/onnx_classifier.py +96 -27
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/classifiers/tier2_classifier.py +7 -5
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/core/prompt_defense.py +135 -20
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/core/tool_result_sanitizer.py +0 -1
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/sanitizers/__init__.py +7 -1
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/sanitizers/encoding_detector.py +4 -1
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/sfe/preprocess.py +6 -4
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/types.py +37 -1
- stackone_defender-0.7.4/tests/__init__.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/tests/test_integration.py +74 -5
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/tests/test_onnx_classifier.py +130 -4
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/tests/test_pattern_detector.py +0 -3
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/tests/test_sanitizers.py +22 -1
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/tests/test_sfe.py +17 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/tests/test_tier2_classifier.py +2 -5
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/tests/test_tier3.py +131 -1
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/tests/test_utils.py +1 -5
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/uv.lock +196 -10
- stackone_defender-0.7.2/.github/workflows/ci.yaml +0 -24
- stackone_defender-0.7.2/.github/workflows/release.yaml +0 -31
- stackone_defender-0.7.2/.release-please-manifest.json +0 -1
- stackone_defender-0.7.2/models/minilm-full-aug/config.json +0 -30
- stackone_defender-0.7.2/models/minilm-full-aug/model_quantized.onnx +0 -0
- stackone_defender-0.7.2/src/stackone_defender/models/minilm-multihead-v5/tokenizer.json +0 -30686
- stackone_defender-0.7.2/src/stackone_defender/models/minilm-multihead-v5/tokenizer_config.json +0 -23
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/.gitignore +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/.python-version +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/.release-please-config.json +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/__init__.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/classifiers/__init__.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/classifiers/pattern_detector.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/classifiers/patterns.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/classifiers/tier3_orchestrator.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/config.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/core/__init__.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/models/minilm-multihead-v5/classifier_config.json +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/models/minilm-multihead-v5/config.json +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/models/minilm-multihead-v5/model_quantized.onnx +0 -0
- {stackone_defender-0.7.2/models/minilm-full-aug → stackone_defender-0.7.4/src/stackone_defender/models/minilm-multihead-v5}/tokenizer.json +0 -0
- {stackone_defender-0.7.2/models/minilm-full-aug → stackone_defender-0.7.4/src/stackone_defender/models/minilm-multihead-v5}/tokenizer_config.json +0 -0
- /stackone_defender-0.7.2/tests/__init__.py → /stackone_defender-0.7.4/src/stackone_defender/py.typed +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/sanitizers/leet_normalizer.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/sanitizers/normalizer.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/sanitizers/pattern_remover.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/sanitizers/role_stripper.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/sanitizers/sanitizer.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/sfe/__init__.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/sfe/model.ftz +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/utils/__init__.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/utils/boundary.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/utils/field_detection.py +0 -0
- {stackone_defender-0.7.2 → stackone_defender-0.7.4}/src/stackone_defender/utils/structure.py +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{".":"0.7.4"}
|
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.7.4](https://github.com/StackOneHQ/defender-py/compare/stackone-defender-v0.7.3...stackone-defender-v0.7.4) (2026-08-13)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Features
|
|
7
|
+
|
|
8
|
+
* **ENG-1761:** port Tier 2 buckets, dedupe, and cost telemetry from TS 0.7.4 ([b92b9f6](https://github.com/StackOneHQ/defender-py/commit/b92b9f661ef927b27542a664d92477e039279758))
|
|
9
|
+
* **ENG-1761:** port Tier 2 fixed-width buckets, dedupe, cost telemetry from TS 0.7.4 ([1e63d09](https://github.com/StackOneHQ/defender-py/commit/1e63d0999d003348c17d6700bf6a03b65a7b2242))
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
### Bug Fixes
|
|
13
|
+
|
|
14
|
+
* **ENG-1761:** address review — cold_load on failure paths + stronger tests ([e897786](https://github.com/StackOneHQ/defender-py/commit/e897786ff013b95b7b74eecd8df554ee978dd98b))
|
|
15
|
+
|
|
16
|
+
## [0.7.3](https://github.com/StackOneHQ/defender-py/compare/stackone-defender-v0.7.2...stackone-defender-v0.7.3) (2026-07-22)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
### Features
|
|
20
|
+
|
|
21
|
+
* **ENG-1279:** port Tier 3 score-threshold (decide on score, not the model's word) ([77c8a6a](https://github.com/StackOneHQ/defender-py/commit/77c8a6a38336ddd797f5691cedf4670f15f575fb))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
### Bug Fixes
|
|
25
|
+
|
|
26
|
+
* **ENG-1279:** Tier 3 score threshold + ENG-1296 Tier 2/base64/SFE fixes ([3f2b9cd](https://github.com/StackOneHQ/defender-py/commit/3f2b9cd1f7dd82f19e468076bcb3196ad22bf83e))
|
|
27
|
+
* **ENG-1296:** port TS parity fixes for Tier 2 truncation, base64, SFE recursion ([4fa8cda](https://github.com/StackOneHQ/defender-py/commit/4fa8cda445d8c08e30e74d6053e2eaf26026fed2))
|
|
28
|
+
|
|
3
29
|
## [0.7.2](https://github.com/StackOneHQ/stackone-defender/compare/stackone-defender-v0.7.1...stackone-defender-v0.7.2) (2026-06-30)
|
|
4
30
|
|
|
5
31
|
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but not
|
|
32
|
+
limited to compiled object code, generated documentation, and
|
|
33
|
+
conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding any notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2024 StackOne
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: stackone-defender
|
|
3
|
-
Version: 0.7.
|
|
3
|
+
Version: 0.7.4
|
|
4
4
|
Summary: Indirect prompt injection defense for AI agents using tool calls
|
|
5
5
|
Project-URL: Homepage, https://github.com/StackOneHQ/stackone-defender
|
|
6
6
|
Project-URL: Repository, https://github.com/StackOneHQ/stackone-defender
|
|
7
7
|
Author-email: StackOne <support@stackone.com>
|
|
8
|
-
License: Apache-2.0
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
9
10
|
Classifier: Development Status :: 4 - Beta
|
|
10
11
|
Classifier: Intended Audience :: Developers
|
|
11
|
-
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
12
|
Classifier: Programming Language :: Python :: 3
|
|
13
13
|
Classifier: Programming Language :: Python :: 3.11
|
|
14
14
|
Classifier: Programming Language :: Python :: 3.12
|
|
@@ -146,6 +146,47 @@ Packed-chunk MiniLM classifier (int8 ONNX ~22 MB, bundled):
|
|
|
146
146
|
| jayavibhav (adversarial) | 0.9717 | ~1k |
|
|
147
147
|
| **Average** | **0.9079** | ~25k |
|
|
148
148
|
|
|
149
|
+
### Optional Tier 3 — LLM adjudication (consumer-supplied)
|
|
150
|
+
|
|
151
|
+
Authoritative LLM-based classification for the cases Tier 2 finds ambiguous. The package ships **only** the orchestration and the `Tier3Provider` interface — the actual model endpoint (a hosted LLM, OpenAI, an internal inference service) lives in your code, keeping proprietary models and credentials out of the package.
|
|
152
|
+
|
|
153
|
+
Two modes, selected via `defender_mode`:
|
|
154
|
+
- **`"cascade"`** (default): Tier 1 → Tier 2 → Tier 3, with Tier 3 invoked only when the Tier 2 effective score falls in the gray band (default `[0.3, 0.85)`). The Tier 3 verdict overrides Tier 2 on the escalated chunk — a `block` forces a block, an `allow` rescues it. Outside the band defender skips the round trip.
|
|
155
|
+
- **`"tier3_only"`**: skip Tier 2; the block/allow decision is the Tier 3 verdict alone. Tier 1 still sanitizes the returned `sanitized` payload.
|
|
156
|
+
|
|
157
|
+
Register a provider once at startup, then opt in per instance:
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
from typing import Any
|
|
161
|
+
|
|
162
|
+
from stackone_defender import create_prompt_defense, set_default_tier3_provider
|
|
163
|
+
from stackone_defender.types import Tier3Verdict
|
|
164
|
+
|
|
165
|
+
class MyProvider:
|
|
166
|
+
def classify(self, text: str, *, ctx: dict[str, Any] | None = None) -> Tier3Verdict:
|
|
167
|
+
# Call your LLM endpoint here (sync or awaitable). ctx["toolName"] is available.
|
|
168
|
+
verdict = call_my_llm(text, tool_name=(ctx or {}).get("toolName"))
|
|
169
|
+
return Tier3Verdict(decision="block" if verdict.block else "allow", score=verdict.p_block)
|
|
170
|
+
|
|
171
|
+
set_default_tier3_provider(MyProvider())
|
|
172
|
+
|
|
173
|
+
defense = create_prompt_defense(
|
|
174
|
+
block_high_risk=True,
|
|
175
|
+
enable_tier3=True,
|
|
176
|
+
defender_mode="cascade", # or "tier3_only"
|
|
177
|
+
tier3={
|
|
178
|
+
"provider": MyProvider(), # optional: overrides the registry for this instance
|
|
179
|
+
"escalation_band": {"lower": 0.3, "upper": 0.85}, # cascade gray band; [lower, upper), defaults shown
|
|
180
|
+
"max_text_length": 10000, # caps text passed to the provider
|
|
181
|
+
"block_threshold": 0.622, # optional; decide on score, not the model's word
|
|
182
|
+
},
|
|
183
|
+
)
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
**Choosing the operating point (`block_threshold`).** By default the model's `decision` word is authoritative — but that word is its argmax, an implicit 0.5 cut that moves on its own whenever the model is retrained. Set `tier3.block_threshold` to decide on `verdict.score` (P(block)) instead: the cut becomes an explicit config value — raise it to trade recall for fewer false positives, lower it for the reverse; `0.5` reproduces argmax. It requires a provider that reports `score` as P(block) (not "confidence in whichever decision I made" — those invert on allows). If `score` is missing or outside `[0, 1]` the verdict's `decision` is used instead and defender warns once, so a provider that cannot report a score degrades to the default rather than failing.
|
|
187
|
+
|
|
188
|
+
**Fail-open semantics.** A provider error or timeout records a `skip_reason` on `result.tier3`; in cascade defender falls back to the Tier 2 decision, in `tier3_only` it allows the request. `enable_tier3=True` with no registered provider falls back to the standard Tier 1 + Tier 2 cascade and logs one warning per instance — Tier 3 misconfiguration never silently disables defense. `result.tier3` carries the verdict (a `Tier3Verdict`, or a `Tier3Skip` when the provider ran but returned nothing usable) when Tier 3 runs, and is `None` when it doesn't.
|
|
189
|
+
|
|
149
190
|
### `allowed` vs `risk_level`
|
|
150
191
|
|
|
151
192
|
- Use **`allowed`** for gating when `block_high_risk=True`: `False` means do not pass `sanitized` to the model as-is.
|
|
@@ -120,6 +120,47 @@ Packed-chunk MiniLM classifier (int8 ONNX ~22 MB, bundled):
|
|
|
120
120
|
| jayavibhav (adversarial) | 0.9717 | ~1k |
|
|
121
121
|
| **Average** | **0.9079** | ~25k |
|
|
122
122
|
|
|
123
|
+
### Optional Tier 3 — LLM adjudication (consumer-supplied)
|
|
124
|
+
|
|
125
|
+
Authoritative LLM-based classification for the cases Tier 2 finds ambiguous. The package ships **only** the orchestration and the `Tier3Provider` interface — the actual model endpoint (a hosted LLM, OpenAI, an internal inference service) lives in your code, keeping proprietary models and credentials out of the package.
|
|
126
|
+
|
|
127
|
+
Two modes, selected via `defender_mode`:
|
|
128
|
+
- **`"cascade"`** (default): Tier 1 → Tier 2 → Tier 3, with Tier 3 invoked only when the Tier 2 effective score falls in the gray band (default `[0.3, 0.85)`). The Tier 3 verdict overrides Tier 2 on the escalated chunk — a `block` forces a block, an `allow` rescues it. Outside the band defender skips the round trip.
|
|
129
|
+
- **`"tier3_only"`**: skip Tier 2; the block/allow decision is the Tier 3 verdict alone. Tier 1 still sanitizes the returned `sanitized` payload.
|
|
130
|
+
|
|
131
|
+
Register a provider once at startup, then opt in per instance:
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
from typing import Any
|
|
135
|
+
|
|
136
|
+
from stackone_defender import create_prompt_defense, set_default_tier3_provider
|
|
137
|
+
from stackone_defender.types import Tier3Verdict
|
|
138
|
+
|
|
139
|
+
class MyProvider:
|
|
140
|
+
def classify(self, text: str, *, ctx: dict[str, Any] | None = None) -> Tier3Verdict:
|
|
141
|
+
# Call your LLM endpoint here (sync or awaitable). ctx["toolName"] is available.
|
|
142
|
+
verdict = call_my_llm(text, tool_name=(ctx or {}).get("toolName"))
|
|
143
|
+
return Tier3Verdict(decision="block" if verdict.block else "allow", score=verdict.p_block)
|
|
144
|
+
|
|
145
|
+
set_default_tier3_provider(MyProvider())
|
|
146
|
+
|
|
147
|
+
defense = create_prompt_defense(
|
|
148
|
+
block_high_risk=True,
|
|
149
|
+
enable_tier3=True,
|
|
150
|
+
defender_mode="cascade", # or "tier3_only"
|
|
151
|
+
tier3={
|
|
152
|
+
"provider": MyProvider(), # optional: overrides the registry for this instance
|
|
153
|
+
"escalation_band": {"lower": 0.3, "upper": 0.85}, # cascade gray band; [lower, upper), defaults shown
|
|
154
|
+
"max_text_length": 10000, # caps text passed to the provider
|
|
155
|
+
"block_threshold": 0.622, # optional; decide on score, not the model's word
|
|
156
|
+
},
|
|
157
|
+
)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
**Choosing the operating point (`block_threshold`).** By default the model's `decision` word is authoritative — but that word is its argmax, an implicit 0.5 cut that moves on its own whenever the model is retrained. Set `tier3.block_threshold` to decide on `verdict.score` (P(block)) instead: the cut becomes an explicit config value — raise it to trade recall for fewer false positives, lower it for the reverse; `0.5` reproduces argmax. It requires a provider that reports `score` as P(block) (not "confidence in whichever decision I made" — those invert on allows). If `score` is missing or outside `[0, 1]` the verdict's `decision` is used instead and defender warns once, so a provider that cannot report a score degrades to the default rather than failing.
|
|
161
|
+
|
|
162
|
+
**Fail-open semantics.** A provider error or timeout records a `skip_reason` on `result.tier3`; in cascade defender falls back to the Tier 2 decision, in `tier3_only` it allows the request. `enable_tier3=True` with no registered provider falls back to the standard Tier 1 + Tier 2 cascade and logs one warning per instance — Tier 3 misconfiguration never silently disables defense. `result.tier3` carries the verdict (a `Tier3Verdict`, or a `Tier3Skip` when the provider ran but returned nothing usable) when Tier 3 runs, and is `None` when it doesn't.
|
|
163
|
+
|
|
123
164
|
### `allowed` vs `risk_level`
|
|
124
165
|
|
|
125
166
|
- Use **`allowed`** for gating when `block_high_risk=True`: `False` means do not pass `sanitized` to the model as-is.
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "stackone-defender"
|
|
3
|
-
version = "0.7.
|
|
3
|
+
version = "0.7.4"
|
|
4
4
|
description = "Indirect prompt injection defense for AI agents using tool calls"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.11"
|
|
7
|
-
license =
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
8
9
|
authors = [{ name = "StackOne", email = "support@stackone.com" }]
|
|
9
10
|
classifiers = [
|
|
10
11
|
"Development Status :: 4 - Beta",
|
|
11
12
|
"Intended Audience :: Developers",
|
|
12
|
-
"License :: OSI Approved :: Apache Software License",
|
|
13
13
|
"Programming Language :: Python :: 3",
|
|
14
14
|
"Programming Language :: Python :: 3.11",
|
|
15
15
|
"Programming Language :: Python :: 3.12",
|
|
@@ -32,6 +32,8 @@ sfe = ["fasttext-ng>=0.9.3"]
|
|
|
32
32
|
[dependency-groups]
|
|
33
33
|
dev = [
|
|
34
34
|
"pytest>=8.0",
|
|
35
|
+
"pytest-cov>=5.0",
|
|
36
|
+
"ruff>=0.9",
|
|
35
37
|
"onnxruntime>=1.16.0",
|
|
36
38
|
"tokenizers>=0.15.0",
|
|
37
39
|
"numpy>=1.24.0",
|
|
@@ -45,5 +47,26 @@ build-backend = "hatchling.build"
|
|
|
45
47
|
[tool.hatch.build.targets.wheel]
|
|
46
48
|
packages = ["src/stackone_defender"]
|
|
47
49
|
|
|
50
|
+
[tool.hatch.build.targets.sdist]
|
|
51
|
+
exclude = ["/models", "/.github"] # legacy model + CI, dev-only
|
|
52
|
+
|
|
53
|
+
[tool.ruff]
|
|
54
|
+
target-version = "py311"
|
|
55
|
+
line-length = 120
|
|
56
|
+
src = ["src", "tests"]
|
|
57
|
+
|
|
58
|
+
[tool.ruff.lint]
|
|
59
|
+
select = ["E", "W", "F", "I", "N", "UP", "B", "C4", "SIM", "RUF"]
|
|
60
|
+
# E501/RUF003 by design; SIM*/UP007 deferred to cleanup.
|
|
61
|
+
ignore = ["E501", "RUF003", "SIM102", "SIM103", "SIM108", "SIM110", "SIM118", "UP007"]
|
|
62
|
+
|
|
63
|
+
[tool.ruff.lint.per-file-ignores]
|
|
64
|
+
"tests/*" = ["RUF012", "N814", "F841", "F811"]
|
|
65
|
+
|
|
48
66
|
[tool.pytest.ini_options]
|
|
49
67
|
testpaths = ["tests"]
|
|
68
|
+
addopts = "--strict-markers --strict-config -ra"
|
|
69
|
+
markers = [
|
|
70
|
+
"model: requires the bundled ONNX model + onnxruntime extra",
|
|
71
|
+
"sfe: requires the fasttext extra",
|
|
72
|
+
]
|
|
@@ -11,13 +11,24 @@ from __future__ import annotations
|
|
|
11
11
|
import logging
|
|
12
12
|
import math
|
|
13
13
|
import threading
|
|
14
|
+
from dataclasses import dataclass
|
|
14
15
|
from pathlib import Path
|
|
15
|
-
from typing import Literal
|
|
16
|
+
from typing import Literal, cast
|
|
16
17
|
|
|
17
18
|
_logger = logging.getLogger(__name__)
|
|
18
19
|
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class BatchTokenStats:
|
|
23
|
+
"""Padding accounting accumulated across a batched classification (#6 telemetry)."""
|
|
24
|
+
|
|
25
|
+
real_tokens: int = 0 # sum of real (non-pad) tokens across all chunks
|
|
26
|
+
padded_tokens: int = 0 # tokens actually run through ONNX, including padding
|
|
27
|
+
|
|
19
28
|
# Shared across all OnnxClassifier instances (keyed by resolved model dir path).
|
|
20
|
-
|
|
29
|
+
# Tuple is (session, tokenizer, count_tokenizer); the count tokenizer is
|
|
30
|
+
# non-truncating so count_tokens reports true length (see _load_model).
|
|
31
|
+
_session_cache: dict[str, tuple[object, object, object]] = {}
|
|
21
32
|
_registry_lock = threading.Lock()
|
|
22
33
|
_load_locks: dict[str, threading.Lock] = {}
|
|
23
34
|
|
|
@@ -59,11 +70,17 @@ class OnnxClassifier:
|
|
|
59
70
|
"""
|
|
60
71
|
|
|
61
72
|
_MAX_BATCH_CHUNK = 32
|
|
73
|
+
# Fixed pad widths (ascending). A string pads to the smallest bucket >= its
|
|
74
|
+
# token length, so its padded length — and thus its quantized score — is a
|
|
75
|
+
# function of the string alone, not its batch neighbours (deterministic).
|
|
76
|
+
_PAD_BUCKETS = (32, 64, 128, 256)
|
|
62
77
|
|
|
63
78
|
def __init__(self, model_path: str | None = None, temperature_t: float | None = None):
|
|
64
79
|
self._model_path = model_path or get_default_model_path()
|
|
65
80
|
self._session = None
|
|
66
81
|
self._tokenizer = None
|
|
82
|
+
# Non-truncating tokenizer used only by count_tokens (see _load_model).
|
|
83
|
+
self._count_tokenizer = None
|
|
67
84
|
self._max_length = 256
|
|
68
85
|
self._load_failed = False
|
|
69
86
|
# Output mode is detected lazily from the logits shape on the first
|
|
@@ -114,13 +131,13 @@ class OnnxClassifier:
|
|
|
114
131
|
cache_key = str(Path(self._model_path).resolve())
|
|
115
132
|
cached = _session_cache.get(cache_key)
|
|
116
133
|
if cached:
|
|
117
|
-
self._session, self._tokenizer = cached
|
|
134
|
+
self._session, self._tokenizer, self._count_tokenizer = cached
|
|
118
135
|
return
|
|
119
136
|
|
|
120
137
|
with _lock_for_cache_key(cache_key):
|
|
121
138
|
cached = _session_cache.get(cache_key)
|
|
122
139
|
if cached:
|
|
123
|
-
self._session, self._tokenizer = cached
|
|
140
|
+
self._session, self._tokenizer, self._count_tokenizer = cached
|
|
124
141
|
return
|
|
125
142
|
|
|
126
143
|
try:
|
|
@@ -138,7 +155,18 @@ class OnnxClassifier:
|
|
|
138
155
|
tokenizer_path = str(Path(self._model_path) / "tokenizer.json")
|
|
139
156
|
self._tokenizer = Tokenizer.from_file(tokenizer_path)
|
|
140
157
|
self._tokenizer.enable_truncation(max_length=self._max_length)
|
|
141
|
-
|
|
158
|
+
# No fixed padding: classify_batch_pair pads each batch per bucket
|
|
159
|
+
# width (see _PAD_BUCKETS), so a string's padded length depends only
|
|
160
|
+
# on itself. Single classify runs at the string's real length.
|
|
161
|
+
self._tokenizer.no_padding()
|
|
162
|
+
|
|
163
|
+
# tokenizer.json bakes in truncation+padding, so disable both
|
|
164
|
+
# here to count true length rather than a value capped at
|
|
165
|
+
# max_length (which would make every long payload look like a
|
|
166
|
+
# single chunk and drop everything past the cap).
|
|
167
|
+
self._count_tokenizer = Tokenizer.from_file(tokenizer_path)
|
|
168
|
+
self._count_tokenizer.no_truncation()
|
|
169
|
+
self._count_tokenizer.no_padding()
|
|
142
170
|
|
|
143
171
|
onnx_path = str(Path(self._model_path) / "model_quantized.onnx")
|
|
144
172
|
self._session = ort.InferenceSession(onnx_path)
|
|
@@ -146,7 +174,7 @@ class OnnxClassifier:
|
|
|
146
174
|
_logger.warning("[defender] ONNX model failed to load: %s", e)
|
|
147
175
|
raise
|
|
148
176
|
|
|
149
|
-
_session_cache[cache_key] = (self._session, self._tokenizer)
|
|
177
|
+
_session_cache[cache_key] = (self._session, self._tokenizer, self._count_tokenizer)
|
|
150
178
|
|
|
151
179
|
# ------------------------------------------------------------------
|
|
152
180
|
# Inference
|
|
@@ -187,36 +215,77 @@ class OnnxClassifier:
|
|
|
187
215
|
main_logit = float(row[0]) if hasattr(row, "__len__") and len(row) > 0 else float(row)
|
|
188
216
|
return _sigmoid(main_logit / t), None
|
|
189
217
|
|
|
190
|
-
def classify_batch(self, texts: list[str]) -> list[float]:
|
|
218
|
+
def classify_batch(self, texts: list[str], stats: BatchTokenStats | None = None) -> list[float]:
|
|
191
219
|
"""Classify multiple texts; returns main-head scores only.
|
|
192
220
|
|
|
193
221
|
Back-compat wrapper around :meth:`classify_batch_pair`.
|
|
194
222
|
"""
|
|
195
|
-
return [main for main, _ in self.classify_batch_pair(texts)]
|
|
223
|
+
return [main for main, _ in self.classify_batch_pair(texts, stats)]
|
|
196
224
|
|
|
197
|
-
def classify_batch_pair(
|
|
225
|
+
def classify_batch_pair(
|
|
226
|
+
self, texts: list[str], stats: BatchTokenStats | None = None
|
|
227
|
+
) -> list[tuple[float, float | None]]:
|
|
198
228
|
"""Classify multiple texts, returning ``(main, aux)`` per row.
|
|
199
229
|
|
|
200
|
-
Aux is ``None`` per-row for single-head models.
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
230
|
+
Aux is ``None`` per-row for single-head models. Groups strings into fixed
|
|
231
|
+
pad-width buckets by token length, batches within each bucket, and pads
|
|
232
|
+
every row to the BUCKET width (not the batch max). This bounds padding
|
|
233
|
+
waste and makes a string's padded length — hence its quantized score —
|
|
234
|
+
depend only on itself, not its batch neighbours. Chunks of 32 bound
|
|
235
|
+
native memory (attention is ``O(chunk * seq_len^2)``). Results scatter
|
|
236
|
+
back to input order. ``stats`` accumulates padding counts when provided.
|
|
204
237
|
"""
|
|
205
238
|
if not texts:
|
|
206
239
|
return []
|
|
207
240
|
self._ensure_loaded()
|
|
208
|
-
all_pairs: list[tuple[float, float | None]] = []
|
|
209
|
-
for offset in range(0, len(texts), self._MAX_BATCH_CHUNK):
|
|
210
|
-
chunk = texts[offset : offset + self._MAX_BATCH_CHUNK]
|
|
211
|
-
all_pairs.extend(self._classify_batch_chunk_pair(chunk))
|
|
212
|
-
return all_pairs
|
|
213
241
|
|
|
214
|
-
|
|
242
|
+
encodings = self._tokenizer.encode_batch(texts)
|
|
243
|
+
last_bucket = self._PAD_BUCKETS[-1]
|
|
244
|
+
buckets: dict[int, list[int]] = {}
|
|
245
|
+
for i, enc in enumerate(encodings):
|
|
246
|
+
length = len(enc.ids)
|
|
247
|
+
width = next((b for b in self._PAD_BUCKETS if length <= b), last_bucket)
|
|
248
|
+
buckets.setdefault(width, []).append(i)
|
|
249
|
+
|
|
250
|
+
pairs: list[tuple[float, float | None] | None] = [None] * len(texts)
|
|
251
|
+
for width in self._PAD_BUCKETS:
|
|
252
|
+
bucket_idxs = buckets.get(width)
|
|
253
|
+
if not bucket_idxs:
|
|
254
|
+
continue
|
|
255
|
+
for offset in range(0, len(bucket_idxs), self._MAX_BATCH_CHUNK):
|
|
256
|
+
idxs = bucket_idxs[offset : offset + self._MAX_BATCH_CHUNK]
|
|
257
|
+
chunk = [encodings[i] for i in idxs]
|
|
258
|
+
if stats is not None:
|
|
259
|
+
# Every row pads to the bucket width; real_tokens is useful work.
|
|
260
|
+
stats.padded_tokens += len(chunk) * width
|
|
261
|
+
for enc in chunk:
|
|
262
|
+
stats.real_tokens += len(enc.ids)
|
|
263
|
+
chunk_pairs = self._classify_batch_chunk_pair(chunk, width)
|
|
264
|
+
for k, orig_idx in enumerate(idxs):
|
|
265
|
+
pairs[orig_idx] = chunk_pairs[k]
|
|
266
|
+
|
|
267
|
+
return cast(list[tuple[float, float | None]], pairs)
|
|
268
|
+
|
|
269
|
+
def _classify_batch_chunk_pair(
|
|
270
|
+
self, encodings: list, pad_to: int | None = None
|
|
271
|
+
) -> list[tuple[float, float | None]]:
|
|
272
|
+
"""Run one pre-tokenized chunk through ONNX, padding rows to ``pad_to``.
|
|
273
|
+
|
|
274
|
+
Rows are padded to at least the chunk's real max, so a caller can never
|
|
275
|
+
under-pad. Inputs are pre-tokenized so ``classify_batch_pair`` can
|
|
276
|
+
length-bucket without re-tokenizing.
|
|
277
|
+
"""
|
|
215
278
|
import numpy as np
|
|
216
279
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
280
|
+
actual_max = max(len(e.ids) for e in encodings)
|
|
281
|
+
max_len = max(pad_to, actual_max) if pad_to is not None else actual_max
|
|
282
|
+
batch_size = len(encodings)
|
|
283
|
+
input_ids = np.zeros((batch_size, max_len), dtype=np.int64)
|
|
284
|
+
attention_mask = np.zeros((batch_size, max_len), dtype=np.int64)
|
|
285
|
+
for i, enc in enumerate(encodings):
|
|
286
|
+
n = len(enc.ids)
|
|
287
|
+
input_ids[i, :n] = enc.ids
|
|
288
|
+
attention_mask[i, :n] = enc.attention_mask
|
|
220
289
|
|
|
221
290
|
results = self._session.run(None, {"input_ids": input_ids, "attention_mask": attention_mask})
|
|
222
291
|
logits = results[0]
|
|
@@ -225,12 +294,12 @@ class OnnxClassifier:
|
|
|
225
294
|
t = self._temperature_t
|
|
226
295
|
pairs: list[tuple[float, float | None]] = []
|
|
227
296
|
if self._output_mode == "multi":
|
|
228
|
-
for i in range(
|
|
297
|
+
for i in range(batch_size):
|
|
229
298
|
main = _sigmoid(float(logits[i][0]) / t)
|
|
230
299
|
aux = _sigmoid(float(logits[i][1]) / t)
|
|
231
300
|
pairs.append((main, aux))
|
|
232
301
|
else:
|
|
233
|
-
for i in range(
|
|
302
|
+
for i in range(batch_size):
|
|
234
303
|
row = logits[i]
|
|
235
304
|
# ``row`` may be a scalar (shape ``[batch]``) or 1-vector.
|
|
236
305
|
main_logit = float(row[0]) if hasattr(row, "__len__") and len(row) > 0 else float(row)
|
|
@@ -258,9 +327,9 @@ class OnnxClassifier:
|
|
|
258
327
|
|
|
259
328
|
def count_tokens(self, text: str) -> int:
|
|
260
329
|
self._ensure_loaded()
|
|
261
|
-
|
|
262
|
-
#
|
|
263
|
-
return
|
|
330
|
+
# Non-truncating count, including special tokens ([CLS]/[SEP]) to match
|
|
331
|
+
# the TS countTokens; the inference tokenizer would cap this at max_length.
|
|
332
|
+
return len(self._count_tokenizer.encode(text).ids)
|
|
264
333
|
|
|
265
334
|
def get_max_length(self) -> int:
|
|
266
335
|
return self._max_length
|
|
@@ -17,7 +17,7 @@ from typing import Any
|
|
|
17
17
|
|
|
18
18
|
from ..types import MultiheadConfig, RiskLevel, Tier2Result
|
|
19
19
|
from ..utils.boundary import strip_boundary_patterns
|
|
20
|
-
from .onnx_classifier import OnnxClassifier, get_default_model_path
|
|
20
|
+
from .onnx_classifier import BatchTokenStats, OnnxClassifier, get_default_model_path
|
|
21
21
|
|
|
22
22
|
_logger = logging.getLogger(__name__)
|
|
23
23
|
|
|
@@ -343,14 +343,16 @@ class Tier2Classifier:
|
|
|
343
343
|
return {"chunks": [], "skipped": True, "skip_reason": "No classifiable sentences"}
|
|
344
344
|
return {"chunks": self._pack_sentences(sentences, max_content_tokens), "skipped": False}
|
|
345
345
|
|
|
346
|
-
def classify_chunks_batch(self, chunks: list[str]) -> list[float]:
|
|
346
|
+
def classify_chunks_batch(self, chunks: list[str], stats: BatchTokenStats | None = None) -> list[float]:
|
|
347
347
|
"""Single-head batch classify. Returns main-head scores only."""
|
|
348
348
|
if not chunks:
|
|
349
349
|
return []
|
|
350
350
|
self._onnx.warmup()
|
|
351
|
-
return self._onnx.classify_batch(chunks)
|
|
351
|
+
return self._onnx.classify_batch(chunks, stats)
|
|
352
352
|
|
|
353
|
-
def classify_chunks_batch_pair(
|
|
353
|
+
def classify_chunks_batch_pair(
|
|
354
|
+
self, chunks: list[str], stats: BatchTokenStats | None = None
|
|
355
|
+
) -> list[tuple[float, float | None]]:
|
|
354
356
|
"""Multi-head variant. Returns ``(main, aux)`` per chunk.
|
|
355
357
|
|
|
356
358
|
Aux is ``None`` per-row for single-head models. Callers in the
|
|
@@ -359,7 +361,7 @@ class Tier2Classifier:
|
|
|
359
361
|
if not chunks:
|
|
360
362
|
return []
|
|
361
363
|
self._onnx.warmup()
|
|
362
|
-
return self._onnx.classify_batch_pair(chunks)
|
|
364
|
+
return self._onnx.classify_batch_pair(chunks, stats)
|
|
363
365
|
|
|
364
366
|
# ------------------------------------------------------------------
|
|
365
367
|
# Helpers / introspection
|