ai 2.2.23 → 2.2.25

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.
@@ -25,9 +25,6 @@ __export(svelte_exports, {
25
25
  });
26
26
  module.exports = __toCommonJS(svelte_exports);
27
27
 
28
- // svelte/use-chat.ts
29
- var import_store = require("svelte/store");
30
-
31
28
  // ../../node_modules/.pnpm/swrev@4.0.0/node_modules/swrev/dist/swrev.mjs
32
29
  var P = Object.defineProperty;
33
30
  var F = (r, e, t) => e in r ? P(r, e, { enumerable: true, configurable: true, writable: true, value: t }) : r[e] = t;
@@ -525,8 +522,137 @@ var W = (t) => new O2(t);
525
522
  var c = W();
526
523
  var F2 = (t, e) => c.useSWR(t, e);
527
524
 
525
+ // svelte/use-chat.ts
526
+ var import_store = require("svelte/store");
527
+
528
+ // shared/call-api.ts
529
+ var import_nanoid = require("nanoid");
530
+
528
531
  // shared/utils.ts
529
532
  var import_non_secure = require("nanoid/non-secure");
533
+
534
+ // shared/stream-parts.ts
535
+ var textStreamPart = {
536
+ code: "0",
537
+ name: "text",
538
+ parse: (value) => {
539
+ if (typeof value !== "string") {
540
+ throw new Error('"text" parts expect a string value.');
541
+ }
542
+ return { type: "text", value };
543
+ }
544
+ };
545
+ var functionCallStreamPart = {
546
+ code: "1",
547
+ name: "function_call",
548
+ parse: (value) => {
549
+ if (value == null || typeof value !== "object" || !("function_call" in value) || typeof value.function_call !== "object" || value.function_call == null || !("name" in value.function_call) || !("arguments" in value.function_call) || typeof value.function_call.name !== "string" || typeof value.function_call.arguments !== "string") {
550
+ throw new Error(
551
+ '"function_call" parts expect an object with a "function_call" property.'
552
+ );
553
+ }
554
+ return {
555
+ type: "function_call",
556
+ value
557
+ };
558
+ }
559
+ };
560
+ var dataStreamPart = {
561
+ code: "2",
562
+ name: "data",
563
+ parse: (value) => {
564
+ if (!Array.isArray(value)) {
565
+ throw new Error('"data" parts expect an array value.');
566
+ }
567
+ return { type: "data", value };
568
+ }
569
+ };
570
+ var errorStreamPart = {
571
+ code: "3",
572
+ name: "error",
573
+ parse: (value) => {
574
+ if (typeof value !== "string") {
575
+ throw new Error('"error" parts expect a string value.');
576
+ }
577
+ return { type: "error", value };
578
+ }
579
+ };
580
+ var assistantMessage = {
581
+ code: "4",
582
+ name: "assistant_message",
583
+ parse: (value) => {
584
+ if (value == null || typeof value !== "object" || !("id" in value) || !("role" in value) || !("content" in value) || typeof value.id !== "string" || typeof value.role !== "string" || value.role !== "assistant" || !Array.isArray(value.content) || !value.content.every(
585
+ (item) => item != null && typeof item === "object" && "type" in item && item.type === "text" && "text" in item && item.text != null && typeof item.text === "object" && "value" in item.text && typeof item.text.value === "string"
586
+ )) {
587
+ throw new Error(
588
+ '"assistant_message" parts expect an object with an "id", "role", and "content" property.'
589
+ );
590
+ }
591
+ return {
592
+ type: "assistant_message",
593
+ value
594
+ };
595
+ }
596
+ };
597
+ var assistantControlData = {
598
+ code: "5",
599
+ name: "assistant_control_data",
600
+ parse: (value) => {
601
+ if (value == null || typeof value !== "object" || !("threadId" in value) || !("messageId" in value) || typeof value.threadId !== "string" || typeof value.messageId !== "string") {
602
+ throw new Error(
603
+ '"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.'
604
+ );
605
+ }
606
+ return {
607
+ type: "assistant_control_data",
608
+ value: {
609
+ threadId: value.threadId,
610
+ messageId: value.messageId
611
+ }
612
+ };
613
+ }
614
+ };
615
+ var streamParts = [
616
+ textStreamPart,
617
+ functionCallStreamPart,
618
+ dataStreamPart,
619
+ errorStreamPart,
620
+ assistantMessage,
621
+ assistantControlData
622
+ ];
623
+ var streamPartsByCode = {
624
+ [textStreamPart.code]: textStreamPart,
625
+ [functionCallStreamPart.code]: functionCallStreamPart,
626
+ [dataStreamPart.code]: dataStreamPart,
627
+ [errorStreamPart.code]: errorStreamPart,
628
+ [assistantMessage.code]: assistantMessage,
629
+ [assistantControlData.code]: assistantControlData
630
+ };
631
+ var StreamStringPrefixes = {
632
+ [textStreamPart.name]: textStreamPart.code,
633
+ [functionCallStreamPart.name]: functionCallStreamPart.code,
634
+ [dataStreamPart.name]: dataStreamPart.code,
635
+ [errorStreamPart.name]: errorStreamPart.code,
636
+ [assistantMessage.name]: assistantMessage.code,
637
+ [assistantControlData.name]: assistantControlData.code
638
+ };
639
+ var validCodes = streamParts.map((part) => part.code);
640
+ var parseStreamPart = (line) => {
641
+ const firstSeparatorIndex = line.indexOf(":");
642
+ if (firstSeparatorIndex === -1) {
643
+ throw new Error("Failed to parse stream string. No separator found.");
644
+ }
645
+ const prefix = line.slice(0, firstSeparatorIndex);
646
+ if (!validCodes.includes(prefix)) {
647
+ throw new Error(`Failed to parse stream string. Invalid code ${prefix}.`);
648
+ }
649
+ const code = prefix;
650
+ const textValue = line.slice(firstSeparatorIndex + 1);
651
+ const jsonValue = JSON.parse(textValue);
652
+ return streamPartsByCode[code].parse(jsonValue);
653
+ };
654
+
655
+ // shared/utils.ts
530
656
  var nanoid = (0, import_non_secure.customAlphabet)(
531
657
  "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
532
658
  7
@@ -542,133 +668,294 @@ function createChunkDecoder(complex) {
542
668
  }
543
669
  return function(chunk) {
544
670
  const decoded = decoder.decode(chunk, { stream: true }).split("\n").filter((line) => line !== "");
545
- return decoded.map(getStreamStringTypeAndValue).filter(Boolean);
671
+ return decoded.map(parseStreamPart).filter(Boolean);
546
672
  };
547
673
  }
