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