ai 2.1.26 → 2.1.27

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,43 +1,3 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __async = (__this, __arguments, generator) => {
21
- return new Promise((resolve, reject) => {
22
- var fulfilled = (value) => {
23
- try {
24
- step(generator.next(value));
25
- } catch (e) {
26
- reject(e);
27
- }
28
- };
29
- var rejected = (value) => {
30
- try {
31
- step(generator.throw(value));
32
- } catch (e) {
33
- reject(e);
34
- }
35
- };
36
- var step = (x3) => x3.done ? resolve(x3.value) : Promise.resolve(x3.value).then(fulfilled, rejected);
37
- step((generator = generator.apply(__this, __arguments)).next());
38
- });
39
- };
40
-
41
1
  // svelte/use-chat.ts
42
2
  import { get, writable } from "svelte/store";
43
3
 
@@ -140,14 +100,14 @@ var q = class {
140
100
  * Removes an key-value pair from the cache.
141
101
  */
142
102
  remove(e, t) {
143
- const { broadcast: s } = __spreadValues(__spreadValues({}, L), t);
103
+ const { broadcast: s } = { ...L, ...t };
144
104
  s && this.broadcast(e, void 0), this.elements.delete(e);
145
105
  }
146
106
  /**
147
107
  * Removes all the key-value pairs from the cache.
148
108
  */
149
109
  clear(e) {
150
- const { broadcast: t } = __spreadValues(__spreadValues({}, S), e);
110
+ const { broadcast: t } = { ...S, ...e };
151
111
  if (t)
152
112
  for (const s of this.elements.keys())
153
113
  this.broadcast(s, void 0);
@@ -182,12 +142,12 @@ var q = class {
182
142
  var x = {
183
143
  cache: new q(),
184
144
  errors: new I(),
185
- fetcher: (r) => __async(void 0, null, function* () {
186
- const e = yield fetch(r);
145
+ fetcher: async (r) => {
146
+ const e = await fetch(r);
187
147
  if (!e.ok)
188
148
  throw Error("Not a 2XX response.");
189
149
  return e.json();
190
- }),
150
+ },
191
151
  fallbackData: void 0,
192
152
  loadInitialCache: true,
193
153
  revalidateOnStart: true,
@@ -211,12 +171,13 @@ var x = {
211
171
  },
212
172
  revalidateFunction: void 0
213
173
  };
214
- var E = __spreadProps(__spreadValues({}, x), {
174
+ var E = {
175
+ ...x,
215
176
  force: false
216
- });
177
+ };
217
178
  var T = {
218
179
  revalidate: true,
219
- revalidateOptions: __spreadValues({}, E),
180
+ revalidateOptions: { ...E },
220
181
  revalidateFunction: void 0
221
182
  };
222
183
  var X = {
@@ -228,7 +189,7 @@ var H = class {
228
189
  */
229
190
  constructor(e) {
230
191
  h(this, "options");
231
- this.options = __spreadValues(__spreadValues({}, x), e);
192
+ this.options = { ...x, ...e };
232
193
  }
233
194
  /**
234
195
  * Gets the cache of the SWR.
@@ -245,11 +206,9 @@ var H = class {
245
206
  /**
246
207
  * Requests the data using the provided fetcher.
247
208
  */
248
- requestData(e, t) {
249
- return __async(this, null, function* () {
250
- return yield Promise.resolve(t(e)).catch((s) => {
251
- throw this.errors.emit(e, s), s;
252
- });
209
+ async requestData(e, t) {
210
+ return await Promise.resolve(t(e)).catch((s) => {
211
+ throw this.errors.emit(e, s), s;
253
212
  });
254
213
  }
255
214
  /**
@@ -269,7 +228,7 @@ var H = class {
269
228
  * are specified, it clears all the cache keys.
270
229
  */
271
230
  clear(e, t) {
272
- const s = __spreadValues(__spreadValues({}, X), t);
231
+ const s = { ...X, ...t };
273
232
  if (e == null)
274
233
  return this.cache.clear(s);
275
234
  if (!Array.isArray(e))
@@ -280,49 +239,50 @@ var H = class {
280
239
  /**
281
240
  * Revalidates the key and mutates the cache if needed.
282
241
  */
283
- revalidate(e, t) {
284
- return __async(this, null, function* () {
285
- if (!e)
286
- throw new Error("[Revalidate] Key issue: ${key}");
287
- const { fetcher: s, dedupingInterval: i } = this.options, { force: a, fetcher: o, dedupingInterval: n } = __spreadValues(__spreadProps(__spreadValues({}, E), {
288
- fetcher: s,
289
- dedupingInterval: i
290
- }), t);
291
- if (a || !this.cache.has(e) || this.cache.has(e) && this.cache.get(e).hasExpired()) {
292
- const c2 = this.requestData(e, o), l = c2.catch(() => {
293
- });
294
- return this.cache.set(e, new O({ data: l }).expiresIn(n)), yield c2;
295
- }
296
- return this.getWait(e);
297
- });
242
+ async revalidate(e, t) {
243
+ if (!e)
244
+ throw new Error("[Revalidate] Key issue: ${key}");
245
+ const { fetcher: s, dedupingInterval: i } = this.options, { force: a, fetcher: o, dedupingInterval: n } = {
246
+ ...E,
247
+ fetcher: s,
248
+ dedupingInterval: i,
249
+ ...t
250
+ };
251
+ if (a || !this.cache.has(e) || this.cache.has(e) && this.cache.get(e).hasExpired()) {
252
+ const c2 = this.requestData(e, o), l = c2.catch(() => {
253
+ });
254
+ return this.cache.set(e, new O({ data: l }).expiresIn(n)), await c2;
255
+ }
256
+ return this.getWait(e);
298
257
  }
299
258
  /**
300
259
  * Mutates the data of a given key with a new value.
301
260
  * This is used to replace the cache contents of the
302
261
  * given key manually.
303
262
  */
304
- mutate(e, t, s) {
305
- return __async(this, null, function* () {
306
- var _a;
307
- if (!e)
308
- throw new Error("[Mutate] Key issue: ${key}");
309
- const {
310
- revalidate: i,
311
- revalidateOptions: a,
312
- revalidateFunction: o
313
- } = __spreadValues(__spreadValues({}, T), s);
314
- let n;
315
- if (typeof t == "function") {
316
- let c2;
317
- if (this.cache.has(e)) {
318
- const l = this.cache.get(e);
319
- l.isResolving() || (c2 = l.data);
320
- }
321
- n = t(c2);
322
- } else
323
- n = t;
324
- 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;
325
- });
263
+ async mutate(e, t, s) {
264
+ var _a;
265
+ if (!e)
266
+ throw new Error("[Mutate] Key issue: ${key}");
267
+ const {
268
+ revalidate: i,
269
+ revalidateOptions: a,
270
+ revalidateFunction: o
271
+ } = {
272
+ ...T,
273
+ ...s
274
+ };
275
+ let n;
276
+ if (typeof t == "function") {
277
+ let c2;
278
+ if (this.cache.has(e)) {
279
+ const l = this.cache.get(e);
280
+ l.isResolving() || (c2 = l.data);
281
+ }
282
+ n = t(c2);
283
+ } else
284
+ n = t;
285
+ 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;
326
286
  }
327
287
  /**
328
288
  * Gets the data of the given key. Keep in mind
@@ -400,7 +360,13 @@ var H = class {
400
360
  reconnectWhen: W2,
401
361
  focusWhen: D2,
402
362
  revalidateFunction: d
403
- } = __spreadValues(__spreadValues({}, this.options), i), K2 = (m) => {
363
+ } = {
364
+ // Current instance options
365
+ // (includes default options)
366
+ ...this.options,
367
+ // Current call options.
368
+ ...i
369
+ }, K2 = (m) => {
404
370
  var _a;
405
371
  return (_a = d == null ? void 0 : d(this.resolveKey(e), m)) != null ? _a : this.revalidate(this.resolveKey(e), m);
406
372
  }, 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;
@@ -516,13 +482,15 @@ var O2 = class extends H {
516
482
  const o = (g) => {
517
483
  a.set(void 0), i.set(g);
518
484
  }, l = (g) => a.set(g);
519
- r || (r = this.subscribe(e, o, l, __spreadValues({
520
- loadInitialCache: true
521
- }, n)).unsubscribe);
485
+ r || (r = this.subscribe(e, o, l, {
486
+ loadInitialCache: true,
487
+ ...n
488
+ }).unsubscribe);
522
489
  }), E2(() => r == null ? void 0 : r());
523
- const d = (o, l) => this.mutate(this.resolveKey(e), o, __spreadValues({
524
- revalidateOptions: n
525
- }, 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);
490
+ const d = (o, l) => this.mutate(this.resolveKey(e), o, {
491
+ revalidateOptions: n,
492
+ ...l
493
+ }), 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);
526
494
  return { data: i, error: a, mutate: d, revalidate: u, clear: f, isLoading: s, isValid: h2 };
527
495
  }
528
496
  };
@@ -546,43 +514,53 @@ function createChunkDecoder() {
546
514
  }
547
515
 
548
516
  // svelte/use-chat.ts
549
- var getStreamedResponse = (api, chatRequest, mutate, extraMetadata, previousMessages, abortControllerRef, onFinish, onResponse, sendExtraMessageFields) => __async(void 0, null, function* () {
517
+ var getStreamedResponse = async (api, chatRequest, mutate, extraMetadata, previousMessages, abortControllerRef, onFinish, onResponse, sendExtraMessageFields) => {
550
518
  var _a, _b, _c, _d;
551
519
  mutate(chatRequest.messages);
552
- const res = yield fetch(api, __spreadValues({
520
+ const res = await fetch(api, {
553
521
  method: "POST",
554
- body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
522
+ body: JSON.stringify({
555
523
  messages: sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(
556
- ({ role, content, name, function_call }) => __spreadValues(__spreadValues({
524
+ ({ role, content, name, function_call }) => ({
557
525
  role,
558
- content
559
- }, name !== void 0 && { name }), function_call !== void 0 && {
560
- function_call
526
+ content,
527
+ ...name !== void 0 && { name },
528
+ ...function_call !== void 0 && {
529
+ function_call
530
+ }
561
531
  })
562
- )
563
- }, extraMetadata.body), (_a = chatRequest.options) == null ? void 0 : _a.body), chatRequest.functions !== void 0 && {
564
- functions: chatRequest.functions
565
- }), chatRequest.function_call !== void 0 && {
566
- function_call: chatRequest.function_call
567
- })),
532
+ ),
533
+ ...extraMetadata.body,
534
+ ...(_a = chatRequest.options) == null ? void 0 : _a.body,
535
+ ...chatRequest.functions !== void 0 && {
536
+ functions: chatRequest.functions
537
+ },
538
+ ...chatRequest.function_call !== void 0 && {
539
+ function_call: chatRequest.function_call
540
+ }
541
+ }),
568
542
  credentials: extraMetadata.credentials,
569
- headers: __spreadValues(__spreadValues({}, extraMetadata.headers), (_b = chatRequest.options) == null ? void 0 : _b.headers)
570
- }, abortControllerRef !== null && {
571
- signal: abortControllerRef.signal
572
- })).catch((err) => {
543
+ headers: {
544
+ ...extraMetadata.headers,
545
+ ...(_b = chatRequest.options) == null ? void 0 : _b.headers
546
+ },
547
+ ...abortControllerRef !== null && {
548
+ signal: abortControllerRef.signal
549
+ }
550
+ }).catch((err) => {
573
551
  mutate(previousMessages);
574
552
  throw err;
575
553
  });
576
554
  if (onResponse) {
577
555
  try {
578
- yield onResponse(res);
556
+ await onResponse(res);
579
557
  } catch (err) {
580
558
  throw err;
581
559
  }
582
560
  }
583
561
  if (!res.ok) {
584
562
  mutate(previousMessages);
585
- throw new Error((yield res.text()) || "Failed to fetch the chat response.");
563
+ throw new Error(await res.text() || "Failed to fetch the chat response.");
586
564
  }
587
565
  if (!res.body) {
588
566
  throw new Error("The response body is empty.");
@@ -599,14 +577,14 @@ var getStreamedResponse = (api, chatRequest, mutate, extraMetadata, previousMess
599
577
  role: "assistant"
600
578
  };
601
579
  while (true) {
602
- const { done, value } = yield reader.read();
580
+ const { done, value } = await reader.read();
603
581
  if (done) {
604
582
  break;
605
583
  }
606
584
  streamedResponse += decode(value);
607
585
  const functionStart = streamedResponse.indexOf("{");
608
586
  if (functionStart !== -1) {
609
- const matches = new RegExp('(.*?)(?:({"function_call".*?}})(.*))?$', "gs").exec(
587
+ const matches = /(.*?)(?:({"function_call".*?}})(.*))?$/gs.exec(
610
588
  streamedResponse
611
589
  );
612
590
  responseMessage.content = `${(_c = matches == null ? void 0 : matches[1]) != null ? _c : ""}${(_d = matches == null ? void 0 : matches[3]) != null ? _d : ""}`;
@@ -614,7 +592,7 @@ var getStreamedResponse = (api, chatRequest, mutate, extraMetadata, previousMess
614
592
  } else {
615
593
  responseMessage.content = streamedResponse;
616
594
  }
617
- mutate([...chatRequest.messages, __spreadValues({}, responseMessage)]);
595
+ mutate([...chatRequest.messages, { ...responseMessage }]);
618
596
  if (abortControllerRef === null) {
619
597
  reader.cancel();
620
598
  break;
@@ -623,13 +601,13 @@ var getStreamedResponse = (api, chatRequest, mutate, extraMetadata, previousMess
623
601
  if (typeof responseMessage.function_call === "string") {
624
602
  const parsedFunctionCall = JSON.parse(responseMessage.function_call).function_call;
625
603
  responseMessage.function_call = parsedFunctionCall;
626
- mutate([...chatRequest.messages, __spreadValues({}, responseMessage)]);
604
+ mutate([...chatRequest.messages, { ...responseMessage }]);
627
605
  }
628
606
  if (onFinish) {
629
607
  onFinish(responseMessage);
630
608
  }
631
609
  return responseMessage;
632
- });
610
+ };
633
611
  var uniqueId = 0;
634
612
  var store = {};
635
613
  function useChat({
@@ -652,6 +630,9 @@ function useChat({
652
630
  fetcher: () => store[key] || initialMessages,
653
631
  fallbackData: initialMessages
654
632
  });
633
+ const { data: isLoading, mutate: mutateLoading } = F2(
634
+ `${key}-loading`
635
+ );
655
636
  data.set(initialMessages);
656
637
  const mutate = (data2) => {
657
638
  store[key] = data2;
@@ -665,83 +646,86 @@ function useChat({
665
646
  body
666
647
  };
667
648
  const error = writable(void 0);
668
- const isLoading = writable(false);
669
- function triggerRequest(chatRequest) {
670
- return __async(this, null, function* () {
671
- try {
672
- isLoading.set(true);
673
- abortController = new AbortController();
674
- while (true) {
675
- const streamedResponseMessage = yield getStreamedResponse(
676
- api,
677
- chatRequest,
678
- mutate,
679
- extraMetadata,
680
- get(messages),
681
- abortController,
682
- onFinish,
683
- onResponse,
684
- sendExtraMessageFields
685
- );
686
- if (streamedResponseMessage.function_call === void 0 || typeof streamedResponseMessage.function_call === "string") {
649
+ async function triggerRequest(chatRequest) {
650
+ try {
651
+ mutateLoading(true);
652
+ abortController = new AbortController();
653
+ while (true) {
654
+ const streamedResponseMessage = await getStreamedResponse(
655
+ api,
656
+ chatRequest,
657
+ mutate,
658
+ extraMetadata,
659
+ get(messages),
660
+ abortController,
661
+ onFinish,
662
+ onResponse,
663
+ sendExtraMessageFields
664
+ );
665
+ if (streamedResponseMessage.function_call === void 0 || typeof streamedResponseMessage.function_call === "string") {
666
+ break;
667
+ }
668
+ if (experimental_onFunctionCall) {
669
+ const functionCall = streamedResponseMessage.function_call;
670
+ const functionCallResponse = await experimental_onFunctionCall(get(messages), functionCall);
671
+ if (functionCallResponse === void 0)
687
672
  break;
688
- }
689
- if (experimental_onFunctionCall) {
690
- const functionCall = streamedResponseMessage.function_call;
691
- const functionCallResponse = yield experimental_onFunctionCall(get(messages), functionCall);
692
- if (functionCallResponse === void 0)
693
- break;
694
- chatRequest = functionCallResponse;
695
- }
673
+ chatRequest = functionCallResponse;
696
674
  }
675
+ }
676
+ abortController = null;
677
+ return null;
678
+ } catch (err) {
679
+ if (err.name === "AbortError") {
697
680
  abortController = null;
698
681
  return null;
699
- } catch (err) {
700
- if (err.name === "AbortError") {
701
- abortController = null;
702
- return null;
703
- }
704
- if (onError && err instanceof Error) {
705
- onError(err);
706
- }
707
- error.set(err);
708
- } finally {
709
- isLoading.set(false);
710
682
  }
711
- });
683
+ if (onError && err instanceof Error) {
684
+ onError(err);
685
+ }
686
+ error.set(err);
687
+ } finally {
688
+ mutateLoading(false);
689
+ }
712
690
  }
713
- const append = (_0, ..._1) => __async(this, [_0, ..._1], function* (message, { options, functions, function_call } = {}) {
691
+ const append = async (message, { options, functions, function_call } = {}) => {
714
692
  if (!message.id) {
715
693
  message.id = nanoid();
716
694
  }
717
- const chatRequest = __spreadValues(__spreadValues({
695
+ const chatRequest = {
718
696
  messages: get(messages).concat(message),
719
- options
720
- }, functions !== void 0 && { functions }), function_call !== void 0 && { function_call });
697
+ options,
698
+ ...functions !== void 0 && { functions },
699
+ ...function_call !== void 0 && { function_call }
700
+ };
721
701
  return triggerRequest(chatRequest);
722
- });
723
- const reload = (..._0) => __async(this, [..._0], function* ({
702
+ };
703
+ const reload = async ({
724
704
  options,
725
705
  functions,
726
706
  function_call
727
- } = {}) {
707
+ } = {}) => {
728
708
  const messagesSnapshot = get(messages);
729
709
  if (messagesSnapshot.length === 0)
730
710
  return null;
731
711
  const lastMessage = messagesSnapshot.at(-1);
732
712
  if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant") {
733
- const chatRequest2 = __spreadValues(__spreadValues({
713
+ const chatRequest2 = {
734
714
  messages: messagesSnapshot.slice(0, -1),
735
- options
736
- }, functions !== void 0 && { functions }), function_call !== void 0 && { function_call });
715
+ options,
716
+ ...functions !== void 0 && { functions },
717
+ ...function_call !== void 0 && { function_call }
718
+ };
737
719
  return triggerRequest(chatRequest2);
738
720
  }
739
- const chatRequest = __spreadValues(__spreadValues({
721
+ const chatRequest = {
740
722
  messages: messagesSnapshot,
741
- options
742
- }, functions !== void 0 && { functions }), function_call !== void 0 && { function_call });
723
+ options,
724
+ ...functions !== void 0 && { functions },
725
+ ...function_call !== void 0 && { function_call }
726
+ };
743
727
  return triggerRequest(chatRequest);
744
- });
728
+ };
745
729
  const stop = () => {
746
730
  if (abortController) {
747
731
  abortController.abort();
@@ -798,10 +782,17 @@ function useCompletion({
798
782
  } = {}) {
799
783
  const completionId = id || `completion-${uniqueId2++}`;
800
784
  const key = `${api}|${completionId}`;
801
- const { data, mutate: originalMutate } = F2(key, {
785
+ const {
786
+ data,
787
+ mutate: originalMutate,
788
+ isLoading: isSWRLoading
789
+ } = F2(key, {
802
790
  fetcher: () => store2[key] || initialCompletion,
803
791
  fallbackData: initialCompletion
804
792
  });
793
+ const { data: isLoading, mutate: mutateLoading } = F2(
794
+ `${key}-loading`
795
+ );
805
796
  data.set(initialCompletion);
806
797
  const mutate = (data2) => {
807
798
  store2[key] = data2;
@@ -809,77 +800,79 @@ function useCompletion({
809
800
  };
810
801
  const completion = data;
811
802
  const error = writable2(void 0);
812
- const isLoading = writable2(false);
813
803
  let abortController = null;
814
- function triggerRequest(prompt, options) {
815
- return __async(this, null, function* () {
816
- try {
817
- isLoading.set(true);
818
- abortController = new AbortController();
819
- mutate("");
820
- const res = yield fetch(api, {
821
- method: "POST",
822
- body: JSON.stringify(__spreadValues(__spreadValues({
823
- prompt
824
- }, body), options == null ? void 0 : options.body)),
825
- headers: __spreadValues(__spreadValues({}, headers), options == null ? void 0 : options.headers),
826
- signal: abortController.signal,
827
- credentials
828
- }).catch((err) => {
804
+ async function triggerRequest(prompt, options) {
805
+ try {
806
+ mutateLoading(true);
807
+ abortController = new AbortController();
808
+ mutate("");
809
+ const res = await fetch(api, {
810
+ method: "POST",
811
+ body: JSON.stringify({
812
+ prompt,
813
+ ...body,
814
+ ...options == null ? void 0 : options.body
815
+ }),
816
+ headers: {
817
+ ...headers,
818
+ ...options == null ? void 0 : options.headers
819
+ },
820
+ signal: abortController.signal,
821
+ credentials
822
+ }).catch((err) => {
823
+ throw err;
824
+ });
825
+ if (onResponse) {
826
+ try {
827
+ await onResponse(res);
828
+ } catch (err) {
829
829
  throw err;
830
- });
831
- if (onResponse) {
832
- try {
833
- yield onResponse(res);
834
- } catch (err) {
835
- throw err;
836
- }
837
- }
838
- if (!res.ok) {
839
- throw new Error(
840
- (yield res.text()) || "Failed to fetch the chat response."
841
- );
842
830
  }
843
- if (!res.body) {
844
- throw new Error("The response body is empty.");
845
- }
846
- let result = "";
847
- const reader = res.body.getReader();
848
- const decoder = createChunkDecoder();
849
- while (true) {
850
- const { done, value } = yield reader.read();
851
- if (done) {
852
- break;
853
- }
854
- result += decoder(value);
855
- mutate(result);
856
- if (abortController === null) {
857
- reader.cancel();
858
- break;
859
- }
831
+ }
832
+ if (!res.ok) {
833
+ throw new Error(
834
+ await res.text() || "Failed to fetch the chat response."
835
+ );
836
+ }
837
+ if (!res.body) {
838
+ throw new Error("The response body is empty.");
839
+ }
840
+ let result = "";
841
+ const reader = res.body.getReader();
842
+ const decoder = createChunkDecoder();
843
+ while (true) {
844
+ const { done, value } = await reader.read();
845
+ if (done) {
846
+ break;
860
847
  }
861
- if (onFinish) {
862
- onFinish(prompt, result);
848
+ result += decoder(value);
849
+ mutate(result);
850
+ if (abortController === null) {
851
+ reader.cancel();
852
+ break;
863
853
  }
854
+ }
855
+ if (onFinish) {
856
+ onFinish(prompt, result);
857
+ }
858
+ abortController = null;
859
+ return result;
860
+ } catch (err) {
861
+ if (err.name === "AbortError") {
864
862
  abortController = null;
865
- return result;
866
- } catch (err) {
867
- if (err.name === "AbortError") {
868
- abortController = null;
869
- return null;
870
- }
871
- if (onError && error instanceof Error) {
872
- onError(error);
873
- }
874
- error.set(err);
875
- } finally {
876
- isLoading.set(false);
863
+ return null;
877
864
  }
878
- });
865
+ if (onError && error instanceof Error) {
866
+ onError(error);
867
+ }
868
+ error.set(err);
869
+ } finally {
870
+ mutateLoading(false);
871
+ }
879
872
  }
880
- const complete = (prompt, options) => __async(this, null, function* () {
873
+ const complete = async (prompt, options) => {
881
874
  return triggerRequest(prompt, options);
882
- });
875
+ };
883
876
  const stop = () => {
884
877
  if (abortController) {
885
878
  abortController.abort();