ai 2.2.26 → 2.2.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.
@@ -498,9 +498,6 @@ var F2 = (t, e) => c.useSWR(t, e);
498
498
  // svelte/use-chat.ts
499
499
  import { derived, get, writable } from "svelte/store";
500
500
 
501
- // shared/utils.ts
502
- import { customAlphabet } from "nanoid/non-secure";
503
-
504
501
  // shared/stream-parts.ts
505
502
  var textStreamPart = {
506
503
  code: "0",
@@ -622,7 +619,51 @@ var parseStreamPart = (line) => {
622
619
  return streamPartsByCode[code].parse(jsonValue);
623
620
  };
624
621
 
622
+ // shared/read-data-stream.ts
623
+ var NEWLINE = "\n".charCodeAt(0);
624
+ function concatChunks(chunks, totalLength) {
625
+ const concatenatedChunks = new Uint8Array(totalLength);
626
+ let offset = 0;
627
+ for (const chunk of chunks) {
628
+ concatenatedChunks.set(chunk, offset);
629
+ offset += chunk.length;
630
+ }
631
+ chunks.length = 0;
632
+ return concatenatedChunks;
633
+ }
634
+ async function* readDataStream(reader, {
635
+ isAborted
636
+ } = {}) {
637
+ const decoder = new TextDecoder();
638
+ const chunks = [];
639
+ let totalLength = 0;
640
+ while (true) {
641
+ const { value } = await reader.read();
642
+ if (value) {
643
+ chunks.push(value);
644
+ totalLength += value.length;
645
+ if (value[value.length - 1] !== NEWLINE) {
646
+ continue;
647
+ }
648
+ }
649
+ if (chunks.length === 0) {
650
+ break;
651
+ }
652
+ const concatenatedChunks = concatChunks(chunks, totalLength);
653
+ totalLength = 0;
654
+ const streamParts2 = decoder.decode(concatenatedChunks, { stream: true }).split("\n").filter((line) => line !== "").map(parseStreamPart);
655
+ for (const streamPart of streamParts2) {
656
+ yield streamPart;
657
+ }
658
+ if (isAborted == null ? void 0 : isAborted()) {
659
+ reader.cancel();
660
+ break;
661
+ }
662
+ }
663
+ }
664
+
625
665
  // shared/utils.ts
666
+ import { customAlphabet } from "nanoid/non-secure";
626
667
  var nanoid = customAlphabet(
627
668
  "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
628
669
  7
@@ -653,80 +694,47 @@ async function parseComplexResponse({
653
694
  getCurrentDate = () => /* @__PURE__ */ new Date()
654
695
  }) {
655
696
  const createdAt = getCurrentDate();
656
- const decode = createChunkDecoder(true);
657
697
  const prefixMap = {
658
698
  data: []
659
699
  };
660
- const NEWLINE = "\n".charCodeAt(0);
661
- const chunks = [];
662
- let totalLength = 0;
663
- while (true) {
664
- const { value } = await reader.read();
665
- if (value) {
666
- chunks.push(value);
667
- totalLength += value.length;
668
- if (value[value.length - 1] !== NEWLINE) {
669
- continue;
670
- }
671
- }
672
- if (chunks.length === 0) {
673
- break;
674
- }
675
- let concatenatedChunks = new Uint8Array(totalLength);
676
- let offset = 0;
677
- for (const chunk of chunks) {
678
- concatenatedChunks.set(chunk, offset);
679
- offset += chunk.length;
680
- }
681
- chunks.length = 0;
682
- totalLength = 0;
683
- const lines = decode(concatenatedChunks);
684
- if (typeof lines === "string") {
685
- throw new Error(
686
- "Invalid response format. Complex mode was set but the response is a string. This should never happen."
687
- );
688
- }
689
- for (const { type, value: value2 } of lines) {
690
- if (type === "text") {
691
- if (prefixMap["text"]) {
692
- prefixMap["text"] = {
693
- ...prefixMap["text"],
694
- content: (prefixMap["text"].content || "") + value2
695
- };
696
- } else {
697
- prefixMap["text"] = {
698
- id: generateId(),
699
- role: "assistant",
700
- content: value2,
701
- createdAt
702
- };
703
- }
704
- }
705
- let functionCallMessage = null;
706
- if (type === "function_call") {
707
- prefixMap["function_call"] = {
700
+ for await (const { type, value } of readDataStream(reader, {
701
+ isAborted: () => (abortControllerRef == null ? void 0 : abortControllerRef.current) === null
702
+ })) {
703
+ if (type === "text") {
704
+ if (prefixMap["text"]) {
705
+ prefixMap["text"] = {
706
+ ...prefixMap["text"],
707
+ content: (prefixMap["text"].content || "") + value
708
+ };
709
+ } else {
710
+ prefixMap["text"] = {
708
711
  id: generateId(),
709
712
  role: "assistant",
710
- content: "",
711
- function_call: value2.function_call,
712
- name: value2.function_call.name,
713
+ content: value,
713
714
  createdAt
714
715
  };
715
- functionCallMessage = prefixMap["function_call"];
716
- }
717
- if (type === "data") {
718
- prefixMap["data"].push(...value2);
719
- }
720
- const responseMessage = prefixMap["text"];
721
- const merged = [functionCallMessage, responseMessage].filter(
722
- Boolean
723
- );
724
- update(merged, [...prefixMap["data"]]);
725
- if ((abortControllerRef == null ? void 0 : abortControllerRef.current) === null) {
726
- reader.cancel();
727
- break;
728
716
  }
729
717
  }
718
+ let functionCallMessage = null;
719
+ if (type === "function_call") {
720
+ prefixMap["function_call"] = {
721
+ id: generateId(),
722
+ role: "assistant",
723
+ content: "",
724
+ function_call: value.function_call,
725
+ name: value.function_call.name,
726
+ createdAt
727
+ };
728
+ functionCallMessage = prefixMap["function_call"];
729
+ }
730
+ if (type === "data") {
731
+ prefixMap["data"].push(...value);
732
+ }
733
+ const responseMessage = prefixMap["text"];
734
+ const merged = [functionCallMessage, responseMessage].filter(
735
+ Boolean
736
+ );
737
+ update(merged, [...prefixMap["data"]]);
730
738
  }
731
739
  onFinish == null ? void 0 : onFinish(prefixMap);
732
740
  return {
@@ -1127,6 +1135,7 @@ function useCompletion({
1127
1135
  fetcher: () => store2[key] || initialCompletion,
1128
1136
  fallbackData: initialCompletion
1129
1137
  });
1138
+ const streamData = writable2(void 0);
1130
1139
  const loading = writable2(false);
1131
1140
  data.set(initialCompletion);
1132
1141
  const mutate = (data2) => {
@@ -1175,17 +1184,37 @@ function useCompletion({
1175
1184
  }
1176
1185
  let result = "";
1177
1186
  const reader = res.body.getReader();
1178
- const decoder = createChunkDecoder();
1179
- while (true) {
1180
- const { done, value } = await reader.read();
1181
- if (done) {
1182
- break;
1187
+ const existingData = get2(streamData);
1188
+ const isComplexMode = res.headers.get(COMPLEX_HEADER) === "true";
1189
+ if (isComplexMode) {
1190
+ for await (const { type, value } of readDataStream(reader, {
1191
+ isAborted: () => abortController === null
1192
+ })) {
1193
+ switch (type) {
1194
+ case "text": {
1195
+ result += value;
1196
+ mutate(result);
1197
+ break;
1198
+ }
1199
+ case "data": {
1200
+ streamData.set([...existingData || [], ...value || []]);
1201
+ break;
1202
+ }
1203
+ }
1183
1204
  }
1184
- result += decoder(value);
1185
- mutate(result);
1186
- if (abortController === null) {
1187
- reader.cancel();
1188
- break;
1205
+ } else {
1206
+ const decoder = createChunkDecoder();
1207
+ while (true) {
1208
+ const { done, value } = await reader.read();
1209
+ if (done) {
1210
+ break;
1211
+ }
1212
+ result += decoder(value);
1213
+ mutate(result);
1214
+ if (abortController === null) {
1215
+ reader.cancel();
1216
+ break;
1217
+ }
1189
1218
  }
1190
1219
  }
1191
1220
  if (onFinish) {
@@ -1240,7 +1269,8 @@ function useCompletion({
1240
1269
  setCompletion,
1241
1270
  input,
1242
1271
  handleSubmit,
1243
- isLoading
1272
+ isLoading,
1273
+ data: streamData
1244
1274
  };
1245
1275
  }
1246
1276
  export {
@@ -273,6 +273,8 @@ type UseCompletionHelpers = {
273
273
  handleSubmit: (e: any) => void;
274
274
  /** Whether the API request is in progress */
275
275
  isLoading: Ref<boolean | undefined>;
276
+ /** Additional data added on the server via StreamData */
277
+ data: Ref<JSONValue[] | undefined>;
276
278
  };
277
279
  declare function useCompletion({ api, id, initialCompletion, initialInput, credentials, headers, body, onResponse, onFinish, onError, }?: UseCompletionOptions): UseCompletionHelpers;
278
280
 
package/vue/dist/index.js CHANGED
@@ -39,9 +39,6 @@ module.exports = __toCommonJS(vue_exports);
39
39
  var import_swrv = __toESM(require("swrv"));
40
40
  var import_vue = require("vue");
41
41
 
42
- // shared/utils.ts
43
- var import_non_secure = require("nanoid/non-secure");
44
-
45
42
  // shared/stream-parts.ts
46
43
  var textStreamPart = {
47
44
  code: "0",
@@ -163,7 +160,51 @@ var parseStreamPart = (line) => {
163
160
  return streamPartsByCode[code].parse(jsonValue);
164
161
  };
165
162
 
163
+ // shared/read-data-stream.ts
164
+ var NEWLINE = "\n".charCodeAt(0);
165
+ function concatChunks(chunks, totalLength) {
166
+ const concatenatedChunks = new Uint8Array(totalLength);
167
+ let offset = 0;
168
+ for (const chunk of chunks) {
169
+ concatenatedChunks.set(chunk, offset);
170
+ offset += chunk.length;
171
+ }
172
+ chunks.length = 0;
173
+ return concatenatedChunks;
174
+ }
175
+ async function* readDataStream(reader, {
176
+ isAborted
177
+ } = {}) {
178
+ const decoder = new TextDecoder();
179
+ const chunks = [];
180
+ let totalLength = 0;
181
+ while (true) {
182
+ const { value } = await reader.read();
183
+ if (value) {
184
+ chunks.push(value);
185
+ totalLength += value.length;
186
+ if (value[value.length - 1] !== NEWLINE) {
187
+ continue;
188
+ }
189
+ }
190
+ if (chunks.length === 0) {
191
+ break;
192
+ }
193
+ const concatenatedChunks = concatChunks(chunks, totalLength);
194
+ totalLength = 0;
195
+ const streamParts2 = decoder.decode(concatenatedChunks, { stream: true }).split("\n").filter((line) => line !== "").map(parseStreamPart);
196
+ for (const streamPart of streamParts2) {
197
+ yield streamPart;
198
+ }
199
+ if (isAborted == null ? void 0 : isAborted()) {
200
+ reader.cancel();
201
+ break;
202
+ }
203
+ }
204
+ }
205
+
166
206
  // shared/utils.ts
207
+ var import_non_secure = require("nanoid/non-secure");
167
208
  var nanoid = (0, import_non_secure.customAlphabet)(
168
209
  "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
169
210
  7
@@ -194,80 +235,47 @@ async function parseComplexResponse({
194
235
  getCurrentDate = () => /* @__PURE__ */ new Date()
195
236
  }) {
196
237
  const createdAt = getCurrentDate();
197
- const decode = createChunkDecoder(true);
198
238
  const prefixMap = {
199
239
  data: []
200
240
  };
201
- const NEWLINE = "\n".charCodeAt(0);
202
- const chunks = [];
203
- let totalLength = 0;
204
- while (true) {
205
- const { value } = await reader.read();
206
- if (value) {
207
- chunks.push(value);
208
- totalLength += value.length;
209
- if (value[value.length - 1] !== NEWLINE) {
210
- continue;
211
- }
212
- }
213
- if (chunks.length === 0) {
214
- break;
215
- }
216
- let concatenatedChunks = new Uint8Array(totalLength);
217
- let offset = 0;
218
- for (const chunk of chunks) {
219
- concatenatedChunks.set(chunk, offset);
220
- offset += chunk.length;
221
- }
222
- chunks.length = 0;
223
- totalLength = 0;
224
- const lines = decode(concatenatedChunks);
225
- if (typeof lines === "string") {
226
- throw new Error(
227
- "Invalid response format. Complex mode was set but the response is a string. This should never happen."
228
- );
229
- }
230
- for (const { type, value: value2 } of lines) {
231
- if (type === "text") {
232
- if (prefixMap["text"]) {
233
- prefixMap["text"] = {
234
- ...prefixMap["text"],
235
- content: (prefixMap["text"].content || "") + value2
236
- };
237
- } else {
238
- prefixMap["text"] = {
239
- id: generateId(),
240
- role: "assistant",
241
- content: value2,
242
- createdAt
243
- };
244
- }
245
- }
246
- let functionCallMessage = null;
247
- if (type === "function_call") {
248
- prefixMap["function_call"] = {
241
+ for await (const { type, value } of readDataStream(reader, {
242
+ isAborted: () => (abortControllerRef == null ? void 0 : abortControllerRef.current) === null
243
+ })) {
244
+ if (type === "text") {
245
+ if (prefixMap["text"]) {
246
+ prefixMap["text"] = {
247
+ ...prefixMap["text"],
248
+ content: (prefixMap["text"].content || "") + value
249
+ };
250
+ } else {
251
+ prefixMap["text"] = {
249
252
  id: generateId(),
250
253
  role: "assistant",
251
- content: "",
252
- function_call: value2.function_call,
253
- name: value2.function_call.name,
254
+ content: value,
254
255
  createdAt
255
256
  };
256
- functionCallMessage = prefixMap["function_call"];
257
- }
258
- if (type === "data") {
259
- prefixMap["data"].push(...value2);
260
- }
261
- const responseMessage = prefixMap["text"];
262
- const merged = [functionCallMessage, responseMessage].filter(
263
- Boolean
264
- );
265
- update(merged, [...prefixMap["data"]]);
266
- if ((abortControllerRef == null ? void 0 : abortControllerRef.current) === null) {
267
- reader.cancel();
268
- break;
269
257
  }
270
258
  }
259
+ let functionCallMessage = null;
260
+ if (type === "function_call") {
261
+ prefixMap["function_call"] = {
262
+ id: generateId(),
263
+ role: "assistant",
264
+ content: "",
265
+ function_call: value.function_call,
266
+ name: value.function_call.name,
267
+ createdAt
268
+ };
269
+ functionCallMessage = prefixMap["function_call"];
270
+ }
271
+ if (type === "data") {
272
+ prefixMap["data"].push(...value);
273
+ }
274
+ const responseMessage = prefixMap["text"];
275
+ const merged = [functionCallMessage, responseMessage].filter(
276
+ Boolean
277
+ );
278
+ update(merged, [...prefixMap["data"]]);
271
279
  }
272
280
  onFinish == null ? void 0 : onFinish(prefixMap);
273
281
  return {
@@ -625,6 +633,7 @@ function useCompletion({
625
633
  null
626
634
  );
627
635
  (_a = isLoading.value) != null ? _a : isLoading.value = false;
636
+ const { data: streamData, mutate: mutateStreamData } = useSWRV2(`${completionId}-data`, null);
628
637
  data.value || (data.value = initialCompletion);
629
638
  const mutate = (data2) => {
630
639
  store2[key] = data2;
@@ -634,6 +643,7 @@ function useCompletion({
634
643
  const error = (0, import_vue2.ref)(void 0);
635
644
  let abortController = null;
636
645
  async function triggerRequest(prompt, options) {
646
+ var _a2;
637
647
  try {
638
648
  error.value = void 0;
639
649
  mutateLoading(() => true);
@@ -647,6 +657,7 @@ function useCompletion({
647
657
  ...options == null ? void 0 : options.body
648
658
  }),
649
659
  headers: {
660
+ "Content-Type": "application/json",
650
661
  ...headers,
651
662
  ...options == null ? void 0 : options.headers
652
663
  },
@@ -672,17 +683,37 @@ function useCompletion({
672
683
  }
673
684
  let result = "";
674
685
  const reader = res.body.getReader();
675
- const decoder = createChunkDecoder();
676
- while (true) {
677
- const { done, value } = await reader.read();
678
- if (done) {
679
- break;
686
+ const existingData = (_a2 = streamData.value) != null ? _a2 : [];
687
+ const isComplexMode = res.headers.get(COMPLEX_HEADER) === "true";
688
+ if (isComplexMode) {
689
+ for await (const { type, value } of readDataStream(reader, {
690
+ isAborted: () => abortController === null
691
+ })) {
692
+ switch (type) {
693
+ case "text": {
694
+ result += value;
695
+ mutate(result);
696
+ break;
697
+ }
698
+ case "data": {
699
+ streamData.value = [...existingData, ...value != null ? value : []];
700
+ break;
701
+ }
702
+ }
680
703
  }
681
- result += decoder(value);
682
- mutate(result);
683
- if (abortController === null) {
684
- reader.cancel();
685
- break;
704
+ } else {
705
+ const decoder = createChunkDecoder();
706
+ while (true) {
707
+ const { done, value } = await reader.read();
708
+ if (done) {
709
+ break;
710
+ }
711
+ result += decoder(value);
712
+ mutate(result);
713
+ if (abortController === null) {
714
+ reader.cancel();
715
+ break;
716
+ }
686
717
  }
687
718
  }
688
719
  if (onFinish) {
@@ -731,7 +762,8 @@ function useCompletion({
731
762
  setCompletion,
732
763
  input,
733
764
  handleSubmit,
734
- isLoading
765
+ isLoading,
766
+ data: streamData
735
767
  };
736
768
  }
737
769
  // Annotate the CommonJS export names for ESM import in node: