ai 5.0.0-alpha.1 → 5.0.0-alpha.11

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.ts CHANGED
@@ -1,7 +1,9 @@
1
- import { ToolResultContent, Schema, ToolCall, ToolResult, IdGenerator, FetchFunction, Validator, StandardSchemaV1 } from '@ai-sdk/provider-utils';
1
+ import { ToolResultContent, Schema, ToolCall, ToolResult, Validator, StandardSchemaV1, IdGenerator, InferSchema, 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';
5
+ import * as z3 from 'zod/v3';
6
+ import * as z4 from 'zod/v4/core';
5
7
  import { z } from 'zod';
6
8
  import { ServerResponse } from 'node:http';
7
9
  import { AttributeValue, Tracer } from '@opentelemetry/api';
@@ -382,7 +384,7 @@ type JSONValue = JSONValue$1;
382
384
  /**
383
385
  Language model that is used by the AI SDK Core functions.
384
386
  */
385
- type LanguageModel = LanguageModelV2;
387
+ type LanguageModel = string | LanguageModelV2;
386
388
  /**
387
389
  Reason why a language model finished generating a response.
388
390
 
@@ -878,8 +880,8 @@ type MCPTransportConfig = {
878
880
  headers?: Record<string, string>;
879
881
  };
880
882
 
881
- type ToolParameters<T = JSONObject> = z.Schema<T> | Schema<T>;
882
- interface ToolExecutionOptions {
883
+ type ToolParameters<T = JSONObject> = z4.$ZodType<T> | z3.Schema<T> | Schema<T>;
884
+ interface ToolCallOptions {
883
885
  /**
884
886
  * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
885
887
  */
@@ -923,11 +925,30 @@ If not provided, the tool will not be executed automatically.
923
925
  @args is the input of the tool call.
924
926
  @options.abortSignal is a signal that can be used to abort the tool call.
925
927
  */
926
- execute: (args: [PARAMETERS] extends [never] ? undefined : PARAMETERS, options: ToolExecutionOptions) => PromiseLike<RESULT>;
928
+ execute: (args: [PARAMETERS] extends [never] ? undefined : PARAMETERS, options: ToolCallOptions) => PromiseLike<RESULT>;
927
929
  /**
928
930
  Optional conversion function that maps the tool result to multi-part tool content for LLMs.
929
931
  */
930
932
  experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
933
+ /**
934
+ * Optional function that is called when the argument streaming starts.
935
+ * Only called when the tool is used in a streaming context.
936
+ */
937
+ onArgsStreamingStart?: (options: ToolCallOptions) => void | PromiseLike<void>;
938
+ /**
939
+ * Optional function that is called when an argument streaming delta is available.
940
+ * Only called when the tool is used in a streaming context.
941
+ */
942
+ onArgsStreamingDelta?: (options: {
943
+ argsTextDelta: string;
944
+ } & ToolCallOptions) => void | PromiseLike<void>;
945
+ /**
946
+ * Optional function that is called when a tool call can be started,
947
+ * even if the execute function is not provided.
948
+ */
949
+ onArgsAvailable?: (options: {
950
+ args: [PARAMETERS] extends [never] ? undefined : PARAMETERS;
951
+ } & ToolCallOptions) => void | PromiseLike<void>;
931
952
  }> & ({
932
953
  /**
933
954
  Function tool.
@@ -950,17 +971,17 @@ The arguments for configuring the tool. Must match the expected arguments define
950
971
  /**
951
972
  Helper function for inferring the execute args of a tool.
952
973
  */
953
- declare function tool(tool: Tool<never, never>): Tool<never, never>;
974
+ declare function tool<PARAMETERS, RESULT>(tool: Tool<PARAMETERS, RESULT>): Tool<PARAMETERS, RESULT>;
954
975
  declare function tool<PARAMETERS>(tool: Tool<PARAMETERS, never>): Tool<PARAMETERS, never>;
955
976
  declare function tool<RESULT>(tool: Tool<never, RESULT>): Tool<never, RESULT>;
956
- declare function tool<PARAMETERS, RESULT>(tool: Tool<PARAMETERS, RESULT>): Tool<PARAMETERS, RESULT>;
977
+ declare function tool(tool: Tool<never, never>): Tool<never, never>;
957
978
  type MappedTool<T extends Tool | JSONObject, RESULT extends any> = T extends Tool<infer P> ? Tool<P, RESULT> : T extends JSONObject ? Tool<T, RESULT> : never;
958
979
 
959
980
  type ToolSchemas = Record<string, {
960
981
  parameters: ToolParameters<JSONObject | unknown>;
961
982
  }> | 'automatic' | undefined;
962
983
  type McpToolSet<TOOL_SCHEMAS extends ToolSchemas = 'automatic'> = TOOL_SCHEMAS extends Record<string, {
963
- parameters: ToolParameters<any>;
984
+ parameters: ToolParameters<unknown>;
964
985
  }> ? {
965
986
  [K in keyof TOOL_SCHEMAS]: MappedTool<TOOL_SCHEMAS[K], CallToolResult> & Required<Pick<MappedTool<TOOL_SCHEMAS[K], CallToolResult>, 'execute'>>;
966
987
  } : McpToolSet<Record<string, {
@@ -1734,7 +1755,7 @@ declare class MCPClient {
1734
1755
  private onResponse;
1735
1756
  }
1736
1757
 
1737
- type ToolSet = Record<string, (Tool<never, never> | Tool<any, any> | Tool<any, never> | Tool<never, any>) & Pick<Tool<any, any>, 'execute'>>;
1758
+ type ToolSet = Record<string, (Tool<never, never> | Tool<any, any> | Tool<any, never> | Tool<never, any>) & Pick<Tool<any, any>, 'execute' | 'onArgsAvailable' | 'onArgsStreamingStart' | 'onArgsStreamingDelta'>>;
1738
1759
 
1739
1760
  type ToolCallUnion<TOOLS extends ToolSet> = ValueOf<{
1740
1761
  [NAME in keyof TOOLS]: {
@@ -1900,6 +1921,8 @@ type Prompt = {
1900
1921
  messages?: Array<ModelMessage>;
1901
1922
  };
1902
1923
 
1924
+ declare const GLOBAL_DEFAULT_PROVIDER: unique symbol;
1925
+
1903
1926
  /**
1904
1927
  * A function that attempts to repair a tool call that failed to parse.
1905
1928
  *
@@ -2114,13 +2137,10 @@ It is optional for backwards compatibility.
2114
2137
  */
2115
2138
  type ToolInvocation = ({
2116
2139
  state: 'partial-call';
2117
- step?: number;
2118
2140
  } & ToolCall<string, any>) | ({
2119
2141
  state: 'call';
2120
- step?: number;
2121
2142
  } & ToolCall<string, any>) | ({
2122
2143
  state: 'result';
2123
- step?: number;
2124
2144
  } & ToolResult<string, any, any>);
2125
2145
  /**
2126
2146
  The data types that can be used in the UI message for the UI message data parts.
@@ -2154,7 +2174,7 @@ interface UIMessage<METADATA = unknown, DATA_PARTS extends UIDataTypes = UIDataT
2154
2174
  */
2155
2175
  parts: Array<UIMessagePart<DATA_PARTS>>;
2156
2176
  }
2157
- type UIMessagePart<DATA_TYPES extends UIDataTypes> = TextUIPart | ReasoningUIPart | ToolInvocationUIPart | SourceUIPart | FileUIPart | DataUIPart<DATA_TYPES> | StepStartUIPart;
2177
+ type UIMessagePart<DATA_TYPES extends UIDataTypes> = TextUIPart | ReasoningUIPart | ToolInvocationUIPart | SourceUrlUIPart | SourceDocumentUIPart | FileUIPart | DataUIPart<DATA_TYPES> | StepStartUIPart;
2158
2178
  type DataUIPart<DATA_TYPES extends UIDataTypes> = ValueOf<{
2159
2179
  [NAME in keyof DATA_TYPES & string]: {
2160
2180
  type: `data-${NAME}`;
@@ -2162,6 +2182,10 @@ type DataUIPart<DATA_TYPES extends UIDataTypes> = ValueOf<{
2162
2182
  data: DATA_TYPES[NAME];
2163
2183
  };
2164
2184
  }>;
2185
+ type UIDataPartSchemas = Record<string, Validator<any> | StandardSchemaV1<any>>;
2186
+ type InferUIDataParts<T extends UIDataPartSchemas> = {
2187
+ [K in keyof T]: T[K] extends Validator<infer U> ? U : T[K] extends StandardSchemaV1<infer U> ? U : unknown;
2188
+ };
2165
2189
  /**
2166
2190
  * A text part of a message.
2167
2191
  */
@@ -2199,18 +2223,23 @@ type ToolInvocationUIPart = {
2199
2223
  /**
2200
2224
  * A source part of a message.
2201
2225
  */
2202
- type SourceUIPart = {
2203
- type: 'source';
2204
- /**
2205
- * The source.
2206
- */
2207
- source: {
2208
- sourceType: 'url';
2209
- id: string;
2210
- url: string;
2211
- title?: string;
2212
- providerMetadata?: Record<string, any>;
2213
- };
2226
+ type SourceUrlUIPart = {
2227
+ type: 'source-url';
2228
+ sourceId: string;
2229
+ url: string;
2230
+ title?: string;
2231
+ providerMetadata?: Record<string, any>;
2232
+ };
2233
+ /**
2234
+ * A document source part of a message.
2235
+ */
2236
+ type SourceDocumentUIPart = {
2237
+ type: 'source-document';
2238
+ sourceId: string;
2239
+ mediaType: string;
2240
+ title: string;
2241
+ filename?: string;
2242
+ providerMetadata?: Record<string, any>;
2214
2243
  };
2215
2244
  /**
2216
2245
  * A file part of a message.
@@ -2239,8 +2268,9 @@ type FileUIPart = {
2239
2268
  type StepStartUIPart = {
2240
2269
  type: 'step-start';
2241
2270
  };
2242
- type CreateUIMessage<METADATA = unknown, DATA_TYPES extends UIDataTypes = UIDataTypes> = Omit<UIMessage<METADATA, DATA_TYPES>, 'id'> & {
2271
+ type CreateUIMessage<METADATA = unknown, DATA_TYPES extends UIDataTypes = UIDataTypes> = Omit<UIMessage<METADATA, DATA_TYPES>, 'id' | 'role'> & {
2243
2272
  id?: UIMessage<METADATA, DATA_TYPES>['id'];
2273
+ role?: UIMessage<METADATA, DATA_TYPES>['role'];
2244
2274
  };
2245
2275
 
2246
2276
  declare const symbol$3: unique symbol;
@@ -2294,15 +2324,22 @@ declare function pipeTextStreamToResponse({ response, status, statusText, header
2294
2324
  textStream: ReadableStream<string>;
2295
2325
  } & ResponseInit): void;
2296
2326
 
2297
- /**
2298
- * Appends a client message to the messages array.
2299
- * If the last message in the array has the same id as the new message, it will be replaced.
2300
- * Otherwise, the new message will be appended.
2301
- */
2302
- declare function appendClientMessage({ messages, message, }: {
2303
- messages: UIMessage[];
2304
- message: UIMessage;
2305
- }): UIMessage<unknown, UIDataTypes>[];
2327
+ declare const getOriginalFetch: () => typeof fetch;
2328
+ declare function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol, setCompletion, setLoading, setError, setAbortController, onFinish, onError, fetch, }: {
2329
+ api: string;
2330
+ prompt: string;
2331
+ credentials: RequestCredentials | undefined;
2332
+ headers: HeadersInit | undefined;
2333
+ body: Record<string, any>;
2334
+ streamProtocol: 'data' | 'text' | undefined;
2335
+ setCompletion: (completion: string) => void;
2336
+ setLoading: (loading: boolean) => void;
2337
+ setError: (error: Error | undefined) => void;
2338
+ setAbortController: (abortController: AbortController | null) => void;
2339
+ onFinish: ((prompt: string, completion: string) => void) | undefined;
2340
+ onError: ((error: Error) => void) | undefined;
2341
+ fetch: ReturnType<typeof getOriginalFetch> | undefined;
2342
+ }): Promise<string | null | undefined>;
2306
2343
 
2307
2344
  /**
2308
2345
  The result of an `embed` call.
@@ -2658,7 +2695,7 @@ It always recurses into arrays.
2658
2695
 
2659
2696
  Adopted from [type-fest](https://github.com/sindresorhus/type-fest/tree/main) PartialDeep.
2660
2697
  */
2661
- type DeepPartial<T> = T extends z.ZodTypeAny ? DeepPartialInternal<z.infer<T>> : DeepPartialInternal<T>;
2698
+ type DeepPartial<T> = T extends z3.ZodTypeAny ? DeepPartialInternal<z3.infer<T>> : T extends z4.$ZodType ? DeepPartialInternal<z4.infer<T>> : DeepPartialInternal<T>;
2662
2699
  type DeepPartialInternal<T> = T extends null | undefined | string | number | boolean | symbol | bigint | void | Date | RegExp | ((...arguments_: any[]) => unknown) | (new (...arguments_: any[]) => unknown) ? T : T extends Map<infer KeyType, infer ValueType> ? PartialMap<KeyType, ValueType> : T extends Set<infer ItemType> ? PartialSet<ItemType> : T extends ReadonlyMap<infer KeyType, infer ValueType> ? PartialReadonlyMap<KeyType, ValueType> : T extends ReadonlySet<infer ItemType> ? PartialReadonlySet<ItemType> : T extends object ? T extends ReadonlyArray<infer ItemType> ? ItemType[] extends T ? readonly ItemType[] extends T ? ReadonlyArray<DeepPartialInternal<ItemType | undefined>> : Array<DeepPartialInternal<ItemType | undefined>> : PartialObject<T> : PartialObject<T> : unknown;
2663
2700
  type PartialMap<KeyType, ValueType> = {} & Map<DeepPartialInternal<KeyType>, DeepPartialInternal<ValueType>>;
2664
2701
  type PartialSet<T> = {} & Set<DeepPartialInternal<T>>;
@@ -2668,7 +2705,7 @@ type PartialObject<ObjectType extends object> = {
2668
2705
  [KeyType in keyof ObjectType]?: DeepPartialInternal<ObjectType[KeyType]>;
2669
2706
  };
2670
2707
 
2671
- interface Output$1<OUTPUT, PARTIAL> {
2708
+ interface Output<OUTPUT, PARTIAL> {
2672
2709
  readonly type: 'object' | 'text';
2673
2710
  responseFormat: LanguageModelV2CallOptions['responseFormat'];
2674
2711
  parsePartial(options: {
@@ -2684,25 +2721,49 @@ interface Output$1<OUTPUT, PARTIAL> {
2684
2721
  finishReason: FinishReason;
2685
2722
  }): Promise<OUTPUT>;
2686
2723
  }
2687
- declare const text: () => Output$1<string, string>;
2724
+ declare const text: () => Output<string, string>;
2688
2725
  declare const object: <OUTPUT>({ schema: inputSchema, }: {
2689
- schema: z.Schema<OUTPUT, z.ZodTypeDef, any> | Schema<OUTPUT>;
2690
- }) => Output$1<OUTPUT, DeepPartial<OUTPUT>>;
2726
+ schema: z4.$ZodType<OUTPUT, any> | z3.Schema<OUTPUT, z3.ZodTypeDef, any> | Schema<OUTPUT>;
2727
+ }) => Output<OUTPUT, DeepPartial<OUTPUT>>;
2691
2728
 
2729
+ type output_Output<OUTPUT, PARTIAL> = Output<OUTPUT, PARTIAL>;
2692
2730
  declare const output_object: typeof object;
2693
2731
  declare const output_text: typeof text;
2694
2732
  declare namespace output {
2695
2733
  export {
2696
- Output$1 as Output,
2734
+ output_Output as Output,
2697
2735
  output_object as object,
2698
2736
  output_text as text,
2699
2737
  };
2700
2738
  }
2701
2739
 
2740
+ /**
2741
+ Function that you can use to provide different settings for a step.
2742
+
2743
+ @param options - The options for the step.
2744
+ @param options.steps - The steps that have been executed so far.
2745
+ @param options.stepNumber - The number of the step that is being executed.
2746
+ @param options.model - The model that is being used.
2747
+
2748
+ @returns An object that contains the settings for the step.
2749
+ If you return undefined (or for undefined settings), the settings from the outer level will be used.
2750
+ */
2751
+ type PrepareStepFunction<TOOLS extends Record<string, Tool> = Record<string, Tool>> = (options: {
2752
+ steps: Array<StepResult<NoInfer<TOOLS>>>;
2753
+ stepNumber: number;
2754
+ model: LanguageModel;
2755
+ }) => PromiseLike<PrepareStepResult<TOOLS>> | PrepareStepResult<TOOLS>;
2756
+ type PrepareStepResult<TOOLS extends Record<string, Tool> = Record<string, Tool>> = {
2757
+ model?: LanguageModel;
2758
+ toolChoice?: ToolChoice<NoInfer<TOOLS>>;
2759
+ activeTools?: Array<keyof NoInfer<TOOLS>>;
2760
+ system?: string;
2761
+ } | undefined;
2762
+
2702
2763
  type StopCondition<TOOLS extends ToolSet> = (options: {
2703
2764
  steps: Array<StepResult<TOOLS>>;
2704
2765
  }) => PromiseLike<boolean> | boolean;
2705
- declare function maxSteps(maxSteps: number): StopCondition<any>;
2766
+ declare function stepCountIs(stepCount: number): StopCondition<any>;
2706
2767
  declare function hasToolCall(toolName: string): StopCondition<any>;
2707
2768
 
2708
2769
  /**
@@ -2757,7 +2818,7 @@ If set and supported by the model, calls will generate deterministic results.
2757
2818
  @returns
2758
2819
  A result object that contains the generated text, the results of the tool calls, and additional information.
2759
2820
  */
2760
- declare function generateText<TOOLS extends ToolSet, OUTPUT = never, OUTPUT_PARTIAL = never>({ model, tools, toolChoice, system, prompt, messages, maxRetries: maxRetriesArg, abortSignal, headers, continueUntil, experimental_output: output, experimental_telemetry: telemetry, providerOptions, experimental_activeTools: activeTools, experimental_prepareStep: prepareStep, experimental_repairToolCall: repairToolCall, _internal: { generateId, currentDate, }, onStepFinish, ...settings }: CallSettings & Prompt & {
2821
+ declare function generateText<TOOLS extends ToolSet, OUTPUT = never, OUTPUT_PARTIAL = never>({ model: modelArg, tools, toolChoice, system, prompt, messages, maxRetries: maxRetriesArg, abortSignal, headers, stopWhen, experimental_output: output, experimental_telemetry: telemetry, providerOptions, experimental_activeTools, activeTools, experimental_prepareStep, prepareStep, experimental_repairToolCall: repairToolCall, _internal: { generateId, currentDate, }, onStepFinish, ...settings }: CallSettings & Prompt & {
2761
2822
  /**
2762
2823
  The language model to use.
2763
2824
  */
@@ -2770,7 +2831,13 @@ The tools that the model can call. The model needs to support calling tools.
2770
2831
  The tool choice strategy. Default: 'auto'.
2771
2832
  */
2772
2833
  toolChoice?: ToolChoice<NoInfer<TOOLS>>;
2773
- continueUntil?: StopCondition<NoInfer<TOOLS>>;
2834
+ /**
2835
+ Condition for stopping the generation when there are tool results in the last step.
2836
+ When the condition is an array, any of the conditions can be met to stop the generation.
2837
+
2838
+ @default stepCountIs(1)
2839
+ */
2840
+ stopWhen?: StopCondition<NoInfer<TOOLS>> | Array<StopCondition<NoInfer<TOOLS>>>;
2774
2841
  /**
2775
2842
  Optional telemetry configuration (experimental).
2776
2843
  */
@@ -2782,34 +2849,26 @@ functionality that can be fully encapsulated in the provider.
2782
2849
  */
2783
2850
  providerOptions?: ProviderOptions;
2784
2851
  /**
2852
+ * @deprecated Use `activeTools` instead.
2853
+ */
2854
+ experimental_activeTools?: Array<keyof NoInfer<TOOLS>>;
2855
+ /**
2785
2856
  Limits the tools that are available for the model to call without
2786
2857
  changing the tool call and result types in the result.
2787
2858
  */
2788
- experimental_activeTools?: Array<keyof NoInfer<TOOLS>>;
2859
+ activeTools?: Array<keyof NoInfer<TOOLS>>;
2789
2860
  /**
2790
2861
  Optional specification for parsing structured outputs from the LLM response.
2791
2862
  */
2792
- experimental_output?: Output$1<OUTPUT, OUTPUT_PARTIAL>;
2863
+ experimental_output?: Output<OUTPUT, OUTPUT_PARTIAL>;
2864
+ /**
2865
+ * @deprecated Use `prepareStep` instead.
2866
+ */
2867
+ experimental_prepareStep?: PrepareStepFunction<NoInfer<TOOLS>>;
2793
2868
  /**
2794
2869
  Optional function that you can use to provide different settings for a step.
2795
-
2796
- @param options - The options for the step.
2797
- @param options.steps - The steps that have been executed so far.
2798
- @param options.stepNumber - The number of the step that is being executed.
2799
- @param options.model - The model that is being used.
2800
-
2801
- @returns An object that contains the settings for the step.
2802
- If you return undefined (or for undefined settings), the settings from the outer level will be used.
2803
2870
  */
2804
- experimental_prepareStep?: (options: {
2805
- steps: Array<StepResult<NoInfer<TOOLS>>>;
2806
- stepNumber: number;
2807
- model: LanguageModel;
2808
- }) => PromiseLike<{
2809
- model?: LanguageModel;
2810
- toolChoice?: ToolChoice<NoInfer<TOOLS>>;
2811
- experimental_activeTools?: Array<keyof NoInfer<TOOLS>>;
2812
- } | undefined>;
2871
+ prepareStep?: PrepareStepFunction<NoInfer<TOOLS>>;
2813
2872
  /**
2814
2873
  A function that attempts to repair a tool call that failed to parse.
2815
2874
  */
@@ -2883,7 +2942,7 @@ type UIMessageStreamOptions = {
2883
2942
  * that send additional data.
2884
2943
  * Default to true.
2885
2944
  */
2886
- experimental_sendFinish?: boolean;
2945
+ sendFinish?: boolean;
2887
2946
  /**
2888
2947
  * Send the message start event to the client.
2889
2948
  * Set to false if you are using additional streamText calls
@@ -2895,7 +2954,7 @@ type UIMessageStreamOptions = {
2895
2954
  * streamText calls that send additional data to prevent
2896
2955
  * the message start event from being sent multiple times.
2897
2956
  */
2898
- experimental_sendStart?: boolean;
2957
+ sendStart?: boolean;
2899
2958
  /**
2900
2959
  * Process an error, e.g. to log it. Default to `() => 'An error occurred.'`.
2901
2960
  *
@@ -3247,7 +3306,7 @@ If set and supported by the model, calls will generate deterministic results.
3247
3306
  @return
3248
3307
  A result object for accessing different stream types and additional information.
3249
3308
  */
3250
- declare function streamText<TOOLS extends ToolSet, OUTPUT = never, PARTIAL_OUTPUT = never>({ model, tools, toolChoice, system, prompt, messages, maxRetries, abortSignal, headers, maxSteps, experimental_output: output, experimental_telemetry: telemetry, providerOptions, experimental_toolCallStreaming, toolCallStreaming, experimental_activeTools: activeTools, experimental_repairToolCall: repairToolCall, experimental_transform: transform, onChunk, onError, onFinish, onStepFinish, _internal: { now, generateId, currentDate, }, ...settings }: CallSettings & Prompt & {
3309
+ declare function streamText<TOOLS extends ToolSet, OUTPUT = never, PARTIAL_OUTPUT = never>({ model, tools, toolChoice, system, prompt, messages, maxRetries, abortSignal, headers, stopWhen, experimental_output: output, experimental_telemetry: telemetry, prepareStep, providerOptions, experimental_toolCallStreaming, toolCallStreaming, experimental_activeTools, activeTools, experimental_repairToolCall: repairToolCall, experimental_transform: transform, onChunk, onError, onFinish, onStepFinish, _internal: { now, generateId, currentDate, }, ...settings }: CallSettings & Prompt & {
3251
3310
  /**
3252
3311
  The language model to use.
3253
3312
  */
@@ -3261,13 +3320,12 @@ The tool choice strategy. Default: 'auto'.
3261
3320
  */
3262
3321
  toolChoice?: ToolChoice<TOOLS>;
3263
3322
  /**
3264
- Maximum number of sequential LLM calls (steps), e.g. when you use tool calls. Must be at least 1.
3323
+ Condition for stopping the generation when there are tool results in the last step.
3324
+ When the condition is an array, any of the conditions can be met to stop the generation.
3265
3325
 
3266
- A maximum number is required to prevent infinite loops in the case of misconfigured tools.
3267
-
3268
- By default, it's set to 1, which means that only a single LLM call is made.
3269
- */
3270
- maxSteps?: number;
3326
+ @default stepCountIs(1)
3327
+ */
3328
+ stopWhen?: StopCondition<NoInfer<TOOLS>> | Array<StopCondition<NoInfer<TOOLS>>>;
3271
3329
  /**
3272
3330
  Optional telemetry configuration (experimental).
3273
3331
  */
@@ -3279,14 +3337,30 @@ functionality that can be fully encapsulated in the provider.
3279
3337
  */
3280
3338
  providerOptions?: ProviderOptions;
3281
3339
  /**
3282
- Limits the tools that are available for the model to call without
3283
- changing the tool call and result types in the result.
3340
+ * @deprecated Use `activeTools` instead.
3284
3341
  */
3285
- experimental_activeTools?: Array<keyof TOOLS>;
3342
+ experimental_activeTools?: Array<keyof NoInfer<TOOLS>>;
3343
+ /**
3344
+ Limits the tools that are available for the model to call without
3345
+ changing the tool call and result types in the result.
3346
+ */
3347
+ activeTools?: Array<keyof NoInfer<TOOLS>>;
3286
3348
  /**
3287
3349
  Optional specification for parsing structured outputs from the LLM response.
3288
3350
  */
3289
- experimental_output?: Output$1<OUTPUT, PARTIAL_OUTPUT>;
3351
+ experimental_output?: Output<OUTPUT, PARTIAL_OUTPUT>;
3352
+ /**
3353
+ Optional function that you can use to provide different settings for a step.
3354
+
3355
+ @param options - The options for the step.
3356
+ @param options.steps - The steps that have been executed so far.
3357
+ @param options.stepNumber - The number of the step that is being executed.
3358
+ @param options.model - The model that is being used.
3359
+
3360
+ @returns An object that contains the settings for the step.
3361
+ If you return undefined (or for undefined settings), the settings from the outer level will be used.
3362
+ */
3363
+ prepareStep?: PrepareStepFunction<NoInfer<TOOLS>>;
3290
3364
  /**
3291
3365
  A function that attempts to repair a tool call that failed to parse.
3292
3366
  */
@@ -3563,14 +3637,14 @@ functionality that can be fully encapsulated in the provider.
3563
3637
  @returns
3564
3638
  A result object that contains the generated object, the finish reason, the token usage, and additional information.
3565
3639
  */
3566
- declare function generateObject<RESULT extends SCHEMA extends z.Schema ? Output extends 'array' ? Array<z.infer<SCHEMA>> : z.infer<SCHEMA> : SCHEMA extends Schema<infer T> ? Output extends 'array' ? Array<T> : T : never, SCHEMA extends z.Schema | Schema = z.Schema<JSONValue$1>, Output extends 'object' | 'array' | 'enum' | 'no-schema' = RESULT extends string ? 'enum' : 'object'>(options: Omit<CallSettings, 'stopSequences'> & Prompt & (Output extends 'enum' ? {
3640
+ declare function generateObject<SCHEMA extends z3.Schema | z4.$ZodType | Schema = z4.$ZodType<JSONValue$1>, OUTPUT extends 'object' | 'array' | 'enum' | 'no-schema' = InferSchema<SCHEMA> extends string ? 'enum' : 'object', RESULT = OUTPUT extends 'array' ? Array<InferSchema<SCHEMA>> : InferSchema<SCHEMA>>(options: Omit<CallSettings, 'stopSequences'> & Prompt & (OUTPUT extends 'enum' ? {
3567
3641
  /**
3568
3642
  The enum values that the model should use.
3569
3643
  */
3570
3644
  enum: Array<RESULT>;
3571
3645
  mode?: 'json';
3572
3646
  output: 'enum';
3573
- } : Output extends 'no-schema' ? {} : {
3647
+ } : OUTPUT extends 'no-schema' ? {} : {
3574
3648
  /**
3575
3649
  The schema of the object that the model should generate.
3576
3650
  */
@@ -3602,7 +3676,7 @@ Default and recommended: 'auto' (best mode for the model).
3602
3676
  */
3603
3677
  mode?: 'auto' | 'json' | 'tool';
3604
3678
  }) & {
3605
- output?: Output;
3679
+ output?: OUTPUT;
3606
3680
  /**
3607
3681
  The language model to use.
3608
3682
  */
@@ -3631,6 +3705,20 @@ functionality that can be fully encapsulated in the provider.
3631
3705
  };
3632
3706
  }): Promise<GenerateObjectResult<RESULT>>;
3633
3707
 
3708
+ /**
3709
+ * Calculates the cosine similarity between two vectors. This is a useful metric for
3710
+ * comparing the similarity of two vectors such as embeddings.
3711
+ *
3712
+ * @param vector1 - The first vector.
3713
+ * @param vector2 - The second vector.
3714
+ *
3715
+ * @returns The cosine similarity between vector1 and vector2.
3716
+ * @returns 0 if either vector is the zero vector.
3717
+ *
3718
+ * @throws {InvalidArgumentError} If the vectors do not have the same length.
3719
+ */
3720
+ declare function cosineSimilarity(vector1: number[], vector2: number[]): number;
3721
+
3634
3722
  /**
3635
3723
  * Converts a data URL of type text/* to a text string.
3636
3724
  */
@@ -3650,19 +3738,14 @@ declare function parsePartialJson(jsonText: string | undefined): Promise<{
3650
3738
  state: 'undefined-input' | 'successful-parse' | 'repaired-parse' | 'failed-parse';
3651
3739
  }>;
3652
3740
 
3653
- /**
3654
- * Calculates the cosine similarity between two vectors. This is a useful metric for
3655
- * comparing the similarity of two vectors such as embeddings.
3656
- *
3657
- * @param vector1 - The first vector.
3658
- * @param vector2 - The second vector.
3659
- *
3660
- * @returns The cosine similarity between vector1 and vector2.
3661
- * @returns 0 if either vector is the zero vector.
3662
- *
3663
- * @throws {InvalidArgumentError} If the vectors do not have the same length.
3664
- */
3665
- declare function cosineSimilarity(vector1: number[], vector2: number[]): number;
3741
+ type Job = () => Promise<void>;
3742
+
3743
+ declare class SerialJobExecutor {
3744
+ private queue;
3745
+ private isProcessing;
3746
+ private processQueue;
3747
+ run(job: Job): Promise<void>;
3748
+ }
3666
3749
 
3667
3750
  /**
3668
3751
  * Creates a ReadableStream that emits the provided values with an optional delay between each value.
@@ -3871,14 +3954,14 @@ functionality that can be fully encapsulated in the provider.
3871
3954
  @returns
3872
3955
  A result object for accessing the partial object stream and additional information.
3873
3956
  */
3874
- declare function streamObject<RESULT extends SCHEMA extends z.Schema ? Output extends 'array' ? Array<z.infer<SCHEMA>> : z.infer<SCHEMA> : SCHEMA extends Schema<infer T> ? Output extends 'array' ? Array<T> : T : never, SCHEMA extends z.Schema | Schema = z.Schema<JSONValue$1>, Output extends 'object' | 'array' | 'enum' | 'no-schema' = RESULT extends string ? 'enum' : 'object'>(options: Omit<CallSettings, 'stopSequences'> & Prompt & (Output extends 'enum' ? {
3957
+ declare function streamObject<SCHEMA extends z3.Schema | z4.$ZodType | Schema = z4.$ZodType<JSONValue$1>, OUTPUT extends 'object' | 'array' | 'enum' | 'no-schema' = InferSchema<SCHEMA> extends string ? 'enum' : 'object', RESULT = OUTPUT extends 'array' ? Array<InferSchema<SCHEMA>> : InferSchema<SCHEMA>>(options: Omit<CallSettings, 'stopSequences'> & Prompt & (OUTPUT extends 'enum' ? {
3875
3958
  /**
3876
3959
  The enum values that the model should use.
3877
3960
  */
3878
3961
  enum: Array<RESULT>;
3879
3962
  mode?: 'json';
3880
3963
  output: 'enum';
3881
- } : Output extends 'no-schema' ? {} : {
3964
+ } : OUTPUT extends 'no-schema' ? {} : {
3882
3965
  /**
3883
3966
  The schema of the object that the model should generate.
3884
3967
  */
@@ -3910,7 +3993,7 @@ Default and recommended: 'auto' (best mode for the model).
3910
3993
  */
3911
3994
  mode?: 'auto' | 'json' | 'tool';
3912
3995
  }) & {
3913
- output?: Output;
3996
+ output?: OUTPUT;
3914
3997
  /**
3915
3998
  The language model to use.
3916
3999
  */
@@ -3943,7 +4026,7 @@ Callback that is called when the LLM response and the final object validation ar
3943
4026
  currentDate?: () => Date;
3944
4027
  now?: () => number;
3945
4028
  };
3946
- }): StreamObjectResult<Output extends 'enum' ? string : Output extends 'array' ? RESULT : DeepPartial<RESULT>, Output extends 'array' ? RESULT : RESULT, Output extends 'array' ? RESULT extends Array<infer U> ? AsyncIterableStream<U> : never : never>;
4029
+ }): StreamObjectResult<OUTPUT extends 'enum' ? string : OUTPUT extends 'array' ? RESULT : DeepPartial<RESULT>, OUTPUT extends 'array' ? RESULT : RESULT, OUTPUT extends 'array' ? RESULT extends Array<infer U> ? AsyncIterableStream<U> : never : never>;
3947
4030
 
3948
4031
  /**
3949
4032
  * A generated audio file.
@@ -4121,15 +4204,15 @@ declare const wrapLanguageModel: ({ model, middleware: middlewareArg, modelId, p
4121
4204
  *
4122
4205
  * @throws {NoSuchModelError} Throws when a requested model is not found and no fallback provider is available.
4123
4206
  */
4124
- declare function customProvider<LANGUAGE_MODELS extends Record<string, LanguageModel>, EMBEDDING_MODELS extends Record<string, EmbeddingModel<string>>, IMAGE_MODELS extends Record<string, ImageModel>>({ languageModels, textEmbeddingModels, imageModels, fallbackProvider, }: {
4207
+ declare function customProvider<LANGUAGE_MODELS extends Record<string, LanguageModelV2>, EMBEDDING_MODELS extends Record<string, EmbeddingModelV2<string>>, IMAGE_MODELS extends Record<string, ImageModelV2>>({ languageModels, textEmbeddingModels, imageModels, fallbackProvider, }: {
4125
4208
  languageModels?: LANGUAGE_MODELS;
4126
4209
  textEmbeddingModels?: EMBEDDING_MODELS;
4127
4210
  imageModels?: IMAGE_MODELS;
4128
4211
  fallbackProvider?: ProviderV2;
4129
- }): Provider & {
4130
- languageModel(modelId: ExtractModelId<LANGUAGE_MODELS>): LanguageModel;
4131
- textEmbeddingModel(modelId: ExtractModelId<EMBEDDING_MODELS>): EmbeddingModel<string>;
4132
- imageModel(modelId: ExtractModelId<IMAGE_MODELS>): ImageModel;
4212
+ }): ProviderV2 & {
4213
+ languageModel(modelId: ExtractModelId<LANGUAGE_MODELS>): LanguageModelV2;
4214
+ textEmbeddingModel(modelId: ExtractModelId<EMBEDDING_MODELS>): EmbeddingModelV2<string>;
4215
+ imageModel(modelId: ExtractModelId<IMAGE_MODELS>): ImageModelV2;
4133
4216
  };
4134
4217
  /**
4135
4218
  * @deprecated Use `customProvider` instead.
@@ -4154,12 +4237,12 @@ declare class NoSuchProviderError extends NoSuchModelError {
4154
4237
 
4155
4238
  type ExtractLiteralUnion<T> = T extends string ? string extends T ? never : T : never;
4156
4239
  interface ProviderRegistryProvider<PROVIDERS extends Record<string, ProviderV2> = Record<string, ProviderV2>, SEPARATOR extends string = ':'> {
4157
- languageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['languageModel']>>[0]>}` : never): LanguageModel;
4158
- languageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): LanguageModel;
4159
- textEmbeddingModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['textEmbeddingModel']>>[0]>}` : never): EmbeddingModel<string>;
4160
- textEmbeddingModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): EmbeddingModel<string>;
4161
- imageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['imageModel']>>[0]>}` : never): ImageModel;
4162
- imageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): ImageModel;
4240
+ languageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['languageModel']>>[0]>}` : never): LanguageModelV2;
4241
+ languageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): LanguageModelV2;
4242
+ textEmbeddingModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['textEmbeddingModel']>>[0]>}` : never): EmbeddingModelV2<string>;
4243
+ textEmbeddingModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): EmbeddingModelV2<string>;
4244
+ imageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['imageModel']>>[0]>}` : never): ImageModelV2;
4245
+ imageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): ImageModelV2;
4163
4246
  }
4164
4247
  /**
4165
4248
  * Creates a registry for the given providers.
@@ -4311,12 +4394,18 @@ type UIMessageStreamPart = {
4311
4394
  text: string;
4312
4395
  providerMetadata?: ProviderMetadata;
4313
4396
  } | {
4314
- type: 'source';
4315
- sourceType: 'url';
4316
- id: string;
4397
+ type: 'source-url';
4398
+ sourceId: string;
4317
4399
  url: string;
4318
4400
  title?: string;
4319
4401
  providerMetadata?: ProviderMetadata;
4402
+ } | {
4403
+ type: 'source-document';
4404
+ sourceId: string;
4405
+ mediaType: string;
4406
+ title: string;
4407
+ filename?: string;
4408
+ providerMetadata?: ProviderMetadata;
4320
4409
  } | {
4321
4410
  type: 'file';
4322
4411
  url: string;
@@ -4341,15 +4430,6 @@ type UIMessageStreamPart = {
4341
4430
  type: 'reasoning-part-finish';
4342
4431
  };
4343
4432
 
4344
- type Job = () => Promise<void>;
4345
-
4346
- declare class SerialJobExecutor {
4347
- private queue;
4348
- private isProcessing;
4349
- private processQueue;
4350
- run(job: Job): Promise<void>;
4351
- }
4352
-
4353
4433
  interface UIMessageStreamWriter {
4354
4434
  /**
4355
4435
  * Appends a data stream part to the stream.
@@ -4367,9 +4447,32 @@ interface UIMessageStreamWriter {
4367
4447
  onError: ((error: unknown) => string) | undefined;
4368
4448
  }
4369
4449
 
4370
- declare function createUIMessageStream({ execute, onError, }: {
4371
- execute: (writer: UIMessageStreamWriter) => Promise<void> | void;
4450
+ declare function createUIMessageStream({ execute, onError, // mask error messages for safety by default
4451
+ originalMessages, onFinish, }: {
4452
+ execute: (options: {
4453
+ writer: UIMessageStreamWriter;
4454
+ }) => Promise<void> | void;
4372
4455
  onError?: (error: unknown) => string;
4456
+ /**
4457
+ * The original messages.
4458
+ */
4459
+ originalMessages?: UIMessage[];
4460
+ onFinish?: (options: {
4461
+ /**
4462
+ * The updates list of UI messages.
4463
+ */
4464
+ messages: UIMessage[];
4465
+ /**
4466
+ * Indicates whether the response message is a continuation of the last original message,
4467
+ * or if a new message was created.
4468
+ */
4469
+ isContinuation: boolean;
4470
+ /**
4471
+ * The message that was sent to the client as a response
4472
+ * (including the original message if it was extended).
4473
+ */
4474
+ responseMessage: UIMessage;
4475
+ }) => void;
4373
4476
  }): ReadableStream<UIMessageStreamPart>;
4374
4477
 
4375
4478
  declare function createUIMessageStreamResponse({ status, statusText, headers, stream, }: ResponseInit & {
@@ -4389,113 +4492,65 @@ interface ChatTransport<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> {
4389
4492
  submitMessages: (options: {
4390
4493
  chatId: string;
4391
4494
  messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];
4392
- abortController: AbortController;
4393
- body?: object;
4394
- headers?: Record<string, string> | Headers;
4495
+ abortSignal: AbortSignal | undefined;
4395
4496
  requestType: 'generate' | 'resume';
4396
- }) => Promise<ReadableStream<UIMessageStreamPart>>;
4397
- }
4398
- declare class DefaultChatTransport<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> implements ChatTransport<MESSAGE_METADATA, DATA_TYPES> {
4399
- private api;
4400
- private credentials?;
4401
- private headers?;
4402
- private body?;
4403
- private streamProtocol?;
4404
- private fetch?;
4405
- private prepareRequestBody?;
4406
- constructor({ api, credentials, headers, body, streamProtocol, fetch, prepareRequestBody, }: {
4407
- api: string;
4408
- /**
4409
- * The credentials mode to be used for the fetch request.
4410
- * Possible values are: 'omit', 'same-origin', 'include'.
4411
- * Defaults to 'same-origin'.
4412
- */
4413
- credentials?: RequestCredentials;
4414
- /**
4415
- * HTTP headers to be sent with the API request.
4416
- */
4417
- headers?: Record<string, string> | Headers;
4418
- /**
4419
- * Extra body object to be sent with the API request.
4420
- * @example
4421
- * Send a `sessionId` to the API along with the messages.
4422
- * ```js
4423
- * useChat({
4424
- * body: {
4425
- * sessionId: '123',
4426
- * }
4427
- * })
4428
- * ```
4429
- */
4430
- body?: object;
4431
- /**
4432
- Streaming protocol that is used. Defaults to `ui-message`.
4433
- */
4434
- streamProtocol?: 'ui-message' | 'text';
4435
- /**
4436
- Custom fetch implementation. You can use it as a middleware to intercept requests,
4437
- or to provide a custom fetch implementation for e.g. testing.
4438
- */
4439
- fetch?: FetchFunction;
4440
- /**
4441
- * When a function is provided, it will be used
4442
- * to prepare the request body for the chat API. This can be useful for
4443
- * customizing the request body based on the messages and data in the chat.
4444
- *
4445
- * @param id The id of the chat.
4446
- * @param messages The current messages in the chat.
4447
- * @param requestBody The request body object passed in the chat request.
4448
- */
4449
- prepareRequestBody?: (options: {
4450
- chatId: string;
4451
- messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];
4452
- requestBody?: object;
4453
- }) => unknown;
4454
- });
4455
- submitMessages({ chatId, messages, abortController, body, headers, requestType, }: Parameters<ChatTransport<MESSAGE_METADATA, DATA_TYPES>['submitMessages']>[0]): Promise<ReadableStream<UIMessageStreamPart>>;
4497
+ } & ChatRequestOptions) => Promise<ReadableStream<UIMessageStreamPart>>;
4456
4498
  }
4457
4499
 
4458
- type StreamingUIMessageState<MESSAGE_METADATA = unknown, UI_DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> = {
4459
- message: UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>;
4460
- activeTextPart: TextUIPart | undefined;
4461
- activeReasoningPart: ReasoningUIPart | undefined;
4462
- partialToolCalls: Record<string, {
4463
- text: string;
4464
- step: number;
4465
- index: number;
4466
- toolName: string;
4467
- }>;
4468
- step: number;
4500
+ type ChatRequestOptions = {
4501
+ /**
4502
+ Additional headers that should be to be passed to the API endpoint.
4503
+ */
4504
+ headers?: Record<string, string> | Headers;
4505
+ /**
4506
+ Additional body JSON properties that should be sent to the API endpoint.
4507
+ */
4508
+ body?: object;
4509
+ metadata?: unknown;
4469
4510
  };
4470
-
4471
- interface ChatStoreSubscriber {
4472
- onChatChanged: (event: ChatStoreEvent) => void;
4511
+ interface ChatSubscriber {
4512
+ onChange: (event: ChatEvent) => void;
4473
4513
  }
4474
- interface ChatStoreEvent {
4475
- type: 'chat-messages-changed' | 'chat-status-changed';
4476
- chatId: number | string;
4477
- error?: Error;
4514
+ interface ChatEvent {
4515
+ type: 'messages-changed' | 'status-changed';
4478
4516
  }
4479
4517
  type ChatStatus = 'submitted' | 'streaming' | 'ready' | 'error';
4480
- interface Chat<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> {
4518
+ interface ChatState<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> {
4481
4519
  status: ChatStatus;
4520
+ error: Error | undefined;
4482
4521
  messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];
4483
- error?: Error;
4484
- activeResponse?: {
4485
- state: StreamingUIMessageState<MESSAGE_METADATA>;
4486
- abortController?: AbortController;
4487
- };
4488
- jobExecutor: SerialJobExecutor;
4522
+ pushMessage: (message: UIMessage<MESSAGE_METADATA, DATA_TYPES>) => void;
4523
+ popMessage: () => void;
4524
+ replaceMessage: (index: number, message: UIMessage<MESSAGE_METADATA, DATA_TYPES>) => void;
4525
+ snapshot: <T>(thing: T) => T;
4489
4526
  }
4490
- type ExtendedCallOptions<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> = ChatRequestOptions & {
4527
+ interface ChatInit<MESSAGE_METADATA = unknown, UI_DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> {
4528
+ /**
4529
+ * A unique identifier for the chat. If not provided, a random one will be
4530
+ * generated.
4531
+ */
4532
+ id?: string;
4533
+ messageMetadataSchema?: Validator<MESSAGE_METADATA> | StandardSchemaV1<MESSAGE_METADATA>;
4534
+ dataPartSchemas?: UI_DATA_PART_SCHEMAS;
4535
+ messages?: UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>[];
4536
+ /**
4537
+ * A way to provide a function that is going to be used for ids for messages and the chat.
4538
+ * If not provided the default AI SDK `generateId` is used.
4539
+ */
4540
+ generateId?: IdGenerator;
4541
+ transport?: ChatTransport<NoInfer<MESSAGE_METADATA>, NoInfer<InferUIDataParts<UI_DATA_PART_SCHEMAS>>>;
4542
+ maxSteps?: number;
4543
+ /**
4544
+ * Callback function to be called when an error is encountered.
4545
+ */
4491
4546
  onError?: (error: Error) => void;
4492
4547
  /**
4493
- Optional callback function that is invoked when a tool call is received.
4494
- Intended for automatic client-side tool execution.
4548
+ Optional callback function that is invoked when a tool call is received.
4549
+ Intended for automatic client-side tool execution.
4495
4550
 
4496
- You can optionally return a result for the tool call,
4497
- either synchronously or asynchronously.
4498
- */
4551
+ You can optionally return a result for the tool call,
4552
+ either synchronously or asynchronously.
4553
+ */
4499
4554
  onToolCall?: ({ toolCall, }: {
4500
4555
  toolCall: ToolCall<string, unknown>;
4501
4556
  }) => void | Promise<unknown> | unknown;
@@ -4505,259 +4560,81 @@ type ExtendedCallOptions<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> = Cha
4505
4560
  * @param message The message that was streamed.
4506
4561
  */
4507
4562
  onFinish?: (options: {
4508
- message: UIMessage<MESSAGE_METADATA, DATA_TYPES>;
4563
+ message: UIMessage<NoInfer<MESSAGE_METADATA>, NoInfer<InferUIDataParts<UI_DATA_PART_SCHEMAS>>>;
4509
4564
  }) => void;
4510
- };
4511
- type UIDataPartSchemas = Record<string, Validator<any> | StandardSchemaV1<any>>;
4512
- type InferUIDataParts<T extends UIDataPartSchemas> = {
4513
- [K in keyof T]: T[K] extends Validator<infer U> ? U : T[K] extends StandardSchemaV1<infer U> ? U : unknown;
4514
- };
4515
- declare class ChatStore<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS extends UIDataPartSchemas> {
4516
- private chats;
4517
- private subscribers;
4518
- private generateId;
4565
+ }
4566
+ declare abstract class AbstractChat<MESSAGE_METADATA = unknown, UI_DATA_PART_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> {
4567
+ readonly id: string;
4568
+ readonly generateId: IdGenerator;
4569
+ protected state: ChatState<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>;
4570
+ private readonly subscribers;
4519
4571
  private messageMetadataSchema;
4520
4572
  private dataPartSchemas;
4521
- private transport;
4573
+ private readonly transport;
4522
4574
  private maxSteps;
4523
- constructor({ chats, generateId, transport, maxSteps, messageMetadataSchema, dataPartSchemas, }: {
4524
- chats?: {
4525
- [id: string]: {
4526
- messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>[];
4527
- };
4528
- };
4529
- generateId?: UseChatOptions['generateId'];
4530
- transport: ChatTransport<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>;
4531
- maxSteps?: number;
4532
- messageMetadataSchema?: Validator<MESSAGE_METADATA> | StandardSchemaV1<MESSAGE_METADATA>;
4533
- dataPartSchemas?: UI_DATA_PART_SCHEMAS;
4575
+ private onError?;
4576
+ private onToolCall?;
4577
+ private onFinish?;
4578
+ private activeResponse;
4579
+ private jobExecutor;
4580
+ constructor({ generateId, id, transport, maxSteps, messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, }: Omit<ChatInit<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS>, 'messages'> & {
4581
+ state: ChatState<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>;
4534
4582
  });
4535
- hasChat(id: string): boolean;
4536
- addChat(id: string, messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>[]): void;
4537
- getChats(): [string, Chat<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>][];
4538
- get chatCount(): number;
4539
- getStatus(id: string): ChatStatus;
4540
- setStatus({ id, status, error, }: {
4541
- id: string;
4542
- status: Chat<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>['status'];
4543
- error?: Error;
4544
- }): void;
4545
- getError(id: string): Error | undefined;
4546
- getMessages(id: string): UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>[];
4547
- getLastMessage(id: string): UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>;
4548
- subscribe(subscriber: ChatStoreSubscriber): () => void;
4549
- setMessages({ id, messages, }: {
4550
- id: string;
4551
- messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>[];
4552
- }): void;
4553
- removeAssistantResponse(id: string): void;
4554
- submitMessage({ chatId, message, headers, body, onError, onToolCall, onFinish, }: ExtendedCallOptions<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>> & {
4555
- chatId: string;
4556
- message: CreateUIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>;
4557
- }): Promise<void>;
4558
- resubmitLastUserMessage({ chatId, headers, body, onError, onToolCall, onFinish, }: ExtendedCallOptions<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>> & {
4559
- chatId: string;
4560
- }): Promise<null | undefined>;
4561
- resumeStream({ chatId, headers, body, onError, onToolCall, onFinish, }: ExtendedCallOptions<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>> & {
4562
- chatId: string;
4563
- }): Promise<null | undefined>;
4564
- addToolResult({ chatId, toolCallId, result, }: {
4565
- chatId: string;
4566
- toolCallId: string;
4567
- result: unknown;
4568
- }): Promise<void>;
4569
- stopStream({ chatId }: {
4570
- chatId: string;
4571
- }): Promise<void>;
4572
- private emit;
4573
- private getChat;
4574
- private triggerRequest;
4575
- }
4576
-
4577
- type ChatRequestOptions = {
4578
- /**
4579
- Additional headers that should be to be passed to the API endpoint.
4580
- */
4581
- headers?: Record<string, string> | Headers;
4582
- /**
4583
- Additional body JSON properties that should be sent to the API endpoint.
4584
- */
4585
- body?: object;
4586
- };
4587
- type UseChatOptions<MESSAGE_METADATA = unknown, DATA_TYPE_SCHEMAS extends UIDataPartSchemas = UIDataPartSchemas> = {
4588
- /**
4589
- * A unique identifier for the chat. If not provided, a random one will be
4590
- * generated. When provided, the `useChat` hook with the same `id` will
4591
- * have shared states across components.
4592
- */
4593
- chatId?: string;
4594
- /**
4595
- * Initial input of the chat.
4596
- */
4597
- initialInput?: string;
4598
- /**
4599
- Optional callback function that is invoked when a tool call is received.
4600
- Intended for automatic client-side tool execution.
4601
-
4602
- You can optionally return a result for the tool call,
4603
- either synchronously or asynchronously.
4604
- */
4605
- onToolCall?: ({ toolCall, }: {
4606
- toolCall: ToolCall<string, unknown>;
4607
- }) => void | Promise<unknown> | unknown;
4608
- /**
4609
- * Optional callback function that is called when the assistant message is finished streaming.
4610
- *
4611
- * @param message The message that was streamed.
4612
- */
4613
- onFinish?: (options: {
4614
- message: UIMessage<MESSAGE_METADATA, InferUIDataParts<DATA_TYPE_SCHEMAS>>;
4615
- }) => void;
4616
- /**
4617
- * Callback function to be called when an error is encountered.
4618
- */
4619
- onError?: (error: Error) => void;
4620
- /**
4621
- * A way to provide a function that is going to be used for ids for messages and the chat.
4622
- * If not provided the default AI SDK `generateId` is used.
4623
- */
4624
- generateId?: IdGenerator;
4625
- /**
4626
- * Optional chat store. Default is used when not provided.
4627
- */
4628
- chatStore?: ChatStore<MESSAGE_METADATA, DATA_TYPE_SCHEMAS>;
4629
- };
4630
- type OriginalUseChatOptions<MESSAGE_METADATA = unknown> = {
4631
- /**
4632
- * Schema for the message metadata. Validates the message metadata.
4633
- * Message metadata can be undefined or must match the schema.
4634
- */
4635
- messageMetadataSchema?: Schema<MESSAGE_METADATA>;
4636
- /**
4637
- * The API endpoint that accepts a `{ messages: Message[] }` object and returns
4638
- * a stream of tokens of the AI chat response. Defaults to `/api/chat`.
4639
- */
4640
- api?: string;
4641
- /**
4642
- * A unique identifier for the chat. If not provided, a random one will be
4643
- * generated. When provided, the `useChat` hook with the same `id` will
4644
- * have shared states across components.
4645
- */
4646
- chatId?: string;
4647
- /**
4648
- * Initial messages of the chat. Useful to load an existing chat history.
4649
- */
4650
- initialMessages?: UIMessage<NoInfer<MESSAGE_METADATA>>[];
4651
- /**
4652
- * Initial input of the chat.
4653
- */
4654
- initialInput?: string;
4655
- /**
4656
- Optional callback function that is invoked when a tool call is received.
4657
- Intended for automatic client-side tool execution.
4658
-
4659
- You can optionally return a result for the tool call,
4660
- either synchronously or asynchronously.
4661
- */
4662
- onToolCall?: ({ toolCall, }: {
4663
- toolCall: ToolCall<string, unknown>;
4664
- }) => void | Promise<unknown> | unknown;
4665
4583
  /**
4666
- * Optional callback function that is called when the assistant message is finished streaming.
4584
+ * Hook status:
4667
4585
  *
4668
- * @param message The message that was streamed.
4669
- */
4670
- onFinish?: (options: {
4671
- message: UIMessage<NoInfer<MESSAGE_METADATA>>;
4672
- }) => void;
4673
- /**
4674
- * Callback function to be called when an error is encountered.
4675
- */
4676
- onError?: (error: Error) => void;
4677
- /**
4678
- * A way to provide a function that is going to be used for ids for messages and the chat.
4679
- * If not provided the default AI SDK `generateId` is used.
4680
- */
4681
- generateId?: IdGenerator;
4682
- /**
4683
- * The credentials mode to be used for the fetch request.
4684
- * Possible values are: 'omit', 'same-origin', 'include'.
4685
- * Defaults to 'same-origin'.
4686
- */
4687
- credentials?: RequestCredentials;
4586
+ * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
4587
+ * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
4588
+ * - `ready`: The full response has been received and processed; a new user message can be submitted.
4589
+ * - `error`: An error occurred during the API request, preventing successful completion.
4590
+ */
4591
+ get status(): ChatStatus;
4592
+ protected setStatus({ status, error, }: {
4593
+ status: ChatStatus;
4594
+ error?: Error;
4595
+ }): void;
4596
+ get error(): Error | undefined;
4597
+ get messages(): UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>[];
4598
+ get lastMessage(): UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>> | undefined;
4599
+ subscribe(subscriber: ChatSubscriber): () => void;
4600
+ set messages(messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>[]);
4601
+ removeAssistantResponse: () => void;
4602
+ /**
4603
+ * Append a user message to the chat list. This triggers the API call to fetch
4604
+ * the assistant's response.
4605
+ */
4606
+ sendMessage: (message: (CreateUIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>> & {
4607
+ text?: never;
4608
+ files?: never;
4609
+ }) | {
4610
+ text: string;
4611
+ files?: FileList | FileUIPart[];
4612
+ metadata?: MESSAGE_METADATA;
4613
+ parts?: never;
4614
+ } | {
4615
+ files: FileList | FileUIPart[];
4616
+ metadata?: MESSAGE_METADATA;
4617
+ parts?: never;
4618
+ }, options?: ChatRequestOptions) => Promise<void>;
4688
4619
  /**
4689
- * HTTP headers to be sent with the API request.
4620
+ * Regenerate the last assistant message.
4690
4621
  */
4691
- headers?: Record<string, string> | Headers;
4622
+ reload: (options?: ChatRequestOptions) => Promise<void>;
4692
4623
  /**
4693
- * Extra body object to be sent with the API request.
4694
- * @example
4695
- * Send a `sessionId` to the API along with the messages.
4696
- * ```js
4697
- * useChat({
4698
- * body: {
4699
- * sessionId: '123',
4700
- * }
4701
- * })
4702
- * ```
4624
+ * Resume an ongoing chat generation stream. This does not resume an aborted generation.
4703
4625
  */
4704
- body?: object;
4705
- /**
4706
- Streaming protocol that is used. Defaults to `ui-message`.
4707
- */
4708
- streamProtocol?: 'ui-message' | 'text';
4709
- /**
4710
- Custom fetch implementation. You can use it as a middleware to intercept requests,
4711
- or to provide a custom fetch implementation for e.g. testing.
4712
- */
4713
- fetch?: FetchFunction;
4626
+ experimental_resume: (options?: ChatRequestOptions) => Promise<void>;
4627
+ addToolResult: ({ toolCallId, result, }: {
4628
+ toolCallId: string;
4629
+ result: unknown;
4630
+ }) => Promise<void>;
4714
4631
  /**
4715
- Maximum number of sequential LLM calls (steps), e.g. when you use tool calls.
4716
- Must be at least 1.
4717
-
4718
- A maximum number is required to prevent infinite loops in the case of misconfigured tools.
4719
-
4720
- By default, it's set to 1, which means that only a single LLM call is made.
4632
+ * Abort the current request immediately, keep the generated tokens if any.
4721
4633
  */
4722
- maxSteps?: number;
4723
- };
4724
-
4725
- declare const getOriginalFetch$1: () => typeof fetch;
4726
- declare function callChatApi<MESSAGE_METADATA>({ api, body, streamProtocol, credentials, headers, abortController, onUpdate, onFinish, onToolCall, generateId, fetch, lastMessage, requestType, messageMetadataSchema, }: {
4727
- api: string;
4728
- body: Record<string, any>;
4729
- streamProtocol: 'ui-message' | 'text' | undefined;
4730
- credentials: RequestCredentials | undefined;
4731
- headers: HeadersInit | undefined;
4732
- abortController: (() => AbortController | null) | undefined;
4733
- onUpdate: (options: {
4734
- message: UIMessage<MESSAGE_METADATA>;
4735
- }) => void;
4736
- onFinish: UseChatOptions<MESSAGE_METADATA>['onFinish'];
4737
- onToolCall: UseChatOptions<MESSAGE_METADATA>['onToolCall'];
4738
- generateId: IdGenerator;
4739
- fetch: ReturnType<typeof getOriginalFetch$1> | undefined;
4740
- lastMessage: UIMessage<MESSAGE_METADATA> | undefined;
4741
- requestType?: 'generate' | 'resume';
4742
- messageMetadataSchema?: Schema<MESSAGE_METADATA>;
4743
- }): Promise<void>;
4744
-
4745
- declare const getOriginalFetch: () => typeof fetch;
4746
- declare function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol, setCompletion, setLoading, setError, setAbortController, onFinish, onError, fetch, }: {
4747
- api: string;
4748
- prompt: string;
4749
- credentials: RequestCredentials | undefined;
4750
- headers: HeadersInit | undefined;
4751
- body: Record<string, any>;
4752
- streamProtocol: 'data' | 'text' | undefined;
4753
- setCompletion: (completion: string) => void;
4754
- setLoading: (loading: boolean) => void;
4755
- setError: (error: Error | undefined) => void;
4756
- setAbortController: (abortController: AbortController | null) => void;
4757
- onFinish: ((prompt: string, completion: string) => void) | undefined;
4758
- onError: ((error: Error) => void) | undefined;
4759
- fetch: ReturnType<typeof getOriginalFetch> | undefined;
4760
- }): Promise<string | null | undefined>;
4634
+ stop: () => Promise<void>;
4635
+ private emit;
4636
+ private triggerRequest;
4637
+ }
4761
4638
 
4762
4639
  declare function convertFileListToFileUIParts(files: FileList | undefined): Promise<Array<FileUIPart>>;
4763
4640
 
@@ -4773,121 +4650,122 @@ declare function convertToModelMessages<TOOLS extends ToolSet = never>(messages:
4773
4650
  */
4774
4651
  declare const convertToCoreMessages: typeof convertToModelMessages;
4775
4652
 
4776
- declare function defaultChatStore<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS extends UIDataPartSchemas>({ api, fetch, streamProtocol, credentials, headers, body, prepareRequestBody, generateId, dataPartSchemas, messageMetadataSchema, maxSteps, chats, }: {
4777
- /**
4778
- * Schema for the message metadata. Validates the message metadata.
4779
- * Message metadata can be undefined or must match the schema.
4780
- */
4781
- messageMetadataSchema?: Validator<MESSAGE_METADATA> | StandardSchemaV1<MESSAGE_METADATA>;
4782
- /**
4783
- * Schema for the data types. Validates the data types.
4784
- */
4785
- dataPartSchemas?: UI_DATA_PART_SCHEMAS;
4786
- /**
4787
- * The API endpoint that accepts a `{ messages: Message[] }` object and returns
4788
- * a stream of tokens of the AI chat response.
4789
- */
4790
- api: string;
4791
- /**
4792
- * A way to provide a function that is going to be used for ids for messages and the chat.
4793
- * If not provided the default AI SDK `generateId` is used.
4794
- */
4795
- generateId?: IdGenerator;
4796
- /**
4797
- * The credentials mode to be used for the fetch request.
4798
- * Possible values are: 'omit', 'same-origin', 'include'.
4799
- * Defaults to 'same-origin'.
4800
- */
4653
+ type PrepareRequest<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> = (options: {
4654
+ id: string;
4655
+ messages: UIMessage<MESSAGE_METADATA, DATA_TYPES>[];
4656
+ requestMetadata: unknown;
4657
+ body: Record<string, any> | undefined;
4658
+ credentials: RequestCredentials | undefined;
4659
+ headers: HeadersInit | undefined;
4660
+ }) => {
4661
+ body: object;
4662
+ headers?: HeadersInit;
4801
4663
  credentials?: RequestCredentials;
4802
- /**
4803
- * HTTP headers to be sent with the API request.
4804
- */
4805
- headers?: Record<string, string> | Headers;
4806
- /**
4807
- * Extra body object to be sent with the API request.
4808
- * @example
4809
- * Send a `sessionId` to the API along with the messages.
4810
- * ```js
4811
- * useChat({
4812
- * body: {
4813
- * sessionId: '123',
4814
- * }
4815
- * })
4816
- * ```
4817
- */
4818
- body?: object;
4819
- /**
4820
- Streaming protocol that is used. Defaults to `ui-message`.
4664
+ };
4665
+
4666
+ declare class DefaultChatTransport<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> implements ChatTransport<MESSAGE_METADATA, DATA_TYPES> {
4667
+ private api;
4668
+ private credentials?;
4669
+ private headers?;
4670
+ private body?;
4671
+ private fetch?;
4672
+ private prepareRequest?;
4673
+ constructor({ api, credentials, headers, body, fetch, prepareRequest, }?: {
4674
+ api?: string;
4675
+ /**
4676
+ * The credentials mode to be used for the fetch request.
4677
+ * Possible values are: 'omit', 'same-origin', 'include'.
4678
+ * Defaults to 'same-origin'.
4821
4679
  */
4822
- streamProtocol?: 'ui-message' | 'text';
4823
- /**
4680
+ credentials?: RequestCredentials;
4681
+ /**
4682
+ * HTTP headers to be sent with the API request.
4683
+ */
4684
+ headers?: Record<string, string> | Headers;
4685
+ /**
4686
+ * Extra body object to be sent with the API request.
4687
+ * @example
4688
+ * Send a `sessionId` to the API along with the messages.
4689
+ * ```js
4690
+ * useChat({
4691
+ * body: {
4692
+ * sessionId: '123',
4693
+ * }
4694
+ * })
4695
+ * ```
4696
+ */
4697
+ body?: object;
4698
+ /**
4824
4699
  Custom fetch implementation. You can use it as a middleware to intercept requests,
4825
4700
  or to provide a custom fetch implementation for e.g. testing.
4826
4701
  */
4827
- fetch?: FetchFunction;
4828
- /**
4829
- Maximum number of sequential LLM calls (steps), e.g. when you use tool calls.
4830
- Must be at least 1.
4831
-
4832
- A maximum number is required to prevent infinite loops in the case of misconfigured tools.
4833
-
4834
- By default, it's set to 1, which means that only a single LLM call is made.
4835
- */
4836
- maxSteps?: number;
4837
- /**
4838
- * When a function is provided, it will be used
4839
- * to prepare the request body for the chat API. This can be useful for
4840
- * customizing the request body based on the messages and data in the chat.
4841
- *
4842
- * @param chatId The id of the chat.
4843
- * @param messages The current messages in the chat.
4844
- * @param requestBody The request body object passed in the chat request.
4845
- */
4846
- prepareRequestBody?: (options: {
4847
- chatId: string;
4848
- messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>[];
4849
- requestBody?: object;
4850
- }) => unknown;
4851
- chats?: {
4852
- [id: string]: {
4853
- messages: UIMessage<MESSAGE_METADATA, InferUIDataParts<UI_DATA_PART_SCHEMAS>>[];
4854
- };
4855
- };
4856
- }): ChatStore<MESSAGE_METADATA, UI_DATA_PART_SCHEMAS>;
4857
-
4858
- declare function extractMaxToolInvocationStep(toolInvocations: ToolInvocation[] | undefined): number | undefined;
4702
+ fetch?: FetchFunction;
4703
+ /**
4704
+ * When a function is provided, it will be used
4705
+ * to prepare the request body for the chat API. This can be useful for
4706
+ * customizing the request body based on the messages and data in the chat.
4707
+ *
4708
+ * @param id The id of the chat.
4709
+ * @param messages The current messages in the chat.
4710
+ * @param requestBody The request body object passed in the chat request.
4711
+ */
4712
+ prepareRequest?: PrepareRequest<MESSAGE_METADATA, DATA_TYPES>;
4713
+ });
4714
+ submitMessages({ chatId, messages, abortSignal, metadata, headers, body, requestType, }: Parameters<ChatTransport<MESSAGE_METADATA, DATA_TYPES>['submitMessages']>[0]): Promise<ReadableStream<UIMessageStreamPart>>;
4715
+ }
4859
4716
 
4860
4717
  declare function getToolInvocations(message: UIMessage): ToolInvocation[];
4861
4718
 
4862
- declare function shouldResubmitMessages({ originalMaxToolInvocationStep, originalMessageCount, maxSteps, messages, }: {
4863
- originalMaxToolInvocationStep: number | undefined;
4864
- originalMessageCount: number;
4865
- maxSteps: number;
4866
- messages: UIMessage[];
4867
- }): boolean;
4868
- /**
4869
- Check if the message is an assistant message with completed tool calls.
4870
- The last step of the message must have at least one tool invocation and
4871
- all tool invocations must have a result.
4872
- */
4873
- declare function isAssistantMessageWithCompletedToolCalls(message: UIMessage): message is UIMessage & {
4874
- role: 'assistant';
4875
- };
4876
-
4877
- /**
4878
- * Updates the result of a specific tool invocation in the last message of the given messages array.
4879
- *
4880
- * @param {object} params - The parameters object.
4881
- * @param {UIMessage[]} params.messages - An array of messages, from which the last one is updated.
4882
- * @param {string} params.toolCallId - The unique identifier for the tool invocation to update.
4883
- * @param {unknown} params.toolResult - The result object to attach to the tool invocation.
4884
- * @returns {void} This function does not return anything.
4885
- */
4886
- declare function updateToolCallResult({ messages, toolCallId, toolResult: result, }: {
4887
- messages: UIMessage[];
4888
- toolCallId: string;
4889
- toolResult: unknown;
4890
- }): void;
4719
+ declare class TextStreamChatTransport<MESSAGE_METADATA, DATA_TYPES extends UIDataTypes> implements ChatTransport<MESSAGE_METADATA, DATA_TYPES> {
4720
+ private api;
4721
+ private credentials?;
4722
+ private headers?;
4723
+ private body?;
4724
+ private fetch?;
4725
+ private prepareRequest?;
4726
+ constructor({ api, credentials, headers, body, fetch, prepareRequest, }: {
4727
+ api: string;
4728
+ /**
4729
+ * The credentials mode to be used for the fetch request.
4730
+ * Possible values are: 'omit', 'same-origin', 'include'.
4731
+ * Defaults to 'same-origin'.
4732
+ */
4733
+ credentials?: RequestCredentials;
4734
+ /**
4735
+ * HTTP headers to be sent with the API request.
4736
+ */
4737
+ headers?: Record<string, string> | Headers;
4738
+ /**
4739
+ * Extra body object to be sent with the API request.
4740
+ * @example
4741
+ * Send a `sessionId` to the API along with the messages.
4742
+ * ```js
4743
+ * useChat({
4744
+ * body: {
4745
+ * sessionId: '123',
4746
+ * }
4747
+ * })
4748
+ * ```
4749
+ */
4750
+ body?: object;
4751
+ /**
4752
+ Custom fetch implementation. You can use it as a middleware to intercept requests,
4753
+ or to provide a custom fetch implementation for e.g. testing.
4754
+ */
4755
+ fetch?: FetchFunction;
4756
+ /**
4757
+ * When a function is provided, it will be used
4758
+ * to prepare the request body for the chat API. This can be useful for
4759
+ * customizing the request body based on the messages and data in the chat.
4760
+ *
4761
+ * @param id The id of the chat.
4762
+ * @param messages The current messages in the chat.
4763
+ * @param requestBody The request body object passed in the chat request.
4764
+ */
4765
+ prepareRequest?: NoInfer<PrepareRequest<MESSAGE_METADATA, DATA_TYPES>>;
4766
+ });
4767
+ submitMessages({ chatId, messages, abortSignal, metadata, headers, body, requestType, }: Parameters<ChatTransport<MESSAGE_METADATA, DATA_TYPES>['submitMessages']>[0]): Promise<ReadableStream<UIMessageStreamPart>>;
4768
+ }
4891
4769
 
4892
4770
  type CompletionRequestOptions = {
4893
4771
  /**
@@ -4961,4 +4839,4 @@ type UseCompletionOptions = {
4961
4839
  fetch?: FetchFunction;
4962
4840
  };
4963
4841
 
4964
- export { AssistantContent, AssistantModelMessage, CallSettings, CallWarning, ChatRequestOptions, ChatStatus, ChatStore, ChatStoreEvent, ChatTransport, ChunkDetector, CompletionRequestOptions, CoreAssistantMessage, CoreMessage, CoreSystemMessage, CoreToolMessage, CoreUserMessage, CreateUIMessage, DataContent, DataUIPart, DeepPartial, 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 as InferUIDataTypes, 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, Prompt, Provider, ProviderMetadata, ProviderOptions, ProviderRegistryProvider, ReasoningUIPart, RepairTextFunction, RetryError, SourceUIPart, SpeechModel, SpeechModelResponseMetadata, SpeechWarning, StepResult, StepStartUIPart, StopCondition, StreamObjectOnFinishCallback, StreamObjectResult, StreamTextOnChunkCallback, StreamTextOnErrorCallback, StreamTextOnFinishCallback, StreamTextOnStepFinishCallback, StreamTextResult, StreamTextTransform, SystemModelMessage, TelemetrySettings, TextPart, TextStreamPart, TextUIPart, Tool, ToolCallPart, ToolCallRepairError, ToolCallRepairFunction, ToolCallUnion, ToolChoice, ToolContent, ToolExecutionError, ToolExecutionOptions, ToolInvocation, ToolInvocationUIPart, ToolModelMessage, ToolResultPart, ToolResultUnion, ToolSet, TranscriptionModel, TranscriptionModelResponseMetadata, TranscriptionWarning, UIDataTypes, UIDataPartSchemas as UIDataTypesSchemas, 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, defaultChatStore, 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, maxSteps, modelMessageSchema, parsePartialJson, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, shouldResubmitMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, streamObject, streamText, systemModelMessageSchema, tool, toolModelMessageSchema, updateToolCallResult, userModelMessageSchema, wrapLanguageModel };
4842
+ export { AbstractChat, AssistantContent, AssistantModelMessage, CallSettings, CallWarning, ChatEvent, ChatInit, ChatRequestOptions, ChatState, ChatStatus, ChatTransport, ChunkDetector, CompletionRequestOptions, CoreAssistantMessage, CoreMessage, CoreSystemMessage, CoreToolMessage, CoreUserMessage, CreateUIMessage, DataContent, DataUIPart, DeepPartial, 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, GLOBAL_DEFAULT_PROVIDER, 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, ToolCallOptions, ToolCallPart, ToolCallRepairError, ToolCallRepairFunction, ToolCallUnion, ToolChoice, ToolContent, ToolExecutionError, ToolInvocation, ToolInvocationUIPart, ToolModelMessage, ToolResultPart, ToolResultUnion, ToolSet, TranscriptionModel, TranscriptionModelResponseMetadata, TranscriptionWarning, UIDataPartSchemas, UIDataTypes, UIMessage, UIMessagePart, UIMessageStreamOptions, UIMessageStreamPart, UIMessageStreamWriter, UseCompletionOptions, UserContent, UserModelMessage, assistantModelMessageSchema, callCompletionApi, convertFileListToFileUIParts, convertToCoreMessages, convertToModelMessages, coreAssistantMessageSchema, coreMessageSchema, coreSystemMessageSchema, coreToolMessageSchema, coreUserMessageSchema, cosineSimilarity, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, 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 };