ai 5.0.0-alpha.6 → 5.0.0-alpha.7

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/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { ToolResultContent, Schema, ToolCall, ToolResult, IdGenerator, FetchFunction, Validator, StandardSchemaV1 } from '@ai-sdk/provider-utils';
1
+ import { ToolResultContent, Schema, ToolCall, ToolResult, IdGenerator, Validator, StandardSchemaV1, FetchFunction } from '@ai-sdk/provider-utils';
2
2
  export { IdGenerator, Schema, ToolCall, ToolResult, asSchema, createIdGenerator, generateId, jsonSchema } from '@ai-sdk/provider-utils';
3
3
  import { AISDKError, SharedV2ProviderMetadata, SharedV2ProviderOptions, EmbeddingModelV2, EmbeddingModelV2Embedding, ImageModelV2, ImageModelV2CallWarning, ImageModelV2ProviderMetadata, JSONValue as JSONValue$1, LanguageModelV2, LanguageModelV2FinishReason, LanguageModelV2CallWarning, LanguageModelV2Source, SpeechModelV1, SpeechModelV1CallWarning, TranscriptionModelV1, TranscriptionModelV1CallWarning, LanguageModelV2Usage, JSONObject, LanguageModelV2ToolCall, JSONSchema7, LanguageModelV2CallOptions, JSONParseError, TypeValidationError, LanguageModelV2Middleware, ProviderV2, NoSuchModelError } from '@ai-sdk/provider';
4
4
  export { AISDKError, APICallError, EmptyResponseBodyError, InvalidPromptError, InvalidResponseDataError, JSONParseError, JSONSchema7, LoadAPIKeyError, NoContentGeneratedError, NoSuchModelError, TypeValidationError, UnsupportedFunctionalityError } from '@ai-sdk/provider';
@@ -2115,13 +2115,10 @@ It is optional for backwards compatibility.
2115
2115
  */
2116
2116
  type ToolInvocation = ({
2117
2117
  state: 'partial-call';
2118
- step?: number;
2119
2118
  } & ToolCall<string, any>) | ({
2120
2119
  state: 'call';
2121
- step?: number;
2122
2120
  } & ToolCall<string, any>) | ({
2123
2121
  state: 'result';
2124
- step?: number;
2125
2122
  } & ToolResult<string, any, any>);
2126
2123
  /**
2127
2124
  The data types that can be used in the UI message for the UI message data parts.
@@ -2289,15 +2286,31 @@ declare function pipeTextStreamToResponse({ response, status, statusText, header
2289
2286
  textStream: ReadableStream<string>;
2290
2287
  } & ResponseInit): void;
2291
2288
 
2292
- /**
2293
- * Appends a client message to the messages array.
2294
- * If the last message in the array has the same id as the new message, it will be replaced.
2295
- * Otherwise, the new message will be appended.
2296
- */
2297
- declare function appendClientMessage({ messages, message, }: {
2298
- messages: UIMessage[];
2299
- message: UIMessage;
2300
- }): UIMessage<unknown, UIDataTypes>[];
2289
+ declare const getOriginalFetch: () => typeof fetch;
2290
+ declare function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol, setCompletion, setLoading, setError, setAbortController, onFinish, onError, fetch, }: {
2291
+ api: string;
2292
+ prompt: string;
2293
+ credentials: RequestCredentials | undefined;
2294
+ headers: HeadersInit | undefined;
2295
+ body: Record<string, any>;
2296
+ streamProtocol: 'data' | 'text' | undefined;
2297
+ setCompletion: (completion: string) => void;
2298
+ setLoading: (loading: boolean) => void;
2299
+ setError: (error: Error | undefined) => void;
2300
+ setAbortController: (abortController: AbortController | null) => void;
2301
+ onFinish: ((prompt: string, completion: string) => void) | undefined;
2302
+ onError: ((error: Error) => void) | undefined;
2303
+ fetch: ReturnType<typeof getOriginalFetch> | undefined;
2304
+ }): Promise<string | null | undefined>;
2305
+
2306
+ type Job = () => Promise<void>;
2307
+
2308
+ declare class SerialJobExecutor {
2309
+ private queue;
2310
+ private isProcessing;
2311
+ private processQueue;
2312
+ run(job: Job): Promise<void>;
2313
+ }
2301
2314
 
