@swissspidy/belay-web 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/README.md +46 -2
- package/dist/classifier-types.d.ts +63 -0
- package/dist/classifier-types.d.ts.map +1 -0
- package/dist/classifier-types.js +9 -0
- package/dist/classifier-types.js.map +1 -0
- package/dist/classifier.d.ts +39 -0
- package/dist/classifier.d.ts.map +1 -0
- package/dist/classifier.js +160 -0
- package/dist/classifier.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/judge.d.ts +23 -0
- package/dist/judge.d.ts.map +1 -0
- package/dist/judge.js +39 -0
- package/dist/judge.js.map +1 -0
- package/dist/prompt-types.d.ts +37 -0
- package/dist/prompt-types.d.ts.map +1 -0
- package/dist/prompt-types.js +6 -0
- package/dist/prompt-types.js.map +1 -0
- package/dist/prompt.d.ts +25 -0
- package/dist/prompt.d.ts.map +1 -0
- package/dist/prompt.js +117 -0
- package/dist/prompt.js.map +1 -0
- package/package.json +46 -4
- package/src/classifier-types.ts +75 -0
- package/src/classifier.ts +229 -0
- package/src/index.ts +8 -0
- package/src/judge.ts +60 -0
- package/src/prompt-types.ts +41 -0
- package/src/prompt.ts +137 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and 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 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 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 those 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
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,47 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @swissspidy/belay-web
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
On-device runners for [Belay](https://github.com/swissspidy/belay#readme), built on the
|
|
4
|
+
browser's built-in AI:
|
|
5
|
+
|
|
6
|
+
- `classifierApi()`: classification with Chrome's Classifier API. The calibrated probability of
|
|
7
|
+
the returned label is the confidence.
|
|
8
|
+
- `promptApi()`: structured (JSON) generation with Chrome's Prompt API.
|
|
9
|
+
- `classifierJudge()`: scores a generated answer with a Classifier API question ("is this answer
|
|
10
|
+
correct?"), so generation tasks get a confidence too.
|
|
11
|
+
|
|
12
|
+
They work with the native APIs and with polyfills that define the same globals, such as the
|
|
13
|
+
[WebAI Studio extension](https://web-ai.studio/playgrounds/classifier).
|
|
14
|
+
|
|
15
|
+
> **Status:** experimental (0.x). The built-in AI APIs are still behind flags in Chrome, and this
|
|
16
|
+
> API may change between minor versions.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npm install @swissspidy/belay-core @swissspidy/belay-web
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { task, fetchAdapter } from '@swissspidy/belay-core';
|
|
28
|
+
import { classifierApi } from '@swissspidy/belay-web';
|
|
29
|
+
|
|
30
|
+
const moderate = task({
|
|
31
|
+
name: 'moderation',
|
|
32
|
+
schema: { type: 'binary', prompt: 'Is this comment abusive?' },
|
|
33
|
+
local: classifierApi(),
|
|
34
|
+
cloud: fetchAdapter({ url: '/api/belay' }),
|
|
35
|
+
threshold: 0.8,
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// run() never downloads a model; call prepare() from a user gesture to download it.
|
|
39
|
+
button.onclick = () => moderate.prepare({ onProgress: (p) => (progress.value = p) });
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
See the [project README](https://github.com/swissspidy/belay#readme) for generation tasks, model
|
|
43
|
+
downloads and the full API.
|
|
44
|
+
|
|
45
|
+
## License
|
|
46
|
+
|
|
47
|
+
Apache-2.0
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types for the proposed Classifier API (`window.Classifier`), as described in the explainer
|
|
3
|
+
* (https://github.com/michaelwasserman/classifier-api, the current revision of
|
|
4
|
+
* explainers-by-googlers/classifier-api) and implemented by Chrome behind `#classifier-api` and by
|
|
5
|
+
* the WebAI Studio extension polyfill (https://web-ai.studio/docs/classifier). The proposal is in
|
|
6
|
+
* flux: only the members Belay relies on are typed, and result fields are checked at runtime.
|
|
7
|
+
*/
|
|
8
|
+
import type { Availability } from '@swissspidy/belay-core';
|
|
9
|
+
export type ClassifierQuestionType = 'binary' | 'categorical' | 'ordinal';
|
|
10
|
+
export interface ClassifierOption {
|
|
11
|
+
label: string;
|
|
12
|
+
description?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface ClassifierQuestion {
|
|
15
|
+
id: string;
|
|
16
|
+
type: ClassifierQuestionType;
|
|
17
|
+
prompt: string;
|
|
18
|
+
options?: ClassifierOption[];
|
|
19
|
+
}
|
|
20
|
+
export interface ClassifierExpectedInput {
|
|
21
|
+
type: 'text';
|
|
22
|
+
languages?: string[];
|
|
23
|
+
}
|
|
24
|
+
export interface ClassifierSchema {
|
|
25
|
+
context?: string;
|
|
26
|
+
questions: ClassifierQuestion[];
|
|
27
|
+
expectedInputs?: ClassifierExpectedInput[];
|
|
28
|
+
}
|
|
29
|
+
export interface ClassifierCreateOptions extends ClassifierSchema {
|
|
30
|
+
/** Same pattern as the other built-in AI APIs: `downloadprogress` events carry `loaded` in [0, 1]. */
|
|
31
|
+
monitor?: (monitor: EventTarget) => void;
|
|
32
|
+
signal?: AbortSignal;
|
|
33
|
+
}
|
|
34
|
+
export interface ClassifierClassifyOptions {
|
|
35
|
+
signal?: AbortSignal;
|
|
36
|
+
context?: string;
|
|
37
|
+
}
|
|
38
|
+
export interface ClassifierProbability {
|
|
39
|
+
label: string;
|
|
40
|
+
probability: number;
|
|
41
|
+
}
|
|
42
|
+
export interface ClassifierDecision {
|
|
43
|
+
id: string;
|
|
44
|
+
label: string;
|
|
45
|
+
/** Calibrated confidence in [0, 1]. */
|
|
46
|
+
confidence: number;
|
|
47
|
+
/** Binary questions only: calibrated P(true). */
|
|
48
|
+
probability?: number;
|
|
49
|
+
/** Ordinal questions only: E[S]. */
|
|
50
|
+
expectedScore?: number;
|
|
51
|
+
probabilities?: ClassifierProbability[];
|
|
52
|
+
}
|
|
53
|
+
/** Keyed by question `id`. */
|
|
54
|
+
export type ClassifierResult = Record<string, ClassifierDecision>;
|
|
55
|
+
export interface ClassifierInstance {
|
|
56
|
+
classify(input: string, options?: ClassifierClassifyOptions): Promise<ClassifierResult>;
|
|
57
|
+
destroy(): void;
|
|
58
|
+
}
|
|
59
|
+
export interface ClassifierStatic {
|
|
60
|
+
availability(options?: ClassifierSchema): Promise<Availability>;
|
|
61
|
+
create(options: ClassifierCreateOptions): Promise<ClassifierInstance>;
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=classifier-types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"classifier-types.d.ts","sourceRoot":"","sources":["../src/classifier-types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAE3D,MAAM,MAAM,sBAAsB,GAAG,QAAQ,GAAG,aAAa,GAAG,SAAS,CAAC;AAE1E,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,kBAAkB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,sBAAsB,CAAC;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAC;CAC9B;AAED,MAAM,WAAW,uBAAuB;IACtC,IAAI,EAAE,MA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C,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;CACvE"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types for the proposed Classifier API (`window.Classifier`), as described in the explainer
|
|
3
|
+
* (https://github.com/michaelwasserman/classifier-api, the current revision of
|
|
4
|
+
* explainers-by-googlers/classifier-api) and implemented by Chrome behind `#classifier-api` and by
|
|
5
|
+
* the WebAI Studio extension polyfill (https://web-ai.studio/docs/classifier). The proposal is in
|
|
6
|
+
* flux: only the members Belay relies on are typed, and result fields are checked at runtime.
|
|
7
|
+
*/
|
|
8
|
+
export {};
|
|
9
|
+
//# sourceMappingURL=classifier-types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"classifier-types.js","sourceRoot":"","sources":["../src/classifier-types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { BinarySchema, CategoricalSchema, LocalOutput, LocalRunner, OrdinalSchema, TaskSchema } from '@swissspidy/belay-core';
|
|
2
|
+
import type { ClassifierDecision, ClassifierExpectedInput, ClassifierSchema, ClassifierStatic } from './classifier-types.js';
|
|
3
|
+
export type ClassifierTaskSchema = BinarySchema | CategoricalSchema | OrdinalSchema;
|
|
4
|
+
export interface ClassifierApiOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Which number becomes the task confidence:
|
|
7
|
+
* - `label-probability` (default): the calibrated probability of the returned label
|
|
8
|
+
* (the top option). For binary questions this is max(P(true), P(false)).
|
|
9
|
+
* - `model`: the decision's own `confidence` field.
|
|
10
|
+
* See ADR 0001 for why the default is the probability.
|
|
11
|
+
*/
|
|
12
|
+
confidence?: 'label-probability' | 'model';
|
|
13
|
+
/** Defaults to `[{ type: 'text', languages: ['en'] }]`. */
|
|
14
|
+
expectedInputs?: ClassifierExpectedInput[];
|
|
15
|
+
/** Question id used in the Classifier schema. Defaults to "answer". */
|
|
16
|
+
questionId?: string;
|
|
17
|
+
/**
|
|
18
|
+
* The `Classifier` implementation. Defaults to `globalThis.Classifier` (Chrome's built-in API or
|
|
19
|
+
* the WebAI Studio extension polyfill). Injectable for tests and custom polyfills.
|
|
20
|
+
*/
|
|
21
|
+
classifier?: ClassifierStatic;
|
|
22
|
+
/** Max number of cached sessions (one per distinct context). Defaults to 4. */
|
|
23
|
+
maxSessions?: number;
|
|
24
|
+
}
|
|
25
|
+
/** Maps a Belay schema to a Classifier API schema with a single question. */
|
|
26
|
+
export declare function toClassifierSchema(schema: TaskSchema, options?: {
|
|
27
|
+
questionId?: string;
|
|
28
|
+
context?: string;
|
|
29
|
+
expectedInputs?: ClassifierExpectedInput[];
|
|
30
|
+
}): ClassifierSchema;
|
|
31
|
+
/** Extracts value, confidence and distribution from a Classifier decision. */
|
|
32
|
+
export declare function readDecision(schema: ClassifierTaskSchema, decision: ClassifierDecision | undefined, mode?: 'label-probability' | 'model'): LocalOutput<string | boolean>;
|
|
33
|
+
/**
|
|
34
|
+
* Local runner backed by the Classifier API. It never triggers a model download from `run()`:
|
|
35
|
+
* while the model is "downloadable" or "downloading" the task escalates with reason
|
|
36
|
+
* `local-unavailable`. Call `task.prepare()` from a user gesture to download the model.
|
|
37
|
+
*/
|
|
38
|
+
export declare function classifierApi(options?: ClassifierApiOptions): LocalRunner<any>;
|
|
39
|
+
//# sourceMappingURL=classifier.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"classifier.d.ts","sourceRoot":"","sources":["../src/classifier.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAEV,YAAY,EACZ,iBAAiB,EACjB,WAAW,EACX,WAAW,EACX,aAAa,EAIb,UAAU,EACX,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EACV,kBAAkB,EAClB,uBAAuB,EAEvB,gBAAgB,EAChB,gBAAgB,EACjB,MAAM,uBAAuB,CAAC;AAE/B,MAAM,MAAM,oBAAoB,GAAG,YAAY,GAAG,iBAAiB,GAAG,aAAa,CAAC;AAEpF,MAAM,WAAW,oBAAoB;IACnC;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC;IAC3C,2DAA2D;IAC3D,cAAc,CAAC,EAAE,uBAAuB,EAAE,CAAC;IAC3C,uEAAuE;IACvE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;OAGG;IACH,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,+EAA+E;IAC/E,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AASD,6EAA6E;AAC7E,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,UAAU,EAClB,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,uBAAuB,EAAE,CAAA;CAAO,GAClG,gBAAgB,CA4BlB;AAED,8EAA8E;AAC9E,wBAAgB,YAAY,CAC1B,MAAM,EAAE,oBAAoB,EAC5B,QAAQ,EAAE,kBAAkB,GAAG,SAAS,EACxC,IAAI,GAAE,mBAAmB,GAAG,OAA6B,GACxD,WAAW,CAAC,MAAM,GAAG,OAAO,CAAC,CAgC/B;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,OAAO,GAAE,oBAAyB,GAAG,WAAW,CAAC,GAAG,CAAC,CA4FlF"}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { BelayError, LocalUnavailableError, clamp01, normalizeOptions, topProbability, } from '@swissspidy/belay-core';
|
|
2
|
+
const DEFAULT_PROMPTS = {
|
|
3
|
+
categorical: 'Which option best describes the input?',
|
|
4
|
+
ordinal: 'Which level best describes the input?',
|
|
5
|
+
};
|
|
6
|
+
/** Maps a Belay schema to a Classifier API schema with a single question. */
|
|
7
|
+
export function toClassifierSchema(schema, options = {}) {
|
|
8
|
+
const id = options.questionId ?? 'answer';
|
|
9
|
+
const base = {
|
|
10
|
+
...(options.context ? { context: options.context } : {}),
|
|
11
|
+
expectedInputs: options.expectedInputs ?? [{ type: 'text', languages: ['en'] }],
|
|
12
|
+
};
|
|
13
|
+
switch (schema.type) {
|
|
14
|
+
case 'binary':
|
|
15
|
+
return { ...base, questions: [{ id, type: 'binary', prompt: schema.prompt }] };
|
|
16
|
+
case 'categorical':
|
|
17
|
+
case 'ordinal':
|
|
18
|
+
return {
|
|
19
|
+
...base,
|
|
20
|
+
questions: [
|
|
21
|
+
{
|
|
22
|
+
id,
|
|
23
|
+
type: schema.type,
|
|
24
|
+
prompt: schema.prompt ?? DEFAULT_PROMPTS[schema.type],
|
|
25
|
+
options: normalizeOptions(schema.options),
|
|
26
|
+
},
|
|
27
|
+
],
|
|
28
|
+
};
|
|
29
|
+
default:
|
|
30
|
+
throw new BelayError('invalid-task', `the Classifier API runner supports binary, categorical and ordinal tasks, not "${schema.type}"`);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** Extracts value, confidence and distribution from a Classifier decision. */
|
|
34
|
+
export function readDecision(schema, decision, mode = 'label-probability') {
|
|
35
|
+
if (!decision || typeof decision !== 'object') {
|
|
36
|
+
throw new Error('Classifier result is missing the decision');
|
|
37
|
+
}
|
|
38
|
+
let probabilities = Array.isArray(decision.probabilities)
|
|
39
|
+
? decision.probabilities.filter((p) => typeof p?.label === 'string' && typeof p.probability === 'number')
|
|
40
|
+
: undefined;
|
|
41
|
+
if (schema.type === 'binary' && typeof decision.probability === 'number') {
|
|
42
|
+
const pTrue = clamp01(decision.probability);
|
|
43
|
+
probabilities = [
|
|
44
|
+
{ label: 'true', probability: pTrue },
|
|
45
|
+
{ label: 'false', probability: 1 - pTrue },
|
|
46
|
+
];
|
|
47
|
+
}
|
|
48
|
+
let label = typeof decision.label === 'string' ? decision.label : undefined;
|
|
49
|
+
if (label === undefined && probabilities?.length) {
|
|
50
|
+
label = probabilities.reduce((a, b) => (b.probability > a.probability ? b : a)).label;
|
|
51
|
+
}
|
|
52
|
+
if (label === undefined)
|
|
53
|
+
throw new Error('Classifier decision has no label');
|
|
54
|
+
let confidence;
|
|
55
|
+
if (mode === 'label-probability' && probabilities?.length) {
|
|
56
|
+
const own = probabilities.find((p) => p.label === label);
|
|
57
|
+
confidence = own ? clamp01(own.probability) : topProbability(probabilities);
|
|
58
|
+
}
|
|
59
|
+
if (confidence === undefined && typeof decision.confidence === 'number')
|
|
60
|
+
confidence = clamp01(decision.confidence);
|
|
61
|
+
if (confidence === undefined)
|
|
62
|
+
throw new Error('Classifier decision has neither probabilities nor confidence');
|
|
63
|
+
const value = schema.type === 'binary' ? label.trim().toLowerCase() === 'true' : label;
|
|
64
|
+
return { value, confidence, ...(probabilities ? { probabilities } : {}), raw: decision };
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Local runner backed by the Classifier API. It never triggers a model download from `run()`:
|
|
68
|
+
* while the model is "downloadable" or "downloading" the task escalates with reason
|
|
69
|
+
* `local-unavailable`. Call `task.prepare()` from a user gesture to download the model.
|
|
70
|
+
*/
|
|
71
|
+
export function classifierApi(options = {}) {
|
|
72
|
+
const mode = options.confidence ?? 'label-probability';
|
|
73
|
+
const maxSessions = Math.max(1, options.maxSessions ?? 4);
|
|
74
|
+
const sessions = new Map();
|
|
75
|
+
const api = () => options.classifier ?? globalThis.Classifier;
|
|
76
|
+
const schemaFor = (ctx) => toClassifierSchema(ctx.schema, {
|
|
77
|
+
...(options.questionId ? { questionId: options.questionId } : {}),
|
|
78
|
+
...(ctx.context ? { context: ctx.context } : {}),
|
|
79
|
+
...(options.expectedInputs ? { expectedInputs: options.expectedInputs } : {}),
|
|
80
|
+
});
|
|
81
|
+
const keyFor = (schema) => JSON.stringify(schema);
|
|
82
|
+
function session(ctx, prepare) {
|
|
83
|
+
const Classifier = api();
|
|
84
|
+
if (!Classifier)
|
|
85
|
+
return Promise.reject(new LocalUnavailableError('Classifier API is not available'));
|
|
86
|
+
const schema = schemaFor(ctx);
|
|
87
|
+
const key = keyFor(schema);
|
|
88
|
+
const cached = sessions.get(key);
|
|
89
|
+
if (cached) {
|
|
90
|
+
sessions.delete(key); // refresh LRU position
|
|
91
|
+
sessions.set(key, cached);
|
|
92
|
+
return cached;
|
|
93
|
+
}
|
|
94
|
+
// Only prepare()'s signal: the session is cached and shared, so a per-run abort must not destroy it.
|
|
95
|
+
const signal = prepare?.signal;
|
|
96
|
+
const created = Classifier.create({
|
|
97
|
+
...schema,
|
|
98
|
+
...(signal ? { signal } : {}),
|
|
99
|
+
...(prepare?.onProgress
|
|
100
|
+
? {
|
|
101
|
+
monitor: (m) => m.addEventListener('downloadprogress', (e) => prepare.onProgress(e.loaded)),
|
|
102
|
+
}
|
|
103
|
+
: {}),
|
|
104
|
+
});
|
|
105
|
+
sessions.set(key, created);
|
|
106
|
+
created.catch(() => {
|
|
107
|
+
if (sessions.get(key) === created)
|
|
108
|
+
sessions.delete(key);
|
|
109
|
+
});
|
|
110
|
+
while (sessions.size > maxSessions) {
|
|
111
|
+
const [oldestKey, oldest] = sessions.entries().next().value;
|
|
112
|
+
sessions.delete(oldestKey);
|
|
113
|
+
oldest.then((s) => s.destroy(), () => { });
|
|
114
|
+
}
|
|
115
|
+
return created;
|
|
116
|
+
}
|
|
117
|
+
async function availability(ctx) {
|
|
118
|
+
const Classifier = api();
|
|
119
|
+
if (!Classifier)
|
|
120
|
+
return 'unavailable';
|
|
121
|
+
const schema = schemaFor(ctx); // throws for unsupported schemas
|
|
122
|
+
if (sessions.has(keyFor(schema)))
|
|
123
|
+
return 'available';
|
|
124
|
+
try {
|
|
125
|
+
return await Classifier.availability(schema);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return 'unavailable';
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
id: 'classifier-api',
|
|
133
|
+
availability,
|
|
134
|
+
async run(input, ctx) {
|
|
135
|
+
const schema = schemaFor(ctx);
|
|
136
|
+
if (!sessions.has(keyFor(schema))) {
|
|
137
|
+
// Creating a session while the model is not downloaded would start a download.
|
|
138
|
+
const state = await availability(ctx);
|
|
139
|
+
if (state !== 'available')
|
|
140
|
+
throw new LocalUnavailableError(`Classifier model is ${state}`);
|
|
141
|
+
}
|
|
142
|
+
const classifier = await session(ctx);
|
|
143
|
+
const result = await classifier.classify(input, ctx.signal ? { signal: ctx.signal } : {});
|
|
144
|
+
const questionId = schema.questions[0].id;
|
|
145
|
+
return readDecision(ctx.schema, result?.[questionId], mode);
|
|
146
|
+
},
|
|
147
|
+
async prepare(ctx, prepareOptions) {
|
|
148
|
+
const state = await availability(ctx);
|
|
149
|
+
if (state === 'unavailable')
|
|
150
|
+
throw new LocalUnavailableError('Classifier model is unavailable on this device');
|
|
151
|
+
await session(ctx, prepareOptions);
|
|
152
|
+
},
|
|
153
|
+
destroy() {
|
|
154
|
+
for (const s of sessions.values())
|
|
155
|
+
s.then((c) => c.destroy(), () => { });
|
|
156
|
+
sessions.clear();
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
//# sourceMappingURL=classifier.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"classifier.js","sourceRoot":"","sources":["../src/classifier.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,qBAAqB,EACrB,OAAO,EACP,gBAAgB,EAChB,cAAc,GACf,MAAM,wBAAwB,CAAC;AA+ChC,MAAM,eAAe,GAAG;IACtB,WAAW,EAAE,wCAAwC;IACrD,OAAO,EAAE,uCAAuC;CACxC,CAAC;AAEX,6EAA6E;AAC7E,MAAM,UAAU,kBAAkB,CAChC,MAAkB,EAClB,OAAO,GAA0F,EAAE;IAEnG,MAAM,EAAE,GAAG,OAAO,CAAC,UAAU,IAAI,QAAQ,CAAC;IAC1C,MAAM,IAAI,GAAG;QACX,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,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CAAC,CAAC,OAAO,EAAE,EAAE,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YACxE,QAAQ,CAAC,KAAK,EAAE,CAAC;QACnB,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { classifierApi, readDecision, toClassifierSchema } from './classifier.js';
|
|
2
|
+
export type { ClassifierApiOptions, ClassifierTaskSchema } from './classifier.js';
|
|
3
|
+
export { promptApi } from './prompt.js';
|
|
4
|
+
export type { PromptApiOptions } from './prompt.js';
|
|
5
|
+
export { classifierJudge, DEFAULT_JUDGE_QUESTION } from './judge.js';
|
|
6
|
+
export type { ClassifierJudgeOptions } from './judge.js';
|
|
7
|
+
export type * from './classifier-types.js';
|
|
8
|
+
export type * from './prompt-types.js';
|
|
9
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAClF,YAAY,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAClF,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,YAAY,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACrE,YAAY,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACzD,mBAAmB,uBAAuB,CAAC;AAC3C,mBAAmB,mBAAmB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAElF,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,OAAO,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/judge.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Judge } from '@swissspidy/belay-core';
|
|
2
|
+
import type { ClassifierExpectedInput, ClassifierStatic } from './classifier-types.js';
|
|
3
|
+
export interface ClassifierJudgeOptions {
|
|
4
|
+
/** The yes/no question the Classifier answers about the (input, output) pair. */
|
|
5
|
+
question?: string;
|
|
6
|
+
/** Shared context for the judge, e.g. what a good answer looks like for this task. */
|
|
7
|
+
context?: string;
|
|
8
|
+
/** Serializes the pair for the Classifier. Defaults to "Input: … / Proposed answer: …". */
|
|
9
|
+
format?: (input: string, value: unknown) => string;
|
|
10
|
+
/** Truncation limits, because on-device classifiers have small windows (e.g. 256 tokens). */
|
|
11
|
+
maxInputChars?: number;
|
|
12
|
+
maxValueChars?: number;
|
|
13
|
+
classifier?: ClassifierStatic;
|
|
14
|
+
expectedInputs?: ClassifierExpectedInput[];
|
|
15
|
+
}
|
|
16
|
+
export declare const DEFAULT_JUDGE_QUESTION = "Is the proposed answer a correct and complete response to the input, with no invented facts?";
|
|
17
|
+
/**
|
|
18
|
+
* A judge for generation tasks built on the Classifier API: one binary question over the input and
|
|
19
|
+
* the generated output. Its calibrated P(true) becomes the confidence (combined with schema
|
|
20
|
+
* validation by the task; see ADR 0001). Costs one classifier forward pass, not a second LLM call.
|
|
21
|
+
*/
|
|
22
|
+
export declare function classifierJudge(options?: ClassifierJudgeOptions): Judge<unknown>;
|
|
23
|
+
//# sourceMappingURL=judge.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"judge.d.ts","sourceRoot":"","sources":["../src/judge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAiC,MAAM,wBAAwB,CAAC;AAEnF,OAAO,KAAK,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEvF,MAAM,WAAW,sBAAsB;IACrC,iFAAiF;IACjF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sFAAsF;IACtF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,2FAA2F;IAC3F,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,KAAK,MAAM,CAAC;IACnD,6FAA6F;IAC7F,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,cAAc,CAAC,EAAE,uBAAuB,EAAE,CAAC;CAC5C;AAED,eAAO,MAAM,sBAAsB,iGAC6D,CAAC;AAIjG;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,sBAA2B,GAAG,KAAK,CAAC,OAAO,CAAC,CA+BpF"}
|
package/dist/judge.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { classifierApi } from './classifier.js';
|
|
2
|
+
export const DEFAULT_JUDGE_QUESTION = 'Is the proposed answer a correct and complete response to the input, with no invented facts?';
|
|
3
|
+
const truncate = (s, max) => (s.length > max ? `${s.slice(0, max - 1)}…` : s);
|
|
4
|
+
/**
|
|
5
|
+
* A judge for generation tasks built on the Classifier API: one binary question over the input and
|
|
6
|
+
* the generated output. Its calibrated P(true) becomes the confidence (combined with schema
|
|
7
|
+
* validation by the task; see ADR 0001). Costs one classifier forward pass, not a second LLM call.
|
|
8
|
+
*/
|
|
9
|
+
export function classifierJudge(options = {}) {
|
|
10
|
+
const runner = classifierApi({
|
|
11
|
+
...(options.classifier ? { classifier: options.classifier } : {}),
|
|
12
|
+
...(options.expectedInputs ? { expectedInputs: options.expectedInputs } : {}),
|
|
13
|
+
questionId: 'judgement',
|
|
14
|
+
});
|
|
15
|
+
const schema = { type: 'binary', prompt: options.question ?? DEFAULT_JUDGE_QUESTION };
|
|
16
|
+
const maxInput = options.maxInputChars ?? 600;
|
|
17
|
+
const maxValue = options.maxValueChars ?? 400;
|
|
18
|
+
const format = options.format ??
|
|
19
|
+
((input, value) => `Input:\n${truncate(input, maxInput)}\n\nProposed answer:\n${truncate(typeof value === 'string' ? value : JSON.stringify(value), maxValue)}`);
|
|
20
|
+
const ctx = (signal) => ({
|
|
21
|
+
task: 'belay-judge',
|
|
22
|
+
schema,
|
|
23
|
+
...(options.context ? { context: options.context } : {}),
|
|
24
|
+
...(signal ? { signal } : {}),
|
|
25
|
+
});
|
|
26
|
+
const judge = (async ({ input, value, signal }) => {
|
|
27
|
+
const out = await runner.run(format(input, value), ctx(signal));
|
|
28
|
+
const pTrue = out.probabilities?.find((p) => p.label === 'true')?.probability;
|
|
29
|
+
if (typeof pTrue === 'number')
|
|
30
|
+
return pTrue;
|
|
31
|
+
// Fall back to the returned label's probability.
|
|
32
|
+
return out.value === true ? out.confidence : 1 - out.confidence;
|
|
33
|
+
});
|
|
34
|
+
judge.availability = () => runner.availability(ctx());
|
|
35
|
+
judge.prepare = (prepareOptions) => runner.prepare(ctx(), prepareOptions);
|
|
36
|
+
judge.destroy = () => runner.destroy?.();
|
|
37
|
+
return judge;
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=judge.js.map
|