webslm-react 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +101 -2
- package/dist/index.d.ts +16 -0
- package/dist/index.js +15 -0
- package/dist/use-capabilities.d.ts +6 -0
- package/dist/use-capabilities.js +10 -0
- package/dist/use-chat.d.ts +37 -0
- package/dist/use-chat.js +113 -0
- package/dist/use-llm.d.ts +52 -0
- package/dist/use-llm.js +100 -0
- package/dist/use-load.d.ts +25 -0
- package/dist/use-load.js +102 -0
- package/dist/use-model-search.d.ts +21 -0
- package/dist/use-model-search.js +46 -0
- package/dist/use-model.d.ts +22 -0
- package/dist/use-model.js +16 -0
- package/package.json +58 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Maxime Golfier
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,102 @@
|
|
|
1
|
-
#
|
|
1
|
+
# webslm-react
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
React hooks for [webslm](https://www.npmjs.com/package/webslm): run a small language model in the browser, ask it, chat with it and search the Hugging Face Hub, from components.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install webslm webslm-react
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```tsx
|
|
10
|
+
import { useLLM } from "webslm-react";
|
|
11
|
+
|
|
12
|
+
const { ask } = useLLM(); // loads webslm's DEFAULT_MODEL
|
|
13
|
+
<button onClick={async () => alert(await ask("Write a haiku about the sea"))}>Ask</button>;
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Peer dependencies: `react` 18 or later and `webslm`. See the webslm README for the bundler settings (Vite: `optimizeDeps.exclude: ["webslm"]` and `worker.format: "es"`). The hooks load models in effects, so server rendering (Next.js and others) never starts one; in the Next.js App Router, use them from client components (`"use client"`). Guide: <https://github.com/maxgfr/webslm/blob/main/docs/nextjs.md>.
|
|
17
|
+
|
|
18
|
+
## useLLM
|
|
19
|
+
|
|
20
|
+
```tsx
|
|
21
|
+
import { useState } from "react";
|
|
22
|
+
import { useLLM } from "webslm-react";
|
|
23
|
+
|
|
24
|
+
export function Story() {
|
|
25
|
+
const { stream, status, progress, error } = useLLM("HuggingFaceTB/SmolLM2-360M-Instruct");
|
|
26
|
+
const [text, setText] = useState("");
|
|
27
|
+
|
|
28
|
+
async function tell() {
|
|
29
|
+
setText("");
|
|
30
|
+
for await (const piece of stream("Tell me a short story")) setText((t) => t + piece);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (status === "error") return <p>{error?.message}</p>;
|
|
34
|
+
return (
|
|
35
|
+
<div>
|
|
36
|
+
{status === "loading" && <progress value={progress?.overallLoadedBytes} max={progress?.overallTotalBytes} />}
|
|
37
|
+
<button onClick={tell}>Tell a story</button>
|
|
38
|
+
<p>{text}</p>
|
|
39
|
+
</div>
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`useLLM(model?, options?)` loads with webslm's `load` and returns `{ llm, ask, stream, chat, status, progress, error }`. `ask`, `stream` and `chat` are webslm's simple API (same options: `maxTokens`, `temperature`, `system`, `think`, `withReasoning`...); they can be called while the model loads and wait for it. `chat(options)` returns a conversation that remembers its turns; a new `chat` function comes with each new model, so `useMemo(() => chat({ system: "Be brief." }), [chat])` keeps one conversation per model. The model is unloaded when the source or a load option changes and on unmount; pass `null` to load nothing.
|
|
45
|
+
|
|
46
|
+
## useModel and useChat
|
|
47
|
+
|
|
48
|
+
For a chat UI with React state (messages, streaming text, timing), use `useModel` and `useChat`:
|
|
49
|
+
|
|
50
|
+
```tsx
|
|
51
|
+
import { useState } from "react";
|
|
52
|
+
import { useChat, useModel } from "webslm-react";
|
|
53
|
+
|
|
54
|
+
export function Chat() {
|
|
55
|
+
const { model, status, progress, error } = useModel("HuggingFaceTB/SmolLM2-135M-Instruct", {
|
|
56
|
+
quant: "q8",
|
|
57
|
+
});
|
|
58
|
+
const { messages, send, stop, isGenerating, streamingText, lastResult } = useChat(model, {
|
|
59
|
+
maxTokens: 256,
|
|
60
|
+
});
|
|
61
|
+
const [draft, setDraft] = useState("");
|
|
62
|
+
|
|
63
|
+
if (status === "loading") {
|
|
64
|
+
return <progress value={progress?.overallLoadedBytes} max={progress?.overallTotalBytes} />;
|
|
65
|
+
}
|
|
66
|
+
if (status === "error") return <p>{error?.message}</p>;
|
|
67
|
+
|
|
68
|
+
return (
|
|
69
|
+
<div>
|
|
70
|
+
{messages.map((m, i) => (
|
|
71
|
+
<p key={i}>
|
|
72
|
+
<b>{m.role}</b> {m.content}
|
|
73
|
+
</p>
|
|
74
|
+
))}
|
|
75
|
+
{isGenerating && <p>{streamingText}</p>}
|
|
76
|
+
{lastResult && <small>{lastResult.tokensPerSecond.toFixed(1)} tokens/s</small>}
|
|
77
|
+
<form
|
|
78
|
+
onSubmit={(e) => {
|
|
79
|
+
e.preventDefault();
|
|
80
|
+
send(draft);
|
|
81
|
+
setDraft("");
|
|
82
|
+
}}
|
|
83
|
+
>
|
|
84
|
+
<input value={draft} onChange={(e) => setDraft(e.target.value)} />
|
|
85
|
+
{isGenerating ? <button type="button" onClick={stop}>Stop</button> : <button>Send</button>}
|
|
86
|
+
</form>
|
|
87
|
+
</div>
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Hooks
|
|
93
|
+
|
|
94
|
+
- `useLLM(model, options)` returns `{ llm, ask, stream, chat, status, progress, error }` (see above).
|
|
95
|
+
- `useModel(source, options)` returns `{ model, status, progress, error }` with `status` one of `"idle" | "loading" | "ready" | "error"`. It loads when the source (a hub repo id or a `ModelSource`) or a load option changes, and unloads the previous model and on unmount. Pass `null` to load nothing.
|
|
96
|
+
- `useChat(model, options)` returns `{ messages, send, stop, clear, setMessages, isGenerating, streamingText, lastResult, error }`. Options are webslm's generation options plus `system`, `initialMessages`, `onFinish` and `onError`.
|
|
97
|
+
- `useModelSearch(query, options)` returns `{ results, status, error }`, searching the Hub as the query changes (debounced, stale requests cancelled). Each result says whether webslm can run it, whether it is gated, and its size.
|
|
98
|
+
- `useCapabilities()` reports WebGPU, SIMD, threads and cross-origin isolation.
|
|
99
|
+
|
|
100
|
+
## License
|
|
101
|
+
|
|
102
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React bindings for webslm: load a model, ask it, chat with it and search
|
|
3
|
+
* the Hugging Face Hub from components.
|
|
4
|
+
*
|
|
5
|
+
* ```tsx
|
|
6
|
+
* const { ask, status } = useLLM();
|
|
7
|
+
* ```
|
|
8
|
+
*
|
|
9
|
+
* @packageDocumentation
|
|
10
|
+
*/
|
|
11
|
+
export { useCapabilities } from "./use-capabilities.js";
|
|
12
|
+
export { useChat, type UseChatOptions, type UseChatResult } from "./use-chat.js";
|
|
13
|
+
export { useLLM, type UseLLMAsk, type UseLLMResult } from "./use-llm.js";
|
|
14
|
+
export { useModel, type ModelStatus, type UseModelOptions, type UseModelResult, } from "./use-model.js";
|
|
15
|
+
export { useModelSearch, type UseModelSearchOptions, type UseModelSearchResult, } from "./use-model-search.js";
|
|
16
|
+
export type { Answer, AskOptions, Capabilities, Chat, ChatOptions, ChatMessage, GenerationResult, HubModel, LLM, LoadProgress, Model, ModelInfo, ModelSource, PromptOptions, TextStream, WebslmError, } from "webslm";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React bindings for webslm: load a model, ask it, chat with it and search
|
|
3
|
+
* the Hugging Face Hub from components.
|
|
4
|
+
*
|
|
5
|
+
* ```tsx
|
|
6
|
+
* const { ask, status } = useLLM();
|
|
7
|
+
* ```
|
|
8
|
+
*
|
|
9
|
+
* @packageDocumentation
|
|
10
|
+
*/
|
|
11
|
+
export { useCapabilities } from "./use-capabilities.js";
|
|
12
|
+
export { useChat } from "./use-chat.js";
|
|
13
|
+
export { useLLM } from "./use-llm.js";
|
|
14
|
+
export { useModel, } from "./use-model.js";
|
|
15
|
+
export { useModelSearch, } from "./use-model-search.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { useState } from "react";
|
|
2
|
+
import { detectCapabilities } from "webslm";
|
|
3
|
+
/**
|
|
4
|
+
* Reports what the browser can do (WebGPU, SIMD, threads, cross-origin
|
|
5
|
+
* isolation). Detection runs once per component, on first render.
|
|
6
|
+
*/
|
|
7
|
+
export function useCapabilities() {
|
|
8
|
+
const [capabilities] = useState(detectCapabilities);
|
|
9
|
+
return capabilities;
|
|
10
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { WebslmError, type ChatMessage, type GenerateOptions, type GenerationResult, type Model } from "webslm";
|
|
2
|
+
export interface UseChatOptions extends Omit<GenerateOptions, "signal"> {
|
|
3
|
+
/** System prompt prepended to every request (not shown in `messages`). */
|
|
4
|
+
readonly system?: string;
|
|
5
|
+
/** Messages to start with. */
|
|
6
|
+
readonly initialMessages?: readonly ChatMessage[];
|
|
7
|
+
/** Called when an answer is complete (or stopped). */
|
|
8
|
+
readonly onFinish?: (message: ChatMessage, result: GenerationResult) => void;
|
|
9
|
+
readonly onError?: (error: WebslmError) => void;
|
|
10
|
+
}
|
|
11
|
+
export interface UseChatResult {
|
|
12
|
+
/** The conversation so far, without the answer being streamed. */
|
|
13
|
+
readonly messages: readonly ChatMessage[];
|
|
14
|
+
/** Sends a user message and streams the answer. Ignored while generating. */
|
|
15
|
+
send(content: string): void;
|
|
16
|
+
/** Stops the current answer; the text so far is kept as the assistant message. */
|
|
17
|
+
stop(): void;
|
|
18
|
+
/** Starts a new conversation. */
|
|
19
|
+
clear(): void;
|
|
20
|
+
/** Replaces the conversation (e.g. to edit or retry). */
|
|
21
|
+
setMessages(messages: readonly ChatMessage[]): void;
|
|
22
|
+
readonly isGenerating: boolean;
|
|
23
|
+
/** The answer being generated. */
|
|
24
|
+
readonly streamingText: string;
|
|
25
|
+
/** Summary of the last answer: timing, token counts, finish reason. */
|
|
26
|
+
readonly lastResult: GenerationResult | undefined;
|
|
27
|
+
readonly error: WebslmError | undefined;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* A chat over a loaded model: keeps the messages, streams answers and
|
|
31
|
+
* reuses the model's cache across turns.
|
|
32
|
+
*
|
|
33
|
+
* ```tsx
|
|
34
|
+
* const { messages, send, stop, isGenerating, streamingText } = useChat(model, { maxTokens: 256 });
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export declare function useChat(model: Model | undefined, options?: UseChatOptions): UseChatResult;
|
package/dist/use-chat.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
2
|
+
import { WebslmError, } from "webslm";
|
|
3
|
+
/**
|
|
4
|
+
* A chat over a loaded model: keeps the messages, streams answers and
|
|
5
|
+
* reuses the model's cache across turns.
|
|
6
|
+
*
|
|
7
|
+
* ```tsx
|
|
8
|
+
* const { messages, send, stop, isGenerating, streamingText } = useChat(model, { maxTokens: 256 });
|
|
9
|
+
* ```
|
|
10
|
+
*/
|
|
11
|
+
export function useChat(model, options = {}) {
|
|
12
|
+
const [messages, setMessagesState] = useState(options.initialMessages ?? []);
|
|
13
|
+
const [streamingText, setStreamingText] = useState("");
|
|
14
|
+
const [isGenerating, setGenerating] = useState(false);
|
|
15
|
+
const [lastResult, setLastResult] = useState();
|
|
16
|
+
const [error, setError] = useState();
|
|
17
|
+
const optionsRef = useRef(options);
|
|
18
|
+
optionsRef.current = options;
|
|
19
|
+
const messagesRef = useRef(messages);
|
|
20
|
+
messagesRef.current = messages;
|
|
21
|
+
const streamRef = useRef(undefined);
|
|
22
|
+
const generationRef = useRef(0);
|
|
23
|
+
const stop = useCallback(() => {
|
|
24
|
+
streamRef.current?.stop();
|
|
25
|
+
}, []);
|
|
26
|
+
// A new model starts a new conversation; unmounting stops the answer.
|
|
27
|
+
useEffect(() => {
|
|
28
|
+
return () => {
|
|
29
|
+
generationRef.current++;
|
|
30
|
+
streamRef.current?.stop();
|
|
31
|
+
streamRef.current = undefined;
|
|
32
|
+
setGenerating(false);
|
|
33
|
+
setStreamingText("");
|
|
34
|
+
};
|
|
35
|
+
}, [model]);
|
|
36
|
+
const send = useCallback((content) => {
|
|
37
|
+
if (model === undefined || streamRef.current !== undefined)
|
|
38
|
+
return;
|
|
39
|
+
const { system, initialMessages, onFinish, onError, ...generate } = optionsRef.current;
|
|
40
|
+
void initialMessages;
|
|
41
|
+
const user = { role: "user", content };
|
|
42
|
+
const history = [...messagesRef.current, user];
|
|
43
|
+
messagesRef.current = history;
|
|
44
|
+
setMessagesState(history);
|
|
45
|
+
setStreamingText("");
|
|
46
|
+
setError(undefined);
|
|
47
|
+
setGenerating(true);
|
|
48
|
+
const generation = ++generationRef.current;
|
|
49
|
+
const request = system === undefined ? history : [{ role: "system", content: system }, ...history];
|
|
50
|
+
let stream;
|
|
51
|
+
try {
|
|
52
|
+
stream = model.chat(request, generate);
|
|
53
|
+
}
|
|
54
|
+
catch (e) {
|
|
55
|
+
const typed = e instanceof WebslmError ? e : new WebslmError("ENGINE", String(e));
|
|
56
|
+
setError(typed);
|
|
57
|
+
setGenerating(false);
|
|
58
|
+
onError?.(typed);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
streamRef.current = stream;
|
|
62
|
+
void (async () => {
|
|
63
|
+
let text = "";
|
|
64
|
+
try {
|
|
65
|
+
for await (const delta of stream) {
|
|
66
|
+
if (generation !== generationRef.current)
|
|
67
|
+
return;
|
|
68
|
+
text += delta;
|
|
69
|
+
setStreamingText(text);
|
|
70
|
+
}
|
|
71
|
+
const result = await stream.result;
|
|
72
|
+
if (generation !== generationRef.current)
|
|
73
|
+
return;
|
|
74
|
+
const answer = { role: "assistant", content: text };
|
|
75
|
+
const next = [...messagesRef.current, answer];
|
|
76
|
+
messagesRef.current = next;
|
|
77
|
+
setMessagesState(next);
|
|
78
|
+
setLastResult(result);
|
|
79
|
+
onFinish?.(answer, result);
|
|
80
|
+
}
|
|
81
|
+
catch (e) {
|
|
82
|
+
if (generation !== generationRef.current)
|
|
83
|
+
return;
|
|
84
|
+
const typed = e instanceof WebslmError ? e : new WebslmError("ENGINE", String(e));
|
|
85
|
+
setError(typed);
|
|
86
|
+
optionsRef.current.onError?.(typed);
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
if (generation === generationRef.current) {
|
|
90
|
+
streamRef.current = undefined;
|
|
91
|
+
setStreamingText("");
|
|
92
|
+
setGenerating(false);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
})();
|
|
96
|
+
}, [model]);
|
|
97
|
+
const clear = useCallback(() => {
|
|
98
|
+
generationRef.current++;
|
|
99
|
+
streamRef.current?.stop();
|
|
100
|
+
streamRef.current = undefined;
|
|
101
|
+
messagesRef.current = [];
|
|
102
|
+
setMessagesState([]);
|
|
103
|
+
setStreamingText("");
|
|
104
|
+
setGenerating(false);
|
|
105
|
+
setLastResult(undefined);
|
|
106
|
+
setError(undefined);
|
|
107
|
+
}, []);
|
|
108
|
+
const setMessages = useCallback((next) => {
|
|
109
|
+
messagesRef.current = next;
|
|
110
|
+
setMessagesState(next);
|
|
111
|
+
}, []);
|
|
112
|
+
return { messages, send, stop, clear, setMessages, isGenerating, streamingText, lastResult, error };
|
|
113
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { WebslmError, type Answer, type AskOptions, type Chat, type ChatOptions, type LLM, type LoadProgress, type ModelSource, type PromptOptions, type TextStream } from "webslm";
|
|
2
|
+
import { type ModelStatus, type UseModelOptions } from "./use-load.js";
|
|
3
|
+
/** `ask` of {@link useLLM}: resolves once the model is loaded and has answered. */
|
|
4
|
+
export interface UseLLMAsk {
|
|
5
|
+
(prompt: string, options: AskOptions & {
|
|
6
|
+
readonly withReasoning: true;
|
|
7
|
+
}): Promise<Answer>;
|
|
8
|
+
(prompt: string, options?: AskOptions & {
|
|
9
|
+
readonly withReasoning?: false;
|
|
10
|
+
}): Promise<string>;
|
|
11
|
+
(prompt: string, options?: AskOptions): Promise<string | Answer>;
|
|
12
|
+
}
|
|
13
|
+
export interface UseLLMResult {
|
|
14
|
+
/** The loaded model, once `status` is `"ready"`. */
|
|
15
|
+
readonly llm: LLM | undefined;
|
|
16
|
+
readonly status: ModelStatus;
|
|
17
|
+
/** Latest progress event of the current load. */
|
|
18
|
+
readonly progress: LoadProgress | undefined;
|
|
19
|
+
readonly error: WebslmError | undefined;
|
|
20
|
+
/** Answers a single prompt. Callable during the load: it waits for the model. */
|
|
21
|
+
readonly ask: UseLLMAsk;
|
|
22
|
+
/** Streams the answer to a single prompt. Callable during the load: it waits for the model. */
|
|
23
|
+
readonly stream: (prompt: string, options?: PromptOptions) => TextStream;
|
|
24
|
+
/**
|
|
25
|
+
* Starts a conversation that remembers its turns. Callable during the load:
|
|
26
|
+
* turns wait for the model. A new function comes with each new model, so
|
|
27
|
+
* `useMemo(() => chat(), [chat])` keeps one conversation per model.
|
|
28
|
+
*/
|
|
29
|
+
readonly chat: (options?: ChatOptions) => Chat;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Loads a model with the simple API (`load` from webslm) and gives
|
|
33
|
+
* `ask`, `stream` and `chat` functions that can be called right away: they
|
|
34
|
+
* wait for the load. The model defaults to `DEFAULT_MODEL`; pass `null` to
|
|
35
|
+
* load nothing. It is unloaded when the source or a load option changes and
|
|
36
|
+
* on unmount.
|
|
37
|
+
*
|
|
38
|
+
* ```tsx
|
|
39
|
+
* function Haiku() {
|
|
40
|
+
* const { ask, status, progress } = useLLM();
|
|
41
|
+
* const [text, setText] = useState("");
|
|
42
|
+
* return (
|
|
43
|
+
* <>
|
|
44
|
+
* <button onClick={async () => setText(await ask("Write a haiku about the sea"))}>Ask</button>
|
|
45
|
+
* {status === "loading" && <progress value={progress?.overallLoadedBytes} max={progress?.overallTotalBytes} />}
|
|
46
|
+
* <p>{text}</p>
|
|
47
|
+
* </>
|
|
48
|
+
* );
|
|
49
|
+
* }
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export declare function useLLM(model?: string | ModelSource | null, options?: UseModelOptions): UseLLMResult;
|
package/dist/use-llm.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { useCallback, useMemo } from "react";
|
|
2
|
+
import { DEFAULT_MODEL, load, WebslmError, } from "webslm";
|
|
3
|
+
import { useLoad } from "./use-load.js";
|
|
4
|
+
/** A stream whose generation starts once `open` resolves. */
|
|
5
|
+
function deferStream(open) {
|
|
6
|
+
let inner;
|
|
7
|
+
let stopped = false;
|
|
8
|
+
const ready = open.then((stream) => {
|
|
9
|
+
inner = stream;
|
|
10
|
+
if (stopped)
|
|
11
|
+
stream.stop();
|
|
12
|
+
return stream;
|
|
13
|
+
});
|
|
14
|
+
const text = ready.then((s) => s.text);
|
|
15
|
+
const reasoning = ready.then((s) => s.reasoning);
|
|
16
|
+
// Iterating is enough: unread promises must not report unhandled rejections.
|
|
17
|
+
text.catch(() => { });
|
|
18
|
+
reasoning.catch(() => { });
|
|
19
|
+
return {
|
|
20
|
+
text,
|
|
21
|
+
reasoning,
|
|
22
|
+
stop() {
|
|
23
|
+
stopped = true;
|
|
24
|
+
inner?.stop();
|
|
25
|
+
},
|
|
26
|
+
async *[Symbol.asyncIterator]() {
|
|
27
|
+
yield* await ready;
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/** A conversation whose turns start once the model is loaded (looked up on first use). */
|
|
32
|
+
function deferChat(getLLM, options) {
|
|
33
|
+
let inner;
|
|
34
|
+
let ready;
|
|
35
|
+
let resetEarly = false;
|
|
36
|
+
const open = () => {
|
|
37
|
+
ready ??= getLLM().then((llm) => {
|
|
38
|
+
inner = llm.chat(options);
|
|
39
|
+
if (resetEarly)
|
|
40
|
+
inner.reset();
|
|
41
|
+
return inner;
|
|
42
|
+
});
|
|
43
|
+
return ready;
|
|
44
|
+
};
|
|
45
|
+
const send = (content, turn) => open().then((chat) => chat.send(content, turn));
|
|
46
|
+
return {
|
|
47
|
+
get system() {
|
|
48
|
+
return options.system;
|
|
49
|
+
},
|
|
50
|
+
get history() {
|
|
51
|
+
return inner?.history ?? (resetEarly ? [] : (options.messages ?? []));
|
|
52
|
+
},
|
|
53
|
+
send: send,
|
|
54
|
+
stream: (content, turn) => deferStream(open().then((chat) => chat.stream(content, turn))),
|
|
55
|
+
reset() {
|
|
56
|
+
if (inner === undefined)
|
|
57
|
+
resetEarly = true;
|
|
58
|
+
else
|
|
59
|
+
inner.reset();
|
|
60
|
+
},
|
|
61
|
+
dispose: async () => {
|
|
62
|
+
if (ready !== undefined)
|
|
63
|
+
await ready.then((chat) => chat.dispose(), () => { });
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Loads a model with the simple API (`load` from webslm) and gives
|
|
69
|
+
* `ask`, `stream` and `chat` functions that can be called right away: they
|
|
70
|
+
* wait for the load. The model defaults to `DEFAULT_MODEL`; pass `null` to
|
|
71
|
+
* load nothing. It is unloaded when the source or a load option changes and
|
|
72
|
+
* on unmount.
|
|
73
|
+
*
|
|
74
|
+
* ```tsx
|
|
75
|
+
* function Haiku() {
|
|
76
|
+
* const { ask, status, progress } = useLLM();
|
|
77
|
+
* const [text, setText] = useState("");
|
|
78
|
+
* return (
|
|
79
|
+
* <>
|
|
80
|
+
* <button onClick={async () => setText(await ask("Write a haiku about the sea"))}>Ask</button>
|
|
81
|
+
* {status === "loading" && <progress value={progress?.overallLoadedBytes} max={progress?.overallTotalBytes} />}
|
|
82
|
+
* <p>{text}</p>
|
|
83
|
+
* </>
|
|
84
|
+
* );
|
|
85
|
+
* }
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
88
|
+
export function useLLM(model = DEFAULT_MODEL, options = {}) {
|
|
89
|
+
const { loadId, value, status, progress, error, pending } = useLoad(model, options, load);
|
|
90
|
+
// The model being loaded (or loaded) when a call is made.
|
|
91
|
+
const current = useCallback(() => pending.current ?? Promise.reject(new WebslmError("INVALID_STATE", "no model is loaded or loading")), [pending]);
|
|
92
|
+
const ask = useCallback((prompt, askOptions) => current().then((llm) => llm.ask(prompt, askOptions)), [current]);
|
|
93
|
+
const stream = useCallback((prompt, streamOptions) => deferStream(current().then((llm) => llm.stream(prompt, streamOptions))), [current]);
|
|
94
|
+
// A new function per load, so memoized conversations follow the model.
|
|
95
|
+
const chat = useMemo(() => {
|
|
96
|
+
void loadId;
|
|
97
|
+
return (chatOptions = {}) => deferChat(current, chatOptions);
|
|
98
|
+
}, [current, loadId]);
|
|
99
|
+
return { llm: value, status, progress, error, ask, stream, chat };
|
|
100
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type MutableRefObject } from "react";
|
|
2
|
+
import { WebslmError, type LoadModelOptions, type LoadProgress, type ModelSource } from "webslm";
|
|
3
|
+
/** Lifecycle of a model load. */
|
|
4
|
+
export type ModelStatus = "idle" | "loading" | "ready" | "error";
|
|
5
|
+
/** Options of the loading hooks: those of `loadModel`, minus the signal (the hook owns it). */
|
|
6
|
+
export type UseModelOptions = Omit<LoadModelOptions, "signal">;
|
|
7
|
+
interface LoadState<T> {
|
|
8
|
+
/** Increases with every load the hook starts (0 before the first). */
|
|
9
|
+
readonly loadId: number;
|
|
10
|
+
readonly value: T | undefined;
|
|
11
|
+
readonly status: ModelStatus;
|
|
12
|
+
readonly progress: LoadProgress | undefined;
|
|
13
|
+
readonly error: WebslmError | undefined;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Shared engine of `useModel` and `useLLM`: loads with `loader` when the
|
|
17
|
+
* source or a load option changes, and unloads the previous value and on
|
|
18
|
+
* unmount. `pending` holds the current load, for calls made before it ends.
|
|
19
|
+
*/
|
|
20
|
+
export declare function useLoad<T extends {
|
|
21
|
+
unload(): Promise<void>;
|
|
22
|
+
}>(source: string | ModelSource | null | undefined, options: UseModelOptions, loader: (source: string | ModelSource, options: LoadModelOptions) => Promise<T>): LoadState<T> & {
|
|
23
|
+
readonly pending: MutableRefObject<Promise<T> | undefined>;
|
|
24
|
+
};
|
|
25
|
+
export {};
|
package/dist/use-load.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from "react";
|
|
2
|
+
import { WebslmError } from "webslm";
|
|
3
|
+
/** Gives every `files` or `fetch` source object a stable id. */
|
|
4
|
+
const objectIds = new WeakMap();
|
|
5
|
+
let nextObjectId = 1;
|
|
6
|
+
/** Identifies a source: a new key means a new load. Objects are keyed by identity. */
|
|
7
|
+
function sourceKey(source) {
|
|
8
|
+
if (source === null || source === undefined)
|
|
9
|
+
return "";
|
|
10
|
+
if (typeof source === "string")
|
|
11
|
+
return `hub:${source}`;
|
|
12
|
+
if ("hub" in source)
|
|
13
|
+
return `hub:${source.hub}@${source.revision ?? ""}@${source.hubUrl ?? ""}`;
|
|
14
|
+
let id = objectIds.get(source);
|
|
15
|
+
if (id === undefined) {
|
|
16
|
+
id = nextObjectId++;
|
|
17
|
+
objectIds.set(source, id);
|
|
18
|
+
}
|
|
19
|
+
return `object:${id}`;
|
|
20
|
+
}
|
|
21
|
+
function toError(error) {
|
|
22
|
+
return error instanceof WebslmError ? error : new WebslmError("ENGINE", String(error), { cause: error });
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Shared engine of `useModel` and `useLLM`: loads with `loader` when the
|
|
26
|
+
* source or a load option changes, and unloads the previous value and on
|
|
27
|
+
* unmount. `pending` holds the current load, for calls made before it ends.
|
|
28
|
+
*/
|
|
29
|
+
export function useLoad(source, options, loader) {
|
|
30
|
+
const optionsRef = useRef(options);
|
|
31
|
+
optionsRef.current = options;
|
|
32
|
+
const pending = useRef(undefined);
|
|
33
|
+
const loads = useRef(0);
|
|
34
|
+
const [state, setState] = useState({
|
|
35
|
+
loadId: 0,
|
|
36
|
+
value: undefined,
|
|
37
|
+
status: "idle",
|
|
38
|
+
progress: undefined,
|
|
39
|
+
error: undefined,
|
|
40
|
+
});
|
|
41
|
+
const key = [
|
|
42
|
+
sourceKey(source),
|
|
43
|
+
options.quant ?? "",
|
|
44
|
+
options.device ?? "",
|
|
45
|
+
options.revision ?? "",
|
|
46
|
+
options.contextLength ?? "",
|
|
47
|
+
options.worker ?? "",
|
|
48
|
+
options.token ?? "",
|
|
49
|
+
options.cacheDir ?? "",
|
|
50
|
+
].join("|");
|
|
51
|
+
useEffect(() => {
|
|
52
|
+
if (source === null || source === undefined) {
|
|
53
|
+
pending.current = undefined;
|
|
54
|
+
setState({ loadId: loads.current, value: undefined, status: "idle", progress: undefined, error: undefined });
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const controller = new AbortController();
|
|
58
|
+
let loaded;
|
|
59
|
+
let active = true;
|
|
60
|
+
const loadId = ++loads.current;
|
|
61
|
+
setState({ loadId, value: undefined, status: "loading", progress: undefined, error: undefined });
|
|
62
|
+
// The latest `onProgress` is read through the ref on every event.
|
|
63
|
+
const { onProgress: _initial, ...rest } = optionsRef.current;
|
|
64
|
+
void _initial;
|
|
65
|
+
const promise = loader(source, {
|
|
66
|
+
...rest,
|
|
67
|
+
signal: controller.signal,
|
|
68
|
+
onProgress: (progress) => {
|
|
69
|
+
if (active)
|
|
70
|
+
setState((s) => ({ ...s, progress }));
|
|
71
|
+
optionsRef.current.onProgress?.(progress);
|
|
72
|
+
},
|
|
73
|
+
}).then((value) => {
|
|
74
|
+
if (!active) {
|
|
75
|
+
void value.unload();
|
|
76
|
+
throw new WebslmError("DISPOSED", "the model was unloaded");
|
|
77
|
+
}
|
|
78
|
+
loaded = value;
|
|
79
|
+
setState((s) => ({ loadId, value, status: "ready", progress: s.progress, error: undefined }));
|
|
80
|
+
return value;
|
|
81
|
+
}, (error) => {
|
|
82
|
+
const typed = toError(error);
|
|
83
|
+
if (active) {
|
|
84
|
+
setState((s) => ({ loadId, value: undefined, status: "error", progress: s.progress, error: typed }));
|
|
85
|
+
}
|
|
86
|
+
throw typed;
|
|
87
|
+
});
|
|
88
|
+
// Callers waiting on `pending` see the error; nobody else has to.
|
|
89
|
+
promise.catch(() => { });
|
|
90
|
+
pending.current = promise;
|
|
91
|
+
return () => {
|
|
92
|
+
active = false;
|
|
93
|
+
controller.abort();
|
|
94
|
+
if (pending.current === promise)
|
|
95
|
+
pending.current = undefined;
|
|
96
|
+
if (loaded !== undefined)
|
|
97
|
+
void loaded.unload();
|
|
98
|
+
};
|
|
99
|
+
// `key` captures everything that requires a reload.
|
|
100
|
+
}, [key]);
|
|
101
|
+
return { ...state, pending };
|
|
102
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { WebslmError, type HubModel, type SearchModelsOptions } from "webslm";
|
|
2
|
+
export interface UseModelSearchOptions extends Omit<SearchModelsOptions, "signal"> {
|
|
3
|
+
/** Milliseconds to wait after the last keystroke (default 300). */
|
|
4
|
+
readonly debounceMs?: number;
|
|
5
|
+
/** Shortest query that triggers a search (default 2 characters). */
|
|
6
|
+
readonly minLength?: number;
|
|
7
|
+
}
|
|
8
|
+
export interface UseModelSearchResult {
|
|
9
|
+
readonly results: readonly HubModel[];
|
|
10
|
+
readonly status: "idle" | "searching" | "done" | "error";
|
|
11
|
+
readonly error: WebslmError | undefined;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Searches the Hugging Face Hub as the query changes (debounced), marking
|
|
15
|
+
* which repositories webslm can run. Stale requests are cancelled.
|
|
16
|
+
*
|
|
17
|
+
* ```tsx
|
|
18
|
+
* const { results, status } = useModelSearch(query, { maxParams: 2e9 });
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export declare function useModelSearch(query: string, options?: UseModelSearchOptions): UseModelSearchResult;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from "react";
|
|
2
|
+
import { searchModels, WebslmError } from "webslm";
|
|
3
|
+
/**
|
|
4
|
+
* Searches the Hugging Face Hub as the query changes (debounced), marking
|
|
5
|
+
* which repositories webslm can run. Stale requests are cancelled.
|
|
6
|
+
*
|
|
7
|
+
* ```tsx
|
|
8
|
+
* const { results, status } = useModelSearch(query, { maxParams: 2e9 });
|
|
9
|
+
* ```
|
|
10
|
+
*/
|
|
11
|
+
export function useModelSearch(query, options = {}) {
|
|
12
|
+
const [state, setState] = useState({
|
|
13
|
+
results: [],
|
|
14
|
+
status: "idle",
|
|
15
|
+
error: undefined,
|
|
16
|
+
});
|
|
17
|
+
const optionsRef = useRef(options);
|
|
18
|
+
optionsRef.current = options;
|
|
19
|
+
const trimmed = query.trim();
|
|
20
|
+
const key = [trimmed, options.maxParams ?? "", options.limit ?? "", options.supportedOnly ?? "", options.hubUrl ?? ""].join("|");
|
|
21
|
+
useEffect(() => {
|
|
22
|
+
const { debounceMs = 300, minLength = 2, ...search } = optionsRef.current;
|
|
23
|
+
if (trimmed.length < minLength) {
|
|
24
|
+
setState({ results: [], status: "idle", error: undefined });
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
const controller = new AbortController();
|
|
28
|
+
setState((s) => ({ ...s, status: "searching", error: undefined }));
|
|
29
|
+
const timer = setTimeout(() => {
|
|
30
|
+
searchModels(trimmed, { ...search, signal: controller.signal }).then((results) => {
|
|
31
|
+
if (!controller.signal.aborted)
|
|
32
|
+
setState({ results, status: "done", error: undefined });
|
|
33
|
+
}, (error) => {
|
|
34
|
+
if (controller.signal.aborted)
|
|
35
|
+
return;
|
|
36
|
+
const typed = error instanceof WebslmError ? error : new WebslmError("NETWORK", String(error));
|
|
37
|
+
setState({ results: [], status: "error", error: typed });
|
|
38
|
+
});
|
|
39
|
+
}, debounceMs);
|
|
40
|
+
return () => {
|
|
41
|
+
clearTimeout(timer);
|
|
42
|
+
controller.abort();
|
|
43
|
+
};
|
|
44
|
+
}, [key, trimmed]);
|
|
45
|
+
return state;
|
|
46
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type LoadProgress, type Model, type ModelSource, type WebslmError } from "webslm";
|
|
2
|
+
import { type ModelStatus, type UseModelOptions } from "./use-load.js";
|
|
3
|
+
export type { ModelStatus, UseModelOptions } from "./use-load.js";
|
|
4
|
+
export interface UseModelResult {
|
|
5
|
+
/** The loaded model, once `status` is `"ready"`. */
|
|
6
|
+
readonly model: Model | undefined;
|
|
7
|
+
readonly status: ModelStatus;
|
|
8
|
+
/** Latest progress event of the current load. */
|
|
9
|
+
readonly progress: LoadProgress | undefined;
|
|
10
|
+
readonly error: WebslmError | undefined;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Loads a model and unloads it when the source changes or the component
|
|
14
|
+
* unmounts. Pass `null` to load nothing. Changing `quant`, `device`,
|
|
15
|
+
* `revision`, `contextLength` or `worker` reloads; `onProgress` may change
|
|
16
|
+
* freely. For simple `ask`/`stream`/`chat` calls, see `useLLM`.
|
|
17
|
+
*
|
|
18
|
+
* ```tsx
|
|
19
|
+
* const { model, status, progress, error } = useModel("HuggingFaceTB/SmolLM2-135M-Instruct");
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export declare function useModel(source: string | ModelSource | null | undefined, options?: UseModelOptions): UseModelResult;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { loadModel } from "webslm";
|
|
2
|
+
import { useLoad } from "./use-load.js";
|
|
3
|
+
/**
|
|
4
|
+
* Loads a model and unloads it when the source changes or the component
|
|
5
|
+
* unmounts. Pass `null` to load nothing. Changing `quant`, `device`,
|
|
6
|
+
* `revision`, `contextLength` or `worker` reloads; `onProgress` may change
|
|
7
|
+
* freely. For simple `ask`/`stream`/`chat` calls, see `useLLM`.
|
|
8
|
+
*
|
|
9
|
+
* ```tsx
|
|
10
|
+
* const { model, status, progress, error } = useModel("HuggingFaceTB/SmolLM2-135M-Instruct");
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
export function useModel(source, options = {}) {
|
|
14
|
+
const { value, status, progress, error } = useLoad(source, options, loadModel);
|
|
15
|
+
return { model: value, status, progress, error };
|
|
16
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "webslm-react",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "React hooks for webslm: load small language models in the browser, chat with them and search the Hugging Face Hub.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Maxime Golfier",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/maxgfr/webslm.git",
|
|
10
|
+
"directory": "packages/webslm-react"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://maxgfr.github.io/webslm/",
|
|
13
|
+
"bugs": "https://github.com/maxgfr/webslm/issues",
|
|
14
|
+
"keywords": [
|
|
15
|
+
"react",
|
|
16
|
+
"hooks",
|
|
17
|
+
"llm",
|
|
18
|
+
"slm",
|
|
19
|
+
"wasm",
|
|
20
|
+
"huggingface",
|
|
21
|
+
"language-model",
|
|
22
|
+
"chat",
|
|
23
|
+
"webassembly"
|
|
24
|
+
],
|
|
25
|
+
"type": "module",
|
|
26
|
+
"sideEffects": false,
|
|
27
|
+
"main": "./dist/index.js",
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"default": "./dist/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./package.json": "./package.json"
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"dist"
|
|
38
|
+
],
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"react": ">=18",
|
|
41
|
+
"webslm": "^0.1.0"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@testing-library/dom": "^10.4.2",
|
|
45
|
+
"@testing-library/react": "^16.3.3",
|
|
46
|
+
"@types/react": "^19.3.3",
|
|
47
|
+
"@types/react-dom": "^19.3.0",
|
|
48
|
+
"@webgpu/types": "^0.1.74",
|
|
49
|
+
"jsdom": "^31.0.1",
|
|
50
|
+
"react": "^19.3.1",
|
|
51
|
+
"react-dom": "^19.3.1",
|
|
52
|
+
"typescript": "^7.0.2",
|
|
53
|
+
"vitest": "^5.1.2",
|
|
54
|
+
"webslm": "^0.1.0"
|
|
55
|
+
},
|
|
56
|
+
"scripts": {
|
|
57
|
+
"build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
|
|
58
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
59
|
+
"test": "vitest run"
|
|
60
|
+
}
|
|
6
61
|
}
|