ai 3.2.38 → 3.2.40

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai",
3
- "version": "3.2.38",
3
+ "version": "3.2.40",
4
4
  "description": "Vercel AI SDK - The AI Toolkit for TypeScript and JavaScript",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -62,7 +62,7 @@
62
62
  "@ai-sdk/provider-utils": "1.0.5",
63
63
  "@ai-sdk/react": "0.0.31",
64
64
  "@ai-sdk/solid": "0.0.24",
65
- "@ai-sdk/svelte": "0.0.25",
65
+ "@ai-sdk/svelte": "0.0.26",
66
66
  "@ai-sdk/ui-utils": "0.0.21",
67
67
  "@ai-sdk/vue": "0.0.25",
68
68
  "@opentelemetry/api": "1.9.0",
@@ -1,7 +1,22 @@
1
- import { Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions, AssistantStatus, UseAssistantOptions } from '@ai-sdk/ui-utils';
2
- export { CreateMessage, Message, UseChatOptions, UseCompletionOptions } from '@ai-sdk/ui-utils';
1
+ import { UseChatOptions as UseChatOptions$1, Message, CreateMessage, ChatRequestOptions, JSONValue, RequestOptions, UseCompletionOptions, AssistantStatus, UseAssistantOptions } from '@ai-sdk/ui-utils';
2
+ export { CreateMessage, Message, UseCompletionOptions } from '@ai-sdk/ui-utils';
3
3
  import { Readable, Writable } from 'svelte/store';
4
4
 
5
+ type UseChatOptions = UseChatOptions$1 & {
6
+ /**
7
+ Maximal number of automatic roundtrips for tool calls.
8
+
9
+ An automatic tool call roundtrip is a call to the server with the
10
+ tool call results when all tool calls in the last assistant
11
+ message have results.
12
+
13
+ A maximum number is required to prevent infinite loops in the
14
+ case of misconfigured tools.
15
+
16
+ By default, it's set to 0, which will disable the feature.
17
+ */
18
+ maxToolRoundtrips?: number;
19
+ };
5
20
  type UseChatHelpers = {
6
21
  /** Current messages in the chat */
7
22
  messages: Readable<Message[]>;
@@ -41,11 +56,29 @@ type UseChatHelpers = {
41
56
  isLoading: Readable<boolean | undefined>;
42
57
  /** Additional data added on the server via StreamData */
43
58
  data: Readable<JSONValue[] | undefined>;
59
+ /**
60
+ Maximal number of automatic roundtrips for tool calls.
61
+
62
+ An automatic tool call roundtrip is a call to the server with the
63
+ tool call results when all tool calls in the last assistant
64
+ message have results.
65
+
66
+ A maximum number is required to prevent infinite loops in the
67
+ case of misconfigured tools.
68
+
69
+ By default, it's set to 0, which will disable the feature.
70
+ */
71
+ maxToolRoundtrips?: number;
44
72
  };
45
73
  /**
46
74
  * @deprecated Use `useChat` from `@ai-sdk/svelte` instead.
47
75
  */
48
- declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, experimental_onFunctionCall, experimental_onToolCall, streamMode, streamProtocol, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, keepLastMessageOnError, }?: UseChatOptions): UseChatHelpers;
76
+ declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, experimental_onFunctionCall, experimental_onToolCall, streamMode, streamProtocol, onResponse, onFinish, onError, onToolCall, credentials, headers, body, generateId, fetch, keepLastMessageOnError, maxToolRoundtrips, }?: UseChatOptions): UseChatHelpers & {
77
+ addToolResult: ({ toolCallId, result, }: {
78
+ toolCallId: string;
79
+ result: any;
80
+ }) => void;
81
+ };
49
82
 