2302
2315
  /**
2303
2316
  The result of an `embed` call.
@@ -3695,15 +3708,6 @@ declare function parsePartialJson(jsonText: string | undefined): Promise<{
3695
3708
  state: 'undefined-input' | 'successful-parse' | 'repaired-parse' | 'failed-parse';
3696
3709
  }>;
3697
3710
 
3698
- type Job = () => Promise<void>;
3699
-
3700
- declare class SerialJobExecutor {
3701
- private queue;
3702
- private isProcessing;
3703
- private processQueue;
3704
- run(job: Job): Promise<void>;
3705
- }
3706
-
3707
3711
  /**
3708
3712
  * Creates a ReadableStream that emits the provided values with an optional delay between each value.
3709
3713
  *
@@ -4448,114 +4452,72 @@ interface ChatTransport<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> {
4448
4452
  requestType: 'generate' | 'resume';
4449
4453
  }) => Promise<ReadableStream<UIMessageStreamPart>>;
4450
4454
  }
4451
- declare class DefaultChatTransport<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> implements ChatTransport<MESSAGE_METADATA, DATA_TYPES> {
4452
- private api;
4453
- private credentials?;
4454
- private headers?;
4455
- private body?;
4456
- private fetch?;
4457
- private prepareRequestBody?;
4458
- constructor({ api, credentials, headers, body, fetch, prepareRequestBody, }: {
4459
- api: string;
4460
- /**
4461
- * The credentials mode to be used for the fetch request.
4462
- * Possible values are: 'omit', 'same-origin', 'include'.
4463
- * Defaults to 'same-origin'.
4464
- */
4465
- credentials?: RequestCredentials;
4466
- /**
4467
- * HTTP headers to be sent with the API request.
4468
- */
4469
- headers?: Record<string, string> | Headers;
4470
- /**
4471
- * Extra body object to be sent with the API request.
4472
- * @example
4473
- * Send a `sessionId` to the API along with the messages.
4474
- * ```js
4475
- * useChat({
4476
- * body: {
4477
- * sessionId: '123',
4478
- * }
4479
- * })
4480
- * ```
4481
- */
4482
- body?: object;
4483
- /**
4484
- Custom fetch implementation. You can use it as a middleware to intercept requests,
4485
- or to provide a custom fetch implementation for e.g. testing.
4486
- */
4487
- fetch?: FetchFunction;
4488
- /**
4489
- * When a function is provided, it will be used
4490
- * to prepare the request body for the chat API. This can be useful for
4491
- * customizing the request body based on the messages and data in the chat.
4492
- *
4493
- * @param id The id of the chat.
4494
- * @param messages The current messages in the chat.
4495
- * @param requestBody The request body object passed in the chat request.
4496
- */
4497
- prepareRequestBody?: (options: {
4498
- chatId: string;
4499
- messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];
4500
- requestBody?: object;
4501
- }) => unknown;
4502
- });
4503
- submitMessages({ chatId, messages, abortController, body, headers, requestType, }: Parameters<ChatTransport<MESSAGE_METADATA, DATA_TYPES>['submitMessages']>[0]): Promise<ReadableStream<UIMessageStreamPart>>;
4504
- }
4505
- declare class TextStreamChatTransport<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> implements ChatTransport<MESSAGE_METADATA, DATA_TYPES> {
4506
- private api;
4507
- private credentials?;
4508
- private headers?;
4509
- private body?;
4510
- private fetch?;
4511
- private prepareRequestBody?;
4512
- constructor({ api, credentials, headers, body, fetch, prepareRequestBody, }: {
4513
- api: string;
4514
- /**
4515
- * The credentials mode to be used for the fetch request.
4516
- * Possible values are: 'omit', 'same-origin', 'include'.
4517
- * Defaults to 'same-origin'.
4518
- */
4519
- credentials?: RequestCredentials;
4520
- /**
4521
- * HTTP headers to be sent with the API request.
4522
- */
4523
- headers?: Record<string, string> | Headers;
4524
- /**
4525
- * Extra body object to be sent with the API request.
4526
- * @example
4527
- * Send a `sessionId` to the API along with the messages.
4528
- * ```js
4529
- * useChat({
4530
- * body: {
4531
- * sessionId: '123',
4532
- * }
4533
- * })
4534
- * ```
4535
- */
4536
- body?: object;
4537
- /**
4538
- Custom fetch implementation. You can use it as a middleware to intercept requests,
4539
- or to provide a custom fetch implementation for e.g. testing.
4540
- */
4541
- fetch?: FetchFunction;
4542
- /**
4543
- * When a function is provided, it will be used
4544
- * to prepare the request body for the chat API. This can be useful for
4545
- * customizing the request body based on the messages and data in the chat.
4546
- *
4547
- * @param id The id of the chat.
4548
- * @param messages The current messages in the chat.
4549
- * @param requestBody The request body object passed in the chat request.
4550
- */
4551
- prepareRequestBody?: (options: {
4552
- chatId: string;
4553
- messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];
4554
- requestBody?: object;
4555
- }) => unknown;
4556
- });
4557
- submitMessages({ chatId, messages, abortController, body, headers, requestType, }: Parameters<ChatTransport<MESSAGE_METADATA, DATA_TYPES>['submitMessages']>[0]): Promise<ReadableStream<UIMessageStreamPart>>;
4558
- }
4455
+
4456
+ type ChatRequestOptions = {
4457
+ /**
4458
+ Additional headers that should be to be passed to the API endpoint.
4459
+ */
4460
+ headers?: Record<string, string> | Headers;
4461
+ /**
4462
+ Additional body JSON properties that should be sent to the API endpoint.
4463
+ */
4464
+ body?: object;
4465
+ };
4466
+ type UseChatOptions<MESSAGE_METADATA = unknown, DATA_TYPE_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> = {
4467
+ /**
4468
+ * A unique identifier for the chat. If not provided, a random one will be
4469
+ * generated. When provided, the `useChat` hook with the same `id` will
4470
+ * have shared states across components.
4471
+ */
4472
+ chatId?: string;
4473
+ /**
4474
+ * Initial input of the chat.
4475
+ */
4476
+ initialInput?: string;
4477
+ /**
4478
+ Optional callback function that is invoked when a tool call is received.
4479
+ Intended for automatic client-side tool execution.
4480
+
4481
+ You can optionally return a result for the tool call,
4482
+ either synchronously or asynchronously.
4483
+ */
4484
+ onToolCall?: ({ toolCall, }: {
4485
+ toolCall: ToolCall<string, unknown>;
4486
+ }) => void | Promise<unknown> | unknown;
4487
+ /**
4488
+ * Optional callback function that is called when the assistant message is finished streaming.
4489
+ *
4490
+ * @param message The message that was streamed.
4491
+ */
4492
+ onFinish?: (options: {
4493
+ message: UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_TYPE_SCHEMAS>>;
4494
+ }) => void;
4495
+ /**
4496
+ * Callback function to be called when an error is encountered.
4497
+ */
4498
+ onError?: (error: Error) => void;
4499
+ /**
4500
+ * A way to provide a function that is going to be used for ids for messages and the chat.
4501
+ * If not provided the default AI SDK `generateId` is used.
4502
+ */
4503
+ generateId?: IdGenerator;
4504
+ /**
4505
+ * Chat store that should be used.
4506
+ * It must not change during the component lifecycle.
4507
+ *
4508
+ * When a ChatStore is provided, it will be used as is.
4509
+ * It should be stable and the stability is guaranteed by the user.
4510
+ *
4511
+ * When a function is provided, it will be called to create a new chat store.
4512
+ * The function will be called when the hook is mounted and the chat store will be
4513
+ * created.
4514
+ * The function will be called with the same arguments as the hook is called with.
4515
+ * The function should return a ChatStoreOptions object.
4516
+ *
4517
+ * When no value is provided, a default chat store will be created.
4518
+ */
4519
+ chatStore?: ChatStore<MESSAGE_METADATA, DATA_TYPE_SCHEMAS> | (() => ChatStoreOptions<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>);
4520
+ };
4559
4521
 
