ai 2.1.0 → 2.1.2

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 (68) hide show
  1. package/dist/index.d.ts +48 -8
  2. package/dist/index.mjs +234 -26
  3. package/package.json +4 -4
  4. package/react/dist/index.d.ts +206 -3
  5. package/react/dist/index.mjs +384 -7
  6. package/svelte/dist/index.d.ts +194 -4
  7. package/svelte/dist/index.mjs +779 -7
  8. package/vue/dist/index.d.ts +194 -4
  9. package/vue/dist/index.mjs +345 -7
  10. package/dist/ai-stream.d.ts +0 -18
  11. package/dist/ai-stream.js +0 -132
  12. package/dist/ai-stream.mjs +0 -15
  13. package/dist/anthropic-stream.d.ts +0 -5
  14. package/dist/anthropic-stream.js +0 -133
  15. package/dist/anthropic-stream.mjs +0 -10
  16. package/dist/chunk-2JQWCLY2.mjs +0 -70
  17. package/dist/chunk-7KLTYB74.mjs +0 -70
  18. package/dist/chunk-BJMBMGA3.mjs +0 -34
  19. package/dist/chunk-KKQRUR3E.mjs +0 -51
  20. package/dist/chunk-RBP6ONSV.mjs +0 -45
  21. package/dist/chunk-TWW2ODJW.mjs +0 -32
  22. package/dist/chunk-U2OQ6HW6.mjs +0 -41
  23. package/dist/chunk-UJV6VDVU.mjs +0 -97
  24. package/dist/huggingface-stream.d.ts +0 -5
  25. package/dist/huggingface-stream.js +0 -121
  26. package/dist/huggingface-stream.mjs +0 -10
  27. package/dist/index.test.d.ts +0 -2
  28. package/dist/index.test.js +0 -568
  29. package/dist/index.test.mjs +0 -286
  30. package/dist/langchain-stream.d.ts +0 -12
  31. package/dist/langchain-stream.js +0 -102
  32. package/dist/langchain-stream.mjs +0 -10
  33. package/dist/openai-stream.d.ts +0 -5
  34. package/dist/openai-stream.js +0 -144
  35. package/dist/openai-stream.mjs +0 -10
  36. package/dist/streaming-text-response.d.ts +0 -17
  37. package/dist/streaming-text-response.js +0 -75
  38. package/dist/streaming-text-response.mjs +0 -11
  39. package/react/dist/chunk-5PP6W52J.mjs +0 -202
  40. package/react/dist/chunk-6EH3SWMP.mjs +0 -55
  41. package/react/dist/chunk-PW6HSU2N.mjs +0 -154
  42. package/react/dist/types-f862f74a.d.ts +0 -123
  43. package/react/dist/use-chat.d.ts +0 -42
  44. package/react/dist/use-chat.js +0 -276
  45. package/react/dist/use-chat.mjs +0 -8
  46. package/react/dist/use-completion.d.ts +0 -47
  47. package/react/dist/use-completion.js +0 -229
  48. package/react/dist/use-completion.mjs +0 -8
  49. package/svelte/dist/chunk-6USBQIV6.mjs +0 -177
  50. package/svelte/dist/chunk-BQ64GHZ3.mjs +0 -136
  51. package/svelte/dist/chunk-CENOSGDG.mjs +0 -493
  52. package/svelte/dist/types-f862f74a.d.ts +0 -123
  53. package/svelte/dist/use-chat.d.ts +0 -39
  54. package/svelte/dist/use-chat.js +0 -680
  55. package/svelte/dist/use-chat.mjs +0 -7
  56. package/svelte/dist/use-completion.d.ts +0 -38
  57. package/svelte/dist/use-completion.js +0 -640
  58. package/svelte/dist/use-completion.mjs +0 -7
  59. package/vue/dist/chunk-FT26CHLO.mjs +0 -137
  60. package/vue/dist/chunk-OYI6GFBM.mjs +0 -178
  61. package/vue/dist/chunk-WXH4YPZV.mjs +0 -54
  62. package/vue/dist/types-f862f74a.d.ts +0 -123
  63. package/vue/dist/use-chat.d.ts +0 -39
  64. package/vue/dist/use-chat.js +0 -252
  65. package/vue/dist/use-chat.mjs +0 -7
  66. package/vue/dist/use-completion.d.ts +0 -38
  67. package/vue/dist/use-completion.js +0 -212
  68. package/vue/dist/use-completion.mjs +0 -7
