laya-system-one 1.0.0
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/.gitattributes +1 -0
- package/LICENSE +179 -0
- package/README.md +322 -0
- package/bin/cli.js +81 -0
- package/models/rl_agent_config.json +26 -0
- package/models/tokenizer.json +4 -0
- package/models/tokenizer_config.json +22 -0
- package/package.json +44 -0
- package/src/agent.js +201 -0
- package/src/engine.js +185 -0
- package/src/index.js +4 -0
- package/src/server.js +127 -0
- package/src/tokenizer.js +122 -0
package/.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
models/*.onnx filter=lfs diff=lfs merge=lfs -text
|
package/LICENSE
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
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
|
+
Copyright 2026 Italo Almeida (https://github.com/italoalmeida0)
|
|
179
|
+
Based on Laya (https://github.com/NandhaKishorM/laya), Copyright 2026 Convai Innovations
|
package/README.md
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
# Laya System-One ⚡
|
|
2
|
+
|
|
3
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
4
|
+
[]()
|
|
5
|
+
[]()
|
|
6
|
+
|
|
7
|
+
> **Self-contained, ultra-fast System 1 decision engine with WebGPU and WASM SIMD acceleration. Drop-in, 100% wire-compatible replacement for the TypeSafe Jev API (`POST /v1/systemone`).**
|
|
8
|
+
|
|
9
|
+
Runs entirely on your local machine with **zero Python**, **zero PyTorch**, and **zero external network requests** at runtime. The INT8 multilingual model (~324 MB) is embedded directly within the package, enabling secure, air-gapped corporate deployments with sub-20ms inference latency.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 🌟 Why Laya System-One?
|
|
14
|
+
|
|
15
|
+
- 🔒 **100% Offline & Air-Gapped:** Zero external calls to Hugging Face or cloud APIs at runtime. Ideal for secure corporate intranets, edge servers, and privacy-sensitive workflows.
|
|
16
|
+
- ⚡ **Sub-20ms Latency:** Executes non-autoregressive decision classification in ~15ms on modern CPUs via native C++/SIMD and WebGPU.
|
|
17
|
+
- 🔄 **TypeSafe Jev Wire-Compatible:** Drop-in emulation of TypeSafe Jev's `POST /v1/systemone` endpoint. Any existing Jev client or SDK can connect immediately simply by changing the base URL.
|
|
18
|
+
- 🌍 **True Multilingual Understanding:** Built on multilingual representations supporting over 100 languages (English, Portuguese, Spanish, German, French, Chinese, Japanese, etc.) out-of-the-box.
|
|
19
|
+
- 💻 **Universal JavaScript Support:** Works seamlessly across **Node.js** (>=18), **Bun**, **Deno**, and modern web browsers.
|
|
20
|
+
- 📦 **Dual Operation Modes:** Run as an independent local HTTP daemon via the CLI (`npx laya-system-one`) or import in-memory into your application process for zero network overhead.
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## 📦 Installation
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
# Using npm
|
|
28
|
+
npm install laya-system-one
|
|
29
|
+
|
|
30
|
+
# Using bun
|
|
31
|
+
bun add laya-system-one
|
|
32
|
+
|
|
33
|
+
# Using pnpm
|
|
34
|
+
pnpm add laya-system-one
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## 🚀 Quick Start
|
|
40
|
+
|
|
41
|
+
### 1. Launch HTTP Microservice via CLI
|
|
42
|
+
|
|
43
|
+
To spin up a TypeSafe Jev-compatible server on port `8080`:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npx laya-system-one --port 8080
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
#### CLI Options:
|
|
50
|
+
|
|
51
|
+
| Flag | Environment Variable | Default | Description |
|
|
52
|
+
| :--- | :--- | :--- | :--- |
|
|
53
|
+
| `--port <number>` | `PORT` | `8080` | Port to bind the HTTP server |
|
|
54
|
+
| `--host <string>` | `HOST` | `0.0.0.0` | Host address to bind |
|
|
55
|
+
| `--device <type>` | `DEVICE` | `auto` | Execution backend: `auto`, `webgpu`, `wasm`, `cpu` |
|
|
56
|
+
| `--api-key <token>`| `LAYA_API_KEY` | *(none)* | Require Bearer authentication on `/v1/systemone` |
|
|
57
|
+
|
|
58
|
+
Example with authentication enabled:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
npx laya-system-one --port 8080 --api-key secret-token-xyz
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
### 2. In-Process Programmatic Usage (Zero Network Latency)
|
|
67
|
+
|
|
68
|
+
You can evaluate states directly in memory inside your Node.js or Bun backend:
|
|
69
|
+
|
|
70
|
+
```javascript
|
|
71
|
+
import { Laya } from 'laya-system-one';
|
|
72
|
+
|
|
73
|
+
// 1. Initialize engine (device: 'auto' | 'webgpu' | 'wasm' | 'cpu')
|
|
74
|
+
const laya = await Laya.load({ device: 'auto' });
|
|
75
|
+
|
|
76
|
+
// 2. Define state (string, object, or array)
|
|
77
|
+
const state = {
|
|
78
|
+
customer_id: 'cust_9821',
|
|
79
|
+
message: 'We were charged twice on our March invoice. Please refund the duplicate amount or we will cancel our plan.'
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// 3. Define typed questions (choice, score, noul)
|
|
83
|
+
const questions = {
|
|
84
|
+
department: {
|
|
85
|
+
type: 'choice',
|
|
86
|
+
instructions: 'Which team should resolve this customer inquiry?',
|
|
87
|
+
criteria: {
|
|
88
|
+
billing: 'Invoices, refunds, and duplicate charges',
|
|
89
|
+
tech_support: 'Software bugs, outages, and error messages',
|
|
90
|
+
sales: 'Upgrades, plan changes, and enterprise contracts'
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
urgency: {
|
|
94
|
+
type: 'score',
|
|
95
|
+
instructions: 'Assess the urgency level of this inquiry.',
|
|
96
|
+
criteria: ['Low / routine', 'Moderate', 'Critical / blocking / angry']
|
|
97
|
+
},
|
|
98
|
+
churn_risk: {
|
|
99
|
+
type: 'noul',
|
|
100
|
+
instructions: 'Does this message present an explicit risk of customer churn?',
|
|
101
|
+
threshold: 0.5
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// 4. Evaluate state
|
|
106
|
+
const result = await laya.predict(state, questions);
|
|
107
|
+
|
|
108
|
+
console.log(result.answers.department.choice); // -> "billing"
|
|
109
|
+
console.log(result.answers.department.confidence); // -> 1.0 (100%)
|
|
110
|
+
console.log(result.answers.urgency.score); // -> 1.95 (High urgency)
|
|
111
|
+
console.log(result.answers.churn_risk.noul); // -> 0.968 (96.8% probability)
|
|
112
|
+
console.log(result.answers.churn_risk.decision); // -> true (Passed threshold 0.5)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
### 3. Programmatic HTTP Server
|
|
118
|
+
|
|
119
|
+
Spin up the HTTP server inside your existing JavaScript application:
|
|
120
|
+
|
|
121
|
+
```javascript
|
|
122
|
+
import { serve } from 'laya-system-one';
|
|
123
|
+
|
|
124
|
+
const { url, close } = await serve({
|
|
125
|
+
host: '127.0.0.1',
|
|
126
|
+
port: 8080,
|
|
127
|
+
apiKey: 'optional-bearer-key'
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
console.log(`Laya Jev server running at ${url}/v1/systemone`);
|
|
131
|
+
|
|
132
|
+
// To stop gracefully later:
|
|
133
|
+
// close();
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
---
|
|
137
|
+
|
|
138
|
+
## 📡 HTTP API Reference (TypeSafe Jev Wire Compatible)
|
|
139
|
+
|
|
140
|
+
### Evaluation Endpoint
|
|
141
|
+
|
|
142
|
+
```http
|
|
143
|
+
POST /v1/systemone
|
|
144
|
+
Host: localhost:8080
|
|
145
|
+
Content-Type: application/json
|
|
146
|
+
Authorization: Bearer <API_KEY> [Optional unless configured]
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### Request Body
|
|
150
|
+
|
|
151
|
+
| Parameter | Type | Required | Description |
|
|
152
|
+
| :--- | :--- | :--- | :--- |
|
|
153
|
+
| `state` | `string` \| `object` \| `array` | **Yes** | The context, text, or structured data being evaluated. |
|
|
154
|
+
| `questions` | `Record<string, Question>` | **Yes** | Map of question keys to typed question objects. |
|
|
155
|
+
| `model` | `string` | No | Model name (defaults to `laya-multilingual`, echoed back). |
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
### Question Specifications
|
|
160
|
+
|
|
161
|
+
#### 1. `choice` Question
|
|
162
|
+
Multi-class classification between distinct options.
|
|
163
|
+
|
|
164
|
+
```json
|
|
165
|
+
{
|
|
166
|
+
"type": "choice",
|
|
167
|
+
"instructions": "Which department should handle this ticket?",
|
|
168
|
+
"criteria": {
|
|
169
|
+
"billing": "Invoices and credit card transactions",
|
|
170
|
+
"technical": "Software bugs and service disruptions"
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
#### 2. `score` Question
|
|
176
|
+
Continuous ordinal scoring along an ordered scale of criteria levels.
|
|
177
|
+
|
|
178
|
+
```json
|
|
179
|
+
{
|
|
180
|
+
"type": "score",
|
|
181
|
+
"instructions": "Rate the severity of the issue.",
|
|
182
|
+
"criteria": [
|
|
183
|
+
"Minor cosmetic issue",
|
|
184
|
+
"Degraded functionality",
|
|
185
|
+
"Critical full service outage"
|
|
186
|
+
]
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
#### 3. `noul` Question
|
|
191
|
+
Calibrated binary verification (0.0 to 1.0).
|
|
192
|
+
|
|
193
|
+
```json
|
|
194
|
+
{
|
|
195
|
+
"type": "noul",
|
|
196
|
+
"instructions": "Does the user explicitly request a refund?",
|
|
197
|
+
"threshold": 0.6
|
|
198
|
+
}
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
---
|
|
202
|
+
|
|
203
|
+
### Example cURL Request
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
curl -X POST http://localhost:8080/v1/systemone \
|
|
207
|
+
-H "Content-Type: application/json" \
|
|
208
|
+
-d '{
|
|
209
|
+
"state": {
|
|
210
|
+
"text": "Fui cobrado duas vezes na minha fatura. Reembolsem imediatamente."
|
|
211
|
+
},
|
|
212
|
+
"questions": {
|
|
213
|
+
"dept": {
|
|
214
|
+
"type": "choice",
|
|
215
|
+
"instructions": "Which department should respond?",
|
|
216
|
+
"criteria": {
|
|
217
|
+
"billing": "Refunds, invoices, and payments",
|
|
218
|
+
"support": "Technical and product questions"
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
"urgency": {
|
|
222
|
+
"type": "score",
|
|
223
|
+
"instructions": "Urgency rating",
|
|
224
|
+
"criteria": ["Low", "Medium", "High"]
|
|
225
|
+
},
|
|
226
|
+
"refund_demanded": {
|
|
227
|
+
"type": "noul",
|
|
228
|
+
"instructions": "Is the customer requesting a refund?",
|
|
229
|
+
"threshold": 0.5
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}'
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### Example HTTP Response (`200 OK`)
|
|
236
|
+
|
|
237
|
+
```json
|
|
238
|
+
{
|
|
239
|
+
"model": "laya-multilingual",
|
|
240
|
+
"answers": {
|
|
241
|
+
"dept": {
|
|
242
|
+
"type": "choice",
|
|
243
|
+
"choice": "billing",
|
|
244
|
+
"probabilities": {
|
|
245
|
+
"billing": 1.0,
|
|
246
|
+
"support": 0.0
|
|
247
|
+
},
|
|
248
|
+
"confidence": 1.0
|
|
249
|
+
},
|
|
250
|
+
"urgency": {
|
|
251
|
+
"type": "score",
|
|
252
|
+
"score": 1.9482,
|
|
253
|
+
"legend": {
|
|
254
|
+
"0": "Low",
|
|
255
|
+
"1": "Medium",
|
|
256
|
+
"2": "High"
|
|
257
|
+
},
|
|
258
|
+
"probabilities": {
|
|
259
|
+
"0": 0.0011,
|
|
260
|
+
"1": 0.0496,
|
|
261
|
+
"2": 0.9493
|
|
262
|
+
},
|
|
263
|
+
"confidence": 0.9493
|
|
264
|
+
},
|
|
265
|
+
"refund_demanded": {
|
|
266
|
+
"type": "noul",
|
|
267
|
+
"noul": 0.9852,
|
|
268
|
+
"confidence": 0.9852,
|
|
269
|
+
"threshold": 0.5,
|
|
270
|
+
"decision": true
|
|
271
|
+
}
|
|
272
|
+
},
|
|
273
|
+
"usage": {
|
|
274
|
+
"input_tokens": 82,
|
|
275
|
+
"output_tokens": 12
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
### Healthcheck Endpoint
|
|
281
|
+
|
|
282
|
+
```http
|
|
283
|
+
GET /health
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
**Response (`200 OK`):**
|
|
287
|
+
```json
|
|
288
|
+
{
|
|
289
|
+
"status": "ok",
|
|
290
|
+
"model": "laya-multilingual",
|
|
291
|
+
"version": "1.0.0",
|
|
292
|
+
"protocol": "TypeSafe Jev /v1/systemone compatible"
|
|
293
|
+
}
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
### HTTP Error Codes
|
|
297
|
+
|
|
298
|
+
- `401 Unauthorized`: Returned when `--api-key` is configured on the server and the `Authorization: Bearer <key>` header is missing or invalid.
|
|
299
|
+
- `422 Unprocessable Entity`: Returned when the JSON body is invalid or missing required `state` / `questions` fields.
|
|
300
|
+
|
|
301
|
+
---
|
|
302
|
+
|
|
303
|
+
## ⚡ Hardware Acceleration Architecture
|
|
304
|
+
|
|
305
|
+
`laya-system-one` includes a hybrid native runtime that maximizes throughput based on the active runtime:
|
|
306
|
+
|
|
307
|
+
| Environment | Primary Provider | Fallback Provider | Typical Inference Latency |
|
|
308
|
+
| :--- | :--- | :--- | :--- |
|
|
309
|
+
| **Node.js** | Native C++ (`cpu`) | WebGPU (`webgpu`) | ~15 ms / query |
|
|
310
|
+
| **Bun** | WebAssembly SIMD (`wasm`) | WebGPU (`webgpu`) | ~25 ms / query |
|
|
311
|
+
| **Browser** | WebGPU (`navigator.gpu`) | WebAssembly SIMD (`wasm`) | ~18 ms / query |
|
|
312
|
+
|
|
313
|
+
---
|
|
314
|
+
|
|
315
|
+
## 📄 License & Attribution
|
|
316
|
+
|
|
317
|
+
- **License:** [Apache-2.0](LICENSE)
|
|
318
|
+
- **Author:** [Italo Almeida](https://github.com/italoalmeida0)
|
|
319
|
+
- **GitHub Repository:** [https://github.com/italoalmeida0/laya-system-one](https://github.com/italoalmeida0/laya-system-one)
|
|
320
|
+
|
|
321
|
+
### Upstream Attribution
|
|
322
|
+
This project incorporates and builds upon the foundational research and model architecture of **Laya** by [Convai Innovations](https://github.com/NandhaKishorM/laya) (licensed under Apache-2.0). All appropriate copyright notices and license requirements are preserved in compliance with Section 4 of the Apache License 2.0.
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { serve } from '../src/server.js';
|
|
4
|
+
|
|
5
|
+
const args = process.argv.slice(2);
|
|
6
|
+
|
|
7
|
+
function getArg(flag, defaultValue) {
|
|
8
|
+
const idx = args.indexOf(flag);
|
|
9
|
+
if (idx !== -1 && idx + 1 < args.length) {
|
|
10
|
+
return args[idx + 1];
|
|
11
|
+
}
|
|
12
|
+
return defaultValue;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
16
|
+
console.log(`
|
|
17
|
+
Laya System-One Decision Engine (TypeSafe Jev Wire-Compatible)
|
|
18
|
+
High-performance, self-contained inference server with WebGPU and WASM support.
|
|
19
|
+
|
|
20
|
+
Usage:
|
|
21
|
+
npx laya-system-one [options]
|
|
22
|
+
|
|
23
|
+
Options:
|
|
24
|
+
--port <number> HTTP port to bind (default: 8080 or PORT env)
|
|
25
|
+
--host <string> Host to bind (default: 0.0.0.0 or HOST env)
|
|
26
|
+
--device <type> Acceleration device: auto | webgpu | wasm | cpu (default: auto)
|
|
27
|
+
--api-key <string> Require Bearer token authentication (optional)
|
|
28
|
+
--help, -h Show this help message
|
|
29
|
+
|
|
30
|
+
Endpoints:
|
|
31
|
+
POST /v1/systemone Evaluate typed decisions (TypeSafe Jev wire protocol)
|
|
32
|
+
GET /health Server healthcheck probe
|
|
33
|
+
|
|
34
|
+
Example:
|
|
35
|
+
npx laya-system-one --port 8080 --device auto
|
|
36
|
+
`);
|
|
37
|
+
process.exit(0);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const port = parseInt(getArg('--port', process.env.PORT || '8080'), 10);
|
|
41
|
+
const host = getArg('--host', process.env.HOST || '0.0.0.0');
|
|
42
|
+
const device = getArg('--device', process.env.DEVICE || 'auto');
|
|
43
|
+
const apiKey = getArg('--api-key', process.env.LAYA_API_KEY || process.env.API_KEY || null);
|
|
44
|
+
|
|
45
|
+
console.log('='.repeat(68));
|
|
46
|
+
console.log(' LAYA SYSTEM-ONE DECISION SERVER (JEV COMPATIBLE) ');
|
|
47
|
+
console.log('='.repeat(68));
|
|
48
|
+
console.log(`Hardware Acceleration : ${device.toUpperCase()} (WebGPU -> Native CPU/WASM)`);
|
|
49
|
+
console.log(`Authentication : ${apiKey ? 'Enabled (Bearer token required)' : 'Disabled (Open local)'}`);
|
|
50
|
+
console.log(`Binding : ${host}:${port}`);
|
|
51
|
+
console.log('-'.repeat(68));
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
const { url } = await serve({ host, port, device, apiKey });
|
|
55
|
+
console.log(`✓ Laya System-One server active and ready!`);
|
|
56
|
+
console.log(`✓ Jev Evaluation Endpoint : ${url}/v1/systemone`);
|
|
57
|
+
console.log(`✓ Healthcheck Endpoint : ${url}/health`);
|
|
58
|
+
console.log('-'.repeat(68));
|
|
59
|
+
console.log('Quick verification (cURL):');
|
|
60
|
+
console.log(`curl -X POST ${url}/v1/systemone \\`);
|
|
61
|
+
console.log(' -H "Content-Type: application/json" \\');
|
|
62
|
+
if (apiKey) {
|
|
63
|
+
console.log(` -H "Authorization: Bearer ${apiKey}" \\`);
|
|
64
|
+
}
|
|
65
|
+
console.log(' -d \'{');
|
|
66
|
+
console.log(' "state": "We were billed twice on March invoice.",');
|
|
67
|
+
console.log(' "model": "laya-multilingual",');
|
|
68
|
+
console.log(' "questions": {');
|
|
69
|
+
console.log(' "department": {');
|
|
70
|
+
console.log(' "type": "choice",');
|
|
71
|
+
console.log(' "instructions": "Which department should handle this?",');
|
|
72
|
+
console.log(' "criteria": { "billing": "refunds and invoices", "tech": "bugs" }');
|
|
73
|
+
console.log(' }');
|
|
74
|
+
console.log(' }');
|
|
75
|
+
console.log(' }\'');
|
|
76
|
+
console.log('='.repeat(68));
|
|
77
|
+
console.log('Press Ctrl+C to stop the server.');
|
|
78
|
+
} catch (err) {
|
|
79
|
+
console.error('Failed to start server:', err);
|
|
80
|
+
process.exit(1);
|
|
81
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"encoder": "jhu-clsp/mmBERT-base",
|
|
3
|
+
"head_layers": 2,
|
|
4
|
+
"max_len": 1024,
|
|
5
|
+
"head_max_len": 256,
|
|
6
|
+
"max_prefixes": 6,
|
|
7
|
+
"act_costs": {
|
|
8
|
+
"escalate": 0.5
|
|
9
|
+
},
|
|
10
|
+
"cost_wrong_act": 3.0,
|
|
11
|
+
"amp_dtype": "bf16",
|
|
12
|
+
"model_name": "rl-agent",
|
|
13
|
+
"temperature": [
|
|
14
|
+
1.0,
|
|
15
|
+
1.0,
|
|
16
|
+
1.0
|
|
17
|
+
],
|
|
18
|
+
"temperature_by_options": {},
|
|
19
|
+
"training": {
|
|
20
|
+
"updates": 15987,
|
|
21
|
+
"epochs_completed": 4,
|
|
22
|
+
"hours": 4.97,
|
|
23
|
+
"world_size": 1,
|
|
24
|
+
"fine_tuned_from_checkpoint": false
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"bos_token": "<bos>",
|
|
3
|
+
"clean_up_tokenization_spaces": false,
|
|
4
|
+
"cls_token": "<bos>",
|
|
5
|
+
"eos_token": "<eos>",
|
|
6
|
+
"extra_special_tokens": {
|
|
7
|
+
"extra_0": "<start_of_turn>",
|
|
8
|
+
"extra_1": "<end_of_turn>"
|
|
9
|
+
},
|
|
10
|
+
"mask_token": "<mask>",
|
|
11
|
+
"model_input_names": [
|
|
12
|
+
"input_ids",
|
|
13
|
+
"attention_mask"
|
|
14
|
+
],
|
|
15
|
+
"model_max_length": 8192,
|
|
16
|
+
"pad_token": "<pad>",
|
|
17
|
+
"padding_side": "right",
|
|
18
|
+
"sep_token": "<eos>",
|
|
19
|
+
"spaces_between_special_tokens": false,
|
|
20
|
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
|
21
|
+
"unk_token": "<unk>"
|
|
22
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "laya-system-one",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Self-contained, ultra-fast System 1 decision engine with WebGPU/WASM acceleration, 100% wire-compatible with TypeSafe Jev (/v1/systemone). Runs offline in Node.js, Bun, and browsers.",
|
|
5
|
+
"main": "./src/index.js",
|
|
6
|
+
"module": "./src/index.js",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"bin": {
|
|
9
|
+
"laya-system-one": "./bin/cli.js"
|
|
10
|
+
},
|
|
11
|
+
"scripts": {
|
|
12
|
+
"start": "node ./bin/cli.js",
|
|
13
|
+
"test": "node ./test.js"
|
|
14
|
+
},
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/italoalmeida0/laya-system-one.git"
|
|
18
|
+
},
|
|
19
|
+
"keywords": [
|
|
20
|
+
"laya",
|
|
21
|
+
"system-one",
|
|
22
|
+
"decision-engine",
|
|
23
|
+
"jev",
|
|
24
|
+
"typesafe",
|
|
25
|
+
"webgpu",
|
|
26
|
+
"wasm",
|
|
27
|
+
"onnx",
|
|
28
|
+
"multilingual",
|
|
29
|
+
"classifier",
|
|
30
|
+
"triage",
|
|
31
|
+
"guardrails"
|
|
32
|
+
],
|
|
33
|
+
"author": "Italo Almeida <https://github.com/italoalmeida0>",
|
|
34
|
+
"license": "Apache-2.0",
|
|
35
|
+
"bugs": {
|
|
36
|
+
"url": "https://github.com/italoalmeida0/laya-system-one/issues"
|
|
37
|
+
},
|
|
38
|
+
"homepage": "https://github.com/italoalmeida0/laya-system-one#readme",
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@huggingface/transformers": "^4.3.0",
|
|
41
|
+
"onnxruntime-node": "^1.21.0",
|
|
42
|
+
"onnxruntime-web": "^1.21.0"
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/agent.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { loadTokenizer, buildSequence, QTYPES } from './tokenizer.js';
|
|
2
|
+
import { LayaEngine } from './engine.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Compute calibrated confidence score from probability distribution.
|
|
6
|
+
* Normalized between 0.0 and 1.0.
|
|
7
|
+
*/
|
|
8
|
+
function confidenceFromProbs(probs, k) {
|
|
9
|
+
if (k <= 1) return 1.0;
|
|
10
|
+
const pMax = Math.max(...probs);
|
|
11
|
+
const conf = (pMax - 1.0 / k) / (1.0 - 1.0 / k);
|
|
12
|
+
return Math.min(1.0, Math.max(0.0, conf));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Numerically stable softmax with temperature scaling.
|
|
17
|
+
*/
|
|
18
|
+
function softmax(arr, temperature = 1.0) {
|
|
19
|
+
const scaled = arr.map(x => x / Math.max(0.01, temperature));
|
|
20
|
+
const max = Math.max(...scaled);
|
|
21
|
+
const exp = scaled.map(x => Math.exp(x - max));
|
|
22
|
+
const sum = exp.reduce((a, b) => a + b, 0);
|
|
23
|
+
return exp.map(x => x / sum);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Laya Decision Engine
|
|
28
|
+
* High-performance System-1 non-autoregressive decision engine.
|
|
29
|
+
*/
|
|
30
|
+
export class Laya {
|
|
31
|
+
constructor(engine, tokenizer) {
|
|
32
|
+
this.engine = engine;
|
|
33
|
+
this.tokenizer = tokenizer;
|
|
34
|
+
this.config = engine.config;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Load Laya model and tokenizer.
|
|
39
|
+
* @param {Object} options - { modelDir, device: 'auto' | 'webgpu' | 'wasm' | 'cpu' }
|
|
40
|
+
*/
|
|
41
|
+
static async load(options = {}) {
|
|
42
|
+
const [engine, tokenizer] = await Promise.all([
|
|
43
|
+
LayaEngine.load(options),
|
|
44
|
+
loadTokenizer(options.modelDir)
|
|
45
|
+
]);
|
|
46
|
+
return new Laya(engine, tokenizer);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Evaluate a state against a map of typed questions (TypeSafe Jev wire protocol).
|
|
51
|
+
* @param {string | object | array} state - The content or structured data to evaluate.
|
|
52
|
+
* @param {Object<string, Object>} questions - Map of question definitions (choice, score, noul).
|
|
53
|
+
* @param {string} [requestedModel] - Optional model identifier to echo back.
|
|
54
|
+
* @returns {Promise<Object>} Formatted answer object matching TypeSafe Jev schema.
|
|
55
|
+
*/
|
|
56
|
+
async predict(state, questions = {}, requestedModel = null) {
|
|
57
|
+
const qids = Object.keys(questions);
|
|
58
|
+
const modelName = requestedModel || 'laya-multilingual';
|
|
59
|
+
|
|
60
|
+
if (qids.length === 0) {
|
|
61
|
+
return {
|
|
62
|
+
model: modelName,
|
|
63
|
+
answers: {},
|
|
64
|
+
usage: { input_tokens: 0, output_tokens: 0 }
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const maxLen = this.config.max_len || 1024;
|
|
69
|
+
const headMaxLen = this.config.head_max_len || 256;
|
|
70
|
+
const items = [];
|
|
71
|
+
let totalInputTokens = 0;
|
|
72
|
+
|
|
73
|
+
for (const qid of qids) {
|
|
74
|
+
const qdef = questions[qid];
|
|
75
|
+
if (!qdef || typeof qdef !== 'object') {
|
|
76
|
+
throw new Error(`Question '${qid}' must be an object.`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const qtype = qdef.type || 'choice';
|
|
80
|
+
if (!(qtype in QTYPES)) {
|
|
81
|
+
throw new Error(`Unsupported question type '${qtype}' for question '${qid}'. Must be 'choice', 'score', or 'noul'.`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const crit = qdef.criteria;
|
|
85
|
+
let ins = qdef.instructions || '';
|
|
86
|
+
if (typeof ins !== 'string') {
|
|
87
|
+
ins = JSON.stringify(ins);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const internalQ = {
|
|
91
|
+
t: qtype,
|
|
92
|
+
ins,
|
|
93
|
+
crit: qtype === 'choice' && Array.isArray(crit)
|
|
94
|
+
? Object.fromEntries(crit.map(c => [c, null]))
|
|
95
|
+
: (crit || {})
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const { ids, markers } = buildSequence(
|
|
99
|
+
this.tokenizer,
|
|
100
|
+
state,
|
|
101
|
+
internalQ,
|
|
102
|
+
maxLen,
|
|
103
|
+
headMaxLen
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
totalInputTokens += ids.length;
|
|
107
|
+
items.push({
|
|
108
|
+
qid,
|
|
109
|
+
q: internalQ,
|
|
110
|
+
qdef,
|
|
111
|
+
ids,
|
|
112
|
+
markers,
|
|
113
|
+
qtype: QTYPES[qtype] ?? 0
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const allLogits = await this.engine.run(items);
|
|
118
|
+
const answers = {};
|
|
119
|
+
|
|
120
|
+
for (let r = 0; r < items.length; r++) {
|
|
121
|
+
const item = items[r];
|
|
122
|
+
const qid = item.qid;
|
|
123
|
+
const q = item.q;
|
|
124
|
+
const qdef = item.qdef;
|
|
125
|
+
const k = item.markers.length;
|
|
126
|
+
const rowLogits = allLogits[r].slice(0, k);
|
|
127
|
+
|
|
128
|
+
// Temperature scaling
|
|
129
|
+
const qt = item.qtype;
|
|
130
|
+
const temp = (this.config.temperature && this.config.temperature[qt]) || 1.0;
|
|
131
|
+
const probs = softmax(rowLogits, temp);
|
|
132
|
+
const conf = Number(confidenceFromProbs(probs, k).toFixed(4));
|
|
133
|
+
|
|
134
|
+
if (q.t === 'choice') {
|
|
135
|
+
const keys = Object.keys(q.crit);
|
|
136
|
+
let maxIdx = 0;
|
|
137
|
+
let maxP = -1;
|
|
138
|
+
const probMap = {};
|
|
139
|
+
|
|
140
|
+
for (let i = 0; i < keys.length; i++) {
|
|
141
|
+
const p = Number(probs[i].toFixed(4));
|
|
142
|
+
probMap[keys[i]] = p;
|
|
143
|
+
if (p > maxP) {
|
|
144
|
+
maxP = p;
|
|
145
|
+
maxIdx = i;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
answers[qid] = {
|
|
150
|
+
type: 'choice',
|
|
151
|
+
choice: keys[maxIdx],
|
|
152
|
+
probabilities: probMap,
|
|
153
|
+
confidence: conf
|
|
154
|
+
};
|
|
155
|
+
} else if (q.t === 'score') {
|
|
156
|
+
let expectedScore = 0;
|
|
157
|
+
const probMap = {};
|
|
158
|
+
for (let i = 0; i < k; i++) {
|
|
159
|
+
const p = Number(probs[i].toFixed(4));
|
|
160
|
+
probMap[String(i)] = p;
|
|
161
|
+
expectedScore += i * p;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const legend = Array.isArray(q.crit)
|
|
165
|
+
? Object.fromEntries(q.crit.map((c, i) => [String(i), c]))
|
|
166
|
+
: q.crit;
|
|
167
|
+
|
|
168
|
+
answers[qid] = {
|
|
169
|
+
type: 'score',
|
|
170
|
+
score: Number(expectedScore.toFixed(4)),
|
|
171
|
+
legend,
|
|
172
|
+
probabilities: probMap,
|
|
173
|
+
confidence: conf
|
|
174
|
+
};
|
|
175
|
+
} else {
|
|
176
|
+
// noul (calibrated yes/no score)
|
|
177
|
+
const pTrue = probs[1] !== undefined ? probs[1] : 0.0;
|
|
178
|
+
const noulVal = Number(pTrue.toFixed(4));
|
|
179
|
+
const ans = {
|
|
180
|
+
type: 'noul',
|
|
181
|
+
noul: noulVal,
|
|
182
|
+
confidence: Number(Math.max(pTrue, 1.0 - pTrue).toFixed(4))
|
|
183
|
+
};
|
|
184
|
+
if (qdef.threshold !== undefined && qdef.threshold !== null) {
|
|
185
|
+
ans.threshold = Number(qdef.threshold);
|
|
186
|
+
ans.decision = noulVal >= ans.threshold;
|
|
187
|
+
}
|
|
188
|
+
answers[qid] = ans;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return {
|
|
193
|
+
model: modelName,
|
|
194
|
+
answers,
|
|
195
|
+
usage: {
|
|
196
|
+
input_tokens: totalInputTokens,
|
|
197
|
+
output_tokens: qids.length * 4
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
}
|
package/src/engine.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
7
|
+
const MODEL_RELEASE_URL = 'https://github.com/italoalmeida0/laya-system-one/releases/download/v1.0.0/model.onnx';
|
|
8
|
+
|
|
9
|
+
async function resolveModelPath(modelDir) {
|
|
10
|
+
const localPath = path.join(modelDir, 'model.onnx');
|
|
11
|
+
if (fs.existsSync(localPath)) {
|
|
12
|
+
return localPath;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Check user cache directory fallback if models dir is read-only
|
|
16
|
+
const cacheDir = path.join(os.homedir(), '.cache', 'laya-system-one');
|
|
17
|
+
const cachePath = path.join(cacheDir, 'model.onnx');
|
|
18
|
+
if (fs.existsSync(cachePath)) {
|
|
19
|
+
return cachePath;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let targetPath = localPath;
|
|
23
|
+
try {
|
|
24
|
+
if (!fs.existsSync(modelDir)) {
|
|
25
|
+
fs.mkdirSync(modelDir, { recursive: true });
|
|
26
|
+
}
|
|
27
|
+
const testFile = path.join(modelDir, '.test_write');
|
|
28
|
+
fs.writeFileSync(testFile, '');
|
|
29
|
+
fs.unlinkSync(testFile);
|
|
30
|
+
} catch (err) {
|
|
31
|
+
if (!fs.existsSync(cacheDir)) {
|
|
32
|
+
fs.mkdirSync(cacheDir, { recursive: true });
|
|
33
|
+
}
|
|
34
|
+
targetPath = cachePath;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
console.log(`[laya-system-one] Downloading INT8 model asset from GitHub Releases (~324 MB)...`);
|
|
38
|
+
console.log(`[laya-system-one] Source: ${MODEL_RELEASE_URL}`);
|
|
39
|
+
|
|
40
|
+
const res = await fetch(MODEL_RELEASE_URL);
|
|
41
|
+
if (!res.ok) {
|
|
42
|
+
throw new Error(`Failed to download model from ${MODEL_RELEASE_URL}: HTTP ${res.status} ${res.statusText}`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const total = parseInt(res.headers.get('content-length') || '324125608', 10);
|
|
46
|
+
let loaded = 0;
|
|
47
|
+
let lastLogged = 0;
|
|
48
|
+
|
|
49
|
+
const fileStream = fs.createWriteStream(targetPath);
|
|
50
|
+
const reader = res.body.getReader();
|
|
51
|
+
|
|
52
|
+
while (true) {
|
|
53
|
+
const { done, value } = await reader.read();
|
|
54
|
+
if (done) break;
|
|
55
|
+
fileStream.write(Buffer.from(value));
|
|
56
|
+
loaded += value.length;
|
|
57
|
+
const pct = Math.floor((loaded / total) * 100);
|
|
58
|
+
if (pct >= lastLogged + 10 || pct === 100) {
|
|
59
|
+
if (process.stdout && process.stdout.write) {
|
|
60
|
+
process.stdout.write(`\r[laya-system-one] Download progress: ${pct}% (${(loaded / (1024 * 1024)).toFixed(1)} MB / ${(total / (1024 * 1024)).toFixed(1)} MB)`);
|
|
61
|
+
}
|
|
62
|
+
lastLogged = pct;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
await new Promise((resolve, reject) => {
|
|
67
|
+
fileStream.end((err) => (err ? reject(err) : resolve()));
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
console.log(`\n[laya-system-one] Model ready at: ${targetPath}`);
|
|
71
|
+
return targetPath;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Dynamic runtime resolver:
|
|
75
|
+
// - In Node.js: uses onnxruntime-node (Native C++ CPU at ~15ms + Native WebGPU)
|
|
76
|
+
// - In Bun / Browser: uses onnxruntime-web (WASM SIMD + Browser WebGPU via navigator.gpu)
|
|
77
|
+
async function getOrt() {
|
|
78
|
+
const isBun = typeof Bun !== 'undefined';
|
|
79
|
+
const isBrowser = typeof window !== 'undefined';
|
|
80
|
+
|
|
81
|
+
if (!isBun && !isBrowser) {
|
|
82
|
+
try {
|
|
83
|
+
const mod = await import('onnxruntime-node');
|
|
84
|
+
return mod.default || mod;
|
|
85
|
+
} catch (err) {
|
|
86
|
+
// fallback to onnxruntime-web
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const mod = await import('onnxruntime-web');
|
|
91
|
+
return mod.default || mod;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export class LayaEngine {
|
|
95
|
+
constructor(session, config, ort) {
|
|
96
|
+
this.session = session;
|
|
97
|
+
this.config = config;
|
|
98
|
+
this.ort = ort;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
static async load(options = {}) {
|
|
102
|
+
const ort = await getOrt();
|
|
103
|
+
const modelDir = options.modelDir || path.resolve(__dirname, '../models');
|
|
104
|
+
const modelPath = await resolveModelPath(modelDir);
|
|
105
|
+
const configPath = path.join(modelDir, 'rl_agent_config.json');
|
|
106
|
+
|
|
107
|
+
let config = {
|
|
108
|
+
max_len: 1024,
|
|
109
|
+
head_max_len: 256,
|
|
110
|
+
temperature: [1.0, 1.0, 1.0],
|
|
111
|
+
temperature_by_options: {}
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
if (fs.existsSync(configPath)) {
|
|
115
|
+
try {
|
|
116
|
+
config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
|
117
|
+
} catch (e) {
|
|
118
|
+
// fallback
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const device = options.device || 'auto';
|
|
123
|
+
let executionProviders;
|
|
124
|
+
|
|
125
|
+
if (device === 'webgpu') {
|
|
126
|
+
executionProviders = ['webgpu'];
|
|
127
|
+
} else if (device === 'wasm' || device === 'cpu') {
|
|
128
|
+
executionProviders = typeof Bun !== 'undefined' || typeof window !== 'undefined' ? ['wasm'] : ['cpu'];
|
|
129
|
+
} else {
|
|
130
|
+
// auto
|
|
131
|
+
executionProviders = typeof Bun !== 'undefined' || typeof window !== 'undefined'
|
|
132
|
+
? ['webgpu', 'wasm']
|
|
133
|
+
: ['webgpu', 'cpu'];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const sessionOptions = {
|
|
137
|
+
executionProviders,
|
|
138
|
+
graphOptimizationLevel: 'all'
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const session = await ort.InferenceSession.create(modelPath, sessionOptions);
|
|
142
|
+
return new LayaEngine(session, config, ort);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async runSingle(item) {
|
|
146
|
+
const seqLen = item.ids.length;
|
|
147
|
+
const numMarkers = item.markers.length;
|
|
148
|
+
|
|
149
|
+
const inputIdsData = new BigInt64Array(seqLen);
|
|
150
|
+
const attentionMaskData = new BigInt64Array(seqLen);
|
|
151
|
+
const markerPosData = new BigInt64Array(numMarkers);
|
|
152
|
+
const markerMaskData = new Uint8Array(numMarkers);
|
|
153
|
+
const qtypeData = new BigInt64Array([BigInt(item.qtype)]);
|
|
154
|
+
|
|
155
|
+
for (let c = 0; c < seqLen; c++) {
|
|
156
|
+
inputIdsData[c] = BigInt(item.ids[c]);
|
|
157
|
+
attentionMaskData[c] = 1n;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
for (let m = 0; m < numMarkers; m++) {
|
|
161
|
+
markerPosData[m] = BigInt(item.markers[m]);
|
|
162
|
+
markerMaskData[m] = 1;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const feeds = {
|
|
166
|
+
input_ids: new this.ort.Tensor('int64', inputIdsData, [1, seqLen]),
|
|
167
|
+
attention_mask: new this.ort.Tensor('int64', attentionMaskData, [1, seqLen]),
|
|
168
|
+
marker_pos: new this.ort.Tensor('int64', markerPosData, [1, numMarkers]),
|
|
169
|
+
marker_mask: new this.ort.Tensor('bool', markerMaskData, [1, numMarkers]),
|
|
170
|
+
qtype: new this.ort.Tensor('int64', qtypeData, [1])
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const results = await this.session.run(feeds);
|
|
174
|
+
return Array.from(results.logits.data);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async run(batch) {
|
|
178
|
+
const allLogits = [];
|
|
179
|
+
for (const item of batch) {
|
|
180
|
+
const logits = await this.runSingle(item);
|
|
181
|
+
allLogits.push(logits);
|
|
182
|
+
}
|
|
183
|
+
return allLogits;
|
|
184
|
+
}
|
|
185
|
+
}
|
package/src/index.js
ADDED
package/src/server.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import { Laya } from './agent.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Start HTTP server exposing the TypeSafe Jev /v1/systemone wire protocol.
|
|
6
|
+
* @param {Object} options - Server options:
|
|
7
|
+
* - host: string (default: '0.0.0.0' or process.env.HOST)
|
|
8
|
+
* - port: number (default: 8080 or process.env.PORT)
|
|
9
|
+
* - apiKey: string (optional, or process.env.LAYA_API_KEY / process.env.API_KEY)
|
|
10
|
+
* - laya: preloaded Laya instance (optional)
|
|
11
|
+
* - device: 'auto' | 'webgpu' | 'wasm' | 'cpu' (default: 'auto')
|
|
12
|
+
* @returns {Promise<{ server: http.Server, url: string, close: Function }>}
|
|
13
|
+
*/
|
|
14
|
+
export async function serve(options = {}) {
|
|
15
|
+
const host = options.host || process.env.HOST || '0.0.0.0';
|
|
16
|
+
const port = parseInt(options.port || process.env.PORT || '8080', 10);
|
|
17
|
+
const apiKey = options.apiKey || process.env.LAYA_API_KEY || process.env.API_KEY || null;
|
|
18
|
+
const laya = options.laya || (await Laya.load(options));
|
|
19
|
+
|
|
20
|
+
const server = http.createServer(async (req, res) => {
|
|
21
|
+
// Standard CORS headers
|
|
22
|
+
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
23
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
24
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
25
|
+
|
|
26
|
+
// Handle preflight OPTIONS request
|
|
27
|
+
if (req.method === 'OPTIONS') {
|
|
28
|
+
res.writeHead(204);
|
|
29
|
+
res.end();
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
|
34
|
+
|
|
35
|
+
// Healthcheck endpoint
|
|
36
|
+
if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/health')) {
|
|
37
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
38
|
+
res.end(JSON.stringify({
|
|
39
|
+
status: 'ok',
|
|
40
|
+
model: 'laya-multilingual',
|
|
41
|
+
version: '1.0.0',
|
|
42
|
+
protocol: 'TypeSafe Jev /v1/systemone compatible'
|
|
43
|
+
}));
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// TypeSafe Jev evaluation endpoint
|
|
48
|
+
if (req.method === 'POST' && url.pathname === '/v1/systemone') {
|
|
49
|
+
// Optional bearer token authentication
|
|
50
|
+
if (apiKey) {
|
|
51
|
+
const authHeader = req.headers['authorization'] || '';
|
|
52
|
+
if (authHeader !== `Bearer ${apiKey}`) {
|
|
53
|
+
res.writeHead(401, { 'Content-Type': 'application/json' });
|
|
54
|
+
res.end(JSON.stringify({
|
|
55
|
+
error: 'Unauthorized: missing or invalid bearer token in Authorization header.'
|
|
56
|
+
}));
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let body = '';
|
|
62
|
+
req.on('data', chunk => {
|
|
63
|
+
body += chunk;
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
req.on('end', async () => {
|
|
67
|
+
let payload;
|
|
68
|
+
try {
|
|
69
|
+
payload = JSON.parse(body);
|
|
70
|
+
} catch (e) {
|
|
71
|
+
res.writeHead(422, { 'Content-Type': 'application/json' });
|
|
72
|
+
res.end(JSON.stringify({
|
|
73
|
+
error: 'Unprocessable Entity: invalid JSON payload.'
|
|
74
|
+
}));
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const state = payload.state;
|
|
79
|
+
const questions = payload.questions;
|
|
80
|
+
const requestedModel = payload.model || null;
|
|
81
|
+
|
|
82
|
+
if (state === undefined || state === null) {
|
|
83
|
+
res.writeHead(422, { 'Content-Type': 'application/json' });
|
|
84
|
+
res.end(JSON.stringify({
|
|
85
|
+
error: "Unprocessable Entity: missing required 'state' field."
|
|
86
|
+
}));
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (!questions || typeof questions !== 'object' || Array.isArray(questions)) {
|
|
91
|
+
res.writeHead(422, { 'Content-Type': 'application/json' });
|
|
92
|
+
res.end(JSON.stringify({
|
|
93
|
+
error: "Unprocessable Entity: 'questions' must be an object map of typed questions."
|
|
94
|
+
}));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
const result = await laya.predict(state, questions, requestedModel);
|
|
100
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
101
|
+
res.end(JSON.stringify(result));
|
|
102
|
+
} catch (err) {
|
|
103
|
+
res.writeHead(422, { 'Content-Type': 'application/json' });
|
|
104
|
+
res.end(JSON.stringify({
|
|
105
|
+
error: `Evaluation failed: ${err.message || err}`
|
|
106
|
+
}));
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// 404 handler
|
|
113
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
114
|
+
res.end(JSON.stringify({
|
|
115
|
+
error: `Not found: ${req.method} ${url.pathname}. Expected POST /v1/systemone`
|
|
116
|
+
}));
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
return new Promise((resolve, reject) => {
|
|
120
|
+
server.listen(port, host, () => {
|
|
121
|
+
const displayHost = host === '0.0.0.0' ? 'localhost' : host;
|
|
122
|
+
const url = `http://${displayHost}:${port}`;
|
|
123
|
+
resolve({ server, url, close: () => server.close() });
|
|
124
|
+
});
|
|
125
|
+
server.on('error', reject);
|
|
126
|
+
});
|
|
127
|
+
}
|
package/src/tokenizer.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import * as ort from 'onnxruntime-web';
|
|
5
|
+
|
|
6
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
7
|
+
|
|
8
|
+
// Ensure ONNX runtime symbol is bound for web build compatibility in Bun/Web
|
|
9
|
+
const ORT_SYMBOL = Symbol.for('onnxruntime');
|
|
10
|
+
if (!(ORT_SYMBOL in globalThis)) {
|
|
11
|
+
globalThis[ORT_SYMBOL] = ort;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const QTYPES = {
|
|
15
|
+
choice: 0,
|
|
16
|
+
score: 1,
|
|
17
|
+
noul: 2,
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export function serializeState(state) {
|
|
21
|
+
if (typeof state === 'string') return state;
|
|
22
|
+
return JSON.stringify(state);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function renderCriterion(value) {
|
|
26
|
+
if (typeof value === 'string') return value;
|
|
27
|
+
return JSON.stringify(value);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function renderOptions(q) {
|
|
31
|
+
const t = q.t;
|
|
32
|
+
const crit = q.crit || {};
|
|
33
|
+
|
|
34
|
+
if (t === 'choice') {
|
|
35
|
+
return Object.entries(crit).map(([k, v]) => {
|
|
36
|
+
if (v === null || v === undefined || v === '') return k;
|
|
37
|
+
return `${k}: ${renderCriterion(v)}`;
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (t === 'score') {
|
|
42
|
+
if (Array.isArray(crit)) {
|
|
43
|
+
return crit.map((c, i) => `level ${i}: ${renderCriterion(c)}`);
|
|
44
|
+
}
|
|
45
|
+
return Object.entries(crit).map(([k, v]) => `level ${k}: ${renderCriterion(v)}`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// noul
|
|
49
|
+
const falseCrit = crit.false;
|
|
50
|
+
const trueCrit = crit.true;
|
|
51
|
+
const falseText = falseCrit ? renderCriterion(falseCrit) : 'no, the statement does not hold';
|
|
52
|
+
const trueText = trueCrit ? renderCriterion(trueCrit) : 'yes, the statement holds';
|
|
53
|
+
return [`false: ${falseText}`, `true: ${trueText}`];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function buildSequence(tok, state, q, maxLen = 1024, headMaxLen = 256) {
|
|
57
|
+
const maskTok = tok.mask_token || '<mask>';
|
|
58
|
+
const maskTokenId = tok.mask_token_id ?? 4;
|
|
59
|
+
const clsTokenId = tok.cls_token_id ?? 2;
|
|
60
|
+
const sepTokenId = tok.sep_token_id ?? 1;
|
|
61
|
+
|
|
62
|
+
const opts = renderOptions(q);
|
|
63
|
+
const ins = String(q.ins).replaceAll(maskTok, ' ');
|
|
64
|
+
|
|
65
|
+
const headEncoded = tok(`${q.t} question: ${ins}`, { add_special_tokens: false });
|
|
66
|
+
let headIds = Array.from(headEncoded.input_ids.data || headEncoded.input_ids).map(Number);
|
|
67
|
+
|
|
68
|
+
const optIds = [];
|
|
69
|
+
for (const opt of opts) {
|
|
70
|
+
const optEncoded = tok(` ${opt.replaceAll(maskTok, ' ')}`, { add_special_tokens: false });
|
|
71
|
+
const rawIds = Array.from(optEncoded.input_ids.data || optEncoded.input_ids).map(Number);
|
|
72
|
+
optIds.push([maskTokenId, ...rawIds.slice(0, 48)]);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
let optBudget = headMaxLen - optIds.reduce((sum, o) => sum + o.length, 0);
|
|
76
|
+
if (optBudget < 16) {
|
|
77
|
+
const per = Math.max(4, Math.floor((headMaxLen - 16) / Math.max(1, optIds.length)));
|
|
78
|
+
for (let i = 0; i < optIds.length; i++) {
|
|
79
|
+
optIds[i] = optIds[i].slice(0, per);
|
|
80
|
+
}
|
|
81
|
+
optBudget = headMaxLen - optIds.reduce((sum, o) => sum + o.length, 0);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
headIds = headIds.slice(0, Math.max(8, optBudget));
|
|
85
|
+
const ids = [clsTokenId, ...headIds, sepTokenId];
|
|
86
|
+
const markers = [];
|
|
87
|
+
|
|
88
|
+
for (const o of optIds) {
|
|
89
|
+
markers.push(ids.length);
|
|
90
|
+
ids.push(...o);
|
|
91
|
+
}
|
|
92
|
+
ids.push(sepTokenId);
|
|
93
|
+
|
|
94
|
+
const room = Math.max(0, maxLen - ids.length - 1);
|
|
95
|
+
const stateStr = serializeState(state).replaceAll(maskTok, ' ');
|
|
96
|
+
const stEncoded = tok(stateStr, { add_special_tokens: false });
|
|
97
|
+
const stIds = Array.from(stEncoded.input_ids.data || stEncoded.input_ids).map(Number);
|
|
98
|
+
|
|
99
|
+
const stateTruncated = stIds.slice(0, room);
|
|
100
|
+
ids.push(...stateTruncated, sepTokenId);
|
|
101
|
+
|
|
102
|
+
const finalIds = ids.slice(0, maxLen);
|
|
103
|
+
const finalMarkers = markers.filter(m => m < maxLen);
|
|
104
|
+
|
|
105
|
+
return { ids: finalIds, markers: finalMarkers };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export async function loadTokenizer(modelDir) {
|
|
109
|
+
const dir = modelDir || path.resolve(__dirname, '../models');
|
|
110
|
+
const isBun = typeof Bun !== 'undefined';
|
|
111
|
+
|
|
112
|
+
if (isBun) {
|
|
113
|
+
const req = createRequire(import.meta.url);
|
|
114
|
+
const resolved = req.resolve('@huggingface/transformers');
|
|
115
|
+
const webPath = resolved.replace(/transformers\.node\.(cjs|mjs)/, 'transformers.web.js');
|
|
116
|
+
const mod = await import(pathToFileURL(webPath).href);
|
|
117
|
+
return await mod.AutoTokenizer.from_pretrained(pathToFileURL(dir).href);
|
|
118
|
+
} else {
|
|
119
|
+
const mod = await import('@huggingface/transformers');
|
|
120
|
+
return await mod.AutoTokenizer.from_pretrained(dir, { local_files_only: true });
|
|
121
|
+
}
|
|
122
|
+
}
|