ai 0.0.0-e27b4ed4-20240419203611

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 (56) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +37 -0
  3. package/dist/index.d.mts +1770 -0
  4. package/dist/index.d.ts +1770 -0
  5. package/dist/index.js +2958 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/index.mjs +2887 -0
  8. package/dist/index.mjs.map +1 -0
  9. package/package.json +174 -0
  10. package/prompts/dist/index.d.mts +267 -0
  11. package/prompts/dist/index.d.ts +267 -0
  12. package/prompts/dist/index.js +178 -0
  13. package/prompts/dist/index.js.map +1 -0
  14. package/prompts/dist/index.mjs +146 -0
  15. package/prompts/dist/index.mjs.map +1 -0
  16. package/react/dist/index.d.mts +487 -0
  17. package/react/dist/index.d.ts +504 -0
  18. package/react/dist/index.js +1310 -0
  19. package/react/dist/index.js.map +1 -0
  20. package/react/dist/index.mjs +1271 -0
  21. package/react/dist/index.mjs.map +1 -0
  22. package/react/dist/index.server.d.mts +17 -0
  23. package/react/dist/index.server.d.ts +17 -0
  24. package/react/dist/index.server.js +50 -0
  25. package/react/dist/index.server.js.map +1 -0
  26. package/react/dist/index.server.mjs +23 -0
  27. package/react/dist/index.server.mjs.map +1 -0
  28. package/rsc/dist/index.d.ts +289 -0
  29. package/rsc/dist/index.mjs +18 -0
  30. package/rsc/dist/rsc-client.d.mts +1 -0
  31. package/rsc/dist/rsc-client.mjs +18 -0
  32. package/rsc/dist/rsc-client.mjs.map +1 -0
  33. package/rsc/dist/rsc-server.d.mts +225 -0
  34. package/rsc/dist/rsc-server.mjs +1246 -0
  35. package/rsc/dist/rsc-server.mjs.map +1 -0
  36. package/rsc/dist/rsc-shared.d.mts +94 -0
  37. package/rsc/dist/rsc-shared.mjs +346 -0
  38. package/rsc/dist/rsc-shared.mjs.map +1 -0
  39. package/solid/dist/index.d.mts +351 -0
  40. package/solid/dist/index.d.ts +351 -0
  41. package/solid/dist/index.js +1002 -0
  42. package/solid/dist/index.js.map +1 -0
  43. package/solid/dist/index.mjs +974 -0
  44. package/solid/dist/index.mjs.map +1 -0
  45. package/svelte/dist/index.d.mts +348 -0
  46. package/svelte/dist/index.d.ts +348 -0
  47. package/svelte/dist/index.js +1556 -0
  48. package/svelte/dist/index.js.map +1 -0
  49. package/svelte/dist/index.mjs +1528 -0
  50. package/svelte/dist/index.mjs.map +1 -0
  51. package/vue/dist/index.d.mts +345 -0
  52. package/vue/dist/index.d.ts +345 -0
  53. package/vue/dist/index.js +1002 -0
  54. package/vue/dist/index.js.map +1 -0
  55. package/vue/dist/index.mjs +964 -0
  56. package/vue/dist/index.mjs.map +1 -0
