@framers/agentos-ext-ml-classifiers 0.1.0 → 0.3.1
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.
- package/.github/workflows/ci.yml +20 -0
- package/.github/workflows/release.yml +37 -0
- package/.releaserc.json +9 -0
- package/LICENSE +96 -21
- package/README.md +72 -0
- package/dist/MLClassifierGuardrail.d.ts +88 -117
- package/dist/MLClassifierGuardrail.d.ts.map +1 -1
- package/dist/MLClassifierGuardrail.js +263 -264
- package/dist/MLClassifierGuardrail.js.map +1 -1
- package/dist/index.d.ts +16 -90
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +36 -309
- package/dist/index.js.map +1 -1
- package/dist/keyword-classifier.d.ts +26 -0
- package/dist/keyword-classifier.d.ts.map +1 -0
- package/dist/keyword-classifier.js +113 -0
- package/dist/keyword-classifier.js.map +1 -0
- package/dist/llm-classifier.d.ts +27 -0
- package/dist/llm-classifier.d.ts.map +1 -0
- package/dist/llm-classifier.js +129 -0
- package/dist/llm-classifier.js.map +1 -0
- package/dist/tools/ClassifyContentTool.d.ts +53 -80
- package/dist/tools/ClassifyContentTool.d.ts.map +1 -1
- package/dist/tools/ClassifyContentTool.js +52 -103
- package/dist/tools/ClassifyContentTool.js.map +1 -1
- package/dist/types.d.ts +77 -277
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +9 -55
- package/dist/types.js.map +1 -1
- package/package.json +10 -24
- package/scripts/fix-esm-imports.mjs +181 -0
- package/src/MLClassifierGuardrail.ts +306 -310
- package/src/index.ts +35 -339
- package/src/keyword-classifier.ts +130 -0
- package/src/llm-classifier.ts +163 -0
- package/src/tools/ClassifyContentTool.ts +75 -132
- package/src/types.ts +78 -325
- package/test/llm-tier.spec.ts +267 -0
- package/test/ml-classifiers.spec.ts +57 -0
- package/test/onnx-tier.spec.ts +255 -0
- package/test/tier-fallthrough.spec.ts +185 -0
- package/tsconfig.json +20 -0
- package/vitest.config.ts +35 -0
- package/dist/ClassifierOrchestrator.d.ts +0 -126
- package/dist/ClassifierOrchestrator.d.ts.map +0 -1
- package/dist/ClassifierOrchestrator.js +0 -239
- package/dist/ClassifierOrchestrator.js.map +0 -1
- package/dist/IContentClassifier.d.ts +0 -117
- package/dist/IContentClassifier.d.ts.map +0 -1
- package/dist/IContentClassifier.js +0 -22
- package/dist/IContentClassifier.js.map +0 -1
- package/dist/SlidingWindowBuffer.d.ts +0 -213
- package/dist/SlidingWindowBuffer.d.ts.map +0 -1
- package/dist/SlidingWindowBuffer.js +0 -246
- package/dist/SlidingWindowBuffer.js.map +0 -1
- package/dist/classifiers/InjectionClassifier.d.ts +0 -126
- package/dist/classifiers/InjectionClassifier.d.ts.map +0 -1
- package/dist/classifiers/InjectionClassifier.js +0 -210
- package/dist/classifiers/InjectionClassifier.js.map +0 -1
- package/dist/classifiers/JailbreakClassifier.d.ts +0 -124
- package/dist/classifiers/JailbreakClassifier.d.ts.map +0 -1
- package/dist/classifiers/JailbreakClassifier.js +0 -208
- package/dist/classifiers/JailbreakClassifier.js.map +0 -1
- package/dist/classifiers/ToxicityClassifier.d.ts +0 -125
- package/dist/classifiers/ToxicityClassifier.d.ts.map +0 -1
- package/dist/classifiers/ToxicityClassifier.js +0 -212
- package/dist/classifiers/ToxicityClassifier.js.map +0 -1
- package/dist/classifiers/WorkerClassifierProxy.d.ts +0 -158
- package/dist/classifiers/WorkerClassifierProxy.d.ts.map +0 -1
- package/dist/classifiers/WorkerClassifierProxy.js +0 -268
- package/dist/classifiers/WorkerClassifierProxy.js.map +0 -1
- package/dist/worker/classifier-worker.d.ts +0 -49
- package/dist/worker/classifier-worker.d.ts.map +0 -1
- package/dist/worker/classifier-worker.js +0 -180
- package/dist/worker/classifier-worker.js.map +0 -1
- package/src/ClassifierOrchestrator.ts +0 -290
- package/src/IContentClassifier.ts +0 -124
- package/src/SlidingWindowBuffer.ts +0 -384
- package/src/classifiers/InjectionClassifier.ts +0 -261
- package/src/classifiers/JailbreakClassifier.ts +0 -259
- package/src/classifiers/ToxicityClassifier.ts +0 -263
- package/src/classifiers/WorkerClassifierProxy.ts +0 -366
- package/src/worker/classifier-worker.ts +0 -267
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [master]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
build:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
steps:
|
|
12
|
+
- uses: actions/checkout@v4
|
|
13
|
+
- uses: pnpm/action-setup@v4
|
|
14
|
+
with:
|
|
15
|
+
version: 10
|
|
16
|
+
- uses: actions/setup-node@v4
|
|
17
|
+
with:
|
|
18
|
+
node-version: 20
|
|
19
|
+
- run: pnpm install --no-frozen-lockfile
|
|
20
|
+
- run: pnpm build
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
name: Release
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [master]
|
|
6
|
+
workflow_dispatch:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: write
|
|
10
|
+
issues: write
|
|
11
|
+
pull-requests: write
|
|
12
|
+
id-token: write
|
|
13
|
+
|
|
14
|
+
jobs:
|
|
15
|
+
release:
|
|
16
|
+
runs-on: ubuntu-latest
|
|
17
|
+
if: "!contains(github.event.head_commit.message, '[skip ci]')"
|
|
18
|
+
steps:
|
|
19
|
+
- uses: actions/checkout@v4
|
|
20
|
+
with:
|
|
21
|
+
fetch-depth: 0
|
|
22
|
+
persist-credentials: false
|
|
23
|
+
- uses: pnpm/action-setup@v4
|
|
24
|
+
with:
|
|
25
|
+
version: 10
|
|
26
|
+
- uses: actions/setup-node@v4
|
|
27
|
+
with:
|
|
28
|
+
node-version: '20'
|
|
29
|
+
registry-url: 'https://registry.npmjs.org'
|
|
30
|
+
- run: pnpm install --no-frozen-lockfile
|
|
31
|
+
- run: pnpm build
|
|
32
|
+
- name: Semantic Release
|
|
33
|
+
env:
|
|
34
|
+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
35
|
+
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
|
36
|
+
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
|
37
|
+
run: npx semantic-release
|
package/.releaserc.json
ADDED
package/LICENSE
CHANGED
|
@@ -1,23 +1,98 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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, and distribution as defined by Sections 1 through 9 of this document.
|
|
10
|
+
|
|
11
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
12
|
+
|
|
13
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
14
|
+
|
|
15
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
16
|
+
|
|
17
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
18
|
+
|
|
19
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
20
|
+
|
|
21
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
22
|
+
|
|
23
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
24
|
+
|
|
25
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
26
|
+
|
|
27
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
28
|
+
|
|
29
|
+
2. Grant of Copyright License.
|
|
30
|
+
|
|
31
|
+
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
32
|
+
|
|
33
|
+
3. Grant of Patent License.
|
|
34
|
+
|
|
35
|
+
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
36
|
+
|
|
37
|
+
4. Redistribution.
|
|
38
|
+
|
|
39
|
+
You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
40
|
+
|
|
41
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
42
|
+
|
|
43
|
+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
44
|
+
|
|
45
|
+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
46
|
+
|
|
47
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
|
48
|
+
|
|
49
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
50
|
+
|
|
51
|
+
5. Submission of Contributions.
|
|
52
|
+
|
|
53
|
+
Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
54
|
+
|
|
55
|
+
6. Trademarks.
|
|
56
|
+
|
|
57
|
+
This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
58
|
+
|
|
59
|
+
7. Disclaimer of Warranty.
|
|
60
|
+
|
|
61
|
+
Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
62
|
+
|
|
63
|
+
8. Limitation of Liability.
|
|
64
|
+
|
|
65
|
+
In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
66
|
+
|
|
67
|
+
9. Accepting Warranty or Additional Liability.
|
|
68
|
+
|
|
69
|
+
While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
70
|
+
|
|
71
|
+
END OF TERMS AND CONDITIONS
|
|
72
|
+
|
|
73
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
74
|
+
|
|
75
|
+
To apply the Apache License to your work, attach the following
|
|
76
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
77
|
+
replaced with your own identifying information. (Don't include
|
|
78
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
79
|
+
comment syntax for the file format. We also recommend that a
|
|
80
|
+
file or class name and description of purpose be included on the
|
|
81
|
+
same "printed page" as the copyright notice for easier
|
|
82
|
+
identification within third-party archives.
|
|
83
|
+
|
|
84
|
+
Copyright (c) 2025 Framers
|
|
85
|
+
|
|
86
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
87
|
+
you may not use this file except in compliance with the License.
|
|
88
|
+
You may obtain a copy of the License at
|
|
89
|
+
|
|
90
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
91
|
+
|
|
92
|
+
Unless required by applicable law or agreed to in writing, software
|
|
93
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
94
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
95
|
+
See the License for the specific language governing permissions and
|
|
96
|
+
limitations under the License.
|
|
22
97
|
|
|
23
98
|
|
package/README.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# @framers/agentos-ext-ml-classifiers
|
|
2
|
+
|
|
3
|
+
ML-based content classifiers for [`@framers/agentos`](https://github.com/framersai/agentos): toxicity, prompt-injection, and NSFW detection via local ONNX models with optional LLM fallback for low-confidence cases.
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
Runs incoming user messages and agent outputs through a chain of small classifiers. Each classifier returns a score; configurable thresholds gate downstream behavior. Local ONNX inference is fast and offline-friendly; the LLM fallback handles ambiguous cases when confidence is low.
|
|
8
|
+
|
|
9
|
+
Built-in classifiers:
|
|
10
|
+
|
|
11
|
+
- Toxicity (insults, threats, harassment)
|
|
12
|
+
- Prompt injection (jailbreak attempts, instruction-override patterns)
|
|
13
|
+
- NSFW content
|
|
14
|
+
- Keyword-based prefilter (zero-cost coarse triage)
|
|
15
|
+
- LLM-as-judge fallback (configurable model)
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install @framers/agentos-ext-ml-classifiers
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Peer dependency: [`@framers/agentos`](https://github.com/framersai/agentos).
|
|
24
|
+
|
|
25
|
+
## Quickstart
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { AgentOS } from '@framers/agentos';
|
|
29
|
+
import { createMLClassifierGuardrail } from '@framers/agentos-ext-ml-classifiers';
|
|
30
|
+
|
|
31
|
+
const agentos = new AgentOS();
|
|
32
|
+
await agentos.initialize({
|
|
33
|
+
extensionManifest: {
|
|
34
|
+
packs: [
|
|
35
|
+
{
|
|
36
|
+
factory: () =>
|
|
37
|
+
createMLClassifierGuardrail({
|
|
38
|
+
classifiers: ['toxicity', 'prompt-injection', 'nsfw'],
|
|
39
|
+
llmFallback: { enabled: true, threshold: 0.6 },
|
|
40
|
+
}),
|
|
41
|
+
enabled: true,
|
|
42
|
+
},
|
|
43
|
+
],
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Public API
|
|
49
|
+
|
|
50
|
+
- `createMLClassifierGuardrail(options?)` — factory returning an `ExtensionPack`
|
|
51
|
+
- `createExtensionPack(context)` — auto-discoverable factory used by AgentOS extension auto-pickup
|
|
52
|
+
- `createMLClassifierPack` — alias for `createMLClassifierGuardrail`
|
|
53
|
+
|
|
54
|
+
See [`src/types.ts`](src/types.ts) for `MLClassifierOptions`.
|
|
55
|
+
|
|
56
|
+
## Examples
|
|
57
|
+
|
|
58
|
+
- `test/` — fixtures and threshold-tuning tests
|
|
59
|
+
|
|
60
|
+
## Lazy loading and optional install
|
|
61
|
+
|
|
62
|
+
This package is an optional dependency of `@framers/agentos-extensions-registry`. The registry ships catalog metadata; `createCuratedManifest()` calls `import.meta.resolve()` per entry and silently skips anything not installed. `npm install @framers/agentos-ext-ml-classifiers` is the gate.
|
|
63
|
+
|
|
64
|
+
The ONNX BERT classifiers (toxicity, prompt-injection, NSFW) do not load at activation. The pack registers a factory under the `ml:classifier-orchestrator` key in `SharedServiceRegistry`, and each model file enters the module graph only on the first classification that needs it. The keyword prefilter runs first at zero cost; the LLM fallback uses a separate factory gated by an optional `requiredSecrets` entry, so the descriptor is skipped if no provider key is configured.
|
|
65
|
+
|
|
66
|
+
The guardrail registers with `config.evaluateStreamingChunks = true` and runs in Phase 2 of the two-phase dispatcher (parallel classifiers). Worst-action aggregation (`BLOCK > FLAG > ALLOW`) resolves conflicts when multiple classifiers fire on the same chunk.
|
|
67
|
+
|
|
68
|
+
For the full DI model and end-to-end walkthrough, see [How extensions stay optional and lazy](https://docs.agentos.sh/extensions#how-extensions-stay-optional-and-lazy) and the [auto-loading guide](https://docs.agentos.sh/extensions/auto-loading).
|
|
69
|
+
|
|
70
|
+
## License
|
|
71
|
+
|
|
72
|
+
Apache 2.0 — see the repo root [LICENSE](../../LICENSE).
|
|
@@ -1,163 +1,134 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @
|
|
2
|
+
* @file MLClassifierGuardrail.ts
|
|
3
|
+
* @description IGuardrailService implementation that classifies text for toxicity,
|
|
4
|
+
* prompt injection, NSFW content, and threats using a three-tier strategy:
|
|
3
5
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
6
|
+
* 1. **ONNX inference** — attempts to load `@huggingface/transformers` at runtime
|
|
7
|
+
* and run a lightweight ONNX classification model.
|
|
8
|
+
* 2. **LLM-as-judge** — falls back to an LLM invoker callback that prompts a
|
|
9
|
+
* language model for structured JSON safety classification.
|
|
10
|
+
* 3. **Keyword matching** — last-resort regex/keyword-based detection when neither
|
|
11
|
+
* ONNX nor LLM are available.
|
|
8
12
|
*
|
|
9
|
-
*
|
|
13
|
+
* The guardrail is configured as Phase 2 (parallel, non-sanitizing) so it runs
|
|
14
|
+
* alongside other read-only guardrails without blocking the streaming pipeline.
|
|
10
15
|
*
|
|
11
|
-
*
|
|
12
|
-
* |---------------|----------------------------------------------------------------|
|
|
13
|
-
* | `blocking` | Every chunk that fills the sliding window is classified |
|
|
14
|
-
* | | **synchronously** — the stream waits for the result. |
|
|
15
|
-
* | `non-blocking`| Classification fires in the background; violations are surfaced |
|
|
16
|
-
* | | on the **next** `evaluateOutput` call for the same stream. |
|
|
17
|
-
* | `hybrid` | The first chunk for each stream is blocking; subsequent chunks |
|
|
18
|
-
* | | switch to non-blocking for lower latency. |
|
|
16
|
+
* ### Action thresholds
|
|
19
17
|
*
|
|
20
|
-
*
|
|
18
|
+
* - **FLAG** when any category confidence exceeds `flagThreshold` (default 0.5).
|
|
19
|
+
* - **BLOCK** when any category confidence exceeds `blockThreshold` (default 0.8).
|
|
21
20
|
*
|
|
22
|
-
* @module
|
|
21
|
+
* @module ml-classifiers/MLClassifierGuardrail
|
|
23
22
|
*/
|
|
24
|
-
import type {
|
|
25
|
-
import type {
|
|
26
|
-
import type { MLClassifierPackOptions } from './types';
|
|
27
|
-
import type { IContentClassifier } from './IContentClassifier';
|
|
23
|
+
import type { IGuardrailService, GuardrailConfig, GuardrailInputPayload, GuardrailOutputPayload, GuardrailEvaluationResult } from '@framers/agentos';
|
|
24
|
+
import type { MLClassifierOptions, ClassifierResult } from './types';
|
|
28
25
|
/**
|
|
29
|
-
*
|
|
30
|
-
*
|
|
26
|
+
* AgentOS guardrail that classifies text for safety using ML models, LLM
|
|
27
|
+
* inference, or keyword fallback.
|
|
31
28
|
*
|
|
32
29
|
* @implements {IGuardrailService}
|
|
33
|
-
*
|
|
34
|
-
* @example
|
|
35
|
-
* ```typescript
|
|
36
|
-
* const guardrail = new MLClassifierGuardrail(serviceRegistry, {
|
|
37
|
-
* classifiers: ['toxicity'],
|
|
38
|
-
* streamingMode: true,
|
|
39
|
-
* chunkSize: 150,
|
|
40
|
-
* guardrailScope: 'both',
|
|
41
|
-
* });
|
|
42
|
-
*
|
|
43
|
-
* // Input evaluation — runs classifier on the full user message.
|
|
44
|
-
* const inputResult = await guardrail.evaluateInput({ context, input });
|
|
45
|
-
*
|
|
46
|
-
* // Output evaluation — accumulates tokens, classifies at window boundary.
|
|
47
|
-
* const outputResult = await guardrail.evaluateOutput({ context, chunk });
|
|
48
|
-
* ```
|
|
49
30
|
*/
|
|
50
31
|
export declare class MLClassifierGuardrail implements IGuardrailService {
|
|
51
32
|
/**
|
|
52
|
-
* Guardrail configuration
|
|
33
|
+
* Guardrail configuration.
|
|
53
34
|
*
|
|
54
|
-
* `
|
|
55
|
-
*
|
|
35
|
+
* - `canSanitize: false` — this guardrail does not modify content; it only
|
|
36
|
+
* BLOCKs or FLAGs. This places it in Phase 2 (parallel) of the guardrail
|
|
37
|
+
* dispatcher for better performance.
|
|
38
|
+
* - `evaluateStreamingChunks: false` — only evaluates complete messages, not
|
|
39
|
+
* individual streaming deltas. ML classification on partial text produces
|
|
40
|
+
* unreliable results.
|
|
56
41
|
*/
|
|
57
42
|
readonly config: GuardrailConfig;
|
|
58
|
-
/**
|
|
59
|
-
private readonly
|
|
60
|
-
/**
|
|
61
|
-
private readonly
|
|
62
|
-
/**
|
|
63
|
-
private readonly
|
|
64
|
-
/**
|
|
65
|
-
private readonly
|
|
43
|
+
/** Categories to evaluate. */
|
|
44
|
+
private readonly categories;
|
|
45
|
+
/** Per-category flag thresholds. */
|
|
46
|
+
private readonly flagThresholds;
|
|
47
|
+
/** Per-category block thresholds. */
|
|
48
|
+
private readonly blockThresholds;
|
|
49
|
+
/** Optional LLM invoker callback for tier-2 classification. */
|
|
50
|
+
private readonly llmInvoker;
|
|
66
51
|
/**
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
52
|
+
* Cached reference to the `@huggingface/transformers` pipeline function.
|
|
53
|
+
* `null` means we already tried and failed to load the module.
|
|
54
|
+
* `undefined` means we have not tried yet.
|
|
70
55
|
*/
|
|
71
|
-
private
|
|
56
|
+
private onnxPipeline;
|
|
72
57
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
58
|
+
* Create a new MLClassifierGuardrail.
|
|
59
|
+
*
|
|
60
|
+
* @param options - Pack-level configuration. All properties have sensible
|
|
61
|
+
* defaults for zero-config operation.
|
|
76
62
|
*/
|
|
77
|
-
|
|
63
|
+
constructor(options?: MLClassifierOptions);
|
|
78
64
|
/**
|
|
79
|
-
*
|
|
65
|
+
* Evaluate user input for safety before orchestration begins.
|
|
80
66
|
*
|
|
81
|
-
* @param
|
|
82
|
-
*
|
|
83
|
-
* @param options - Pack-level options controlling classifier selection,
|
|
84
|
-
* thresholds, sliding window size, and streaming mode.
|
|
85
|
-
* @param classifiers - Pre-built classifier instances. When provided,
|
|
86
|
-
* these are used directly instead of constructing
|
|
87
|
-
* classifiers from `options.classifiers`.
|
|
67
|
+
* @param payload - Input evaluation payload containing the user's message.
|
|
68
|
+
* @returns Guardrail result or `null` if no action is required.
|
|
88
69
|
*/
|
|
89
|
-
|
|
70
|
+
evaluateInput(payload: GuardrailInputPayload): Promise<GuardrailEvaluationResult | null>;
|
|
90
71
|
/**
|
|
91
|
-
* Evaluate
|
|
92
|
-
*
|
|
93
|
-
* Runs the full text through all registered classifiers and returns a
|
|
94
|
-
* {@link GuardrailEvaluationResult} when a violation is detected, or
|
|
95
|
-
* `null` when the content is clean.
|
|
72
|
+
* Evaluate agent output for safety. Only processes FINAL_RESPONSE chunks
|
|
73
|
+
* since `evaluateStreamingChunks` is disabled.
|
|
96
74
|
*
|
|
97
|
-
*
|
|
75
|
+
* @param payload - Output evaluation payload from the AgentOS dispatcher.
|
|
76
|
+
* @returns Guardrail result or `null` if no action is required.
|
|
77
|
+
*/
|
|
78
|
+
evaluateOutput(payload: GuardrailOutputPayload): Promise<GuardrailEvaluationResult | null>;
|
|
79
|
+
/**
|
|
80
|
+
* Classify a text string using the three-tier strategy: ONNX -> LLM -> keyword.
|
|
98
81
|
*
|
|
99
|
-
* @param
|
|
100
|
-
* @returns
|
|
82
|
+
* @param text - The text to classify.
|
|
83
|
+
* @returns Classification result with per-category scores.
|
|
101
84
|
*/
|
|
102
|
-
|
|
85
|
+
classify(text: string): Promise<ClassifierResult>;
|
|
103
86
|
/**
|
|
104
|
-
*
|
|
105
|
-
*
|
|
87
|
+
* Attempt to load `@huggingface/transformers` and run ONNX-based text
|
|
88
|
+
* classification. Returns `null` if the module is unavailable or inference
|
|
89
|
+
* fails.
|
|
106
90
|
*
|
|
107
|
-
* The
|
|
108
|
-
*
|
|
109
|
-
* evaluation strategy depends on the configured streaming mode.
|
|
91
|
+
* The module load is attempted only once; subsequent calls use the cached
|
|
92
|
+
* result (either a working pipeline or `null`).
|
|
110
93
|
*
|
|
111
|
-
*
|
|
94
|
+
* @param text - Text to classify.
|
|
95
|
+
* @returns Classification result or `null`.
|
|
112
96
|
*
|
|
113
|
-
* @
|
|
114
|
-
* @returns Evaluation result or `null` if no action is needed yet.
|
|
97
|
+
* @internal
|
|
115
98
|
*/
|
|
116
|
-
|
|
99
|
+
private tryOnnxClassification;
|
|
117
100
|
/**
|
|
118
|
-
*
|
|
119
|
-
* ready, await the classifier result before returning.
|
|
101
|
+
* Map raw ONNX text-classification output labels to our standard categories.
|
|
120
102
|
*
|
|
121
|
-
*
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
*
|
|
128
|
-
* ready, fire classification in the background and store the promise.
|
|
129
|
-
* On the **next** `evaluateOutput` call for the same stream, check the
|
|
130
|
-
* pending promise — if it resolved with a violation, return that result.
|
|
103
|
+
* ONNX models (e.g. toxic-bert) produce labels like `"toxic"`, `"obscene"`,
|
|
104
|
+
* `"threat"`, `"insult"`, `"identity_hate"`, etc. We map these to our four
|
|
105
|
+
* categories, taking the max score when multiple ONNX labels map to the same
|
|
106
|
+
* category.
|
|
107
|
+
*
|
|
108
|
+
* @param raw - Raw ONNX pipeline output.
|
|
109
|
+
* @returns Per-category scores.
|
|
131
110
|
*
|
|
132
|
-
* @
|
|
133
|
-
* @param textDelta - New text fragment from the current chunk.
|
|
134
|
-
* @returns A previously resolved violation result, or `null`.
|
|
111
|
+
* @internal
|
|
135
112
|
*/
|
|
136
|
-
private
|
|
113
|
+
private mapOnnxScores;
|
|
137
114
|
/**
|
|
138
|
-
*
|
|
139
|
-
* blocking mode; subsequent chunks use non-blocking.
|
|
115
|
+
* Classify text using the LLM-as-judge fallback.
|
|
140
116
|
*
|
|
141
|
-
*
|
|
142
|
-
*
|
|
143
|
-
* remainder of the stream.
|
|
117
|
+
* @param text - Text to classify.
|
|
118
|
+
* @returns Classification result or `null` if the LLM call fails.
|
|
144
119
|
*
|
|
145
|
-
* @
|
|
146
|
-
* @param textDelta - New text fragment from the current chunk.
|
|
147
|
-
* @returns Evaluation result or `null`.
|
|
120
|
+
* @internal
|
|
148
121
|
*/
|
|
149
|
-
private
|
|
122
|
+
private tryLlmClassification;
|
|
150
123
|
/**
|
|
151
|
-
* Convert a {@link
|
|
152
|
-
*
|
|
124
|
+
* Convert a {@link ClassifierResult} into a {@link GuardrailEvaluationResult},
|
|
125
|
+
* or return `null` when no thresholds are exceeded.
|
|
153
126
|
*
|
|
154
|
-
*
|
|
155
|
-
*
|
|
156
|
-
* metadata for audit/logging.
|
|
127
|
+
* @param result - Classification result from any tier.
|
|
128
|
+
* @returns Guardrail evaluation result or `null`.
|
|
157
129
|
*
|
|
158
|
-
* @
|
|
159
|
-
* @returns A guardrail result or `null` for clean content.
|
|
130
|
+
* @internal
|
|
160
131
|
*/
|
|
161
|
-
private
|
|
132
|
+
private buildResult;
|
|
162
133
|
}
|
|
163
134
|
//# sourceMappingURL=MLClassifierGuardrail.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MLClassifierGuardrail.d.ts","sourceRoot":"","sources":["../src/MLClassifierGuardrail.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"MLClassifierGuardrail.d.ts","sourceRoot":"","sources":["../src/MLClassifierGuardrail.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,KAAK,EACV,iBAAiB,EACjB,eAAe,EACf,qBAAqB,EACrB,sBAAsB,EACtB,yBAAyB,EAE1B,MAAM,kBAAkB,CAAC;AAG1B,OAAO,KAAK,EACV,mBAAmB,EAEnB,gBAAgB,EAEjB,MAAM,SAAS,CAAC;AA8BjB;;;;;GAKG;AACH,qBAAa,qBAAsB,YAAW,iBAAiB;IAK7D;;;;;;;;;OASG;IACH,QAAQ,CAAC,MAAM,EAAE,eAAe,CAG9B;IAMF,8BAA8B;IAC9B,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAuB;IAElD,oCAAoC;IACpC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAqC;IAEpE,qCAAqC;IACrC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAqC;IAErE,+DAA+D;IAC/D,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAoC;IAE/D;;;;OAIG;IACH,OAAO,CAAC,YAAY,CAAgE;IAMpF;;;;;OAKG;gBACS,OAAO,CAAC,EAAE,mBAAmB;IAuBzC;;;;;OAKG;IACG,aAAa,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IAY9F;;;;;;OAMG;IACG,cAAc,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,yBAAyB,GAAG,IAAI,CAAC;IAoBhG;;;;;OAKG;IACG,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAwBvD;;;;;;;;;;;;OAYG;YACW,qBAAqB;IA+CnC;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,aAAa;IAsCrB;;;;;;;OAOG;YACW,oBAAoB;IAuBlC;;;;;;;;OAQG;IACH,OAAO,CAAC,WAAW;CAsCpB"}
|