548
- var StreamStringPrefixes = {
549
- text: 0,
550
- function_call: 1,
551
- data: 2
552
- // user_err: 3?
553
- };
554
- var getStreamStringTypeAndValue = (line) => {
555
- const firstSeperatorIndex = line.indexOf(":");
556
- if (firstSeperatorIndex === -1) {
557
- throw new Error("Failed to parse stream string");
558
- }
559
- const prefix = line.slice(0, firstSeperatorIndex);
560
- const type = Object.keys(StreamStringPrefixes).find(
561
- (key) => StreamStringPrefixes[key] === Number(prefix)
562
- );
563
- const val = line.slice(firstSeperatorIndex + 1);
564
- let parsedVal = val;
565
- if (!val) {
566
- return { type, value: "" };
567
- }
568
- try {
569
- parsedVal = JSON.parse(val);
570
- } catch (e) {
571
- console.error("Failed to parse JSON value:", val);
674
+ var COMPLEX_HEADER = "X-Experimental-Stream-Data";
675
+
676
+ // shared/parse-complex-response.ts
677
+ async function parseComplexResponse({
678
+ reader,
679
+ abortControllerRef,
680
+ update,
681
+ onFinish,
682
+ generateId = nanoid,
683
+ getCurrentDate = () => /* @__PURE__ */ new Date()
684
+ }) {
685
+ const createdAt = getCurrentDate();
686
+ const decode = createChunkDecoder(true);
687
+ const prefixMap = {
688
+ data: []
689
+ };
690
+ const NEWLINE = "\n".charCodeAt(0);
691
+ const chunks = [];
692
+ let totalLength = 0;
693
+ while (true) {
694
+ const { value } = await reader.read();
695
+ if (value) {
696
+ chunks.push(value);
697
+ totalLength += value.length;
698
+ if (value[value.length - 1] !== NEWLINE) {
699
+ continue;
700
+ }
701
+ }
702
+ if (chunks.length === 0) {
703
+ break;
704
+ }
705
+ let concatenatedChunks = new Uint8Array(totalLength);
706
+ let offset = 0;
707
+ for (const chunk of chunks) {
708
+ concatenatedChunks.set(chunk, offset);
709
+ offset += chunk.length;
710
+ }
711
+ chunks.length = 0;
712
+ totalLength = 0;
713
+ const lines = decode(concatenatedChunks);
714
+ if (typeof lines === "string") {
715
+ throw new Error(
716
+ "Invalid response format. Complex mode was set but the response is a string. This should never happen."
717
+ );
718
+ }
719
+ for (const { type, value: value2 } of lines) {
720
+ if (type === "text") {
721
+ if (prefixMap["text"]) {
722
+ prefixMap["text"] = {
723
+ ...prefixMap["text"],
724
+ content: (prefixMap["text"].content || "") + value2
725
+ };
726
+ } else {
727
+ prefixMap["text"] = {
728
+ id: generateId(),
729
+ role: "assistant",
730
+ content: value2,
731
+ createdAt
732
+ };
733
+ }
734
+ }
735
+ let functionCallMessage = null;
736
+ if (type === "function_call") {
737
+ prefixMap["function_call"] = {
738
+ id: generateId(),
739
+ role: "assistant",
740
+ content: "",
741
+ function_call: value2.function_call,
742
+ name: value2.function_call.name,
743
+ createdAt
744
+ };
745
+ functionCallMessage = prefixMap["function_call"];
746
+ }
747
+ if (type === "data") {
748
+ prefixMap["data"].push(...value2);
749
+ }
750
+ const responseMessage = prefixMap["text"];
751
+ const merged = [functionCallMessage, responseMessage].filter(
752
+ Boolean
753
+ );
754
+ update(merged, [...prefixMap["data"]]);
755
+ if ((abortControllerRef == null ? void 0 : abortControllerRef.current) === null) {
756
+ reader.cancel();
757
+ break;
758
+ }
759
+ }
572
760
  }
573
- return { type, value: parsedVal };
574
- };
761
+ onFinish == null ? void 0 : onFinish(prefixMap);
762
+ return {
763
+ messages: [prefixMap.text, prefixMap.function_call].filter(
764
+ Boolean
765
+ ),
766
+ data: prefixMap.data
767
+ };
768
+ }
575
769
 
576
- // svelte/use-chat.ts
577
- var getStreamedResponse = async (api, chatRequest, mutate, extraMetadata, previousMessages, abortControllerRef, onFinish, onResponse, sendExtraMessageFields) => {
578
- var _a, _b, _c, _d;
579
- mutate(chatRequest.messages);
580
- const res = await fetch(api, {
770
+ // shared/call-api.ts
771
+ async function callApi({
772
+ api,
773
+ messages,
774
+ body,
775
+ credentials,
776
+ headers,
777
+ abortController,
778
+ appendMessage,
779
+ restoreMessagesOnFailure,
780
+ onResponse,
781
+ onUpdate,
782
+ onFinish
783
+ }) {
784
+ var _a;
785
+ const response = await fetch(api, {
581
786
  method: "POST",
582
787
  body: JSON.stringify({
583
- messages: sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(
584
- ({ role, content, name, function_call }) => ({
585
- role,
586
- content,
587
- ...name !== void 0 && { name },
588
- ...function_call !== void 0 && {
589
- function_call
590
- }
591
- })
592
- ),
593
- ...extraMetadata.body,
594
- ...(_a = chatRequest.options) == null ? void 0 : _a.body,
595
- ...chatRequest.functions !== void 0 && {
596
- functions: chatRequest.functions
597
- },
598
- ...chatRequest.function_call !== void 0 && {
599
- function_call: chatRequest.function_call
600
- }
788
+ messages,
789
+ ...body
601
790
  }),
602
- credentials: extraMetadata.credentials,
603
- headers: {
604
- ...extraMetadata.headers,
605
- ...(_b = chatRequest.options) == null ? void 0 : _b.headers
606
- },
607
- ...abortControllerRef !== null && {
608
- signal: abortControllerRef.signal
609
- }
791
+ headers,
792
+ signal: (_a = abortController == null ? void 0 : abortController()) == null ? void 0 : _a.signal,
793
+ credentials
610
794
  }).catch((err) => {
611
- mutate(previousMessages);
795
+ restoreMessagesOnFailure();
612
796
  throw err;
613
797
  });
614
798
  if (onResponse) {
615
799
  try {
616
- await onResponse(res);
800
+ await onResponse(response);
617
801
  } catch (err) {
618
802
  throw err;
619
803
  }
620
804
  }
621
- if (!res.ok) {
622
- mutate(previousMessages);
623
- throw new Error(await res.text() || "Failed to fetch the chat response.");
805
+ if (!response.ok) {
806
+ restoreMessagesOnFailure();
807
+ throw new Error(
808
+ await response.text() || "Failed to fetch the chat response."
809
+ );
624
810
  }
625
- if (!res.body) {
811
+ if (!response.body) {
626
812
  throw new Error("The response body is empty.");
627
813
  }
628
- let streamedResponse = "";
629
- const createdAt = /* @__PURE__ */ new Date();
630
- const replyId = nanoid();
631
- const reader = res.body.getReader();
632
- const decode = createChunkDecoder();
633
- let responseMessage = {
634
- id: replyId,
635
- createdAt,
636
- content: "",
637
- role: "assistant"
638
- };
639
- while (true) {
640
- const { done, value } = await reader.read();
641
- if (done) {
642
- break;
814
+ const reader = response.body.getReader();
815
+ const isComplexMode = response.headers.get(COMPLEX_HEADER) === "true";
816
+ if (isComplexMode) {
817
+ return await parseComplexResponse({
818
+ reader,
819
+ abortControllerRef: abortController != null ? { current: abortController() } : void 0,
820
+ update: onUpdate,
821
+ onFinish(prefixMap) {
822
+ if (onFinish && prefixMap.text != null) {
823
+ onFinish(prefixMap.text);
824
+ }
825
+ }
826
+ });
827
+ } else {
828
+ const createdAt = /* @__PURE__ */ new Date();
829
+ const decode = createChunkDecoder(false);
830
+ let streamedResponse = "";
831
+ const replyId = (0, import_nanoid.nanoid)();
832
+ let responseMessage = {
833
+ id: replyId,
834
+ createdAt,
835
+ content: "",
836
+ role: "assistant"
837
+ };
838
+ while (true) {
839
+ const { done, value } = await reader.read();
840
+ if (done) {
841
+ break;
842
+ }
843
+ streamedResponse += decode(value);
844
+ if (streamedResponse.startsWith('{"function_call":')) {
845
+ responseMessage["function_call"] = streamedResponse;
846
+ } else {
847
+ responseMessage["content"] = streamedResponse;
848
+ }
849
+ appendMessage({ ...responseMessage });
850
+ if ((abortController == null ? void 0 : abortController()) === null) {
851
+ reader.cancel();
852
+ break;
853
+ }
643
854
  }
644
- streamedResponse += decode(value);
645
- const functionStart = streamedResponse.indexOf("{");
646
- if (functionStart !== -1) {
647
- const matches = /(.*?)(?:({"function_call".*?}})(.*))?$/gs.exec(
648
- streamedResponse
649
- );
650
- responseMessage.content = `${(_c = matches == null ? void 0 : matches[1]) != null ? _c : ""}${(_d = matches == null ? void 0 : matches[3]) != null ? _d : ""}`;
651
- responseMessage.function_call = matches == null ? void 0 : matches[2];
652
- } else {
653
- responseMessage.content = streamedResponse;
855
+ if (streamedResponse.startsWith('{"function_call":')) {
856
+ const parsedFunctionCall = JSON.parse(streamedResponse).function_call;
857
+ responseMessage["function_call"] = parsedFunctionCall;
858
+ appendMessage({ ...responseMessage });
654
859
  }
655
- mutate([...chatRequest.messages, { ...responseMessage }]);
656
- if (abortControllerRef === null) {
657
- reader.cancel();
658
- break;
860
+ if (onFinish) {
861
+ onFinish(responseMessage);
659
862
  }
863
+ return responseMessage;
660
864
  }
661
- if (typeof responseMessage.function_call === "string") {
662
- const parsedFunctionCall = JSON.parse(
663
- responseMessage.function_call
664
- ).function_call;
665
- responseMessage.function_call = parsedFunctionCall;
666
- mutate([...chatRequest.messages, { ...responseMessage }]);
667
- }
668
- if (onFinish) {
669
- onFinish(responseMessage);
865
+ }
866
+
867
+ // shared/process-chat-stream.ts
868
+ async function processChatStream({
869
+ getStreamedResponse: getStreamedResponse2,
870
+ experimental_onFunctionCall,
871
+ updateChatRequest,
872
+ getCurrentMessages
873
+ }) {
874
+ while (true) {
875
+ const messagesAndDataOrJustMessage = await getStreamedResponse2();
876
+ if ("messages" in messagesAndDataOrJustMessage) {
877
+ let hasFollowingResponse = false;
878
+ for (const message of messagesAndDataOrJustMessage.messages) {
879
+ if (message.function_call === void 0 || typeof message.function_call === "string") {
880
+ continue;
881
+ }
882
+ hasFollowingResponse = true;
883
+ if (experimental_onFunctionCall) {
884
+ const functionCall = message.function_call;
885
+ const functionCallResponse = await experimental_onFunctionCall(
886
+ getCurrentMessages(),
887
+ functionCall
888
+ );
889
+ if (functionCallResponse === void 0) {
890
+ hasFollowingResponse = false;
891
+ break;
892
+ }
893
+ updateChatRequest(functionCallResponse);
894
+ }
895
+ }
896
+ if (!hasFollowingResponse) {
897
+ break;
898
+ }
899
+ } else {
900
+ const streamedResponseMessage = messagesAndDataOrJustMessage;
901
+ if (streamedResponseMessage.function_call === void 0 || typeof streamedResponseMessage.function_call === "string") {
902
+ break;
903
+ }
904
+ if (experimental_onFunctionCall) {
905
+ const functionCall = streamedResponseMessage.function_call;
906
+ const functionCallResponse = await experimental_onFunctionCall(getCurrentMessages(), functionCall);
907
+ if (functionCallResponse === void 0)
908
+ break;
909
+ updateChatRequest(functionCallResponse);
910
+ }
911
+ }
670
912
  }
671
- return responseMessage;
913
+ }
914
+
915
+ // svelte/use-chat.ts
916
+ var getStreamedResponse = async (api, chatRequest, mutate, mutateStreamData, existingData, extraMetadata, previousMessages, abortControllerRef, onFinish, onResponse, sendExtraMessageFields) => {
917
+ var _a, _b;
918
+ mutate(chatRequest.messages);
919
+ const constructedMessagesPayload = sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(({ role, content, name, function_call }) => ({
920
+ role,
921
+ content,
922
+ ...name !== void 0 && { name },
923
+ ...function_call !== void 0 && {
924
+ function_call
925
+ }
926
+ }));
927
+ return await callApi({
928
+ api,
929
+ messages: constructedMessagesPayload,
930
+ body: {
931
+ ...extraMetadata.body,
932
+ ...(_a = chatRequest.options) == null ? void 0 : _a.body,
933
+ ...chatRequest.functions !== void 0 && {
934
+ functions: chatRequest.functions
935
+ },
936
+ ...chatRequest.function_call !== void 0 && {
937
+ function_call: chatRequest.function_call
938
+ }
939
+ },
940
+ credentials: extraMetadata.credentials,
941
+ headers: {
942
+ ...extraMetadata.headers,
943
+ ...(_b = chatRequest.options) == null ? void 0 : _b.headers
944
+ },
945
+ abortController: () => abortControllerRef,
946
+ appendMessage(message) {
947
+ mutate([...chatRequest.messages, message]);
948
+ },
949
+ restoreMessagesOnFailure() {
950
+ mutate(previousMessages);
951
+ },
952
+ onResponse,
953
+ onUpdate(merged, data) {
954
+ mutate([...chatRequest.messages, ...merged]);
955
+ mutateStreamData([...existingData || [], ...data || []]);
956
+ },
957
+ onFinish
958
+ });
672
959
  };
673
960
  var uniqueId = 0;
674
961
  var store = {};
@@ -696,6 +983,7 @@ function useChat({
696
983
  fetcher: () => store[key] || initialMessages,
697
984
  fallbackData: initialMessages
698
985
  });
986
+ const streamData = (0, import_store.writable)(void 0);
699
987
  const loading = (0, import_store.writable)(false);
700
988
  data.set(initialMessages);
701
989
  const mutate = (data2) => {
@@ -715,29 +1003,28 @@ function useChat({
715
1003
  error.set(void 0);
716
1004
  loading.set(true);
717
1005
  abortController = new AbortController();
718
- while (true) {
719
- const streamedResponseMessage = await getStreamedResponse(
1006
+ await processChatStream({
1007
+ getStreamedResponse: () => getStreamedResponse(
720
1008
  api,
721
1009
  chatRequest,
722
1010
  mutate,
1011
+ (data2) => {
1012
+ streamData.set(data2);
1013
+ },
1014
+ (0, import_store.get)(streamData),
723
1015
  extraMetadata,
724
1016
  (0, import_store.get)(messages),
725
1017
  abortController,
726
1018
  onFinish,
727
1019
  onResponse,
728
1020
  sendExtraMessageFields
729
- );
730
- if (streamedResponseMessage.function_call === void 0 || typeof streamedResponseMessage.function_call === "string") {
731
- break;
732
- }
733
- if (experimental_onFunctionCall) {
734
- const functionCall = streamedResponseMessage.function_call;
735
- const functionCallResponse = await experimental_onFunctionCall((0, import_store.get)(messages), functionCall);
736
- if (functionCallResponse === void 0)
737
- break;
738
- chatRequest = functionCallResponse;
739
- }
740
- }
1021
+ ),
1022
+ experimental_onFunctionCall,
1023
+ updateChatRequest: (chatRequestParam) => {
1024
+ chatRequest = chatRequestParam;
1025
+ },
1026
+ getCurrentMessages: () => (0, import_store.get)(messages)
1027
+ });
741
1028
  abortController = null;
742
1029
  return null;
743
1030
  } catch (err) {
@@ -831,7 +1118,8 @@ function useChat({
831
1118
  setMessages,
832
1119
  input,
833
1120
  handleSubmit,
834
- isLoading
1121
+ isLoading,
1122
+ data: streamData
835
1123
  };
836
1124
  }
837
1125