4560
4522
  type StreamingUIMessageState<MESSAGE_METADATA = unknown, UI_DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> = {
4561
4523
  message: UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>;
@@ -4563,11 +4525,9 @@ type StreamingUIMessageState<MESSAGE_METADATA = unknown, UI_DATA_PART_SCHEMAS ex
4563
4525
  activeReasoningPart: ReasoningUIPart | undefined;
4564
4526
  partialToolCalls: Record<string, {
4565
4527
  text: string;
4566
- step: number;
4567
4528
  index: number;
4568
4529
  toolName: string;
4569
4530
  }>;
4570
- step: number;
4571
4531
  };
4572
4532
 
4573
4533
  interface ChatStoreSubscriber {
@@ -4703,123 +4663,42 @@ declare class ChatStore<MESSAGE_METADATA = unknown, UI_DATA_PART_SCHEMAS extends
4703
4663
  private triggerRequest;
4704
4664
  }
4705
4665
 
4706
- type ChatRequestOptions = {
4666
+ declare function convertFileListToFileUIParts(files: FileList | undefined): Promise<Array<FileUIPart>>;
4667
+
4668
+ /**
4669
+ Converts an array of messages from useChat into an array of CoreMessages that can be used
4670
+ with the AI core functions (e.g. `streamText`).
4671
+ */
4672
+ declare function convertToModelMessages<TOOLS extends ToolSet = never>(messages: Array<Omit<UIMessage, 'id'>>, options?: {
4673
+ tools?: TOOLS;
4674
+ }): ModelMessage[];
4675
+ /**
4676
+ @deprecated Use `convertToModelMessages` instead.
4677
+ */
4678
+ declare const convertToCoreMessages: typeof convertToModelMessages;
4679
+
4680
+ interface DefaultChatStoreOptions<MESSAGE_METADATA = unknown, UI_DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> {
4707
4681
  /**
4708
- Additional headers that should be to be passed to the API endpoint.
4682
+ * Schema for the message metadata. Validates the message metadata.
4683
+ * Message metadata can be undefined or must match the schema.
4709
4684
  */
4710
- headers?: Record<string, string> | Headers;
4685
+ messageMetadataSchema?: Validator<MESSAGE_METADATA> | StandardSchemaV1<MESSAGE_METADATA>;
4711
4686
  /**
4712
- Additional body JSON properties that should be sent to the API endpoint.
4687
+ * Schema for the data types. Validates the data types.
4713
4688
  */
4714
- body?: object;
4715
- };
4716
- type UseChatOptions<MESSAGE_METADATA = unknown, DATA_TYPE_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> = {
4689
+ dataPartSchemas?: UI_DATA_PART_SCHEMAS;
4717
4690
  /**
4718
- * A unique identifier for the chat. If not provided, a random one will be
4719
- * generated. When provided, the `useChat` hook with the same `id` will
4720
- * have shared states across components.
4691
+ * The API endpoint that accepts a `{ messages: Message[] }` object and returns
4692
+ * a stream of tokens of the AI chat response.
4693
+ *
4694
+ * Defaults to `/api/chat`
4721
4695
  */
4722
- chatId?: string;
4696
+ api?: string;
4723
4697
  /**
4724
- * Initial input of the chat.
4698
+ * A way to provide a function that is going to be used for ids for messages and the chat.
4699
+ * If not provided the default AI SDK `generateId` is used.
4725
4700
  */
4726
- initialInput?: string;
4727
- /**
4728
- Optional callback function that is invoked when a tool call is received.
4729
- Intended for automatic client-side tool execution.
4730
-
4731
- You can optionally return a result for the tool call,
4732
- either synchronously or asynchronously.
4733
- */
4734
- onToolCall?: ({ toolCall, }: {
4735
- toolCall: ToolCall<string, unknown>;
4736
- }) => void | Promise<unknown> | unknown;
4737
- /**
4738
- * Optional callback function that is called when the assistant message is finished streaming.
4739
- *
4740
- * @param message The message that was streamed.
4741
- */
4742
- onFinish?: (options: {
4743
- message: UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_TYPE_SCHEMAS>>;
4744
- }) => void;
4745
- /**
4746
- * Callback function to be called when an error is encountered.
4747
- */
4748
- onError?: (error: Error) => void;
4749
- /**
4750
- * A way to provide a function that is going to be used for ids for messages and the chat.
4751
- * If not provided the default AI SDK `generateId` is used.
4752
- */
4753
- generateId?: IdGenerator;
4754
- /**
4755
- * Chat store that should be used.
4756
- * It must not change during the component lifecycle.
4757
- *
4758
- * When a ChatStore is provided, it will be used as is.
4759
- * It should be stable and the stability is guaranteed by the user.
4760
- *
4761
- * When a function is provided, it will be called to create a new chat store.
4762
- * The function will be called when the hook is mounted and the chat store will be
4763
- * created.
4764
- * The function will be called with the same arguments as the hook is called with.
4765
- * The function should return a ChatStoreOptions object.
4766
- *
4767
- * When no value is provided, a default chat store will be created.
4768
- */
4769
- chatStore?: ChatStore<MESSAGE_METADATA, DATA_TYPE_SCHEMAS> | (() => ChatStoreOptions<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>);
4770
- };
4771
- type OriginalUseChatOptions<MESSAGE_METADATA = unknown> = {
4772
- /**
4773
- * Schema for the message metadata. Validates the message metadata.
4774
- * Message metadata can be undefined or must match the schema.
4775
- */
4776
- messageMetadataSchema?: Schema<MESSAGE_METADATA>;
4777
- /**
4778
- * The API endpoint that accepts a `{ messages: Message[] }` object and returns
4779
- * a stream of tokens of the AI chat response. Defaults to `/api/chat`.
4780
- */
4781
- api?: string;
4782
- /**
4783
- * A unique identifier for the chat. If not provided, a random one will be
4784
- * generated. When provided, the `useChat` hook with the same `id` will
4785
- * have shared states across components.
4786
- */
4787
- chatId?: string;
4788
- /**
4789
- * Initial messages of the chat. Useful to load an existing chat history.
4790
- */
4791
- initialMessages?: UIMessage<NoInfer<MESSAGE_METADATA>>[];
4792
- /**
4793
- * Initial input of the chat.
4794
- */
4795
- initialInput?: string;
4796
- /**
4797
- Optional callback function that is invoked when a tool call is received.
4798
- Intended for automatic client-side tool execution.
4799
-
4800
- You can optionally return a result for the tool call,
4801
- either synchronously or asynchronously.
4802
- */
4803
- onToolCall?: ({ toolCall, }: {
4804
- toolCall: ToolCall<string, unknown>;
4805
- }) => void | Promise<unknown> | unknown;
4806
- /**
4807
- * Optional callback function that is called when the assistant message is finished streaming.
4808
- *
4809
- * @param message The message that was streamed.
4810
- */
4811
- onFinish?: (options: {
4812
- message: UIMessage<NoInfer<MESSAGE_METADATA>>;
4813
- }) => void;
4814
- /**
4815
- * Callback function to be called when an error is encountered.
4816
- */
4817
- onError?: (error: Error) => void;
4818
- /**
4819
- * A way to provide a function that is going to be used for ids for messages and the chat.
4820
- * If not provided the default AI SDK `generateId` is used.
4821
- */
4822
- generateId?: IdGenerator;
4701
+ generateId?: IdGenerator;
4823
4702
  /**
4824
4703
  * The credentials mode to be used for the fetch request.
4825
4704
  * Possible values are: 'omit', 'same-origin', 'include'.
@@ -4844,109 +4723,152 @@ type OriginalUseChatOptions<MESSAGE_METADATA = unknown> = {
4844
4723
  */
4845
4724
  body?: object;
4846
4725
  /**
4847
- Streaming protocol that is used. Defaults to `ui-message`.
4848
- */
4849
- streamProtocol?: 'ui-message' | 'text';
4850
- /**
4851
- Custom fetch implementation. You can use it as a middleware to intercept requests,
4852
- or to provide a custom fetch implementation for e.g. testing.
4853
- */
4726
+ Custom fetch implementation. You can use it as a middleware to intercept requests,
4727
+ or to provide a custom fetch implementation for e.g. testing.
4728
+ */
4854
4729
  fetch?: FetchFunction;
4855
4730
  /**
4856
- Maximum number of sequential LLM calls (steps), e.g. when you use tool calls.
4857
- Must be at least 1.
4731
+ Maximum number of sequential LLM calls (steps), e.g. when you use tool calls.
4732
+ Must be at least 1.
4858
4733
 
4859
- A maximum number is required to prevent infinite loops in the case of misconfigured tools.
4734
+ A maximum number is required to prevent infinite loops in the case of misconfigured tools.
4860
4735
 
4861
- By default, it's set to 1, which means that only a single LLM call is made.
4862
- */
4736
+ By default, it's set to 1, which means that only a single LLM call is made.
4737
+ */
4863
4738
  maxSteps?: number;
4864
- };
4865
-
4866
- declare const getOriginalFetch$1: () => typeof fetch;
4867
- declare function callChatApi<MESSAGE_METADATA>({ api, body, streamProtocol, credentials, headers, abortController, onUpdate, onFinish, onToolCall, generateId, fetch, lastMessage, requestType, messageMetadataSchema, }: {
4868
- api: string;
4869
- body: Record<string, any>;
4870
- streamProtocol: 'ui-message' | 'text' | undefined;
4871
- credentials: RequestCredentials | undefined;
4872
- headers: HeadersInit | undefined;
4873
- abortController: (() => AbortController | null) | undefined;
4874
- onUpdate: (options: {
4875
- message: UIMessage<MESSAGE_METADATA>;
4876
- }) => void;
4877
- onFinish: UseChatOptions<MESSAGE_METADATA>['onFinish'];
4878
- onToolCall: UseChatOptions<MESSAGE_METADATA>['onToolCall'];
4879
- generateId: IdGenerator;
4880
- fetch: ReturnType<typeof getOriginalFetch$1> | undefined;
4881
- lastMessage: UIMessage<MESSAGE_METADATA> | undefined;
4882
- requestType?: 'generate' | 'resume';
4883
- messageMetadataSchema?: Schema<MESSAGE_METADATA>;
4884
- }): Promise<void>;
4885
-
4886
- declare const getOriginalFetch: () => typeof fetch;
4887
- declare function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol, setCompletion, setLoading, setError, setAbortController, onFinish, onError, fetch, }: {
4888
- api: string;
4889
- prompt: string;
4890
- credentials: RequestCredentials | undefined;
4891
- headers: HeadersInit | undefined;
4892
- body: Record<string, any>;
4893
- streamProtocol: 'data' | 'text' | undefined;
4894
- setCompletion: (completion: string) => void;
4895
- setLoading: (loading: boolean) => void;
4896
- setError: (error: Error | undefined) => void;
4897
- setAbortController: (abortController: AbortController | null) => void;
4898
- onFinish: ((prompt: string, completion: string) => void) | undefined;
4899
- onError: ((error: Error) => void) | undefined;
4900
- fetch: ReturnType<typeof getOriginalFetch> | undefined;
4901
- }): Promise<string | null | undefined>;
4902
-
4903
- declare function convertFileListToFileUIParts(files: FileList | undefined): Promise<Array<FileUIPart>>;
4904
-
4905
- /**
4906
- Converts an array of messages from useChat into an array of CoreMessages that can be used
4907
- with the AI core functions (e.g. `streamText`).
4908
- */
4909
- declare function convertToModelMessages<TOOLS extends ToolSet = never>(messages: Array<Omit<UIMessage, 'id'>>, options?: {
4910
- tools?: TOOLS;
4911
- }): ModelMessage[];
4912
- /**
4913
- @deprecated Use `convertToModelMessages` instead.
4914
- */
4915
- declare const convertToCoreMessages: typeof convertToModelMessages;
4739
+ /**
4740
+ * When a function is provided, it will be used
4741
+ * to prepare the request body for the chat API. This can be useful for
4742
+ * customizing the request body based on the messages and data in the chat.
4743
+ *
4744
+ * @param chatId The id of the chat.
4745
+ * @param messages The current messages in the chat.
4746
+ * @param requestBody The request body object passed in the chat request.
4747
+ */
4748
+ prepareRequestBody?: (options: {
4749
+ chatId: string;
4750
+ messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>[];
4751
+ requestBody?: object;
4752
+ }) => unknown;
4753
+ chats?: {
4754
+ [id: string]: {
4755
+ messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>[];
4756
+ };
4757
+ };
4758
+ }
4759
+ declare function defaultChatStoreOptions<MESSAGE_METADATA = unknown, UI_DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas>({ api, fetch, credentials, headers, body, prepareRequestBody, generateId, messageMetadataSchema, maxSteps, dataPartSchemas, chats, }: DefaultChatStoreOptions<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS>): () => ChatStoreOptions<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS>;
4916
4760
 