50
83
  type UseCompletionHelpers = {
51
84
  /** The current completion result */
@@ -140,4 +173,4 @@ type UseAssistantHelpers = {
140
173
  */
141
174
  declare function useAssistant({ api, threadId: threadIdParam, credentials, headers, body, onError, fetch, }: UseAssistantOptions): UseAssistantHelpers;
142
175
 
143
- export { UseAssistantHelpers, UseChatHelpers, UseCompletionHelpers, useAssistant, useChat, useCompletion };
176
+ export { UseAssistantHelpers, UseChatHelpers, UseChatOptions, UseCompletionHelpers, useAssistant, useChat, useCompletion };
@@ -1,7 +1,22 @@
1
- import { Message, CreateMessage, ChatRequestOptions, JSONValue, UseChatOptions, RequestOptions, UseCompletionOptions, AssistantStatus, UseAssistantOptions } from '@ai-sdk/ui-utils';
2
- export { CreateMessage, Message, UseChatOptions, UseCompletionOptions } from '@ai-sdk/ui-utils';
1
+ import { UseChatOptions as UseChatOptions$1, Message, CreateMessage, ChatRequestOptions, JSONValue, RequestOptions, UseCompletionOptions, AssistantStatus, UseAssistantOptions } from '@ai-sdk/ui-utils';
2
+ export { CreateMessage, Message, UseCompletionOptions } from '@ai-sdk/ui-utils';
3
3
  import { Readable, Writable } from 'svelte/store';
4
4
 
5
+ type UseChatOptions = UseChatOptions$1 & {
6
+ /**
7
+ Maximal number of automatic roundtrips for tool calls.
8
+
9
+ An automatic tool call roundtrip is a call to the server with the
10
+ tool call results when all tool calls in the last assistant
11
+ message have results.
12
+
13
+ A maximum number is required to prevent infinite loops in the
14
+ case of misconfigured tools.
15
+
16
+ By default, it's set to 0, which will disable the feature.
17
+ */
18
+ maxToolRoundtrips?: number;
19
+ };
5
20
  type UseChatHelpers = {
6
21
  /** Current messages in the chat */
7
22
  messages: Readable<Message[]>;
@@ -41,11 +56,29 @@ type UseChatHelpers = {
41
56
  isLoading: Readable<boolean | undefined>;
42
57
  /** Additional data added on the server via StreamData */
43
58
  data: Readable<JSONValue[] | undefined>;
59
+ /**
60
+ Maximal number of automatic roundtrips for tool calls.
61
+
62
+ An automatic tool call roundtrip is a call to the server with the
63
+ tool call results when all tool calls in the last assistant
64
+ message have results.
65
+
66
+ A maximum number is required to prevent infinite loops in the
67
+ case of misconfigured tools.
68
+
69
+ By default, it's set to 0, which will disable the feature.
70
+ */
71
+ maxToolRoundtrips?: number;
44
72
  };
45
73
  /**
46
74
  * @deprecated Use `useChat` from `@ai-sdk/svelte` instead.
47
75
  */
48
- declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, experimental_onFunctionCall, experimental_onToolCall, streamMode, streamProtocol, onResponse, onFinish, onError, credentials, headers, body, generateId, fetch, keepLastMessageOnError, }?: UseChatOptions): UseChatHelpers;
76
+ declare function useChat({ api, id, initialMessages, initialInput, sendExtraMessageFields, experimental_onFunctionCall, experimental_onToolCall, streamMode, streamProtocol, onResponse, onFinish, onError, onToolCall, credentials, headers, body, generateId, fetch, keepLastMessageOnError, maxToolRoundtrips, }?: UseChatOptions): UseChatHelpers & {
77
+ addToolResult: ({ toolCallId, result, }: {
78
+ toolCallId: string;
79
+ result: any;
80
+ }) => void;
81
+ };
49
82
 
50
83
  type UseCompletionHelpers = {
51
84
  /** The current completion result */
@@ -140,4 +173,4 @@ type UseAssistantHelpers = {
140
173
  */
141
174
  declare function useAssistant({ api, threadId: threadIdParam, credentials, headers, body, onError, fetch, }: UseAssistantOptions): UseAssistantHelpers;
142
175
 
143
- export { UseAssistantHelpers, UseChatHelpers, UseCompletionHelpers, useAssistant, useChat, useCompletion };
176
+ export { UseAssistantHelpers, UseChatHelpers, UseChatOptions, UseCompletionHelpers, useAssistant, useChat, useCompletion };
@@ -528,7 +528,7 @@ var F2 = (t, e) => c.useSWR(t, e);
528
528
 
529
529
  // svelte/use-chat.ts
530
530
  var import_store = require("svelte/store");
531
- var getStreamedResponse = async (api, chatRequest, mutate, mutateStreamData, existingData, extraMetadata, previousMessages, abortControllerRef, generateId2, streamProtocol, onFinish, onResponse, sendExtraMessageFields, fetch2, keepLastMessageOnError) => {
531
+ var getStreamedResponse = async (api, chatRequest, mutate, mutateStreamData, existingData, extraMetadata, previousMessages, abortControllerRef, generateId2, streamProtocol, onFinish, onResponse, onToolCall, sendExtraMessageFields, fetch2, keepLastMessageOnError) => {
532
532
  mutate(chatRequest.messages);
533
533
  const constructedMessagesPayload = sendExtraMessageFields ? chatRequest.messages : chatRequest.messages.map(
534
534
  ({
@@ -539,13 +539,15 @@ var getStreamedResponse = async (api, chatRequest, mutate, mutateStreamData, exi
539
539
  annotations,
540
540
  function_call,
541
541
  tool_calls,
542
- tool_call_id
542
+ tool_call_id,
543
+ toolInvocations
543
544
  }) => ({
544
545
  role,
545
546
  content,
546
547
  ...name !== void 0 && { name },
547
548
  ...data !== void 0 && { data },
548
549
  ...annotations !== void 0 && { annotations },
550
+ ...toolInvocations !== void 0 && { toolInvocations },
549
551
  // outdated function/tool call handling (TODO deprecate):
550
552
  tool_call_id,
551
553
  ...function_call !== void 0 && { function_call },
@@ -591,13 +593,26 @@ var getStreamedResponse = async (api, chatRequest, mutate, mutateStreamData, exi
591
593
  },
592
594
  onFinish,
593
595
  generateId: generateId2,
594
- onToolCall: void 0,
595
- // not implemented yet
596
+ onToolCall,
596
597
  fetch: fetch2
597
598
  });
598
599
  };
599
600
  var uniqueId = 0;
600
601
  var store = {};
602
+ function isAssistantMessageWithCompletedToolCalls(message) {
603
+ return message.role === "assistant" && message.toolInvocations && message.toolInvocations.length > 0 && message.toolInvocations.every((toolInvocation) => "result" in toolInvocation);
604
+ }
605
+ function countTrailingAssistantMessages(messages) {
606
+ let count = 0;
607
+ for (let i = messages.length - 1; i >= 0; i--) {
608
+ if (messages[i].role === "assistant") {
609
+ count++;
610
+ } else {
611
+ break;
612
+ }
613
+ }
614
+ return count;
615
+ }
601
616
  function useChat({
602
617
  api = "/api/chat",
603
618
  id,
@@ -611,12 +626,14 @@ function useChat({
611
626
  onResponse,
612
627
  onFinish,
613
628
  onError,
629
+ onToolCall,
614
630
  credentials,
615
631
  headers,
616
632
  body,
617
633
  generateId: generateId2 = import_ui_utils.generateId,
618
634
  fetch: fetch2,
619
- keepLastMessageOnError = false
635
+ keepLastMessageOnError = false,
636
+ maxToolRoundtrips = 0
620
637
  } = {}) {
621
638
  if (streamMode) {
622
639
  streamProtocol != null ? streamProtocol : streamProtocol = streamMode === "text" ? "text" : void 0;
@@ -647,6 +664,8 @@ function useChat({
647
664
  };
648
665
  const error = (0, import_store.writable)(void 0);
649
666
  async function triggerRequest(chatRequest) {
667
+ const messagesSnapshot = (0, import_store.get)(messages);
668
+ const messageCount = messagesSnapshot.length;
650
669
  try {
651
670
  error.set(void 0);
652
671
  loading.set(true);
@@ -667,6 +686,7 @@ function useChat({
667
686
  streamProtocol,
668
687
  onFinish,
669
688
  onResponse,
689
+ onToolCall,
670
690
  sendExtraMessageFields,
671
691
  fetch2,
672
692
  keepLastMessageOnError
@@ -679,7 +699,6 @@ function useChat({
679
699
  getCurrentMessages: () => (0, import_store.get)(messages)
680
700
  });
681
701
  abortController = null;
682
- return null;
683
702
  } catch (err) {
684
703
  if (err.name === "AbortError") {
685
704
  abortController = null;
@@ -692,6 +711,18 @@ function useChat({
692
711
  } finally {
693
712
  loading.set(false);
694
713
  }
714
+ const newMessagesSnapshot = (0, import_store.get)(messages);
715
+ const lastMessage = newMessagesSnapshot[newMessagesSnapshot.length - 1];
716
+ if (
717
+ // ensure we actually have new messages (to prevent infinite loops in case of errors):
718
+ newMessagesSnapshot.length > messageCount && // ensure there is a last message:
719
+ lastMessage != null && // check if the feature is enabled:
720
+ maxToolRoundtrips > 0 && // check that roundtrip is possible:
721
+ isAssistantMessageWithCompletedToolCalls(lastMessage) && // limit the number of automatic roundtrips:
722
+ countTrailingAssistantMessages(newMessagesSnapshot) <= maxToolRoundtrips
723
+ ) {
724
+ await triggerRequest({ messages: newMessagesSnapshot });
725
+ }
695
726
  }
696
727
  const append = async (message, {
697
728
  options,
@@ -760,11 +791,7 @@ function useChat({
760
791
  options: requestOptions,
761
792
  headers: requestOptions.headers,
762
793
  body: requestOptions.body,
763
- data: data2,
764
- ...functions !== void 0 && { functions },
765
- ...function_call !== void 0 && { function_call },
766
- ...tools !== void 0 && { tools },
767
- ...tool_choice !== void 0 && { tool_choice }
794
+ data: data2
768
795
  };
769
796
  return triggerRequest(chatRequest);
770
797
  };
@@ -785,17 +812,19 @@ function useChat({
785
812
  var _a, _b, _c, _d, _e;
786
813
  (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);
787
814
  const inputValue = (0, import_store.get)(input);
815
+ if (!inputValue && !options.allowEmptySubmit)
816
+ return;
788
817
  const requestOptions = {
789
818
  headers: (_c = options.headers) != null ? _c : (_b = options.options) == null ? void 0 : _b.headers,
790
819
  body: (_e = options.body) != null ? _e : (_d = options.options) == null ? void 0 : _d.body
791
820
  };
792
821
  const chatRequest = {
793
- messages: inputValue ? (0, import_store.get)(messages).concat({
822
+ messages: !inputValue && options.allowEmptySubmit ? (0, import_store.get)(messages) : (0, import_store.get)(messages).concat({
794
823
  id: generateId2(),
795
824
  content: inputValue,
796
825
  role: "user",
797
826
  createdAt: /* @__PURE__ */ new Date()
798
- }) : (0, import_store.get)(messages),
827
+ }),
799
828
  options: requestOptions,
800
829
  body: requestOptions.body,
801
830
  headers: requestOptions.headers,
@@ -810,6 +839,29 @@ function useChat({
810
839
  return $isSWRLoading || $loading;
811
840
  }
812
841
  );
842
+ const addToolResult = ({
843
+ toolCallId,
844
+ result
845
+ }) => {
846
+ var _a;
847
+ const messagesSnapshot = (_a = (0, import_store.get)(messages)) != null ? _a : [];
848
+ const updatedMessages = messagesSnapshot.map(
849
+ (message, index, arr) => (
850
+ // update the tool calls in the last assistant message:
851
+ index === arr.length - 1 && message.role === "assistant" && message.toolInvocations ? {
852
+ ...message,
853
+ toolInvocations: message.toolInvocations.map(
854
+ (toolInvocation) => toolInvocation.toolCallId === toolCallId ? { ...toolInvocation, result } : toolInvocation
855
+ )
856
+ } : message
857
+ )
858
+ );
859
+ messages.set(updatedMessages);
860
+ const lastMessage = updatedMessages[updatedMessages.length - 1];
861
+ if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {
862
+ triggerRequest({ messages: updatedMessages });
863
+ }
864
+ };
813
865
  return {
814
866
  messages,
815
867
  error,
@@ -820,7 +872,8 @@ function useChat({
820
872
  input,
821
873
  handleSubmit,
822
874
  isLoading,
823
- data: streamData
875
+ data: streamData,
876
+ addToolResult
824
877
  };
825
878
  }
826
879