catalyst-ai 0.1.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/README.md +30 -0
- package/android/.gradle/8.9/checksums/checksums.lock +0 -0
- package/android/.gradle/8.9/dependencies-accessors/gc.properties +0 -0
- package/android/.gradle/8.9/fileChanges/last-build.bin +0 -0
- package/android/.gradle/8.9/fileHashes/fileHashes.lock +0 -0
- package/android/.gradle/8.9/gc.properties +0 -0
- package/android/.gradle/9.2.0/checksums/checksums.lock +0 -0
- package/android/.gradle/9.2.0/fileChanges/last-build.bin +0 -0
- package/android/.gradle/9.2.0/fileHashes/fileHashes.bin +0 -0
- package/android/.gradle/9.2.0/fileHashes/fileHashes.lock +0 -0
- package/android/.gradle/9.2.0/gc.properties +0 -0
- package/android/.gradle/buildOutputCleanup/buildOutputCleanup.lock +0 -0
- package/android/.gradle/buildOutputCleanup/cache.properties +2 -0
- package/android/.gradle/vcs-1/gc.properties +0 -0
- package/android/build.gradle.kts +47 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/io/catalyst/nativeai/AIBridge.kt +24 -0
- package/android/src/main/java/io/catalyst/nativeai/CatalystAIBridge.kt +79 -0
- package/android/src/main/java/io/catalyst/nativeai/NativeBridgeAI.kt +293 -0
- package/android/src/main/resources/META-INF/services/io.catalyst.nativeai.AIBridge +1 -0
- package/package.json +27 -0
- package/scripts/check-peer.js +11 -0
- package/src/buildAttachmentSystemPrompt.js +19 -0
- package/src/index.js +4 -0
- package/src/metrics.js +210 -0
- package/src/pricing.js +14 -0
- package/src/route.js +529 -0
- package/src/useCloudAI.js +315 -0
- package/src/useNativeAI.js +308 -0
- package/src/useWebAI.js +385 -0
package/src/useWebAI.js
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import { useState, useRef, useCallback, useMemo, useEffect } from "react"
|
|
2
|
+
import { aggregateWebSessionMetrics } from "./metrics.js"
|
|
3
|
+
|
|
4
|
+
const schedule = typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : (fn) => setTimeout(fn, 16)
|
|
5
|
+
const cancelSchedule = typeof cancelAnimationFrame !== "undefined" ? cancelAnimationFrame : clearTimeout
|
|
6
|
+
|
|
7
|
+
// EXPERIMENTAL: in-browser inference via Transformers.js is not efficient or reliable yet —
|
|
8
|
+
// generation quality/instruction-following degrades noticeably on larger models (e.g. Llama 3)
|
|
9
|
+
// versus useCloudAI/useNativeAI, and WebGPU/WASM backend selection is unpredictable across
|
|
10
|
+
// devices. Treat this provider as a demo/fallback path, not production-ready, until revisited.
|
|
11
|
+
|
|
12
|
+
const TRANSFORMERS_CDN = "https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.2.0/dist/transformers.min.js"
|
|
13
|
+
|
|
14
|
+
const WORKER_SCRIPT = `
|
|
15
|
+
const TRANSFORMERS_CDN = "${TRANSFORMERS_CDN}";
|
|
16
|
+
let pipe = null;
|
|
17
|
+
let TextStreamer = null;
|
|
18
|
+
let loadedModel = null;
|
|
19
|
+
let loadedDevice = null;
|
|
20
|
+
|
|
21
|
+
async function loadPipeline(model) {
|
|
22
|
+
if (loadedModel === model && pipe) {
|
|
23
|
+
self.postMessage({ type: "log", msg: "[worker] pipeline cache hit — " + model + " on " + loadedDevice });
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
self.postMessage({ type: "log", msg: "[worker] importing transformers from CDN..." });
|
|
28
|
+
const mod = await import(TRANSFORMERS_CDN);
|
|
29
|
+
mod.env.allowLocalModels = false;
|
|
30
|
+
TextStreamer = mod.TextStreamer;
|
|
31
|
+
|
|
32
|
+
const backends = [
|
|
33
|
+
{ device: "webgpu", dtype: "q4f16" },
|
|
34
|
+
{ device: "wasm", dtype: "q4" },
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
let lastErr = null;
|
|
38
|
+
for (const { device, dtype } of backends) {
|
|
39
|
+
try {
|
|
40
|
+
self.postMessage({ type: "log", msg: "[worker] trying device=" + device + " dtype=" + dtype });
|
|
41
|
+
const fileTotals = {};
|
|
42
|
+
const dlStart = performance.now();
|
|
43
|
+
|
|
44
|
+
pipe = await mod.pipeline("text-generation", model, {
|
|
45
|
+
device,
|
|
46
|
+
dtype,
|
|
47
|
+
progress_callback: (info) => {
|
|
48
|
+
const { status, file, name, loaded, total } = info;
|
|
49
|
+
const pct = total > 0 ? Math.round((loaded / total) * 100) : null;
|
|
50
|
+
if (total) fileTotals[file || name] = total;
|
|
51
|
+
if (status === "initiate") {
|
|
52
|
+
self.postMessage({ type: "progress", file: file || name, percent: 0, status: "initiate" });
|
|
53
|
+
self.postMessage({ type: "log", msg: "[worker] download initiate: " + (file || name) });
|
|
54
|
+
} else if (status === "download" || status === "progress") {
|
|
55
|
+
self.postMessage({ type: "progress", file: file || name, percent: pct, loaded, total, status: "downloading" });
|
|
56
|
+
} else if (status === "done") {
|
|
57
|
+
self.postMessage({ type: "progress", file: file || name, percent: 100, status: "done" });
|
|
58
|
+
self.postMessage({ type: "log", msg: "[worker] download done: " + (file || name) });
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
loadedModel = model;
|
|
64
|
+
loadedDevice = device;
|
|
65
|
+
const loadMs = Math.round(performance.now() - dlStart);
|
|
66
|
+
const totalBytes = Object.values(fileTotals).reduce((sum, n) => sum + n, 0);
|
|
67
|
+
self.postMessage({ type: "model_ready", device, dtype, loadMs, totalBytes });
|
|
68
|
+
self.postMessage({ type: "log", msg: "[worker] pipeline ready — device=" + device + " loadMs=" + loadMs });
|
|
69
|
+
return;
|
|
70
|
+
} catch (err) {
|
|
71
|
+
self.postMessage({ type: "log", msg: "[worker] " + device + " failed (" + err.message + "), trying next..." });
|
|
72
|
+
lastErr = err;
|
|
73
|
+
pipe = null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
throw lastErr || new Error("All backends failed");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
self.onmessage = async (e) => {
|
|
80
|
+
const { type, model, messages, genConfig, formatPrompt } = e.data;
|
|
81
|
+
if (type !== "generate") return;
|
|
82
|
+
|
|
83
|
+
try {
|
|
84
|
+
await loadPipeline(model);
|
|
85
|
+
|
|
86
|
+
let pipeInput;
|
|
87
|
+
if (formatPrompt) {
|
|
88
|
+
try {
|
|
89
|
+
const overrideFn = new Function("return (" + formatPrompt + ")")();
|
|
90
|
+
const text = overrideFn(messages);
|
|
91
|
+
pipeInput = text;
|
|
92
|
+
self.postMessage({ type: "log", msg: "[worker] using custom formatPrompt (" + text.length + " chars)" });
|
|
93
|
+
} catch (err) {
|
|
94
|
+
self.postMessage({ type: "log", msg: "[worker] formatPrompt failed (" + err.message + "), falling back to tokenizer template" });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (!pipeInput) {
|
|
98
|
+
try {
|
|
99
|
+
const text = pipe.tokenizer.apply_chat_template(messages, { tokenize: false, add_generation_prompt: true });
|
|
100
|
+
pipeInput = text;
|
|
101
|
+
self.postMessage({ type: "log", msg: "[worker] chat template applied (" + text.length + " chars)" });
|
|
102
|
+
} catch (err) {
|
|
103
|
+
pipeInput = messages;
|
|
104
|
+
self.postMessage({ type: "log", msg: "[worker] no chat template (" + err.message + "), passing messages array" });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const pipeInputType = typeof pipeInput === "string" ? "string" : Array.isArray(pipeInput) ? "messages[]" : typeof pipeInput;
|
|
109
|
+
const pipeInputLength = typeof pipeInput === "string" ? pipeInput.length : Array.isArray(pipeInput) ? pipeInput.length : 0;
|
|
110
|
+
self.postMessage({ type: "log", msg: "[worker] pipe input: type=" + pipeInputType + " length=" + pipeInputLength });
|
|
111
|
+
self.postMessage({ type: "streaming_start" });
|
|
112
|
+
|
|
113
|
+
let tokenCount = 0;
|
|
114
|
+
let ttftFired = false;
|
|
115
|
+
const tGen = performance.now();
|
|
116
|
+
|
|
117
|
+
let batch = "";
|
|
118
|
+
let batchTimer = null;
|
|
119
|
+
const flushBatch = () => {
|
|
120
|
+
batchTimer = null;
|
|
121
|
+
if (!batch) return;
|
|
122
|
+
self.postMessage({ type: "token", text: batch });
|
|
123
|
+
batch = "";
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const streamer = new TextStreamer(pipe.tokenizer, {
|
|
127
|
+
skip_prompt: true,
|
|
128
|
+
skip_special_tokens: true,
|
|
129
|
+
token_callback_function: () => {
|
|
130
|
+
if (!ttftFired) {
|
|
131
|
+
ttftFired = true;
|
|
132
|
+
self.postMessage({ type: "ttft", ms: Math.round(performance.now() - tGen) });
|
|
133
|
+
}
|
|
134
|
+
tokenCount++;
|
|
135
|
+
},
|
|
136
|
+
callback_function: (text) => {
|
|
137
|
+
batch += text;
|
|
138
|
+
if (tokenCount % 8 === 0) { clearTimeout(batchTimer); flushBatch(); }
|
|
139
|
+
else if (!batchTimer) { batchTimer = setTimeout(flushBatch, 80); }
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
const { maxTokens, temperature, topP, repetitionPenalty, noRepeatNgramSize, earlyStop, ...rest } = genConfig;
|
|
144
|
+
await pipe(pipeInput, {
|
|
145
|
+
max_new_tokens: maxTokens,
|
|
146
|
+
do_sample: temperature > 0,
|
|
147
|
+
temperature,
|
|
148
|
+
top_p: topP,
|
|
149
|
+
repetition_penalty: repetitionPenalty,
|
|
150
|
+
no_repeat_ngram_size: noRepeatNgramSize ?? 3,
|
|
151
|
+
early_stopping: earlyStop ?? true,
|
|
152
|
+
...rest,
|
|
153
|
+
streamer,
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
clearTimeout(batchTimer);
|
|
157
|
+
flushBatch();
|
|
158
|
+
|
|
159
|
+
const genMs = Math.round(performance.now() - tGen);
|
|
160
|
+
const tps = tokenCount > 0 ? parseFloat((tokenCount / (genMs / 1000)).toFixed(1)) : 0;
|
|
161
|
+
self.postMessage({ type: "done", totalTokens: tokenCount, genMs, tps });
|
|
162
|
+
} catch (err) {
|
|
163
|
+
self.postMessage({ type: "error", message: err.message || String(err) });
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
`
|
|
167
|
+
|
|
168
|
+
let workerBlobUrl = null
|
|
169
|
+
function getWorkerBlobUrl() {
|
|
170
|
+
if (!workerBlobUrl) {
|
|
171
|
+
const blob = new Blob([WORKER_SCRIPT], { type: "application/javascript" })
|
|
172
|
+
workerBlobUrl = URL.createObjectURL(blob)
|
|
173
|
+
}
|
|
174
|
+
return workerBlobUrl
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function useWebAI({
|
|
178
|
+
model: modelProp,
|
|
179
|
+
formatPrompt,
|
|
180
|
+
genConfig: genConfigProp = {},
|
|
181
|
+
defaultGenConfig = {},
|
|
182
|
+
sessionMode = "stateless",
|
|
183
|
+
} = {}) {
|
|
184
|
+
// stable merged genConfig — only changes when values actually change
|
|
185
|
+
const hookGenConfig = useMemo(
|
|
186
|
+
() => ({ ...defaultGenConfig, ...genConfigProp }),
|
|
187
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
188
|
+
[JSON.stringify(defaultGenConfig), JSON.stringify(genConfigProp)]
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
const [output, setOutput] = useState("")
|
|
192
|
+
const [streaming, setStreaming] = useState(false)
|
|
193
|
+
const [loading, setLoading] = useState(false)
|
|
194
|
+
const [error, setError] = useState(null)
|
|
195
|
+
const [modelReady, setModelReady] = useState(false)
|
|
196
|
+
const [downloadProgress, setDownloadProgress] = useState(null)
|
|
197
|
+
const [metrics, setMetrics] = useState(null)
|
|
198
|
+
|
|
199
|
+
const workerRef = useRef(null)
|
|
200
|
+
const outputAccRef = useRef("")
|
|
201
|
+
const rafRef = useRef(null)
|
|
202
|
+
const cancelledRef = useRef(false)
|
|
203
|
+
const historyRef = useRef([])
|
|
204
|
+
const messagesRef = useRef([])
|
|
205
|
+
const conversationIdRef = useRef(null)
|
|
206
|
+
|
|
207
|
+
useEffect(() => () => {
|
|
208
|
+
if (rafRef.current) { cancelSchedule(rafRef.current); rafRef.current = null }
|
|
209
|
+
if (workerRef.current) { workerRef.current.terminate(); workerRef.current = null }
|
|
210
|
+
}, [])
|
|
211
|
+
|
|
212
|
+
const formatPromptRef = useRef(formatPrompt)
|
|
213
|
+
formatPromptRef.current = formatPrompt
|
|
214
|
+
|
|
215
|
+
const generate = useCallback(
|
|
216
|
+
({ messages, genConfig: callGenConfig = {}, model: callModel }) => {
|
|
217
|
+
if (workerRef.current) {
|
|
218
|
+
workerRef.current.terminate()
|
|
219
|
+
workerRef.current = null
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const resolvedModel = callModel || modelProp
|
|
223
|
+
if (!resolvedModel) {
|
|
224
|
+
setError(new Error("[catalyst-ai/useWebAI] no model specified — pass model prop or per-call model"))
|
|
225
|
+
return
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const genConfig = { ...hookGenConfig, ...callGenConfig }
|
|
229
|
+
const resolvedMessages = sessionMode === "stateful" ? [...messagesRef.current, ...messages] : messages
|
|
230
|
+
|
|
231
|
+
setLoading(true)
|
|
232
|
+
setOutput("")
|
|
233
|
+
setError(null)
|
|
234
|
+
setDownloadProgress(null)
|
|
235
|
+
setMetrics(null)
|
|
236
|
+
setModelReady(false)
|
|
237
|
+
cancelledRef.current = false
|
|
238
|
+
outputAccRef.current = ""
|
|
239
|
+
if (rafRef.current) { cancelSchedule(rafRef.current); rafRef.current = null }
|
|
240
|
+
|
|
241
|
+
const metricsAcc = { device: null, dtype: null, loadMs: null, downloadBytes: 0, ttftMs: null, tps: null, totalTokens: null, genMs: null }
|
|
242
|
+
|
|
243
|
+
let worker
|
|
244
|
+
try {
|
|
245
|
+
worker = new Worker(getWorkerBlobUrl(), { type: "module" })
|
|
246
|
+
} catch (err) {
|
|
247
|
+
setError(new Error("[catalyst-ai/useWebAI] module worker unavailable: " + (err.message || String(err))))
|
|
248
|
+
setLoading(false)
|
|
249
|
+
return
|
|
250
|
+
}
|
|
251
|
+
workerRef.current = worker
|
|
252
|
+
|
|
253
|
+
worker.onmessage = (e) => {
|
|
254
|
+
const msg = e.data
|
|
255
|
+
switch (msg.type) {
|
|
256
|
+
case "log":
|
|
257
|
+
console.log(msg.msg)
|
|
258
|
+
break
|
|
259
|
+
case "progress":
|
|
260
|
+
setDownloadProgress({ file: msg.file, percent: msg.percent, status: msg.status })
|
|
261
|
+
if (msg.total) metricsAcc.downloadBytes = Math.max(metricsAcc.downloadBytes, msg.total)
|
|
262
|
+
break
|
|
263
|
+
case "model_ready":
|
|
264
|
+
metricsAcc.device = msg.device
|
|
265
|
+
metricsAcc.dtype = msg.dtype
|
|
266
|
+
metricsAcc.loadMs = msg.loadMs
|
|
267
|
+
if (msg.totalBytes) metricsAcc.downloadBytes = msg.totalBytes
|
|
268
|
+
setModelReady(true)
|
|
269
|
+
setDownloadProgress(null)
|
|
270
|
+
break
|
|
271
|
+
case "streaming_start":
|
|
272
|
+
setLoading(false)
|
|
273
|
+
setStreaming(true)
|
|
274
|
+
break
|
|
275
|
+
case "ttft":
|
|
276
|
+
metricsAcc.ttftMs = msg.ms
|
|
277
|
+
break
|
|
278
|
+
case "token":
|
|
279
|
+
outputAccRef.current += msg.text
|
|
280
|
+
if (!rafRef.current) {
|
|
281
|
+
rafRef.current = schedule(() => {
|
|
282
|
+
rafRef.current = null
|
|
283
|
+
setOutput(outputAccRef.current)
|
|
284
|
+
})
|
|
285
|
+
}
|
|
286
|
+
break
|
|
287
|
+
case "done":
|
|
288
|
+
if (rafRef.current) { cancelSchedule(rafRef.current) }
|
|
289
|
+
rafRef.current = null
|
|
290
|
+
setOutput(outputAccRef.current)
|
|
291
|
+
metricsAcc.tps = msg.tps
|
|
292
|
+
metricsAcc.totalTokens = msg.totalTokens
|
|
293
|
+
metricsAcc.genMs = msg.genMs
|
|
294
|
+
setMetrics({ ...metricsAcc })
|
|
295
|
+
historyRef.current.push({ ...metricsAcc })
|
|
296
|
+
if (sessionMode === "stateful") {
|
|
297
|
+
if (!conversationIdRef.current) {
|
|
298
|
+
conversationIdRef.current =
|
|
299
|
+
typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
|
|
300
|
+
? crypto.randomUUID()
|
|
301
|
+
: `web-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
|
|
302
|
+
}
|
|
303
|
+
messagesRef.current = [...resolvedMessages, { role: "assistant", content: outputAccRef.current }]
|
|
304
|
+
}
|
|
305
|
+
setStreaming(false)
|
|
306
|
+
setLoading(false)
|
|
307
|
+
worker.terminate()
|
|
308
|
+
workerRef.current = null
|
|
309
|
+
break
|
|
310
|
+
case "error":
|
|
311
|
+
console.error("[catalyst-ai/useWebAI] worker error:", msg.message)
|
|
312
|
+
setError(new Error(msg.message))
|
|
313
|
+
setStreaming(false)
|
|
314
|
+
setLoading(false)
|
|
315
|
+
worker.terminate()
|
|
316
|
+
workerRef.current = null
|
|
317
|
+
break
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
worker.onerror = (e) => {
|
|
322
|
+
console.error("[catalyst-ai/useWebAI] worker uncaught error:", e)
|
|
323
|
+
setError(new Error(e.message || "Worker crashed"))
|
|
324
|
+
setStreaming(false)
|
|
325
|
+
setLoading(false)
|
|
326
|
+
worker.terminate()
|
|
327
|
+
workerRef.current = null
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
worker.postMessage({
|
|
331
|
+
type: "generate",
|
|
332
|
+
model: resolvedModel,
|
|
333
|
+
messages: resolvedMessages,
|
|
334
|
+
genConfig,
|
|
335
|
+
formatPrompt: typeof formatPromptRef.current === "function" ? formatPromptRef.current.toString() : null,
|
|
336
|
+
})
|
|
337
|
+
},
|
|
338
|
+
[modelProp, hookGenConfig, sessionMode]
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
const cancel = useCallback(() => {
|
|
342
|
+
cancelledRef.current = true
|
|
343
|
+
if (rafRef.current) { cancelSchedule(rafRef.current); rafRef.current = null }
|
|
344
|
+
if (workerRef.current) { workerRef.current.terminate(); workerRef.current = null }
|
|
345
|
+
setStreaming(false)
|
|
346
|
+
}, [])
|
|
347
|
+
|
|
348
|
+
const reset = useCallback(() => {
|
|
349
|
+
cancelledRef.current = true
|
|
350
|
+
if (rafRef.current) { cancelSchedule(rafRef.current); rafRef.current = null }
|
|
351
|
+
outputAccRef.current = ""
|
|
352
|
+
if (workerRef.current) { workerRef.current.terminate(); workerRef.current = null }
|
|
353
|
+
conversationIdRef.current = null
|
|
354
|
+
messagesRef.current = []
|
|
355
|
+
setOutput("")
|
|
356
|
+
setError(null)
|
|
357
|
+
setMetrics(null)
|
|
358
|
+
setModelReady(false)
|
|
359
|
+
setDownloadProgress(null)
|
|
360
|
+
setStreaming(false)
|
|
361
|
+
setLoading(false)
|
|
362
|
+
}, [])
|
|
363
|
+
|
|
364
|
+
return {
|
|
365
|
+
output,
|
|
366
|
+
streaming,
|
|
367
|
+
loading,
|
|
368
|
+
error,
|
|
369
|
+
modelReady,
|
|
370
|
+
downloadProgress,
|
|
371
|
+
nativeDownloadProgress: null,
|
|
372
|
+
nativeLogs: [],
|
|
373
|
+
metrics,
|
|
374
|
+
isLocal: true,
|
|
375
|
+
isNative: false,
|
|
376
|
+
isWeb: true,
|
|
377
|
+
generate,
|
|
378
|
+
cancel,
|
|
379
|
+
reset,
|
|
380
|
+
clearError: useCallback(() => setError(null), []),
|
|
381
|
+
get conversationId() { return conversationIdRef.current },
|
|
382
|
+
getSessionMetrics: useCallback(() => aggregateWebSessionMetrics(historyRef.current), []),
|
|
383
|
+
resetSessionMetrics: useCallback(() => { historyRef.current = [] }, []),
|
|
384
|
+
}
|
|
385
|
+
}
|