4917
- declare function extractMaxToolInvocationStep(toolInvocations: ToolInvocation[] | undefined): number | undefined;
4761
+ declare class DefaultChatTransport<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> implements ChatTransport<MESSAGE_METADATA, DATA_TYPES> {
4762
+ private api;
4763
+ private credentials?;
4764
+ private headers?;
4765
+ private body?;
4766
+ private fetch?;
4767
+ private prepareRequestBody?;
4768
+ constructor({ api, credentials, headers, body, fetch, prepareRequestBody, }: {
4769
+ api: string;
4770
+ /**
4771
+ * The credentials mode to be used for the fetch request.
4772
+ * Possible values are: 'omit', 'same-origin', 'include'.
4773
+ * Defaults to 'same-origin'.
4774
+ */
4775
+ credentials?: RequestCredentials;
4776
+ /**
4777
+ * HTTP headers to be sent with the API request.
4778
+ */
4779
+ headers?: Record<string, string> | Headers;
4780
+ /**
4781
+ * Extra body object to be sent with the API request.
4782
+ * @example
4783
+ * Send a `sessionId` to the API along with the messages.
4784
+ * ```js
4785
+ * useChat({
4786
+ * body: {
4787
+ * sessionId: '123',
4788
+ * }
4789
+ * })
4790
+ * ```
4791
+ */
4792
+ body?: object;
4793
+ /**
4794
+ Custom fetch implementation. You can use it as a middleware to intercept requests,
4795
+ or to provide a custom fetch implementation for e.g. testing.
4796
+ */
4797
+ fetch?: FetchFunction;
4798
+ /**
4799
+ * When a function is provided, it will be used
4800
+ * to prepare the request body for the chat API. This can be useful for
4801
+ * customizing the request body based on the messages and data in the chat.
4802
+ *
4803
+ * @param id The id of the chat.
4804
+ * @param messages The current messages in the chat.
4805
+ * @param requestBody The request body object passed in the chat request.
4806
+ */
4807
+ prepareRequestBody?: (options: {
4808
+ chatId: string;
4809
+ messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];
4810
+ requestBody?: object;
4811
+ }) => unknown;
4812
+ });
4813
+ submitMessages({ chatId, messages, abortController, body, headers, requestType, }: Parameters<ChatTransport<MESSAGE_METADATA, DATA_TYPES>['submitMessages']>[0]): Promise<ReadableStream<UIMessageStreamPart>>;
4814
+ }
4918
4815
 
