web-llm-runner 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +211 -0
  2. package/README.md +564 -0
  3. package/lib/cache_util.d.ts +19 -0
  4. package/lib/cache_util.d.ts.map +1 -0
  5. package/lib/config.d.ts +199 -0
  6. package/lib/config.d.ts.map +1 -0
  7. package/lib/conversation.d.ts +107 -0
  8. package/lib/conversation.d.ts.map +1 -0
  9. package/lib/embedding.d.ts +38 -0
  10. package/lib/embedding.d.ts.map +1 -0
  11. package/lib/engine.d.ts +140 -0
  12. package/lib/engine.d.ts.map +1 -0
  13. package/lib/error.d.ts +208 -0
  14. package/lib/error.d.ts.map +1 -0
  15. package/lib/extension_service_worker.d.ts +54 -0
  16. package/lib/extension_service_worker.d.ts.map +1 -0
  17. package/lib/index.d.ts +13 -0
  18. package/lib/index.d.ts.map +1 -0
  19. package/lib/index.js +13767 -0
  20. package/lib/index.js.map +1 -0
  21. package/lib/integrity.d.ts +44 -0
  22. package/lib/integrity.d.ts.map +1 -0
  23. package/lib/llm_chat.d.ts +258 -0
  24. package/lib/llm_chat.d.ts.map +1 -0
  25. package/lib/message.d.ts +87 -0
  26. package/lib/message.d.ts.map +1 -0
  27. package/lib/openai_api_protocols/chat_completion.d.ts +834 -0
  28. package/lib/openai_api_protocols/chat_completion.d.ts.map +1 -0
  29. package/lib/openai_api_protocols/completion.d.ts +270 -0
  30. package/lib/openai_api_protocols/completion.d.ts.map +1 -0
  31. package/lib/openai_api_protocols/embedding.d.ts +125 -0
  32. package/lib/openai_api_protocols/embedding.d.ts.map +1 -0
  33. package/lib/openai_api_protocols/index.d.ts +20 -0
  34. package/lib/openai_api_protocols/index.d.ts.map +1 -0
  35. package/lib/service_worker.d.ts +53 -0
  36. package/lib/service_worker.d.ts.map +1 -0
  37. package/lib/support.d.ts +117 -0
  38. package/lib/support.d.ts.map +1 -0
  39. package/lib/types.d.ts +202 -0
  40. package/lib/types.d.ts.map +1 -0
  41. package/lib/utils.d.ts +7 -0
  42. package/lib/utils.d.ts.map +1 -0
  43. package/lib/web_worker.d.ts +132 -0
  44. package/lib/web_worker.d.ts.map +1 -0
  45. package/lib/wrapper/WebLLMWrapper.d.ts +20 -0
  46. package/lib/wrapper/WebLLMWrapper.d.ts.map +1 -0
  47. package/lib/wrapper/llm-worker.d.ts +2 -0
  48. package/lib/wrapper/llm-worker.d.ts.map +1 -0
  49. package/package.json +60 -0
