ai 3.4.33 → 4.0.0-canary.1

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