@@ -1,10 +1,782 @@
1
- import {
2
- useChat
3
- } from "./chunk-6USBQIV6.mjs";
4
- import {
5
- useCompletion
6
- } from "./chunk-BQ64GHZ3.mjs";
7
- import "./chunk-CENOSGDG.mjs";
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
17
+ var __async = (__this, __arguments, generator) => {
18
+ return new Promise((resolve, reject) => {
19
+ var fulfilled = (value) => {
20
+ try {
21
+ step(generator.next(value));
22
+ } catch (e) {
23
+ reject(e);
24
+ }
25
+ };
26
+ var rejected = (value) => {
27
+ try {
28
+ step(generator.throw(value));
29
+ } catch (e) {
30
+ reject(e);
31
+ }
32
+ };
33
+ var step = (x2) => x2.done ? resolve(x2.value) : Promise.resolve(x2.value).then(fulfilled, rejected);
34
+ step((generator = generator.apply(__this, __arguments)).next());
35
+ });
36
+ };
37
+
38
+ // ../../node_modules/.pnpm/swrev@3.0.0/node_modules/swrev/dist/swrev.es.js
39
+ var __defProp2 = Object.defineProperty;
40
+ var __defProps = Object.defineProperties;
41
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
42
+ var __getOwnPropSymbols2 = Object.getOwnPropertySymbols;
43
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
44
+ var __propIsEnum2 = Object.prototype.propertyIsEnumerable;
45
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
46
+ var __spreadValues2 = (a, b) => {
47
+ for (var prop in b || (b = {}))
48
+ if (__hasOwnProp2.call(b, prop))
49
+ __defNormalProp2(a, prop, b[prop]);
50
+ if (__getOwnPropSymbols2)
51
+ for (var prop of __getOwnPropSymbols2(b)) {
52
+ if (__propIsEnum2.call(b, prop))
53
+ __defNormalProp2(a, prop, b[prop]);
54
+ }
55
+ return a;
56
+ };
57
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
58
+ var __publicField = (obj, key, value) => {
59
+ __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
60
+ return value;
61
+ };
62
+ var DefaultSWREventManager = class {
63
+ constructor() {
64
+ __publicField(this, "listeners", /* @__PURE__ */ new Map());
65
+ }
66
+ subscribe(key, listener) {
67
+ if (!this.listeners.has(key))
68
+ this.listeners.set(key, []);
69
+ if (this.listeners.get(key).includes(listener))
70
+ return;
71
+ this.listeners.get(key).push(listener);
72
+ }
73
+ unsubscribe(key, listener) {
74
+ if (!this.listeners.has(key))
75
+ return;
76
+ if (!this.listeners.get(key).includes(listener))
77
+ return;
78
+ this.listeners.get(key).splice(this.listeners.get(key).indexOf(listener), 1);
79
+ if (this.listeners.get(key).length === 0)
80
+ this.listeners.delete(key);
81
+ }
82
+ emit(key, payload) {
83
+ if (!this.listeners.has(key))
84
+ return;
85
+ this.listeners.get(key).forEach((listener) => listener(payload));
86
+ }
87
+ };
88
+ var defaultCacheRemoveOptions = {
89
+ broadcast: false
90
+ };
91
+ var defaultCacheClearOptions = {
92
+ broadcast: false
93
+ };
94
+ var CacheItem = class {
95
+ constructor({ data, expiresAt = null }) {
96
+ __publicField(this, "data");
97
+ __publicField(this, "expiresAt");
98
+ this.data = data;
99
+ this.expiresAt = expiresAt;
100
+ }
101
+ isResolving() {
102
+ return this.data instanceof Promise;
103
+ }
104
+ hasExpired() {
105
+ return this.expiresAt === null || this.expiresAt < /* @__PURE__ */ new Date();
106
+ }
107
+ expiresIn(milliseconds) {
108
+ this.expiresAt = /* @__PURE__ */ new Date();
109
+ this.expiresAt.setMilliseconds(this.expiresAt.getMilliseconds() + milliseconds);
110
+ return this;
111
+ }
112
+ };
113
+ var DefaultCache = class {
114
+ constructor() {
115
+ __publicField(this, "elements", /* @__PURE__ */ new Map());
116
+ __publicField(this, "event", new DefaultSWREventManager());
117
+ }
118
+ resolve(key, value) {
119
+ Promise.resolve(value.data).then((detail) => {
120
+ if (detail === void 0 || detail === null) {
121
+ return this.remove(key);
122
+ }
123
+ value.data = detail;
124
+ this.broadcast(key, detail);
125
+ });
126
+ }
127
+ get(key) {
128
+ return this.elements.get(key);
129
+ }
130
+ set(key, value) {
131
+ this.elements.set(key, value);
132
+ this.resolve(key, value);
133
+ }
134
+ remove(key, options) {
135
+ const { broadcast } = __spreadValues2(__spreadValues2({}, defaultCacheRemoveOptions), options);
136
+ if (broadcast)
137
+ this.broadcast(key, void 0);
138
+ this.elements.delete(key);
139
+ }
140
+ clear(options) {
141
+ const { broadcast } = __spreadValues2(__spreadValues2({}, defaultCacheClearOptions), options);
142
+ if (broadcast)
143
+ for (const key of this.elements.keys())
144
+ this.broadcast(key, void 0);
145
+ this.elements.clear();
146
+ }
147
+ has(key) {
148
+ return this.elements.has(key);
149
+ }
150
+ subscribe(key, listener) {
151
+ this.event.subscribe(key, listener);
152
+ }
153
+ unsubscribe(key, listener) {
154
+ this.event.unsubscribe(key, listener);
155
+ }
156
+ broadcast(key, data) {
157
+ this.event.emit(key, data);
158
+ }
159
+ };
160
+ var defaultOptions = {
161
+ cache: new DefaultCache(),
162
+ errors: new DefaultSWREventManager(),
163
+ fetcher: (url) => __async(void 0, null, function* () {
164
+ const response = yield fetch(url);
165
+ if (!response.ok)
166
+ throw Error("Not a 2XX response.");
167
+ return response.json();
168
+ }),
169
+ initialData: void 0,
170
+ loadInitialCache: true,
171
+ revalidateOnStart: true,
172
+ dedupingInterval: 2e3,
173
+ revalidateOnFocus: true,
174
+ focusThrottleInterval: 5e3,
175
+ revalidateOnReconnect: true,
176
+ reconnectWhen: (notify, { enabled }) => {
177
+ if (enabled && typeof window !== "undefined") {
178
+ window.addEventListener("online", notify);
179
+ return () => window.removeEventListener("online", notify);
180
+ }
181
+ return () => {
182
+ };
183
+ },
184
+ focusWhen: (notify, { enabled, throttleInterval }) => {
185
+ if (enabled && typeof window !== "undefined") {
186
+ let lastFocus = null;
187
+ const rawHandler = () => {
188
+ const now = Date.now();
189
+ if (lastFocus === null || now - lastFocus > throttleInterval) {
190
+ lastFocus = now;
191
+ notify();
192
+ }
193
+ };
194
+ window.addEventListener("focus", rawHandler);
195
+ return () => window.removeEventListener("focus", rawHandler);
196
+ }
197
+ return () => {
198
+ };
199
+ }
200
+ };
201
+ var defaultRevalidateOptions = __spreadProps(__spreadValues2({}, defaultOptions), {
202
+ force: false
203
+ });
204
+ var defaultMutateOptions = {
205
+ revalidate: true,
206
+ revalidateOptions: __spreadValues2({}, defaultRevalidateOptions)
207
+ };
208
+ var defaultClearOptions = {
209
+ broadcast: false
210
+ };
211
+ var SWR = class {
212
+ constructor(options) {
213
+ __publicField(this, "options");
214
+ this.options = __spreadValues2(__spreadValues2({}, defaultOptions), options);
215
+ }
216
+ get cache() {
217
+ return this.options.cache;
218
+ }
219
+ get errors() {
220
+ return this.options.errors;
221
+ }
222
+ requestData(key, fetcher) {
223
+ return Promise.resolve(fetcher(key)).catch((data) => {
224
+ this.errors.emit(key, data);
225
+ return void 0;
226
+ });
227
+ }
228
+ resolveKey(key) {
229
+ if (typeof key === "function") {
230
+ try {
231
+ return key();
232
+ } catch (e) {
233
+ return void 0;
234
+ }
235
+ }
236
+ return key;
237
+ }
238
+ clear(keys, options) {
239
+ const ops = __spreadValues2(__spreadValues2({}, defaultClearOptions), options);
240
+ if (keys === void 0 || keys === null)
241
+ return this.cache.clear(ops);
242
+ if (!Array.isArray(keys))
243
+ return this.cache.remove(keys, ops);
244
+ for (const key of keys)
245
+ this.cache.remove(key, ops);
246
+ }
247
+ revalidate(key, options) {
248
+ if (!key)
249
+ return;
250
+ const { fetcher: defaultFetcher, dedupingInterval: defaultDedupingInterval } = this.options;
251
+ const { force, fetcher, dedupingInterval } = __spreadValues2(__spreadValues2(__spreadValues2({}, defaultRevalidateOptions), { fetcher: defaultFetcher, dedupingInterval: defaultDedupingInterval }), options);
252
+ let data = void 0;
253
+ if (force || !this.cache.has(key) || this.cache.has(key) && this.cache.get(key).hasExpired()) {
254
+ data = this.requestData(key, fetcher);
255
+ }
256
+ if (data !== void 0) {
257
+ this.mutate(key, new CacheItem({ data }).expiresIn(dedupingInterval), {
258
+ revalidate: false
259
+ });
260
+ }
261
+ }
262
+ mutate(key, value, options) {
263
+ if (!key)
264
+ return;
265
+ const { revalidate: revalidateAfterMutation, revalidateOptions } = __spreadValues2(__spreadValues2({}, defaultMutateOptions), options);
266
+ let data;
267
+ if (typeof value === "function") {
268
+ let state = null;
269
+ if (this.cache.has(key)) {
270
+ const item = this.cache.get(key);
271
+ if (!item.isResolving())
272
+ state = item.data;
273
+ }
274
+ data = value(state);
275
+ } else {
276
+ data = value;
277
+ }
278
+ this.cache.set(key, data instanceof CacheItem ? data : new CacheItem({ data }));
279
+ if (revalidateAfterMutation)
280
+ this.revalidate(key, revalidateOptions);
281
+ }
282
+ subscribeData(key, onData) {
283
+ if (key) {
284
+ const handler = (payload) => onData(payload);
285
+ this.cache.subscribe(key, handler);
286
+ return () => this.cache.unsubscribe(key, handler);
287
+ }
288
+ return () => {
289
+ };
290
+ }
291
+ subscribeErrors(key, onError) {
292
+ if (key) {
293
+ const handler = (payload) => onError(payload);
294
+ this.errors.subscribe(key, handler);
295
+ return () => this.errors.unsubscribe(key, handler);
296
+ }
297
+ return () => {
298
+ };
299
+ }
300
+ get(key) {
301
+ if (key && this.cache.has(key)) {
302
+ const item = this.cache.get(key);
303
+ if (!item.isResolving())
304
+ return item.data;
305
+ }
306
+ return void 0;
307
+ }
308
+ getWait(key) {
309
+ return new Promise((resolve, reject) => {
310
+ const unsubscribe = this.subscribeData(key, (data) => {
311
+ unsubscribe();
312
+ return resolve(data);
313
+ });
314
+ const unsubscribeErrors = this.subscribeErrors(key, (error) => {
315
+ unsubscribeErrors();
316
+ return reject(error);
317
+ });
318
+ const current = this.get(key);
319
+ if (current)
320
+ return resolve(current);
321
+ });
322
+ }
323
+ subscribe(key, onData, onError, options) {
324
+ const {
325
+ fetcher,
326
+ initialData,
327
+ loadInitialCache,
328
+ revalidateOnStart,
329
+ dedupingInterval,
330
+ revalidateOnFocus,
331
+ focusThrottleInterval,
332
+ revalidateOnReconnect,
333
+ reconnectWhen,
334
+ focusWhen
335
+ } = __spreadValues2(__spreadValues2({}, this.options), options);
336
+ const mutateCurrent = (value, options2) => {
337
+ return this.mutate(this.resolveKey(key), value, options2);
338
+ };
339
+ const revalidateCurrent = (options2) => {
340
+ return this.revalidate(this.resolveKey(key), options2);
341
+ };
342
+ const revalidateCurrentWithOptions = () => {
343
+ return revalidateCurrent({ fetcher, dedupingInterval });
344
+ };
345
+ if (revalidateOnStart)
346
+ revalidateCurrentWithOptions();
347
+ const unsubscribeData = this.subscribeData(this.resolveKey(key), onData);
348
+ const unsubscribeErrors = this.subscribeErrors(this.resolveKey(key), onError);
349
+ const unsubscribeVisibility = focusWhen(revalidateCurrentWithOptions, {
350
+ throttleInterval: focusThrottleInterval,
351
+ enabled: revalidateOnFocus
352
+ });
353
+ const unsubscribeNetwork = reconnectWhen(revalidateCurrentWithOptions, {
354
+ enabled: revalidateOnReconnect
355
+ });
356
+ const unsubscribe = () => {
357
+ unsubscribeData();
358
+ unsubscribeErrors();
359
+ unsubscribeVisibility == null ? void 0 : unsubscribeVisibility();
360
+ unsubscribeNetwork == null ? void 0 : unsubscribeNetwork();
361
+ };
362
+ if (initialData) {
363
+ mutateCurrent(initialData, { revalidate: false });
364
+ }
365
+ if (loadInitialCache) {
366
+ const cachedData = this.get(this.resolveKey(key));
367
+ if (cachedData)
368
+ onData(cachedData);
369
+ }
370
+ return { unsubscribe };
371
+ }
372
+ };
373
+
374
+ // ../../node_modules/.pnpm/sswr@1.10.0_svelte@3.59.1/node_modules/sswr/dist/sswr.mjs
375
+ import { beforeUpdate as _, onDestroy as D } from "svelte";
376
+ function h() {
377
+ }
378
+ function E(t) {
379
+ return t();
380
+ }
381
+ function q(t) {
382
+ t.forEach(E);
383
+ }
384
+ function w(t) {
385
+ return typeof t == "function";
386
+ }
387
+ function K(t, e) {
388
+ return t != t ? e == e : t !== e || t && typeof t == "object" || typeof t == "function";
389
+ }
390
+ function x(t, ...e) {
391
+ if (t == null)
392
+ return h;
393
+ const n = t.subscribe(...e);
394
+ return n.unsubscribe ? () => n.unsubscribe() : n;
395
+ }
396
+ Promise.resolve();
397
+ var v = [];
398
+ function z(t, e) {
399
+ return {
400
+ subscribe: m(t, e).subscribe
401
+ };
402
+ }
403
+ function m(t, e = h) {
404
+ let n;
405
+ const r = /* @__PURE__ */ new Set();
406
+ function c(i) {
407
+ if (K(t, i) && (t = i, n)) {
408
+ const f = !v.length;
409
+ for (const s of r)
410
+ s[1](), v.push(s, t);
411
+ if (f) {
412
+ for (let s = 0; s < v.length; s += 2)
413
+ v[s][0](v[s + 1]);
414
+ v.length = 0;
415
+ }
416
+ }
417
+ }
418
+ function l(i) {
419
+ c(i(t));
420
+ }
421
+ function d(i, f = h) {
422
+ const s = [i, f];
423
+ return r.add(s), r.size === 1 && (n = e(c) || h), i(t), () => {
424
+ r.delete(s), r.size === 0 && (n(), n = null);
425
+ };
426
+ }
427
+ return { set: c, update: l, subscribe: d };
428
+ }
429
+ function S(t, e, n) {
430
+ const r = !Array.isArray(t), c = r ? [t] : t, l = e.length < 2;
431
+ return z(n, (d) => {
432
+ let i = false;
433
+ const f = [];
434
+ let s = 0, p = h;
435
+ const o = () => {
436
+ if (s)
437
+ return;
438
+ p();
439
+ const a = e(r ? f[0] : f, d);
440
+ l ? d(a) : p = w(a) ? a : h;
441
+ }, b = c.map((a, g) => x(a, (y) => {
442
+ f[g] = y, s &= ~(1 << g), i && o();
443
+ }, () => {
444
+ s |= 1 << g;
445
+ }));
446
+ return i = true, o(), function() {
447
+ q(b), p();
448
+ };
449
+ });
450
+ }
451
+ var A = class extends SWR {
452
+ /**
453
+ * Svelte specific use of SWR.
454
+ */
455
+ useSWR(e, n) {
456
+ let r;
457
+ const c = m(void 0, () => () => r == null ? void 0 : r()), l = m(void 0, () => () => r == null ? void 0 : r());
458
+ _(() => {
459
+ const o = (a) => {
460
+ l.set(void 0), c.set(a);
461
+ }, b = (a) => l.set(a);
462
+ r || (r = this.subscribe(e, o, b, __spreadValues({
463
+ loadInitialCache: true
464
+ }, n)).unsubscribe);
465
+ }), D(() => r == null ? void 0 : r());
466
+ const d = (o, b) => this.mutate(this.resolveKey(e), o, __spreadValues({
467
+ revalidateOptions: n
468
+ }, b)), i = (o) => this.revalidate(this.resolveKey(e), __spreadValues(__spreadValues({}, n), o)), f = (o) => this.clear(this.resolveKey(e), o), s = S([c, l], ([o, b]) => o === void 0 && b === void 0), p = S([c, l], ([o, b]) => o !== void 0 && b === void 0);
469
+ return { data: c, error: l, mutate: d, revalidate: i, clear: f, isLoading: s, isValid: p };
470
+ }
471
+ };
472
+ var W = (t) => new A(t);
473
+ var u = W();
474
+ var $ = (t, e) => u.useSWR(t, e);
475
+
476
+ // svelte/use-chat.ts
477
+ import { get, writable } from "svelte/store";
478
+
479
+ // shared/utils.ts
480
+ import { customAlphabet } from "nanoid";
481
+ var nanoid = customAlphabet(
482
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
483
+ 7
484
+ );
485
+ var decoder = new TextDecoder();
486
+ function decodeAIStreamChunk(chunk) {
487
+ return decoder.decode(chunk);
488
+ }
489
+
490
+ // svelte/use-chat.ts
491
+ var uniqueId = 0;
492
+ var store = {};
493
+ function useChat({
494
+ api = "/api/chat",
495
+ id,
496
+ initialMessages = [],
497
+ initialInput = "",
498
+ sendExtraMessageFields,
499
+ onResponse,
500
+ onFinish,
501
+ onError,
502
+ headers,
503
+ body
504
+ } = {}) {
505
+ const chatId = id || `chat-${uniqueId++}`;
506
+ const key = `${api}|${chatId}`;
507
+ const { data, mutate: originalMutate } = $(key, {
508
+ fetcher: () => store[key] || initialMessages,
509
+ initialData: initialMessages
510
+ });
511
+ data.set(initialMessages);
512
+ const mutate = (data2) => {
513
+ store[key] = data2;
514
+ return originalMutate(data2);
515
+ };
516
+ const messages = data;
517
+ const error = writable(void 0);
518
+ const isLoading = writable(false);
519
+ let abortController = null;
520
+ function triggerRequest(messagesSnapshot) {
521
+ return __async(this, null, function* () {
522
+ try {
523
+ isLoading.set(true);
524
+ abortController = new AbortController();
525
+ const previousMessages = get(messages);
526
+ mutate(messagesSnapshot);
527
+ const res = yield fetch(api, {
528
+ method: "POST",
529
+ body: JSON.stringify(__spreadValues({
530
+ messages: sendExtraMessageFields ? messagesSnapshot : messagesSnapshot.map(({ role, content }) => ({
531
+ role,
532
+ content
533
+ }))
534
+ }, body)),
535
+ headers: headers || {},
536
+ signal: abortController.signal
537
+ }).catch((err) => {
538
+ mutate(previousMessages);
539
+ throw err;
540
+ });
541
+ if (onResponse) {
542
+ try {
543
+ yield onResponse(res);
544
+ } catch (err) {
545
+ throw err;
546
+ }
547
+ }
548
+ if (!res.ok) {
549
+ mutate(previousMessages);
550
+ throw new Error(
551
+ (yield res.text()) || "Failed to fetch the chat response."
552
+ );
553
+ }
554
+ if (!res.body) {
555
+ throw new Error("The response body is empty.");
556
+ }
557
+ let result = "";
558
+ const createdAt = /* @__PURE__ */ new Date();
559
+ const replyId = nanoid();
560
+ const reader = res.body.getReader();
561
+ while (true) {
562
+ const { done, value } = yield reader.read();
563
+ if (done) {
564
+ break;
565
+ }
566
+ result += decodeAIStreamChunk(value);
567
+ mutate([
568
+ ...messagesSnapshot,
569
+ {
570
+ id: replyId,
571
+ createdAt,
572
+ content: result,
573
+ role: "assistant"
574
+ }
575
+ ]);
576
+ if (abortController === null) {
577
+ reader.cancel();
578
+ break;
579
+ }
580
+ }
581
+ if (onFinish) {
582
+ onFinish({
583
+ id: replyId,
584
+ createdAt,
585
+ content: result,
586
+ role: "assistant"
587
+ });
588
+ }
589
+ abortController = null;
590
+ return result;
591
+ } catch (err) {
592
+ if (err.name === "AbortError") {
593
+ abortController = null;
594
+ return null;
595
+ }
596
+ if (onError && err instanceof Error) {
597
+ onError(err);
598
+ }
599
+ error.set(err);
600
+ } finally {
601
+ isLoading.set(false);
602
+ }
603
+ });
604
+ }
605
+ const append = (message) => __async(this, null, function* () {
606
+ if (!message.id) {
607
+ message.id = nanoid();
608
+ }
609
+ return triggerRequest(get(messages).concat(message));
610
+ });
611
+ const reload = () => __async(this, null, function* () {
612
+ const messagesSnapshot = get(messages);
613
+ if (messagesSnapshot.length === 0)
614
+ return null;
615
+ const lastMessage = messagesSnapshot[messagesSnapshot.length - 1];
616
+ if (lastMessage.role === "assistant") {
617
+ return triggerRequest(messagesSnapshot.slice(0, -1));
618
+ }
619
+ return triggerRequest(messagesSnapshot);
620
+ });
621
+ const stop = () => {
622
+ if (abortController) {
623
+ abortController.abort();
624
+ abortController = null;
625
+ }
626
+ };
627
+ const setMessages = (messages2) => {
628
+ mutate(messages2);
629
+ };
630
+ const input = writable(initialInput);
631
+ const handleSubmit = (e) => {
632
+ e.preventDefault();
633
+ const inputValue = get(input);
634
+ if (!inputValue)
635
+ return;
636
+ append({
637
+ content: inputValue,
638
+ role: "user"
639
+ });
640
+ input.set("");
641
+ };
642
+ return {
643
+ messages,
644
+ append,
645
+ error,
646
+ reload,
647
+ stop,
648
+ setMessages,
649
+ input,
650
+ handleSubmit,
651
+ isLoading
652
+ };
653
+ }
654
+
655
+ // svelte/use-completion.ts
656
+ import { get as get2, writable as writable2 } from "svelte/store";
657
+ var uniqueId2 = 0;
658
+ var store2 = {};
659
+ function useCompletion({
660
+ api = "/api/completion",
661
+ id,
662
+ initialCompletion = "",
663
+ initialInput = "",
664
+ headers,
665
+ body,
666
+ onResponse,
667
+ onFinish,
668
+ onError
669
+ } = {}) {
670
+ const completionId = id || `completion-${uniqueId2++}`;
671
+ const key = `${api}|${completionId}`;
672
+ const { data, mutate: originalMutate } = $(key, {
673
+ fetcher: () => store2[key] || initialCompletion,
674
+ initialData: initialCompletion
675
+ });
676
+ data.set(initialCompletion);
677
+ const mutate = (data2) => {
678
+ store2[key] = data2;
679
+ return originalMutate(data2);
680
+ };
681
+ const completion = data;
682
+ const error = writable2(void 0);
683
+ const isLoading = writable2(false);
684
+ let abortController = null;
685
+ function triggerRequest(prompt) {
686
+ return __async(this, null, function* () {
687
+ try {
688
+ isLoading.set(true);
689
+ abortController = new AbortController();
690
+ mutate("");
691
+ const res = yield fetch(api, {
692
+ method: "POST",
693
+ body: JSON.stringify(__spreadValues({
694
+ prompt
695
+ }, body)),
696
+ headers: headers || {},
697
+ signal: abortController.signal
698
+ }).catch((err) => {
699
+ throw err;
700
+ });
701
+ if (onResponse) {
702
+ try {
703
+ yield onResponse(res);
704
+ } catch (err) {
705
+ throw err;
706
+ }
707
+ }
708
+ if (!res.ok) {
709
+ throw new Error(
710
+ (yield res.text()) || "Failed to fetch the chat response."
711
+ );
712
+ }
713
+ if (!res.body) {
714
+ throw new Error("The response body is empty.");
715
+ }
716
+ let result = "";
717
+ const reader = res.body.getReader();
718
+ while (true) {
719
+ const { done, value } = yield reader.read();
720
+ if (done) {
721
+ break;
722
+ }
723
+ result += decodeAIStreamChunk(value);
724
+ mutate(result);
725
+ if (abortController === null) {
726
+ reader.cancel();
727
+ break;
728
+ }
729
+ }
730
+ if (onFinish) {
731
+ onFinish(prompt, result);
732
+ }
733
+ abortController = null;
734
+ return result;
735
+ } catch (err) {
736
+ if (err.name === "AbortError") {
737
+ abortController = null;
738
+ return null;
739
+ }
740
+ if (onError && error instanceof Error) {
741
+ onError(error);
742
+ }
743
+ error.set(err);
744
+ } finally {
745
+ isLoading.set(false);
746
+ }
747
+ });
748
+ }
749
+ const complete = (prompt) => __async(this, null, function* () {
750
+ return triggerRequest(prompt);
751
+ });
752
+ const stop = () => {
753
+ if (abortController) {
754
+ abortController.abort();
755
+ abortController = null;
756
+ }
757
+ };
758
+ const setCompletion = (completion2) => {
759
+ mutate(completion2);
760
+ };
761
+ const input = writable2(initialInput);
762
+ const handleSubmit = (e) => {
763
+ e.preventDefault();
764
+ const inputValue = get2(input);
765
+ if (!inputValue)
766
+ return;
767
+ return complete(inputValue);
768
+ };
769
+ return {
770
+ completion,
771
+ complete,
772
+ error,
773
+ stop,
774
+ setCompletion,
775
+ input,
776
+ handleSubmit,
777
+ isLoading
778
+ };
779
+ }
8
780
  export {
9
781
  useChat,
10
782
  useCompletion