@@ -0,0 +1,1556 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // svelte/index.ts
21
+ var svelte_exports = {};
22
+ __export(svelte_exports, {
23
+ useChat: () => useChat,
24
+ useCompletion: () => useCompletion
25
+ });
26
+ module.exports = __toCommonJS(svelte_exports);
27
+
28
+ // ../../node_modules/.pnpm/swrev@4.0.0/node_modules/swrev/dist/swrev.mjs
29
+ var P = Object.defineProperty;
30
+ var F = (r, e, t) => e in r ? P(r, e, { enumerable: true, configurable: true, writable: true, value: t }) : r[e] = t;
31
+ var h = (r, e, t) => (F(r, typeof e != "symbol" ? e + "" : e, t), t);
32
+ var I = class {
33
+ constructor() {
34
+ h(this, "listeners", /* @__PURE__ */ new Map());
35
+ }
36
+ /**
37
+ * Subscribes a given listener.
38
+ */
39
+ subscribe(e, t) {
40
+ this.listeners.has(e) || this.listeners.set(e, []), !this.listeners.get(e).includes(t) && this.listeners.get(e).push(t);
41
+ }
42
+ /**
43
+ * Unsubscribes the given listener.
44
+ */
45
+ unsubscribe(e, t) {
46
+ this.listeners.has(e) && this.listeners.get(e).includes(t) && (this.listeners.get(e).splice(this.listeners.get(e).indexOf(t), 1), this.listeners.get(e).length === 0 && this.listeners.delete(e));
47
+ }
48
+ /**
49
+ * Emits an event to all active listeners.
50
+ */
51
+ emit(e, t) {
52
+ this.listeners.has(e) && this.listeners.get(e).forEach((s) => s(t));
53
+ }
54
+ };
55
+ var L = {
56
+ broadcast: false
57
+ };
58
+ var S = {
59
+ broadcast: false
60
+ };
61
+ var O = class {
62
+ /**
63
+ * Creates the cache item given the data and expiration at.
64
+ */
65
+ constructor({ data: e, expiresAt: t = null }) {
66
+ h(this, "data");
67
+ h(this, "expiresAt");
68
+ this.data = e, this.expiresAt = t;
69
+ }
70
+ /**
71
+ * Determines if the current cache item is still being resolved.
72
+ * This returns true if data is a promise, or false if type `D`.
73
+ */
74
+ isResolving() {
75
+ return this.data instanceof Promise;
76
+ }
77
+ /**
78
+ * Determines if the given cache item has expired.
79
+ */
80
+ hasExpired() {
81
+ return this.expiresAt === null || this.expiresAt < /* @__PURE__ */ new Date();
82
+ }
83
+ /**
84
+ * Set the expiration time of the given cache item relative to now.
85
+ */
86
+ expiresIn(e) {
87
+ return this.expiresAt = /* @__PURE__ */ new Date(), this.expiresAt.setMilliseconds(this.expiresAt.getMilliseconds() + e), this;
88
+ }
89
+ };
90
+ var q = class {
91
+ constructor() {
92
+ h(this, "elements", /* @__PURE__ */ new Map());
93
+ h(this, "event", new I());
94
+ }
95
+ /**
96
+ * Resolves the promise and replaces the Promise to the resolved data.
97
+ * It also broadcasts the value change if needed or deletes the key if
98
+ * the value resolves to undefined or null.
99
+ */
100
+ resolve(e, t) {
101
+ Promise.resolve(t.data).then((s) => {
102
+ if (s == null)
103
+ return this.remove(e);
104
+ t.data = s, this.broadcast(e, s);
105
+ });
106
+ }
107
+ /**
108
+ * Gets an element from the cache.
109
+ *
110
+ * It is assumed the item always exist when
111
+ * you get it. Use the has method to check
112
+ * for the existence of it.
113
+ */
114
+ get(e) {
115
+ return this.elements.get(e);
116
+ }
117
+ /**
118
+ * Sets an element to the cache.
119
+ */
120
+ set(e, t) {
121
+ this.elements.set(e, t), this.resolve(e, t);
122
+ }
123
+ /**
124
+ * Removes an key-value pair from the cache.
125
+ */
126
+ remove(e, t) {
127
+ const { broadcast: s } = { ...L, ...t };
128
+ s && this.broadcast(e, void 0), this.elements.delete(e);
129
+ }
130
+ /**
131
+ * Removes all the key-value pairs from the cache.
132
+ */
133
+ clear(e) {
134
+ const { broadcast: t } = { ...S, ...e };
135
+ if (t)
136
+ for (const s of this.elements.keys())
137
+ this.broadcast(s, void 0);
138
+ this.elements.clear();
139
+ }
140
+ /**
141
+ * Determines if the given key exists
142
+ * in the cache.
143
+ */
144
+ has(e) {
145
+ return this.elements.has(e);
146
+ }
147
+ /**
148
+ * Subscribes the callback to the given key.
149
+ */
150
+ subscribe(e, t) {
151
+ this.event.subscribe(e, t);
152
+ }
153
+ /**
154
+ * Unsubscribes to the given key events.
155
+ */
156
+ unsubscribe(e, t) {
157
+ this.event.unsubscribe(e, t);
158
+ }
159
+ /**
160
+ * Broadcasts a value change on all subscribed instances.
161
+ */
162
+ broadcast(e, t) {
163
+ this.event.emit(e, t);
164
+ }
165
+ };
166
+ var x = {
167
+ cache: new q(),
168
+ errors: new I(),
169
+ fetcher: async (r) => {
170
+ const e = await fetch(r);
171
+ if (!e.ok)
172
+ throw Error("Not a 2XX response.");
173
+ return e.json();
174
+ },
175
+ fallbackData: void 0,
176
+ loadInitialCache: true,
177
+ revalidateOnStart: true,
178
+ dedupingInterval: 2e3,
179
+ revalidateOnFocus: true,
180
+ focusThrottleInterval: 5e3,
181
+ revalidateOnReconnect: true,
182
+ reconnectWhen: (r, { enabled: e }) => e && typeof window < "u" ? (window.addEventListener("online", r), () => window.removeEventListener("online", r)) : () => {
183
+ },
184
+ focusWhen: (r, { enabled: e, throttleInterval: t }) => {
185
+ if (e && typeof window < "u") {
186
+ let s = null;
187
+ const i = () => {
188
+ const a = Date.now();
189
+ (s === null || a - s > t) && (s = a, r());
190
+ };
191
+ return window.addEventListener("focus", i), () => window.removeEventListener("focus", i);
192
+ }
193
+ return () => {
194
+ };
195
+ },
196
+ revalidateFunction: void 0
197
+ };
198
+ var E = {
199
+ ...x,
200
+ force: false
201
+ };
202
+ var T = {
203
+ revalidate: true,
204
+ revalidateOptions: { ...E },
205
+ revalidateFunction: void 0
206
+ };
207
+ var X = {
208
+ broadcast: false
209
+ };
210
+ var H = class {
211
+ /**
212
+ * Creates a new instance of SWR.
213
+ */
214
+ constructor(e) {
215
+ h(this, "options");
216
+ this.options = { ...x, ...e };
217
+ }
218
+ /**
219
+ * Gets the cache of the SWR.
220
+ */
221
+ get cache() {
222
+ return this.options.cache;
223
+ }
224
+ /**
225
+ * Gets the cache of the SWR.
226
+ */
227
+ get errors() {
228
+ return this.options.errors;
229
+ }
230
+ /**
231
+ * Requests the data using the provided fetcher.
232
+ */
233
+ async requestData(e, t) {
234
+ return await Promise.resolve(t(e)).catch((s) => {
235
+ throw this.errors.emit(e, s), s;
236
+ });
237
+ }
238
+ /**
239
+ * Resolves the given to a SWRKey or undefined.
240
+ */
241
+ resolveKey(e) {
242
+ if (typeof e == "function")
243
+ try {
244
+ return e();
245
+ } catch (e2) {
246
+ return;
247
+ }
248
+ return e;
249
+ }
250
+ /**
251
+ * Clear the specified keys from the cache. If no keys
252
+ * are specified, it clears all the cache keys.
253
+ */
254
+ clear(e, t) {
255
+ const s = { ...X, ...t };
256
+ if (e == null)
257
+ return this.cache.clear(s);
258
+ if (!Array.isArray(e))
259
+ return this.cache.remove(e, s);
260
+ for (const i of e)
261
+ this.cache.remove(i, s);
262
+ }
263
+ /**
264
+ * Revalidates the key and mutates the cache if needed.
265
+ */
266
+ async revalidate(e, t) {
267
+ if (!e)
268
+ throw new Error("[Revalidate] Key issue: ${key}");
269
+ const { fetcher: s, dedupingInterval: i } = this.options, { force: a, fetcher: o, dedupingInterval: n } = {
270
+ ...E,
271
+ fetcher: s,
272
+ dedupingInterval: i,
273
+ ...t
274
+ };
275
+ if (a || !this.cache.has(e) || this.cache.has(e) && this.cache.get(e).hasExpired()) {
276
+ const c2 = this.requestData(e, o), l = c2.catch(() => {
277
+ });
278
+ return this.cache.set(e, new O({ data: l }).expiresIn(n)), await c2;
279
+ }
280
+ return this.getWait(e);
281
+ }
282
+ /**
283
+ * Mutates the data of a given key with a new value.
284
+ * This is used to replace the cache contents of the
285
+ * given key manually.
286
+ */
287
+ async mutate(e, t, s) {
288
+ var _a;
289
+ if (!e)
290
+ throw new Error("[Mutate] Key issue: ${key}");
291
+ const {
292
+ revalidate: i,
293
+ revalidateOptions: a,
294
+ revalidateFunction: o
295
+ } = {
296
+ ...T,
297
+ ...s
298
+ };
299
+ let n;
300
+ if (typeof t == "function") {
301
+ let c2;
302
+ if (this.cache.has(e)) {
303
+ const l = this.cache.get(e);
304
+ l.isResolving() || (c2 = l.data);
305
+ }
306
+ n = t(c2);
307
+ } else
308
+ n = t;
309
+ return this.cache.set(e, new O({ data: n })), i ? await ((_a = o == null ? void 0 : o(e, a)) != null ? _a : this.revalidate(e, a)) : n;
310
+ }
311
+ /**
312
+ * Gets the data of the given key. Keep in mind
313
+ * this data will be stale and revalidate in the background
314
+ * unless specified otherwise.
315
+ */
316
+ subscribeData(e, t) {
317
+ if (e) {
318
+ const s = (i) => t(i);
319
+ return this.cache.subscribe(e, s), () => this.cache.unsubscribe(e, s);
320
+ }
321
+ return () => {
322
+ };
323
+ }
324
+ /**
325
+ * Subscribes to errors on the given key.
326
+ */
327
+ subscribeErrors(e, t) {
328
+ if (e) {
329
+ const s = (i) => t(i);
330
+ return this.errors.subscribe(e, s), () => this.errors.unsubscribe(e, s);
331
+ }
332
+ return () => {
333
+ };
334
+ }
335
+ /**
336
+ * Gets the current cached data of the given key.
337
+ * This does not trigger any revalidation nor mutation
338
+ * of the data.
339
+ * - If the data has never been validated
340
+ * (there is no cache) it will return undefined.
341
+ * - If the item is pending to resolve (there is a request
342
+ * pending to resolve) it will return undefined.
343
+ */
344
+ get(e) {
345
+ if (e && this.cache.has(e)) {
346
+ const t = this.cache.get(e);
347
+ if (!t.isResolving())
348
+ return t.data;
349
+ }
350
+ }
351
+ /**
352
+ * Gets an element from the cache. The difference
353
+ * with the get is that this method returns a promise
354
+ * that will resolve the the value. If there's no item
355
+ * in the cache, it will wait for it before resolving.
356
+ */
357
+ getWait(e) {
358
+ return new Promise((t, s) => {
359
+ const i = this.subscribeData(e, (n) => {
360
+ if (i(), n !== void 0)
361
+ return t(n);
362
+ }), a = this.subscribeErrors(e, (n) => {
363
+ if (a(), n !== void 0)
364
+ return s(n);
365
+ }), o = this.get(e);
366
+ if (o !== void 0)
367
+ return t(o);
368
+ });
369
+ }
370
+ /**
371
+ * Use a SWR value given the key and
372
+ * subscribe to future changes.
373
+ */
374
+ subscribe(e, t, s, i) {
375
+ const {
376
+ fetcher: a,
377
+ fallbackData: o,
378
+ loadInitialCache: n,
379
+ revalidateOnStart: c2,
380
+ dedupingInterval: l,
381
+ revalidateOnFocus: A2,
382
+ focusThrottleInterval: C,
383
+ revalidateOnReconnect: R,
384
+ reconnectWhen: W2,
385
+ focusWhen: D2,
386
+ revalidateFunction: d
387
+ } = {
388
+ // Current instance options
389
+ // (includes default options)
390
+ ...this.options,
391
+ // Current call options.
392
+ ...i
393
+ }, K2 = (m) => {
394
+ var _a;
395
+ return (_a = d == null ? void 0 : d(this.resolveKey(e), m)) != null ? _a : this.revalidate(this.resolveKey(e), m);
396
+ }, f = () => K2({ fetcher: a, dedupingInterval: l }), u = n ? this.get(this.resolveKey(e)) : o != null ? o : void 0, g = c2 ? f() : Promise.resolve(void 0), M = u ? Promise.resolve(u) : g;
397
+ u && (t == null || t(u));
398
+ const v2 = t ? this.subscribeData(this.resolveKey(e), t) : void 0, b = s ? this.subscribeErrors(this.resolveKey(e), s) : void 0, p2 = D2(f, {
399
+ throttleInterval: C,
400
+ enabled: A2
401
+ }), w2 = W2(f, {
402
+ enabled: R
403
+ });
404
+ return { unsubscribe: () => {
405
+ v2 == null || v2(), b == null || b(), p2 == null || p2(), w2 == null || w2();
406
+ }, dataPromise: M, revalidatePromise: g };
407
+ }
408
+ };
409
+
410
+ // ../../node_modules/.pnpm/sswr@2.0.0_svelte@4.2.3/node_modules/sswr/dist/sswr.mjs
411
+ var import_svelte = require("svelte");
412
+ function p() {
413
+ }
414
+ function D(t) {
415
+ return t();
416
+ }
417
+ function q2(t) {
418
+ t.forEach(D);
419
+ }
420
+ function x2(t) {
421
+ return typeof t == "function";
422
+ }
423
+ function K(t, e) {
424
+ return t != t ? e == e : t !== e || t && typeof t == "object" || typeof t == "function";
425
+ }
426
+ function z(t, ...e) {
427
+ if (t == null) {
428
+ for (const r of e)
429
+ r(void 0);
430
+ return p;
431
+ }
432
+ const n = t.subscribe(...e);
433
+ return n.unsubscribe ? () => n.unsubscribe() : n;
434
+ }
435
+ var v = [];
436
+ function A(t, e) {
437
+ return {
438
+ subscribe: y(t, e).subscribe
439
+ };
440
+ }
441
+ function y(t, e = p) {
442
+ let n;
443
+ const r = /* @__PURE__ */ new Set();
444
+ function i(u) {
445
+ if (K(t, u) && (t = u, n)) {
446
+ const f = !v.length;
447
+ for (const s of r)
448
+ s[1](), v.push(s, t);
449
+ if (f) {
450
+ for (let s = 0; s < v.length; s += 2)
451
+ v[s][0](v[s + 1]);
452
+ v.length = 0;
453
+ }
454
+ }
455
+ }
456
+ function a(u) {
457
+ i(u(t));
458
+ }
459
+ function d(u, f = p) {
460
+ const s = [u, f];
461
+ return r.add(s), r.size === 1 && (n = e(i, a) || p), u(t), () => {
462
+ r.delete(s), r.size === 0 && n && (n(), n = null);
463
+ };
464
+ }
465
+ return { set: i, update: a, subscribe: d };
466
+ }
467
+ function S2(t, e, n) {
468
+ const r = !Array.isArray(t), i = r ? [t] : t;
469
+ if (!i.every(Boolean))
470
+ throw new Error("derived() expects stores as input, got a falsy value");
471
+ const a = e.length < 2;
472
+ return A(n, (d, u) => {
473
+ let f = false;
474
+ const s = [];
475
+ let h2 = 0, o = p;
476
+ const l = () => {
477
+ if (h2)
478
+ return;
479
+ o();
480
+ const b = e(r ? s[0] : s, d, u);
481
+ a ? d(b) : o = x2(b) ? b : p;
482
+ }, g = i.map(
483
+ (b, m) => z(
484
+ b,
485
+ (R) => {
486
+ s[m] = R, h2 &= ~(1 << m), f && l();
487
+ },
488
+ () => {
489
+ h2 |= 1 << m;
490
+ }
491
+ )
492
+ );
493
+ return f = true, l(), function() {
494
+ q2(g), o(), f = false;
495
+ };
496
+ });
497
+ }
498
+ var O2 = class extends H {
499
+ /**
500
+ * Svelte specific use of SWR.
501
+ */
502
+ useSWR(e, n) {
503
+ let r;
504
+ const i = y(void 0, () => () => r == null ? void 0 : r()), a = y(void 0, () => () => r == null ? void 0 : r());
505
+ (0, import_svelte.beforeUpdate)(() => {
506
+ const o = (g) => {
507
+ a.set(void 0), i.set(g);
508
+ }, l = (g) => a.set(g);
509
+ r || (r = this.subscribe(e, o, l, {
510
+ loadInitialCache: true,
511
+ ...n
512
+ }).unsubscribe);
513
+ }), (0, import_svelte.onDestroy)(() => r == null ? void 0 : r());
514
+ const d = (o, l) => this.mutate(this.resolveKey(e), o, {
515
+ revalidateOptions: n,
516
+ ...l
517
+ }), u = (o) => this.revalidate(this.resolveKey(e), { ...n, ...o }), f = (o) => this.clear(this.resolveKey(e), o), s = S2([i, a], ([o, l]) => o === void 0 && l === void 0), h2 = S2([i, a], ([o, l]) => o !== void 0 && l === void 0);
518
+ return { data: i, error: a, mutate: d, revalidate: u, clear: f, isLoading: s, isValid: h2 };
519
+ }
520
+ };
521
+ var W = (t) => new O2(t);
522
+ var c = W();
523
+ var F2 = (t, e) => c.useSWR(t, e);
524
+
525
+ // svelte/use-chat.ts
526
+ var import_store = require("svelte/store");
527
+
528
+ // shared/stream-parts.ts
529
+ var textStreamPart = {
530
+ code: "0",
531
+ name: "text",
532
+ parse: (value) => {
533
+ if (typeof value !== "string") {
534
+ throw new Error('"text" parts expect a string value.');
535
+ }
536
+ return { type: "text", value };
537
+ }
538
+ };
539
+ var functionCallStreamPart = {
540
+ code: "1",
541
+ name: "function_call",
542
+ parse: (value) => {
543
+ if (value == null || typeof value !== "object" || !("function_call" in value) || typeof value.function_call !== "object" || value.function_call == null || !("name" in value.function_call) || !("arguments" in value.function_call) || typeof value.function_call.name !== "string" || typeof value.function_call.arguments !== "string") {
544
+ throw new Error(
545
+ '"function_call" parts expect an object with a "function_call" property.'
546
+ );
547
+ }
548
+ return {
549
+ type: "function_call",
550
+ value
551
+ };
552
+ }
553
+ };
554
+ var dataStreamPart = {
555
+ code: "2",
556
+ name: "data",
557
+ parse: (value) => {
558
+ if (!Array.isArray(value)) {
559
+ throw new Error('"data" parts expect an array value.');
560
+ }
561
+ return { type: "data", value };
562
+ }
563
+ };
564
+ var errorStreamPart = {
565
+ code: "3",
566
+ name: "error",
567
+ parse: (value) => {
568
+ if (typeof value !== "string") {
569
+ throw new Error('"error" parts expect a string value.');
570
+ }
571
+ return { type: "error", value };
572
+ }
573
+ };
574
+ var assistantMessageStreamPart = {
575
+ code: "4",
576
+ name: "assistant_message",
577
+ parse: (value) => {
578
+ if (value == null || typeof value !== "object" || !("id" in value) || !("role" in value) || !("content" in value) || typeof value.id !== "string" || typeof value.role !== "string" || value.role !== "assistant" || !Array.isArray(value.content) || !value.content.every(
579
+ (item) => item != null && typeof item === "object" && "type" in item && item.type === "text" && "text" in item && item.text != null && typeof item.text === "object" && "value" in item.text && typeof item.text.value === "string"
580
+ )) {
581
+ throw new Error(
582
+ '"assistant_message" parts expect an object with an "id", "role", and "content" property.'
583
+ );
584
+ }
585
+ return {
586
+ type: "assistant_message",
587
+ value
588
+ };
589
+ }
590
+ };
591
+ var assistantControlDataStreamPart = {
592
+ code: "5",
593
+ name: "assistant_control_data",
594
+ parse: (value) => {
595
+ if (value == null || typeof value !== "object" || !("threadId" in value) || !("messageId" in value) || typeof value.threadId !== "string" || typeof value.messageId !== "string") {
596
+ throw new Error(
597
+ '"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.'
598
+ );
599
+ }
600
+ return {
601
+ type: "assistant_control_data",
602
+ value: {
603
+ threadId: value.threadId,
604
+ messageId: value.messageId
605
+ }
606
+ };
607
+ }
608
+ };
609
+ var dataMessageStreamPart = {
610
+ code: "6",
611
+ name: "data_message",
612
+ parse: (value) => {
613
+ if (value == null || typeof value !== "object" || !("role" in value) || !("data" in value) || typeof value.role !== "string" || value.role !== "data") {
614
+ throw new Error(
615
+ '"data_message" parts expect an object with a "role" and "data" property.'
616
+ );
617
+ }
618
+ return {
619
+ type: "data_message",
620
+ value
621
+ };
622
+ }
623
+ };
624
+ var toolCallStreamPart = {
625
+ code: "7",
626
+ name: "tool_calls",
627
+ parse: (value) => {
628
+ if (value == null || typeof value !== "object" || !("tool_calls" in value) || typeof value.tool_calls !== "object" || value.tool_calls == null || !Array.isArray(value.tool_calls) || value.tool_calls.some(
629
+ (tc) => tc == null || typeof tc !== "object" || !("id" in tc) || typeof tc.id !== "string" || !("type" in tc) || typeof tc.type !== "string" || !("function" in tc) || tc.function == null || typeof tc.function !== "object" || !("arguments" in tc.function) || typeof tc.function.name !== "string" || typeof tc.function.arguments !== "string"
630
+ )) {
631
+ throw new Error(
632
+ '"tool_calls" parts expect an object with a ToolCallPayload.'
633
+ );
634
+ }
635
+ return {
636
+ type: "tool_calls",
637
+ value
638
+ };
639
+ }
640
+ };
641
+ var messageAnnotationsStreamPart = {
642
+ code: "8",
643
+ name: "message_annotations",
644
+ parse: (value) => {
645
+ if (!Array.isArray(value)) {
646
+ throw new Error('"message_annotations" parts expect an array value.');
647
+ }
648
+ return { type: "message_annotations", value };
649
+ }
650
+ };
651
+ var streamParts = [
652
+ textStreamPart,
653
+ functionCallStreamPart,
654
+ dataStreamPart,
655
+ errorStreamPart,
656
+ assistantMessageStreamPart,
657
+ assistantControlDataStreamPart,
658
+ dataMessageStreamPart,
659
+ toolCallStreamPart,
660
+ messageAnnotationsStreamPart
661
+ ];
662
+ var streamPartsByCode = {
663
+ [textStreamPart.code]: textStreamPart,
664
+ [functionCallStreamPart.code]: functionCallStreamPart,
665
+ [dataStreamPart.code]: dataStreamPart,
666
+ [errorStreamPart.code]: errorStreamPart,
667
+ [assistantMessageStreamPart.code]: assistantMessageStreamPart,
668
+ [assistantControlDataStreamPart.code]: assistantControlDataStreamPart,
669
+ [dataMessageStreamPart.code]: dataMessageStreamPart,
670
+ [toolCallStreamPart.code]: toolCallStreamPart,
671
+ [messageAnnotationsStreamPart.code]: messageAnnotationsStreamPart
672
+ };
673
+ var StreamStringPrefixes = {
674
+ [textStreamPart.name]: textStreamPart.code,
675
+ [functionCallStreamPart.name]: functionCallStreamPart.code,
676
+ [dataStreamPart.name]: dataStreamPart.code,
677
+ [errorStreamPart.name]: errorStreamPart.code,
678
+ [assistantMessageStreamPart.name]: assistantMessageStreamPart.code,
679
+ [assistantControlDataStreamPart.name]: assistantControlDataStreamPart.code,
680
+ [dataMessageStreamPart.name]: dataMessageStreamPart.code,
681
+ [toolCallStreamPart.name]: toolCallStreamPart.code,
682
+ [messageAnnotationsStreamPart.name]: messageAnnotationsStreamPart.code
683
+ };
684
+ var validCodes = streamParts.map((part) => part.code);
685
+ var parseStreamPart = (line) => {
686
+ const firstSeparatorIndex = line.indexOf(":");
687
+ if (firstSeparatorIndex === -1) {
688
+ throw new Error("Failed to parse stream string. No separator found.");
689
+ }
690
+ const prefix = line.slice(0, firstSeparatorIndex);
691
+ if (!validCodes.includes(prefix)) {
692
+ throw new Error(`Failed to parse stream string. Invalid code ${prefix}.`);
693
+ }
694
+ const code = prefix;
695
+ const textValue = line.slice(firstSeparatorIndex + 1);
696
+ const jsonValue = JSON.parse(textValue);
697
+ return streamPartsByCode[code].parse(jsonValue);
698
+ };
699
+
700
+ // shared/read-data-stream.ts
701
+ var NEWLINE = "\n".charCodeAt(0);
702
+ function concatChunks(chunks, totalLength) {
703
+ const concatenatedChunks = new Uint8Array(totalLength);
704
+ let offset = 0;
705
+ for (const chunk of chunks) {
706
+ concatenatedChunks.set(chunk, offset);
707
+ offset += chunk.length;
708
+ }
709
+ chunks.length = 0;
710
+ return concatenatedChunks;
711
+ }
712
+ async function* readDataStream(reader, {
713
+ isAborted
714
+ } = {}) {
715
+ const decoder = new TextDecoder();
716
+ const chunks = [];
717
+ let totalLength = 0;
718
+ while (true) {
719
+ const { value } = await reader.read();
720
+ if (value) {
721
+ chunks.push(value);
722
+ totalLength += value.length;
723
+ if (value[value.length - 1] !== NEWLINE) {
724
+ continue;
725
+ }
726
+ }
727
+ if (chunks.length === 0) {
728
+ break;
729
+ }
730
+ const concatenatedChunks = concatChunks(chunks, totalLength);
731
+ totalLength = 0;
732
+ const streamParts2 = decoder.decode(concatenatedChunks, { stream: true }).split("\n").filter((line) => line !== "").map(parseStreamPart);
733
+ for (const streamPart of streamParts2) {
734
+ yield streamPart;
735
+ }
736
+ if (isAborted == null ? void 0 : isAborted()) {
737
+ reader.cancel();
738
+ break;
739
+ }
740
+ }
741
+ }
742
+
743
+ // shared/generate-id.ts
744
+ var import_non_secure = require("nanoid/non-secure");
745
+ var generateId = (0, import_non_secure.customAlphabet)(
746
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
747
+ 7
748
+ );
749
+
750
+ // shared/parse-complex-response.ts
751
+ function assignAnnotationsToMessage(message, annotations) {
752
+ if (!message || !annotations || !annotations.length)
753
+ return message;
754
+ return { ...message, annotations: [...annotations] };
755
+ }
756
+ async function parseComplexResponse({
757
+ reader,
758
+ abortControllerRef,
759
+ update,
760
+ onFinish,
761
+ generateId: generateId2 = generateId,
762
+ getCurrentDate = () => /* @__PURE__ */ new Date()
763
+ }) {
764
+ const createdAt = getCurrentDate();
765
+ const prefixMap = {
766
+ data: []
767
+ };
768
+ let message_annotations = void 0;
769
+ for await (const { type, value } of readDataStream(reader, {
770
+ isAborted: () => (abortControllerRef == null ? void 0 : abortControllerRef.current) === null
771
+ })) {
772
+ if (type === "text") {
773
+ if (prefixMap["text"]) {
774
+ prefixMap["text"] = {
775
+ ...prefixMap["text"],
776
+ content: (prefixMap["text"].content || "") + value
777
+ };
778
+ } else {
779
+ prefixMap["text"] = {
780
+ id: generateId2(),
781
+ role: "assistant",
782
+ content: value,
783
+ createdAt
784
+ };
785
+ }
786
+ }
787
+ let functionCallMessage = null;
788
+ if (type === "function_call") {
789
+ prefixMap["function_call"] = {
790
+ id: generateId2(),
791
+ role: "assistant",
792
+ content: "",
793
+ function_call: value.function_call,
794
+ name: value.function_call.name,
795
+ createdAt
796
+ };
797
+ functionCallMessage = prefixMap["function_call"];
798
+ }
799
+ let toolCallMessage = null;
800
+ if (type === "tool_calls") {
801
+ prefixMap["tool_calls"] = {
802
+ id: generateId2(),
803
+ role: "assistant",
804
+ content: "",
805
+ tool_calls: value.tool_calls,
806
+ createdAt
807
+ };
808
+ toolCallMessage = prefixMap["tool_calls"];
809
+ }
810
+ if (type === "data") {
811
+ prefixMap["data"].push(...value);
812
+ }
813
+ let responseMessage = prefixMap["text"];
814
+ if (type === "message_annotations") {
815
+ if (!message_annotations) {
816
+ message_annotations = [...value];
817
+ } else {
818
+ message_annotations.push(...value);
819
+ }
820
+ functionCallMessage = assignAnnotationsToMessage(
821
+ prefixMap["function_call"],
822
+ message_annotations
823
+ );
824
+ toolCallMessage = assignAnnotationsToMessage(
825
+ prefixMap["tool_calls"],
826
+ message_annotations
827
+ );
828
+ responseMessage = assignAnnotationsToMessage(
829
+ prefixMap["text"],
830
+ message_annotations
831
+ );
832
+ }
833
+ if (message_annotations == null ? void 0 : message_annotations.length) {
834
+ const messagePrefixKeys = [
835
+ "text",
836
+ "function_call",
837
+ "tool_calls"
838
+ ];
839
+ messagePrefixKeys.forEach((key) => {
840
+ if (prefixMap[key]) {
841
+ prefixMap[key].annotations = [...message_annotations];
842
+ }
843
+ });
844
+ }
845
+ const merged = [functionCallMessage, toolCallMessage, responseMessage].filter(Boolean).map((message) => ({
846
+ ...assignAnnotationsToMessage(message, message_annotations)
847
+ }));
848
+ update(merged, [...prefixMap["data"]]);
849
+ }
850
+ onFinish == null ? void 0 : onFinish(prefixMap);
851
+ return {
852
+ messages: [
853
+ prefixMap.text,
854
+ prefixMap.function_call,
855
+ prefixMap.tool_calls
856
+ ].filter(Boolean),
857
+ data: prefixMap.data
858
+ };
859
+ }
860
+
861
+ // shared/utils.ts
862
+ function createChunkDecoder(complex) {
863
+ const decoder = new TextDecoder();
864
+ if (!complex) {
865
+ return function(chunk) {
866
+ if (!chunk)
867
+ return "";
868
+ return decoder.decode(chunk, { stream: true });
869
+ };
870
+ }
871
+ return function(chunk) {
872
+ const decoded = decoder.decode(chunk, { stream: true }).split("\n").filter((line) => line !== "");
873
+ return decoded.map(parseStreamPart).filter(Boolean);
874
+ };
875
+ }
876
+
877
+ // shared/call-chat-api.ts
878
+ async function callChatApi({
879
+ api,
880
+ messages,
881
+ body,
882
+ streamMode = "stream-data",
883
+ credentials,
884
+ headers,
885
+ abortController,
886
+ restoreMessagesOnFailure,
887
+ onResponse,
888
+ onUpdate,
889
+ onFinish,
890
+ generateId: generateId2
891
+ }) {
892
+ var _a;
893
+ const response = await fetch(api, {
894
+ method: "POST",
895
+ body: JSON.stringify({
896
+ messages,
897
+ ...body
898
+ }),
899
+ headers: {
900
+ "Content-Type": "application/json",
901
+ ...headers
902
+ },
903
+ signal: (_a = abortController == null ? void 0 : abortController()) == null ? void 0 : _a.signal,
904
+ credentials
905
+ }).catch((err) => {
906
+ restoreMessagesOnFailure();
907
+ throw err;
908
+ });
909
+ if (onResponse) {
910
+ try {
911
+ await onResponse(response);
912
+ } catch (err) {
913
+ throw err;
914
+ }
915
+ }
916
+ if (!response.ok) {
917
+ restoreMessagesOnFailure();
918
+ throw new Error(
919
+ await response.text() || "Failed to fetch the chat response."
920
+ );
921
+ }
922
+ if (!response.body) {
923
+ throw new Error("The response body is empty.");
924
+ }
925
+ const reader = response.body.getReader();
926
+ switch (streamMode) {
927
+ case "text": {
928
+ const decoder = createChunkDecoder();
929
+ const resultMessage = {
930
+ id: generateId2(),
931
+ createdAt: /* @__PURE__ */ new Date(),
932
+ role: "assistant",
933
+ content: ""
934
+ };
935
+ while (true) {
936
+ const { done, value } = await reader.read();
937
+ if (done) {
938
+ break;
939
+ }
940
+ resultMessage.content += decoder(value);
941
+ resultMessage.id = generateId2();
942
+ onUpdate([{ ...resultMessage }], []);
943
+ if ((abortController == null ? void 0 : abortController()) === null) {
944
+ reader.cancel();
945
+ break;
946
+ }
947
+ }
948
+ onFinish == null ? void 0 : onFinish(resultMessage);
949
+ return {
950
+ messages: [resultMessage],
951
+ data: []
952
+ };
953
+ }
954
+ case "stream-data": {
955
+ return await parseComplexResponse({
956
+ reader,
957
+ abortControllerRef: abortController != null ? { current: abortController() } : void 0,
958
+ update: onUpdate,
959
+ onFinish(prefixMap) {
960
+ if (onFinish && prefixMap.text != null) {
961
+ onFinish(prefixMap.text);
962
+ }
963
+ },
964
+ generateId: generateId2
965
+ });
966
+ }
967
+ default: {
968
+ const exhaustiveCheck = streamMode;
969
+ throw new Error(`Unknown stream mode: ${exhaustiveCheck}`);
970
+ }
971
+ }
972
+ }
973
+
974
+ // shared/process-chat-stream.ts
975
+ async function processChatStream({
976
+ getStreamedResponse: getStreamedResponse2,
977
+ experimental_onFunctionCall,
978
+ experimental_onToolCall,
979
+ updateChatRequest,
980
+ getCurrentMessages
981
+ }) {
982
+ while (true) {
983
+ const messagesAndDataOrJustMessage = await getStreamedResponse2();
984
+ if ("messages" in messagesAndDataOrJustMessage) {
985
+ let hasFollowingResponse = false;
986
+ for (const message of messagesAndDataOrJustMessage.messages) {
987
+ if ((message.function_call === void 0 || typeof message.function_call === "string") && (message.tool_calls === void 0 || typeof message.tool_calls === "string")) {
988
+ continue;
989
+ }
990
+ hasFollowingResponse = true;
991
+ if (experimental_onFunctionCall) {
992
+ const functionCall = message.function_call;
993
+ if (typeof functionCall !== "object") {
994
+ console.warn(
995
+ "experimental_onFunctionCall should not be defined when using tools"
996
+ );
997
+ continue;
998
+ }
999
+ const functionCallResponse = await experimental_onFunctionCall(
1000
+ getCurrentMessages(),
1001
+ functionCall
1002
+ );
1003
+ if (functionCallResponse === void 0) {
1004
+ hasFollowingResponse = false;
1005
+ break;
1006
+ }
1007
+ updateChatRequest(functionCallResponse);
1008
+ }
1009
+ if (experimental_onToolCall) {
1010
+ const toolCalls = message.tool_calls;
1011
+ if (!Array.isArray(toolCalls) || toolCalls.some((toolCall) => typeof toolCall !== "object")) {
1012
+ console.warn(
1013
+ "experimental_onToolCall should not be defined when using tools"
1014
+ );
1015
+ continue;
1016
+ }
1017
+ const toolCallResponse = await experimental_onToolCall(getCurrentMessages(), toolCalls);
1018
+ if (toolCallResponse === void 0) {
1019
+ hasFollowingResponse = false;
1020
+ break;
1021
+ }
1022
+ updateChatRequest(toolCallResponse);
1023
+ }
1024
+ }
1025
+ if (!hasFollowingResponse) {
1026
+ break;
1027
+ }
1028
+ } else {
1029
+ let fixFunctionCallArguments2 = function(response) {
1030
+ for (const message of response.messages) {
1031
+ if (message.tool_calls !== void 0) {
1032
+ for (const toolCall of message.tool_calls) {
1033
+ if (typeof toolCall === "object") {
1034
+ if (toolCall.function.arguments && typeof toolCall.function.arguments !== "string") {
1035
+ toolCall.function.arguments = JSON.stringify(
1036
+ toolCall.function.arguments
1037
+ );
1038
+ }
1039
+ }
1040
+ }
1041
+ }
1042
+ if (message.function_call !== void 0) {
1043
+ if (typeof message.function_call === "object") {
1044
+ if (message.function_call.arguments && typeof message.function_call.arguments !== "string") {
1045
+ message.function_call.arguments = JSON.stringify(
1046
+ message.function_call.arguments
1047
+ );
1048
+ }
1049
+ }
1050
+ }
1051
+ }
1052
+ };
1053
+ var fixFunctionCallArguments = fixFunctionCallArguments2;
1054
+ const streamedResponseMessage = messagesAndDataOrJustMessage;
1055
+ if ((streamedResponseMessage.function_call === void 0 || typeof streamedResponseMessage.function_call === "string") && (streamedResponseMessage.tool_calls === void 0 || typeof streamedResponseMessage.tool_calls === "string")) {
1056
+ break;
1057
+ }
1058
+ if (experimental_onFunctionCall) {
1059
+ const functionCall = streamedResponseMessage.function_call;
1060
+ if (!(typeof functionCall === "object")) {
1061
+ console.warn(
1062
+ "experimental_onFunctionCall should not be defined when using tools"
1063
+ );
1064
+ continue;
1065
+ }
1066
+ const functionCallResponse = await experimental_onFunctionCall(getCurrentMessages(), functionCall);
1067
+ if (functionCallResponse === void 0)
1068
+ break;
1069
+ fixFunctionCallArguments2(functionCallResponse);
1070
+ updateChatRequest(functionCallResponse);
1071
+ }
1072
+ if (experimental_onToolCall) {
1073
+ const toolCalls = streamedResponseMessage.tool_calls;
1074
+ if (!(typeof toolCalls === "object")) {
1075
+ console.warn(
1076
+ "experimental_onToolCall should not be defined when using functions"
1077
+ );
1078
+ continue;
1079
+ }
1080
+ const toolCallResponse = await experimental_onToolCall(getCurrentMessages(), toolCalls);
1081
+ if (toolCallResponse === void 0)
1082
+ break;
1083
+ fixFunctionCallArguments2(toolCallResponse);
1084
+ updateChatRequest(toolCallResponse);
1085
+ }
1086
+ }
1087
+ }
1088
+ }
1089
+
1090
+ // svelte/use-chat.ts
1091
+ var getStreamedResponse = async (api, chatRequest, mutate, mutateStreamData, existingData, extraMetadata, previousMessages, abortControllerRef, generateId2, streamMode, onFinish, onResponse, sendExtraMessageFields) => {
1092
+ var _a, _b;
1093
+ mutate(chatRequest.messages);
1094
+ const constructedMessagesPayload = sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(
1095
+ ({ role, content, name, function_call, tool_calls, tool_call_id }) => ({
1096
+ role,
1097
+ content,
1098
+ tool_call_id,
1099
+ ...name !== void 0 && { name },
1100
+ ...function_call !== void 0 && {
1101
+ function_call
1102
+ },
1103
+ ...tool_calls !== void 0 && {
1104
+ tool_calls
1105
+ }
1106
+ })
1107
+ );
1108
+ return await callChatApi({
1109
+ api,
1110
+ messages: constructedMessagesPayload,
1111
+ body: {
1112
+ ...extraMetadata.body,
1113
+ ...(_a = chatRequest.options) == null ? void 0 : _a.body,
1114
+ ...chatRequest.functions !== void 0 && {
1115
+ functions: chatRequest.functions
1116
+ },
1117
+ ...chatRequest.function_call !== void 0 && {
1118
+ function_call: chatRequest.function_call
1119
+ },
1120
+ ...chatRequest.tools !== void 0 && {
1121
+ tools: chatRequest.tools
1122
+ },
1123
+ ...chatRequest.tool_choice !== void 0 && {
1124
+ tool_choice: chatRequest.tool_choice
1125
+ }
1126
+ },
1127
+ streamMode,
1128
+ credentials: extraMetadata.credentials,
1129
+ headers: {
1130
+ ...extraMetadata.headers,
1131
+ ...(_b = chatRequest.options) == null ? void 0 : _b.headers
1132
+ },
1133
+ abortController: () => abortControllerRef,
1134
+ restoreMessagesOnFailure() {
1135
+ mutate(previousMessages);
1136
+ },
1137
+ onResponse,
1138
+ onUpdate(merged, data) {
1139
+ mutate([...chatRequest.messages, ...merged]);
1140
+ mutateStreamData([...existingData || [], ...data || []]);
1141
+ },
1142
+ onFinish,
1143
+ generateId: generateId2
1144
+ });
1145
+ };
1146
+ var uniqueId = 0;
1147
+ var store = {};
1148
+ function useChat({
1149
+ api = "/api/chat",
1150
+ id,
1151
+ initialMessages = [],
1152
+ initialInput = "",
1153
+ sendExtraMessageFields,
1154
+ experimental_onFunctionCall,
1155
+ experimental_onToolCall,
1156
+ streamMode,
1157
+ onResponse,
1158
+ onFinish,
1159
+ onError,
1160
+ credentials,
1161
+ headers,
1162
+ body,
1163
+ generateId: generateId2 = generateId
1164
+ } = {}) {
1165
+ const chatId = id || `chat-${uniqueId++}`;
1166
+ const key = `${api}|${chatId}`;
1167
+ const {
1168
+ data,
1169
+ mutate: originalMutate,
1170
+ isLoading: isSWRLoading
1171
+ } = F2(key, {
1172
+ fetcher: () => store[key] || initialMessages,
1173
+ fallbackData: initialMessages
1174
+ });
1175
+ const streamData = (0, import_store.writable)(void 0);
1176
+ const loading = (0, import_store.writable)(false);
1177
+ data.set(initialMessages);
1178
+ const mutate = (data2) => {
1179
+ store[key] = data2;
1180
+ return originalMutate(data2);
1181
+ };
1182
+ const messages = data;
1183
+ let abortController = null;
1184
+ const extraMetadata = {
1185
+ credentials,
1186
+ headers,
1187
+ body
1188
+ };
1189
+ const error = (0, import_store.writable)(void 0);
1190
+ async function triggerRequest(chatRequest) {
1191
+ try {
1192
+ error.set(void 0);
1193
+ loading.set(true);
1194
+ abortController = new AbortController();
1195
+ await processChatStream({
1196
+ getStreamedResponse: () => getStreamedResponse(
1197
+ api,
1198
+ chatRequest,
1199
+ mutate,
1200
+ (data2) => {
1201
+ streamData.set(data2);
1202
+ },
1203
+ (0, import_store.get)(streamData),
1204
+ extraMetadata,
1205
+ (0, import_store.get)(messages),
1206
+ abortController,
1207
+ generateId2,
1208
+ streamMode,
1209
+ onFinish,
1210
+ onResponse,
1211
+ sendExtraMessageFields
1212
+ ),
1213
+ experimental_onFunctionCall,
1214
+ experimental_onToolCall,
1215
+ updateChatRequest: (chatRequestParam) => {
1216
+ chatRequest = chatRequestParam;
1217
+ },
1218
+ getCurrentMessages: () => (0, import_store.get)(messages)
1219
+ });
1220
+ abortController = null;
1221
+ return null;
1222
+ } catch (err) {
1223
+ if (err.name === "AbortError") {
1224
+ abortController = null;
1225
+ return null;
1226
+ }
1227
+ if (onError && err instanceof Error) {
1228
+ onError(err);
1229
+ }
1230
+ error.set(err);
1231
+ } finally {
1232
+ loading.set(false);
1233
+ }
1234
+ }
1235
+ const append = async (message, {
1236
+ options,
1237
+ functions,
1238
+ function_call,
1239
+ tools,
1240
+ tool_choice
1241
+ } = {}) => {
1242
+ if (!message.id) {
1243
+ message.id = generateId2();
1244
+ }
1245
+ const chatRequest = {
1246
+ messages: (0, import_store.get)(messages).concat(message),
1247
+ options,
1248
+ ...functions !== void 0 && { functions },
1249
+ ...function_call !== void 0 && { function_call },
1250
+ ...tools !== void 0 && { tools },
1251
+ ...tool_choice !== void 0 && { tool_choice }
1252
+ };
1253
+ return triggerRequest(chatRequest);
1254
+ };
1255
+ const reload = async ({
1256
+ options,
1257
+ functions,
1258
+ function_call,
1259
+ tools,
1260
+ tool_choice
1261
+ } = {}) => {
1262
+ const messagesSnapshot = (0, import_store.get)(messages);
1263
+ if (messagesSnapshot.length === 0)
1264
+ return null;
1265
+ const lastMessage = messagesSnapshot.at(-1);
1266
+ if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant") {
1267
+ const chatRequest2 = {
1268
+ messages: messagesSnapshot.slice(0, -1),
1269
+ options,
1270
+ ...functions !== void 0 && { functions },
1271
+ ...function_call !== void 0 && { function_call },
1272
+ ...tools !== void 0 && { tools },
1273
+ ...tool_choice !== void 0 && { tool_choice }
1274
+ };
1275
+ return triggerRequest(chatRequest2);
1276
+ }
1277
+ const chatRequest = {
1278
+ messages: messagesSnapshot,
1279
+ options,
1280
+ ...functions !== void 0 && { functions },
1281
+ ...function_call !== void 0 && { function_call },
1282
+ ...tools !== void 0 && { tools },
1283
+ ...tool_choice !== void 0 && { tool_choice }
1284
+ };
1285
+ return triggerRequest(chatRequest);
1286
+ };
1287
+ const stop = () => {
1288
+ if (abortController) {
1289
+ abortController.abort();
1290
+ abortController = null;
1291
+ }
1292
+ };
1293
+ const setMessages = (messages2) => {
1294
+ mutate(messages2);
1295
+ };
1296
+ const input = (0, import_store.writable)(initialInput);
1297
+ const handleSubmit = (e, options = {}) => {
1298
+ e.preventDefault();
1299
+ const inputValue = (0, import_store.get)(input);
1300
+ if (!inputValue)
1301
+ return;
1302
+ append(
1303
+ {
1304
+ content: inputValue,
1305
+ role: "user",
1306
+ createdAt: /* @__PURE__ */ new Date()
1307
+ },
1308
+ options
1309
+ );
1310
+ input.set("");
1311
+ };
1312
+ const isLoading = (0, import_store.derived)(
1313
+ [isSWRLoading, loading],
1314
+ ([$isSWRLoading, $loading]) => {
1315
+ return $isSWRLoading || $loading;
1316
+ }
1317
+ );
1318
+ return {
1319
+ messages,
1320
+ error,
1321
+ append,
1322
+ reload,
1323
+ stop,
1324
+ setMessages,
1325
+ input,
1326
+ handleSubmit,
1327
+ isLoading,
1328
+ data: streamData
1329
+ };
1330
+ }
1331
+
1332
+ // svelte/use-completion.ts
1333
+ var import_store2 = require("svelte/store");
1334
+
1335
+ // shared/call-completion-api.ts
1336
+ async function callCompletionApi({
1337
+ api,
1338
+ prompt,
1339
+ credentials,
1340
+ headers,
1341
+ body,
1342
+ streamMode = "stream-data",
1343
+ setCompletion,
1344
+ setLoading,
1345
+ setError,
1346
+ setAbortController,
1347
+ onResponse,
1348
+ onFinish,
1349
+ onError,
1350
+ onData
1351
+ }) {
1352
+ try {
1353
+ setLoading(true);
1354
+ setError(void 0);
1355
+ const abortController = new AbortController();
1356
+ setAbortController(abortController);
1357
+ setCompletion("");
1358
+ const res = await fetch(api, {
1359
+ method: "POST",
1360
+ body: JSON.stringify({
1361
+ prompt,
1362
+ ...body
1363
+ }),
1364
+ credentials,
1365
+ headers: {
1366
+ "Content-Type": "application/json",
1367
+ ...headers
1368
+ },
1369
+ signal: abortController.signal
1370
+ }).catch((err) => {
1371
+ throw err;
1372
+ });
1373
+ if (onResponse) {
1374
+ try {
1375
+ await onResponse(res);
1376
+ } catch (err) {
1377
+ throw err;
1378
+ }
1379
+ }
1380
+ if (!res.ok) {
1381
+ throw new Error(
1382
+ await res.text() || "Failed to fetch the chat response."
1383
+ );
1384
+ }
1385
+ if (!res.body) {
1386
+ throw new Error("The response body is empty.");
1387
+ }
1388
+ let result = "";
1389
+ const reader = res.body.getReader();
1390
+ switch (streamMode) {
1391
+ case "text": {
1392
+ const decoder = createChunkDecoder();
1393
+ while (true) {
1394
+ const { done, value } = await reader.read();
1395
+ if (done) {
1396
+ break;
1397
+ }
1398
+ result += decoder(value);
1399
+ setCompletion(result);
1400
+ if (abortController === null) {
1401
+ reader.cancel();
1402
+ break;
1403
+ }
1404
+ }
1405
+ break;
1406
+ }
1407
+ case "stream-data": {
1408
+ for await (const { type, value } of readDataStream(reader, {
1409
+ isAborted: () => abortController === null
1410
+ })) {
1411
+ switch (type) {
1412
+ case "text": {
1413
+ result += value;
1414
+ setCompletion(result);
1415
+ break;
1416
+ }
1417
+ case "data": {
1418
+ onData == null ? void 0 : onData(value);
1419
+ break;
1420
+ }
1421
+ }
1422
+ }
1423
+ break;
1424
+ }
1425
+ default: {
1426
+ const exhaustiveCheck = streamMode;
1427
+ throw new Error(`Unknown stream mode: ${exhaustiveCheck}`);
1428
+ }
1429
+ }
1430
+ if (onFinish) {
1431
+ onFinish(prompt, result);
1432
+ }
1433
+ setAbortController(null);
1434
+ return result;
1435
+ } catch (err) {
1436
+ if (err.name === "AbortError") {
1437
+ setAbortController(null);
1438
+ return null;
1439
+ }
1440
+ if (err instanceof Error) {
1441
+ if (onError) {
1442
+ onError(err);
1443
+ }
1444
+ }
1445
+ setError(err);
1446
+ } finally {
1447
+ setLoading(false);
1448
+ }
1449
+ }
1450
+
1451
+ // svelte/use-completion.ts
1452
+ var uniqueId2 = 0;
1453
+ var store2 = {};
1454
+ function useCompletion({
1455
+ api = "/api/completion",
1456
+ id,
1457
+ initialCompletion = "",
1458
+ initialInput = "",
1459
+ credentials,
1460
+ headers,
1461
+ body,
1462
+ streamMode,
1463
+ onResponse,
1464
+ onFinish,
1465
+ onError
1466
+ } = {}) {
1467
+ const completionId = id || `completion-${uniqueId2++}`;
1468
+ const key = `${api}|${completionId}`;
1469
+ const {
1470
+ data,
1471
+ mutate: originalMutate,
1472
+ isLoading: isSWRLoading
1473
+ } = F2(key, {
1474
+ fetcher: () => store2[key] || initialCompletion,
1475
+ fallbackData: initialCompletion
1476
+ });
1477
+ const streamData = (0, import_store2.writable)(void 0);
1478
+ const loading = (0, import_store2.writable)(false);
1479
+ data.set(initialCompletion);
1480
+ const mutate = (data2) => {
1481
+ store2[key] = data2;
1482
+ return originalMutate(data2);
1483
+ };
1484
+ const completion = data;
1485
+ const error = (0, import_store2.writable)(void 0);
1486
+ let abortController = null;
1487
+ const complete = async (prompt, options) => {
1488
+ const existingData = (0, import_store2.get)(streamData);
1489
+ return callCompletionApi({
1490
+ api,
1491
+ prompt,
1492
+ credentials,
1493
+ headers: {
1494
+ ...headers,
1495
+ ...options == null ? void 0 : options.headers
1496
+ },
1497
+ body: {
1498
+ ...body,
1499
+ ...options == null ? void 0 : options.body
1500
+ },
1501
+ streamMode,
1502
+ setCompletion: mutate,
1503
+ setLoading: (loadingState) => loading.set(loadingState),
1504
+ setError: (err) => error.set(err),
1505
+ setAbortController: (controller) => {
1506
+ abortController = controller;
1507
+ },
1508
+ onResponse,
1509
+ onFinish,
1510
+ onError,
1511
+ onData(data2) {
1512
+ streamData.set([...existingData || [], ...data2 || []]);
1513
+ }
1514
+ });
1515
+ };
1516
+ const stop = () => {
1517
+ if (abortController) {
1518
+ abortController.abort();
1519
+ abortController = null;
1520
+ }
1521
+ };
1522
+ const setCompletion = (completion2) => {
1523
+ mutate(completion2);
1524
+ };
1525
+ const input = (0, import_store2.writable)(initialInput);
1526
+ const handleSubmit = (e) => {
1527
+ e.preventDefault();
1528
+ const inputValue = (0, import_store2.get)(input);
1529
+ if (!inputValue)
1530
+ return;
1531
+ return complete(inputValue);
1532
+ };
1533
+ const isLoading = (0, import_store2.derived)(
1534
+ [isSWRLoading, loading],
1535
+ ([$isSWRLoading, $loading]) => {
1536
+ return $isSWRLoading || $loading;
1537
+ }
1538
+ );
1539
+ return {
1540
+ completion,
1541
+ complete,
1542
+ error,
1543
+ stop,
1544
+ setCompletion,
1545
+ input,
1546
+ handleSubmit,
1547
+ isLoading,
1548
+ data: streamData
1549
+ };
1550
+ }
1551
+ // Annotate the CommonJS export names for ESM import in node:
1552
+ 0 && (module.exports = {
1553
+ useChat,
1554
+ useCompletion
1555
+ });
1556
+ //# sourceMappingURL=index.js.map