@runanywhere/web-llamacpp 0.1.0-beta.5
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/dist/Extensions/DiffusionTypes.d.ts +64 -0
- package/dist/Extensions/DiffusionTypes.d.ts.map +1 -0
- package/dist/Extensions/DiffusionTypes.js +28 -0
- package/dist/Extensions/DiffusionTypes.js.map +1 -0
- package/dist/Extensions/EmbeddingsTypes.d.ts +33 -0
- package/dist/Extensions/EmbeddingsTypes.d.ts.map +1 -0
- package/dist/Extensions/EmbeddingsTypes.js +13 -0
- package/dist/Extensions/EmbeddingsTypes.js.map +1 -0
- package/dist/Extensions/RunAnywhere+Diffusion.d.ts +44 -0
- package/dist/Extensions/RunAnywhere+Diffusion.d.ts.map +1 -0
- package/dist/Extensions/RunAnywhere+Diffusion.js +183 -0
- package/dist/Extensions/RunAnywhere+Diffusion.js.map +1 -0
- package/dist/Extensions/RunAnywhere+Embeddings.d.ts +56 -0
- package/dist/Extensions/RunAnywhere+Embeddings.d.ts.map +1 -0
- package/dist/Extensions/RunAnywhere+Embeddings.js +234 -0
- package/dist/Extensions/RunAnywhere+Embeddings.js.map +1 -0
- package/dist/Extensions/RunAnywhere+StructuredOutput.d.ts +69 -0
- package/dist/Extensions/RunAnywhere+StructuredOutput.d.ts.map +1 -0
- package/dist/Extensions/RunAnywhere+StructuredOutput.js +192 -0
- package/dist/Extensions/RunAnywhere+StructuredOutput.js.map +1 -0
- package/dist/Extensions/RunAnywhere+TextGeneration.d.ts +80 -0
- package/dist/Extensions/RunAnywhere+TextGeneration.d.ts.map +1 -0
- package/dist/Extensions/RunAnywhere+TextGeneration.js +464 -0
- package/dist/Extensions/RunAnywhere+TextGeneration.js.map +1 -0
- package/dist/Extensions/RunAnywhere+ToolCalling.d.ts +82 -0
- package/dist/Extensions/RunAnywhere+ToolCalling.d.ts.map +1 -0
- package/dist/Extensions/RunAnywhere+ToolCalling.js +573 -0
- package/dist/Extensions/RunAnywhere+ToolCalling.js.map +1 -0
- package/dist/Extensions/RunAnywhere+VLM.d.ts +58 -0
- package/dist/Extensions/RunAnywhere+VLM.d.ts.map +1 -0
- package/dist/Extensions/RunAnywhere+VLM.js +256 -0
- package/dist/Extensions/RunAnywhere+VLM.js.map +1 -0
- package/dist/Extensions/ToolCallingTypes.d.ts +78 -0
- package/dist/Extensions/ToolCallingTypes.d.ts.map +1 -0
- package/dist/Extensions/ToolCallingTypes.js +8 -0
- package/dist/Extensions/ToolCallingTypes.js.map +1 -0
- package/dist/Extensions/VLMTypes.d.ts +56 -0
- package/dist/Extensions/VLMTypes.d.ts.map +1 -0
- package/dist/Extensions/VLMTypes.js +24 -0
- package/dist/Extensions/VLMTypes.js.map +1 -0
- package/dist/Infrastructure/VLMWorkerBridge.d.ts +211 -0
- package/dist/Infrastructure/VLMWorkerBridge.d.ts.map +1 -0
- package/dist/Infrastructure/VLMWorkerBridge.js +263 -0
- package/dist/Infrastructure/VLMWorkerBridge.js.map +1 -0
- package/dist/Infrastructure/VLMWorkerRuntime.d.ts +38 -0
- package/dist/Infrastructure/VLMWorkerRuntime.d.ts.map +1 -0
- package/dist/Infrastructure/VLMWorkerRuntime.js +503 -0
- package/dist/Infrastructure/VLMWorkerRuntime.js.map +1 -0
- package/dist/Infrastructure/VideoCapture.d.ts +118 -0
- package/dist/Infrastructure/VideoCapture.d.ts.map +1 -0
- package/dist/Infrastructure/VideoCapture.js +207 -0
- package/dist/Infrastructure/VideoCapture.js.map +1 -0
- package/dist/LlamaCPP.d.ts +33 -0
- package/dist/LlamaCPP.d.ts.map +1 -0
- package/dist/LlamaCPP.js +48 -0
- package/dist/LlamaCPP.js.map +1 -0
- package/dist/LlamaCppProvider.d.ts +30 -0
- package/dist/LlamaCppProvider.d.ts.map +1 -0
- package/dist/LlamaCppProvider.js +103 -0
- package/dist/LlamaCppProvider.js.map +1 -0
- package/dist/index.d.ts +43 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +38 -0
- package/dist/index.js.map +1 -0
- package/dist/types/LLMTypes.d.ts +48 -0
- package/dist/types/LLMTypes.d.ts.map +1 -0
- package/dist/types/LLMTypes.js +8 -0
- package/dist/types/LLMTypes.js.map +1 -0
- package/dist/workers/vlm-worker.d.ts +9 -0
- package/dist/workers/vlm-worker.d.ts.map +1 -0
- package/dist/workers/vlm-worker.js +10 -0
- package/dist/workers/vlm-worker.js.map +1 -0
- package/package.json +66 -0
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RunAnywhere Web SDK - Embeddings Extension
|
|
3
|
+
*
|
|
4
|
+
* Adds text embedding generation capabilities via RACommons WASM.
|
|
5
|
+
* Uses the rac_embeddings_component_* C API for model lifecycle
|
|
6
|
+
* and embedding generation.
|
|
7
|
+
*
|
|
8
|
+
* Embeddings convert text into fixed-dimensional dense vectors
|
|
9
|
+
* useful for semantic search, clustering, and RAG.
|
|
10
|
+
*
|
|
11
|
+
* Backend: llama.cpp (GGUF embedding models like nomic-embed-text)
|
|
12
|
+
*
|
|
13
|
+
* Usage:
|
|
14
|
+
* import { Embeddings } from '@runanywhere/web';
|
|
15
|
+
*
|
|
16
|
+
* await Embeddings.loadModel('/models/nomic-embed-text-v1.5.Q4_K_M.gguf', 'nomic-embed');
|
|
17
|
+
* const result = await Embeddings.embed('Hello, world!');
|
|
18
|
+
* console.log('Dimension:', result.dimension);
|
|
19
|
+
* console.log('Vector:', result.embeddings[0].data);
|
|
20
|
+
*
|
|
21
|
+
* // Batch embedding
|
|
22
|
+
* const batch = await Embeddings.embedBatch(['text1', 'text2', 'text3']);
|
|
23
|
+
*/
|
|
24
|
+
import { RunAnywhere, WASMBridge, Offsets, SDKError, SDKErrorCode, SDKLogger, EventBus, SDKEventType } from '@runanywhere/web';
|
|
25
|
+
export { EmbeddingsNormalize, EmbeddingsPooling, } from './EmbeddingsTypes';
|
|
26
|
+
const logger = new SDKLogger('Embeddings');
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// Embeddings Extension
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
class EmbeddingsImpl {
|
|
31
|
+
extensionName = 'Embeddings';
|
|
32
|
+
_embeddingsComponentHandle = 0;
|
|
33
|
+
requireBridge() {
|
|
34
|
+
if (!RunAnywhere.isInitialized)
|
|
35
|
+
throw SDKError.notInitialized();
|
|
36
|
+
return WASMBridge.shared;
|
|
37
|
+
}
|
|
38
|
+
ensureEmbeddingsComponent() {
|
|
39
|
+
if (this._embeddingsComponentHandle !== 0)
|
|
40
|
+
return this._embeddingsComponentHandle;
|
|
41
|
+
const bridge = this.requireBridge();
|
|
42
|
+
const m = bridge.module;
|
|
43
|
+
const handlePtr = m._malloc(4);
|
|
44
|
+
const result = bridge.callFunction('rac_embeddings_component_create', 'number', ['number'], [handlePtr]);
|
|
45
|
+
if (result !== 0) {
|
|
46
|
+
m._free(handlePtr);
|
|
47
|
+
bridge.checkResult(result, 'rac_embeddings_component_create');
|
|
48
|
+
}
|
|
49
|
+
this._embeddingsComponentHandle = m.getValue(handlePtr, 'i32');
|
|
50
|
+
m._free(handlePtr);
|
|
51
|
+
logger.debug('Embeddings component created');
|
|
52
|
+
return this._embeddingsComponentHandle;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Load an embedding model (GGUF format).
|
|
56
|
+
*/
|
|
57
|
+
async loadModel(modelPath, modelId, modelName) {
|
|
58
|
+
const bridge = this.requireBridge();
|
|
59
|
+
const m = bridge.module;
|
|
60
|
+
const handle = this.ensureEmbeddingsComponent();
|
|
61
|
+
logger.info(`Loading embeddings model: ${modelId} from ${modelPath}`);
|
|
62
|
+
EventBus.shared.emit('model.loadStarted', SDKEventType.Model, { modelId, component: 'embeddings' });
|
|
63
|
+
const pathPtr = bridge.allocString(modelPath);
|
|
64
|
+
const idPtr = bridge.allocString(modelId);
|
|
65
|
+
const namePtr = bridge.allocString(modelName ?? modelId);
|
|
66
|
+
try {
|
|
67
|
+
const result = m.ccall('rac_embeddings_component_load_model', 'number', ['number', 'number', 'number', 'number'], [handle, pathPtr, idPtr, namePtr]);
|
|
68
|
+
bridge.checkResult(result, 'rac_embeddings_component_load_model');
|
|
69
|
+
logger.info(`Embeddings model loaded: ${modelId}`);
|
|
70
|
+
EventBus.shared.emit('model.loadCompleted', SDKEventType.Model, { modelId, component: 'embeddings' });
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
bridge.free(pathPtr);
|
|
74
|
+
bridge.free(idPtr);
|
|
75
|
+
bridge.free(namePtr);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** Unload the embeddings model. */
|
|
79
|
+
async unloadModel() {
|
|
80
|
+
if (this._embeddingsComponentHandle === 0)
|
|
81
|
+
return;
|
|
82
|
+
const bridge = this.requireBridge();
|
|
83
|
+
const result = bridge.module.ccall('rac_embeddings_component_unload', 'number', ['number'], [this._embeddingsComponentHandle]);
|
|
84
|
+
bridge.checkResult(result, 'rac_embeddings_component_unload');
|
|
85
|
+
logger.info('Embeddings model unloaded');
|
|
86
|
+
}
|
|
87
|
+
/** Check if an embeddings model is loaded. */
|
|
88
|
+
get isModelLoaded() {
|
|
89
|
+
if (this._embeddingsComponentHandle === 0)
|
|
90
|
+
return false;
|
|
91
|
+
try {
|
|
92
|
+
return WASMBridge.shared.module.ccall('rac_embeddings_component_is_loaded', 'number', ['number'], [this._embeddingsComponentHandle]) === 1;
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Generate embedding for a single text.
|
|
100
|
+
*/
|
|
101
|
+
async embed(text, options = {}) {
|
|
102
|
+
const bridge = this.requireBridge();
|
|
103
|
+
const m = bridge.module;
|
|
104
|
+
const handle = this.ensureEmbeddingsComponent();
|
|
105
|
+
if (!this.isModelLoaded) {
|
|
106
|
+
throw new SDKError(SDKErrorCode.ModelNotLoaded, 'No embeddings model loaded. Call loadModel() first.');
|
|
107
|
+
}
|
|
108
|
+
logger.debug(`Embedding text (${text.length} chars)`);
|
|
109
|
+
const textPtr = bridge.allocString(text);
|
|
110
|
+
// Build rac_embeddings_options_t
|
|
111
|
+
const optSize = m._rac_wasm_sizeof_embeddings_options();
|
|
112
|
+
const optPtr = m._malloc(optSize);
|
|
113
|
+
const eOpt = Offsets.embeddingsOptions;
|
|
114
|
+
m.setValue(optPtr + eOpt.normalize, options.normalize !== undefined ? options.normalize : -1, 'i32');
|
|
115
|
+
m.setValue(optPtr + eOpt.pooling, options.pooling !== undefined ? options.pooling : -1, 'i32');
|
|
116
|
+
m.setValue(optPtr + eOpt.nThreads, 0, 'i32'); // n_threads = auto
|
|
117
|
+
// Result struct
|
|
118
|
+
const resSize = m._rac_wasm_sizeof_embeddings_result();
|
|
119
|
+
const resPtr = m._malloc(resSize);
|
|
120
|
+
try {
|
|
121
|
+
const r = m.ccall('rac_embeddings_component_embed', 'number', ['number', 'number', 'number', 'number'], [handle, textPtr, optPtr, resPtr]);
|
|
122
|
+
bridge.checkResult(r, 'rac_embeddings_component_embed');
|
|
123
|
+
return readEmbeddingsResult(bridge, m, resPtr);
|
|
124
|
+
}
|
|
125
|
+
finally {
|
|
126
|
+
bridge.free(textPtr);
|
|
127
|
+
m._free(optPtr);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Generate embeddings for multiple texts at once.
|
|
132
|
+
*/
|
|
133
|
+
async embedBatch(texts, options = {}) {
|
|
134
|
+
const bridge = this.requireBridge();
|
|
135
|
+
const m = bridge.module;
|
|
136
|
+
const handle = this.ensureEmbeddingsComponent();
|
|
137
|
+
if (!this.isModelLoaded) {
|
|
138
|
+
throw new SDKError(SDKErrorCode.ModelNotLoaded, 'No embeddings model loaded. Call loadModel() first.');
|
|
139
|
+
}
|
|
140
|
+
logger.debug(`Embedding batch of ${texts.length} texts`);
|
|
141
|
+
// Allocate array of string pointers
|
|
142
|
+
const textPtrs = [];
|
|
143
|
+
const textArrayPtr = m._malloc(texts.length * 4);
|
|
144
|
+
for (let i = 0; i < texts.length; i++) {
|
|
145
|
+
const ptr = bridge.allocString(texts[i]);
|
|
146
|
+
textPtrs.push(ptr);
|
|
147
|
+
m.setValue(textArrayPtr + i * 4, ptr, '*');
|
|
148
|
+
}
|
|
149
|
+
// Options
|
|
150
|
+
const optSize = m._rac_wasm_sizeof_embeddings_options();
|
|
151
|
+
const optPtr = m._malloc(optSize);
|
|
152
|
+
const eOpt2 = Offsets.embeddingsOptions;
|
|
153
|
+
m.setValue(optPtr + eOpt2.normalize, options.normalize !== undefined ? options.normalize : -1, 'i32');
|
|
154
|
+
m.setValue(optPtr + eOpt2.pooling, options.pooling !== undefined ? options.pooling : -1, 'i32');
|
|
155
|
+
m.setValue(optPtr + eOpt2.nThreads, 0, 'i32');
|
|
156
|
+
// Result
|
|
157
|
+
const resSize = m._rac_wasm_sizeof_embeddings_result();
|
|
158
|
+
const resPtr = m._malloc(resSize);
|
|
159
|
+
try {
|
|
160
|
+
const r = m.ccall('rac_embeddings_component_embed_batch', 'number', ['number', 'number', 'number', 'number', 'number'], [handle, textArrayPtr, texts.length, optPtr, resPtr]);
|
|
161
|
+
bridge.checkResult(r, 'rac_embeddings_component_embed_batch');
|
|
162
|
+
return readEmbeddingsResult(bridge, m, resPtr);
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
for (const ptr of textPtrs)
|
|
166
|
+
bridge.free(ptr);
|
|
167
|
+
m._free(textArrayPtr);
|
|
168
|
+
m._free(optPtr);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Compute cosine similarity between two embedding vectors.
|
|
173
|
+
* Pure TypeScript utility -- no WASM call needed.
|
|
174
|
+
*/
|
|
175
|
+
cosineSimilarity(a, b) {
|
|
176
|
+
if (a.length !== b.length)
|
|
177
|
+
throw new Error('Vectors must have the same dimension');
|
|
178
|
+
let dot = 0;
|
|
179
|
+
let normA = 0;
|
|
180
|
+
let normB = 0;
|
|
181
|
+
for (let i = 0; i < a.length; i++) {
|
|
182
|
+
dot += a[i] * b[i];
|
|
183
|
+
normA += a[i] * a[i];
|
|
184
|
+
normB += b[i] * b[i];
|
|
185
|
+
}
|
|
186
|
+
const denominator = Math.sqrt(normA) * Math.sqrt(normB);
|
|
187
|
+
return denominator === 0 ? 0 : dot / denominator;
|
|
188
|
+
}
|
|
189
|
+
/** Clean up the embeddings component. */
|
|
190
|
+
cleanup() {
|
|
191
|
+
if (this._embeddingsComponentHandle !== 0) {
|
|
192
|
+
try {
|
|
193
|
+
WASMBridge.shared.module.ccall('rac_embeddings_component_destroy', null, ['number'], [this._embeddingsComponentHandle]);
|
|
194
|
+
}
|
|
195
|
+
catch { /* ignore */ }
|
|
196
|
+
this._embeddingsComponentHandle = 0;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
export const Embeddings = new EmbeddingsImpl();
|
|
201
|
+
// ---------------------------------------------------------------------------
|
|
202
|
+
// Helper: Read rac_embeddings_result_t from WASM memory
|
|
203
|
+
// ---------------------------------------------------------------------------
|
|
204
|
+
function readEmbeddingsResult(bridge, m, resPtr) {
|
|
205
|
+
// rac_embeddings_result_t (offsets from compiler via StructOffsets)
|
|
206
|
+
const eRes = Offsets.embeddingsResult;
|
|
207
|
+
const embeddingsArrayPtr = m.getValue(resPtr + eRes.embeddings, '*');
|
|
208
|
+
const numEmbeddings = m.getValue(resPtr + eRes.numEmbeddings, 'i32');
|
|
209
|
+
const dimension = m.getValue(resPtr + eRes.dimension, 'i32');
|
|
210
|
+
const processingTimeMs = m.getValue(resPtr + eRes.processingTimeMs, 'i32'); // low 32 bits of int64
|
|
211
|
+
const totalTokens = m.getValue(resPtr + eRes.totalTokens, 'i32');
|
|
212
|
+
const embeddings = [];
|
|
213
|
+
const ev = Offsets.embeddingVector;
|
|
214
|
+
for (let i = 0; i < numEmbeddings; i++) {
|
|
215
|
+
// Each rac_embedding_vector_t
|
|
216
|
+
const vecPtr = embeddingsArrayPtr + i * ev.structSize;
|
|
217
|
+
const dataPtr = m.getValue(vecPtr + ev.data, '*');
|
|
218
|
+
const vecDim = m.getValue(vecPtr + ev.dimension, 'i32');
|
|
219
|
+
const data = new Float32Array(vecDim);
|
|
220
|
+
if (dataPtr && vecDim > 0) {
|
|
221
|
+
data.set(bridge.readFloat32Array(dataPtr, vecDim));
|
|
222
|
+
}
|
|
223
|
+
embeddings.push({ data, dimension: vecDim });
|
|
224
|
+
}
|
|
225
|
+
// Free C result
|
|
226
|
+
m.ccall('rac_embeddings_result_free', null, ['number'], [resPtr]);
|
|
227
|
+
EventBus.shared.emit('embeddings.generated', SDKEventType.Generation, {
|
|
228
|
+
numEmbeddings,
|
|
229
|
+
dimension,
|
|
230
|
+
processingTimeMs,
|
|
231
|
+
});
|
|
232
|
+
return { embeddings, dimension, processingTimeMs, totalTokens };
|
|
233
|
+
}
|
|
234
|
+
//# sourceMappingURL=RunAnywhere+Embeddings.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RunAnywhere+Embeddings.js","sourceRoot":"","sources":["../../src/Extensions/RunAnywhere+Embeddings.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAO/H,OAAO,EACL,mBAAmB,EACnB,iBAAiB,GAIlB,MAAM,mBAAmB,CAAC;AAE3B,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC,YAAY,CAAC,CAAC;AAE3C,8EAA8E;AAC9E,uBAAuB;AACvB,8EAA8E;AAE9E,MAAM,cAAc;IACT,aAAa,GAAG,YAAY,CAAC;IAC9B,0BAA0B,GAAG,CAAC,CAAC;IAE/B,aAAa;QACnB,IAAI,CAAC,WAAW,CAAC,aAAa;YAAE,MAA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C;QAED,UAAU,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED,gBAAgB;IAChB,CAAC,CAAC,KAAK,CAAC,4BAA4B,EAAE,IAAI,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAElE,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,sBAAsB,EAAE,YAAY,CAAC,UAAU,EAAE;QACpE,aAAa;QACb,SAAS;QACT,gBAAgB;KACjB,CAAC,CAAC;IAEH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,gBAAgB,EAAE,WAAW,EAAE,CAAC;AAClE,CAAC"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RunAnywhere Web SDK - Structured Output Extension
|
|
3
|
+
*
|
|
4
|
+
* Adds JSON-structured output capabilities for LLM generation.
|
|
5
|
+
* Uses the RACommons rac_structured_output_* C API for schema-guided
|
|
6
|
+
* generation and JSON extraction/validation.
|
|
7
|
+
*
|
|
8
|
+
* Mirrors: sdk/runanywhere-swift/Sources/RunAnywhere/Public/Extensions/StructuredOutput/
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* import { StructuredOutput, TextGeneration } from '@runanywhere/web';
|
|
12
|
+
*
|
|
13
|
+
* const schema = JSON.stringify({ type: 'object', properties: { name: { type: 'string' } } });
|
|
14
|
+
* const prompt = await StructuredOutput.preparePrompt('List 3 colors', schema);
|
|
15
|
+
* const result = await TextGeneration.generate(prompt);
|
|
16
|
+
* const validated = StructuredOutput.validate(result.text, schema);
|
|
17
|
+
* console.log(validated.extractedJson); // parsed JSON
|
|
18
|
+
*/
|
|
19
|
+
export interface StructuredOutputConfig {
|
|
20
|
+
/** JSON Schema string */
|
|
21
|
+
jsonSchema: string;
|
|
22
|
+
/** Whether to include the schema in the prompt (default: true) */
|
|
23
|
+
includeSchemaInPrompt?: boolean;
|
|
24
|
+
}
|
|
25
|
+
export interface StructuredOutputValidation {
|
|
26
|
+
isValid: boolean;
|
|
27
|
+
errorMessage?: string;
|
|
28
|
+
extractedJson?: string;
|
|
29
|
+
}
|
|
30
|
+
export declare const StructuredOutput: {
|
|
31
|
+
/**
|
|
32
|
+
* Extract JSON from a text response (finds first complete JSON object/array).
|
|
33
|
+
*
|
|
34
|
+
* @param text - Raw LLM output text
|
|
35
|
+
* @returns Extracted JSON string, or null if none found
|
|
36
|
+
*/
|
|
37
|
+
extractJson(text: string): string | null;
|
|
38
|
+
/**
|
|
39
|
+
* Prepare a prompt with schema instructions for structured output.
|
|
40
|
+
*
|
|
41
|
+
* @param originalPrompt - The user's original prompt
|
|
42
|
+
* @param config - Schema configuration
|
|
43
|
+
* @returns Enhanced prompt with schema instructions
|
|
44
|
+
*/
|
|
45
|
+
preparePrompt(originalPrompt: string, config: StructuredOutputConfig): string;
|
|
46
|
+
/**
|
|
47
|
+
* Get a system prompt that instructs the LLM to produce JSON matching a schema.
|
|
48
|
+
*
|
|
49
|
+
* @param jsonSchema - JSON Schema string
|
|
50
|
+
* @returns System prompt string
|
|
51
|
+
*/
|
|
52
|
+
getSystemPrompt(jsonSchema: string): string;
|
|
53
|
+
/**
|
|
54
|
+
* Validate LLM output against a JSON schema.
|
|
55
|
+
*
|
|
56
|
+
* @param text - Raw LLM output
|
|
57
|
+
* @param config - Schema configuration
|
|
58
|
+
* @returns Validation result with extracted JSON if valid
|
|
59
|
+
*/
|
|
60
|
+
validate(text: string, config: StructuredOutputConfig): StructuredOutputValidation;
|
|
61
|
+
/**
|
|
62
|
+
* Check if text contains a complete JSON object or array.
|
|
63
|
+
*
|
|
64
|
+
* @param text - Text to check
|
|
65
|
+
* @returns True if a complete JSON block was found
|
|
66
|
+
*/
|
|
67
|
+
hasCompleteJson(text: string): boolean;
|
|
68
|
+
};
|
|
69
|
+
//# sourceMappingURL=RunAnywhere+StructuredOutput.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RunAnywhere+StructuredOutput.d.ts","sourceRoot":"","sources":["../../src/Extensions/RunAnywhere+StructuredOutput.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAeH,MAAM,WAAW,sBAAsB;IACrC,yBAAyB;IACzB,UAAU,EAAE,MAAM,CAAC;IACnB,kEAAkE;IAClE,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC;AAED,MAAM,WAAW,0BAA0B;IACzC,OAAO,EAAE,OAAO,CAAC;IACjB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAMD,eAAO,MAAM,gBAAgB;IAC3B;;;;;OAKG;sBACe,MAAM,GAAG,MAAM,GAAG,IAAI;IA8BxC;;;;;;OAMG;kCAC2B,MAAM,UAAU,sBAAsB,GAAG,MAAM;IA0C7E;;;;;OAKG;gCACyB,MAAM,GAAG,MAAM;IA4B3C;;;;;;OAMG;mBACY,MAAM,UAAU,sBAAsB,GAAG,0BAA0B;IAkDlF;;;;;OAKG;0BACmB,MAAM,GAAG,OAAO;CAqBvC,CAAC"}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RunAnywhere Web SDK - Structured Output Extension
|
|
3
|
+
*
|
|
4
|
+
* Adds JSON-structured output capabilities for LLM generation.
|
|
5
|
+
* Uses the RACommons rac_structured_output_* C API for schema-guided
|
|
6
|
+
* generation and JSON extraction/validation.
|
|
7
|
+
*
|
|
8
|
+
* Mirrors: sdk/runanywhere-swift/Sources/RunAnywhere/Public/Extensions/StructuredOutput/
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* import { StructuredOutput, TextGeneration } from '@runanywhere/web';
|
|
12
|
+
*
|
|
13
|
+
* const schema = JSON.stringify({ type: 'object', properties: { name: { type: 'string' } } });
|
|
14
|
+
* const prompt = await StructuredOutput.preparePrompt('List 3 colors', schema);
|
|
15
|
+
* const result = await TextGeneration.generate(prompt);
|
|
16
|
+
* const validated = StructuredOutput.validate(result.text, schema);
|
|
17
|
+
* console.log(validated.extractedJson); // parsed JSON
|
|
18
|
+
*/
|
|
19
|
+
import { RunAnywhere, WASMBridge, Offsets, SDKError, SDKLogger } from '@runanywhere/web';
|
|
20
|
+
const logger = new SDKLogger('StructuredOutput');
|
|
21
|
+
function requireBridge() {
|
|
22
|
+
if (!RunAnywhere.isInitialized)
|
|
23
|
+
throw SDKError.notInitialized();
|
|
24
|
+
return WASMBridge.shared;
|
|
25
|
+
}
|
|
26
|
+
// ---------------------------------------------------------------------------
|
|
27
|
+
// Structured Output Extension
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
export const StructuredOutput = {
|
|
30
|
+
/**
|
|
31
|
+
* Extract JSON from a text response (finds first complete JSON object/array).
|
|
32
|
+
*
|
|
33
|
+
* @param text - Raw LLM output text
|
|
34
|
+
* @returns Extracted JSON string, or null if none found
|
|
35
|
+
*/
|
|
36
|
+
extractJson(text) {
|
|
37
|
+
const bridge = requireBridge();
|
|
38
|
+
const m = bridge.module;
|
|
39
|
+
const textPtr = bridge.allocString(text);
|
|
40
|
+
const outJsonPtr = m._malloc(4); // char** out_json
|
|
41
|
+
const outLenPtr = m._malloc(4); // size_t* out_length
|
|
42
|
+
try {
|
|
43
|
+
const result = m.ccall('rac_structured_output_extract_json', 'number', ['number', 'number', 'number'], [textPtr, outJsonPtr, outLenPtr]);
|
|
44
|
+
if (result !== 0)
|
|
45
|
+
return null;
|
|
46
|
+
const jsonPtr = m.getValue(outJsonPtr, '*');
|
|
47
|
+
if (!jsonPtr)
|
|
48
|
+
return null;
|
|
49
|
+
const json = bridge.readString(jsonPtr);
|
|
50
|
+
m._free(jsonPtr); // rac_strdup'd, so we free it
|
|
51
|
+
return json;
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
bridge.free(textPtr);
|
|
55
|
+
m._free(outJsonPtr);
|
|
56
|
+
m._free(outLenPtr);
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
/**
|
|
60
|
+
* Prepare a prompt with schema instructions for structured output.
|
|
61
|
+
*
|
|
62
|
+
* @param originalPrompt - The user's original prompt
|
|
63
|
+
* @param config - Schema configuration
|
|
64
|
+
* @returns Enhanced prompt with schema instructions
|
|
65
|
+
*/
|
|
66
|
+
preparePrompt(originalPrompt, config) {
|
|
67
|
+
const bridge = requireBridge();
|
|
68
|
+
const m = bridge.module;
|
|
69
|
+
const promptPtr = bridge.allocString(originalPrompt);
|
|
70
|
+
// Build rac_structured_output_config_t: { json_schema, include_schema_in_prompt }
|
|
71
|
+
const configSize = m._rac_wasm_sizeof_structured_output_config();
|
|
72
|
+
const configPtr = m._malloc(configSize);
|
|
73
|
+
const soConf = Offsets.structuredOutputConfig;
|
|
74
|
+
const schemaPtr = bridge.allocString(config.jsonSchema);
|
|
75
|
+
m.setValue(configPtr + soConf.jsonSchema, schemaPtr, '*');
|
|
76
|
+
m.setValue(configPtr + soConf.includeSchemaInPrompt, (config.includeSchemaInPrompt !== false) ? 1 : 0, 'i32');
|
|
77
|
+
const outPromptPtr = m._malloc(4);
|
|
78
|
+
try {
|
|
79
|
+
const result = m.ccall('rac_structured_output_prepare_prompt', 'number', ['number', 'number', 'number'], [promptPtr, configPtr, outPromptPtr]);
|
|
80
|
+
if (result !== 0) {
|
|
81
|
+
logger.warning('Failed to prepare structured prompt, returning original');
|
|
82
|
+
return originalPrompt;
|
|
83
|
+
}
|
|
84
|
+
const preparedPtr = m.getValue(outPromptPtr, '*');
|
|
85
|
+
if (!preparedPtr)
|
|
86
|
+
return originalPrompt;
|
|
87
|
+
const prepared = bridge.readString(preparedPtr);
|
|
88
|
+
m._free(preparedPtr);
|
|
89
|
+
return prepared;
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
bridge.free(promptPtr);
|
|
93
|
+
bridge.free(schemaPtr);
|
|
94
|
+
m._free(configPtr);
|
|
95
|
+
m._free(outPromptPtr);
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
/**
|
|
99
|
+
* Get a system prompt that instructs the LLM to produce JSON matching a schema.
|
|
100
|
+
*
|
|
101
|
+
* @param jsonSchema - JSON Schema string
|
|
102
|
+
* @returns System prompt string
|
|
103
|
+
*/
|
|
104
|
+
getSystemPrompt(jsonSchema) {
|
|
105
|
+
const bridge = requireBridge();
|
|
106
|
+
const m = bridge.module;
|
|
107
|
+
const schemaPtr = bridge.allocString(jsonSchema);
|
|
108
|
+
const outPtr = m._malloc(4);
|
|
109
|
+
try {
|
|
110
|
+
const result = m.ccall('rac_structured_output_get_system_prompt', 'number', ['number', 'number'], [schemaPtr, outPtr]);
|
|
111
|
+
if (result !== 0)
|
|
112
|
+
return '';
|
|
113
|
+
const ptr = m.getValue(outPtr, '*');
|
|
114
|
+
if (!ptr)
|
|
115
|
+
return '';
|
|
116
|
+
const prompt = bridge.readString(ptr);
|
|
117
|
+
m._free(ptr);
|
|
118
|
+
return prompt;
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
bridge.free(schemaPtr);
|
|
122
|
+
m._free(outPtr);
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
/**
|
|
126
|
+
* Validate LLM output against a JSON schema.
|
|
127
|
+
*
|
|
128
|
+
* @param text - Raw LLM output
|
|
129
|
+
* @param config - Schema configuration
|
|
130
|
+
* @returns Validation result with extracted JSON if valid
|
|
131
|
+
*/
|
|
132
|
+
validate(text, config) {
|
|
133
|
+
const bridge = requireBridge();
|
|
134
|
+
const m = bridge.module;
|
|
135
|
+
const textPtr = bridge.allocString(text);
|
|
136
|
+
const configSize = m._rac_wasm_sizeof_structured_output_config();
|
|
137
|
+
const configPtr = m._malloc(configSize);
|
|
138
|
+
const soConf2 = Offsets.structuredOutputConfig;
|
|
139
|
+
const schemaPtr = bridge.allocString(config.jsonSchema);
|
|
140
|
+
m.setValue(configPtr + soConf2.jsonSchema, schemaPtr, '*');
|
|
141
|
+
m.setValue(configPtr + soConf2.includeSchemaInPrompt, (config.includeSchemaInPrompt !== false) ? 1 : 0, 'i32');
|
|
142
|
+
// rac_structured_output_validation_t (size from sizeof helper)
|
|
143
|
+
const valSize = 12; // 3 fields × 4 bytes on wasm32 — all i32/ptr
|
|
144
|
+
const valPtr = m._malloc(valSize);
|
|
145
|
+
try {
|
|
146
|
+
const result = m.ccall('rac_structured_output_validate', 'number', ['number', 'number', 'number'], [textPtr, configPtr, valPtr]);
|
|
147
|
+
if (result !== 0) {
|
|
148
|
+
return { isValid: false, errorMessage: 'Validation call failed' };
|
|
149
|
+
}
|
|
150
|
+
const soVal = Offsets.structuredOutputValidation;
|
|
151
|
+
const isValid = m.getValue(valPtr + soVal.isValid, 'i32') === 1;
|
|
152
|
+
const errorMsgPtr = m.getValue(valPtr + soVal.errorMessage, '*');
|
|
153
|
+
const extractedPtr = m.getValue(valPtr + soVal.extractedJson, '*');
|
|
154
|
+
const validation = {
|
|
155
|
+
isValid,
|
|
156
|
+
errorMessage: errorMsgPtr ? bridge.readString(errorMsgPtr) : undefined,
|
|
157
|
+
extractedJson: extractedPtr ? bridge.readString(extractedPtr) : undefined,
|
|
158
|
+
};
|
|
159
|
+
// Free C validation struct
|
|
160
|
+
m.ccall('rac_structured_output_validation_free', null, ['number'], [valPtr]);
|
|
161
|
+
return validation;
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
bridge.free(textPtr);
|
|
165
|
+
bridge.free(schemaPtr);
|
|
166
|
+
m._free(configPtr);
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
/**
|
|
170
|
+
* Check if text contains a complete JSON object or array.
|
|
171
|
+
*
|
|
172
|
+
* @param text - Text to check
|
|
173
|
+
* @returns True if a complete JSON block was found
|
|
174
|
+
*/
|
|
175
|
+
hasCompleteJson(text) {
|
|
176
|
+
const bridge = requireBridge();
|
|
177
|
+
const m = bridge.module;
|
|
178
|
+
const textPtr = bridge.allocString(text);
|
|
179
|
+
const startPtr = m._malloc(4);
|
|
180
|
+
const endPtr = m._malloc(4);
|
|
181
|
+
try {
|
|
182
|
+
const found = m.ccall('rac_structured_output_find_complete_json', 'number', ['number', 'number', 'number'], [textPtr, startPtr, endPtr]);
|
|
183
|
+
return found === 1;
|
|
184
|
+
}
|
|
185
|
+
finally {
|
|
186
|
+
bridge.free(textPtr);
|
|
187
|
+
m._free(startPtr);
|
|
188
|
+
m._free(endPtr);
|
|
189
|
+
}
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
//# sourceMappingURL=RunAnywhere+StructuredOutput.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RunAnywhere+StructuredOutput.js","sourceRoot":"","sources":["../../src/Extensions/RunAnywhere+StructuredOutput.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAEzF,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC,kBAAkB,CAAC,CAAC;AAEjD,SAAS,aAAa;IACpB,IAAI,CAAC,WAAW,CAAC,aAAa;QAAE,MAAM,QAAQ,CAAC,cAAc,EAAE,CAAC;IAChE,OAAO,UAAU,CAAC,MAAM,CAAC;AAC3B,CAAC;AAmBD,8EAA8E;AAC9E,8BAA8B;AAC9B,8EAA8E;AAE9E,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B;;;;;OAKG;IACH,WAAW,CAAC,IAAY;QACtB,MAAM,MAAM,GAAG,aAAa,EAAE,CAAC;QAC/B,MAAM,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC;QAExB,MAAM,OAAO,GAAG,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QACzC,MAAM,UAAU,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAE,kBAAkB;QACpD,MAAM,SAAS,GAAG,CAAC,CA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AAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACrB,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;YAClB,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC;IACH,CAAC;CACF,CAAC"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RunAnywhere Web SDK - Text Generation Extension
|
|
3
|
+
*
|
|
4
|
+
* Adds LLM text generation capabilities to RunAnywhere.
|
|
5
|
+
* Mirrors: sdk/runanywhere-swift/Sources/RunAnywhere/Public/Extensions/LLM/
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* import { RunAnywhere } from '@runanywhere/web';
|
|
9
|
+
*
|
|
10
|
+
* await RunAnywhere.loadModel('tinyllama-1.1b-q4');
|
|
11
|
+
* const result = await RunAnywhere.generate('Hello!', { maxTokens: 100 });
|
|
12
|
+
* console.log(result.text);
|
|
13
|
+
*
|
|
14
|
+
* // Streaming
|
|
15
|
+
* for await (const token of RunAnywhere.generateStream('Tell me a story')) {
|
|
16
|
+
* process.stdout.write(token);
|
|
17
|
+
* }
|
|
18
|
+
*/
|
|
19
|
+
import type { LLMGenerationOptions, LLMGenerationResult, LLMStreamingResult } from '../types/LLMTypes';
|
|
20
|
+
declare class TextGenerationImpl {
|
|
21
|
+
readonly extensionName = "TextGeneration";
|
|
22
|
+
private _llmComponentHandle;
|
|
23
|
+
/** Ensure the SDK is initialized and return the bridge. */
|
|
24
|
+
private requireBridge;
|
|
25
|
+
/** Ensure the LLM component is created. */
|
|
26
|
+
private ensureLLMComponent;
|
|
27
|
+
/**
|
|
28
|
+
* Load an LLM model for text generation.
|
|
29
|
+
*
|
|
30
|
+
* @param modelPath - Path to the model file (in Emscripten FS)
|
|
31
|
+
* @param modelId - Model identifier
|
|
32
|
+
* @param modelName - Human-readable model name
|
|
33
|
+
*/
|
|
34
|
+
loadModel(modelPath: string, modelId: string, modelName?: string): Promise<void>;
|
|
35
|
+
/**
|
|
36
|
+
* Unload the currently loaded LLM model.
|
|
37
|
+
*/
|
|
38
|
+
unloadModel(): Promise<void>;
|
|
39
|
+
/**
|
|
40
|
+
* Check if an LLM model is currently loaded.
|
|
41
|
+
*/
|
|
42
|
+
get isModelLoaded(): boolean;
|
|
43
|
+
/**
|
|
44
|
+
* Generate text from a prompt (non-streaming).
|
|
45
|
+
*
|
|
46
|
+
* Uses `ccall` with `{async: true}` so that Emscripten's JSPI / Asyncify
|
|
47
|
+
* can suspend the WASM stack for async WebGPU buffer operations. Without
|
|
48
|
+
* this the blocking C function traps with `RuntimeError: unreachable` on
|
|
49
|
+
* WebGPU builds because the browser event-loop cannot pump GPU command
|
|
50
|
+
* buffers while the main thread is blocked in a synchronous ccall.
|
|
51
|
+
*
|
|
52
|
+
* @param prompt - Input text prompt
|
|
53
|
+
* @param options - Generation options (temperature, maxTokens, etc.)
|
|
54
|
+
* @returns Generation result with text and metrics
|
|
55
|
+
*/
|
|
56
|
+
generate(prompt: string, options?: LLMGenerationOptions): Promise<LLMGenerationResult>;
|
|
57
|
+
/**
|
|
58
|
+
* Generate text with streaming (returns AsyncIterable of tokens).
|
|
59
|
+
*
|
|
60
|
+
* Async because the underlying C call uses `{async: true}` so Emscripten's
|
|
61
|
+
* JSPI can suspend the WASM stack during WebGPU buffer operations. On
|
|
62
|
+
* CPU-only builds the result is simply an already-resolved Promise.
|
|
63
|
+
*
|
|
64
|
+
* @param prompt - Input text prompt
|
|
65
|
+
* @param options - Generation options
|
|
66
|
+
* @returns Streaming result with async token stream and final result promise
|
|
67
|
+
*/
|
|
68
|
+
generateStream(prompt: string, options?: LLMGenerationOptions): Promise<LLMStreamingResult>;
|
|
69
|
+
/**
|
|
70
|
+
* Cancel any in-progress generation.
|
|
71
|
+
*/
|
|
72
|
+
cancel(): void;
|
|
73
|
+
/**
|
|
74
|
+
* Clean up the LLM component (frees memory).
|
|
75
|
+
*/
|
|
76
|
+
cleanup(): void;
|
|
77
|
+
}
|
|
78
|
+
export declare const TextGeneration: TextGenerationImpl;
|
|
79
|
+
export {};
|
|
80
|
+
//# sourceMappingURL=RunAnywhere+TextGeneration.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RunAnywhere+TextGeneration.d.ts","sourceRoot":"","sources":["../../src/Extensions/RunAnywhere+TextGeneration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAGH,OAAO,KAAK,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAQvG,cAAM,kBAAkB;IACtB,QAAQ,CAAC,aAAa,oBAAoB;IAC1C,OAAO,CAAC,mBAAmB,CAAK;IAEhC,2DAA2D;IAC3D,OAAO,CAAC,aAAa;IAOrB,2CAA2C;YAC7B,kBAAkB;IA2BhC;;;;;;OAMG;IACG,SAAS,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAuCtF;;OAEG;IACG,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAiBlC;;OAEG;IACH,IAAI,aAAa,IAAI,OAAO,CAQ3B;IAED;;;;;;;;;;;;OAYG;IACG,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IA4IhG;;;;;;;;;;OAUG;IACG,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IA2MrG;;OAEG;IACH,MAAM,IAAI,IAAI;IAUd;;OAEG;IACH,OAAO,IAAI,IAAI;CAWhB;AAED,eAAO,MAAM,cAAc,oBAA2B,CAAC"}
|