4919
4816
  declare function getToolInvocations(message: UIMessage): ToolInvocation[];
4920
4817
 
4921
- declare function shouldResubmitMessages({ originalMaxToolInvocationStep, originalMessageCount, maxSteps, messages, }: {
4922
- originalMaxToolInvocationStep: number | undefined;
4923
- originalMessageCount: number;
4924
- maxSteps: number;
4925
- messages: UIMessage[];
4926
- }): boolean;
4927
- /**
4928
- Check if the message is an assistant message with completed tool calls.
4929
- The last step of the message must have at least one tool invocation and
4930
- all tool invocations must have a result.
4931
- */
4932
- declare function isAssistantMessageWithCompletedToolCalls(message: UIMessage): message is UIMessage & {
4933
- role: 'assistant';
4934
- };
4935
-
4936
- /**
4937
- * Updates the result of a specific tool invocation in the last message of the given messages array.
4938
- *
4939
- * @param {object} params - The parameters object.
4940
- * @param {UIMessage[]} params.messages - An array of messages, from which the last one is updated.
4941
- * @param {string} params.toolCallId - The unique identifier for the tool invocation to update.
4942
- * @param {unknown} params.toolResult - The result object to attach to the tool invocation.
4943
- * @returns {void} This function does not return anything.
4944
- */
4945
- declare function updateToolCallResult({ messages, toolCallId, toolResult: result, }: {
4946
- messages: UIMessage[];
4947
- toolCallId: string;
4948
- toolResult: unknown;
4949
- }): void;
4818
+ declare class TextStreamChatTransport<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> implements ChatTransport<MESSAGE_METADATA, DATA_TYPES> {
4819
+ private api;
4820
+ private credentials?;
4821
+ private headers?;
4822
+ private body?;
4823
+ private fetch?;
4824
+ private prepareRequestBody?;
4825
+ constructor({ api, credentials, headers, body, fetch, prepareRequestBody, }: {
4826
+ api: string;
4827
+ /**
4828
+ * The credentials mode to be used for the fetch request.
4829
+ * Possible values are: 'omit', 'same-origin', 'include'.
4830
+ * Defaults to 'same-origin'.
4831
+ */
4832
+ credentials?: RequestCredentials;
4833
+ /**
4834
+ * HTTP headers to be sent with the API request.
4835
+ */
4836
+ headers?: Record<string, string> | Headers;
4837
+ /**
4838
+ * Extra body object to be sent with the API request.
4839
+ * @example
4840
+ * Send a `sessionId` to the API along with the messages.
4841
+ * ```js
4842
+ * useChat({
4843
+ * body: {
4844
+ * sessionId: '123',
4845
+ * }
4846
+ * })
4847
+ * ```
4848
+ */
4849
+ body?: object;
4850
+ /**
4851
+ Custom fetch implementation. You can use it as a middleware to intercept requests,
4852
+ or to provide a custom fetch implementation for e.g. testing.
4853
+ */
4854
+ fetch?: FetchFunction;
4855
+ /**
4856
+ * When a function is provided, it will be used
4857
+ * to prepare the request body for the chat API. This can be useful for
4858
+ * customizing the request body based on the messages and data in the chat.
4859
+ *
4860
+ * @param id The id of the chat.
4861
+ * @param messages The current messages in the chat.
4862
+ * @param requestBody The request body object passed in the chat request.
4863
+ */
4864
+ prepareRequestBody?: (options: {
4865
+ chatId: string;
4866
+ messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];
4867
+ requestBody?: object;
4868
+ }) => unknown;
4869
+ });
4870
+ submitMessages({ chatId, messages, abortController, body, headers, requestType, }: Parameters<ChatTransport<MESSAGE_METADATA, DATA_TYPES>['submitMessages']>[0]): Promise<ReadableStream<UIMessageStreamPart>>;
4871
+ }
4950
4872
 
