@dudko.dev/agent-web-react 0.0.12 β†’ 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,7 +21,9 @@ app with a single hook and (optionally) a set of pre-styled components:
21
21
  `useVirtualFiles`, `useSpeechToText`, `useMcpServers`.
22
22
  - πŸ”‘ **`useCredentials`** β€” store BYOK API keys **encrypted at rest**
23
23
  (WebCrypto + IndexedDB).
24
- - πŸ–₯️ **`useWebLLMModel`** β€” load a local WebGPU model with download progress.
24
+ - πŸ–₯️ **`useWebLLMModel`** / **`useLocalModel`** β€” load an on-device model (WebLLM,
25
+ the browser's built-in model, transformers.js, or your own runtime) with
26
+ download progress, switching and unloading.
25
27
  - πŸŽ›οΈ **Headless-first** β€” the eventβ†’UI logic is a pure, exported reducer
26
28
  (`agentStateReducer`); the components are optional sugar on top.
27
29
 
@@ -229,6 +231,48 @@ function LocalAgent() {
229
231
  > yet. The previous model stays in memory (`loadedModelId`; switching back is
230
232
  > instant) until the new one is loaded β€” that frees it first, so two models
231
233
  > never share the GPU β€” or until `unload()`.
234
+ >
235
+ > **Context window.** WebLLM loads its models with a 4096-token window, far
236
+ > below what Qwen3 or Llama 3.x were trained on. Pass `contextWindowTokens` to
237
+ > load with more (it costs KV-cache VRAM, not a new download); your `create`
238
+ > factory receives it and applies it with the core's `withWebLLMContextWindow`
239
+ > (see the demo's `providers.ts`). `local.contextWindow` is the window the model
240
+ > was loaded with, and the agent fits its runs into it on its own β€” compaction,
241
+ > tool lists and tool results are sized from it.
242
+ >
243
+ > **Vision.** `Phi-3.5-vision-instruct-q4f16_1-MLC` takes images (paste, drop
244
+ > or attach them) β€” a multimodal model that never sends them anywhere.
245
+
246
+ ### Any on-device runtime β€” `useLocalModel`
247
+
248
+ `useWebLLMModel` is `useLocalModel` with the WebLLM engine. Describe another
249
+ runtime as an engine β€” `create`, and optionally `warmUp` (download now, with
250
+ progress), `unload`, `supported`, `contextWindowOf` β€” and the hook gives the
251
+ same `load` / `unload` / progress / switching:
252
+
253
+ ```tsx
254
+ import { useLocalModel, createWebLLMEngine, type LocalModelEngine } from '@dudko.dev/agent-web-react'
255
+
256
+ const builtIn: LocalModelEngine = {
257
+ create: async () => (await import('@browser-ai/core')).browserAI('text', {
258
+ expectedInputs: [{ type: 'text' }, { type: 'image' }],
259
+ }),
260
+ warmUp: async (m, { onProgress }) => {
261
+ await m.createSessionWithProgress((p) => onProgress({ progress: p, text: 'Downloading' }))
262
+ },
263
+ supported: () => 'LanguageModel' in globalThis, // Chrome's Prompt API
264
+ contextWindowOf: (m) => m.getContextWindow(),
265
+ }
266
+ const webllm = createWebLLMEngine({ create: createLocalModel })
267
+
268
+ // One hook, any runtime: switching frees the previous model with its own engine.
269
+ const local = useLocalModel(option.model, option.builtIn ? builtIn : webllm, {
270
+ contextWindowTokens: option.contextWindow,
271
+ })
272
+ ```
273
+
274
+ The demo runs WebLLM, Chrome's Gemini Nano and transformers.js this way β€” see
275
+ [`demo/src/local-engines.ts`](demo/src/local-engines.ts).
232
276
 
233
277
  ## Models in a bundler (Vite, Next, CRA)
234
278
 
package/dist/index.cjs CHANGED
@@ -66,6 +66,7 @@ __export(src_exports, {
66
66
  createFileTools: () => import_agent_web4.createFileTools,
67
67
  createInitialAgentState: () => createInitialAgentState,
68
68
  createSubagentTool: () => import_agent_web4.createSubagentTool,
69
+ createWebLLMEngine: () => createWebLLMEngine,
69
70
  createWebLLMModel: () => import_agent_web4.createWebLLMModel,
70
71
  defaultLabels: () => defaultLabels,
71
72
  defineSkill: () => import_agent_web4.defineSkill,
@@ -96,6 +97,7 @@ __export(src_exports, {
96
97
  useChatHistory: () => useChatHistory,
97
98
  useCredentials: () => useCredentials,
98
99
  useLabels: () => useLabels,
100
+ useLocalModel: () => useLocalModel,
99
101
  useMcp: () => useMcp,
100
102
  useMcpServers: () => useMcpServers,
101
103
  useOptionalAgentContext: () => useOptionalAgentContext,
@@ -1718,65 +1720,75 @@ var useMcpServers = (options = {}) => {
1718
1720
  };
1719
1721
 
1720
1722
  // src/hooks/use-webllm-model.ts
1721
- var import_react8 = require("react");
1722
1723
  var import_agent_web3 = require("@dudko.dev/agent-web");
1723
- var useWebLLMModel = (modelId, options) => {
1724
+
1725
+ // src/hooks/use-local-model.ts
1726
+ var import_react8 = require("react");
1727
+ var keyOf = (id, tokens) => tokens ? `${id}@${tokens}` : id;
1728
+ var useLocalModel = (modelId, engine, options) => {
1724
1729
  const [loaded, setLoaded] = (0, import_react8.useState)(void 0);
1725
1730
  const [pending, setPending] = (0, import_react8.useState)();
1726
1731
  const [failure, setFailure] = (0, import_react8.useState)();
1727
- const optionsRef = (0, import_react8.useRef)(options);
1728
- optionsRef.current = options;
1732
+ const engineRef = (0, import_react8.useRef)(engine);
1733
+ engineRef.current = engine;
1729
1734
  const loadedRef = (0, import_react8.useRef)(void 0);
1730
1735
  const inflightRef = (0, import_react8.useRef)(
1731
1736
  void 0
1732
1737
  );
1738
+ const windowTokens = options?.contextWindowTokens;
1739
+ const key = keyOf(modelId, windowTokens);
1733
1740
  const seqRef = (0, import_react8.useRef)(0);
1734
1741
  const setHeld = (next) => {
1735
1742
  loadedRef.current = next;
1736
1743
  setLoaded(next);
1737
1744
  };
1745
+ const freeWith = (eng, model2) => async () => {
1746
+ try {
1747
+ await eng.unload?.(model2);
1748
+ } catch {
1749
+ }
1750
+ };
1738
1751
  const load = (0, import_react8.useCallback)(() => {
1739
1752
  const id = modelId;
1740
- if (loadedRef.current?.id === id) return Promise.resolve(loadedRef.current.model);
1741
- if (inflightRef.current?.id === id) return inflightRef.current.promise;
1742
- if (!(0, import_agent_web3.isWebGPUAvailable)()) {
1743
- setFailure({ id, message: "WebGPU is not available in this browser." });
1753
+ if (loadedRef.current?.key === key) return Promise.resolve(loadedRef.current.model);
1754
+ if (inflightRef.current?.key === key) return inflightRef.current.promise;
1755
+ const eng = engineRef.current;
1756
+ if (eng.supported && !eng.supported()) {
1757
+ setFailure({
1758
+ key,
1759
+ message: eng.unsupportedMessage ?? "This browser cannot run this model."
1760
+ });
1744
1761
  return Promise.resolve(void 0);
1745
1762
  }
1746
1763
  const seq = ++seqRef.current;
1747
1764
  const current = () => seq === seqRef.current;
1765
+ const ctx = {
1766
+ onProgress: (report) => {
1767
+ if (current()) setPending({ key, progress: report.progress, text: report.text });
1768
+ },
1769
+ ...windowTokens ? { contextWindowTokens: windowTokens } : {}
1770
+ };
1748
1771
  const promise = (async () => {
1749
- setPending({ id, progress: 0, text: "" });
1772
+ setPending({ key, progress: 0, text: "" });
1750
1773
  setFailure(void 0);
1751
1774
  let built;
1752
1775
  try {
1753
1776
  const previous = loadedRef.current;
1754
1777
  if (previous) {
1755
1778
  setHeld(void 0);
1756
- await (0, import_agent_web3.unloadWebLLMModel)(previous.model);
1779
+ await previous.free();
1757
1780
  }
1758
- const { create = import_agent_web3.createWebLLMModel, ...modelOptions } = optionsRef.current ?? {};
1759
- built = await create(id, {
1760
- ...modelOptions,
1761
- // Drive preload here (below) so download progress is reported the same
1762
- // way whether `create` is the core's `createWebLLMModel` or an injected
1763
- // factory (e.g. a statically-imported `webLLM`, needed under bundlers).
1764
- preload: false,
1765
- initProgressCallback: (report) => {
1766
- if (current()) setPending({ id, progress: report.progress, text: report.text });
1767
- modelOptions.initProgressCallback?.(report);
1768
- }
1769
- });
1770
- await (0, import_agent_web3.preloadWebLLMModel)(built);
1781
+ built = await eng.create(id, ctx);
1782
+ await eng.warmUp?.(built, ctx);
1771
1783
  if (!current()) {
1772
- await (0, import_agent_web3.unloadWebLLMModel)(built);
1784
+ await freeWith(eng, built)();
1773
1785
  return void 0;
1774
1786
  }
1775
- setHeld({ id, model: built });
1787
+ setHeld({ id, key, model: built, free: freeWith(eng, built) });
1776
1788
  return built;
1777
1789
  } catch (err) {
1778
- if (built) await (0, import_agent_web3.unloadWebLLMModel)(built);
1779
- if (current()) setFailure({ id, message: errMessage(err) });
1790
+ if (built) await freeWith(eng, built)();
1791
+ if (current()) setFailure({ key, message: errMessage(err) });
1780
1792
  return void 0;
1781
1793
  } finally {
1782
1794
  if (current()) {
@@ -1785,19 +1797,19 @@ var useWebLLMModel = (modelId, options) => {
1785
1797
  }
1786
1798
  }
1787
1799
  })();
1788
- inflightRef.current = { id, promise };
1800
+ inflightRef.current = { key, promise };
1789
1801
  return promise;
1790
- }, [modelId]);
1802
+ }, [modelId, key]);
1791
1803
  const unload = (0, import_react8.useCallback)(async () => {
1792
1804
  seqRef.current++;
1793
1805
  inflightRef.current = void 0;
1794
1806
  setPending(void 0);
1795
1807
  const previous = loadedRef.current;
1796
1808
  setHeld(void 0);
1797
- if (previous) await (0, import_agent_web3.unloadWebLLMModel)(previous.model);
1809
+ if (previous) await previous.free();
1798
1810
  }, []);
1799
- const model = loaded?.id === modelId ? loaded.model : void 0;
1800
- const progressing = pending?.id === modelId ? pending : void 0;
1811
+ const model = loaded?.key === key ? loaded.model : void 0;
1812
+ const progressing = pending?.key === key ? pending : void 0;
1801
1813
  return {
1802
1814
  model,
1803
1815
  load,
@@ -1806,9 +1818,46 @@ var useWebLLMModel = (modelId, options) => {
1806
1818
  loading: progressing !== void 0,
1807
1819
  progress: progressing?.progress ?? 0,
1808
1820
  text: progressing?.text ?? "",
1809
- error: failure?.id === modelId ? failure.message : void 0,
1810
- supported: (0, import_agent_web3.isWebGPUAvailable)(),
1811
- ready: model !== void 0
1821
+ error: failure?.key === key ? failure.message : void 0,
1822
+ supported: engine.supported ? engine.supported() : true,
1823
+ ready: model !== void 0,
1824
+ contextWindow: model ? engine.contextWindowOf?.(model) : void 0
1825
+ };
1826
+ };
1827
+
1828
+ // src/hooks/use-webllm-model.ts
1829
+ var useWebLLMModel = (modelId, options) => useLocalModel(modelId, createWebLLMEngine(options), {
1830
+ contextWindowTokens: options?.contextWindowTokens
1831
+ });
1832
+ var createWebLLMEngine = (options) => {
1833
+ const {
1834
+ create = import_agent_web3.createWebLLMModel,
1835
+ contextWindowTokens: _perLoad,
1836
+ ...modelOptions
1837
+ } = options ?? {};
1838
+ return {
1839
+ create: (id, ctx) => create(id, {
1840
+ ...modelOptions,
1841
+ ...ctx.contextWindowTokens ? { contextWindowTokens: ctx.contextWindowTokens } : {},
1842
+ // Drive preload in warmUp (below) so download progress is reported the
1843
+ // same way whether `create` is the core's `createWebLLMModel` or an
1844
+ // injected factory (e.g. a statically-imported `webLLM`, needed under
1845
+ // bundlers).
1846
+ preload: false,
1847
+ initProgressCallback: (report) => {
1848
+ ctx.onProgress({ progress: report.progress, text: report.text });
1849
+ modelOptions.initProgressCallback?.(report);
1850
+ }
1851
+ }),
1852
+ // Download the weights + init the engine now via the core's helper (a
1853
+ // 1-token warm-up). WebLLM builds are otherwise lazy β€” the ~GB download
1854
+ // would only start on the first `run()`, long after we told the UI the
1855
+ // model is "ready". Fast + idempotent once the weights are cached.
1856
+ warmUp: (model) => (0, import_agent_web3.preloadWebLLMModel)(model),
1857
+ unload: import_agent_web3.unloadWebLLMModel,
1858
+ supported: import_agent_web3.isWebGPUAvailable,
1859
+ unsupportedMessage: "WebGPU is not available in this browser.",
1860
+ contextWindowOf: import_agent_web3.webLLMContextWindow
1812
1861
  };
1813
1862
  };
1814
1863
 
@@ -4070,6 +4119,7 @@ var import_agent_web4 = require("@dudko.dev/agent-web");
4070
4119
  createFileTools,
4071
4120
  createInitialAgentState,
4072
4121
  createSubagentTool,
4122
+ createWebLLMEngine,
4073
4123
  createWebLLMModel,
4074
4124
  defaultLabels,
4075
4125
  defineSkill,
@@ -4100,6 +4150,7 @@ var import_agent_web4 = require("@dudko.dev/agent-web");
4100
4150
  useChatHistory,
4101
4151
  useCredentials,
4102
4152
  useLabels,
4153
+ useLocalModel,
4103
4154
  useMcp,
4104
4155
  useMcpServers,
4105
4156
  useOptionalAgentContext,