ai 0.0.0-85f9a635-20240518005312 → 0.0.0-8777c42a-20250115032312

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 (58) hide show
  1. package/CHANGELOG.md +2863 -0
  2. package/README.md +99 -22
  3. package/dist/index.d.mts +1925 -1592
  4. package/dist/index.d.ts +1925 -1592
  5. package/dist/index.js +5500 -2961
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +5497 -2916
  8. package/dist/index.mjs.map +1 -1
  9. package/package.json +39 -100
  10. package/react/dist/index.d.mts +8 -563
  11. package/react/dist/index.d.ts +8 -580
  12. package/react/dist/index.js +7 -1395
  13. package/react/dist/index.js.map +1 -1
  14. package/react/dist/index.mjs +12 -1383
  15. package/react/dist/index.mjs.map +1 -1
  16. package/rsc/dist/index.d.ts +340 -197
  17. package/rsc/dist/rsc-server.d.mts +339 -197
  18. package/rsc/dist/rsc-server.mjs +1295 -1347
  19. package/rsc/dist/rsc-server.mjs.map +1 -1
  20. package/rsc/dist/rsc-shared.d.mts +30 -23
  21. package/rsc/dist/rsc-shared.mjs +69 -105
  22. package/rsc/dist/rsc-shared.mjs.map +1 -1
  23. package/test/dist/index.d.mts +67 -0
  24. package/test/dist/index.d.ts +67 -0
  25. package/test/dist/index.js +131 -0
  26. package/test/dist/index.js.map +1 -0
  27. package/test/dist/index.mjs +101 -0
  28. package/test/dist/index.mjs.map +1 -0
  29. package/prompts/dist/index.d.mts +0 -324
  30. package/prompts/dist/index.d.ts +0 -324
  31. package/prompts/dist/index.js +0 -178
  32. package/prompts/dist/index.js.map +0 -1
  33. package/prompts/dist/index.mjs +0 -146
  34. package/prompts/dist/index.mjs.map +0 -1
  35. package/react/dist/index.server.d.mts +0 -17
  36. package/react/dist/index.server.d.ts +0 -17
  37. package/react/dist/index.server.js +0 -50
  38. package/react/dist/index.server.js.map +0 -1
  39. package/react/dist/index.server.mjs +0 -23
  40. package/react/dist/index.server.mjs.map +0 -1
  41. package/solid/dist/index.d.mts +0 -408
  42. package/solid/dist/index.d.ts +0 -408
  43. package/solid/dist/index.js +0 -1072
  44. package/solid/dist/index.js.map +0 -1
  45. package/solid/dist/index.mjs +0 -1044
  46. package/solid/dist/index.mjs.map +0 -1
  47. package/svelte/dist/index.d.mts +0 -484
  48. package/svelte/dist/index.d.ts +0 -484
  49. package/svelte/dist/index.js +0 -1778
  50. package/svelte/dist/index.js.map +0 -1
  51. package/svelte/dist/index.mjs +0 -1749
  52. package/svelte/dist/index.mjs.map +0 -1
  53. package/vue/dist/index.d.mts +0 -402
  54. package/vue/dist/index.d.ts +0 -402
  55. package/vue/dist/index.js +0 -1072
  56. package/vue/dist/index.js.map +0 -1
  57. package/vue/dist/index.mjs +0 -1034
  58. package/vue/dist/index.mjs.map +0 -1
