@framers/agentos-ext-ml-classifiers 0.1.0 → 0.2.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/CHANGELOG.md +18 -0
- package/dist/MLClassifierGuardrail.d.ts +88 -117
- package/dist/MLClassifierGuardrail.d.ts.map +1 -1
- package/dist/MLClassifierGuardrail.js +255 -264
- package/dist/MLClassifierGuardrail.js.map +1 -1
- package/dist/classifiers/InjectionClassifier.d.ts +1 -1
- package/dist/classifiers/InjectionClassifier.d.ts.map +1 -1
- package/dist/classifiers/JailbreakClassifier.d.ts +1 -1
- package/dist/classifiers/JailbreakClassifier.d.ts.map +1 -1
- package/dist/classifiers/ToxicityClassifier.d.ts +1 -1
- package/dist/classifiers/ToxicityClassifier.d.ts.map +1 -1
- package/dist/classifiers/WorkerClassifierProxy.d.ts +1 -1
- package/dist/classifiers/WorkerClassifierProxy.d.ts.map +1 -1
- package/dist/index.d.ts +16 -90
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +33 -306
- 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 -16
- package/src/MLClassifierGuardrail.ts +279 -316
- 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/ClassifierOrchestrator.spec.ts +365 -0
- package/test/ClassifyContentTool.spec.ts +226 -0
- package/test/InjectionClassifier.spec.ts +263 -0
- package/test/JailbreakClassifier.spec.ts +295 -0
- package/test/MLClassifierGuardrail.spec.ts +486 -0
- package/test/SlidingWindowBuffer.spec.ts +391 -0
- package/test/ToxicityClassifier.spec.ts +268 -0
- package/test/WorkerClassifierProxy.spec.ts +303 -0
- package/test/index.spec.ts +431 -0
- package/tsconfig.json +20 -0
- package/vitest.config.ts +24 -0
|
@@ -1,419 +1,382 @@
|
|
|
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
23
|
|
|
25
24
|
import type {
|
|
25
|
+
IGuardrailService,
|
|
26
26
|
GuardrailConfig,
|
|
27
|
-
GuardrailEvaluationResult,
|
|
28
27
|
GuardrailInputPayload,
|
|
29
28
|
GuardrailOutputPayload,
|
|
30
|
-
|
|
29
|
+
GuardrailEvaluationResult,
|
|
31
30
|
} from '@framers/agentos';
|
|
32
31
|
import { GuardrailAction } from '@framers/agentos';
|
|
33
32
|
import { AgentOSResponseChunkType } from '@framers/agentos';
|
|
34
|
-
import type {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
// ---------------------------------------------------------------------------
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* The evaluation strategy used for output (streaming) chunks.
|
|
47
|
-
*
|
|
48
|
-
* - `blocking` — await classification on every filled window.
|
|
49
|
-
* - `non-blocking` — fire classification in the background; surface result later.
|
|
50
|
-
* - `hybrid` — first chunk per stream is blocking, rest non-blocking.
|
|
51
|
-
*/
|
|
52
|
-
type StreamingMode = 'blocking' | 'non-blocking' | 'hybrid';
|
|
33
|
+
import type {
|
|
34
|
+
MLClassifierOptions,
|
|
35
|
+
ClassifierCategory,
|
|
36
|
+
ClassifierResult,
|
|
37
|
+
CategoryScore,
|
|
38
|
+
} from './types';
|
|
39
|
+
import { ALL_CATEGORIES } from './types';
|
|
40
|
+
import { classifyByKeywords } from './keyword-classifier';
|
|
41
|
+
import { classifyByLlm } from './llm-classifier';
|
|
53
42
|
|
|
54
43
|
// ---------------------------------------------------------------------------
|
|
55
44
|
// MLClassifierGuardrail
|
|
56
45
|
// ---------------------------------------------------------------------------
|
|
57
46
|
|
|
58
47
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
48
|
+
* AgentOS guardrail that classifies text for safety using ML models, LLM
|
|
49
|
+
* inference, or keyword fallback.
|
|
61
50
|
*
|
|
62
51
|
* @implements {IGuardrailService}
|
|
63
|
-
*
|
|
64
|
-
* @example
|
|
65
|
-
* ```typescript
|
|
66
|
-
* const guardrail = new MLClassifierGuardrail(serviceRegistry, {
|
|
67
|
-
* classifiers: ['toxicity'],
|
|
68
|
-
* streamingMode: true,
|
|
69
|
-
* chunkSize: 150,
|
|
70
|
-
* guardrailScope: 'both',
|
|
71
|
-
* });
|
|
72
|
-
*
|
|
73
|
-
* // Input evaluation — runs classifier on the full user message.
|
|
74
|
-
* const inputResult = await guardrail.evaluateInput({ context, input });
|
|
75
|
-
*
|
|
76
|
-
* // Output evaluation — accumulates tokens, classifies at window boundary.
|
|
77
|
-
* const outputResult = await guardrail.evaluateOutput({ context, chunk });
|
|
78
|
-
* ```
|
|
79
52
|
*/
|
|
80
53
|
export class MLClassifierGuardrail implements IGuardrailService {
|
|
81
|
-
//
|
|
82
|
-
// IGuardrailService
|
|
83
|
-
//
|
|
54
|
+
// -----------------------------------------------------------------------
|
|
55
|
+
// IGuardrailService.config
|
|
56
|
+
// -----------------------------------------------------------------------
|
|
84
57
|
|
|
85
58
|
/**
|
|
86
|
-
* Guardrail configuration
|
|
59
|
+
* Guardrail configuration.
|
|
87
60
|
*
|
|
88
|
-
* `
|
|
89
|
-
*
|
|
61
|
+
* - `canSanitize: false` — this guardrail does not modify content; it only
|
|
62
|
+
* BLOCKs or FLAGs. This places it in Phase 2 (parallel) of the guardrail
|
|
63
|
+
* dispatcher for better performance.
|
|
64
|
+
* - `evaluateStreamingChunks: false` — only evaluates complete messages, not
|
|
65
|
+
* individual streaming deltas. ML classification on partial text produces
|
|
66
|
+
* unreliable results.
|
|
90
67
|
*/
|
|
91
|
-
readonly config: GuardrailConfig
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
// -------------------------------------------------------------------------
|
|
68
|
+
readonly config: GuardrailConfig = {
|
|
69
|
+
canSanitize: false,
|
|
70
|
+
evaluateStreamingChunks: false,
|
|
71
|
+
};
|
|
96
72
|
|
|
97
|
-
|
|
98
|
-
|
|
73
|
+
// -----------------------------------------------------------------------
|
|
74
|
+
// Private state
|
|
75
|
+
// -----------------------------------------------------------------------
|
|
99
76
|
|
|
100
|
-
/**
|
|
101
|
-
private readonly
|
|
77
|
+
/** Categories to evaluate. */
|
|
78
|
+
private readonly categories: ClassifierCategory[];
|
|
102
79
|
|
|
103
|
-
/**
|
|
104
|
-
private readonly
|
|
80
|
+
/** Per-category flag thresholds. */
|
|
81
|
+
private readonly flagThresholds: Record<ClassifierCategory, number>;
|
|
105
82
|
|
|
106
|
-
/**
|
|
107
|
-
private readonly
|
|
83
|
+
/** Per-category block thresholds. */
|
|
84
|
+
private readonly blockThresholds: Record<ClassifierCategory, number>;
|
|
108
85
|
|
|
109
|
-
/**
|
|
110
|
-
|
|
111
|
-
* Used in `non-blocking` and `hybrid` modes to defer result checking
|
|
112
|
-
* to the next `evaluateOutput` call.
|
|
113
|
-
*/
|
|
114
|
-
private readonly pendingResults: Map<string, Promise<ChunkEvaluation>> = new Map();
|
|
86
|
+
/** Optional LLM invoker callback for tier-2 classification. */
|
|
87
|
+
private readonly llmInvoker: MLClassifierOptions['llmInvoker'];
|
|
115
88
|
|
|
116
89
|
/**
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
90
|
+
* Cached reference to the `@huggingface/transformers` pipeline function.
|
|
91
|
+
* `null` means we already tried and failed to load the module.
|
|
92
|
+
* `undefined` means we have not tried yet.
|
|
120
93
|
*/
|
|
121
|
-
private
|
|
94
|
+
private onnxPipeline: any | null | undefined = undefined;
|
|
122
95
|
|
|
123
|
-
//
|
|
96
|
+
// -----------------------------------------------------------------------
|
|
124
97
|
// Constructor
|
|
125
|
-
//
|
|
98
|
+
// -----------------------------------------------------------------------
|
|
126
99
|
|
|
127
100
|
/**
|
|
128
|
-
* Create a new
|
|
101
|
+
* Create a new MLClassifierGuardrail.
|
|
129
102
|
*
|
|
130
|
-
* @param
|
|
131
|
-
*
|
|
132
|
-
* @param options - Pack-level options controlling classifier selection,
|
|
133
|
-
* thresholds, sliding window size, and streaming mode.
|
|
134
|
-
* @param classifiers - Pre-built classifier instances. When provided,
|
|
135
|
-
* these are used directly instead of constructing
|
|
136
|
-
* classifiers from `options.classifiers`.
|
|
103
|
+
* @param options - Pack-level configuration. All properties have sensible
|
|
104
|
+
* defaults for zero-config operation.
|
|
137
105
|
*/
|
|
138
|
-
constructor(
|
|
139
|
-
|
|
140
|
-
options: MLClassifierPackOptions,
|
|
141
|
-
classifiers: IContentClassifier[] = [],
|
|
142
|
-
) {
|
|
143
|
-
// Resolve thresholds: merge caller overrides on top of defaults.
|
|
144
|
-
const thresholds = {
|
|
145
|
-
...DEFAULT_THRESHOLDS,
|
|
146
|
-
...options.thresholds,
|
|
147
|
-
};
|
|
106
|
+
constructor(options?: MLClassifierOptions) {
|
|
107
|
+
const opts = options ?? {};
|
|
148
108
|
|
|
149
|
-
|
|
150
|
-
this.
|
|
151
|
-
|
|
152
|
-
//
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
// is 'blocking'; callers can override via the `streamingMode` option
|
|
164
|
-
// (which we reinterpret as a boolean gate here — advanced callers pass
|
|
165
|
-
// a StreamingMode string via `options` when they need finer control).
|
|
166
|
-
this.streamingMode = options.streamingMode ? 'blocking' : 'blocking';
|
|
167
|
-
|
|
168
|
-
// Expose guardrail config to the pipeline.
|
|
169
|
-
this.config = {
|
|
170
|
-
evaluateStreamingChunks: true,
|
|
171
|
-
maxStreamingEvaluations: options.maxEvaluations ?? 100,
|
|
172
|
-
};
|
|
109
|
+
this.categories = opts.categories ?? [...ALL_CATEGORIES];
|
|
110
|
+
this.llmInvoker = opts.llmInvoker;
|
|
111
|
+
|
|
112
|
+
// Resolve per-category thresholds.
|
|
113
|
+
const globalFlag = opts.flagThreshold ?? 0.5;
|
|
114
|
+
const globalBlock = opts.blockThreshold ?? 0.8;
|
|
115
|
+
|
|
116
|
+
this.flagThresholds = {} as Record<ClassifierCategory, number>;
|
|
117
|
+
this.blockThresholds = {} as Record<ClassifierCategory, number>;
|
|
118
|
+
|
|
119
|
+
for (const cat of ALL_CATEGORIES) {
|
|
120
|
+
this.flagThresholds[cat] = opts.thresholds?.[cat]?.flag ?? globalFlag;
|
|
121
|
+
this.blockThresholds[cat] = opts.thresholds?.[cat]?.block ?? globalBlock;
|
|
122
|
+
}
|
|
173
123
|
}
|
|
174
124
|
|
|
175
|
-
//
|
|
176
|
-
// evaluateInput
|
|
177
|
-
//
|
|
125
|
+
// -----------------------------------------------------------------------
|
|
126
|
+
// IGuardrailService — evaluateInput
|
|
127
|
+
// -----------------------------------------------------------------------
|
|
178
128
|
|
|
179
129
|
/**
|
|
180
|
-
* Evaluate
|
|
181
|
-
*
|
|
182
|
-
* Runs the full text through all registered classifiers and returns a
|
|
183
|
-
* {@link GuardrailEvaluationResult} when a violation is detected, or
|
|
184
|
-
* `null` when the content is clean.
|
|
185
|
-
*
|
|
186
|
-
* Skipped entirely when `scope === 'output'`.
|
|
130
|
+
* Evaluate user input for safety before orchestration begins.
|
|
187
131
|
*
|
|
188
|
-
* @param payload -
|
|
189
|
-
* @returns
|
|
132
|
+
* @param payload - Input evaluation payload containing the user's message.
|
|
133
|
+
* @returns Guardrail result or `null` if no action is required.
|
|
190
134
|
*/
|
|
191
135
|
async evaluateInput(payload: GuardrailInputPayload): Promise<GuardrailEvaluationResult | null> {
|
|
192
|
-
// Skip input evaluation when scope is output-only.
|
|
193
|
-
if (this.scope === 'output') {
|
|
194
|
-
return null;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
// Extract the text from the input. If there is no text, nothing to classify.
|
|
198
136
|
const text = payload.input.textInput;
|
|
199
|
-
if (!text)
|
|
200
|
-
return null;
|
|
201
|
-
}
|
|
137
|
+
if (!text || text.length === 0) return null;
|
|
202
138
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
// Map the evaluation to a guardrail result (null for ALLOW).
|
|
207
|
-
return this.evaluationToResult(evaluation);
|
|
139
|
+
const result = await this.classify(text);
|
|
140
|
+
return this.buildResult(result);
|
|
208
141
|
}
|
|
209
142
|
|
|
210
|
-
//
|
|
211
|
-
// evaluateOutput
|
|
212
|
-
//
|
|
143
|
+
// -----------------------------------------------------------------------
|
|
144
|
+
// IGuardrailService — evaluateOutput
|
|
145
|
+
// -----------------------------------------------------------------------
|
|
213
146
|
|
|
214
147
|
/**
|
|
215
|
-
* Evaluate
|
|
216
|
-
*
|
|
217
|
-
*
|
|
218
|
-
* The method accumulates text tokens in the sliding window buffer and
|
|
219
|
-
* triggers classifier evaluation when a full window is available. The
|
|
220
|
-
* evaluation strategy depends on the configured streaming mode.
|
|
221
|
-
*
|
|
222
|
-
* Skipped entirely when `scope === 'input'`.
|
|
148
|
+
* Evaluate agent output for safety. Only processes FINAL_RESPONSE chunks
|
|
149
|
+
* since `evaluateStreamingChunks` is disabled.
|
|
223
150
|
*
|
|
224
|
-
* @param payload -
|
|
225
|
-
* @returns
|
|
151
|
+
* @param payload - Output evaluation payload from the AgentOS dispatcher.
|
|
152
|
+
* @returns Guardrail result or `null` if no action is required.
|
|
226
153
|
*/
|
|
227
154
|
async evaluateOutput(payload: GuardrailOutputPayload): Promise<GuardrailEvaluationResult | null> {
|
|
228
|
-
|
|
229
|
-
if (this.scope === 'input') {
|
|
230
|
-
return null;
|
|
231
|
-
}
|
|
155
|
+
const { chunk } = payload;
|
|
232
156
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
// Handle final chunks: flush remaining buffer and classify.
|
|
236
|
-
if (chunk.isFinal) {
|
|
237
|
-
const streamId = chunk.streamId;
|
|
238
|
-
const flushed = this.buffer.flush(streamId);
|
|
239
|
-
|
|
240
|
-
// Clean up tracking state for this stream.
|
|
241
|
-
this.isFirstChunk.delete(streamId);
|
|
242
|
-
this.pendingResults.delete(streamId);
|
|
243
|
-
|
|
244
|
-
if (!flushed) {
|
|
245
|
-
return null;
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
// Classify the remaining buffered text.
|
|
249
|
-
const evaluation = await this.orchestrator.classifyAll(flushed.text);
|
|
250
|
-
return this.evaluationToResult(evaluation);
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
// Only process TEXT_DELTA chunks — ignore tool calls, progress, etc.
|
|
254
|
-
if (chunk.type !== AgentOSResponseChunkType.TEXT_DELTA) {
|
|
255
|
-
return null;
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// Extract the text delta from the chunk.
|
|
259
|
-
const textDelta = (chunk as any).textDelta as string | undefined;
|
|
260
|
-
if (!textDelta) {
|
|
157
|
+
// Only evaluate final text responses.
|
|
158
|
+
if (chunk.type !== AgentOSResponseChunkType.FINAL_RESPONSE) {
|
|
261
159
|
return null;
|
|
262
160
|
}
|
|
263
161
|
|
|
264
|
-
|
|
265
|
-
|
|
162
|
+
const text = (chunk as any).text ?? (chunk as any).content ?? '';
|
|
163
|
+
if (typeof text !== 'string' || text.length === 0) return null;
|
|
266
164
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
return this.handleNonBlocking(streamId, textDelta);
|
|
165
|
+
const result = await this.classify(text);
|
|
166
|
+
return this.buildResult(result);
|
|
167
|
+
}
|
|
271
168
|
|
|
272
|
-
|
|
273
|
-
|
|
169
|
+
// -----------------------------------------------------------------------
|
|
170
|
+
// Public classification method (also used by ClassifyContentTool)
|
|
171
|
+
// -----------------------------------------------------------------------
|
|
274
172
|
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
173
|
+
/**
|
|
174
|
+
* Classify a text string using the three-tier strategy: ONNX -> LLM -> keyword.
|
|
175
|
+
*
|
|
176
|
+
* @param text - The text to classify.
|
|
177
|
+
* @returns Classification result with per-category scores.
|
|
178
|
+
*/
|
|
179
|
+
async classify(text: string): Promise<ClassifierResult> {
|
|
180
|
+
// Tier 1: try ONNX inference.
|
|
181
|
+
const onnxResult = await this.tryOnnxClassification(text);
|
|
182
|
+
if (onnxResult) return onnxResult;
|
|
183
|
+
|
|
184
|
+
// Tier 2: try LLM-as-judge.
|
|
185
|
+
if (this.llmInvoker) {
|
|
186
|
+
const llmResult = await this.tryLlmClassification(text);
|
|
187
|
+
if (llmResult) return llmResult;
|
|
278
188
|
}
|
|
189
|
+
|
|
190
|
+
// Tier 3: keyword fallback.
|
|
191
|
+
const scores = classifyByKeywords(text, this.categories);
|
|
192
|
+
return {
|
|
193
|
+
categories: scores,
|
|
194
|
+
flagged: scores.some((s) => s.confidence > this.flagThresholds[s.name]),
|
|
195
|
+
source: 'keyword',
|
|
196
|
+
};
|
|
279
197
|
}
|
|
280
198
|
|
|
281
|
-
//
|
|
282
|
-
//
|
|
283
|
-
//
|
|
199
|
+
// -----------------------------------------------------------------------
|
|
200
|
+
// Private — ONNX classification (Tier 1)
|
|
201
|
+
// -----------------------------------------------------------------------
|
|
284
202
|
|
|
285
203
|
/**
|
|
286
|
-
*
|
|
287
|
-
*
|
|
204
|
+
* Attempt to load `@huggingface/transformers` and run ONNX-based text
|
|
205
|
+
* classification. Returns `null` if the module is unavailable or inference
|
|
206
|
+
* fails.
|
|
207
|
+
*
|
|
208
|
+
* The module load is attempted only once; subsequent calls use the cached
|
|
209
|
+
* result (either a working pipeline or `null`).
|
|
210
|
+
*
|
|
211
|
+
* @param text - Text to classify.
|
|
212
|
+
* @returns Classification result or `null`.
|
|
288
213
|
*
|
|
289
|
-
* @
|
|
290
|
-
* @param textDelta - New text fragment from the current chunk.
|
|
291
|
-
* @returns Evaluation result (possibly BLOCK/FLAG) or `null`.
|
|
214
|
+
* @internal
|
|
292
215
|
*/
|
|
293
|
-
private async
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
if (
|
|
299
|
-
|
|
216
|
+
private async tryOnnxClassification(text: string): Promise<ClassifierResult | null> {
|
|
217
|
+
// If we already know ONNX is unavailable, skip.
|
|
218
|
+
if (this.onnxPipeline === null) return null;
|
|
219
|
+
|
|
220
|
+
// First-time load attempt.
|
|
221
|
+
if (this.onnxPipeline === undefined) {
|
|
222
|
+
try {
|
|
223
|
+
// Dynamic import so the optional dependency does not fail at boot.
|
|
224
|
+
const transformers = await import('@huggingface/transformers');
|
|
225
|
+
this.onnxPipeline = await transformers.pipeline(
|
|
226
|
+
'text-classification',
|
|
227
|
+
'Xenova/toxic-bert',
|
|
228
|
+
{ device: 'cpu' }
|
|
229
|
+
);
|
|
230
|
+
} catch {
|
|
231
|
+
// Module not installed or model load failed — mark as unavailable.
|
|
232
|
+
this.onnxPipeline = null;
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
300
235
|
}
|
|
301
236
|
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
237
|
+
try {
|
|
238
|
+
const raw = await this.onnxPipeline(text, { topk: null });
|
|
239
|
+
|
|
240
|
+
// Map ONNX labels to our categories.
|
|
241
|
+
const scores = this.mapOnnxScores(raw);
|
|
242
|
+
return {
|
|
243
|
+
categories: scores,
|
|
244
|
+
flagged: scores.some((s) => s.confidence > this.flagThresholds[s.name]),
|
|
245
|
+
source: 'onnx',
|
|
246
|
+
};
|
|
247
|
+
} catch {
|
|
248
|
+
// Inference failed — fall through to next tier.
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
305
251
|
}
|
|
306
252
|
|
|
307
253
|
/**
|
|
308
|
-
*
|
|
309
|
-
* ready, fire classification in the background and store the promise.
|
|
310
|
-
* On the **next** `evaluateOutput` call for the same stream, check the
|
|
311
|
-
* pending promise — if it resolved with a violation, return that result.
|
|
254
|
+
* Map raw ONNX text-classification output labels to our standard categories.
|
|
312
255
|
*
|
|
313
|
-
*
|
|
314
|
-
*
|
|
315
|
-
*
|
|
256
|
+
* ONNX models (e.g. toxic-bert) produce labels like `"toxic"`, `"obscene"`,
|
|
257
|
+
* `"threat"`, `"insult"`, `"identity_hate"`, etc. We map these to our four
|
|
258
|
+
* categories, taking the max score when multiple ONNX labels map to the same
|
|
259
|
+
* category.
|
|
260
|
+
*
|
|
261
|
+
* @param raw - Raw ONNX pipeline output.
|
|
262
|
+
* @returns Per-category scores.
|
|
263
|
+
*
|
|
264
|
+
* @internal
|
|
316
265
|
*/
|
|
317
|
-
private
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
Promise.resolve({ done: false as const, val: null as ChunkEvaluation | null }),
|
|
328
|
-
]);
|
|
329
|
-
|
|
330
|
-
if (resolved.done && resolved.val) {
|
|
331
|
-
// Consume the pending result.
|
|
332
|
-
this.pendingResults.delete(streamId);
|
|
333
|
-
|
|
334
|
-
const result = this.evaluationToResult(resolved.val);
|
|
335
|
-
if (result) {
|
|
336
|
-
return result;
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
}
|
|
266
|
+
private mapOnnxScores(raw: any[]): CategoryScore[] {
|
|
267
|
+
/** Map of ONNX label -> our category. */
|
|
268
|
+
const labelMap: Record<string, ClassifierCategory> = {
|
|
269
|
+
toxic: 'toxic',
|
|
270
|
+
severe_toxic: 'toxic',
|
|
271
|
+
obscene: 'nsfw',
|
|
272
|
+
insult: 'toxic',
|
|
273
|
+
identity_hate: 'toxic',
|
|
274
|
+
threat: 'threat',
|
|
275
|
+
};
|
|
340
276
|
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
277
|
+
const maxScores: Record<ClassifierCategory, number> = {
|
|
278
|
+
toxic: 0,
|
|
279
|
+
injection: 0,
|
|
280
|
+
nsfw: 0,
|
|
281
|
+
threat: 0,
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
for (const item of raw) {
|
|
285
|
+
const label = (item.label ?? '').toLowerCase().replace(/\s+/g, '_');
|
|
286
|
+
const score = typeof item.score === 'number' ? item.score : 0;
|
|
287
|
+
const cat = labelMap[label];
|
|
288
|
+
if (cat && score > maxScores[cat]) {
|
|
289
|
+
maxScores[cat] = score;
|
|
290
|
+
}
|
|
347
291
|
}
|
|
348
292
|
|
|
349
|
-
//
|
|
350
|
-
return
|
|
293
|
+
// ONNX models typically do not detect prompt injection; leave at 0.
|
|
294
|
+
return this.categories.map((name) => ({
|
|
295
|
+
name,
|
|
296
|
+
confidence: maxScores[name] ?? 0,
|
|
297
|
+
}));
|
|
351
298
|
}
|
|
352
299
|
|
|
300
|
+
// -----------------------------------------------------------------------
|
|
301
|
+
// Private — LLM classification (Tier 2)
|
|
302
|
+
// -----------------------------------------------------------------------
|
|
303
|
+
|
|
353
304
|
/**
|
|
354
|
-
*
|
|
355
|
-
* blocking mode; subsequent chunks use non-blocking.
|
|
305
|
+
* Classify text using the LLM-as-judge fallback.
|
|
356
306
|
*
|
|
357
|
-
*
|
|
358
|
-
*
|
|
359
|
-
* remainder of the stream.
|
|
307
|
+
* @param text - Text to classify.
|
|
308
|
+
* @returns Classification result or `null` if the LLM call fails.
|
|
360
309
|
*
|
|
361
|
-
* @
|
|
362
|
-
* @param textDelta - New text fragment from the current chunk.
|
|
363
|
-
* @returns Evaluation result or `null`.
|
|
310
|
+
* @internal
|
|
364
311
|
*/
|
|
365
|
-
private async
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
}
|
|
312
|
+
private async tryLlmClassification(text: string): Promise<ClassifierResult | null> {
|
|
313
|
+
if (!this.llmInvoker) return null;
|
|
314
|
+
|
|
315
|
+
try {
|
|
316
|
+
const scores = await classifyByLlm(text, this.llmInvoker, this.categories);
|
|
317
|
+
|
|
318
|
+
// If all scores are zero the LLM likely failed to parse — treat as null.
|
|
319
|
+
if (scores.every((s) => s.confidence === 0)) return null;
|
|
374
320
|
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
321
|
+
return {
|
|
322
|
+
categories: scores,
|
|
323
|
+
flagged: scores.some((s) => s.confidence > this.flagThresholds[s.name]),
|
|
324
|
+
source: 'llm',
|
|
325
|
+
};
|
|
326
|
+
} catch {
|
|
327
|
+
return null;
|
|
378
328
|
}
|
|
379
|
-
return this.handleNonBlocking(streamId, textDelta);
|
|
380
329
|
}
|
|
381
330
|
|
|
382
|
-
//
|
|
383
|
-
// Private
|
|
384
|
-
//
|
|
331
|
+
// -----------------------------------------------------------------------
|
|
332
|
+
// Private — result builder
|
|
333
|
+
// -----------------------------------------------------------------------
|
|
385
334
|
|
|
386
335
|
/**
|
|
387
|
-
* Convert a {@link
|
|
388
|
-
*
|
|
336
|
+
* Convert a {@link ClassifierResult} into a {@link GuardrailEvaluationResult},
|
|
337
|
+
* or return `null` when no thresholds are exceeded.
|
|
389
338
|
*
|
|
390
|
-
*
|
|
391
|
-
*
|
|
392
|
-
* metadata for audit/logging.
|
|
339
|
+
* @param result - Classification result from any tier.
|
|
340
|
+
* @returns Guardrail evaluation result or `null`.
|
|
393
341
|
*
|
|
394
|
-
* @
|
|
395
|
-
* @returns A guardrail result or `null` for clean content.
|
|
342
|
+
* @internal
|
|
396
343
|
*/
|
|
397
|
-
private
|
|
398
|
-
//
|
|
399
|
-
|
|
400
|
-
|
|
344
|
+
private buildResult(result: ClassifierResult): GuardrailEvaluationResult | null {
|
|
345
|
+
// Check for BLOCK-level violations first.
|
|
346
|
+
const blockers = result.categories.filter((s) => s.confidence > this.blockThresholds[s.name]);
|
|
347
|
+
|
|
348
|
+
if (blockers.length > 0) {
|
|
349
|
+
const worst = blockers.reduce((a, b) => (b.confidence > a.confidence ? b : a));
|
|
350
|
+
|
|
351
|
+
return {
|
|
352
|
+
action: GuardrailAction.BLOCK,
|
|
353
|
+
reason: `ML classifier detected unsafe content: ${blockers.map((b) => `${b.name}(${b.confidence.toFixed(2)})`).join(', ')}`,
|
|
354
|
+
reasonCode: `ML_CLASSIFIER_${worst.name.toUpperCase()}`,
|
|
355
|
+
metadata: {
|
|
356
|
+
source: result.source,
|
|
357
|
+
categories: result.categories,
|
|
358
|
+
},
|
|
359
|
+
};
|
|
401
360
|
}
|
|
402
361
|
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
362
|
+
// Check for FLAG-level violations.
|
|
363
|
+
const flaggers = result.categories.filter((s) => s.confidence > this.flagThresholds[s.name]);
|
|
364
|
+
|
|
365
|
+
if (flaggers.length > 0) {
|
|
366
|
+
const worst = flaggers.reduce((a, b) => (b.confidence > a.confidence ? b : a));
|
|
367
|
+
|
|
368
|
+
return {
|
|
369
|
+
action: GuardrailAction.FLAG,
|
|
370
|
+
reason: `ML classifier flagged content: ${flaggers.map((f) => `${f.name}(${f.confidence.toFixed(2)})`).join(', ')}`,
|
|
371
|
+
reasonCode: `ML_CLASSIFIER_${worst.name.toUpperCase()}`,
|
|
372
|
+
metadata: {
|
|
373
|
+
source: result.source,
|
|
374
|
+
categories: result.categories,
|
|
375
|
+
},
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// No thresholds exceeded — allow.
|
|
380
|
+
return null;
|
|
418
381
|
}
|
|
419
382
|
}
|