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