@@ -1,1749 +0,0 @@
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/generate-id.ts
502
- import { customAlphabet } from "nanoid/non-secure";
503
- var generateId = customAlphabet(
504
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
505
- 7
506
- );
507
-
508
- // shared/stream-parts.ts
509
- var textStreamPart = {
510
- code: "0",
511
- name: "text",
512
- parse: (value) => {
513
- if (typeof value !== "string") {
514
- throw new Error('"text" parts expect a string value.');
515
- }
516
- return { type: "text", value };
517
- }
518
- };
519
- var functionCallStreamPart = {
520
- code: "1",
521
- name: "function_call",
522
- parse: (value) => {
523
- 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") {
524
- throw new Error(
525
- '"function_call" parts expect an object with a "function_call" property.'
526
- );
527
- }
528
- return {
529
- type: "function_call",
530
- value
531
- };
532
- }
533
- };
534
- var dataStreamPart = {
535
- code: "2",
536
- name: "data",
537
- parse: (value) => {
538
- if (!Array.isArray(value)) {
539
- throw new Error('"data" parts expect an array value.');
540
- }
541
- return { type: "data", value };
542
- }
543
- };
544
- var errorStreamPart = {
545
- code: "3",
546
- name: "error",
547
- parse: (value) => {
548
- if (typeof value !== "string") {
549
- throw new Error('"error" parts expect a string value.');
550
- }
551
- return { type: "error", value };
552
- }
553
- };
554
- var assistantMessageStreamPart = {
555
- code: "4",
556
- name: "assistant_message",
557
- parse: (value) => {
558
- 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(
559
- (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"
560
- )) {
561
- throw new Error(
562
- '"assistant_message" parts expect an object with an "id", "role", and "content" property.'
563
- );
564
- }
565
- return {
566
- type: "assistant_message",
567
- value
568
- };
569
- }
570
- };
571
- var assistantControlDataStreamPart = {
572
- code: "5",
573
- name: "assistant_control_data",
574
- parse: (value) => {
575
- if (value == null || typeof value !== "object" || !("threadId" in value) || !("messageId" in value) || typeof value.threadId !== "string" || typeof value.messageId !== "string") {
576
- throw new Error(
577
- '"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.'
578
- );
579
- }
580
- return {
581
- type: "assistant_control_data",
582
- value: {
583
- threadId: value.threadId,
584
- messageId: value.messageId
585
- }
586
- };
587
- }
588
- };
589
- var dataMessageStreamPart = {
590
- code: "6",
591
- name: "data_message",
592
- parse: (value) => {
593
- if (value == null || typeof value !== "object" || !("role" in value) || !("data" in value) || typeof value.role !== "string" || value.role !== "data") {
594
- throw new Error(
595
- '"data_message" parts expect an object with a "role" and "data" property.'
596
- );
597
- }
598
- return {
599
- type: "data_message",
600
- value
601
- };
602
- }
603
- };
604
- var toolCallsStreamPart = {
605
- code: "7",
606
- name: "tool_calls",
607
- parse: (value) => {
608
- 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(
609
- (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"
610
- )) {
611
- throw new Error(
612
- '"tool_calls" parts expect an object with a ToolCallPayload.'
613
- );
614
- }
615
- return {
616
- type: "tool_calls",
617
- value
618
- };
619
- }
620
- };
621
- var messageAnnotationsStreamPart = {
622
- code: "8",
623
- name: "message_annotations",
624
- parse: (value) => {
625
- if (!Array.isArray(value)) {
626
- throw new Error('"message_annotations" parts expect an array value.');
627
- }
628
- return { type: "message_annotations", value };
629
- }
630
- };
631
- var toolCallStreamPart = {
632
- code: "9",
633
- name: "tool_call",
634
- parse: (value) => {
635
- if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object") {
636
- throw new Error(
637
- '"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.'
638
- );
639
- }
640
- return {
641
- type: "tool_call",
642
- value
643
- };
644
- }
645
- };
646
- var toolResultStreamPart = {
647
- code: "a",
648
- name: "tool_result",
649
- parse: (value) => {
650
- if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object" || !("result" in value)) {
651
- throw new Error(
652
- '"tool_result" parts expect an object with a "toolCallId", "toolName", "args", and "result" property.'
653
- );
654
- }
655
- return {
656
- type: "tool_result",
657
- value
658
- };
659
- }
660
- };
661
- var streamParts = [
662
- textStreamPart,
663
- functionCallStreamPart,
664
- dataStreamPart,
665
- errorStreamPart,
666
- assistantMessageStreamPart,
667
- assistantControlDataStreamPart,
668
- dataMessageStreamPart,
669
- toolCallsStreamPart,
670
- messageAnnotationsStreamPart,
671
- toolCallStreamPart,
672
- toolResultStreamPart
673
- ];
674
- var streamPartsByCode = {
675
- [textStreamPart.code]: textStreamPart,
676
- [functionCallStreamPart.code]: functionCallStreamPart,
677
- [dataStreamPart.code]: dataStreamPart,
678
- [errorStreamPart.code]: errorStreamPart,
679
- [assistantMessageStreamPart.code]: assistantMessageStreamPart,
680
- [assistantControlDataStreamPart.code]: assistantControlDataStreamPart,
681
- [dataMessageStreamPart.code]: dataMessageStreamPart,
682
- [toolCallsStreamPart.code]: toolCallsStreamPart,
683
- [messageAnnotationsStreamPart.code]: messageAnnotationsStreamPart,
684
- [toolCallStreamPart.code]: toolCallStreamPart,
685
- [toolResultStreamPart.code]: toolResultStreamPart
686
- };
687
- var StreamStringPrefixes = {
688
- [textStreamPart.name]: textStreamPart.code,
689
- [functionCallStreamPart.name]: functionCallStreamPart.code,
690
- [dataStreamPart.name]: dataStreamPart.code,
691
- [errorStreamPart.name]: errorStreamPart.code,
692
- [assistantMessageStreamPart.name]: assistantMessageStreamPart.code,
693
- [assistantControlDataStreamPart.name]: assistantControlDataStreamPart.code,
694
- [dataMessageStreamPart.name]: dataMessageStreamPart.code,
695
- [toolCallsStreamPart.name]: toolCallsStreamPart.code,
696
- [messageAnnotationsStreamPart.name]: messageAnnotationsStreamPart.code,
697
- [toolCallStreamPart.name]: toolCallStreamPart.code,
698
- [toolResultStreamPart.name]: toolResultStreamPart.code
699
- };
700
- var validCodes = streamParts.map((part) => part.code);
701
- var parseStreamPart = (line) => {
702
- const firstSeparatorIndex = line.indexOf(":");
703
- if (firstSeparatorIndex === -1) {
704
- throw new Error("Failed to parse stream string. No separator found.");
705
- }
706
- const prefix = line.slice(0, firstSeparatorIndex);
707
- if (!validCodes.includes(prefix)) {
708
- throw new Error(`Failed to parse stream string. Invalid code ${prefix}.`);
709
- }
710
- const code = prefix;
711
- const textValue = line.slice(firstSeparatorIndex + 1);
712
- const jsonValue = JSON.parse(textValue);
713
- return streamPartsByCode[code].parse(jsonValue);
714
- };
715
-
716
- // shared/read-data-stream.ts
717
- var NEWLINE = "\n".charCodeAt(0);
718
- function concatChunks(chunks, totalLength) {
719
- const concatenatedChunks = new Uint8Array(totalLength);
720
- let offset = 0;
721
- for (const chunk of chunks) {
722
- concatenatedChunks.set(chunk, offset);
723
- offset += chunk.length;
724
- }
725
- chunks.length = 0;
726
- return concatenatedChunks;
727
- }
728
- async function* readDataStream(reader, {
729
- isAborted
730
- } = {}) {
731
- const decoder = new TextDecoder();
732
- const chunks = [];
733
- let totalLength = 0;
734
- while (true) {
735
- const { value } = await reader.read();
736
- if (value) {
737
- chunks.push(value);
738
- totalLength += value.length;
739
- if (value[value.length - 1] !== NEWLINE) {
740
- continue;
741
- }
742
- }
743
- if (chunks.length === 0) {
744
- break;
745
- }
746
- const concatenatedChunks = concatChunks(chunks, totalLength);
747
- totalLength = 0;
748
- const streamParts2 = decoder.decode(concatenatedChunks, { stream: true }).split("\n").filter((line) => line !== "").map(parseStreamPart);
749
- for (const streamPart of streamParts2) {
750
- yield streamPart;
751
- }
752
- if (isAborted == null ? void 0 : isAborted()) {
753
- reader.cancel();
754
- break;
755
- }
756
- }
757
- }
758
-
759
- // shared/parse-complex-response.ts
760
- function assignAnnotationsToMessage(message, annotations) {
761
- if (!message || !annotations || !annotations.length)
762
- return message;
763
- return { ...message, annotations: [...annotations] };
764
- }
765
- async function parseComplexResponse({
766
- reader,
767
- abortControllerRef,
768
- update,
769
- onFinish,
770
- generateId: generateId2 = generateId,
771
- getCurrentDate = () => /* @__PURE__ */ new Date()
772
- }) {
773
- const createdAt = getCurrentDate();
774
- const prefixMap = {
775
- data: []
776
- };
777
- let message_annotations = void 0;
778
- for await (const { type, value } of readDataStream(reader, {
779
- isAborted: () => (abortControllerRef == null ? void 0 : abortControllerRef.current) === null
780
- })) {
781
- if (type === "text") {
782
- if (prefixMap["text"]) {
783
- prefixMap["text"] = {
784
- ...prefixMap["text"],
785
- content: (prefixMap["text"].content || "") + value
786
- };
787
- } else {
788
- prefixMap["text"] = {
789
- id: generateId2(),
790
- role: "assistant",
791
- content: value,
792
- createdAt
793
- };
794
- }
795
- }
796
- if (type === "tool_call") {
797
- if (prefixMap.text == null) {
798
- prefixMap.text = {
799
- id: generateId2(),
800
- role: "assistant",
801
- content: "",
802
- createdAt
803
- };
804
- }
805
- if (prefixMap.text.toolInvocations == null) {
806
- prefixMap.text.toolInvocations = [];
807
- }
808
- prefixMap.text.toolInvocations.push(value);
809
- } else if (type === "tool_result") {
810
- if (prefixMap.text == null) {
811
- prefixMap.text = {
812
- id: generateId2(),
813
- role: "assistant",
814
- content: "",
815
- createdAt
816
- };
817
- }
818
- if (prefixMap.text.toolInvocations == null) {
819
- prefixMap.text.toolInvocations = [];
820
- }
821
- const toolInvocationIndex = prefixMap.text.toolInvocations.findIndex(
822
- (invocation) => invocation.toolCallId === value.toolCallId
823
- );
824
- if (toolInvocationIndex !== -1) {
825
- prefixMap.text.toolInvocations[toolInvocationIndex] = value;
826
- } else {
827
- prefixMap.text.toolInvocations.push(value);
828
- }
829
- }
830
- let functionCallMessage = null;
831
- if (type === "function_call") {
832
- prefixMap["function_call"] = {
833
- id: generateId2(),
834
- role: "assistant",
835
- content: "",
836
- function_call: value.function_call,
837
- name: value.function_call.name,
838
- createdAt
839
- };
840
- functionCallMessage = prefixMap["function_call"];
841
- }
842
- let toolCallMessage = null;
843
- if (type === "tool_calls") {
844
- prefixMap["tool_calls"] = {
845
- id: generateId2(),
846
- role: "assistant",
847
- content: "",
848
- tool_calls: value.tool_calls,
849
- createdAt
850
- };
851
- toolCallMessage = prefixMap["tool_calls"];
852
- }
853
- if (type === "data") {
854
- prefixMap["data"].push(...value);
855
- }
856
- let responseMessage = prefixMap["text"];
857
- if (type === "message_annotations") {
858
- if (!message_annotations) {
859
- message_annotations = [...value];
860
- } else {
861
- message_annotations.push(...value);
862
- }
863
- functionCallMessage = assignAnnotationsToMessage(
864
- prefixMap["function_call"],
865
- message_annotations
866
- );
867
- toolCallMessage = assignAnnotationsToMessage(
868
- prefixMap["tool_calls"],
869
- message_annotations
870
- );
871
- responseMessage = assignAnnotationsToMessage(
872
- prefixMap["text"],
873
- message_annotations
874
- );
875
- }
876
- if (message_annotations == null ? void 0 : message_annotations.length) {
877
- const messagePrefixKeys = [
878
- "text",
879
- "function_call",
880
- "tool_calls"
881
- ];
882
- messagePrefixKeys.forEach((key) => {
883
- if (prefixMap[key]) {
884
- prefixMap[key].annotations = [...message_annotations];
885
- }
886
- });
887
- }
888
- const merged = [functionCallMessage, toolCallMessage, responseMessage].filter(Boolean).map((message) => ({
889
- ...assignAnnotationsToMessage(message, message_annotations)
890
- }));
891
- update(merged, [...prefixMap["data"]]);
892
- }
893
- onFinish == null ? void 0 : onFinish(prefixMap);
894
- return {
895
- messages: [
896
- prefixMap.text,
897
- prefixMap.function_call,
898
- prefixMap.tool_calls
899
- ].filter(Boolean),
900
- data: prefixMap.data
901
- };
902
- }
903
-
904
- // shared/utils.ts
905
- function createChunkDecoder(complex) {
906
- const decoder = new TextDecoder();
907
- if (!complex) {
908
- return function(chunk) {
909
- if (!chunk)
910
- return "";
911
- return decoder.decode(chunk, { stream: true });
912
- };
913
- }
914
- return function(chunk) {
915
- const decoded = decoder.decode(chunk, { stream: true }).split("\n").filter((line) => line !== "");
916
- return decoded.map(parseStreamPart).filter(Boolean);
917
- };
918
- }
919
-
920
- // shared/call-chat-api.ts
921
- async function callChatApi({
922
- api,
923
- messages,
924
- body,
925
- streamMode = "stream-data",
926
- credentials,
927
- headers,
928
- abortController,
929
- restoreMessagesOnFailure,
930
- onResponse,
931
- onUpdate,
932
- onFinish,
933
- generateId: generateId2
934
- }) {
935
- var _a;
936
- const response = await fetch(api, {
937
- method: "POST",
938
- body: JSON.stringify({
939
- messages,
940
- ...body
941
- }),
942
- headers: {
943
- "Content-Type": "application/json",
944
- ...headers
945
- },
946
- signal: (_a = abortController == null ? void 0 : abortController()) == null ? void 0 : _a.signal,
947
- credentials
948
- }).catch((err) => {
949
- restoreMessagesOnFailure();
950
- throw err;
951
- });
952
- if (onResponse) {
953
- try {
954
- await onResponse(response);
955
- } catch (err) {
956
- throw err;
957
- }
958
- }
959
- if (!response.ok) {
960
- restoreMessagesOnFailure();
961
- throw new Error(
962
- await response.text() || "Failed to fetch the chat response."
963
- );
964
- }
965
- if (!response.body) {
966
- throw new Error("The response body is empty.");
967
- }
968
- const reader = response.body.getReader();
969
- switch (streamMode) {
970
- case "text": {
971
- const decoder = createChunkDecoder();
972
- const resultMessage = {
973
- id: generateId2(),
974
- createdAt: /* @__PURE__ */ new Date(),
975
- role: "assistant",
976
- content: ""
977
- };
978
- while (true) {
979
- const { done, value } = await reader.read();
980
- if (done) {
981
- break;
982
- }
983
- resultMessage.content += decoder(value);
984
- resultMessage.id = generateId2();
985
- onUpdate([{ ...resultMessage }], []);
986
- if ((abortController == null ? void 0 : abortController()) === null) {
987
- reader.cancel();
988
- break;
989
- }
990
- }
991
- onFinish == null ? void 0 : onFinish(resultMessage);
992
- return {
993
- messages: [resultMessage],
994
- data: []
995
- };
996
- }
997
- case "stream-data": {
998
- return await parseComplexResponse({
999
- reader,
1000
- abortControllerRef: abortController != null ? { current: abortController() } : void 0,
1001
- update: onUpdate,
1002
- onFinish(prefixMap) {
1003
- if (onFinish && prefixMap.text != null) {
1004
- onFinish(prefixMap.text);
1005
- }
1006
- },
1007
- generateId: generateId2
1008
- });
1009
- }
1010
- default: {
1011
- const exhaustiveCheck = streamMode;
1012
- throw new Error(`Unknown stream mode: ${exhaustiveCheck}`);
1013
- }
1014
- }
1015
- }
1016
-
1017
- // shared/process-chat-stream.ts
1018
- async function processChatStream({
1019
- getStreamedResponse: getStreamedResponse2,
1020
- experimental_onFunctionCall,
1021
- experimental_onToolCall,
1022
- updateChatRequest,
1023
- getCurrentMessages
1024
- }) {
1025
- while (true) {
1026
- const messagesAndDataOrJustMessage = await getStreamedResponse2();
1027
- if ("messages" in messagesAndDataOrJustMessage) {
1028
- let hasFollowingResponse = false;
1029
- for (const message of messagesAndDataOrJustMessage.messages) {
1030
- if ((message.function_call === void 0 || typeof message.function_call === "string") && (message.tool_calls === void 0 || typeof message.tool_calls === "string")) {
1031
- continue;
1032
- }
1033
- hasFollowingResponse = true;
1034
- if (experimental_onFunctionCall) {
1035
- const functionCall = message.function_call;
1036
- if (typeof functionCall !== "object") {
1037
- console.warn(
1038
- "experimental_onFunctionCall should not be defined when using tools"
1039
- );
1040
- continue;
1041
- }
1042
- const functionCallResponse = await experimental_onFunctionCall(
1043
- getCurrentMessages(),
1044
- functionCall
1045
- );
1046
- if (functionCallResponse === void 0) {
1047
- hasFollowingResponse = false;
1048
- break;
1049
- }
1050
- updateChatRequest(functionCallResponse);
1051
- }
1052
- if (experimental_onToolCall) {
1053
- const toolCalls = message.tool_calls;
1054
- if (!Array.isArray(toolCalls) || toolCalls.some((toolCall) => typeof toolCall !== "object")) {
1055
- console.warn(
1056
- "experimental_onToolCall should not be defined when using tools"
1057
- );
1058
- continue;
1059
- }
1060
- const toolCallResponse = await experimental_onToolCall(getCurrentMessages(), toolCalls);
1061
- if (toolCallResponse === void 0) {
1062
- hasFollowingResponse = false;
1063
- break;
1064
- }
1065
- updateChatRequest(toolCallResponse);
1066
- }
1067
- }
1068
- if (!hasFollowingResponse) {
1069
- break;
1070
- }
1071
- } else {
1072
- let fixFunctionCallArguments2 = function(response) {
1073
- for (const message of response.messages) {
1074
- if (message.tool_calls !== void 0) {
1075
- for (const toolCall of message.tool_calls) {
1076
- if (typeof toolCall === "object") {
1077
- if (toolCall.function.arguments && typeof toolCall.function.arguments !== "string") {
1078
- toolCall.function.arguments = JSON.stringify(
1079
- toolCall.function.arguments
1080
- );
1081
- }
1082
- }
1083
- }
1084
- }
1085
- if (message.function_call !== void 0) {
1086
- if (typeof message.function_call === "object") {
1087
- if (message.function_call.arguments && typeof message.function_call.arguments !== "string") {
1088
- message.function_call.arguments = JSON.stringify(
1089
- message.function_call.arguments
1090
- );
1091
- }
1092
- }
1093
- }
1094
- }
1095
- };
1096
- var fixFunctionCallArguments = fixFunctionCallArguments2;
1097
- const streamedResponseMessage = messagesAndDataOrJustMessage;
1098
- if ((streamedResponseMessage.function_call === void 0 || typeof streamedResponseMessage.function_call === "string") && (streamedResponseMessage.tool_calls === void 0 || typeof streamedResponseMessage.tool_calls === "string")) {
1099
- break;
1100
- }
1101
- if (experimental_onFunctionCall) {
1102
- const functionCall = streamedResponseMessage.function_call;
1103
- if (!(typeof functionCall === "object")) {
1104
- console.warn(
1105
- "experimental_onFunctionCall should not be defined when using tools"
1106
- );
1107
- continue;
1108
- }
1109
- const functionCallResponse = await experimental_onFunctionCall(getCurrentMessages(), functionCall);
1110
- if (functionCallResponse === void 0)
1111
- break;
1112
- fixFunctionCallArguments2(functionCallResponse);
1113
- updateChatRequest(functionCallResponse);
1114
- }
1115
- if (experimental_onToolCall) {
1116
- const toolCalls = streamedResponseMessage.tool_calls;
1117
- if (!(typeof toolCalls === "object")) {
1118
- console.warn(
1119
- "experimental_onToolCall should not be defined when using functions"
1120
- );
1121
- continue;
1122
- }
1123
- const toolCallResponse = await experimental_onToolCall(getCurrentMessages(), toolCalls);
1124
- if (toolCallResponse === void 0)
1125
- break;
1126
- fixFunctionCallArguments2(toolCallResponse);
1127
- updateChatRequest(toolCallResponse);
1128
- }
1129
- }
1130
- }
1131
- }
1132
-
1133
- // svelte/use-chat.ts
1134
- var getStreamedResponse = async (api, chatRequest, mutate, mutateStreamData, existingData, extraMetadata, previousMessages, abortControllerRef, generateId2, streamMode, onFinish, onResponse, sendExtraMessageFields) => {
1135
- var _a, _b;
1136
- mutate(chatRequest.messages);
1137
- const constructedMessagesPayload = sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(
1138
- ({ role, content, name, function_call, tool_calls, tool_call_id }) => ({
1139
- role,
1140
- content,
1141
- tool_call_id,
1142
- ...name !== void 0 && { name },
1143
- ...function_call !== void 0 && {
1144
- function_call
1145
- },
1146
- ...tool_calls !== void 0 && {
1147
- tool_calls
1148
- }
1149
- })
1150
- );
1151
- return await callChatApi({
1152
- api,
1153
- messages: constructedMessagesPayload,
1154
- body: {
1155
- ...extraMetadata.body,
1156
- ...(_a = chatRequest.options) == null ? void 0 : _a.body,
1157
- ...chatRequest.functions !== void 0 && {
1158
- functions: chatRequest.functions
1159
- },
1160
- ...chatRequest.function_call !== void 0 && {
1161
- function_call: chatRequest.function_call
1162
- },
1163
- ...chatRequest.tools !== void 0 && {
1164
- tools: chatRequest.tools
1165
- },
1166
- ...chatRequest.tool_choice !== void 0 && {
1167
- tool_choice: chatRequest.tool_choice
1168
- }
1169
- },
1170
- streamMode,
1171
- credentials: extraMetadata.credentials,
1172
- headers: {
1173
- ...extraMetadata.headers,
1174
- ...(_b = chatRequest.options) == null ? void 0 : _b.headers
1175
- },
1176
- abortController: () => abortControllerRef,
1177
- restoreMessagesOnFailure() {
1178
- mutate(previousMessages);
1179
- },
1180
- onResponse,
1181
- onUpdate(merged, data) {
1182
- mutate([...chatRequest.messages, ...merged]);
1183
- mutateStreamData([...existingData || [], ...data || []]);
1184
- },
1185
- onFinish,
1186
- generateId: generateId2
1187
- });
1188
- };
1189
- var uniqueId = 0;
1190
- var store = {};
1191
- function useChat({
1192
- api = "/api/chat",
1193
- id,
1194
- initialMessages = [],
1195
- initialInput = "",
1196
- sendExtraMessageFields,
1197
- experimental_onFunctionCall,
1198
- experimental_onToolCall,
1199
- streamMode,
1200
- onResponse,
1201
- onFinish,
1202
- onError,
1203
- credentials,
1204
- headers,
1205
- body,
1206
- generateId: generateId2 = generateId
1207
- } = {}) {
1208
- const chatId = id || `chat-${uniqueId++}`;
1209
- const key = `${api}|${chatId}`;
1210
- const {
1211
- data,
1212
- mutate: originalMutate,
1213
- isLoading: isSWRLoading
1214
- } = F2(key, {
1215
- fetcher: () => store[key] || initialMessages,
1216
- fallbackData: initialMessages
1217
- });
1218
- const streamData = writable(void 0);
1219
- const loading = writable(false);
1220
- data.set(initialMessages);
1221
- const mutate = (data2) => {
1222
- store[key] = data2;
1223
- return originalMutate(data2);
1224
- };
1225
- const messages = data;
1226
- let abortController = null;
1227
- const extraMetadata = {
1228
- credentials,
1229
- headers,
1230
- body
1231
- };
1232
- const error = writable(void 0);
1233
- async function triggerRequest(chatRequest) {
1234
- try {
1235
- error.set(void 0);
1236
- loading.set(true);
1237
- abortController = new AbortController();
1238
- await processChatStream({
1239
- getStreamedResponse: () => getStreamedResponse(
1240
- api,
1241
- chatRequest,
1242
- mutate,
1243
- (data2) => {
1244
- streamData.set(data2);
1245
- },
1246
- get(streamData),
1247
- extraMetadata,
1248
- get(messages),
1249
- abortController,
1250
- generateId2,
1251
- streamMode,
1252
- onFinish,
1253
- onResponse,
1254
- sendExtraMessageFields
1255
- ),
1256
- experimental_onFunctionCall,
1257
- experimental_onToolCall,
1258
- updateChatRequest: (chatRequestParam) => {
1259
- chatRequest = chatRequestParam;
1260
- },
1261
- getCurrentMessages: () => get(messages)
1262
- });
1263
- abortController = null;
1264
- return null;
1265
- } catch (err) {
1266
- if (err.name === "AbortError") {
1267
- abortController = null;
1268
- return null;
1269
- }
1270
- if (onError && err instanceof Error) {
1271
- onError(err);
1272
- }
1273
- error.set(err);
1274
- } finally {
1275
- loading.set(false);
1276
- }
1277
- }
1278
- const append = async (message, {
1279
- options,
1280
- functions,
1281
- function_call,
1282
- tools,
1283
- tool_choice
1284
- } = {}) => {
1285
- if (!message.id) {
1286
- message.id = generateId2();
1287
- }
1288
- const chatRequest = {
1289
- messages: get(messages).concat(message),
1290
- options,
1291
- ...functions !== void 0 && { functions },
1292
- ...function_call !== void 0 && { function_call },
1293
- ...tools !== void 0 && { tools },
1294
- ...tool_choice !== void 0 && { tool_choice }
1295
- };
1296
- return triggerRequest(chatRequest);
1297
- };
1298
- const reload = async ({
1299
- options,
1300
- functions,
1301
- function_call,
1302
- tools,
1303
- tool_choice
1304
- } = {}) => {
1305
- const messagesSnapshot = get(messages);
1306
- if (messagesSnapshot.length === 0)
1307
- return null;
1308
- const lastMessage = messagesSnapshot.at(-1);
1309
- if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant") {
1310
- const chatRequest2 = {
1311
- messages: messagesSnapshot.slice(0, -1),
1312
- options,
1313
- ...functions !== void 0 && { functions },
1314
- ...function_call !== void 0 && { function_call },
1315
- ...tools !== void 0 && { tools },
1316
- ...tool_choice !== void 0 && { tool_choice }
1317
- };
1318
- return triggerRequest(chatRequest2);
1319
- }
1320
- const chatRequest = {
1321
- messages: messagesSnapshot,
1322
- options,
1323
- ...functions !== void 0 && { functions },
1324
- ...function_call !== void 0 && { function_call },
1325
- ...tools !== void 0 && { tools },
1326
- ...tool_choice !== void 0 && { tool_choice }
1327
- };
1328
- return triggerRequest(chatRequest);
1329
- };
1330
- const stop = () => {
1331
- if (abortController) {
1332
- abortController.abort();
1333
- abortController = null;
1334
- }
1335
- };
1336
- const setMessages = (messages2) => {
1337
- mutate(messages2);
1338
- };
1339
- const input = writable(initialInput);
1340
- const handleSubmit = (e, options = {}) => {
1341
- e.preventDefault();
1342
- const inputValue = get(input);
1343
- if (!inputValue)
1344
- return;
1345
- append(
1346
- {
1347
- content: inputValue,
1348
- role: "user",
1349
- createdAt: /* @__PURE__ */ new Date()
1350
- },
1351
- options
1352
- );
1353
- input.set("");
1354
- };
1355
- const isLoading = derived(
1356
- [isSWRLoading, loading],
1357
- ([$isSWRLoading, $loading]) => {
1358
- return $isSWRLoading || $loading;
1359
- }
1360
- );
1361
- return {
1362
- messages,
1363
- error,
1364
- append,
1365
- reload,
1366
- stop,
1367
- setMessages,
1368
- input,
1369
- handleSubmit,
1370
- isLoading,
1371
- data: streamData
1372
- };
1373
- }
1374
-
1375
- // svelte/use-completion.ts
1376
- import { derived as derived2, get as get2, writable as writable2 } from "svelte/store";
1377
-
1378
- // shared/call-completion-api.ts
1379
- async function callCompletionApi({
1380
- api,
1381
- prompt,
1382
- credentials,
1383
- headers,
1384
- body,
1385
- streamMode = "stream-data",
1386
- setCompletion,
1387
- setLoading,
1388
- setError,
1389
- setAbortController,
1390
- onResponse,
1391
- onFinish,
1392
- onError,
1393
- onData
1394
- }) {
1395
- try {
1396
- setLoading(true);
1397
- setError(void 0);
1398
- const abortController = new AbortController();
1399
- setAbortController(abortController);
1400
- setCompletion("");
1401
- const res = await fetch(api, {
1402
- method: "POST",
1403
- body: JSON.stringify({
1404
- prompt,
1405
- ...body
1406
- }),
1407
- credentials,
1408
- headers: {
1409
- "Content-Type": "application/json",
1410
- ...headers
1411
- },
1412
- signal: abortController.signal
1413
- }).catch((err) => {
1414
- throw err;
1415
- });
1416
- if (onResponse) {
1417
- try {
1418
- await onResponse(res);
1419
- } catch (err) {
1420
- throw err;
1421
- }
1422
- }
1423
- if (!res.ok) {
1424
- throw new Error(
1425
- await res.text() || "Failed to fetch the chat response."
1426
- );
1427
- }
1428
- if (!res.body) {
1429
- throw new Error("The response body is empty.");
1430
- }
1431
- let result = "";
1432
- const reader = res.body.getReader();
1433
- switch (streamMode) {
1434
- case "text": {
1435
- const decoder = createChunkDecoder();
1436
- while (true) {
1437
- const { done, value } = await reader.read();
1438
- if (done) {
1439
- break;
1440
- }
1441
- result += decoder(value);
1442
- setCompletion(result);
1443
- if (abortController === null) {
1444
- reader.cancel();
1445
- break;
1446
- }
1447
- }
1448
- break;
1449
- }
1450
- case "stream-data": {
1451
- for await (const { type, value } of readDataStream(reader, {
1452
- isAborted: () => abortController === null
1453
- })) {
1454
- switch (type) {
1455
- case "text": {
1456
- result += value;
1457
- setCompletion(result);
1458
- break;
1459
- }
1460
- case "data": {
1461
- onData == null ? void 0 : onData(value);
1462
- break;
1463
- }
1464
- }
1465
- }
1466
- break;
1467
- }
1468
- default: {
1469
- const exhaustiveCheck = streamMode;
1470
- throw new Error(`Unknown stream mode: ${exhaustiveCheck}`);
1471
- }
1472
- }
1473
- if (onFinish) {
1474
- onFinish(prompt, result);
1475
- }
1476
- setAbortController(null);
1477
- return result;
1478
- } catch (err) {
1479
- if (err.name === "AbortError") {
1480
- setAbortController(null);
1481
- return null;
1482
- }
1483
- if (err instanceof Error) {
1484
- if (onError) {
1485
- onError(err);
1486
- }
1487
- }
1488
- setError(err);
1489
- } finally {
1490
- setLoading(false);
1491
- }
1492
- }
1493
-
1494
- // svelte/use-completion.ts
1495
- var uniqueId2 = 0;
1496
- var store2 = {};
1497
- function useCompletion({
1498
- api = "/api/completion",
1499
- id,
1500
- initialCompletion = "",
1501
- initialInput = "",
1502
- credentials,
1503
- headers,
1504
- body,
1505
- streamMode,
1506
- onResponse,
1507
- onFinish,
1508
- onError
1509
- } = {}) {
1510
- const completionId = id || `completion-${uniqueId2++}`;
1511
- const key = `${api}|${completionId}`;
1512
- const {
1513
- data,
1514
- mutate: originalMutate,
1515
- isLoading: isSWRLoading
1516
- } = F2(key, {
1517
- fetcher: () => store2[key] || initialCompletion,
1518
- fallbackData: initialCompletion
1519
- });
1520
- const streamData = writable2(void 0);
1521
- const loading = writable2(false);
1522
- data.set(initialCompletion);
1523
- const mutate = (data2) => {
1524
- store2[key] = data2;
1525
- return originalMutate(data2);
1526
- };
1527
- const completion = data;
1528
- const error = writable2(void 0);
1529
- let abortController = null;
1530
- const complete = async (prompt, options) => {
1531
- const existingData = get2(streamData);
1532
- return callCompletionApi({
1533
- api,
1534
- prompt,
1535
- credentials,
1536
- headers: {
1537
- ...headers,
1538
- ...options == null ? void 0 : options.headers
1539
- },
1540
- body: {
1541
- ...body,
1542
- ...options == null ? void 0 : options.body
1543
- },
1544
- streamMode,
1545
- setCompletion: mutate,
1546
- setLoading: (loadingState) => loading.set(loadingState),
1547
- setError: (err) => error.set(err),
1548
- setAbortController: (controller) => {
1549
- abortController = controller;
1550
- },
1551
- onResponse,
1552
- onFinish,
1553
- onError,
1554
- onData(data2) {
1555
- streamData.set([...existingData || [], ...data2 || []]);
1556
- }
1557
- });
1558
- };
1559
- const stop = () => {
1560
- if (abortController) {
1561
- abortController.abort();
1562
- abortController = null;
1563
- }
1564
- };
1565
- const setCompletion = (completion2) => {
1566
- mutate(completion2);
1567
- };
1568
- const input = writable2(initialInput);
1569
- const handleSubmit = (e) => {
1570
- e.preventDefault();
1571
- const inputValue = get2(input);
1572
- if (!inputValue)
1573
- return;
1574
- return complete(inputValue);
1575
- };
1576
- const isLoading = derived2(
1577
- [isSWRLoading, loading],
1578
- ([$isSWRLoading, $loading]) => {
1579
- return $isSWRLoading || $loading;
1580
- }
1581
- );
1582
- return {
1583
- completion,
1584
- complete,
1585
- error,
1586
- stop,
1587
- setCompletion,
1588
- input,
1589
- handleSubmit,
1590
- isLoading,
1591
- data: streamData
1592
- };
1593
- }
1594
-
1595
- // svelte/use-assistant.ts
1596
- import { isAbortError } from "@ai-sdk/provider-utils";
1597
- import { get as get3, writable as writable3 } from "svelte/store";
1598
- var uniqueId3 = 0;
1599
- var store3 = {};
1600
- function useAssistant({
1601
- api,
1602
- threadId: threadIdParam,
1603
- credentials,
1604
- headers,
1605
- body,
1606
- onError
1607
- }) {
1608
- const threadIdStore = writable3(threadIdParam);
1609
- const key = `${api}|${threadIdParam != null ? threadIdParam : `completion-${uniqueId3++}`}`;
1610
- const messages = writable3(store3[key] || []);
1611
- const input = writable3("");
1612
- const status = writable3("awaiting_message");
1613
- const error = writable3(void 0);
1614
- let abortController = null;
1615
- const mutateMessages = (newMessages) => {
1616
- store3[key] = newMessages;
1617
- messages.set(newMessages);
1618
- };
1619
- async function append(message, requestOptions) {
1620
- var _a, _b, _c, _d;
1621
- status.set("in_progress");
1622
- abortController = new AbortController();
1623
- mutateMessages([
1624
- ...get3(messages),
1625
- { ...message, id: (_a = message.id) != null ? _a : generateId() }
1626
- ]);
1627
- input.set("");
1628
- try {
1629
- const result = await fetch(api, {
1630
- method: "POST",
1631
- credentials,
1632
- signal: abortController.signal,
1633
- headers: { "Content-Type": "application/json", ...headers },
1634
- body: JSON.stringify({
1635
- ...body,
1636
- // always use user-provided threadId when available:
1637
- threadId: (_b = threadIdParam != null ? threadIdParam : get3(threadIdStore)) != null ? _b : null,
1638
- message: message.content,
1639
- // optional request data:
1640
- data: requestOptions == null ? void 0 : requestOptions.data
1641
- })
1642
- });
1643
- if (result.body == null) {
1644
- throw new Error("The response body is empty.");
1645
- }
1646
- for await (const { type, value } of readDataStream(
1647
- result.body.getReader()
1648
- )) {
1649
- switch (type) {
1650
- case "assistant_message": {
1651
- mutateMessages([
1652
- ...get3(messages),
1653
- {
1654
- id: value.id,
1655
- role: value.role,
1656
- content: value.content[0].text.value
1657
- }
1658
- ]);
1659
- break;
1660
- }
1661
- case "text": {
1662
- mutateMessages(
1663
- get3(messages).map((msg, index, array) => {
1664
- if (index === array.length - 1) {
1665
- return { ...msg, content: msg.content + value };
1666
- }
1667
- return msg;
1668
- })
1669
- );
1670
- break;
1671
- }
1672
- case "data_message": {
1673
- mutateMessages([
1674
- ...get3(messages),
1675
- {
1676
- id: (_c = value.id) != null ? _c : generateId(),
1677
- role: "data",
1678
- content: "",
1679
- data: value.data
1680
- }
1681
- ]);
1682
- break;
1683
- }
1684
- case "assistant_control_data": {
1685
- threadIdStore.set(value.threadId);
1686
- mutateMessages(
1687
- get3(messages).map((msg, index, array) => {
1688
- if (index === array.length - 1) {
1689
- return { ...msg, id: value.messageId };
1690
- }
1691
- return msg;
1692
- })
1693
- );
1694
- break;
1695
- }
1696
- case "error": {
1697
- error.set(new Error(value));
1698
- break;
1699
- }
1700
- }
1701
- }
1702
- } catch (err) {
1703
- if (isAbortError(error) && ((_d = abortController == null ? void 0 : abortController.signal) == null ? void 0 : _d.aborted)) {
1704
- abortController = null;
1705
- return;
1706
- }
1707
- if (onError && err instanceof Error) {
1708
- onError(err);
1709
- }
1710
- error.set(err);
1711
- } finally {
1712
- abortController = null;
1713
- status.set("awaiting_message");
1714
- }
1715
- }
1716
- function setMessages(messages2) {
1717
- mutateMessages(messages2);
1718
- }
1719
- function stop() {
1720
- if (abortController) {
1721
- abortController.abort();
1722
- abortController = null;
1723
- }
1724
- }
1725
- async function submitMessage(e, requestOptions) {
1726
- e.preventDefault();
1727
- const inputValue = get3(input);
1728
- if (!inputValue)
1729
- return;
1730
- await append({ role: "user", content: inputValue }, requestOptions);
1731
- }
1732
- return {
1733
- messages,
1734
- error,
1735
- threadId: threadIdStore,
1736
- input,
1737
- append,
1738
- submitMessage,
1739
- status,
1740
- setMessages,
1741
- stop
1742
- };
1743
- }
1744
- export {
1745
- useAssistant,
1746
- useChat,
1747
- useCompletion
1748
- };
1749
- //# sourceMappingURL=index.mjs.map