ai 2.2.24 → 2.2.26

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,6 +1,3 @@
1
- // svelte/use-chat.ts
2
- import { get, writable, derived } from "svelte/store";
3
-
4
1
  // ../../node_modules/.pnpm/swrev@4.0.0/node_modules/swrev/dist/swrev.mjs
5
2
  var P = Object.defineProperty;
6
3
  var F = (r, e, t) => e in r ? P(r, e, { enumerable: true, configurable: true, writable: true, value: t }) : r[e] = t;
@@ -498,6 +495,9 @@ var W = (t) => new O2(t);
498
495
  var c = W();
499
496
  var F2 = (t, e) => c.useSWR(t, e);
500
497
 
498
+ // svelte/use-chat.ts
499
+ import { derived, get, writable } from "svelte/store";
500
+
501
501
  // shared/utils.ts
502
502
  import { customAlphabet } from "nanoid/non-secure";
503
503
 
@@ -641,103 +641,297 @@ function createChunkDecoder(complex) {
641
641
  return decoded.map(parseStreamPart).filter(Boolean);
642
642
  };
643
643
  }
644
+ var COMPLEX_HEADER = "X-Experimental-Stream-Data";
644
645
 
645
- // svelte/use-chat.ts
646
- var getStreamedResponse = async (api, chatRequest, mutate, extraMetadata, previousMessages, abortControllerRef, onFinish, onResponse, sendExtraMessageFields) => {
647
- var _a, _b, _c, _d;
648
- mutate(chatRequest.messages);
649
- const res = await fetch(api, {
646
+ // shared/parse-complex-response.ts
647
+ async function parseComplexResponse({
648
+ reader,
649
+ abortControllerRef,
650
+ update,
651
+ onFinish,
652
+ generateId = nanoid,
653
+ getCurrentDate = () => /* @__PURE__ */ new Date()
654
+ }) {
655
+ const createdAt = getCurrentDate();
656
+ const decode = createChunkDecoder(true);
657
+ const prefixMap = {
658
+ data: []
659
+ };
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"] = {
708
+ id: generateId(),
709
+ role: "assistant",
710
+ content: "",
711
+ function_call: value2.function_call,
712
+ name: value2.function_call.name,
713
+ createdAt
714
+ };
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
+ }
729
+ }
730
+ }
731
+ onFinish == null ? void 0 : onFinish(prefixMap);
732
+ return {
733
+ messages: [prefixMap.text, prefixMap.function_call].filter(
734
+ Boolean
735
+ ),
736
+ data: prefixMap.data
737
+ };
738
+ }
739
+
740
+ // shared/call-api.ts
741
+ async function callApi({
742
+ api,
743
+ messages,
744
+ body,
745
+ credentials,
746
+ headers,
747
+ abortController,
748
+ appendMessage,
749
+ restoreMessagesOnFailure,
750
+ onResponse,
751
+ onUpdate,
752
+ onFinish,
753
+ generateId
754
+ }) {
755
+ var _a;
756
+ const response = await fetch(api, {
650
757
  method: "POST",
651
758
  body: JSON.stringify({
652
- messages: sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(
653
- ({ role, content, name, function_call }) => ({
654
- role,
655
- content,
656
- ...name !== void 0 && { name },
657
- ...function_call !== void 0 && {
658
- function_call
659
- }
660
- })
661
- ),
662
- ...extraMetadata.body,
663
- ...(_a = chatRequest.options) == null ? void 0 : _a.body,
664
- ...chatRequest.functions !== void 0 && {
665
- functions: chatRequest.functions
666
- },
667
- ...chatRequest.function_call !== void 0 && {
668
- function_call: chatRequest.function_call
669
- }
759
+ messages,
760
+ ...body
670
761
  }),
671
- credentials: extraMetadata.credentials,
672
762
  headers: {
673
- ...extraMetadata.headers,
674
- ...(_b = chatRequest.options) == null ? void 0 : _b.headers
763
+ "Content-Type": "application/json",
764
+ ...headers
675
765
  },
676
- ...abortControllerRef !== null && {
677
- signal: abortControllerRef.signal
678
- }
766
+ signal: (_a = abortController == null ? void 0 : abortController()) == null ? void 0 : _a.signal,
767
+ credentials
679
768
  }).catch((err) => {
680
- mutate(previousMessages);
769
+ restoreMessagesOnFailure();
681
770
  throw err;
682
771
  });
683
772
  if (onResponse) {
684
773
  try {
685
- await onResponse(res);
774
+ await onResponse(response);
686
775
  } catch (err) {
687
776
  throw err;
688
777
  }
689
778
  }
690
- if (!res.ok) {
691
- mutate(previousMessages);
692
- throw new Error(await res.text() || "Failed to fetch the chat response.");
779
+ if (!response.ok) {
780
+ restoreMessagesOnFailure();
781
+ throw new Error(
782
+ await response.text() || "Failed to fetch the chat response."
783
+ );
693
784
  }
694
- if (!res.body) {
785
+ if (!response.body) {
695
786
  throw new Error("The response body is empty.");
696
787
  }
697
- let streamedResponse = "";
698
- const createdAt = /* @__PURE__ */ new Date();
699
- const replyId = nanoid();
700
- const reader = res.body.getReader();
701
- const decode = createChunkDecoder();
702
- let responseMessage = {
703
- id: replyId,
704
- createdAt,
705
- content: "",
706
- role: "assistant"
707
- };
708
- while (true) {
709
- const { done, value } = await reader.read();
710
- if (done) {
711
- break;
788
+ const reader = response.body.getReader();
789
+ const isComplexMode = response.headers.get(COMPLEX_HEADER) === "true";
790
+ if (isComplexMode) {
791
+ return await parseComplexResponse({
792
+ reader,
793
+ abortControllerRef: abortController != null ? { current: abortController() } : void 0,
794
+ update: onUpdate,
795
+ onFinish(prefixMap) {
796
+ if (onFinish && prefixMap.text != null) {
797
+ onFinish(prefixMap.text);
798
+ }
799
+ },
800
+ generateId
801
+ });
802
+ } else {
803
+ const createdAt = /* @__PURE__ */ new Date();
804
+ const decode = createChunkDecoder(false);
805
+ let streamedResponse = "";
806
+ const replyId = generateId();
807
+ let responseMessage = {
808
+ id: replyId,
809
+ createdAt,
810
+ content: "",
811
+ role: "assistant"
812
+ };
813
+ while (true) {
814
+ const { done, value } = await reader.read();
815
+ if (done) {
816
+ break;
817
+ }
818
+ streamedResponse += decode(value);
819
+ if (streamedResponse.startsWith('{"function_call":')) {
820
+ responseMessage["function_call"] = streamedResponse;
821
+ } else {
822
+ responseMessage["content"] = streamedResponse;
823
+ }
824
+ appendMessage({ ...responseMessage });
825
+ if ((abortController == null ? void 0 : abortController()) === null) {
826
+ reader.cancel();
827
+ break;
828
+ }
712
829
  }
713
- streamedResponse += decode(value);
714
- const functionStart = streamedResponse.indexOf("{");
715
- if (functionStart !== -1) {
716
- const matches = /(.*?)(?:({"function_call".*?}})(.*))?$/gs.exec(
717
- streamedResponse
718
- );
719
- responseMessage.content = `${(_c = matches == null ? void 0 : matches[1]) != null ? _c : ""}${(_d = matches == null ? void 0 : matches[3]) != null ? _d : ""}`;
720
- responseMessage.function_call = matches == null ? void 0 : matches[2];
721
- } else {
722
- responseMessage.content = streamedResponse;
830
+ if (streamedResponse.startsWith('{"function_call":')) {
831
+ const parsedFunctionCall = JSON.parse(streamedResponse).function_call;
832
+ responseMessage["function_call"] = parsedFunctionCall;
833
+ appendMessage({ ...responseMessage });
723
834
  }
724
- mutate([...chatRequest.messages, { ...responseMessage }]);
725
- if (abortControllerRef === null) {
726
- reader.cancel();
727
- break;
835
+ if (onFinish) {
836
+ onFinish(responseMessage);
728
837
  }
838
+ return responseMessage;
729
839
  }
730
- if (typeof responseMessage.function_call === "string") {
731
- const parsedFunctionCall = JSON.parse(
732
- responseMessage.function_call
733
- ).function_call;
734
- responseMessage.function_call = parsedFunctionCall;
735
- mutate([...chatRequest.messages, { ...responseMessage }]);
736
- }
737
- if (onFinish) {
738
- onFinish(responseMessage);
840
+ }
841
+
842
+ // shared/process-chat-stream.ts
843
+ async function processChatStream({
844
+ getStreamedResponse: getStreamedResponse2,
845
+ experimental_onFunctionCall,
846
+ updateChatRequest,
847
+ getCurrentMessages
848
+ }) {
849
+ while (true) {
850
+ const messagesAndDataOrJustMessage = await getStreamedResponse2();
851
+ if ("messages" in messagesAndDataOrJustMessage) {
852
+ let hasFollowingResponse = false;
853
+ for (const message of messagesAndDataOrJustMessage.messages) {
854
+ if (message.function_call === void 0 || typeof message.function_call === "string") {
855
+ continue;
856
+ }
857
+ hasFollowingResponse = true;
858
+ if (experimental_onFunctionCall) {
859
+ const functionCall = message.function_call;
860
+ const functionCallResponse = await experimental_onFunctionCall(
861
+ getCurrentMessages(),
862
+ functionCall
863
+ );
864
+ if (functionCallResponse === void 0) {
865
+ hasFollowingResponse = false;
866
+ break;
867
+ }
868
+ updateChatRequest(functionCallResponse);
869
+ }
870
+ }
871
+ if (!hasFollowingResponse) {
872
+ break;
873
+ }
874
+ } else {
875
+ const streamedResponseMessage = messagesAndDataOrJustMessage;
876
+ if (streamedResponseMessage.function_call === void 0 || typeof streamedResponseMessage.function_call === "string") {
877
+ break;
878
+ }
879
+ if (experimental_onFunctionCall) {
880
+ const functionCall = streamedResponseMessage.function_call;
881
+ const functionCallResponse = await experimental_onFunctionCall(getCurrentMessages(), functionCall);
882
+ if (functionCallResponse === void 0)
883
+ break;
884
+ updateChatRequest(functionCallResponse);
885
+ }
886
+ }
739
887
  }
740
- return responseMessage;
888
+ }
889
+
890
+ // svelte/use-chat.ts
891
+ var getStreamedResponse = async (api, chatRequest, mutate, mutateStreamData, existingData, extraMetadata, previousMessages, abortControllerRef, generateId, onFinish, onResponse, sendExtraMessageFields) => {
892
+ var _a, _b;
893
+ mutate(chatRequest.messages);
894
+ const constructedMessagesPayload = sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(({ role, content, name, function_call }) => ({
895
+ role,
896
+ content,
897
+ ...name !== void 0 && { name },
898
+ ...function_call !== void 0 && {
899
+ function_call
900
+ }
901
+ }));
902
+ return await callApi({
903
+ api,
904
+ messages: constructedMessagesPayload,
905
+ body: {
906
+ ...extraMetadata.body,
907
+ ...(_a = chatRequest.options) == null ? void 0 : _a.body,
908
+ ...chatRequest.functions !== void 0 && {
909
+ functions: chatRequest.functions
910
+ },
911
+ ...chatRequest.function_call !== void 0 && {
912
+ function_call: chatRequest.function_call
913
+ }
914
+ },
915
+ credentials: extraMetadata.credentials,
916
+ headers: {
917
+ ...extraMetadata.headers,
918
+ ...(_b = chatRequest.options) == null ? void 0 : _b.headers
919
+ },
920
+ abortController: () => abortControllerRef,
921
+ appendMessage(message) {
922
+ mutate([...chatRequest.messages, message]);
923
+ },
924
+ restoreMessagesOnFailure() {
925
+ mutate(previousMessages);
926
+ },
927
+ onResponse,
928
+ onUpdate(merged, data) {
929
+ mutate([...chatRequest.messages, ...merged]);
930
+ mutateStreamData([...existingData || [], ...data || []]);
931
+ },
932
+ onFinish,
933
+ generateId
934
+ });
741
935
  };
742
936
  var uniqueId = 0;
743
937
  var store = {};
@@ -753,7 +947,8 @@ function useChat({
753
947
  onError,
754
948
  credentials,
755
949
  headers,
756
- body
950
+ body,
951
+ generateId = nanoid
757
952
  } = {}) {
758
953
  const chatId = id || `chat-${uniqueId++}`;
759
954
  const key = `${api}|${chatId}`;
@@ -765,6 +960,7 @@ function useChat({
765
960
  fetcher: () => store[key] || initialMessages,
766
961
  fallbackData: initialMessages
767
962
  });
963
+ const streamData = writable(void 0);
768
964
  const loading = writable(false);
769
965
  data.set(initialMessages);
770
966
  const mutate = (data2) => {
@@ -784,29 +980,29 @@ function useChat({
784
980
  error.set(void 0);
785
981
  loading.set(true);
786
982
  abortController = new AbortController();
787
- while (true) {
788
- const streamedResponseMessage = await getStreamedResponse(
983
+ await processChatStream({
984
+ getStreamedResponse: () => getStreamedResponse(
789
985
  api,
790
986
  chatRequest,
791
987
  mutate,
988
+ (data2) => {
989
+ streamData.set(data2);
990
+ },
991
+ get(streamData),
792
992
  extraMetadata,
793
993
  get(messages),
794
994
  abortController,
995
+ generateId,
795
996
  onFinish,
796
997
  onResponse,
797
998
  sendExtraMessageFields
798
- );
799
- if (streamedResponseMessage.function_call === void 0 || typeof streamedResponseMessage.function_call === "string") {
800
- break;
801
- }
802
- if (experimental_onFunctionCall) {
803
- const functionCall = streamedResponseMessage.function_call;
804
- const functionCallResponse = await experimental_onFunctionCall(get(messages), functionCall);
805
- if (functionCallResponse === void 0)
806
- break;
807
- chatRequest = functionCallResponse;
808
- }
809
- }
999
+ ),
1000
+ experimental_onFunctionCall,
1001
+ updateChatRequest: (chatRequestParam) => {
1002
+ chatRequest = chatRequestParam;
1003
+ },
1004
+ getCurrentMessages: () => get(messages)
1005
+ });
810
1006
  abortController = null;
811
1007
  return null;
812
1008
  } catch (err) {
@@ -824,7 +1020,7 @@ function useChat({
824
1020
  }
825
1021
  const append = async (message, { options, functions, function_call } = {}) => {
826
1022
  if (!message.id) {
827
- message.id = nanoid();
1023
+ message.id = generateId();
828
1024
  }
829
1025
  const chatRequest = {
830
1026
  messages: get(messages).concat(message),
@@ -900,7 +1096,8 @@ function useChat({
900
1096
  setMessages,
901
1097
  input,
902
1098
  handleSubmit,
903
- isLoading
1099
+ isLoading,
1100
+ data: streamData
904
1101
  };
905
1102
  }
906
1103
 
@@ -35,6 +35,7 @@ interface Function {
35
35
  */
36
36
  description?: string;
37
37
  }
38
+ type IdGenerator = () => string;
38
39
  /**
39
40
  * Shared types between the API and UI packages.
40
41
  */
@@ -109,6 +110,11 @@ type UseChatOptions = {
109
110
  * Callback function to be called when an error is encountered.
110
111
  */
111
112
  onError?: (error: Error) => void;
113
+ /**
114
+ * A way to provide a function that is going to be used for ids for messages.
115
+ * If not provided nanoid is used by default.
116
+ */
117
+ generateId?: IdGenerator;
112
118
  /**
113
119
  * The credentials mode to be used for the fetch request.
114
120
  * Possible values are: 'omit', 'same-origin', 'include'.
@@ -195,6 +201,9 @@ type UseCompletionOptions = {
195
201
  */
196
202
  body?: object;
197
203
  };
204
+ type JSONValue = null | string | number | boolean | {
205
+ [x: string]: JSONValue;
206
+ } | Array<JSONValue>;
198
207
 
199
208
  type UseChatHelpers = {
200
209
  /** Current messages in the chat */
@@ -228,8 +237,10 @@ type UseChatHelpers = {
228
237
  handleSubmit: (e: any) => void;
229
238
  /** Whether the API request is in progress */
230
239
  isLoading: Ref<boolean | undefined>;
240
+ /** Additional data added on the server via StreamData */
241
+ data: Ref<JSONValue[] | undefined>;
231
242
  };
232
- declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, onResponse, onFinish, onError, credentials, headers, body, }?: UseChatOptions): UseChatHelpers;
243
+ declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, experimental_onFunctionCall, onResponse, onFinish, onError, credentials, headers, body, generateId, }?: UseChatOptions): UseChatHelpers;
233
244
 
234
245
  type UseCompletionHelpers = {
235
246
  /** The current completion result */