4951
4873
  type CompletionRequestOptions = {
4952
4874
  /**
@@ -5020,85 +4942,4 @@ type UseCompletionOptions = {
5020
4942
  fetch?: FetchFunction;
5021
4943
  };
5022
4944
 
5023
- interface DefaultChatStoreOptions<MESSAGE_METADATA = unknown, UI_DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> {
5024
- /**
5025
- * Schema for the message metadata. Validates the message metadata.
5026
- * Message metadata can be undefined or must match the schema.
5027
- */
5028
- messageMetadataSchema?: Validator<MESSAGE_METADATA> | StandardSchemaV1<MESSAGE_METADATA>;
5029
- /**
5030
- * Schema for the data types. Validates the data types.
5031
- */
5032
- dataPartSchemas?: UI_DATA_PART_SCHEMAS;
5033
- /**
5034
- * The API endpoint that accepts a `{ messages: Message[] }` object and returns
5035
- * a stream of tokens of the AI chat response.
5036
- *
5037
- * Defaults to `/api/chat`
5038
- */
5039
- api?: string;
5040
- /**
5041
- * A way to provide a function that is going to be used for ids for messages and the chat.
5042
- * If not provided the default AI SDK `generateId` is used.
5043
- */
5044
- generateId?: IdGenerator;
5045
- /**
5046
- * The credentials mode to be used for the fetch request.
5047
- * Possible values are: 'omit', 'same-origin', 'include'.
5048
- * Defaults to 'same-origin'.
5049
- */
5050
- credentials?: RequestCredentials;
5051
- /**
5052
- * HTTP headers to be sent with the API request.
5053
- */
5054
- headers?: Record<string, string> | Headers;
5055
- /**
5056
- * Extra body object to be sent with the API request.
5057
- * @example
5058
- * Send a `sessionId` to the API along with the messages.
5059
- * ```js
5060
- * useChat({
5061
- * body: {
5062
- * sessionId: '123',
5063
- * }
5064
- * })
5065
- * ```
5066
- */
5067
- body?: object;
5068
- /**
5069
- Custom fetch implementation. You can use it as a middleware to intercept requests,
5070
- or to provide a custom fetch implementation for e.g. testing.
5071
- */
5072
- fetch?: FetchFunction;
5073
- /**
5074
- Maximum number of sequential LLM calls (steps), e.g. when you use tool calls.
5075
- Must be at least 1.
5076
-
5077
- A maximum number is required to prevent infinite loops in the case of misconfigured tools.
5078
-
5079
- By default, it's set to 1, which means that only a single LLM call is made.
5080
- */
5081
- maxSteps?: number;
5082
- /**
5083
- * When a function is provided, it will be used
5084
- * to prepare the request body for the chat API. This can be useful for
5085
- * customizing the request body based on the messages and data in the chat.
5086
- *
5087
- * @param chatId The id of the chat.
5088
- * @param messages The current messages in the chat.
5089
- * @param requestBody The request body object passed in the chat request.
5090
- */
5091
- prepareRequestBody?: (options: {
5092
- chatId: string;
5093
- messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>[];
5094
- requestBody?: object;
5095
- }) => unknown;
5096
- chats?: {
5097
- [id: string]: {
5098
- messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>[];
5099
- };
5100
- };
5101
- }
5102
- declare function defaultChatStoreOptions<MESSAGE_METADATA = unknown, UI_DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas>({ api, fetch, credentials, headers, body, prepareRequestBody, generateId, messageMetadataSchema, maxSteps, dataPartSchemas, chats, }: DefaultChatStoreOptions<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS>): () => ChatStoreOptions<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS>;
5103
-
5104
- export { ActiveResponse, AssistantContent, AssistantModelMessage, CallSettings, CallWarning, Chat, ChatRequestOptions, ChatStatus, ChatStore, ChatStoreEvent, ChatStoreFactory, ChatStoreOptions, ChatTransport, ChunkDetector, CompletionRequestOptions, CoreAssistantMessage, CoreMessage, CoreSystemMessage, CoreToolMessage, CoreUserMessage, CreateUIMessage, DataContent, DataUIPart, DeepPartial, DefaultChatStoreOptions, DefaultChatTransport, DownloadError, EmbedManyResult, EmbedResult, Embedding, EmbeddingModel, EmbeddingModelUsage, GenerateImageResult as Experimental_GenerateImageResult, GeneratedFile as Experimental_GeneratedImage, SpeechResult as Experimental_SpeechResult, TranscriptionResult as Experimental_TranscriptionResult, FilePart, FileUIPart, FinishReason, GenerateObjectResult, GenerateTextOnStepFinishCallback, GenerateTextResult, GeneratedAudioFile, GeneratedFile, ImageModel, ImageGenerationWarning as ImageModelCallWarning, ImageModelProviderMetadata, ImageModelResponseMetadata, ImagePart, InferUIDataParts, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidStreamPartError, InvalidToolArgumentsError, JSONRPCError, JSONRPCMessage, JSONRPCNotification, JSONRPCRequest, JSONRPCResponse, JSONValue, JsonToSseTransformStream, LanguageModel, LanguageModelRequestMetadata, LanguageModelResponseMetadata, LanguageModelUsage, MCPClientError, MCPTransport, MessageConversionError, ModelMessage, NoImageGeneratedError, NoObjectGeneratedError, NoOutputSpecifiedError, NoSuchProviderError, NoSuchToolError, ObjectStreamPart, OriginalUseChatOptions, output as Output, PrepareStepFunction, PrepareStepResult, Prompt, Provider, ProviderMetadata, ProviderOptions, ProviderRegistryProvider, ReasoningUIPart, RepairTextFunction, RetryError, SerialJobExecutor, SourceUrlUIPart, SpeechModel, SpeechModelResponseMetadata, SpeechWarning, StepResult, StepStartUIPart, StopCondition, StreamObjectOnFinishCallback, StreamObjectResult, StreamTextOnChunkCallback, StreamTextOnErrorCallback, StreamTextOnFinishCallback, StreamTextOnStepFinishCallback, StreamTextResult, StreamTextTransform, SystemModelMessage, TelemetrySettings, TextPart, TextStreamChatTransport, TextStreamPart, TextUIPart, Tool, ToolCallPart, ToolCallRepairError, ToolCallRepairFunction, ToolCallUnion, ToolChoice, ToolContent, ToolExecutionError, ToolExecutionOptions, ToolInvocation, ToolInvocationUIPart, ToolModelMessage, ToolResultPart, ToolResultUnion, ToolSet, TranscriptionModel, TranscriptionModelResponseMetadata, TranscriptionWarning, UIDataPartSchemas, UIDataTypes, UIMessage, UIMessagePart, UIMessageStreamOptions, UIMessageStreamPart, UIMessageStreamWriter, UseChatOptions, UseCompletionOptions, UserContent, UserModelMessage, appendClientMessage, assistantModelMessageSchema, callChatApi, callCompletionApi, convertFileListToFileUIParts, convertToCoreMessages, convertToModelMessages, coreAssistantMessageSchema, coreMessageSchema, coreSystemMessageSchema, coreToolMessageSchema, coreUserMessageSchema, cosineSimilarity, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, defaultChatStoreOptions, defaultSettingsMiddleware, embed, embedMany, createMCPClient as experimental_createMCPClient, experimental_createProviderRegistry, experimental_customProvider, generateImage as experimental_generateImage, generateSpeech as experimental_generateSpeech, transcribe as experimental_transcribe, extractMaxToolInvocationStep, extractReasoningMiddleware, generateObject, generateText, getTextFromDataUrl, getToolInvocations, hasToolCall, isAssistantMessageWithCompletedToolCalls, isDeepEqualData, modelMessageSchema, parsePartialJson, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, shouldResubmitMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, stepCountIs, streamObject, streamText, systemModelMessageSchema, tool, toolModelMessageSchema, updateToolCallResult, userModelMessageSchema, wrapLanguageModel };
4945
+ export { ActiveResponse, AssistantContent, AssistantModelMessage, CallSettings, CallWarning, Chat, ChatRequestOptions, ChatStatus, ChatStore, ChatStoreEvent, ChatStoreFactory, ChatStoreOptions, ChatTransport, ChunkDetector, CompletionRequestOptions, CoreAssistantMessage, CoreMessage, CoreSystemMessage, CoreToolMessage, CoreUserMessage, CreateUIMessage, DataContent, DataUIPart, DeepPartial, DefaultChatStoreOptions, DefaultChatTransport, DownloadError, EmbedManyResult, EmbedResult, Embedding, EmbeddingModel, EmbeddingModelUsage, GenerateImageResult as Experimental_GenerateImageResult, GeneratedFile as Experimental_GeneratedImage, SpeechResult as Experimental_SpeechResult, TranscriptionResult as Experimental_TranscriptionResult, FilePart, FileUIPart, FinishReason, GenerateObjectResult, GenerateTextOnStepFinishCallback, GenerateTextResult, GeneratedAudioFile, GeneratedFile, ImageModel, ImageGenerationWarning as ImageModelCallWarning, ImageModelProviderMetadata, ImageModelResponseMetadata, ImagePart, InferUIDataParts, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidStreamPartError, InvalidToolArgumentsError, JSONRPCError, JSONRPCMessage, JSONRPCNotification, JSONRPCRequest, JSONRPCResponse, JSONValue, JsonToSseTransformStream, LanguageModel, LanguageModelRequestMetadata, LanguageModelResponseMetadata, LanguageModelUsage, MCPClientError, MCPTransport, MessageConversionError, ModelMessage, NoImageGeneratedError, NoObjectGeneratedError, NoOutputSpecifiedError, NoSuchProviderError, NoSuchToolError, ObjectStreamPart, output as Output, PrepareStepFunction, PrepareStepResult, Prompt, Provider, ProviderMetadata, ProviderOptions, ProviderRegistryProvider, ReasoningUIPart, RepairTextFunction, RetryError, SerialJobExecutor, SourceUrlUIPart, SpeechModel, SpeechModelResponseMetadata, SpeechWarning, StepResult, StepStartUIPart, StopCondition, StreamObjectOnFinishCallback, StreamObjectResult, StreamTextOnChunkCallback, StreamTextOnErrorCallback, StreamTextOnFinishCallback, StreamTextOnStepFinishCallback, StreamTextResult, StreamTextTransform, SystemModelMessage, TelemetrySettings, TextPart, TextStreamChatTransport, TextStreamPart, TextUIPart, Tool, ToolCallPart, ToolCallRepairError, ToolCallRepairFunction, ToolCallUnion, ToolChoice, ToolContent, ToolExecutionError, ToolExecutionOptions, ToolInvocation, ToolInvocationUIPart, ToolModelMessage, ToolResultPart, ToolResultUnion, ToolSet, TranscriptionModel, TranscriptionModelResponseMetadata, TranscriptionWarning, UIDataPartSchemas, UIDataTypes, UIMessage, UIMessagePart, UIMessageStreamOptions, UIMessageStreamPart, UIMessageStreamWriter, UseChatOptions, UseCompletionOptions, UserContent, UserModelMessage, assistantModelMessageSchema, callCompletionApi, convertFileListToFileUIParts, convertToCoreMessages, convertToModelMessages, coreAssistantMessageSchema, coreMessageSchema, coreSystemMessageSchema, coreToolMessageSchema, coreUserMessageSchema, cosineSimilarity, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, defaultChatStoreOptions, defaultSettingsMiddleware, embed, embedMany, createMCPClient as experimental_createMCPClient, experimental_createProviderRegistry, experimental_customProvider, generateImage as experimental_generateImage, generateSpeech as experimental_generateSpeech, transcribe as experimental_transcribe, extractReasoningMiddleware, generateObject, generateText, getTextFromDataUrl, getToolInvocations, hasToolCall, isDeepEqualData, modelMessageSchema, parsePartialJson, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, simulateReadableStream, simulateStreamingMiddleware, smoothStream, stepCountIs, streamObject, streamText, systemModelMessageSchema, tool, toolModelMessageSchema, userModelMessageSchema, wrapLanguageModel };