ai 2.1.26 → 2.1.28

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,25 +1,8 @@
1
1
  "use strict";
2
2
  var __defProp = Object.defineProperty;
3
- var __defProps = Object.defineProperties;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
- var __spreadValues = (a, b) => {
12
- for (var prop in b || (b = {}))
13
- if (__hasOwnProp.call(b, prop))
14
- __defNormalProp(a, prop, b[prop]);
15
- if (__getOwnPropSymbols)
16
- for (var prop of __getOwnPropSymbols(b)) {
17
- if (__propIsEnum.call(b, prop))
18
- __defNormalProp(a, prop, b[prop]);
19
- }
20
- return a;
21
- };
22
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
6
  var __export = (target, all) => {
24
7
  for (var name in all)
25
8
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -33,26 +16,6 @@ var __copyProps = (to, from, except, desc) => {
33
16
  return to;
34
17
  };
35
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
- var __async = (__this, __arguments, generator) => {
37
- return new Promise((resolve, reject) => {
38
- var fulfilled = (value) => {
39
- try {
40
- step(generator.next(value));
41
- } catch (e) {
42
- reject(e);
43
- }
44
- };
45
- var rejected = (value) => {
46
- try {
47
- step(generator.throw(value));
48
- } catch (e) {
49
- reject(e);
50
- }
51
- };
52
- var step = (x3) => x3.done ? resolve(x3.value) : Promise.resolve(x3.value).then(fulfilled, rejected);
53
- step((generator = generator.apply(__this, __arguments)).next());
54
- });
55
- };
56
19
 
57
20
  // svelte/index.ts
58
21
  var svelte_exports = {};
@@ -164,14 +127,14 @@ var q = class {
164
127
  * Removes an key-value pair from the cache.
165
128
  */
166
129
  remove(e, t) {
167
- const { broadcast: s } = __spreadValues(__spreadValues({}, L), t);
130
+ const { broadcast: s } = { ...L, ...t };
168
131
  s && this.broadcast(e, void 0), this.elements.delete(e);
169
132
  }
170
133
  /**
171
134
  * Removes all the key-value pairs from the cache.
172
135
  */
173
136
  clear(e) {
174
- const { broadcast: t } = __spreadValues(__spreadValues({}, S), e);
137
+ const { broadcast: t } = { ...S, ...e };
175
138
  if (t)
176
139
  for (const s of this.elements.keys())
177
140
  this.broadcast(s, void 0);
@@ -206,12 +169,12 @@ var q = class {
206
169
  var x = {
207
170
  cache: new q(),
208
171
  errors: new I(),
209
- fetcher: (r) => __async(void 0, null, function* () {
210
- const e = yield fetch(r);
172
+ fetcher: async (r) => {
173
+ const e = await fetch(r);
211
174
  if (!e.ok)
212
175
  throw Error("Not a 2XX response.");
213
176
  return e.json();
214
- }),
177
+ },
215
178
  fallbackData: void 0,
216
179
  loadInitialCache: true,
217
180
  revalidateOnStart: true,
@@ -235,12 +198,13 @@ var x = {
235
198
  },
236
199
  revalidateFunction: void 0
237
200
  };
238
- var E = __spreadProps(__spreadValues({}, x), {
201
+ var E = {
202
+ ...x,
239
203
  force: false
240
- });
204
+ };
241
205
  var T = {
242
206
  revalidate: true,
243
- revalidateOptions: __spreadValues({}, E),
207
+ revalidateOptions: { ...E },
244
208
  revalidateFunction: void 0
245
209
  };
246
210
  var X = {
@@ -252,7 +216,7 @@ var H = class {
252
216
  */
253
217
  constructor(e) {
254
218
  h(this, "options");
255
- this.options = __spreadValues(__spreadValues({}, x), e);
219
+ this.options = { ...x, ...e };
256
220
  }
257
221
  /**
258
222
  * Gets the cache of the SWR.
@@ -269,11 +233,9 @@ var H = class {
269
233
  /**
270
234
  * Requests the data using the provided fetcher.
271
235
  */
272
- requestData(e, t) {
273
- return __async(this, null, function* () {
274
- return yield Promise.resolve(t(e)).catch((s) => {
275
- throw this.errors.emit(e, s), s;
276
- });
236
+ async requestData(e, t) {
237
+ return await Promise.resolve(t(e)).catch((s) => {
238
+ throw this.errors.emit(e, s), s;
277
239
  });
278
240
  }
279
241
  /**
@@ -293,7 +255,7 @@ var H = class {
293
255
  * are specified, it clears all the cache keys.
294
256
  */
295
257
  clear(e, t) {
296
- const s = __spreadValues(__spreadValues({}, X), t);
258
+ const s = { ...X, ...t };
297
259
  if (e == null)
298
260
  return this.cache.clear(s);
299
261
  if (!Array.isArray(e))
@@ -304,49 +266,50 @@ var H = class {
304
266
  /**
305
267
  * Revalidates the key and mutates the cache if needed.
306
268
  */
307
- revalidate(e, t) {
308
- return __async(this, null, function* () {
309
- if (!e)
310
- throw new Error("[Revalidate] Key issue: ${key}");
311
- const { fetcher: s, dedupingInterval: i } = this.options, { force: a, fetcher: o, dedupingInterval: n } = __spreadValues(__spreadProps(__spreadValues({}, E), {
312
- fetcher: s,
313
- dedupingInterval: i
314
- }), t);
315
- if (a || !this.cache.has(e) || this.cache.has(e) && this.cache.get(e).hasExpired()) {
316
- const c2 = this.requestData(e, o), l = c2.catch(() => {
317
- });
318
- return this.cache.set(e, new O({ data: l }).expiresIn(n)), yield c2;
319
- }
320
- return this.getWait(e);
321
- });
269
+ async revalidate(e, t) {
270
+ if (!e)
271
+ throw new Error("[Revalidate] Key issue: ${key}");
272
+ const { fetcher: s, dedupingInterval: i } = this.options, { force: a, fetcher: o, dedupingInterval: n } = {
273
+ ...E,
274
+ fetcher: s,
275
+ dedupingInterval: i,
276
+ ...t
277
+ };
278
+ if (a || !this.cache.has(e) || this.cache.has(e) && this.cache.get(e).hasExpired()) {
279
+ const c2 = this.requestData(e, o), l = c2.catch(() => {
280
+ });
281
+ return this.cache.set(e, new O({ data: l }).expiresIn(n)), await c2;
282
+ }
283
+ return this.getWait(e);
322
284
  }
323
285
  /**
324
286
  * Mutates the data of a given key with a new value.
325
287
  * This is used to replace the cache contents of the
326
288
  * given key manually.
327
289
  */
328
- mutate(e, t, s) {
329
- return __async(this, null, function* () {
330
- var _a;
331
- if (!e)
332
- throw new Error("[Mutate] Key issue: ${key}");
333
- const {
334
- revalidate: i,
335
- revalidateOptions: a,
336
- revalidateFunction: o
337
- } = __spreadValues(__spreadValues({}, T), s);
338
- let n;
339
- if (typeof t == "function") {
340
- let c2;
341
- if (this.cache.has(e)) {
342
- const l = this.cache.get(e);
343
- l.isResolving() || (c2 = l.data);
344
- }
345
- n = t(c2);
346
- } else
347
- n = t;
348
- return this.cache.set(e, new O({ data: n })), i ? yield (_a = o == null ? void 0 : o(e, a)) != null ? _a : this.revalidate(e, a) : n;
349
- });
290
+ async mutate(e, t, s) {
291
+ var _a;
292
+ if (!e)
293
+ throw new Error("[Mutate] Key issue: ${key}");
294
+ const {
295
+ revalidate: i,
296
+ revalidateOptions: a,
297
+ revalidateFunction: o
298
+ } = {
299
+ ...T,
300
+ ...s
301
+ };
302
+ let n;
303
+ if (typeof t == "function") {
304
+ let c2;
305
+ if (this.cache.has(e)) {
306
+ const l = this.cache.get(e);
307
+ l.isResolving() || (c2 = l.data);
308
+ }
309
+ n = t(c2);
310
+ } else
311
+ n = t;
312
+ 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;
350
313
  }
351
314
  /**
352
315
  * Gets the data of the given key. Keep in mind
@@ -424,7 +387,13 @@ var H = class {
424
387
  reconnectWhen: W2,
425
388
  focusWhen: D2,
426
389
  revalidateFunction: d
427
- } = __spreadValues(__spreadValues({}, this.options), i), K2 = (m) => {
390
+ } = {
391
+ // Current instance options
392
+ // (includes default options)
393
+ ...this.options,
394
+ // Current call options.
395
+ ...i
396
+ }, K2 = (m) => {
428
397
  var _a;
429
398
  return (_a = d == null ? void 0 : d(this.resolveKey(e), m)) != null ? _a : this.revalidate(this.resolveKey(e), m);
430
399
  }, 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;
@@ -540,13 +509,15 @@ var O2 = class extends H {
540
509
  const o = (g) => {
541
510
  a.set(void 0), i.set(g);
542
511
  }, l = (g) => a.set(g);
543
- r || (r = this.subscribe(e, o, l, __spreadValues({
544
- loadInitialCache: true
545
- }, n)).unsubscribe);
512
+ r || (r = this.subscribe(e, o, l, {
513
+ loadInitialCache: true,
514
+ ...n
515
+ }).unsubscribe);
546
516
  }), (0, import_svelte.onDestroy)(() => r == null ? void 0 : r());
547
- const d = (o, l) => this.mutate(this.resolveKey(e), o, __spreadValues({
548
- revalidateOptions: n
549
- }, l)), u = (o) => this.revalidate(this.resolveKey(e), __spreadValues(__spreadValues({}, 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);
517
+ const d = (o, l) => this.mutate(this.resolveKey(e), o, {
518
+ revalidateOptions: n,
519
+ ...l
520
+ }), 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);
550
521
  return { data: i, error: a, mutate: d, revalidate: u, clear: f, isLoading: s, isValid: h2 };
551
522
  }
552
523
  };
@@ -570,43 +541,53 @@ function createChunkDecoder() {
570
541
  }
571
542
 
572
543
  // svelte/use-chat.ts
573
- var getStreamedResponse = (api, chatRequest, mutate, extraMetadata, previousMessages, abortControllerRef, onFinish, onResponse, sendExtraMessageFields) => __async(void 0, null, function* () {
544
+ var getStreamedResponse = async (api, chatRequest, mutate, extraMetadata, previousMessages, abortControllerRef, onFinish, onResponse, sendExtraMessageFields) => {
574
545
  var _a, _b, _c, _d;
575
546
  mutate(chatRequest.messages);
576
- const res = yield fetch(api, __spreadValues({
547
+ const res = await fetch(api, {
577
548
  method: "POST",
578
- body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
549
+ body: JSON.stringify({
579
550
  messages: sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(
580
- ({ role, content, name, function_call }) => __spreadValues(__spreadValues({
551
+ ({ role, content, name, function_call }) => ({
581
552
  role,
582
- content
583
- }, name !== void 0 && { name }), function_call !== void 0 && {
584
- function_call
553
+ content,
554
+ ...name !== void 0 && { name },
555
+ ...function_call !== void 0 && {
556
+ function_call
557
+ }
585
558
  })
586
- )
587
- }, extraMetadata.body), (_a = chatRequest.options) == null ? void 0 : _a.body), chatRequest.functions !== void 0 && {
588
- functions: chatRequest.functions
589
- }), chatRequest.function_call !== void 0 && {
590
- function_call: chatRequest.function_call
591
- })),
559
+ ),
560
+ ...extraMetadata.body,
561
+ ...(_a = chatRequest.options) == null ? void 0 : _a.body,
562
+ ...chatRequest.functions !== void 0 && {
563
+ functions: chatRequest.functions
564
+ },
565
+ ...chatRequest.function_call !== void 0 && {
566
+ function_call: chatRequest.function_call
567
+ }
568
+ }),
592
569
  credentials: extraMetadata.credentials,
593
- headers: __spreadValues(__spreadValues({}, extraMetadata.headers), (_b = chatRequest.options) == null ? void 0 : _b.headers)
594
- }, abortControllerRef !== null && {
595
- signal: abortControllerRef.signal
596
- })).catch((err) => {
570
+ headers: {
571
+ ...extraMetadata.headers,
572
+ ...(_b = chatRequest.options) == null ? void 0 : _b.headers
573
+ },
574
+ ...abortControllerRef !== null && {
575
+ signal: abortControllerRef.signal
576
+ }
577
+ }).catch((err) => {
597
578
  mutate(previousMessages);
598
579
  throw err;
599
580
  });
600
581
  if (onResponse) {
601
582
  try {
602
- yield onResponse(res);
583
+ await onResponse(res);
603
584
  } catch (err) {
604
585
  throw err;
605
586
  }
606
587
  }
607
588
  if (!res.ok) {
608
589
  mutate(previousMessages);
609
- throw new Error((yield res.text()) || "Failed to fetch the chat response.");
590
+ throw new Error(await res.text() || "Failed to fetch the chat response.");
610
591
  }
611
592
  if (!res.body) {
612
593
  throw new Error("The response body is empty.");
@@ -623,14 +604,14 @@ var getStreamedResponse = (api, chatRequest, mutate, extraMetadata, previousMess
623
604
  role: "assistant"
624
605
  };
625
606
  while (true) {
626
- const { done, value } = yield reader.read();
607
+ const { done, value } = await reader.read();
627
608
  if (done) {
628
609
  break;
629
610
  }
630
611
  streamedResponse += decode(value);
631
612
  const functionStart = streamedResponse.indexOf("{");
632
613
  if (functionStart !== -1) {
633
- const matches = new RegExp('(.*?)(?:({"function_call".*?}})(.*))?$', "gs").exec(
614
+ const matches = /(.*?)(?:({"function_call".*?}})(.*))?$/gs.exec(
634
615
  streamedResponse
635
616
  );
636
617
  responseMessage.content = `${(_c = matches == null ? void 0 : matches[1]) != null ? _c : ""}${(_d = matches == null ? void 0 : matches[3]) != null ? _d : ""}`;
@@ -638,7 +619,7 @@ var getStreamedResponse = (api, chatRequest, mutate, extraMetadata, previousMess
638
619
  } else {
639
620
  responseMessage.content = streamedResponse;
640
621
  }
641
- mutate([...chatRequest.messages, __spreadValues({}, responseMessage)]);
622
+ mutate([...chatRequest.messages, { ...responseMessage }]);
642
623
  if (abortControllerRef === null) {
643
624
  reader.cancel();
644
625
  break;
@@ -647,13 +628,13 @@ var getStreamedResponse = (api, chatRequest, mutate, extraMetadata, previousMess
647
628
  if (typeof responseMessage.function_call === "string") {
648
629
  const parsedFunctionCall = JSON.parse(responseMessage.function_call).function_call;
649
630
  responseMessage.function_call = parsedFunctionCall;
650
- mutate([...chatRequest.messages, __spreadValues({}, responseMessage)]);
631
+ mutate([...chatRequest.messages, { ...responseMessage }]);
651
632
  }
652
633
  if (onFinish) {
653
634
  onFinish(responseMessage);
654
635
  }
655
636
  return responseMessage;
656
- });
637
+ };
657
638
  var uniqueId = 0;
658
639
  var store = {};
659
640
  function useChat({
@@ -672,10 +653,15 @@ function useChat({
672
653
  } = {}) {
673
654
  const chatId = id || `chat-${uniqueId++}`;
674
655
  const key = `${api}|${chatId}`;
675
- const { data, mutate: originalMutate } = F2(key, {
656
+ const {
657
+ data,
658
+ mutate: originalMutate,
659
+ isLoading: isSWRLoading
660
+ } = F2(key, {
676
661
  fetcher: () => store[key] || initialMessages,
677
662
  fallbackData: initialMessages
678
663
  });
664
+ const loading = (0, import_store.writable)(false);
679
665
  data.set(initialMessages);
680
666
  const mutate = (data2) => {
681
667
  store[key] = data2;
@@ -689,83 +675,86 @@ function useChat({
689
675
  body
690
676
  };
691
677
  const error = (0, import_store.writable)(void 0);
692
- const isLoading = (0, import_store.writable)(false);
693
- function triggerRequest(chatRequest) {
694
- return __async(this, null, function* () {
695
- try {
696
- isLoading.set(true);
697
- abortController = new AbortController();
698
- while (true) {
699
- const streamedResponseMessage = yield getStreamedResponse(
700
- api,
701
- chatRequest,
702
- mutate,
703
- extraMetadata,
704
- (0, import_store.get)(messages),
705
- abortController,
706
- onFinish,
707
- onResponse,
708
- sendExtraMessageFields
709
- );
710
- if (streamedResponseMessage.function_call === void 0 || typeof streamedResponseMessage.function_call === "string") {
678
+ async function triggerRequest(chatRequest) {
679
+ try {
680
+ loading.set(true);
681
+ abortController = new AbortController();
682
+ while (true) {
683
+ const streamedResponseMessage = await getStreamedResponse(
684
+ api,
685
+ chatRequest,
686
+ mutate,
687
+ extraMetadata,
688
+ (0, import_store.get)(messages),
689
+ abortController,
690
+ onFinish,
691
+ onResponse,
692
+ sendExtraMessageFields
693
+ );
694
+ if (streamedResponseMessage.function_call === void 0 || typeof streamedResponseMessage.function_call === "string") {
695
+ break;
696
+ }
697
+ if (experimental_onFunctionCall) {
698
+ const functionCall = streamedResponseMessage.function_call;
699
+ const functionCallResponse = await experimental_onFunctionCall((0, import_store.get)(messages), functionCall);
700
+ if (functionCallResponse === void 0)
711
701
  break;
712
- }
713
- if (experimental_onFunctionCall) {
714
- const functionCall = streamedResponseMessage.function_call;
715
- const functionCallResponse = yield experimental_onFunctionCall((0, import_store.get)(messages), functionCall);
716
- if (functionCallResponse === void 0)
717
- break;
718
- chatRequest = functionCallResponse;
719
- }
702
+ chatRequest = functionCallResponse;
720
703
  }
704
+ }
705
+ abortController = null;
706
+ return null;
707
+ } catch (err) {
708
+ if (err.name === "AbortError") {
721
709
  abortController = null;
722
710
  return null;
723
- } catch (err) {
724
- if (err.name === "AbortError") {
725
- abortController = null;
726
- return null;
727
- }
728
- if (onError && err instanceof Error) {
729
- onError(err);
730
- }
731
- error.set(err);
732
- } finally {
733
- isLoading.set(false);
734
711
  }
735
- });
712
+ if (onError && err instanceof Error) {
713
+ onError(err);
714
+ }
715
+ error.set(err);
716
+ } finally {
717
+ loading.set(false);
718
+ }
736
719
  }
737
- const append = (_0, ..._1) => __async(this, [_0, ..._1], function* (message, { options, functions, function_call } = {}) {
720
+ const append = async (message, { options, functions, function_call } = {}) => {
738
721
  if (!message.id) {
739
722
  message.id = nanoid();
740
723
  }
741
- const chatRequest = __spreadValues(__spreadValues({
724
+ const chatRequest = {
742
725
  messages: (0, import_store.get)(messages).concat(message),
743
- options
744
- }, functions !== void 0 && { functions }), function_call !== void 0 && { function_call });
726
+ options,
727
+ ...functions !== void 0 && { functions },
728
+ ...function_call !== void 0 && { function_call }
729
+ };
745
730
  return triggerRequest(chatRequest);
746
- });
747
- const reload = (..._0) => __async(this, [..._0], function* ({
731
+ };
732
+ const reload = async ({
748
733
  options,
749
734
  functions,
750
735
  function_call
751
- } = {}) {
736
+ } = {}) => {
752
737
  const messagesSnapshot = (0, import_store.get)(messages);
753
738
  if (messagesSnapshot.length === 0)
754
739
  return null;
755
740
  const lastMessage = messagesSnapshot.at(-1);
756
741
  if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant") {
757
- const chatRequest2 = __spreadValues(__spreadValues({
742
+ const chatRequest2 = {
758
743
  messages: messagesSnapshot.slice(0, -1),
759
- options
760
- }, functions !== void 0 && { functions }), function_call !== void 0 && { function_call });
744
+ options,
745
+ ...functions !== void 0 && { functions },
746
+ ...function_call !== void 0 && { function_call }
747
+ };
761
748
  return triggerRequest(chatRequest2);
762
749
  }
763
- const chatRequest = __spreadValues(__spreadValues({
750
+ const chatRequest = {
764
751
  messages: messagesSnapshot,
765
- options
766
- }, functions !== void 0 && { functions }), function_call !== void 0 && { function_call });
752
+ options,
753
+ ...functions !== void 0 && { functions },
754
+ ...function_call !== void 0 && { function_call }
755
+ };
767
756
  return triggerRequest(chatRequest);
768
- });
757
+ };
769
758
  const stop = () => {
770
759
  if (abortController) {
771
760
  abortController.abort();
@@ -800,7 +789,7 @@ function useChat({
800
789
  setMessages,
801
790
  input,
802
791
  handleSubmit,
803
- isLoading
792
+ isLoading: isSWRLoading || loading
804
793
  };
805
794
  }
806
795
 
@@ -822,10 +811,15 @@ function useCompletion({
822
811
  } = {}) {
823
812
  const completionId = id || `completion-${uniqueId2++}`;
824
813
  const key = `${api}|${completionId}`;
825
- const { data, mutate: originalMutate } = F2(key, {
814
+ const {
815
+ data,
816
+ mutate: originalMutate,
817
+ isLoading: isSWRLoading
818
+ } = F2(key, {
826
819
  fetcher: () => store2[key] || initialCompletion,
827
820
  fallbackData: initialCompletion
828
821
  });
822
+ const loading = (0, import_store2.writable)(false);
829
823
  data.set(initialCompletion);
830
824
  const mutate = (data2) => {
831
825
  store2[key] = data2;
@@ -833,77 +827,79 @@ function useCompletion({
833
827
  };
834
828
  const completion = data;
835
829
  const error = (0, import_store2.writable)(void 0);
836
- const isLoading = (0, import_store2.writable)(false);
837
830
  let abortController = null;
838
- function triggerRequest(prompt, options) {
839
- return __async(this, null, function* () {
840
- try {
841
- isLoading.set(true);
842
- abortController = new AbortController();
843
- mutate("");
844
- const res = yield fetch(api, {
845
- method: "POST",
846
- body: JSON.stringify(__spreadValues(__spreadValues({
847
- prompt
848
- }, body), options == null ? void 0 : options.body)),
849
- headers: __spreadValues(__spreadValues({}, headers), options == null ? void 0 : options.headers),
850
- signal: abortController.signal,
851
- credentials
852
- }).catch((err) => {
831
+ async function triggerRequest(prompt, options) {
832
+ try {
833
+ loading.set(true);
834
+ abortController = new AbortController();
835
+ mutate("");
836
+ const res = await fetch(api, {
837
+ method: "POST",
838
+ body: JSON.stringify({
839
+ prompt,
840
+ ...body,
841
+ ...options == null ? void 0 : options.body
842
+ }),
843
+ headers: {
844
+ ...headers,
845
+ ...options == null ? void 0 : options.headers
846
+ },
847
+ signal: abortController.signal,
848
+ credentials
849
+ }).catch((err) => {
850
+ throw err;
851
+ });
852
+ if (onResponse) {
853
+ try {
854
+ await onResponse(res);
855
+ } catch (err) {
853
856
  throw err;
854
- });
855
- if (onResponse) {
856
- try {
857
- yield onResponse(res);
858
- } catch (err) {
859
- throw err;
860
- }
861
- }
862
- if (!res.ok) {
863
- throw new Error(
864
- (yield res.text()) || "Failed to fetch the chat response."
865
- );
866
857
  }
867
- if (!res.body) {
868
- throw new Error("The response body is empty.");
869
- }
870
- let result = "";
871
- const reader = res.body.getReader();
872
- const decoder = createChunkDecoder();
873
- while (true) {
874
- const { done, value } = yield reader.read();
875
- if (done) {
876
- break;
877
- }
878
- result += decoder(value);
879
- mutate(result);
880
- if (abortController === null) {
881
- reader.cancel();
882
- break;
883
- }
858
+ }
859
+ if (!res.ok) {
860
+ throw new Error(
861
+ await res.text() || "Failed to fetch the chat response."
862
+ );
863
+ }
864
+ if (!res.body) {
865
+ throw new Error("The response body is empty.");
866
+ }
867
+ let result = "";
868
+ const reader = res.body.getReader();
869
+ const decoder = createChunkDecoder();
870
+ while (true) {
871
+ const { done, value } = await reader.read();
872
+ if (done) {
873
+ break;
884
874
  }
885
- if (onFinish) {
886
- onFinish(prompt, result);
875
+ result += decoder(value);
876
+ mutate(result);
877
+ if (abortController === null) {
878
+ reader.cancel();
879
+ break;
887
880
  }
881
+ }
882
+ if (onFinish) {
883
+ onFinish(prompt, result);
884
+ }
885
+ abortController = null;
886
+ return result;
887
+ } catch (err) {
888
+ if (err.name === "AbortError") {
888
889
  abortController = null;
889
- return result;
890
- } catch (err) {
891
- if (err.name === "AbortError") {
892
- abortController = null;
893
- return null;
894
- }
895
- if (onError && error instanceof Error) {
896
- onError(error);
897
- }
898
- error.set(err);
899
- } finally {
900
- isLoading.set(false);
890
+ return null;
901
891
  }
902
- });
892
+ if (onError && error instanceof Error) {
893
+ onError(error);
894
+ }
895
+ error.set(err);
896
+ } finally {
897
+ loading.set(false);
898
+ }
903
899
  }
904
- const complete = (prompt, options) => __async(this, null, function* () {
900
+ const complete = async (prompt, options) => {
905
901
  return triggerRequest(prompt, options);
906
- });
902
+ };
907
903
  const stop = () => {
908
904
  if (abortController) {
909
905
  abortController.abort();
@@ -929,7 +925,7 @@ function useCompletion({
929
925
  setCompletion,
930
926
  input,
931
927
  handleSubmit,
932
- isLoading
928
+ isLoading: isSWRLoading || loading
933
929
  };
934
930
  }
935
931
  // Annotate the CommonJS export names for ESM import in node: