ai 3.4.32 → 4.0.0-canary.0

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.
@@ -1,1136 +0,0 @@
1
- // svelte/use-chat.ts
2
- import {
3
- callChatApi,
4
- generateId as generateIdFunc,
5
- processChatStream
6
- } from "@ai-sdk/ui-utils";
7
-
8
- // ../../node_modules/.pnpm/swrev@4.0.0/node_modules/swrev/dist/swrev.mjs
9
- var P = Object.defineProperty;
10
- var F = (r, e, t) => e in r ? P(r, e, { enumerable: true, configurable: true, writable: true, value: t }) : r[e] = t;
11
- var h = (r, e, t) => (F(r, typeof e != "symbol" ? e + "" : e, t), t);
12
- var I = class {
13
- constructor() {
14
- h(this, "listeners", /* @__PURE__ */ new Map());
15
- }
16
- /**
17
- * Subscribes a given listener.
18
- */
19
- subscribe(e, t) {
20
- this.listeners.has(e) || this.listeners.set(e, []), !this.listeners.get(e).includes(t) && this.listeners.get(e).push(t);
21
- }
22
- /**
23
- * Unsubscribes the given listener.
24
- */
25
- unsubscribe(e, t) {
26
- 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));
27
- }
28
- /**
29
- * Emits an event to all active listeners.
30
- */
31
- emit(e, t) {
32
- this.listeners.has(e) && this.listeners.get(e).forEach((s) => s(t));
33
- }
34
- };
35
- var L = {
36
- broadcast: false
37
- };
38
- var S = {
39
- broadcast: false
40
- };
41
- var O = class {
42
- /**
43
- * Creates the cache item given the data and expiration at.
44
- */
45
- constructor({ data: e, expiresAt: t = null }) {
46
- h(this, "data");
47
- h(this, "expiresAt");
48
- this.data = e, this.expiresAt = t;
49
- }
50
- /**
51
- * Determines if the current cache item is still being resolved.
52
- * This returns true if data is a promise, or false if type `D`.
53
- */
54
- isResolving() {
55
- return this.data instanceof Promise;
56
- }
57
- /**
58
- * Determines if the given cache item has expired.
59
- */
60
- hasExpired() {
61
- return this.expiresAt === null || this.expiresAt < /* @__PURE__ */ new Date();
62
- }
63
- /**
64
- * Set the expiration time of the given cache item relative to now.
65
- */
66
- expiresIn(e) {
67
- return this.expiresAt = /* @__PURE__ */ new Date(), this.expiresAt.setMilliseconds(this.expiresAt.getMilliseconds() + e), this;
68
- }
69
- };
70
- var q = class {
71
- constructor() {
72
- h(this, "elements", /* @__PURE__ */ new Map());
73
- h(this, "event", new I());
74
- }
75
- /**
76
- * Resolves the promise and replaces the Promise to the resolved data.
77
- * It also broadcasts the value change if needed or deletes the key if
78
- * the value resolves to undefined or null.
79
- */
80
- resolve(e, t) {
81
- Promise.resolve(t.data).then((s) => {
82
- if (s == null)
83
- return this.remove(e);
84
- t.data = s, this.broadcast(e, s);
85
- });
86
- }
87
- /**
88
- * Gets an element from the cache.
89
- *
90
- * It is assumed the item always exist when
91
- * you get it. Use the has method to check
92
- * for the existence of it.
93
- */
94
- get(e) {
95
- return this.elements.get(e);
96
- }
97
- /**
98
- * Sets an element to the cache.
99
- */
100
- set(e, t) {
101
- this.elements.set(e, t), this.resolve(e, t);
102
- }
103
- /**
104
- * Removes an key-value pair from the cache.
105
- */
106
- remove(e, t) {
107
- const { broadcast: s } = { ...L, ...t };
108
- s && this.broadcast(e, void 0), this.elements.delete(e);
109
- }
110
- /**
111
- * Removes all the key-value pairs from the cache.
112
- */
113
- clear(e) {
114
- const { broadcast: t } = { ...S, ...e };
115
- if (t)
116
- for (const s of this.elements.keys())
117
- this.broadcast(s, void 0);
118
- this.elements.clear();
119
- }
120
- /**
121
- * Determines if the given key exists
122
- * in the cache.
123
- */
124
- has(e) {
125
- return this.elements.has(e);
126
- }
127
- /**
128
- * Subscribes the callback to the given key.
129
- */
130
- subscribe(e, t) {
131
- this.event.subscribe(e, t);
132
- }
133
- /**
134
- * Unsubscribes to the given key events.
135
- */
136
- unsubscribe(e, t) {
137
- this.event.unsubscribe(e, t);
138
- }
139
- /**
140
- * Broadcasts a value change on all subscribed instances.
141
- */
142
- broadcast(e, t) {
143
- this.event.emit(e, t);
144
- }
145
- };
146
- var x = {
147
- cache: new q(),
148
- errors: new I(),
149
- fetcher: async (r) => {
150
- const e = await fetch(r);
151
- if (!e.ok)
152
- throw Error("Not a 2XX response.");
153
- return e.json();
154
- },
155
- fallbackData: void 0,
156
- loadInitialCache: true,
157
- revalidateOnStart: true,
158
- dedupingInterval: 2e3,
159
- revalidateOnFocus: true,
160
- focusThrottleInterval: 5e3,
161
- revalidateOnReconnect: true,
162
- reconnectWhen: (r, { enabled: e }) => e && typeof window < "u" ? (window.addEventListener("online", r), () => window.removeEventListener("online", r)) : () => {
163
- },
164
- focusWhen: (r, { enabled: e, throttleInterval: t }) => {
165
- if (e && typeof window < "u") {
166
- let s = null;
167
- const i = () => {
168
- const a = Date.now();
169
- (s === null || a - s > t) && (s = a, r());
170
- };
171
- return window.addEventListener("focus", i), () => window.removeEventListener("focus", i);
172
- }
173
- return () => {
174
- };
175
- },
176
- revalidateFunction: void 0
177
- };
178
- var E = {
179
- ...x,
180
- force: false
181
- };
182
- var T = {
183
- revalidate: true,
184
- revalidateOptions: { ...E },
185
- revalidateFunction: void 0
186
- };
187
- var X = {
188
- broadcast: false
189
- };
190
- var H = class {
191
- /**
192
- * Creates a new instance of SWR.
193
- */
194
- constructor(e) {
195
- h(this, "options");
196
- this.options = { ...x, ...e };
197
- }
198
- /**
199
- * Gets the cache of the SWR.
200
- */
201
- get cache() {
202
- return this.options.cache;
203
- }
204
- /**
205
- * Gets the cache of the SWR.
206
- */
207
- get errors() {
208
- return this.options.errors;
209
- }
210
- /**
211
- * Requests the data using the provided fetcher.
212
- */
213
- async requestData(e, t) {
214
- return await Promise.resolve(t(e)).catch((s) => {
215
- throw this.errors.emit(e, s), s;
216
- });
217
- }
218
- /**
219
- * Resolves the given to a SWRKey or undefined.
220
- */
221
- resolveKey(e) {
222
- if (typeof e == "function")
223
- try {
224
- return e();
225
- } catch (e2) {
226
- return;
227
- }
228
- return e;
229
- }
230
- /**
231
- * Clear the specified keys from the cache. If no keys
232
- * are specified, it clears all the cache keys.
233
- */
234
- clear(e, t) {
235
- const s = { ...X, ...t };
236
- if (e == null)
237
- return this.cache.clear(s);
238
- if (!Array.isArray(e))
239
- return this.cache.remove(e, s);
240
- for (const i of e)
241
- this.cache.remove(i, s);
242
- }
243
- /**
244
- * Revalidates the key and mutates the cache if needed.
245
- */
246
- async revalidate(e, t) {
247
- if (!e)
248
- throw new Error("[Revalidate] Key issue: ${key}");
249
- const { fetcher: s, dedupingInterval: i } = this.options, { force: a, fetcher: o, dedupingInterval: n } = {
250
- ...E,
251
- fetcher: s,
252
- dedupingInterval: i,
253
- ...t
254
- };
255
- if (a || !this.cache.has(e) || this.cache.has(e) && this.cache.get(e).hasExpired()) {
256
- const c2 = this.requestData(e, o), l = c2.catch(() => {
257
- });
258
- return this.cache.set(e, new O({ data: l }).expiresIn(n)), await c2;
259
- }
260
- return this.getWait(e);
261
- }
262
- /**
263
- * Mutates the data of a given key with a new value.
264
- * This is used to replace the cache contents of the
265
- * given key manually.
266
- */
267
- async mutate(e, t, s) {
268
- var _a;
269
- if (!e)
270
- throw new Error("[Mutate] Key issue: ${key}");
271
- const {
272
- revalidate: i,
273
- revalidateOptions: a,
274
- revalidateFunction: o
275
- } = {
276
- ...T,
277
- ...s
278
- };
279
- let n;
280
- if (typeof t == "function") {
281
- let c2;
282
- if (this.cache.has(e)) {
283
- const l = this.cache.get(e);
284
- l.isResolving() || (c2 = l.data);
285
- }
286
- n = t(c2);
287
- } else
288
- n = t;
289
- 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;
290
- }
291
- /**
292
- * Gets the data of the given key. Keep in mind
293
- * this data will be stale and revalidate in the background
294
- * unless specified otherwise.
295
- */
296
- subscribeData(e, t) {
297
- if (e) {
298
- const s = (i) => t(i);
299
- return this.cache.subscribe(e, s), () => this.cache.unsubscribe(e, s);
300
- }
301
- return () => {
302
- };
303
- }
304
- /**
305
- * Subscribes to errors on the given key.
306
- */
307
- subscribeErrors(e, t) {
308
- if (e) {
309
- const s = (i) => t(i);
310
- return this.errors.subscribe(e, s), () => this.errors.unsubscribe(e, s);
311
- }
312
- return () => {
313
- };
314
- }
315
- /**
316
- * Gets the current cached data of the given key.
317
- * This does not trigger any revalidation nor mutation
318
- * of the data.
319
- * - If the data has never been validated
320
- * (there is no cache) it will return undefined.
321
- * - If the item is pending to resolve (there is a request
322
- * pending to resolve) it will return undefined.
323
- */
324
- get(e) {
325
- if (e && this.cache.has(e)) {
326
- const t = this.cache.get(e);
327
- if (!t.isResolving())
328
- return t.data;
329
- }
330
- }
331
- /**
332
- * Gets an element from the cache. The difference
333
- * with the get is that this method returns a promise
334
- * that will resolve the the value. If there's no item
335
- * in the cache, it will wait for it before resolving.
336
- */
337
- getWait(e) {
338
- return new Promise((t, s) => {
339
- const i = this.subscribeData(e, (n) => {
340
- if (i(), n !== void 0)
341
- return t(n);
342
- }), a = this.subscribeErrors(e, (n) => {
343
- if (a(), n !== void 0)
344
- return s(n);
345
- }), o = this.get(e);
346
- if (o !== void 0)
347
- return t(o);
348
- });
349
- }
350
- /**
351
- * Use a SWR value given the key and
352
- * subscribe to future changes.
353
- */
354
- subscribe(e, t, s, i) {
355
- const {
356
- fetcher: a,
357
- fallbackData: o,
358
- loadInitialCache: n,
359
- revalidateOnStart: c2,
360
- dedupingInterval: l,
361
- revalidateOnFocus: A2,
362
- focusThrottleInterval: C,
363
- revalidateOnReconnect: R,
364
- reconnectWhen: W2,
365
- focusWhen: D2,
366
- revalidateFunction: d
367
- } = {
368
- // Current instance options
369
- // (includes default options)
370
- ...this.options,
371
- // Current call options.
372
- ...i
373
- }, K2 = (m) => {
374
- var _a;
375
- return (_a = d == null ? void 0 : d(this.resolveKey(e), m)) != null ? _a : this.revalidate(this.resolveKey(e), m);
376
- }, 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;
377
- u && (t == null || t(u));
378
- const v2 = t ? this.subscribeData(this.resolveKey(e), t) : void 0, b = s ? this.subscribeErrors(this.resolveKey(e), s) : void 0, p2 = D2(f, {
379
- throttleInterval: C,
380
- enabled: A2
381
- }), w2 = W2(f, {
382
- enabled: R
383
- });
384
- return { unsubscribe: () => {
385
- v2 == null || v2(), b == null || b(), p2 == null || p2(), w2 == null || w2();
386
- }, dataPromise: M, revalidatePromise: g };
387
- }
388
- };
389
-
390
- // ../../node_modules/.pnpm/sswr@2.1.0_svelte@4.2.18/node_modules/sswr/dist/sswr.js
391
- import { beforeUpdate as w, onDestroy as E2 } from "svelte";
392
- function p() {
393
- }
394
- function D(t) {
395
- return t();
396
- }
397
- function q2(t) {
398
- t.forEach(D);
399
- }
400
- function x2(t) {
401
- return typeof t == "function";
402
- }
403
- function K(t, e) {
404
- return t != t ? e == e : t !== e || t && typeof t == "object" || typeof t == "function";
405
- }
406
- function z(t, ...e) {
407
- if (t == null) {
408
- for (const r of e)
409
- r(void 0);
410
- return p;
411
- }
412
- const n = t.subscribe(...e);
413
- return n.unsubscribe ? () => n.unsubscribe() : n;
414
- }
415
- var v = [];
416
- function A(t, e) {
417
- return {
418
- subscribe: y(t, e).subscribe
419
- };
420
- }
421
- function y(t, e = p) {
422
- let n;
423
- const r = /* @__PURE__ */ new Set();
424
- function i(u) {
425
- if (K(t, u) && (t = u, n)) {
426
- const f = !v.length;
427
- for (const s of r)
428
- s[1](), v.push(s, t);
429
- if (f) {
430
- for (let s = 0; s < v.length; s += 2)
431
- v[s][0](v[s + 1]);
432
- v.length = 0;
433
- }
434
- }
435
- }
436
- function a(u) {
437
- i(u(t));
438
- }
439
- function d(u, f = p) {
440
- const s = [u, f];
441
- return r.add(s), r.size === 1 && (n = e(i, a) || p), u(t), () => {
442
- r.delete(s), r.size === 0 && n && (n(), n = null);
443
- };
444
- }
445
- return { set: i, update: a, subscribe: d };
446
- }
447
- function S2(t, e, n) {
448
- const r = !Array.isArray(t), i = r ? [t] : t;
449
- if (!i.every(Boolean))
450
- throw new Error("derived() expects stores as input, got a falsy value");
451
- const a = e.length < 2;
452
- return A(n, (d, u) => {
453
- let f = false;
454
- const s = [];
455
- let h2 = 0, o = p;
456
- const l = () => {
457
- if (h2)
458
- return;
459
- o();
460
- const b = e(r ? s[0] : s, d, u);
461
- a ? d(b) : o = x2(b) ? b : p;
462
- }, g = i.map(
463
- (b, m) => z(
464
- b,
465
- (R) => {
466
- s[m] = R, h2 &= ~(1 << m), f && l();
467
- },
468
- () => {
469
- h2 |= 1 << m;
470
- }
471
- )
472
- );
473
- return f = true, l(), function() {
474
- q2(g), o(), f = false;
475
- };
476
- });
477
- }
478
- var O2 = class extends H {
479
- /**
480
- * Svelte specific use of SWR.
481
- */
482
- useSWR(e, n) {
483
- let r;
484
- const i = y(void 0, () => () => r == null ? void 0 : r()), a = y(void 0, () => () => r == null ? void 0 : r());
485
- w(() => {
486
- const o = (g) => {
487
- a.set(void 0), i.set(g);
488
- }, l = (g) => a.set(g);
489
- r || (r = this.subscribe(e, o, l, {
490
- loadInitialCache: true,
491
- ...n
492
- }).unsubscribe);
493
- }), E2(() => r == null ? void 0 : r());
494
- const d = (o, l) => this.mutate(this.resolveKey(e), o, {
495
- revalidateOptions: n,
496
- ...l
497
- }), 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);
498
- return { data: i, error: a, mutate: d, revalidate: u, clear: f, isLoading: s, isValid: h2 };
499
- }
500
- };
501
- var W = (t) => new O2(t);
502
- var c = W();
503
- var F2 = (t, e) => c.useSWR(t, e);
504
-
505
- // svelte/use-chat.ts
506
- import { derived, get, writable } from "svelte/store";
507
- var getStreamedResponse = async (api, chatRequest, mutate, mutateStreamData, existingData, extraMetadata, previousMessages, abortControllerRef, generateId2, streamProtocol, onFinish, onResponse, onToolCall, sendExtraMessageFields, fetch2, keepLastMessageOnError) => {
508
- mutate(chatRequest.messages);
509
- const constructedMessagesPayload = sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(
510
- ({
511
- role,
512
- content,
513
- name,
514
- data,
515
- annotations,
516
- function_call,
517
- tool_calls,
518
- tool_call_id,
519
- toolInvocations
520
- }) => ({
521
- role,
522
- content,
523
- ...name !== void 0 && { name },
524
- ...data !== void 0 && { data },
525
- ...annotations !== void 0 && { annotations },
526
- ...toolInvocations !== void 0 && { toolInvocations },
527
- // outdated function/tool call handling (TODO deprecate):
528
- tool_call_id,
529
- ...function_call !== void 0 && { function_call },
530
- ...tool_calls !== void 0 && { tool_calls }
531
- })
532
- );
533
- return await callChatApi({
534
- api,
535
- body: {
536
- messages: constructedMessagesPayload,
537
- data: chatRequest.data,
538
- ...extraMetadata.body,
539
- ...chatRequest.body,
540
- ...chatRequest.functions !== void 0 && {
541
- functions: chatRequest.functions
542
- },
543
- ...chatRequest.function_call !== void 0 && {
544
- function_call: chatRequest.function_call
545
- },
546
- ...chatRequest.tools !== void 0 && {
547
- tools: chatRequest.tools
548
- },
549
- ...chatRequest.tool_choice !== void 0 && {
550
- tool_choice: chatRequest.tool_choice
551
- }
552
- },
553
- streamProtocol,
554
- credentials: extraMetadata.credentials,
555
- headers: {
556
- ...extraMetadata.headers,
557
- ...chatRequest.headers
558
- },
559
- abortController: () => abortControllerRef,
560
- restoreMessagesOnFailure() {
561
- if (!keepLastMessageOnError) {
562
- mutate(previousMessages);
563
- }
564
- },
565
- onResponse,
566
- onUpdate(merged, data) {
567
- mutate([...chatRequest.messages, ...merged]);
568
- mutateStreamData([...existingData || [], ...data || []]);
569
- },
570
- onFinish,
571
- generateId: generateId2,
572
- onToolCall,
573
- fetch: fetch2
574
- });
575
- };
576
- var uniqueId = 0;
577
- var store = {};
578
- function isAssistantMessageWithCompletedToolCalls(message) {
579
- return message.role === "assistant" && message.toolInvocations && message.toolInvocations.length > 0 && message.toolInvocations.every((toolInvocation) => "result" in toolInvocation);
580
- }
581
- function countTrailingAssistantMessages(messages) {
582
- let count = 0;
583
- for (let i = messages.length - 1; i >= 0; i--) {
584
- if (messages[i].role === "assistant") {
585
- count++;
586
- } else {
587
- break;
588
- }
589
- }
590
- return count;
591
- }
592
- function useChat({
593
- api = "/api/chat",
594
- id,
595
- initialMessages = [],
596
- initialInput = "",
597
- sendExtraMessageFields,
598
- experimental_onFunctionCall,
599
- experimental_onToolCall,
600
- streamMode,
601
- streamProtocol,
602
- onResponse,
603
- onFinish,
604
- onError,
605
- onToolCall,
606
- credentials,
607
- headers,
608
- body,
609
- generateId: generateId2 = generateIdFunc,
610
- fetch: fetch2,
611
- keepLastMessageOnError = false,
612
- maxToolRoundtrips = 0,
613
- maxSteps = maxToolRoundtrips != null ? maxToolRoundtrips + 1 : 1
614
- } = {}) {
615
- if (streamMode) {
616
- streamProtocol != null ? streamProtocol : streamProtocol = streamMode === "text" ? "text" : void 0;
617
- }
618
- const chatId = id || `chat-${uniqueId++}`;
619
- const key = `${api}|${chatId}`;
620
- const {
621
- data,
622
- mutate: originalMutate,
623
- isLoading: isSWRLoading
624
- } = F2(key, {
625
- fetcher: () => store[key] || initialMessages,
626
- fallbackData: initialMessages
627
- });
628
- const streamData = writable(void 0);
629
- const loading = writable(false);
630
- data.set(initialMessages);
631
- const mutate = (data2) => {
632
- store[key] = data2;
633
- return originalMutate(data2);
634
- };
635
- const messages = data;
636
- let abortController = null;
637
- const extraMetadata = {
638
- credentials,
639
- headers,
640
- body
641
- };
642
- const error = writable(void 0);
643
- async function triggerRequest(chatRequest) {
644
- const messagesSnapshot = get(messages);
645
- const messageCount = messagesSnapshot.length;
646
- try {
647
- error.set(void 0);
648
- loading.set(true);
649
- abortController = new AbortController();
650
- await processChatStream({
651
- getStreamedResponse: () => getStreamedResponse(
652
- api,
653
- chatRequest,
654
- mutate,
655
- (data2) => {
656
- streamData.set(data2);
657
- },
658
- get(streamData),
659
- extraMetadata,
660
- get(messages),
661
- abortController,
662
- generateId2,
663
- streamProtocol,
664
- onFinish,
665
- onResponse,
666
- onToolCall,
667
- sendExtraMessageFields,
668
- fetch2,
669
- keepLastMessageOnError
670
- ),
671
- experimental_onFunctionCall,
672
- experimental_onToolCall,
673
- updateChatRequest: (chatRequestParam) => {
674
- chatRequest = chatRequestParam;
675
- },
676
- getCurrentMessages: () => get(messages)
677
- });
678
- abortController = null;
679
- } catch (err) {
680
- if (err.name === "AbortError") {
681
- abortController = null;
682
- return null;
683
- }
684
- if (onError && err instanceof Error) {
685
- onError(err);
686
- }
687
- error.set(err);
688
- } finally {
689
- loading.set(false);
690
- }
691
- const newMessagesSnapshot = get(messages);
692
- const lastMessage = newMessagesSnapshot[newMessagesSnapshot.length - 1];
693
- if (
694
- // ensure we actually have new messages (to prevent infinite loops in case of errors):
695
- newMessagesSnapshot.length > messageCount && // ensure there is a last message:
696
- lastMessage != null && // check if the feature is enabled:
697
- maxSteps > 1 && // check that next step is possible:
698
- isAssistantMessageWithCompletedToolCalls(lastMessage) && // limit the number of automatic steps:
699
- countTrailingAssistantMessages(newMessagesSnapshot) < maxSteps
700
- ) {
701
- await triggerRequest({ messages: newMessagesSnapshot });
702
- }
703
- }
704
- const append = async (message, {
705
- options,
706
- functions,
707
- function_call,
708
- tools,
709
- tool_choice,
710
- data: data2,
711
- headers: headers2,
712
- body: body2
713
- } = {}) => {
714
- if (!message.id) {
715
- message.id = generateId2();
716
- }
717
- const requestOptions = {
718
- headers: headers2 != null ? headers2 : options == null ? void 0 : options.headers,
719
- body: body2 != null ? body2 : options == null ? void 0 : options.body
720
- };
721
- const chatRequest = {
722
- messages: get(messages).concat(message),
723
- options: requestOptions,
724
- headers: requestOptions.headers,
725
- body: requestOptions.body,
726
- data: data2,
727
- ...functions !== void 0 && { functions },
728
- ...function_call !== void 0 && { function_call },
729
- ...tools !== void 0 && { tools },
730
- ...tool_choice !== void 0 && { tool_choice }
731
- };
732
- return triggerRequest(chatRequest);
733
- };
734
- const reload = async ({
735
- options,
736
- functions,
737
- function_call,
738
- tools,
739
- tool_choice,
740
- data: data2,
741
- headers: headers2,
742
- body: body2
743
- } = {}) => {
744
- const messagesSnapshot = get(messages);
745
- if (messagesSnapshot.length === 0)
746
- return null;
747
- const requestOptions = {
748
- headers: headers2 != null ? headers2 : options == null ? void 0 : options.headers,
749
- body: body2 != null ? body2 : options == null ? void 0 : options.body
750
- };
751
- const lastMessage = messagesSnapshot.at(-1);
752
- if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant") {
753
- const chatRequest2 = {
754
- messages: messagesSnapshot.slice(0, -1),
755
- options: requestOptions,
756
- headers: requestOptions.headers,
757
- body: requestOptions.body,
758
- data: data2,
759
- ...functions !== void 0 && { functions },
760
- ...function_call !== void 0 && { function_call },
761
- ...tools !== void 0 && { tools },
762
- ...tool_choice !== void 0 && { tool_choice }
763
- };
764
- return triggerRequest(chatRequest2);
765
- }
766
- const chatRequest = {
767
- messages: messagesSnapshot,
768
- options: requestOptions,
769
- headers: requestOptions.headers,
770
- body: requestOptions.body,
771
- data: data2
772
- };
773
- return triggerRequest(chatRequest);
774
- };
775
- const stop = () => {
776
- if (abortController) {
777
- abortController.abort();
778
- abortController = null;
779
- }
780
- };
781
- const setMessages = (messagesArg) => {
782
- if (typeof messagesArg === "function") {
783
- messagesArg = messagesArg(get(messages));
784
- }
785
- mutate(messagesArg);
786
- };
787
- const setData = (dataArg) => {
788
- if (typeof dataArg === "function") {
789
- dataArg = dataArg(get(streamData));
790
- }
791
- streamData.set(dataArg);
792
- };
793
- const input = writable(initialInput);
794
- const handleSubmit = (event, options = {}) => {
795
- var _a, _b, _c, _d, _e;
796
- (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
797
- const inputValue = get(input);
798
- if (!inputValue && !options.allowEmptySubmit)
799
- return;
800
- const requestOptions = {
801
- headers: (_c = options.headers) != null ? _c : (_b = options.options) == null ? void 0 : _b.headers,
802
- body: (_e = options.body) != null ? _e : (_d = options.options) == null ? void 0 : _d.body
803
- };
804
- const chatRequest = {
805
- messages: !inputValue && options.allowEmptySubmit ? get(messages) : get(messages).concat({
806
- id: generateId2(),
807
- content: inputValue,
808
- role: "user",
809
- createdAt: /* @__PURE__ */ new Date()
810
- }),
811
- options: requestOptions,
812
- body: requestOptions.body,
813
- headers: requestOptions.headers,
814
- data: options.data
815
- };
816
- triggerRequest(chatRequest);
817
- input.set("");
818
- };
819
- const isLoading = derived(
820
- [isSWRLoading, loading],
821
- ([$isSWRLoading, $loading]) => {
822
- return $isSWRLoading || $loading;
823
- }
824
- );
825
- const addToolResult = ({
826
- toolCallId,
827
- result
828
- }) => {
829
- var _a;
830
- const messagesSnapshot = (_a = get(messages)) != null ? _a : [];
831
- const updatedMessages = messagesSnapshot.map(
832
- (message, index, arr) => (
833
- // update the tool calls in the last assistant message:
834
- index === arr.length - 1 && message.role === "assistant" && message.toolInvocations ? {
835
- ...message,
836
- toolInvocations: message.toolInvocations.map(
837
- (toolInvocation) => toolInvocation.toolCallId === toolCallId ? { ...toolInvocation, result } : toolInvocation
838
- )
839
- } : message
840
- )
841
- );
842
- messages.set(updatedMessages);
843
- const lastMessage = updatedMessages[updatedMessages.length - 1];
844
- if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {
845
- triggerRequest({ messages: updatedMessages });
846
- }
847
- };
848
- return {
849
- messages,
850
- error,
851
- append,
852
- reload,
853
- stop,
854
- setMessages,
855
- input,
856
- handleSubmit,
857
- isLoading,
858
- data: streamData,
859
- setData,
860
- addToolResult
861
- };
862
- }
863
-
864
- // svelte/use-completion.ts
865
- import { callCompletionApi } from "@ai-sdk/ui-utils";
866
- import { derived as derived2, get as get2, writable as writable2 } from "svelte/store";
867
- var uniqueId2 = 0;
868
- var store2 = {};
869
- function useCompletion({
870
- api = "/api/completion",
871
- id,
872
- initialCompletion = "",
873
- initialInput = "",
874
- credentials,
875
- headers,
876
- body,
877
- streamMode,
878
- streamProtocol,
879
- onResponse,
880
- onFinish,
881
- onError,
882
- fetch: fetch2
883
- } = {}) {
884
- if (streamMode) {
885
- streamProtocol != null ? streamProtocol : streamProtocol = streamMode === "text" ? "text" : void 0;
886
- }
887
- const completionId = id || `completion-${uniqueId2++}`;
888
- const key = `${api}|${completionId}`;
889
- const {
890
- data,
891
- mutate: originalMutate,
892
- isLoading: isSWRLoading
893
- } = F2(key, {
894
- fetcher: () => store2[key] || initialCompletion,
895
- fallbackData: initialCompletion
896
- });
897
- const streamData = writable2(void 0);
898
- const loading = writable2(false);
899
- data.set(initialCompletion);
900
- const mutate = (data2) => {
901
- store2[key] = data2;
902
- return originalMutate(data2);
903
- };
904
- const completion = data;
905
- const error = writable2(void 0);
906
- let abortController = null;
907
- const complete = async (prompt, options) => {
908
- const existingData = get2(streamData);
909
- return callCompletionApi({
910
- api,
911
- prompt,
912
- credentials,
913
- headers: {
914
- ...headers,
915
- ...options == null ? void 0 : options.headers
916
- },
917
- body: {
918
- ...body,
919
- ...options == null ? void 0 : options.body
920
- },
921
- streamProtocol,
922
- setCompletion: mutate,
923
- setLoading: (loadingState) => loading.set(loadingState),
924
- setError: (err) => error.set(err),
925
- setAbortController: (controller) => {
926
- abortController = controller;
927
- },
928
- onResponse,
929
- onFinish,
930
- onError,
931
- onData(data2) {
932
- streamData.set([...existingData || [], ...data2 || []]);
933
- },
934
- fetch: fetch2
935
- });
936
- };
937
- const stop = () => {
938
- if (abortController) {
939
- abortController.abort();
940
- abortController = null;
941
- }
942
- };
943
- const setCompletion = (completion2) => {
944
- mutate(completion2);
945
- };
946
- const input = writable2(initialInput);
947
- const handleSubmit = (event) => {
948
- var _a;
949
- (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
950
- const inputValue = get2(input);
951
- return inputValue ? complete(inputValue) : void 0;
952
- };
953
- const isLoading = derived2(
954
- [isSWRLoading, loading],
955
- ([$isSWRLoading, $loading]) => {
956
- return $isSWRLoading || $loading;
957
- }
958
- );
959
- return {
960
- completion,
961
- complete,
962
- error,
963
- stop,
964
- setCompletion,
965
- input,
966
- handleSubmit,
967
- isLoading,
968
- data: streamData
969
- };
970
- }
971
-
972
- // svelte/use-assistant.ts
973
- import { isAbortError } from "@ai-sdk/provider-utils";
974
- import { generateId, readDataStream } from "@ai-sdk/ui-utils";
975
- import { get as get3, writable as writable3 } from "svelte/store";
976
- var getOriginalFetch = () => fetch;
977
- var uniqueId3 = 0;
978
- var store3 = {};
979
- function useAssistant({
980
- api,
981
- threadId: threadIdParam,
982
- credentials,
983
- headers,
984
- body,
985
- onError,
986
- fetch: fetch2
987
- }) {
988
- const threadIdStore = writable3(threadIdParam);
989
- const key = `${api}|${threadIdParam != null ? threadIdParam : `completion-${uniqueId3++}`}`;
990
- const messages = writable3(store3[key] || []);
991
- const input = writable3("");
992
- const status = writable3("awaiting_message");
993
- const error = writable3(void 0);
994
- let abortController = null;
995
- const mutateMessages = (newMessages) => {
996
- store3[key] = newMessages;
997
- messages.set(newMessages);
998
- };
999
- async function append(message, requestOptions) {
1000
- var _a, _b, _c, _d, _e;
1001
- status.set("in_progress");
1002
- abortController = new AbortController();
1003
- mutateMessages([
1004
- ...get3(messages),
1005
- { ...message, id: (_a = message.id) != null ? _a : generateId() }
1006
- ]);
1007
- input.set("");
1008
- try {
1009
- const actualFetch = fetch2 != null ? fetch2 : getOriginalFetch();
1010
- const response = await actualFetch(api, {
1011
- method: "POST",
1012
- credentials,
1013
- signal: abortController.signal,
1014
- headers: { "Content-Type": "application/json", ...headers },
1015
- body: JSON.stringify({
1016
- ...body,
1017
- // always use user-provided threadId when available:
1018
- threadId: (_b = threadIdParam != null ? threadIdParam : get3(threadIdStore)) != null ? _b : null,
1019
- message: message.content,
1020
- // optional request data:
1021
- data: requestOptions == null ? void 0 : requestOptions.data
1022
- })
1023
- });
1024
- if (!response.ok) {
1025
- throw new Error(
1026
- (_c = await response.text()) != null ? _c : "Failed to fetch the assistant response."
1027
- );
1028
- }
1029
- if (response.body == null) {
1030
- throw new Error("The response body is empty.");
1031
- }
1032
- for await (const { type, value } of readDataStream(
1033
- response.body.getReader()
1034
- )) {
1035
- switch (type) {
1036
- case "assistant_message": {
1037
- mutateMessages([
1038
- ...get3(messages),
1039
- {
1040
- id: value.id,
1041
- role: value.role,
1042
- content: value.content[0].text.value
1043
- }
1044
- ]);
1045
- break;
1046
- }
1047
- case "text": {
1048
- mutateMessages(
1049
- get3(messages).map((msg, index, array) => {
1050
- if (index === array.length - 1) {
1051
- return { ...msg, content: msg.content + value };
1052
- }
1053
- return msg;
1054
- })
1055
- );
1056
- break;
1057
- }
1058
- case "data_message": {
1059
- mutateMessages([
1060
- ...get3(messages),
1061
- {
1062
- id: (_d = value.id) != null ? _d : generateId(),
1063
- role: "data",
1064
- content: "",
1065
- data: value.data
1066
- }
1067
- ]);
1068
- break;
1069
- }
1070
- case "assistant_control_data": {
1071
- threadIdStore.set(value.threadId);
1072
- mutateMessages(
1073
- get3(messages).map((msg, index, array) => {
1074
- if (index === array.length - 1) {
1075
- return { ...msg, id: value.messageId };
1076
- }
1077
- return msg;
1078
- })
1079
- );
1080
- break;
1081
- }
1082
- case "error": {
1083
- error.set(new Error(value));
1084
- break;
1085
- }
1086
- }
1087
- }
1088
- } catch (err) {
1089
- if (isAbortError(error) && ((_e = abortController == null ? void 0 : abortController.signal) == null ? void 0 : _e.aborted)) {
1090
- abortController = null;
1091
- return;
1092
- }
1093
- if (onError && err instanceof Error) {
1094
- onError(err);
1095
- }
1096
- error.set(err);
1097
- } finally {
1098
- abortController = null;
1099
- status.set("awaiting_message");
1100
- }
1101
- }
1102
- function setMessages(messages2) {
1103
- mutateMessages(messages2);
1104
- }
1105
- function stop() {
1106
- if (abortController) {
1107
- abortController.abort();
1108
- abortController = null;
1109
- }
1110
- }
1111
- async function submitMessage(event, requestOptions) {
1112
- var _a;
1113
- (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
1114
- const inputValue = get3(input);
1115
- if (!inputValue)
1116
- return;
1117
- await append({ role: "user", content: inputValue }, requestOptions);
1118
- }
1119
- return {
1120
- messages,
1121
- error,
1122
- threadId: threadIdStore,
1123
- input,
1124
- append,
1125
- submitMessage,
1126
- status,
1127
- setMessages,
1128
- stop
1129
- };
1130
- }
1131
- export {
1132
- useAssistant,
1133
- useChat,
1134
- useCompletion
1135
- };
1136
- //# sourceMappingURL=index.mjs.map