package/README.md ADDED
@@ -0,0 +1,564 @@
1
+ <div align="center" id="top">
2
+
3
+ # WebLLM
4
+
5
+ [![NPM Package](https://img.shields.io/badge/NPM_Package-Published-cc3534)](https://www.npmjs.com/package/@mlc-ai/web-llm)
6
+ [!["WebLLM Chat Deployed"](https://img.shields.io/badge/WebLLM_Chat-Deployed-%2332a852)](https://chat.webllm.ai/)
7
+ [![Join Discord](https://img.shields.io/badge/Join-Discord-7289DA?logo=discord&logoColor=white)](https://discord.gg/9Xpy2HGBuD)
8
+ [![Related Repository: WebLLM Chat](https://img.shields.io/badge/Related_Repo-WebLLM_Chat-fafbfc?logo=github)](https://github.com/mlc-ai/web-llm-chat/)
9
+ [![Related Repository: MLC LLM](https://img.shields.io/badge/Related_Repo-MLC_LLM-fafbfc?logo=github)](https://github.com/mlc-ai/mlc-llm/)
10
+
11
+ **High-Performance In-Browser LLM Inference Engine.**
12
+
13
+ [Documentation](https://webllm.mlc.ai/docs/) | [Blogpost](https://blog.mlc.ai/2024/06/13/webllm-a-high-performance-in-browser-llm-inference-engine) | [Paper](https://arxiv.org/abs/2412.15803) | [Examples](examples)
14
+
15
+ </div>
16
+
17
+ ## Overview
18
+
19
+ WebLLM is a high-performance in-browser LLM inference engine that brings language model inference directly onto web browsers with hardware acceleration.
20
+ Everything runs inside the browser with no server support and is accelerated with WebGPU.
21
+
22
+ WebLLM is **fully compatible with [OpenAI API](https://platform.openai.com/docs/api-reference/chat).**
23
+ That is, you can use the same OpenAI API on **any open source models** locally, with functionalities
24
+ including streaming, JSON-mode, function-calling (WIP), etc.
25
+
26
+ We can bring a lot of fun opportunities to build AI assistants for everyone and enable privacy while enjoying GPU acceleration.
27
+
28
+ You can use WebLLM as a base [npm package](https://www.npmjs.com/package/@mlc-ai/web-llm) and build your own web application on top of it by following the examples below. This project is a companion project of [MLC LLM](https://github.com/mlc-ai/mlc-llm), which enables universal deployment of LLM across hardware environments.
29
+
30
+ <div align="center">
31
+
32
+ **[Check out WebLLM Chat to try it out!](https://chat.webllm.ai/)**
33
+
34
+ </div>
35
+
36
+ ## Key Features
37
+
38
+ - **In-Browser Inference**: WebLLM is a high-performance, in-browser language model inference engine that leverages WebGPU for hardware acceleration, enabling powerful LLM operations directly within web browsers without server-side processing.
39
+
40
+ - [**Full OpenAI API Compatibility**](#full-openai-compatibility): Seamlessly integrate your app with WebLLM using OpenAI API with functionalities such as streaming, JSON-mode, logit-level control, seeding, and more.
41
+
42
+ - **Structured JSON Generation**: WebLLM supports state-of-the-art JSON mode structured generation, implemented in the WebAssembly portion of the model library for optimal performance. Check [WebLLM JSON Playground](https://huggingface.co/spaces/mlc-ai/WebLLM-JSON-Playground) on HuggingFace to try generating JSON output with custom JSON schema.
43
+
44
+ - [**Extensive Model Support**](#built-in-models): WebLLM natively supports a range of models including Llama 3, Phi 3, Gemma, Mistral, Qwen(通义千问), and many others, making it versatile for various AI tasks. For the complete supported model list, check [MLC Models](https://mlc.ai/models).
45
+
46
+ - [**Custom Model Integration**](#custom-models): Easily integrate and deploy custom models in MLC format, allowing you to adapt WebLLM to specific needs and scenarios, enhancing flexibility in model deployment.
47
+
48
+ - **Plug-and-Play Integration**: Easily integrate WebLLM into your projects using package managers like NPM and Yarn, or directly via CDN, complete with comprehensive [examples](./examples/) and a modular design for connecting with UI components.
49
+
50
+ - **Streaming & Real-Time Interactions**: Supports streaming chat completions, allowing real-time output generation which enhances interactive applications like chatbots and virtual assistants.
51
+
52
+ - **Web Worker & Service Worker Support**: Optimize UI performance and manage the lifecycle of models efficiently by offloading computations to separate worker threads or service workers.
53
+
54
+ - **Chrome Extension Support**: Extend the functionality of web browsers through custom Chrome extensions using WebLLM, with examples available for building both basic and advanced extensions.
55
+
56
+ ## Built-in Models
57
+
58
+ Check the complete list of available models on [MLC Models](https://mlc.ai/models). WebLLM supports a subset of these available models and the list can be accessed at [`prebuiltAppConfig.model_list`](https://github.com/mlc-ai/web-llm/blob/main/src/config.ts#L293).
59
+
60
+ Here are the primary families of models currently supported:
61
+
62
+ - **Llama**: Llama 3, Llama 2, Hermes-2-Pro-Llama-3
63
+ - **Phi**: Phi 3, Phi 2, Phi 1.5
64
+ - **Gemma**: Gemma-2B
65
+ - **Mistral**: Mistral-7B-v0.3, Hermes-2-Pro-Mistral-7B, NeuralHermes-2.5-Mistral-7B, OpenHermes-2.5-Mistral-7B
66
+ - **Qwen (通义千问)**: Qwen2 0.5B, 1.5B, 7B
67
+
68
+ If you need more models, [request a new model via opening an issue](https://github.com/mlc-ai/web-llm/issues/new/choose) or check [Custom Models](#custom-models) for how to compile and use your own models with WebLLM.
69
+
70
+ ## Jumpstart with Examples
71
+
72
+ Learn how to use WebLLM to integrate large language models into your application and generate chat completions through this simple Chatbot example:
73
+
74
+ [![Example Chatbot on JSFiddle](https://img.shields.io/badge/Example-JSFiddle-blue?logo=jsfiddle&logoColor=white)](https://jsfiddle.net/neetnestor/4nmgvsa2/)
75
+ [![Example Chatbot on Codepen](https://img.shields.io/badge/Example-Codepen-gainsboro?logo=codepen)](https://codepen.io/neetnestor/pen/vYwgZaG)
76
+
77
+ For an advanced example of a larger, more complicated project, check [WebLLM Chat](https://github.com/mlc-ai/web-llm-chat/blob/main/app/client/webllm.ts).
78
+
79
+ More examples for different use cases are available in the [examples](./examples/) folder.
80
+
81
+ ## Get Started
82
+
83
+ WebLLM offers a minimalist and modular interface to access the chatbot in the browser.
84
+ The package is designed in a modular way to hook to any of the UI components.
85
+
86
+ ### Installation
87
+
88
+ #### Package Manager
89
+
90
+ ```sh
91
+ # npm
92
+ npm install @mlc-ai/web-llm
93
+ # yarn
94
+ yarn add @mlc-ai/web-llm
95
+ # or pnpm
96
+ pnpm install @mlc-ai/web-llm
97
+ ```
98
+
99
+ Then import the module in your code.
100
+
101
+ ```typescript
102
+ // Import everything
103
+ import * as webllm from "@mlc-ai/web-llm";
104
+ // Or only import what you need
105
+ import { CreateMLCEngine } from "@mlc-ai/web-llm";
106
+ ```
107
+
108
+ #### CDN Delivery
109
+
110
+ Thanks to [jsdelivr.com](https://www.jsdelivr.com/package/npm/@mlc-ai/web-llm), WebLLM can be imported directly through URL and work out-of-the-box on cloud development platforms like [jsfiddle.net](https://jsfiddle.net/), [Codepen.io](https://codepen.io/), and [Scribbler](https://scribbler.live):
111
+
112
+ ```javascript
113
+ import * as webllm from "https://esm.run/@mlc-ai/web-llm";
114
+ ```
115
+
116
+ It can also be dynamically imported as:
117
+
118
+ ```javascript
119
+ const webllm = await import("https://esm.run/@mlc-ai/web-llm");
120
+ ```
121
+
122
+ ### Create MLCEngine
123
+
124
+ Most operations in WebLLM are invoked through the `MLCEngine` interface. You can create an `MLCEngine` instance and loading the model by calling the `CreateMLCEngine()` factory function.
125
+
126
+ (Note that loading models requires downloading and it can take a significant amount of time for the very first run without caching previously. You should properly handle this asynchronous call.)
127
+
128
+ ```typescript
129
+ import { CreateMLCEngine } from "@mlc-ai/web-llm";
130
+
131
+ // Callback function to update model loading progress
132
+ const initProgressCallback = (initProgress) => {
133
+ console.log(initProgress);
134
+ };
135
+ const selectedModel = "Llama-3.1-8B-Instruct-q4f32_1-MLC";
136
+
137
+ const engine = await CreateMLCEngine(
138
+ selectedModel,
139
+ { initProgressCallback: initProgressCallback }, // engineConfig
140
+ );
141
+ ```
142
+
143
+ Under the hood, this factory function does the following steps for first creating an engine instance (synchronous) and then loading the model (asynchronous). You can also do them separately in your application.
144
+
145
+ ```typescript
146
+ import { MLCEngine } from "@mlc-ai/web-llm";
147
+
148
+ // This is a synchronous call that returns immediately
149
+ const engine = new MLCEngine({
150
+ initProgressCallback: initProgressCallback,
151
+ });
152
+
153
+ // This is an asynchronous call and can take a long time to finish
154
+ await engine.reload(selectedModel);
155
+ ```
156
+
157
+ ### Cache Backend Policy
158
+
159
+ WebLLM supports three cache backends through `AppConfig.cacheBackend`:
160
+
161
+ - `"cache"`: browser [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache) (default).
162
+ - `"indexeddb"`: browser [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API).
163
+ - `"cross-origin"`: experimental Chrome [Cross-Origin Storage API](https://github.com/WICG/cross-origin-storage) extension backend. Install the [Cross-Origin Storage extension](https://chromewebstore.google.com/detail/cross-origin-storage/denpnpcgjgikjpoglpjefakmdcbmlgih) to use it. (If the extension isn't installed, WebLLM falls back to the default cache automatically.)
164
+
165
+ Example:
166
+
167
+ ```typescript
168
+ import { CreateMLCEngine, prebuiltAppConfig } from "@mlc-ai/web-llm";
169
+
170
+ const appConfig = { ...prebuiltAppConfig, cacheBackend: "cross-origin" };
171
+ const engine = await CreateMLCEngine("Llama-3.1-8B-Instruct-q4f32_1-MLC", {
172
+ appConfig,
173
+ });
174
+ ```
175
+
176
+ Notes:
177
+ - The `"cross-origin"` backend requires installing and enabling a compatible browser extension.
178
+ - Cross-origin backend currently does not support programmatic tensor-cache deletion; clearing is extension-managed.
179
+
180
+ ### Chat Completion
181
+
182
+ After successfully initializing the engine, you can now invoke chat completions using OpenAI style chat APIs through the `engine.chat.completions` interface. For the full list of parameters and their descriptions, check [section below](#full-openai-compatibility) and [OpenAI API reference](https://platform.openai.com/docs/api-reference/chat/create).
183
+
184
+ (Note: The `model` parameter is not supported and will be ignored here. Instead, call `CreateMLCEngine(model)` or `engine.reload(model)` instead as shown in the [Create MLCEngine](#create-mlcengine) above.)
185
+
186
+ ```typescript
187
+ const messages = [
188
+ { role: "system", content: "You are a helpful AI assistant." },
189
+ { role: "user", content: "Hello!" },
190
+ ];
191
+
192
+ const reply = await engine.chat.completions.create({
193
+ messages,
194
+ });
195
+ console.log(reply.choices[0].message);
196
+ console.log(reply.usage);
197
+ ```
198
+
199
+ ### Streaming
200
+
201
+ WebLLM also supports streaming chat completion generating. To use it, simply pass `stream: true` to the `engine.chat.completions.create` call.
202
+
203
+ ```typescript
204
+ const messages = [
205
+ { role: "system", content: "You are a helpful AI assistant." },
206
+ { role: "user", content: "Hello!" },
207
+ ];
208
+
209
+ // Chunks is an AsyncGenerator object
210
+ const chunks = await engine.chat.completions.create({
211
+ messages,
212
+ temperature: 1,
213
+ stream: true, // <-- Enable streaming
214
+ stream_options: { include_usage: true },
215
+ });
216
+
217
+ let reply = "";
218
+ for await (const chunk of chunks) {
219
+ reply += chunk.choices[0]?.delta.content || "";
220
+ console.log(reply);
221
+ if (chunk.usage) {
222
+ console.log(chunk.usage); // only last chunk has usage
223
+ }
224
+ }
225
+
226
+ const fullReply = await engine.getMessage();
227
+ console.log(fullReply);
228
+ ```
229
+
230
+ ## Advanced Usage
231
+
232
+ ### Using Workers
233
+
234
+ You can put the heavy computation in a worker script to optimize your application performance. To do so, you need to:
235
+
236
+ 1. Create a handler in the worker thread that communicates with the frontend while handling the requests.
237
+ 2. Create a Worker Engine in your main application, which under the hood sends messages to the handler in the worker thread.
238
+
239
+ For detailed implementations of different kinds of Workers, check the following sections.
240
+
241
+ #### Dedicated Web Worker
242
+
243
+ WebLLM comes with API support for WebWorker so you can hook
244
+ the generation process into a separate worker thread so that
245
+ the computing in the worker thread won't disrupt the UI.
246
+
247
+ We create a handler in the worker thread that communicates with the frontend while handling the requests.
248
+
249
+ ```typescript
250
+ // worker.ts
251
+ import { WebWorkerMLCEngineHandler } from "@mlc-ai/web-llm";
252
+
253
+ // A handler that resides in the worker thread
254
+ const handler = new WebWorkerMLCEngineHandler();
255
+ self.onmessage = (msg: MessageEvent) => {
256
+ handler.onmessage(msg);
257
+ };
258
+ ```
259
+
260
+ In the main logic, we create a `WebWorkerMLCEngine` that
261
+ implements the same `MLCEngineInterface`. The rest of the logic remains the same.
262
+
263
+ ```typescript
264
+ // main.ts
265
+ import { CreateWebWorkerMLCEngine } from "@mlc-ai/web-llm";
266
+
267
+ async function main() {
268
+ // Use a WebWorkerMLCEngine instead of MLCEngine here
269
+ const engine = await CreateWebWorkerMLCEngine(
270
+ new Worker(new URL("./worker.ts", import.meta.url), {
271
+ type: "module",
272
+ }),
273
+ selectedModel,
274
+ { initProgressCallback }, // engineConfig
275
+ );
276
+
277
+ // everything else remains the same
278
+ }
279
+ ```
280
+
281
+ ### Use Service Worker
282
+
283
+ WebLLM comes with API support for ServiceWorker so you can hook the generation process
284
+ into a service worker to avoid reloading the model in every page visit and optimize
285
+ your application's offline experience.
286
+
287
+ (Note, Service Worker's life cycle is managed by the browser and can be killed any time without notifying the webapp. `ServiceWorkerMLCEngine` will try to keep the service worker thread alive by periodically sending heartbeat events, but your application should also include proper error handling. Check `keepAliveMs` and `missedHeatbeat` in [`ServiceWorkerMLCEngine`](https://github.com/mlc-ai/web-llm/blob/main/src/service_worker.ts#L234) for more details.)
288
+
289
+ We create a handler in the worker thread that communicates with the frontend while handling the requests.
290
+
291
+ ```typescript
292
+ // sw.ts
293
+ import { ServiceWorkerMLCEngineHandler } from "@mlc-ai/web-llm";
294
+
295
+ let handler: ServiceWorkerMLCEngineHandler;
296
+
297
+ self.addEventListener("activate", function (event) {
298
+ handler = new ServiceWorkerMLCEngineHandler();
299
+ console.log("Service Worker is ready");
300
+ });
301
+ ```
302
+
303
+ Then in the main logic, we register the service worker and create the engine using
304
+ `CreateServiceWorkerMLCEngine` function. The rest of the logic remains the same.
305
+
306
+ ```typescript
307
+ // main.ts
308
+ import {
309
+ MLCEngineInterface,
310
+ CreateServiceWorkerMLCEngine,
311
+ } from "@mlc-ai/web-llm";
312
+
313
+ if ("serviceWorker" in navigator) {
314
+ navigator.serviceWorker.register(
315
+ new URL("sw.ts", import.meta.url), // worker script
316
+ { type: "module" },
317
+ );
318
+ }
319
+
320
+ const engine: MLCEngineInterface = await CreateServiceWorkerMLCEngine(
321
+ selectedModel,
322
+ { initProgressCallback }, // engineConfig
323
+ );
324
+ ```
325
+
326
+ You can find a complete example on how to run WebLLM in service worker in [examples/service-worker](examples/service-worker/).
327
+
328
+ ### Chrome Extension
329
+
330
+ You can also find examples of building Chrome extension with WebLLM in [examples/chrome-extension](examples/chrome-extension/) and [examples/chrome-extension-webgpu-service-worker](examples/chrome-extension-webgpu-service-worker/). The latter one leverages service worker, so the extension is persistent in the background. Additionally, you can explore another full project of a Chrome extension, WebLLM Assistant, which leverages WebLLM [here](https://github.com/mlc-ai/web-llm-assistant).
331
+
332
+ ## Full OpenAI Compatibility
333
+
334
+ WebLLM is designed to be fully compatible with [OpenAI API](https://platform.openai.com/docs/api-reference/chat). Thus, besides building a simple chatbot, you can also have the following functionalities with WebLLM:
335
+
336
+ - [streaming](examples/streaming): return output as chunks in real-time in the form of an AsyncGenerator
337
+ - [json-mode](examples/json-mode): efficiently ensure output is in JSON format, see [OpenAI Reference](https://platform.openai.com/docs/guides/text-generation/chat-completions-api) for more.
338
+ - [seed-to-reproduce](examples/seed-to-reproduce): use seeding to ensure a reproducible output with fields `seed`.
339
+ - [function-calling](examples/function-calling) (WIP): function calling with fields `tools` and `tool_choice` (with preliminary support); or manual function calling without `tools` or `tool_choice` (keeps the most flexibility).
340
+
341
+ ## Integrity Verification
342
+
343
+ WebLLM supports optional integrity verification for model artifacts using
344
+ [SRI (Subresource Integrity)](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) hashes.
345
+ When the `integrity` field is set on a `ModelRecord`, WebLLM will verify the downloaded config,
346
+ WASM, and tokenizer files against the provided hashes before loading.
347
+
348
+ ```typescript
349
+ import { CreateMLCEngine } from "@mlc-ai/web-llm";
350
+
351
+ const appConfig = {
352
+ model_list: [
353
+ {
354
+ model: "https://huggingface.co/mlc-ai/Llama-3.2-1B-Instruct-q4f16_1-MLC",
355
+ model_id: "Llama-3.2-1B-Instruct-q4f16_1-MLC",
356
+ model_lib:
357
+ "https://raw.githubusercontent.com/user/model-libs/main/model.wasm",
358
+ integrity: {
359
+ config: "sha256-<base64-hash-of-mlc-chat-config.json>",
360
+ model_lib: "sha256-<base64-hash-of-wasm-file>",
361
+ tokenizer: {
362
+ "tokenizer.json": "sha256-<base64-hash-of-tokenizer.json>",
363
+ },
364
+ onFailure: "error", // "error" (default) throws IntegrityError, "warn" logs and continues
365
+ },
366
+ },
367
+ ],
368
+ };
369
+
370
+ const engine = await CreateMLCEngine("Llama-3.2-1B-Instruct-q4f16_1-MLC", {
371
+ appConfig,
372
+ });
373
+ ```
374
+
375
+ You can generate SRI hashes for model files with:
376
+
377
+ ```bash
378
+ # SHA-256
379
+ openssl dgst -sha256 -binary <file> | openssl base64 -A | sed 's/^/sha256-/'
380
+ # SHA-384
381
+ openssl dgst -sha384 -binary <file> | openssl base64 -A | sed 's/^/sha384-/'
382
+ # SHA-512
383
+ openssl dgst -sha512 -binary <file> | openssl base64 -A | sed 's/^/sha512-/'
384
+ ```
385
+
386
+ > The `openssl` commands require a Unix-like shell (macOS/Linux). On Windows, run `openssl` via [Git Bash](https://gitforwindows.org/) or [WSL](https://learn.microsoft.com/en-us/windows/wsl/).
387
+
388
+ If a hash does not match, an `IntegrityError` is thrown (or a warning is logged when `onFailure: "warn"`).
389
+ All fields in `integrity` are optional — only specified artifacts will be verified.
390
+ When the `integrity` field is omitted entirely, WebLLM behaves exactly as before (no verification).
391
+
392
+ See the [integrity-verification example](examples/integrity-verification/) for a complete working demo.
393
+
394
+ ## Custom Models
395
+
396
+ WebLLM works as a companion project of [MLC LLM](https://github.com/mlc-ai/mlc-llm) and it supports custom models in MLC format.
397
+ It reuses the model artifact and builds the flow of MLC LLM. To compile and use your own models with WebLLM, please check out
398
+ [MLC LLM document](https://llm.mlc.ai/docs/deploy/webllm.html)
399
+ on how to compile and deploy new model weights and libraries to WebLLM.
400
+
401
+ Here, we go over the high-level idea. There are two elements of the WebLLM package that enable new models and weight variants.
402
+
403
+ - `model`: Contains a URL to model artifacts, such as weights and meta-data.
404
+ - `model_lib`: A URL to the web assembly library (i.e. wasm file) that contains the executables to accelerate the model computations.
405
+
406
+ Both are customizable in the WebLLM.
407
+
408
+ ```typescript
409
+ import { CreateMLCEngine } from "@mlc-ai/web-llm";
410
+
411
+ async main() {
412
+ const appConfig = {
413
+ "model_list": [
414
+ {
415
+ "model": "/url/to/my/llama",
416
+ "model_id": "MyLlama-3b-v1-q4f32_0",
417
+ "model_lib": "/url/to/myllama3b.wasm",
418
+ }
419
+ ],
420
+ };
421
+ // override default
422
+ const chatOpts = {
423
+ "repetition_penalty": 1.01
424
+ };
425
+
426
+ // load a prebuilt model
427
+ // with a chat option override and app config
428
+ // under the hood, it will load the model from myLlamaUrl
429
+ // and cache it in the browser cache
430
+ // The chat will also load the model library from "/url/to/myllama3b.wasm",
431
+ // assuming that it is compatible to the model in myLlamaUrl.
432
+ const engine = await CreateMLCEngine(
433
+ "MyLlama-3b-v1-q4f32_0",
434
+ { appConfig }, // engineConfig
435
+ chatOpts,
436
+ );
437
+ }
438
+ ```
439
+
440
+ In many cases, we only want to supply the model weight variant, but
441
+ not necessarily a new model (e.g. `NeuralHermes-Mistral` can reuse `Mistral`'s
442
+ model library). For examples of how a model library can be shared by different model variants,
443
+ see `webllm.prebuiltAppConfig`.
444
+
445
+ ## Build WebLLM Package From Source
446
+
447
+ NOTE: you don't need to build from source unless you would like to modify the WebLLM package.
448
+ To use the npm, simply follow [Get Started](#get-started) or any of the [examples](examples) instead.
449
+
450
+ To build from source, simply run:
451
+
452
+ ```bash
453
+ npm install
454
+ npm run build
455
+ ```
456
+
457
+ Then, to test the effects of your code change in an example, inside `examples/get-started/package.json`, change from `"@mlc-ai/web-llm": "^0.2.82"` to `"@mlc-ai/web-llm": ../..`.
458
+
459
+ Then run:
460
+
461
+ ```bash
462
+ cd examples/get-started
463
+ npm install
464
+ npm start
465
+ ```
466
+
467
+ Note that sometimes you would need to switch between `file:../..` and `../..` to trigger npm to recognize new changes. In the worst case, you can run:
468
+
469
+ ```bash
470
+ cd examples/get-started
471
+ rm -rf node_modules dist package-lock.json .parcel-cache
472
+ npm install
473
+ npm start
474
+ ```
475
+
476
+ ### In case you need to build TVMjs from source
477
+
478
+ WebLLM's runtime largely depends on TVMjs: https://github.com/apache/tvm/tree/main/web
479
+
480
+ While it is also available as an npm package: https://www.npmjs.com/package/@mlc-ai/web-runtime, you can build it from source if needed by following the steps below.
481
+
482
+ 1. Install [emscripten](https://emscripten.org). It is an LLVM-based compiler that compiles C/C++ source code to WebAssembly.
483
+ - Follow the [installation instruction](https://emscripten.org/docs/getting_started/downloads.html#installation-instructions-using-the-emsdk-recommended) to install the latest emsdk.
484
+ - Source `emsdk_env.sh` by `source path/to/emsdk_env.sh`, so that `emcc` is reachable from PATH and the command `emcc` works.
485
+
486
+ We can verify the successful installation by trying out `emcc` terminal.
487
+
488
+ Note: We recently found that using the latest `emcc` version may run into issues during runtime. Use `./emsdk install 3.1.56` instead of `./emsdk install latest` for now as a workaround. The error may look like
489
+
490
+ ```
491
+ Init error, LinkError: WebAssembly.instantiate(): Import #6 module="wasi_snapshot_preview1"
492
+ function="proc_exit": function import requires a callable
493
+ ```
494
+
495
+ 2. In `./package.json`, change from `"@mlc-ai/web-runtime": "0.18.0-dev2",` to `"@mlc-ai/web-runtime": "file:./tvm_home/web",`.
496
+
497
+ 3. Setup necessary environment
498
+
499
+ Prepare all the necessary dependencies for web build:
500
+
501
+ ```shell
502
+ ./scripts/prep_deps.sh
503
+ ```
504
+
505
+ In this step, if `$TVM_SOURCE_DIR` is not defined in the environment, we will execute the following line to build `tvmjs` dependency:
506
+
507
+ ```shell
508
+ git clone https://github.com/mlc-ai/relax 3rdparty/tvm-unity --recursive
509
+ ```
510
+
511
+ This clones the current HEAD of `mlc-ai/relax`. However, it may not always be the correct branch or commit to clone. To build a specific npm version from source, refer to the version bump PR, which states which branch (i.e. `mlc-ai/relax` or `apache/tvm`) and which commit the current WebLLM version depends on. For instance, version 0.2.52, according to its version bump PR https://github.com/mlc-ai/web-llm/pull/521, is built by checking out the following commit https://github.com/apache/tvm/commit/e6476847753c80e054719ac47bc2091c888418b6 in `apache/tvm`, rather than the HEAD of `mlc-ai/relax`.
512
+
513
+ Besides, `--recursive` is necessary and important. Otherwise, you may encounter errors like `fatal error: 'dlpack/dlpack.h' file not found`.
514
+
515
+ 4. Build WebLLM Package
516
+
517
+ ```shell
518
+ npm run build
519
+ ```
520
+
521
+ 5. Validate some of the sub-packages
522
+
523
+ You can then go to the subfolders in [examples](examples) to validate some of the sub-packages.
524
+ We use Parcelv2 for bundling. Although Parcel is not very good at tracking parent directory
525
+ changes sometimes. When you make a change in the WebLLM package, try to edit the `package.json`
526
+ of the subfolder and save it, which will trigger Parcel to rebuild.
527
+
528
+ ## Links
529
+
530
+ - [Demo App: WebLLM Chat](https://chat.webllm.ai/)
531
+ - If you want to run LLM on native runtime, check out [MLC-LLM](https://github.com/mlc-ai/mlc-llm)
532
+ - You might also be interested in [Web Stable Diffusion](https://github.com/mlc-ai/web-stable-diffusion/).
533
+
534
+ ## Acknowledgement
535
+
536
+ This project is initiated by members from CMU Catalyst, UW SAMPL, SJTU, OctoML, and the MLC community. We would love to continue developing and supporting the open-source ML community.
537
+
538
+ This project is only possible thanks to the shoulders open-source ecosystems that we stand on. We want to thank the Apache TVM community and developers of the TVM Unity effort. The open-source ML community members made these models publicly available. PyTorch and Hugging Face communities make these models accessible. We would like to thank the teams behind Vicuna, SentencePiece, LLaMA, and Alpaca. We also would like to thank the WebAssembly, Emscripten, and WebGPU communities. Finally, thanks to Dawn and WebGPU developers.
539
+
540
+ ## Citation
541
+
542
+ If you find this project to be useful, please cite:
543
+
544
+ ```
545
+ @misc{ruan2024webllmhighperformanceinbrowserllm,
546
+ title={WebLLM: A High-Performance In-Browser LLM Inference Engine},
547
+ author={Charlie F. Ruan and Yucheng Qin and Xun Zhou and Ruihang Lai and Hongyi Jin and Yixin Dong and Bohan Hou and Meng-Shiun Yu and Yiyan Zhai and Sudeep Agarwal and Hangrui Cao and Siyuan Feng and Tianqi Chen},
548
+ year={2024},
549
+ eprint={2412.15803},
550
+ archivePrefix={arXiv},
551
+ primaryClass={cs.LG},
552
+ url={https://arxiv.org/abs/2412.15803},
553
+ }
554
+ ```
555
+
556
+ ## Contributors
557
+
558
+ <a href="https://github.com/mlc-ai/web-llm/graphs/contributors">
559
+ <img alt="contributors" src="https://contrib.rocks/image?repo=mlc-ai/web-llm"/>
560
+ </a>
561
+
562
+ <p align="right">
563
+ <a href="#top">⬆ Back to Top ⬆</a>
564
+ </p>
@@ -0,0 +1,19 @@
1
+ import { AppConfig, ChatConfig } from "./config";
2
+ import { Tokenizer } from "@mlc-ai/web-tokenizers";
3
+ import { ModelIntegrity } from "./integrity";
4
+ export declare function hasModelInCache(modelId: string, appConfig?: AppConfig): Promise<boolean>;
5
+ export declare function deleteModelAllInfoInCache(modelId: string, appConfig?: AppConfig): Promise<void>;
6
+ export declare function deleteModelInCache(modelId: string, appConfig?: AppConfig): Promise<void>;
7
+ export declare function deleteChatConfigInCache(modelId: string, appConfig?: AppConfig): Promise<void>;
8
+ export declare function deleteModelWasmInCache(modelId: string, appConfig?: AppConfig): Promise<void>;
9
+ /**
10
+ *
11
+ * @param baseUrl The link to which we can find tokenizer files, usually is a `ModelRecord.model`.
12
+ * @param config A ChatConfig, usually loaded from `mlc-chat-config.json` in `baseUrl`.
13
+ * @param appConfig An AppConfig, usually `webllm.prebuiltAppConfig` if not defined by user.
14
+ * @param logger Logging function, console.log by default.
15
+ * @param integrity Optional integrity configuration for verifying tokenizer files.
16
+ * @returns
17
+ */
18
+ export declare function asyncLoadTokenizer(baseUrl: string, config: ChatConfig, appConfig: AppConfig, logger?: (msg: string) => void, integrity?: ModelIntegrity): Promise<Tokenizer>;
19
+ //# sourceMappingURL=cache_util.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache_util.d.ts","sourceRoot":"","sources":["../src/cache_util.ts"],"names":[],"mappings":"AACA,OAAO,EACL,SAAS,EACT,UAAU,EAIX,MAAM,UAAU,CAAC;AAGlB,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAmB,MAAM,aAAa,CAAC;AA8C9D,wBAAsB,eAAe,CACnC,OAAO,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,SAAS,GACpB,OAAO,CAAC,OAAO,CAAC,CAUlB;AAED,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,SAAS,iBAYtB;AAED,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,SAAS,iBAetB;AAED,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,SAAS,iBAWtB;AAED,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,SAAS,iBAStB;AAED;;;;;;;;GAQG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,UAAU,EAClB,SAAS,EAAE,SAAS,EACpB,MAAM,GAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAkB,EAC3C,SAAS,CAAC,EAAE,cAAc,GACzB,OAAO,CAAC,SAAS,CAAC,CAgCpB"}