ai 6.0.0-beta.60 → 6.0.0-beta.62

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,6 +1,6 @@
1
1
  export { createGateway, gateway } from '@ai-sdk/gateway';
2
2
  import * as _ai_sdk_provider_utils from '@ai-sdk/provider-utils';
3
- import { Tool, InferToolInput, InferToolOutput, AssistantModelMessage, ToolModelMessage, ReasoningPart, ModelMessage, FlexibleSchema, InferSchema, SystemModelMessage, UserModelMessage, ProviderOptions, IdGenerator, ToolCall, DataContent, Resolvable, FetchFunction } from '@ai-sdk/provider-utils';
3
+ import { Tool, InferToolInput, InferToolOutput, AssistantModelMessage, ToolModelMessage, ReasoningPart, ModelMessage, FlexibleSchema, InferSchema, SystemModelMessage, UserModelMessage, ProviderOptions, IdGenerator, ToolCall, Resolvable, FetchFunction, DataContent } from '@ai-sdk/provider-utils';
4
4
  export { AssistantContent, AssistantModelMessage, DataContent, FilePart, FlexibleSchema, IdGenerator, ImagePart, InferSchema, InferToolInput, InferToolOutput, ModelMessage, Schema, SystemModelMessage, TextPart, Tool, ToolApprovalRequest, ToolApprovalResponse, ToolCallOptions, ToolCallPart, ToolContent, ToolExecuteFunction, ToolModelMessage, ToolResultPart, UserContent, UserModelMessage, asSchema, createIdGenerator, dynamicTool, generateId, jsonSchema, parseJsonEventStream, tool, zodSchema } from '@ai-sdk/provider-utils';
5
5
  import * as _ai_sdk_provider from '@ai-sdk/provider';
6
6
  import { EmbeddingModelV3, EmbeddingModelV2, EmbeddingModelV3Embedding, ImageModelV3, ImageModelV3CallWarning, ImageModelV3ProviderMetadata, JSONValue as JSONValue$1, LanguageModelV3, LanguageModelV2, LanguageModelV3FinishReason, LanguageModelV3CallWarning, LanguageModelV3Source, LanguageModelV3Middleware, SharedV3ProviderMetadata, SpeechModelV3, SpeechModelV2, SpeechModelV3CallWarning, TranscriptionModelV3, TranscriptionModelV2, TranscriptionModelV3CallWarning, LanguageModelV3Usage, LanguageModelV3CallOptions, AISDKError, LanguageModelV3ToolCall, JSONSchema7, JSONParseError, TypeValidationError, ProviderV3, ProviderV2, NoSuchModelError, JSONObject } from '@ai-sdk/provider';
@@ -2552,592 +2552,740 @@ type InferAgentTools<AGENT> = AGENT extends Agent<infer TOOLS, any, any> ? TOOLS
2552
2552
  type InferAgentUIMessage<AGENT> = UIMessage<never, never, InferUITools<InferAgentTools<AGENT>>>;
2553
2553
 
2554
2554
  /**
2555
- * Runs the agent and stream the output as a UI message stream
2556
- * in the response body.
2555
+ * Runs the agent and returns a response object with a UI message stream.
2557
2556
  *
2558
2557
  * @param agent - The agent to run.
2559
2558
  * @param messages - The input UI messages.
2560
2559
  *
2561
2560
  * @returns The response object.
2562
2561
  */
2563
- declare function createAgentStreamResponse<TOOLS extends ToolSet = {}, OUTPUT = never, OUTPUT_PARTIAL = never>({ agent, messages, ...options }: {
2562
+ declare function createAgentUIStreamResponse<TOOLS extends ToolSet = {}, OUTPUT = never, OUTPUT_PARTIAL = never>({ headers, status, statusText, consumeSseStream, ...options }: {
2564
2563
  agent: Agent<TOOLS, OUTPUT, OUTPUT_PARTIAL>;
2565
2564
  messages: unknown[];
2566
- } & UIMessageStreamOptions<UIMessage<never, never, InferUITools<TOOLS>>>): Promise<Response>;
2565
+ } & UIMessageStreamResponseInit & UIMessageStreamOptions<UIMessage<never, never, InferUITools<TOOLS>>>): Promise<Response>;
2566
+
2567
+ declare const getOriginalFetch: () => typeof fetch;
2568
+ declare function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol, setCompletion, setLoading, setError, setAbortController, onFinish, onError, fetch, }: {
2569
+ api: string;
2570
+ prompt: string;
2571
+ credentials: RequestCredentials | undefined;
2572
+ headers: HeadersInit | undefined;
2573
+ body: Record<string, any>;
2574
+ streamProtocol: 'data' | 'text' | undefined;
2575
+ setCompletion: (completion: string) => void;
2576
+ setLoading: (loading: boolean) => void;
2577
+ setError: (error: Error | undefined) => void;
2578
+ setAbortController: (abortController: AbortController | null) => void;
2579
+ onFinish: ((prompt: string, completion: string) => void) | undefined;
2580
+ onError: ((error: Error) => void) | undefined;
2581
+ fetch: ReturnType<typeof getOriginalFetch> | undefined;
2582
+ }): Promise<string | null | undefined>;
2567
2583
 
2568
2584
  /**
2569
- The result of an `embed` call.
2570
- It contains the embedding, the value, and additional information.
2585
+ * Transport interface for handling chat message communication and streaming.
2586
+ *
2587
+ * The `ChatTransport` interface provides fine-grained control over how messages
2588
+ * are sent to API endpoints and how responses are processed. This enables
2589
+ * alternative communication protocols like WebSockets, custom authentication
2590
+ * patterns, or specialized backend integrations.
2591
+ *
2592
+ * @template UI_MESSAGE - The UI message type extending UIMessage
2571
2593
  */
2572
- interface EmbedResult<VALUE> {
2573
- /**
2574
- The value that was embedded.
2575
- */
2576
- readonly value: VALUE;
2577
- /**
2578
- The embedding of the value.
2579
- */
2580
- readonly embedding: Embedding;
2581
- /**
2582
- The embedding token usage.
2583
- */
2584
- readonly usage: EmbeddingModelUsage;
2594
+ interface ChatTransport<UI_MESSAGE extends UIMessage> {
2585
2595
  /**
2586
- Optional provider-specific metadata.
2587
- */
2588
- readonly providerMetadata?: ProviderMetadata;
2596
+ * Sends messages to the chat API endpoint and returns a streaming response.
2597
+ *
2598
+ * This method handles both new message submission and message regeneration.
2599
+ * It supports real-time streaming of responses through UIMessageChunk events.
2600
+ *
2601
+ * @param options - Configuration object containing:
2602
+ * @param options.trigger - The type of message submission:
2603
+ * - `'submit-message'`: Submitting a new user message
2604
+ * - `'regenerate-message'`: Regenerating an assistant response
2605
+ * @param options.chatId - Unique identifier for the chat session
2606
+ * @param options.messageId - ID of the message to regenerate (for regenerate-message trigger) or undefined for new messages
2607
+ * @param options.messages - Array of UI messages representing the conversation history
2608
+ * @param options.abortSignal - Signal to abort the request if needed
2609
+ * @param options.headers - Additional HTTP headers to include in the request
2610
+ * @param options.body - Additional JSON properties to include in the request body
2611
+ * @param options.metadata - Custom metadata to attach to the request
2612
+ *
2613
+ * @returns Promise resolving to a ReadableStream of UIMessageChunk objects.
2614
+ * The stream emits various chunk types like:
2615
+ * - `text-start`, `text-delta`, `text-end`: For streaming text content
2616
+ * - `tool-input-start`, `tool-input-delta`, `tool-input-available`: For tool calls
2617
+ * - `data-part-start`, `data-part-delta`, `data-part-available`: For data parts
2618
+ * - `error`: For error handling
2619
+ *
2620
+ * @throws Error when the API request fails or response is invalid
2621
+ */
2622
+ sendMessages: (options: {
2623
+ /** The type of message submission - either new message or regeneration */
2624
+ trigger: 'submit-message' | 'regenerate-message';
2625
+ /** Unique identifier for the chat session */
2626
+ chatId: string;
2627
+ /** ID of the message to regenerate, or undefined for new messages */
2628
+ messageId: string | undefined;
2629
+ /** Array of UI messages representing the conversation history */
2630
+ messages: UI_MESSAGE[];
2631
+ /** Signal to abort the request if needed */
2632
+ abortSignal: AbortSignal | undefined;
2633
+ } & ChatRequestOptions) => Promise<ReadableStream<UIMessageChunk>>;
2589
2634
  /**
2590
- Optional response data.
2591
- */
2592
- readonly response?: {
2593
- /**
2594
- Response headers.
2595
- */
2596
- headers?: Record<string, string>;
2597
- /**
2598
- The response body.
2599
- */
2600
- body?: unknown;
2601
- };
2635
+ * Reconnects to an existing streaming response for the specified chat session.
2636
+ *
2637
+ * This method is used to resume streaming when a connection is interrupted
2638
+ * or when resuming a chat session. It's particularly useful for maintaining
2639
+ * continuity in long-running conversations or recovering from network issues.
2640
+ *
2641
+ * @param options - Configuration object containing:
2642
+ * @param options.chatId - Unique identifier for the chat session to reconnect to
2643
+ * @param options.headers - Additional HTTP headers to include in the reconnection request
2644
+ * @param options.body - Additional JSON properties to include in the request body
2645
+ * @param options.metadata - Custom metadata to attach to the request
2646
+ *
2647
+ * @returns Promise resolving to:
2648
+ * - `ReadableStream<UIMessageChunk>`: If an active stream is found and can be resumed
2649
+ * - `null`: If no active stream exists for the specified chat session (e.g., response already completed)
2650
+ *
2651
+ * @throws Error when the reconnection request fails or response is invalid
2652
+ */
2653
+ reconnectToStream: (options: {
2654
+ /** Unique identifier for the chat session to reconnect to */
2655
+ chatId: string;
2656
+ } & ChatRequestOptions) => Promise<ReadableStream<UIMessageChunk> | null>;
2602
2657
  }
2603
2658
 
2604
- /**
2605
- Embed a value using an embedding model. The type of the value is defined by the embedding model.
2606
-
2607
- @param model - The embedding model to use.
2608
- @param value - The value that should be embedded.
2609
-
2610
- @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
2611
- @param abortSignal - An optional abort signal that can be used to cancel the call.
2612
- @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
2613
-
2614
- @returns A result object that contains the embedding, the value, and additional information.
2615
- */
2616
- declare function embed<VALUE = string>({ model: modelArg, value, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry: telemetry, }: {
2617
- /**
2618
- The embedding model to use.
2619
- */
2620
- model: EmbeddingModel<VALUE>;
2659
+ type CreateUIMessage<UI_MESSAGE extends UIMessage> = Omit<UI_MESSAGE, 'id' | 'role'> & {
2660
+ id?: UI_MESSAGE['id'];
2661
+ role?: UI_MESSAGE['role'];
2662
+ };
2663
+ type UIDataPartSchemas = Record<string, FlexibleSchema>;
2664
+ type UIDataTypesToSchemas<T extends UIDataTypes> = {
2665
+ [K in keyof T]: FlexibleSchema<T[K]>;
2666
+ };
2667
+ type InferUIDataParts<T extends UIDataPartSchemas> = {
2668
+ [K in keyof T]: InferSchema<T[K]>;
2669
+ };
2670
+ type ChatRequestOptions = {
2621
2671
  /**
2622
- The value that should be embedded.
2672
+ Additional headers that should be to be passed to the API endpoint.
2623
2673
  */
2624
- value: VALUE;
2674
+ headers?: Record<string, string> | Headers;
2625
2675
  /**
2626
- Maximum number of retries per embedding model call. Set to 0 to disable retries.
2627
-
2628
- @default 2
2676
+ Additional body JSON properties that should be sent to the API endpoint.
2629
2677
  */
2630
- maxRetries?: number;
2631
- /**
2632
- Abort signal.
2633
- */
2634
- abortSignal?: AbortSignal;
2635
- /**
2636
- Additional headers to include in the request.
2637
- Only applicable for HTTP-based providers.
2638
- */
2639
- headers?: Record<string, string>;
2678
+ body?: object;
2679
+ metadata?: unknown;
2680
+ };
2681
+ /**
2682
+ * Function that can be called to add a tool approval response to the chat.
2683
+ */
2684
+ type ChatAddToolApproveResponseFunction = ({ id, approved, reason, }: {
2685
+ id: string;
2640
2686
  /**
2641
- Additional provider-specific options. They are passed through
2642
- to the provider from the AI SDK and enable provider-specific
2643
- functionality that can be fully encapsulated in the provider.
2644
- */
2645
- providerOptions?: ProviderOptions;
2687
+ * Flag indicating whether the approval was granted or denied.
2688
+ */
2689
+ approved: boolean;
2646
2690
  /**
2647
- * Optional telemetry configuration (experimental).
2691
+ * Optional reason for the approval or denial.
2648
2692
  */
2649
- experimental_telemetry?: TelemetrySettings;
2650
- }): Promise<EmbedResult<VALUE>>;
2651
-
2693
+ reason?: string;
2694
+ }) => void | PromiseLike<void>;
2695
+ type ChatStatus = 'submitted' | 'streaming' | 'ready' | 'error';
2696
+ interface ChatState<UI_MESSAGE extends UIMessage> {
2697
+ status: ChatStatus;
2698
+ error: Error | undefined;
2699
+ messages: UI_MESSAGE[];
2700
+ pushMessage: (message: UI_MESSAGE) => void;
2701
+ popMessage: () => void;
2702
+ replaceMessage: (index: number, message: UI_MESSAGE) => void;
2703
+ snapshot: <T>(thing: T) => T;
2704
+ }
2705
+ type ChatOnErrorCallback = (error: Error) => void;
2706
+ type ChatOnToolCallCallback<UI_MESSAGE extends UIMessage = UIMessage> = (options: {
2707
+ toolCall: InferUIMessageToolCall<UI_MESSAGE>;
2708
+ }) => void | PromiseLike<void>;
2709
+ type ChatOnDataCallback<UI_MESSAGE extends UIMessage> = (dataPart: DataUIPart<InferUIMessageData<UI_MESSAGE>>) => void;
2652
2710
  /**
2653
- The result of a `embedMany` call.
2654
- It contains the embeddings, the values, and additional information.
2711
+ * Function that is called when the assistant response has finished streaming.
2712
+ *
2713
+ * @param message The assistant message that was streamed.
2714
+ * @param messages The full chat history, including the assistant message.
2715
+ *
2716
+ * @param isAbort Indicates whether the request has been aborted.
2717
+ * @param isDisconnect Indicates whether the request has been ended by a network error.
2718
+ * @param isError Indicates whether the request has been ended by an error.
2655
2719
  */
2656
- interface EmbedManyResult<VALUE> {
2720
+ type ChatOnFinishCallback<UI_MESSAGE extends UIMessage> = (options: {
2721
+ message: UI_MESSAGE;
2722
+ messages: UI_MESSAGE[];
2723
+ isAbort: boolean;
2724
+ isDisconnect: boolean;
2725
+ isError: boolean;
2726
+ }) => void;
2727
+ interface ChatInit<UI_MESSAGE extends UIMessage> {
2657
2728
  /**
2658
- The values that were embedded.
2659
- */
2660
- readonly values: Array<VALUE>;
2729
+ * A unique identifier for the chat. If not provided, a random one will be
2730
+ * generated.
2731
+ */
2732
+ id?: string;
2733
+ messageMetadataSchema?: FlexibleSchema<InferUIMessageMetadata<UI_MESSAGE>>;
2734
+ dataPartSchemas?: UIDataTypesToSchemas<InferUIMessageData<UI_MESSAGE>>;
2735
+ messages?: UI_MESSAGE[];
2661
2736
  /**
2662
- The embeddings. They are in the same order as the values.
2663
- */
2664
- readonly embeddings: Array<Embedding>;
2737
+ * A way to provide a function that is going to be used for ids for messages and the chat.
2738
+ * If not provided the default AI SDK `generateId` is used.
2739
+ */
2740
+ generateId?: IdGenerator;
2741
+ transport?: ChatTransport<UI_MESSAGE>;
2665
2742
  /**
2666
- The embedding token usage.
2667
- */
2668
- readonly usage: EmbeddingModelUsage;
2743
+ * Callback function to be called when an error is encountered.
2744
+ */
2745
+ onError?: ChatOnErrorCallback;
2669
2746
  /**
2670
- Optional provider-specific metadata.
2747
+ Optional callback function that is invoked when a tool call is received.
2748
+ Intended for automatic client-side tool execution.
2749
+
2750
+ You can optionally return a result for the tool call,
2751
+ either synchronously or asynchronously.
2671
2752
  */
2672
- readonly providerMetadata?: ProviderMetadata;
2753
+ onToolCall?: ChatOnToolCallCallback<UI_MESSAGE>;
2673
2754
  /**
2674
- Optional raw response data.
2675
- */
2676
- readonly responses?: Array<{
2677
- /**
2678
- Response headers.
2679
- */
2680
- headers?: Record<string, string>;
2681
- /**
2682
- The response body.
2683
- */
2684
- body?: unknown;
2685
- } | undefined>;
2755
+ * Function that is called when the assistant response has finished streaming.
2756
+ */
2757
+ onFinish?: ChatOnFinishCallback<UI_MESSAGE>;
2758
+ /**
2759
+ * Optional callback function that is called when a data part is received.
2760
+ *
2761
+ * @param data The data part that was received.
2762
+ */
2763
+ onData?: ChatOnDataCallback<UI_MESSAGE>;
2764
+ /**
2765
+ * When provided, this function will be called when the stream is finished or a tool call is added
2766
+ * to determine if the current messages should be resubmitted.
2767
+ */
2768
+ sendAutomaticallyWhen?: (options: {
2769
+ messages: UI_MESSAGE[];
2770
+ }) => boolean | PromiseLike<boolean>;
2771
+ }
2772
+ declare abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
2773
+ readonly id: string;
2774
+ readonly generateId: IdGenerator;
2775
+ protected state: ChatState<UI_MESSAGE>;
2776
+ private messageMetadataSchema;
2777
+ private dataPartSchemas;
2778
+ private readonly transport;
2779
+ private onError?;
2780
+ private onToolCall?;
2781
+ private onFinish?;
2782
+ private onData?;
2783
+ private sendAutomaticallyWhen?;
2784
+ private activeResponse;
2785
+ private jobExecutor;
2786
+ constructor({ generateId, id, transport, messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen, }: Omit<ChatInit<UI_MESSAGE>, 'messages'> & {
2787
+ state: ChatState<UI_MESSAGE>;
2788
+ });
2789
+ /**
2790
+ * Hook status:
2791
+ *
2792
+ * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
2793
+ * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
2794
+ * - `ready`: The full response has been received and processed; a new user message can be submitted.
2795
+ * - `error`: An error occurred during the API request, preventing successful completion.
2796
+ */
2797
+ get status(): ChatStatus;
2798
+ protected setStatus({ status, error, }: {
2799
+ status: ChatStatus;
2800
+ error?: Error;
2801
+ }): void;
2802
+ get error(): Error | undefined;
2803
+ get messages(): UI_MESSAGE[];
2804
+ get lastMessage(): UI_MESSAGE | undefined;
2805
+ set messages(messages: UI_MESSAGE[]);
2806
+ /**
2807
+ * Appends or replaces a user message to the chat list. This triggers the API call to fetch
2808
+ * the assistant's response.
2809
+ *
2810
+ * If a messageId is provided, the message will be replaced.
2811
+ */
2812
+ sendMessage: (message?: (CreateUIMessage<UI_MESSAGE> & {
2813
+ text?: never;
2814
+ files?: never;
2815
+ messageId?: string;
2816
+ }) | {
2817
+ text: string;
2818
+ files?: FileList | FileUIPart[];
2819
+ metadata?: InferUIMessageMetadata<UI_MESSAGE>;
2820
+ parts?: never;
2821
+ messageId?: string;
2822
+ } | {
2823
+ files: FileList | FileUIPart[];
2824
+ metadata?: InferUIMessageMetadata<UI_MESSAGE>;
2825
+ parts?: never;
2826
+ messageId?: string;
2827
+ }, options?: ChatRequestOptions) => Promise<void>;
2828
+ /**
2829
+ * Regenerate the assistant message with the provided message id.
2830
+ * If no message id is provided, the last assistant message will be regenerated.
2831
+ */
2832
+ regenerate: ({ messageId, ...options }?: {
2833
+ messageId?: string;
2834
+ } & ChatRequestOptions) => Promise<void>;
2835
+ /**
2836
+ * Attempt to resume an ongoing streaming response.
2837
+ */
2838
+ resumeStream: (options?: ChatRequestOptions) => Promise<void>;
2839
+ /**
2840
+ * Clear the error state and set the status to ready if the chat is in an error state.
2841
+ */
2842
+ clearError: () => void;
2843
+ addToolApprovalResponse: ChatAddToolApproveResponseFunction;
2844
+ addToolResult: <TOOL extends keyof InferUIMessageTools<UI_MESSAGE>>({ state, tool, toolCallId, output, errorText, }: {
2845
+ state?: "output-available";
2846
+ tool: TOOL;
2847
+ toolCallId: string;
2848
+ output: InferUIMessageTools<UI_MESSAGE>[TOOL]["output"];
2849
+ errorText?: never;
2850
+ } | {
2851
+ state: "output-error";
2852
+ tool: TOOL;
2853
+ toolCallId: string;
2854
+ output?: never;
2855
+ errorText: string;
2856
+ }) => Promise<void>;
2857
+ /**
2858
+ * Abort the current request immediately, keep the generated tokens if any.
2859
+ */
2860
+ stop: () => Promise<void>;
2861
+ private makeRequest;
2686
2862
  }
2687
2863
 
2688
- /**
2689
- Embed several values using an embedding model. The type of the value is defined
2690
- by the embedding model.
2864
+ declare function convertFileListToFileUIParts(files: FileList | undefined): Promise<Array<FileUIPart>>;
2691
2865
 
2692
- `embedMany` automatically splits large requests into smaller chunks if the model
2693
- has a limit on how many embeddings can be generated in a single call.
2866
+ /**
2867
+ Converts an array of UI messages from useChat into an array of ModelMessages that can be used
2868
+ with the AI functions (e.g. `streamText`, `generateText`).
2694
2869
 
2695
- @param model - The embedding model to use.
2696
- @param values - The values that should be embedded.
2870
+ @param messages - The UI messages to convert.
2871
+ @param options.tools - The tools to use.
2872
+ @param options.ignoreIncompleteToolCalls - Whether to ignore incomplete tool calls. Default is `false`.
2697
2873
 
2698
- @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
2699
- @param abortSignal - An optional abort signal that can be used to cancel the call.
2700
- @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
2874
+ @returns An array of ModelMessages.
2875
+ */
2876
+ declare function convertToModelMessages(messages: Array<Omit<UIMessage, 'id'>>, options?: {
2877
+ tools?: ToolSet;
2878
+ ignoreIncompleteToolCalls?: boolean;
2879
+ }): ModelMessage[];
2880
+ /**
2881
+ @deprecated Use `convertToModelMessages` instead.
2882
+ */
2883
+ declare const convertToCoreMessages: typeof convertToModelMessages;
2701
2884
 
2702
- @returns A result object that contains the embeddings, the value, and additional information.
2885
+ type PrepareSendMessagesRequest<UI_MESSAGE extends UIMessage> = (options: {
2886
+ id: string;
2887
+ messages: UI_MESSAGE[];
2888
+ requestMetadata: unknown;
2889
+ body: Record<string, any> | undefined;
2890
+ credentials: RequestCredentials | undefined;
2891
+ headers: HeadersInit | undefined;
2892
+ api: string;
2893
+ } & {
2894
+ trigger: 'submit-message' | 'regenerate-message';
2895
+ messageId: string | undefined;
2896
+ }) => {
2897
+ body: object;
2898
+ headers?: HeadersInit;
2899
+ credentials?: RequestCredentials;
2900
+ api?: string;
2901
+ } | PromiseLike<{
2902
+ body: object;
2903
+ headers?: HeadersInit;
2904
+ credentials?: RequestCredentials;
2905
+ api?: string;
2906
+ }>;
2907
+ type PrepareReconnectToStreamRequest = (options: {
2908
+ id: string;
2909
+ requestMetadata: unknown;
2910
+ body: Record<string, any> | undefined;
2911
+ credentials: RequestCredentials | undefined;
2912
+ headers: HeadersInit | undefined;
2913
+ api: string;
2914
+ }) => {
2915
+ headers?: HeadersInit;
2916
+ credentials?: RequestCredentials;
2917
+ api?: string;
2918
+ } | PromiseLike<{
2919
+ headers?: HeadersInit;
2920
+ credentials?: RequestCredentials;
2921
+ api?: string;
2922
+ }>;
2923
+ /**
2924
+ * Options for the `HttpChatTransport` class.
2925
+ *
2926
+ * @param UI_MESSAGE - The type of message to be used in the chat.
2703
2927
  */
2704
- declare function embedMany<VALUE = string>({ model: modelArg, values, maxParallelCalls, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry: telemetry, }: {
2928
+ type HttpChatTransportInitOptions<UI_MESSAGE extends UIMessage> = {
2705
2929
  /**
2706
- The embedding model to use.
2707
- */
2708
- model: EmbeddingModel<VALUE>;
2930
+ * The API URL to be used for the chat transport.
2931
+ * Defaults to '/api/chat'.
2932
+ */
2933
+ api?: string;
2709
2934
  /**
2710
- The values that should be embedded.
2935
+ * The credentials mode to be used for the fetch request.
2936
+ * Possible values are: 'omit', 'same-origin', 'include'.
2937
+ * Defaults to 'same-origin'.
2711
2938
  */
2712
- values: Array<VALUE>;
2939
+ credentials?: Resolvable<RequestCredentials>;
2713
2940
  /**
2714
- Maximum number of retries per embedding model call. Set to 0 to disable retries.
2715
-
2716
- @default 2
2941
+ * HTTP headers to be sent with the API request.
2717
2942
  */
2718
- maxRetries?: number;
2943
+ headers?: Resolvable<Record<string, string> | Headers>;
2719
2944
  /**
2720
- Abort signal.
2721
- */
2722
- abortSignal?: AbortSignal;
2945
+ * Extra body object to be sent with the API request.
2946
+ * @example
2947
+ * Send a `sessionId` to the API along with the messages.
2948
+ * ```js
2949
+ * useChat({
2950
+ * body: {
2951
+ * sessionId: '123',
2952
+ * }
2953
+ * })
2954
+ * ```
2955
+ */
2956
+ body?: Resolvable<object>;
2723
2957
  /**
2724
- Additional headers to include in the request.
2725
- Only applicable for HTTP-based providers.
2726
- */
2727
- headers?: Record<string, string>;
2958
+ Custom fetch implementation. You can use it as a middleware to intercept requests,
2959
+ or to provide a custom fetch implementation for e.g. testing.
2960
+ */
2961
+ fetch?: FetchFunction;
2728
2962
  /**
2729
- * Optional telemetry configuration (experimental).
2963
+ * When a function is provided, it will be used
2964
+ * to prepare the request body for the chat API. This can be useful for
2965
+ * customizing the request body based on the messages and data in the chat.
2966
+ *
2967
+ * @param id The id of the chat.
2968
+ * @param messages The current messages in the chat.
2969
+ * @param requestBody The request body object passed in the chat request.
2730
2970
  */
2731
- experimental_telemetry?: TelemetrySettings;
2732
- /**
2733
- Additional provider-specific options. They are passed through
2734
- to the provider from the AI SDK and enable provider-specific
2735
- functionality that can be fully encapsulated in the provider.
2736
- */
2737
- providerOptions?: ProviderOptions;
2971
+ prepareSendMessagesRequest?: PrepareSendMessagesRequest<UI_MESSAGE>;
2738
2972
  /**
2739
- * Maximum number of concurrent requests.
2973
+ * When a function is provided, it will be used
2974
+ * to prepare the request body for the chat API. This can be useful for
2975
+ * customizing the request body based on the messages and data in the chat.
2740
2976
  *
2741
- * @default Infinity
2977
+ * @param id The id of the chat.
2978
+ * @param messages The current messages in the chat.
2979
+ * @param requestBody The request body object passed in the chat request.
2742
2980
  */
2743
- maxParallelCalls?: number;
2744
- }): Promise<EmbedManyResult<VALUE>>;
2745
-
2746
- declare const symbol$d: unique symbol;
2747
- declare class InvalidArgumentError extends AISDKError {
2748
- private readonly [symbol$d];
2749
- readonly parameter: string;
2750
- readonly value: unknown;
2751
- constructor({ parameter, value, message, }: {
2752
- parameter: string;
2753
- value: unknown;
2754
- message: string;
2755
- });
2756
- static isInstance(error: unknown): error is InvalidArgumentError;
2757
- }
2758
-
2759
- type SingleRequestTextStreamPart<TOOLS extends ToolSet> = {
2760
- type: 'text-start';
2761
- providerMetadata?: ProviderMetadata;
2762
- id: string;
2763
- } | {
2764
- type: 'text-delta';
2765
- id: string;
2766
- providerMetadata?: ProviderMetadata;
2767
- delta: string;
2768
- } | {
2769
- type: 'text-end';
2770
- providerMetadata?: ProviderMetadata;
2771
- id: string;
2772
- } | {
2773
- type: 'reasoning-start';
2774
- providerMetadata?: ProviderMetadata;
2775
- id: string;
2776
- } | {
2777
- type: 'reasoning-delta';
2778
- id: string;
2779
- providerMetadata?: ProviderMetadata;
2780
- delta: string;
2781
- } | {
2782
- type: 'reasoning-end';
2783
- id: string;
2784
- providerMetadata?: ProviderMetadata;
2785
- } | {
2786
- type: 'tool-input-start';
2787
- id: string;
2788
- toolName: string;
2789
- providerMetadata?: ProviderMetadata;
2790
- dynamic?: boolean;
2791
- } | {
2792
- type: 'tool-input-delta';
2793
- id: string;
2794
- delta: string;
2795
- providerMetadata?: ProviderMetadata;
2796
- } | {
2797
- type: 'tool-input-end';
2798
- id: string;
2799
- providerMetadata?: ProviderMetadata;
2800
- } | ToolApprovalRequestOutput<TOOLS> | ({
2801
- type: 'source';
2802
- } & Source) | {
2803
- type: 'file';
2804
- file: GeneratedFile;
2805
- } | ({
2806
- type: 'tool-call';
2807
- } & TypedToolCall<TOOLS>) | ({
2808
- type: 'tool-result';
2809
- } & TypedToolResult<TOOLS>) | ({
2810
- type: 'tool-error';
2811
- } & TypedToolError<TOOLS>) | {
2812
- type: 'file';
2813
- file: GeneratedFile;
2814
- } | {
2815
- type: 'stream-start';
2816
- warnings: LanguageModelV3CallWarning[];
2817
- } | {
2818
- type: 'response-metadata';
2819
- id?: string;
2820
- timestamp?: Date;
2821
- modelId?: string;
2822
- } | {
2823
- type: 'finish';
2824
- finishReason: FinishReason;
2825
- usage: LanguageModelUsage;
2826
- providerMetadata?: ProviderMetadata;
2827
- } | {
2828
- type: 'error';
2829
- error: unknown;
2830
- } | {
2831
- type: 'raw';
2832
- rawValue: unknown;
2981
+ prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest;
2833
2982
  };
2834
-
2835
- declare const symbol$c: unique symbol;
2836
- declare class InvalidStreamPartError extends AISDKError {
2837
- private readonly [symbol$c];
2838
- readonly chunk: SingleRequestTextStreamPart<any>;
2839
- constructor({ chunk, message, }: {
2840
- chunk: SingleRequestTextStreamPart<any>;
2841
- message: string;
2842
- });
2843
- static isInstance(error: unknown): error is InvalidStreamPartError;
2983
+ declare abstract class HttpChatTransport<UI_MESSAGE extends UIMessage> implements ChatTransport<UI_MESSAGE> {
2984
+ protected api: string;
2985
+ protected credentials: HttpChatTransportInitOptions<UI_MESSAGE>['credentials'];
2986
+ protected headers: HttpChatTransportInitOptions<UI_MESSAGE>['headers'];
2987
+ protected body: HttpChatTransportInitOptions<UI_MESSAGE>['body'];
2988
+ protected fetch?: FetchFunction;
2989
+ protected prepareSendMessagesRequest?: PrepareSendMessagesRequest<UI_MESSAGE>;
2990
+ protected prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest;
2991
+ constructor({ api, credentials, headers, body, fetch, prepareSendMessagesRequest, prepareReconnectToStreamRequest, }: HttpChatTransportInitOptions<UI_MESSAGE>);
2992
+ sendMessages({ abortSignal, ...options }: Parameters<ChatTransport<UI_MESSAGE>['sendMessages']>[0]): Promise<ReadableStream<UIMessageChunk>>;
2993
+ reconnectToStream(options: Parameters<ChatTransport<UI_MESSAGE>['reconnectToStream']>[0]): Promise<ReadableStream<UIMessageChunk> | null>;
2994
+ protected abstract processResponseStream(stream: ReadableStream<Uint8Array<ArrayBufferLike>>): ReadableStream<UIMessageChunk>;
2844
2995
  }
2845
2996
 
2846
- declare const symbol$b: unique symbol;
2847
- /**
2848
- * An error occurred with the MCP client.
2849
- */
2850
- declare class MCPClientError extends AISDKError {
2851
- private readonly [symbol$b];
2852
- readonly data?: unknown;
2853
- readonly code?: number;
2854
- constructor({ name, message, cause, data, code, }: {
2855
- name?: string;
2856
- message: string;
2857
- cause?: unknown;
2858
- data?: unknown;
2859
- code?: number;
2860
- });
2861
- static isInstance(error: unknown): error is MCPClientError;
2997
+ declare class DefaultChatTransport<UI_MESSAGE extends UIMessage> extends HttpChatTransport<UI_MESSAGE> {
2998
+ constructor(options?: HttpChatTransportInitOptions<UI_MESSAGE>);
2999
+ protected processResponseStream(stream: ReadableStream<Uint8Array<ArrayBufferLike>>): ReadableStream<UIMessageChunk>;
2862
3000
  }
2863
3001
 
2864
- declare const symbol$a: unique symbol;
2865
3002
  /**
2866
- Thrown when no image could be generated. This can have multiple causes:
2867
-
2868
- - The model failed to generate a response.
2869
- - The model generated a response that could not be parsed.
3003
+ Check if the last message is an assistant message with completed tool call approvals.
3004
+ The last step of the message must have at least one tool approval response and
3005
+ all tool approvals must have a response.
2870
3006
  */
2871
- declare class NoImageGeneratedError extends AISDKError {
2872
- private readonly [symbol$a];
2873
- /**
2874
- The response metadata for each call.
2875
- */
2876
- readonly responses: Array<ImageModelResponseMetadata> | undefined;
2877
- constructor({ message, cause, responses, }: {
2878
- message?: string;
2879
- cause?: Error;
2880
- responses?: Array<ImageModelResponseMetadata>;
2881
- });
2882
- static isInstance(error: unknown): error is NoImageGeneratedError;
2883
- }
3007
+ declare function lastAssistantMessageIsCompleteWithApprovalResponses({ messages, }: {
3008
+ messages: UIMessage[];
3009
+ }): boolean;
2884
3010
 
2885
- declare const symbol$9: unique symbol;
2886
3011
  /**
2887
- Thrown when no object could be generated. This can have several causes:
2888
-
2889
- - The model failed to generate a response.
2890
- - The model generated a response that could not be parsed.
2891
- - The model generated a response that could not be validated against the schema.
3012
+ Check if the message is an assistant message with completed tool calls.
3013
+ The last step of the message must have at least one tool invocation and
3014
+ all tool invocations must have a result.
3015
+ */
3016
+ declare function lastAssistantMessageIsCompleteWithToolCalls({ messages, }: {
3017
+ messages: UIMessage[];
3018
+ }): boolean;
2892
3019
 
2893
- The error contains the following properties:
3020
+ declare class TextStreamChatTransport<UI_MESSAGE extends UIMessage> extends HttpChatTransport<UI_MESSAGE> {
3021
+ constructor(options?: HttpChatTransportInitOptions<UI_MESSAGE>);
3022
+ protected processResponseStream(stream: ReadableStream<Uint8Array<ArrayBufferLike>>): ReadableStream<UIMessageChunk>;
3023
+ }
2894
3024
 
2895
- - `text`: The text that was generated by the model. This can be the raw text or the tool call text, depending on the model.
2896
- */
2897
- declare class NoObjectGeneratedError extends AISDKError {
2898
- private readonly [symbol$9];
3025
+ type CompletionRequestOptions = {
2899
3026
  /**
2900
- The text that was generated by the model. This can be the raw text or the tool call text, depending on the model.
3027
+ An optional object of headers to be passed to the API endpoint.
2901
3028
  */
2902
- readonly text: string | undefined;
3029
+ headers?: Record<string, string> | Headers;
2903
3030
  /**
2904
- The response metadata.
3031
+ An optional object to be passed to the API endpoint.
3032
+ */
3033
+ body?: object;
3034
+ };
3035
+ type UseCompletionOptions = {
3036
+ /**
3037
+ * The API endpoint that accepts a `{ prompt: string }` object and returns
3038
+ * a stream of tokens of the AI completion response. Defaults to `/api/completion`.
2905
3039
  */
2906
- readonly response: LanguageModelResponseMetadata | undefined;
3040
+ api?: string;
2907
3041
  /**
2908
- The usage of the model.
3042
+ * An unique identifier for the chat. If not provided, a random one will be
3043
+ * generated. When provided, the `useChat` hook with the same `id` will
3044
+ * have shared states across components.
2909
3045
  */
2910
- readonly usage: LanguageModelUsage | undefined;
3046
+ id?: string;
2911
3047
  /**
2912
- Reason why the model finished generating a response.
3048
+ * Initial prompt input of the completion.
2913
3049
  */
2914
- readonly finishReason: FinishReason | undefined;
2915
- constructor({ message, cause, text, response, usage, finishReason, }: {
2916
- message?: string;
2917
- cause?: Error;
2918
- text?: string;
2919
- response: LanguageModelResponseMetadata;
2920
- usage: LanguageModelUsage;
2921
- finishReason: FinishReason;
2922
- });
2923
- static isInstance(error: unknown): error is NoObjectGeneratedError;
2924
- }
3050
+ initialInput?: string;
3051
+ /**
3052
+ * Initial completion result. Useful to load an existing history.
3053
+ */
3054
+ initialCompletion?: string;
3055
+ /**
3056
+ * Callback function to be called when the completion is finished streaming.
3057
+ */
3058
+ onFinish?: (prompt: string, completion: string) => void;
3059
+ /**
3060
+ * Callback function to be called when an error is encountered.
3061
+ */
3062
+ onError?: (error: Error) => void;
3063
+ /**
3064
+ * The credentials mode to be used for the fetch request.
3065
+ * Possible values are: 'omit', 'same-origin', 'include'.
3066
+ * Defaults to 'same-origin'.
3067
+ */
3068
+ credentials?: RequestCredentials;
3069
+ /**
3070
+ * HTTP headers to be sent with the API request.
3071
+ */
3072
+ headers?: Record<string, string> | Headers;
3073
+ /**
3074
+ * Extra body object to be sent with the API request.
3075
+ * @example
3076
+ * Send a `sessionId` to the API along with the prompt.
3077
+ * ```js
3078
+ * useChat({
3079
+ * body: {
3080
+ * sessionId: '123',
3081
+ * }
3082
+ * })
3083
+ * ```
3084
+ */
3085
+ body?: object;
3086
+ /**
3087
+ Streaming protocol that is used. Defaults to `data`.
3088
+ */
3089
+ streamProtocol?: 'data' | 'text';
3090
+ /**
3091
+ Custom fetch implementation. You can use it as a middleware to intercept requests,
3092
+ or to provide a custom fetch implementation for e.g. testing.
3093
+ */
3094
+ fetch?: FetchFunction;
3095
+ };
2925
3096
 
2926
- declare const symbol$8: unique symbol;
3097
+ type SafeValidateUIMessagesResult<UI_MESSAGE extends UIMessage> = {
3098
+ success: true;
3099
+ data: Array<UI_MESSAGE>;
3100
+ } | {
3101
+ success: false;
3102
+ error: Error;
3103
+ };
2927
3104
  /**
2928
- Thrown when no LLM output was generated, e.g. because of errors.
3105
+ * Validates a list of UI messages like `validateUIMessages`,
3106
+ * but instead of throwing it returns `{ success: true, data }`
3107
+ * or `{ success: false, error }`.
2929
3108
  */
2930
- declare class NoOutputGeneratedError extends AISDKError {
2931
- private readonly [symbol$8];
2932
- constructor({ message, cause, }?: {
2933
- message?: string;
2934
- cause?: Error;
2935
- });
2936
- static isInstance(error: unknown): error is NoOutputGeneratedError;
2937
- }
2938
-
2939
- declare const symbol$7: unique symbol;
3109
+ declare function safeValidateUIMessages<UI_MESSAGE extends UIMessage>({ messages, metadataSchema, dataSchemas, tools, }: {
3110
+ messages: unknown;
3111
+ metadataSchema?: FlexibleSchema<UIMessage['metadata']>;
3112
+ dataSchemas?: {
3113
+ [NAME in keyof InferUIMessageData<UI_MESSAGE> & string]?: FlexibleSchema<InferUIMessageData<UI_MESSAGE>[NAME]>;
3114
+ };
3115
+ tools?: {
3116
+ [NAME in keyof InferUIMessageTools<UI_MESSAGE> & string]?: Tool<InferUIMessageTools<UI_MESSAGE>[NAME]['input'], InferUIMessageTools<UI_MESSAGE>[NAME]['output']>;
3117
+ };
3118
+ }): Promise<SafeValidateUIMessagesResult<UI_MESSAGE>>;
2940
3119
  /**
2941
- Thrown when no output type is specified and output-related methods are called.
3120
+ * Validates a list of UI messages.
3121
+ *
3122
+ * Metadata, data parts, and generic tool call structures are only validated if
3123
+ * the corresponding schemas are provided. Otherwise, they are assumed to be
3124
+ * valid.
2942
3125
  */
2943
- declare class NoOutputSpecifiedError extends AISDKError {
2944
- private readonly [symbol$7];
2945
- constructor({ message }?: {
2946
- message?: string;
2947
- });
2948
- static isInstance(error: unknown): error is NoOutputSpecifiedError;
2949
- }
3126
+ declare function validateUIMessages<UI_MESSAGE extends UIMessage>({ messages, metadataSchema, dataSchemas, tools, }: {
3127
+ messages: unknown;
3128
+ metadataSchema?: FlexibleSchema<UIMessage['metadata']>;
3129
+ dataSchemas?: {
3130
+ [NAME in keyof InferUIMessageData<UI_MESSAGE> & string]?: FlexibleSchema<InferUIMessageData<UI_MESSAGE>[NAME]>;
3131
+ };
3132
+ tools?: {
3133
+ [NAME in keyof InferUIMessageTools<UI_MESSAGE> & string]?: Tool<InferUIMessageTools<UI_MESSAGE>[NAME]['input'], InferUIMessageTools<UI_MESSAGE>[NAME]['output']>;
3134
+ };
3135
+ }): Promise<Array<UI_MESSAGE>>;
2950
3136
 
2951
- /**
2952
- Error that is thrown when no speech audio was generated.
2953
- */
2954
- declare class NoSpeechGeneratedError extends AISDKError {
2955
- readonly responses: Array<SpeechModelResponseMetadata>;
2956
- constructor(options: {
2957
- responses: Array<SpeechModelResponseMetadata>;
2958
- });
3137
+ interface UIMessageStreamWriter<UI_MESSAGE extends UIMessage = UIMessage> {
3138
+ /**
3139
+ * Appends a data stream part to the stream.
3140
+ */
3141
+ write(part: InferUIMessageChunk<UI_MESSAGE>): void;
3142
+ /**
3143
+ * Merges the contents of another stream to this stream.
3144
+ */
3145
+ merge(stream: ReadableStream<InferUIMessageChunk<UI_MESSAGE>>): void;
3146
+ /**
3147
+ * Error handler that is used by the data stream writer.
3148
+ * This is intended for forwarding when merging streams
3149
+ * to prevent duplicated error masking.
3150
+ */
3151
+ onError: ErrorHandler | undefined;
2959
3152
  }
2960
3153
 
2961
- declare const symbol$6: unique symbol;
2962
- declare class ToolCallRepairError extends AISDKError {
2963
- private readonly [symbol$6];
2964
- readonly originalError: NoSuchToolError | InvalidToolInputError;
2965
- constructor({ cause, originalError, message, }: {
2966
- message?: string;
2967
- cause: unknown;
2968
- originalError: NoSuchToolError | InvalidToolInputError;
2969
- });
2970
- static isInstance(error: unknown): error is ToolCallRepairError;
2971
- }
3154
+ declare function createUIMessageStream<UI_MESSAGE extends UIMessage>({ execute, onError, originalMessages, onFinish, generateId, }: {
3155
+ execute: (options: {
3156
+ writer: UIMessageStreamWriter<UI_MESSAGE>;
3157
+ }) => Promise<void> | void;
3158
+ onError?: (error: unknown) => string;
3159
+ /**
3160
+ * The original messages. If they are provided, persistence mode is assumed,
3161
+ * and a message ID is provided for the response message.
3162
+ */
3163
+ originalMessages?: UI_MESSAGE[];
3164
+ onFinish?: UIMessageStreamOnFinishCallback<UI_MESSAGE>;
3165
+ generateId?: IdGenerator;
3166
+ }): ReadableStream<InferUIMessageChunk<UI_MESSAGE>>;
2972
3167
 
2973
- /**
2974
- Error that is thrown when a model with an unsupported version is used.
2975
- */
2976
- declare class UnsupportedModelVersionError extends AISDKError {
2977
- readonly version: string;
2978
- readonly provider: string;
2979
- readonly modelId: string;
2980
- constructor(options: {
2981
- version: string;
2982
- provider: string;
2983
- modelId: string;
2984
- });
2985
- }
3168
+ declare function createUIMessageStreamResponse({ status, statusText, headers, stream, consumeSseStream, }: UIMessageStreamResponseInit & {
3169
+ stream: ReadableStream<UIMessageChunk>;
3170
+ }): Response;
2986
3171
 
2987
- declare const symbol$5: unique symbol;
2988
- declare class InvalidDataContentError extends AISDKError {
2989
- private readonly [symbol$5];
2990
- readonly content: unknown;
2991
- constructor({ content, cause, message, }: {
2992
- content: unknown;
2993
- cause?: unknown;
2994
- message?: string;
2995
- });
2996
- static isInstance(error: unknown): error is InvalidDataContentError;
3172
+ declare class JsonToSseTransformStream extends TransformStream<unknown, string> {
3173
+ constructor();
2997
3174
  }
2998
3175
 
2999
- declare const symbol$4: unique symbol;
3000
- declare class InvalidMessageRoleError extends AISDKError {
3001
- private readonly [symbol$4];
3002
- readonly role: string;
3003
- constructor({ role, message, }: {
3004
- role: string;
3005
- message?: string;
3006
- });
3007
- static isInstance(error: unknown): error is InvalidMessageRoleError;
3008
- }
3176
+ declare function pipeUIMessageStreamToResponse({ response, status, statusText, headers, stream, consumeSseStream, }: {
3177
+ response: ServerResponse;
3178
+ stream: ReadableStream<UIMessageChunk>;
3179
+ } & UIMessageStreamResponseInit): void;
3009
3180
 
3010
- declare const symbol$3: unique symbol;
3011
- declare class MessageConversionError extends AISDKError {
3012
- private readonly [symbol$3];
3013
- readonly originalMessage: Omit<UIMessage, 'id'>;
3014
- constructor({ originalMessage, message, }: {
3015
- originalMessage: Omit<UIMessage, 'id'>;
3016
- message: string;
3017
- });
3018
- static isInstance(error: unknown): error is MessageConversionError;
3019
- }
3181
+ /**
3182
+ * Transforms a stream of `UIMessageChunk`s into an `AsyncIterableStream` of `UIMessage`s.
3183
+ *
3184
+ * @param options.message - The last assistant message to use as a starting point when the conversation is resumed. Otherwise undefined.
3185
+ * @param options.stream - The stream of `UIMessageChunk`s to read.
3186
+ * @param options.terminateOnError - Whether to terminate the stream if an error occurs.
3187
+ * @param options.onError - A function that is called when an error occurs.
3188
+ *
3189
+ * @returns An `AsyncIterableStream` of `UIMessage`s. Each stream part is a different state of the same message
3190
+ * as it is being completed.
3191
+ */
3192
+ declare function readUIMessageStream<UI_MESSAGE extends UIMessage>({ message, stream, onError, terminateOnError, }: {
3193
+ message?: UI_MESSAGE;
3194
+ stream: ReadableStream<UIMessageChunk>;
3195
+ onError?: (error: unknown) => void;
3196
+ terminateOnError?: boolean;
3197
+ }): AsyncIterableStream<UI_MESSAGE>;
3020
3198
 
3021
- declare const symbol$2: unique symbol;
3022
- declare class DownloadError extends AISDKError {
3023
- private readonly [symbol$2];
3024
- readonly url: string;
3025
- readonly statusCode?: number;
3026
- readonly statusText?: string;
3027
- constructor({ url, statusCode, statusText, cause, message, }: {
3028
- url: string;
3029
- statusCode?: number;
3030
- statusText?: string;
3031
- message?: string;
3032
- cause?: unknown;
3033
- });
3034
- static isInstance(error: unknown): error is DownloadError;
3035
- }
3199
+ declare const UI_MESSAGE_STREAM_HEADERS: {
3200
+ 'content-type': string;
3201
+ 'cache-control': string;
3202
+ connection: string;
3203
+ 'x-vercel-ai-ui-message-stream': string;
3204
+ 'x-accel-buffering': string;
3205
+ };
3036
3206
 
3037
- declare const symbol$1: unique symbol;
3038
- type RetryErrorReason = 'maxRetriesExceeded' | 'errorNotRetryable' | 'abort';
3039
- declare class RetryError extends AISDKError {
3040
- private readonly [symbol$1];
3041
- readonly reason: RetryErrorReason;
3042
- readonly lastError: unknown;
3043
- readonly errors: Array<unknown>;
3044
- constructor({ message, reason, errors, }: {
3045
- message: string;
3046
- reason: RetryErrorReason;
3047
- errors: Array<unknown>;
3048
- });
3049
- static isInstance(error: unknown): error is RetryError;
3050
- }
3207
+ /**
3208
+ * Runs the agent and stream the output as a UI message stream.
3209
+ *
3210
+ * @param agent - The agent to run.
3211
+ * @param messages - The input UI messages.
3212
+ *
3213
+ * @returns The UI message stream.
3214
+ */
3215
+ declare function createAgentUIStream<TOOLS extends ToolSet = {}, OUTPUT = never, OUTPUT_PARTIAL = never>({ agent, messages, ...uiMessageStreamOptions }: {
3216
+ agent: Agent<TOOLS, OUTPUT, OUTPUT_PARTIAL>;
3217
+ messages: unknown[];
3218
+ } & UIMessageStreamOptions<UIMessage<never, never, InferUITools<TOOLS>>>): Promise<AsyncIterableStream<InferUIMessageChunk<UIMessage<never, never, InferUITools<TOOLS>>>>>;
3051
3219
 
3052
3220
  /**
3053
- The result of a `generateImage` call.
3054
- It contains the images and additional information.
3221
+ * Pipes the agent UI message stream to a Node.js ServerResponse object.
3222
+ *
3223
+ * @param agent - The agent to run.
3224
+ * @param messages - The input UI messages.
3055
3225
  */
3056
- interface GenerateImageResult {
3057
- /**
3058
- The first image that was generated.
3059
- */
3060
- readonly image: GeneratedFile;
3226
+ declare function pipeAgentUIStreamToResponse<TOOLS extends ToolSet = {}, OUTPUT = never, OUTPUT_PARTIAL = never>({ response, headers, status, statusText, consumeSseStream, ...options }: {
3227
+ response: ServerResponse;
3228
+ agent: Agent<TOOLS, OUTPUT, OUTPUT_PARTIAL>;
3229
+ messages: unknown[];
3230
+ } & UIMessageStreamResponseInit & UIMessageStreamOptions<UIMessage<never, never, InferUITools<TOOLS>>>): Promise<void>;
3231
+
3232
+ /**
3233
+ The result of an `embed` call.
3234
+ It contains the embedding, the value, and additional information.
3235
+ */
3236
+ interface EmbedResult<VALUE> {
3061
3237
  /**
3062
- The images that were generated.
3238
+ The value that was embedded.
3063
3239
  */
3064
- readonly images: Array<GeneratedFile>;
3240
+ readonly value: VALUE;
3065
3241
  /**
3066
- Warnings for the call, e.g. unsupported settings.
3067
- */
3068
- readonly warnings: Array<ImageGenerationWarning>;
3242
+ The embedding of the value.
3243
+ */
3244
+ readonly embedding: Embedding;
3069
3245
  /**
3070
- Response metadata from the provider. There may be multiple responses if we made multiple calls to the model.
3071
- */
3072
- readonly responses: Array<ImageModelResponseMetadata>;
3246
+ The embedding token usage.
3247
+ */
3248
+ readonly usage: EmbeddingModelUsage;
3073
3249
  /**
3074
- * Provider-specific metadata. They are passed through from the provider to the AI SDK and enable provider-specific
3075
- * results that can be fully encapsulated in the provider.
3076
- */
3077
- readonly providerMetadata: ImageModelProviderMetadata;
3078
- }
3079
-
3250
+ Optional provider-specific metadata.
3251
+ */
3252
+ readonly providerMetadata?: ProviderMetadata;
3253
+ /**
3254
+ Optional response data.
3255
+ */
3256
+ readonly response?: {
3257
+ /**
3258
+ Response headers.
3259
+ */
3260
+ headers?: Record<string, string>;
3261
+ /**
3262
+ The response body.
3263
+ */
3264
+ body?: unknown;
3265
+ };
3266
+ }
3267
+
3080
3268
  /**
3081
- Generates images using an image model.
3269
+ Embed a value using an embedding model. The type of the value is defined by the embedding model.
3270
+
3271
+ @param model - The embedding model to use.
3272
+ @param value - The value that should be embedded.
3082
3273
 
3083
- @param model - The image model to use.
3084
- @param prompt - The prompt that should be used to generate the image.
3085
- @param n - Number of images to generate. Default: 1.
3086
- @param size - Size of the images to generate. Must have the format `{width}x{height}`.
3087
- @param aspectRatio - Aspect ratio of the images to generate. Must have the format `{width}:{height}`.
3088
- @param seed - Seed for the image generation.
3089
- @param providerOptions - Additional provider-specific options that are passed through to the provider
3090
- as body parameters.
3091
3274
  @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
3092
3275
  @param abortSignal - An optional abort signal that can be used to cancel the call.
3093
3276
  @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
3094
3277
 
3095
- @returns A result object that contains the generated images.
3278
+ @returns A result object that contains the embedding, the value, and additional information.
3096
3279
  */
3097
- declare function generateImage({ model, prompt, n, maxImagesPerCall, size, aspectRatio, seed, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, }: {
3280
+ declare function embed<VALUE = string>({ model: modelArg, value, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry: telemetry, }: {
3098
3281
  /**
3099
- The image model to use.
3282
+ The embedding model to use.
3100
3283
  */
3101
- model: ImageModelV3;
3102
- /**
3103
- The prompt that should be used to generate the image.
3104
- */
3105
- prompt: string;
3106
- /**
3107
- Number of images to generate.
3108
- */
3109
- n?: number;
3110
- /**
3111
- Number of images to generate.
3112
- */
3113
- maxImagesPerCall?: number;
3114
- /**
3115
- Size of the images to generate. Must have the format `{width}x{height}`. If not provided, the default size will be used.
3116
- */
3117
- size?: `${number}x${number}`;
3118
- /**
3119
- Aspect ratio of the images to generate. Must have the format `{width}:{height}`. If not provided, the default aspect ratio will be used.
3120
- */
3121
- aspectRatio?: `${number}:${number}`;
3284
+ model: EmbeddingModel<VALUE>;
3122
3285
  /**
3123
- Seed for the image generation. If not provided, the default seed will be used.
3286
+ The value that should be embedded.
3124
3287
  */
3125
- seed?: number;
3126
- /**
3127
- Additional provider-specific options that are passed through to the provider
3128
- as body parameters.
3129
-
3130
- The outer record is keyed by the provider name, and the inner
3131
- record is keyed by the provider-specific metadata key.
3132
- ```ts
3133
- {
3134
- "openai": {
3135
- "style": "vivid"
3136
- }
3137
- }
3138
- ```
3139
- */
3140
- providerOptions?: ProviderOptions;
3288
+ value: VALUE;
3141
3289
  /**
3142
3290
  Maximum number of retries per embedding model call. Set to 0 to disable retries.
3143
3291
 
@@ -3153,643 +3301,492 @@ declare function generateImage({ model, prompt, n, maxImagesPerCall, size, aspec
3153
3301
  Only applicable for HTTP-based providers.
3154
3302
  */
3155
3303
  headers?: Record<string, string>;
3156
- }): Promise<GenerateImageResult>;
3304
+ /**
3305
+ Additional provider-specific options. They are passed through
3306
+ to the provider from the AI SDK and enable provider-specific
3307
+ functionality that can be fully encapsulated in the provider.
3308
+ */
3309
+ providerOptions?: ProviderOptions;
3310
+ /**
3311
+ * Optional telemetry configuration (experimental).
3312
+ */
3313
+ experimental_telemetry?: TelemetrySettings;
3314
+ }): Promise<EmbedResult<VALUE>>;
3157
3315
 
3158
3316
  /**
3159
- The result of a `generateObject` call.
3317
+ The result of a `embedMany` call.
3318
+ It contains the embeddings, the values, and additional information.
3160
3319
  */
3161
- interface GenerateObjectResult<OBJECT> {
3320
+ interface EmbedManyResult<VALUE> {
3162
3321
  /**
3163
- The generated object (typed according to the schema).
3322
+ The values that were embedded.
3164
3323
  */
3165
- readonly object: OBJECT;
3324
+ readonly values: Array<VALUE>;
3166
3325
  /**
3167
- * The reasoning that was used to generate the object.
3168
- * Concatenated from all reasoning parts.
3169
- */
3170
- readonly reasoning: string | undefined;
3326
+ The embeddings. They are in the same order as the values.
3327
+ */
3328
+ readonly embeddings: Array<Embedding>;
3171
3329
  /**
3172
- The reason why the generation finished.
3173
- */
3174
- readonly finishReason: FinishReason;
3330
+ The embedding token usage.
3331
+ */
3332
+ readonly usage: EmbeddingModelUsage;
3175
3333
  /**
3176
- The token usage of the generated text.
3334
+ Optional provider-specific metadata.
3177
3335
  */
3178
- readonly usage: LanguageModelUsage;
3336
+ readonly providerMetadata?: ProviderMetadata;
3179
3337
  /**
3180
- Warnings from the model provider (e.g. unsupported settings).
3338
+ Optional raw response data.
3181
3339
  */
3182
- readonly warnings: CallWarning[] | undefined;
3183
- /**
3184
- Additional request information.
3185
- */
3186
- readonly request: LanguageModelRequestMetadata;
3187
- /**
3188
- Additional response information.
3189
- */
3190
- readonly response: LanguageModelResponseMetadata & {
3340
+ readonly responses?: Array<{
3191
3341
  /**
3192
- Response body (available only for providers that use HTTP requests).
3193
- */
3194
- body?: unknown;
3195
- };
3196
- /**
3197
- Additional provider-specific metadata. They are passed through
3198
- from the provider to the AI SDK and enable provider-specific
3199
- results that can be fully encapsulated in the provider.
3200
- */
3201
- readonly providerMetadata: ProviderMetadata | undefined;
3202
- /**
3203
- Converts the object to a JSON response.
3204
- The response will have a status code of 200 and a content type of `application/json; charset=utf-8`.
3342
+ Response headers.
3205
3343
  */
3206
- toJsonResponse(init?: ResponseInit): Response;
3344
+ headers?: Record<string, string>;
3345
+ /**
3346
+ The response body.
3347
+ */
3348
+ body?: unknown;
3349
+ } | undefined>;
3207
3350
  }
3208
3351
 
3209
3352
  /**
3210
- A function that attempts to repair the raw output of the model
3211
- to enable JSON parsing.
3212
-
3213
- Should return the repaired text or null if the text cannot be repaired.
3214
- */
3215
- type RepairTextFunction = (options: {
3216
- text: string;
3217
- error: JSONParseError | TypeValidationError;
3218
- }) => Promise<string | null>;
3219
-
3220
- /**
3221
- Generate a structured, typed object for a given prompt and schema using a language model.
3222
-
3223
- This function does not stream the output. If you want to stream the output, use `streamObject` instead.
3224
-
3225
- @param model - The language model to use.
3226
- @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.
3353
+ Embed several values using an embedding model. The type of the value is defined
3354
+ by the embedding model.
3227
3355
 
3228
- @param system - A system message that will be part of the prompt.
3229
- @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.
3230
- @param messages - A list of messages. You can either use `prompt` or `messages` but not both.
3356
+ `embedMany` automatically splits large requests into smaller chunks if the model
3357
+ has a limit on how many embeddings can be generated in a single call.
3231
3358
 
3232
- @param maxOutputTokens - Maximum number of tokens to generate.
3233
- @param temperature - Temperature setting.
3234
- The value is passed through to the provider. The range depends on the provider and model.
3235
- It is recommended to set either `temperature` or `topP`, but not both.
3236
- @param topP - Nucleus sampling.
3237
- The value is passed through to the provider. The range depends on the provider and model.
3238
- It is recommended to set either `temperature` or `topP`, but not both.
3239
- @param topK - Only sample from the top K options for each subsequent token.
3240
- Used to remove "long tail" low probability responses.
3241
- Recommended for advanced use cases only. You usually only need to use temperature.
3242
- @param presencePenalty - Presence penalty setting.
3243
- It affects the likelihood of the model to repeat information that is already in the prompt.
3244
- The value is passed through to the provider. The range depends on the provider and model.
3245
- @param frequencyPenalty - Frequency penalty setting.
3246
- It affects the likelihood of the model to repeatedly use the same words or phrases.
3247
- The value is passed through to the provider. The range depends on the provider and model.
3248
- @param stopSequences - Stop sequences.
3249
- If set, the model will stop generating text when one of the stop sequences is generated.
3250
- @param seed - The seed (integer) to use for random sampling.
3251
- If set and supported by the model, calls will generate deterministic results.
3359
+ @param model - The embedding model to use.
3360
+ @param values - The values that should be embedded.
3252
3361
 
3253
3362
  @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
3254
3363
  @param abortSignal - An optional abort signal that can be used to cancel the call.
3255
3364
  @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
3256
3365
 
3257
- @param schema - The schema of the object that the model should generate.
3258
- @param schemaName - Optional name of the output that should be generated.
3259
- Used by some providers for additional LLM guidance, e.g.
3260
- via tool or schema name.
3261
- @param schemaDescription - Optional description of the output that should be generated.
3262
- Used by some providers for additional LLM guidance, e.g.
3263
- via tool or schema description.
3264
-
3265
- @param output - The type of the output.
3266
-
3267
- - 'object': The output is an object.
3268
- - 'array': The output is an array.
3269
- - 'enum': The output is an enum.
3270
- - 'no-schema': The output is not a schema.
3271
-
3272
- @param experimental_repairText - A function that attempts to repair the raw output of the model
3273
- to enable JSON parsing.
3274
-
3275
- @param experimental_telemetry - Optional telemetry configuration (experimental).
3276
-
3277
- @param providerOptions - Additional provider-specific options. They are passed through
3278
- to the provider from the AI SDK and enable provider-specific
3279
- functionality that can be fully encapsulated in the provider.
3280
-
3281
- @returns
3282
- A result object that contains the generated object, the finish reason, the token usage, and additional information.
3366
+ @returns A result object that contains the embeddings, the value, and additional information.
3283
3367
  */
3284
- declare function generateObject<SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<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' ? {
3285
- /**
3286
- The enum values that the model should use.
3287
- */
3288
- enum: Array<RESULT>;
3289
- mode?: 'json';
3290
- output: 'enum';
3291
- } : OUTPUT extends 'no-schema' ? {} : {
3368
+ declare function embedMany<VALUE = string>({ model: modelArg, values, maxParallelCalls, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry: telemetry, }: {
3292
3369
  /**
3293
- The schema of the object that the model should generate.
3294
- */
3295
- schema: SCHEMA;
3370
+ The embedding model to use.
3371
+ */
3372
+ model: EmbeddingModel<VALUE>;
3296
3373
  /**
3297
- Optional name of the output that should be generated.
3298
- Used by some providers for additional LLM guidance, e.g.
3299
- via tool or schema name.
3300
- */
3301
- schemaName?: string;
3374
+ The values that should be embedded.
3375
+ */
3376
+ values: Array<VALUE>;
3302
3377
  /**
3303
- Optional description of the output that should be generated.
3304
- Used by some providers for additional LLM guidance, e.g.
3305
- via tool or schema description.
3306
- */
3307
- schemaDescription?: string;
3378
+ Maximum number of retries per embedding model call. Set to 0 to disable retries.
3379
+
3380
+ @default 2
3381
+ */
3382
+ maxRetries?: number;
3308
3383
  /**
3309
- The mode to use for object generation.
3310
-
3311
- The schema is converted into a JSON schema and used in one of the following ways
3312
-
3313
- - 'auto': The provider will choose the best mode for the model.
3314
- - 'tool': A tool with the JSON schema as parameters is provided and the provider is instructed to use it.
3315
- - 'json': The JSON schema and an instruction are injected into the prompt. If the provider supports JSON mode, it is enabled. If the provider supports JSON grammars, the grammar is used.
3316
-
3317
- Please note that most providers do not support all modes.
3318
-
3319
- Default and recommended: 'auto' (best mode for the model).
3320
- */
3321
- mode?: 'auto' | 'json' | 'tool';
3322
- }) & {
3323
- output?: OUTPUT;
3384
+ Abort signal.
3385
+ */
3386
+ abortSignal?: AbortSignal;
3324
3387
  /**
3325
- The language model to use.
3326
- */
3327
- model: LanguageModel;
3388
+ Additional headers to include in the request.
3389
+ Only applicable for HTTP-based providers.
3390
+ */
3391
+ headers?: Record<string, string>;
3328
3392
  /**
3329
- A function that attempts to repair the raw output of the model
3330
- to enable JSON parsing.
3393
+ * Optional telemetry configuration (experimental).
3331
3394
  */
3332
- experimental_repairText?: RepairTextFunction;
3333
- /**
3334
- Optional telemetry configuration (experimental).
3335
- */
3336
3395
  experimental_telemetry?: TelemetrySettings;
3337
3396
  /**
3338
- Custom download function to use for URLs.
3339
-
3340
- By default, files are downloaded if the model does not support the URL for the given media type.
3341
- */
3342
- experimental_download?: DownloadFunction | undefined;
3343
- /**
3344
- Additional provider-specific options. They are passed through
3345
- to the provider from the AI SDK and enable provider-specific
3346
- functionality that can be fully encapsulated in the provider.
3347
- */
3397
+ Additional provider-specific options. They are passed through
3398
+ to the provider from the AI SDK and enable provider-specific
3399
+ functionality that can be fully encapsulated in the provider.
3400
+ */
3348
3401
  providerOptions?: ProviderOptions;
3349
3402
  /**
3350
- * Internal. For test use only. May change without notice.
3403
+ * Maximum number of concurrent requests.
3404
+ *
3405
+ * @default Infinity
3351
3406
  */
3352
- _internal?: {
3353
- generateId?: () => string;
3354
- currentDate?: () => Date;
3355
- };
3356
- }): Promise<GenerateObjectResult<RESULT>>;
3407
+ maxParallelCalls?: number;
3408
+ }): Promise<EmbedManyResult<VALUE>>;
3357
3409
 
3358
- /**
3359
- * Consumes a ReadableStream until it's fully read.
3360
- *
3361
- * This function reads the stream chunk by chunk until the stream is exhausted.
3362
- * It doesn't process or return the data from the stream; it simply ensures
3363
- * that the entire stream is read.
3364
- *
3365
- * @param {ReadableStream} stream - The ReadableStream to be consumed.
3366
- * @returns {Promise<void>} A promise that resolves when the stream is fully consumed.
3367
- */
3368
- declare function consumeStream({ stream, onError, }: {
3369
- stream: ReadableStream;
3370
- onError?: (error: unknown) => void;
3371
- }): Promise<void>;
3410
+ declare const symbol$d: unique symbol;
3411
+ declare class InvalidArgumentError extends AISDKError {
3412
+ private readonly [symbol$d];
3413
+ readonly parameter: string;
3414
+ readonly value: unknown;
3415
+ constructor({ parameter, value, message, }: {
3416
+ parameter: string;
3417
+ value: unknown;
3418
+ message: string;
3419
+ });
3420
+ static isInstance(error: unknown): error is InvalidArgumentError;
3421
+ }
3372
3422
 
3373
- /**
3374
- * Calculates the cosine similarity between two vectors. This is a useful metric for
3375
- * comparing the similarity of two vectors such as embeddings.
3376
- *
3377
- * @param vector1 - The first vector.
3378
- * @param vector2 - The second vector.
3379
- *
3380
- * @returns The cosine similarity between vector1 and vector2.
3381
- * @returns 0 if either vector is the zero vector.
3382
- *
3383
- * @throws {InvalidArgumentError} If the vectors do not have the same length.
3384
- */
3385
- declare function cosineSimilarity(vector1: number[], vector2: number[]): number;
3423
+ type SingleRequestTextStreamPart<TOOLS extends ToolSet> = {
3424
+ type: 'text-start';
3425
+ providerMetadata?: ProviderMetadata;
3426
+ id: string;
3427
+ } | {
3428
+ type: 'text-delta';
3429
+ id: string;
3430
+ providerMetadata?: ProviderMetadata;
3431
+ delta: string;
3432
+ } | {
3433
+ type: 'text-end';
3434
+ providerMetadata?: ProviderMetadata;
3435
+ id: string;
3436
+ } | {
3437
+ type: 'reasoning-start';
3438
+ providerMetadata?: ProviderMetadata;
3439
+ id: string;
3440
+ } | {
3441
+ type: 'reasoning-delta';
3442
+ id: string;
3443
+ providerMetadata?: ProviderMetadata;
3444
+ delta: string;
3445
+ } | {
3446
+ type: 'reasoning-end';
3447
+ id: string;
3448
+ providerMetadata?: ProviderMetadata;
3449
+ } | {
3450
+ type: 'tool-input-start';
3451
+ id: string;
3452
+ toolName: string;
3453
+ providerMetadata?: ProviderMetadata;
3454
+ dynamic?: boolean;
3455
+ } | {
3456
+ type: 'tool-input-delta';
3457
+ id: string;
3458
+ delta: string;
3459
+ providerMetadata?: ProviderMetadata;
3460
+ } | {
3461
+ type: 'tool-input-end';
3462
+ id: string;
3463
+ providerMetadata?: ProviderMetadata;
3464
+ } | ToolApprovalRequestOutput<TOOLS> | ({
3465
+ type: 'source';
3466
+ } & Source) | {
3467
+ type: 'file';
3468
+ file: GeneratedFile;
3469
+ } | ({
3470
+ type: 'tool-call';
3471
+ } & TypedToolCall<TOOLS>) | ({
3472
+ type: 'tool-result';
3473
+ } & TypedToolResult<TOOLS>) | ({
3474
+ type: 'tool-error';
3475
+ } & TypedToolError<TOOLS>) | {
3476
+ type: 'file';
3477
+ file: GeneratedFile;
3478
+ } | {
3479
+ type: 'stream-start';
3480
+ warnings: LanguageModelV3CallWarning[];
3481
+ } | {
3482
+ type: 'response-metadata';
3483
+ id?: string;
3484
+ timestamp?: Date;
3485
+ modelId?: string;
3486
+ } | {
3487
+ type: 'finish';
3488
+ finishReason: FinishReason;
3489
+ usage: LanguageModelUsage;
3490
+ providerMetadata?: ProviderMetadata;
3491
+ } | {
3492
+ type: 'error';
3493
+ error: unknown;
3494
+ } | {
3495
+ type: 'raw';
3496
+ rawValue: unknown;
3497
+ };
3386
3498
 
3387
- /**
3388
- * Converts a data URL of type text/* to a text string.
3389
- */
3390
- declare function getTextFromDataUrl(dataUrl: string): string;
3499
+ declare const symbol$c: unique symbol;
3500
+ declare class InvalidStreamPartError extends AISDKError {
3501
+ private readonly [symbol$c];
3502
+ readonly chunk: SingleRequestTextStreamPart<any>;
3503
+ constructor({ chunk, message, }: {
3504
+ chunk: SingleRequestTextStreamPart<any>;
3505
+ message: string;
3506
+ });
3507
+ static isInstance(error: unknown): error is InvalidStreamPartError;
3508
+ }
3391
3509
 
3510
+ declare const symbol$b: unique symbol;
3392
3511
  /**
3393
- * Performs a deep-equal comparison of two parsed JSON objects.
3394
- *
3395
- * @param {any} obj1 - The first object to compare.
3396
- * @param {any} obj2 - The second object to compare.
3397
- * @returns {boolean} - Returns true if the two objects are deeply equal, false otherwise.
3512
+ * An error occurred with the MCP client.
3398
3513
  */
3399
- declare function isDeepEqualData(obj1: any, obj2: any): boolean;
3400
-
3401
- declare function parsePartialJson(jsonText: string | undefined): Promise<{
3402
- value: JSONValue$1 | undefined;
3403
- state: 'undefined-input' | 'successful-parse' | 'repaired-parse' | 'failed-parse';
3404
- }>;
3405
-
3406
- type Job = () => Promise<void>;
3407
-
3408
- declare class SerialJobExecutor {
3409
- private queue;
3410
- private isProcessing;
3411
- private processQueue;
3412
- run(job: Job): Promise<void>;
3514
+ declare class MCPClientError extends AISDKError {
3515
+ private readonly [symbol$b];
3516
+ readonly data?: unknown;
3517
+ readonly code?: number;
3518
+ constructor({ name, message, cause, data, code, }: {
3519
+ name?: string;
3520
+ message: string;
3521
+ cause?: unknown;
3522
+ data?: unknown;
3523
+ code?: number;
3524
+ });
3525
+ static isInstance(error: unknown): error is MCPClientError;
3413
3526
  }
3414
3527
 
3528
+ declare const symbol$a: unique symbol;
3415
3529
  /**
3416
- * Creates a ReadableStream that emits the provided values with an optional delay between each value.
3417
- *
3418
- * @param options - The configuration options
3419
- * @param options.chunks - Array of values to be emitted by the stream
3420
- * @param options.initialDelayInMs - Optional initial delay in milliseconds before emitting the first value (default: 0). Can be set to `null` to skip the initial delay. The difference between `initialDelayInMs: null` and `initialDelayInMs: 0` is that `initialDelayInMs: null` will emit the values without any delay, while `initialDelayInMs: 0` will emit the values with a delay of 0 milliseconds.
3421
- * @param options.chunkDelayInMs - Optional delay in milliseconds between emitting each value (default: 0). Can be set to `null` to skip the delay. The difference between `chunkDelayInMs: null` and `chunkDelayInMs: 0` is that `chunkDelayInMs: null` will emit the values without any delay, while `chunkDelayInMs: 0` will emit the values with a delay of 0 milliseconds.
3422
- * @returns A ReadableStream that emits the provided values
3423
- */
3424
- declare function simulateReadableStream<T>({ chunks, initialDelayInMs, chunkDelayInMs, _internal, }: {
3425
- chunks: T[];
3426
- initialDelayInMs?: number | null;
3427
- chunkDelayInMs?: number | null;
3428
- _internal?: {
3429
- delay?: (ms: number | null) => Promise<void>;
3430
- };
3431
- }): ReadableStream<T>;
3530
+ Thrown when no image could be generated. This can have multiple causes:
3432
3531
 
3433
- /**
3434
- The result of a `streamObject` call that contains the partial object stream and additional information.
3532
+ - The model failed to generate a response.
3533
+ - The model generated a response that could not be parsed.
3435
3534
  */
3436
- interface StreamObjectResult<PARTIAL, RESULT, ELEMENT_STREAM> {
3437
- /**
3438
- Warnings from the model provider (e.g. unsupported settings)
3439
- */
3440
- readonly warnings: Promise<CallWarning[] | undefined>;
3441
- /**
3442
- The token usage of the generated response. Resolved when the response is finished.
3443
- */
3444
- readonly usage: Promise<LanguageModelUsage>;
3535
+ declare class NoImageGeneratedError extends AISDKError {
3536
+ private readonly [symbol$a];
3445
3537
  /**
3446
- Additional provider-specific metadata. They are passed through
3447
- from the provider to the AI SDK and enable provider-specific
3448
- results that can be fully encapsulated in the provider.
3538
+ The response metadata for each call.
3449
3539
  */
3450
- readonly providerMetadata: Promise<ProviderMetadata | undefined>;
3451
- /**
3452
- Additional request information from the last step.
3453
- */
3454
- readonly request: Promise<LanguageModelRequestMetadata>;
3455
- /**
3456
- Additional response information.
3457
- */
3458
- readonly response: Promise<LanguageModelResponseMetadata>;
3459
- /**
3460
- The reason why the generation finished. Taken from the last step.
3461
-
3462
- Resolved when the response is finished.
3463
- */
3464
- readonly finishReason: Promise<FinishReason>;
3465
- /**
3466
- The generated object (typed according to the schema). Resolved when the response is finished.
3467
- */
3468
- readonly object: Promise<RESULT>;
3469
- /**
3470
- Stream of partial objects. It gets more complete as the stream progresses.
3471
-
3472
- Note that the partial object is not validated.
3473
- If you want to be certain that the actual content matches your schema, you need to implement your own validation for partial results.
3474
- */
3475
- readonly partialObjectStream: AsyncIterableStream<PARTIAL>;
3476
- /**
3477
- * Stream over complete array elements. Only available if the output strategy is set to `array`.
3478
- */
3479
- readonly elementStream: ELEMENT_STREAM;
3480
- /**
3481
- Text stream of the JSON representation of the generated object. It contains text chunks.
3482
- When the stream is finished, the object is valid JSON that can be parsed.
3483
- */
3484
- readonly textStream: AsyncIterableStream<string>;
3485
- /**
3486
- Stream of different types of events, including partial objects, errors, and finish events.
3487
- Only errors that stop the stream, such as network errors, are thrown.
3488
- */
3489
- readonly fullStream: AsyncIterableStream<ObjectStreamPart<PARTIAL>>;
3490
- /**
3491
- Writes text delta output to a Node.js response-like object.
3492
- It sets a `Content-Type` header to `text/plain; charset=utf-8` and
3493
- writes each text delta as a separate chunk.
3494
-
3495
- @param response A Node.js response-like object (ServerResponse).
3496
- @param init Optional headers, status code, and status text.
3497
- */
3498
- pipeTextStreamToResponse(response: ServerResponse$1, init?: ResponseInit): void;
3499
- /**
3500
- Creates a simple text stream response.
3501
- The response has a `Content-Type` header set to `text/plain; charset=utf-8`.
3502
- Each text delta is encoded as UTF-8 and sent as a separate chunk.
3503
- Non-text-delta events are ignored.
3504
-
3505
- @param init Optional headers, status code, and status text.
3506
- */
3507
- toTextStreamResponse(init?: ResponseInit): Response;
3540
+ readonly responses: Array<ImageModelResponseMetadata> | undefined;
3541
+ constructor({ message, cause, responses, }: {
3542
+ message?: string;
3543
+ cause?: Error;
3544
+ responses?: Array<ImageModelResponseMetadata>;
3545
+ });
3546
+ static isInstance(error: unknown): error is NoImageGeneratedError;
3508
3547
  }
3509
- type ObjectStreamPart<PARTIAL> = {
3510
- type: 'object';
3511
- object: PARTIAL;
3512
- } | {
3513
- type: 'text-delta';
3514
- textDelta: string;
3515
- } | {
3516
- type: 'error';
3517
- error: unknown;
3518
- } | {
3519
- type: 'finish';
3520
- finishReason: FinishReason;
3521
- usage: LanguageModelUsage;
3522
- response: LanguageModelResponseMetadata;
3523
- providerMetadata?: ProviderMetadata;
3524
- };
3525
3548
 
3549
+ declare const symbol$9: unique symbol;
3526
3550
  /**
3527
- Callback that is set using the `onError` option.
3551
+ Thrown when no object could be generated. This can have several causes:
3528
3552
 
3529
- @param event - The event that is passed to the callback.
3530
- */
3531
- type StreamObjectOnErrorCallback = (event: {
3532
- error: unknown;
3533
- }) => Promise<void> | void;
3534
- /**
3535
- Callback that is set using the `onFinish` option.
3553
+ - The model failed to generate a response.
3554
+ - The model generated a response that could not be parsed.
3555
+ - The model generated a response that could not be validated against the schema.
3536
3556
 
3537
- @param event - The event that is passed to the callback.
3557
+ The error contains the following properties:
3558
+
3559
+ - `text`: The text that was generated by the model. This can be the raw text or the tool call text, depending on the model.
3538
3560
  */
3539
- type StreamObjectOnFinishCallback<RESULT> = (event: {
3540
- /**
3541
- The token usage of the generated response.
3542
- */
3543
- usage: LanguageModelUsage;
3544
- /**
3545
- The generated object. Can be undefined if the final object does not match the schema.
3546
- */
3547
- object: RESULT | undefined;
3561
+ declare class NoObjectGeneratedError extends AISDKError {
3562
+ private readonly [symbol$9];
3548
3563
  /**
3549
- Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.
3550
- */
3551
- error: unknown | undefined;
3564
+ The text that was generated by the model. This can be the raw text or the tool call text, depending on the model.
3565
+ */
3566
+ readonly text: string | undefined;
3552
3567
  /**
3553
- Response metadata.
3554
- */
3555
- response: LanguageModelResponseMetadata;
3568
+ The response metadata.
3569
+ */
3570
+ readonly response: LanguageModelResponseMetadata | undefined;
3556
3571
  /**
3557
- Warnings from the model provider (e.g. unsupported settings).
3558
- */
3559
- warnings?: CallWarning[];
3572
+ The usage of the model.
3573
+ */
3574
+ readonly usage: LanguageModelUsage | undefined;
3560
3575
  /**
3561
- Additional provider-specific metadata. They are passed through
3562
- to the provider from the AI SDK and enable provider-specific
3563
- functionality that can be fully encapsulated in the provider.
3564
- */
3565
- providerMetadata: ProviderMetadata | undefined;
3566
- }) => Promise<void> | void;
3567
- /**
3568
- Generate a structured, typed object for a given prompt and schema using a language model.
3569
-
3570
- This function streams the output. If you do not want to stream the output, use `generateObject` instead.
3571
-
3572
- @param model - The language model to use.
3573
- @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.
3576
+ Reason why the model finished generating a response.
3577
+ */
3578
+ readonly finishReason: FinishReason | undefined;
3579
+ constructor({ message, cause, text, response, usage, finishReason, }: {
3580
+ message?: string;
3581
+ cause?: Error;
3582
+ text?: string;
3583
+ response: LanguageModelResponseMetadata;
3584
+ usage: LanguageModelUsage;
3585
+ finishReason: FinishReason;
3586
+ });
3587
+ static isInstance(error: unknown): error is NoObjectGeneratedError;
3588
+ }
3574
3589
 
3575
- @param system - A system message that will be part of the prompt.
3576
- @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.
3577
- @param messages - A list of messages. You can either use `prompt` or `messages` but not both.
3590
+ declare const symbol$8: unique symbol;
3591
+ /**
3592
+ Thrown when no LLM output was generated, e.g. because of errors.
3593
+ */
3594
+ declare class NoOutputGeneratedError extends AISDKError {
3595
+ private readonly [symbol$8];
3596
+ constructor({ message, cause, }?: {
3597
+ message?: string;
3598
+ cause?: Error;
3599
+ });
3600
+ static isInstance(error: unknown): error is NoOutputGeneratedError;
3601
+ }
3578
3602
 
3579
- @param maxOutputTokens - Maximum number of tokens to generate.
3580
- @param temperature - Temperature setting.
3581
- The value is passed through to the provider. The range depends on the provider and model.
3582
- It is recommended to set either `temperature` or `topP`, but not both.
3583
- @param topP - Nucleus sampling.
3584
- The value is passed through to the provider. The range depends on the provider and model.
3585
- It is recommended to set either `temperature` or `topP`, but not both.
3586
- @param topK - Only sample from the top K options for each subsequent token.
3587
- Used to remove "long tail" low probability responses.
3588
- Recommended for advanced use cases only. You usually only need to use temperature.
3589
- @param presencePenalty - Presence penalty setting.
3590
- It affects the likelihood of the model to repeat information that is already in the prompt.
3591
- The value is passed through to the provider. The range depends on the provider and model.
3592
- @param frequencyPenalty - Frequency penalty setting.
3593
- It affects the likelihood of the model to repeatedly use the same words or phrases.
3594
- The value is passed through to the provider. The range depends on the provider and model.
3595
- @param stopSequences - Stop sequences.
3596
- If set, the model will stop generating text when one of the stop sequences is generated.
3597
- @param seed - The seed (integer) to use for random sampling.
3598
- If set and supported by the model, calls will generate deterministic results.
3603
+ declare const symbol$7: unique symbol;
3604
+ /**
3605
+ Thrown when no output type is specified and output-related methods are called.
3606
+ */
3607
+ declare class NoOutputSpecifiedError extends AISDKError {
3608
+ private readonly [symbol$7];
3609
+ constructor({ message }?: {
3610
+ message?: string;
3611
+ });
3612
+ static isInstance(error: unknown): error is NoOutputSpecifiedError;
3613
+ }
3599
3614
 
3600
- @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
3601
- @param abortSignal - An optional abort signal that can be used to cancel the call.
3602
- @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
3615
+ /**
3616
+ Error that is thrown when no speech audio was generated.
3617
+ */
3618
+ declare class NoSpeechGeneratedError extends AISDKError {
3619
+ readonly responses: Array<SpeechModelResponseMetadata>;
3620
+ constructor(options: {
3621
+ responses: Array<SpeechModelResponseMetadata>;
3622
+ });
3623
+ }
3603
3624
 
3604
- @param schema - The schema of the object that the model should generate.
3605
- @param schemaName - Optional name of the output that should be generated.
3606
- Used by some providers for additional LLM guidance, e.g.
3607
- via tool or schema name.
3608
- @param schemaDescription - Optional description of the output that should be generated.
3609
- Used by some providers for additional LLM guidance, e.g.
3610
- via tool or schema description.
3625
+ declare const symbol$6: unique symbol;
3626
+ declare class ToolCallRepairError extends AISDKError {
3627
+ private readonly [symbol$6];
3628
+ readonly originalError: NoSuchToolError | InvalidToolInputError;
3629
+ constructor({ cause, originalError, message, }: {
3630
+ message?: string;
3631
+ cause: unknown;
3632
+ originalError: NoSuchToolError | InvalidToolInputError;
3633
+ });
3634
+ static isInstance(error: unknown): error is ToolCallRepairError;
3635
+ }
3611
3636
 
3612
- @param output - The type of the output.
3637
+ /**
3638
+ Error that is thrown when a model with an unsupported version is used.
3639
+ */
3640
+ declare class UnsupportedModelVersionError extends AISDKError {
3641
+ readonly version: string;
3642
+ readonly provider: string;
3643
+ readonly modelId: string;
3644
+ constructor(options: {
3645
+ version: string;
3646
+ provider: string;
3647
+ modelId: string;
3648
+ });
3649
+ }
3613
3650
 
3614
- - 'object': The output is an object.
3615
- - 'array': The output is an array.
3616
- - 'enum': The output is an enum.
3617
- - 'no-schema': The output is not a schema.
3651
+ declare const symbol$5: unique symbol;
3652
+ declare class InvalidDataContentError extends AISDKError {
3653
+ private readonly [symbol$5];
3654
+ readonly content: unknown;
3655
+ constructor({ content, cause, message, }: {
3656
+ content: unknown;
3657
+ cause?: unknown;
3658
+ message?: string;
3659
+ });
3660
+ static isInstance(error: unknown): error is InvalidDataContentError;
3661
+ }
3618
3662
 
3619
- @param experimental_telemetry - Optional telemetry configuration (experimental).
3620
-
3621
- @param providerOptions - Additional provider-specific options. They are passed through
3622
- to the provider from the AI SDK and enable provider-specific
3623
- functionality that can be fully encapsulated in the provider.
3624
-
3625
- @returns
3626
- A result object for accessing the partial object stream and additional information.
3627
- */
3628
- declare function streamObject<SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<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' ? {
3629
- /**
3630
- The enum values that the model should use.
3631
- */
3632
- enum: Array<RESULT>;
3633
- mode?: 'json';
3634
- output: 'enum';
3635
- } : OUTPUT extends 'no-schema' ? {} : {
3636
- /**
3637
- The schema of the object that the model should generate.
3638
- */
3639
- schema: SCHEMA;
3640
- /**
3641
- Optional name of the output that should be generated.
3642
- Used by some providers for additional LLM guidance, e.g.
3643
- via tool or schema name.
3644
- */
3645
- schemaName?: string;
3646
- /**
3647
- Optional description of the output that should be generated.
3648
- Used by some providers for additional LLM guidance, e.g.
3649
- via tool or schema description.
3650
- */
3651
- schemaDescription?: string;
3652
- /**
3653
- The mode to use for object generation.
3654
-
3655
- The schema is converted into a JSON schema and used in one of the following ways
3656
-
3657
- - 'auto': The provider will choose the best mode for the model.
3658
- - 'tool': A tool with the JSON schema as parameters is provided and the provider is instructed to use it.
3659
- - 'json': The JSON schema and an instruction are injected into the prompt. If the provider supports JSON mode, it is enabled. If the provider supports JSON grammars, the grammar is used.
3660
-
3661
- Please note that most providers do not support all modes.
3663
+ declare const symbol$4: unique symbol;
3664
+ declare class InvalidMessageRoleError extends AISDKError {
3665
+ private readonly [symbol$4];
3666
+ readonly role: string;
3667
+ constructor({ role, message, }: {
3668
+ role: string;
3669
+ message?: string;
3670
+ });
3671
+ static isInstance(error: unknown): error is InvalidMessageRoleError;
3672
+ }
3662
3673
 
3663
- Default and recommended: 'auto' (best mode for the model).
3664
- */
3665
- mode?: 'auto' | 'json' | 'tool';
3666
- }) & {
3667
- output?: OUTPUT;
3668
- /**
3669
- The language model to use.
3670
- */
3671
- model: LanguageModel;
3672
- /**
3673
- A function that attempts to repair the raw output of the model
3674
- to enable JSON parsing.
3675
- */
3676
- experimental_repairText?: RepairTextFunction;
3677
- /**
3678
- Optional telemetry configuration (experimental).
3679
- */
3680
- experimental_telemetry?: TelemetrySettings;
3681
- /**
3682
- Custom download function to use for URLs.
3674
+ declare const symbol$3: unique symbol;
3675
+ declare class MessageConversionError extends AISDKError {
3676
+ private readonly [symbol$3];
3677
+ readonly originalMessage: Omit<UIMessage, 'id'>;
3678
+ constructor({ originalMessage, message, }: {
3679
+ originalMessage: Omit<UIMessage, 'id'>;
3680
+ message: string;
3681
+ });
3682
+ static isInstance(error: unknown): error is MessageConversionError;
3683
+ }
3683
3684
 
3684
- By default, files are downloaded if the model does not support the URL for the given media type.
3685
- */
3686
- experimental_download?: DownloadFunction | undefined;
3687
- /**
3688
- Additional provider-specific options. They are passed through
3689
- to the provider from the AI SDK and enable provider-specific
3690
- functionality that can be fully encapsulated in the provider.
3691
- */
3692
- providerOptions?: ProviderOptions;
3693
- /**
3694
- Callback that is invoked when an error occurs during streaming.
3695
- You can use it to log errors.
3696
- The stream processing will pause until the callback promise is resolved.
3697
- */
3698
- onError?: StreamObjectOnErrorCallback;
3699
- /**
3700
- Callback that is called when the LLM response and the final object validation are finished.
3701
- */
3702
- onFinish?: StreamObjectOnFinishCallback<RESULT>;
3703
- /**
3704
- * Internal. For test use only. May change without notice.
3705
- */
3706
- _internal?: {
3707
- generateId?: () => string;
3708
- currentDate?: () => Date;
3709
- now?: () => number;
3710
- };
3711
- }): 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>;
3685
+ declare const symbol$2: unique symbol;
3686
+ declare class DownloadError extends AISDKError {
3687
+ private readonly [symbol$2];
3688
+ readonly url: string;
3689
+ readonly statusCode?: number;
3690
+ readonly statusText?: string;
3691
+ constructor({ url, statusCode, statusText, cause, message, }: {
3692
+ url: string;
3693
+ statusCode?: number;
3694
+ statusText?: string;
3695
+ message?: string;
3696
+ cause?: unknown;
3697
+ });
3698
+ static isInstance(error: unknown): error is DownloadError;
3699
+ }
3712
3700
 
3713
- /**
3714
- * A generated audio file.
3715
- */
3716
- interface GeneratedAudioFile extends GeneratedFile {
3717
- /**
3718
- * Audio format of the file (e.g., 'mp3', 'wav', etc.)
3719
- */
3720
- readonly format: string;
3701
+ declare const symbol$1: unique symbol;
3702
+ type RetryErrorReason = 'maxRetriesExceeded' | 'errorNotRetryable' | 'abort';
3703
+ declare class RetryError extends AISDKError {
3704
+ private readonly [symbol$1];
3705
+ readonly reason: RetryErrorReason;
3706
+ readonly lastError: unknown;
3707
+ readonly errors: Array<unknown>;
3708
+ constructor({ message, reason, errors, }: {
3709
+ message: string;
3710
+ reason: RetryErrorReason;
3711
+ errors: Array<unknown>;
3712
+ });
3713
+ static isInstance(error: unknown): error is RetryError;
3721
3714
  }
3722
3715
 
3723
3716
  /**
3724
- The result of a `generateSpeech` call.
3725
- It contains the audio data and additional information.
3717
+ The result of a `generateImage` call.
3718
+ It contains the images and additional information.
3726
3719
  */
3727
- interface SpeechResult {
3720
+ interface GenerateImageResult {
3728
3721
  /**
3729
- * The audio data as a base64 encoded string or binary data.
3722
+ The first image that was generated.
3730
3723
  */
3731
- readonly audio: GeneratedAudioFile;
3724
+ readonly image: GeneratedFile;
3732
3725
  /**
3733
- Warnings for the call, e.g. unsupported settings.
3726
+ The images that were generated.
3734
3727
  */
3735
- readonly warnings: Array<SpeechWarning>;
3728
+ readonly images: Array<GeneratedFile>;
3736
3729
  /**
3737
- Response metadata from the provider. There may be multiple responses if we made multiple calls to the model.
3730
+ Warnings for the call, e.g. unsupported settings.
3731
+ */
3732
+ readonly warnings: Array<ImageGenerationWarning>;
3733
+ /**
3734
+ Response metadata from the provider. There may be multiple responses if we made multiple calls to the model.
3738
3735
  */
3739
- readonly responses: Array<SpeechModelResponseMetadata>;
3736
+ readonly responses: Array<ImageModelResponseMetadata>;
3740
3737
  /**
3741
- Provider metadata from the provider.
3738
+ * Provider-specific metadata. They are passed through from the provider to the AI SDK and enable provider-specific
3739
+ * results that can be fully encapsulated in the provider.
3742
3740
  */
3743
- readonly providerMetadata: Record<string, Record<string, JSONValue$1>>;
3741
+ readonly providerMetadata: ImageModelProviderMetadata;
3744
3742
  }
3745
3743
 
3746
3744
  /**
3747
- Generates speech audio using a speech model.
3745
+ Generates images using an image model.
3748
3746
 
3749
- @param model - The speech model to use.
3750
- @param text - The text to convert to speech.
3751
- @param voice - The voice to use for speech generation.
3752
- @param outputFormat - The output format to use for speech generation e.g. "mp3", "wav", etc.
3753
- @param instructions - Instructions for the speech generation e.g. "Speak in a slow and steady tone".
3754
- @param speed - The speed of the speech generation.
3747
+ @param model - The image model to use.
3748
+ @param prompt - The prompt that should be used to generate the image.
3749
+ @param n - Number of images to generate. Default: 1.
3750
+ @param size - Size of the images to generate. Must have the format `{width}x{height}`.
3751
+ @param aspectRatio - Aspect ratio of the images to generate. Must have the format `{width}:{height}`.
3752
+ @param seed - Seed for the image generation.
3755
3753
  @param providerOptions - Additional provider-specific options that are passed through to the provider
3756
3754
  as body parameters.
3757
3755
  @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
3758
3756
  @param abortSignal - An optional abort signal that can be used to cancel the call.
3759
3757
  @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
3760
3758
 
3761
- @returns A result object that contains the generated audio data.
3759
+ @returns A result object that contains the generated images.
3762
3760
  */
3763
- declare function generateSpeech({ model, text, voice, outputFormat, instructions, speed, language, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, }: {
3761
+ declare function generateImage({ model, prompt, n, maxImagesPerCall, size, aspectRatio, seed, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, }: {
3764
3762
  /**
3765
- The speech model to use.
3763
+ The image model to use.
3766
3764
  */
3767
- model: SpeechModel;
3765
+ model: ImageModelV3;
3768
3766
  /**
3769
- The text to convert to speech.
3767
+ The prompt that should be used to generate the image.
3770
3768
  */
3771
- text: string;
3769
+ prompt: string;
3772
3770
  /**
3773
- The voice to use for speech generation.
3771
+ Number of images to generate.
3774
3772
  */
3775
- voice?: string;
3773
+ n?: number;
3776
3774
  /**
3777
- * The desired output format for the audio e.g. "mp3", "wav", etc.
3775
+ Number of images to generate.
3778
3776
  */
3779
- outputFormat?: 'mp3' | 'wav' | (string & {});
3777
+ maxImagesPerCall?: number;
3780
3778
  /**
3781
- Instructions for the speech generation e.g. "Speak in a slow and steady tone".
3782
- */
3783
- instructions?: string;
3779
+ Size of the images to generate. Must have the format `{width}x{height}`. If not provided, the default size will be used.
3780
+ */
3781
+ size?: `${number}x${number}`;
3784
3782
  /**
3785
- The speed of the speech generation.
3783
+ Aspect ratio of the images to generate. Must have the format `{width}:{height}`. If not provided, the default aspect ratio will be used.
3786
3784
  */
3787
- speed?: number;
3785
+ aspectRatio?: `${number}:${number}`;
3788
3786
  /**
3789
- The language for speech generation. This should be an ISO 639-1 language code (e.g. "en", "es", "fr")
3790
- or "auto" for automatic language detection. Provider support varies.
3787
+ Seed for the image generation. If not provided, the default seed will be used.
3791
3788
  */
3792
- language?: string;
3789
+ seed?: number;
3793
3790
  /**
3794
3791
  Additional provider-specific options that are passed through to the provider
3795
3792
  as body parameters.
@@ -3798,13 +3795,15 @@ declare function generateSpeech({ model, text, voice, outputFormat, instructions
3798
3795
  record is keyed by the provider-specific metadata key.
3799
3796
  ```ts
3800
3797
  {
3801
- "openai": {}
3798
+ "openai": {
3799
+ "style": "vivid"
3800
+ }
3802
3801
  }
3803
3802
  ```
3804
3803
  */
3805
3804
  providerOptions?: ProviderOptions;
3806
3805
  /**
3807
- Maximum number of retries per speech model call. Set to 0 to disable retries.
3806
+ Maximum number of retries per embedding model call. Set to 0 to disable retries.
3808
3807
 
3809
3808
  @default 2
3810
3809
  */
@@ -3818,1086 +3817,1111 @@ declare function generateSpeech({ model, text, voice, outputFormat, instructions
3818
3817
  Only applicable for HTTP-based providers.
3819
3818
  */
3820
3819
  headers?: Record<string, string>;
3821
- }): Promise<SpeechResult>;
3822
-
3823
- type Warning = LanguageModelV3CallWarning | ImageModelV3CallWarning | SpeechModelV3CallWarning | TranscriptionModelV3CallWarning;
3824
- type LogWarningsFunction = (warnings: Warning[]) => void;
3820
+ }): Promise<GenerateImageResult>;
3825
3821
 
3826
3822
  /**
3827
- * Applies default settings for a language model.
3823
+ The result of a `generateObject` call.
3828
3824
  */
3829
- declare function defaultSettingsMiddleware({ settings, }: {
3830
- settings: Partial<{
3831
- maxOutputTokens?: LanguageModelV3CallOptions['maxOutputTokens'];
3832
- temperature?: LanguageModelV3CallOptions['temperature'];
3833
- stopSequences?: LanguageModelV3CallOptions['stopSequences'];
3834
- topP?: LanguageModelV3CallOptions['topP'];
3835
- topK?: LanguageModelV3CallOptions['topK'];
3836
- presencePenalty?: LanguageModelV3CallOptions['presencePenalty'];
3837
- frequencyPenalty?: LanguageModelV3CallOptions['frequencyPenalty'];
3838
- responseFormat?: LanguageModelV3CallOptions['responseFormat'];
3839
- seed?: LanguageModelV3CallOptions['seed'];
3840
- tools?: LanguageModelV3CallOptions['tools'];
3841
- toolChoice?: LanguageModelV3CallOptions['toolChoice'];
3842
- headers?: LanguageModelV3CallOptions['headers'];
3843
- providerOptions?: LanguageModelV3CallOptions['providerOptions'];
3844
- }>;
3845
- }): LanguageModelMiddleware;
3846
-
3847
- /**
3848
- * Extract an XML-tagged reasoning section from the generated text and exposes it
3849
- * as a `reasoning` property on the result.
3850
- *
3851
- * @param tagName - The name of the XML tag to extract reasoning from.
3852
- * @param separator - The separator to use between reasoning and text sections.
3853
- * @param startWithReasoning - Whether to start with reasoning tokens.
3854
- */
3855
- declare function extractReasoningMiddleware({ tagName, separator, startWithReasoning, }: {
3856
- tagName: string;
3857
- separator?: string;
3858
- startWithReasoning?: boolean;
3859
- }): LanguageModelMiddleware;
3825
+ interface GenerateObjectResult<OBJECT> {
3826
+ /**
3827
+ The generated object (typed according to the schema).
3828
+ */
3829
+ readonly object: OBJECT;
3830
+ /**
3831
+ * The reasoning that was used to generate the object.
3832
+ * Concatenated from all reasoning parts.
3833
+ */
3834
+ readonly reasoning: string | undefined;
3835
+ /**
3836
+ The reason why the generation finished.
3837
+ */
3838
+ readonly finishReason: FinishReason;
3839
+ /**
3840
+ The token usage of the generated text.
3841
+ */
3842
+ readonly usage: LanguageModelUsage;
3843
+ /**
3844
+ Warnings from the model provider (e.g. unsupported settings).
3845
+ */
3846
+ readonly warnings: CallWarning[] | undefined;
3847
+ /**
3848
+ Additional request information.
3849
+ */
3850
+ readonly request: LanguageModelRequestMetadata;
3851
+ /**
3852
+ Additional response information.
3853
+ */
3854
+ readonly response: LanguageModelResponseMetadata & {
3855
+ /**
3856
+ Response body (available only for providers that use HTTP requests).
3857
+ */
3858
+ body?: unknown;
3859
+ };
3860
+ /**
3861
+ Additional provider-specific metadata. They are passed through
3862
+ from the provider to the AI SDK and enable provider-specific
3863
+ results that can be fully encapsulated in the provider.
3864
+ */
3865
+ readonly providerMetadata: ProviderMetadata | undefined;
3866
+ /**
3867
+ Converts the object to a JSON response.
3868
+ The response will have a status code of 200 and a content type of `application/json; charset=utf-8`.
3869
+ */
3870
+ toJsonResponse(init?: ResponseInit): Response;
3871
+ }
3860
3872
 
3861
3873
  /**
3862
- * Simulates streaming chunks with the response from a generate call.
3874
+ A function that attempts to repair the raw output of the model
3875
+ to enable JSON parsing.
3876
+
3877
+ Should return the repaired text or null if the text cannot be repaired.
3878
+ */
3879
+ type RepairTextFunction = (options: {
3880
+ text: string;
3881
+ error: JSONParseError | TypeValidationError;
3882
+ }) => Promise<string | null>;
3883
+
3884
+ /**
3885
+ Generate a structured, typed object for a given prompt and schema using a language model.
3886
+
3887
+ This function does not stream the output. If you want to stream the output, use `streamObject` instead.
3888
+
3889
+ @param model - The language model to use.
3890
+ @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.
3891
+
3892
+ @param system - A system message that will be part of the prompt.
3893
+ @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.
3894
+ @param messages - A list of messages. You can either use `prompt` or `messages` but not both.
3895
+
3896
+ @param maxOutputTokens - Maximum number of tokens to generate.
3897
+ @param temperature - Temperature setting.
3898
+ The value is passed through to the provider. The range depends on the provider and model.
3899
+ It is recommended to set either `temperature` or `topP`, but not both.
3900
+ @param topP - Nucleus sampling.
3901
+ The value is passed through to the provider. The range depends on the provider and model.
3902
+ It is recommended to set either `temperature` or `topP`, but not both.
3903
+ @param topK - Only sample from the top K options for each subsequent token.
3904
+ Used to remove "long tail" low probability responses.
3905
+ Recommended for advanced use cases only. You usually only need to use temperature.
3906
+ @param presencePenalty - Presence penalty setting.
3907
+ It affects the likelihood of the model to repeat information that is already in the prompt.
3908
+ The value is passed through to the provider. The range depends on the provider and model.
3909
+ @param frequencyPenalty - Frequency penalty setting.
3910
+ It affects the likelihood of the model to repeatedly use the same words or phrases.
3911
+ The value is passed through to the provider. The range depends on the provider and model.
3912
+ @param stopSequences - Stop sequences.
3913
+ If set, the model will stop generating text when one of the stop sequences is generated.
3914
+ @param seed - The seed (integer) to use for random sampling.
3915
+ If set and supported by the model, calls will generate deterministic results.
3916
+
3917
+ @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
3918
+ @param abortSignal - An optional abort signal that can be used to cancel the call.
3919
+ @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
3920
+
3921
+ @param schema - The schema of the object that the model should generate.
3922
+ @param schemaName - Optional name of the output that should be generated.
3923
+ Used by some providers for additional LLM guidance, e.g.
3924
+ via tool or schema name.
3925
+ @param schemaDescription - Optional description of the output that should be generated.
3926
+ Used by some providers for additional LLM guidance, e.g.
3927
+ via tool or schema description.
3928
+
3929
+ @param output - The type of the output.
3930
+
3931
+ - 'object': The output is an object.
3932
+ - 'array': The output is an array.
3933
+ - 'enum': The output is an enum.
3934
+ - 'no-schema': The output is not a schema.
3935
+
3936
+ @param experimental_repairText - A function that attempts to repair the raw output of the model
3937
+ to enable JSON parsing.
3938
+
3939
+ @param experimental_telemetry - Optional telemetry configuration (experimental).
3940
+
3941
+ @param providerOptions - Additional provider-specific options. They are passed through
3942
+ to the provider from the AI SDK and enable provider-specific
3943
+ functionality that can be fully encapsulated in the provider.
3944
+
3945
+ @returns
3946
+ A result object that contains the generated object, the finish reason, the token usage, and additional information.
3863
3947
  */
3864
- declare function simulateStreamingMiddleware(): LanguageModelMiddleware;
3948
+ declare function generateObject<SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<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' ? {
3949
+ /**
3950
+ The enum values that the model should use.
3951
+ */
3952
+ enum: Array<RESULT>;
3953
+ mode?: 'json';
3954
+ output: 'enum';
3955
+ } : OUTPUT extends 'no-schema' ? {} : {
3956
+ /**
3957
+ The schema of the object that the model should generate.
3958
+ */
3959
+ schema: SCHEMA;
3960
+ /**
3961
+ Optional name of the output that should be generated.
3962
+ Used by some providers for additional LLM guidance, e.g.
3963
+ via tool or schema name.
3964
+ */
3965
+ schemaName?: string;
3966
+ /**
3967
+ Optional description of the output that should be generated.
3968
+ Used by some providers for additional LLM guidance, e.g.
3969
+ via tool or schema description.
3970
+ */
3971
+ schemaDescription?: string;
3972
+ /**
3973
+ The mode to use for object generation.
3974
+
3975
+ The schema is converted into a JSON schema and used in one of the following ways
3976
+
3977
+ - 'auto': The provider will choose the best mode for the model.
3978
+ - 'tool': A tool with the JSON schema as parameters is provided and the provider is instructed to use it.
3979
+ - 'json': The JSON schema and an instruction are injected into the prompt. If the provider supports JSON mode, it is enabled. If the provider supports JSON grammars, the grammar is used.
3980
+
3981
+ Please note that most providers do not support all modes.
3982
+
3983
+ Default and recommended: 'auto' (best mode for the model).
3984
+ */
3985
+ mode?: 'auto' | 'json' | 'tool';
3986
+ }) & {
3987
+ output?: OUTPUT;
3988
+ /**
3989
+ The language model to use.
3990
+ */
3991
+ model: LanguageModel;
3992
+ /**
3993
+ A function that attempts to repair the raw output of the model
3994
+ to enable JSON parsing.
3995
+ */
3996
+ experimental_repairText?: RepairTextFunction;
3997
+ /**
3998
+ Optional telemetry configuration (experimental).
3999
+ */
4000
+ experimental_telemetry?: TelemetrySettings;
4001
+ /**
4002
+ Custom download function to use for URLs.
4003
+
4004
+ By default, files are downloaded if the model does not support the URL for the given media type.
4005
+ */
4006
+ experimental_download?: DownloadFunction | undefined;
4007
+ /**
4008
+ Additional provider-specific options. They are passed through
4009
+ to the provider from the AI SDK and enable provider-specific
4010
+ functionality that can be fully encapsulated in the provider.
4011
+ */
4012
+ providerOptions?: ProviderOptions;
4013
+ /**
4014
+ * Internal. For test use only. May change without notice.
4015
+ */
4016
+ _internal?: {
4017
+ generateId?: () => string;
4018
+ currentDate?: () => Date;
4019
+ };
4020
+ }): Promise<GenerateObjectResult<RESULT>>;
3865
4021
 
3866
4022
  /**
3867
- * Wraps a LanguageModelV3 instance with middleware functionality.
3868
- * This function allows you to apply middleware to transform parameters,
3869
- * wrap generate operations, and wrap stream operations of a language model.
4023
+ * Consumes a ReadableStream until it's fully read.
3870
4024
  *
3871
- * @param options - Configuration options for wrapping the language model.
3872
- * @param options.model - The original LanguageModelV3 instance to be wrapped.
3873
- * @param options.middleware - The middleware to be applied to the language model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.
3874
- * @param options.modelId - Optional custom model ID to override the original model's ID.
3875
- * @param options.providerId - Optional custom provider ID to override the original model's provider ID.
3876
- * @returns A new LanguageModelV3 instance with middleware applied.
4025
+ * This function reads the stream chunk by chunk until the stream is exhausted.
4026
+ * It doesn't process or return the data from the stream; it simply ensures
4027
+ * that the entire stream is read.
4028
+ *
4029
+ * @param {ReadableStream} stream - The ReadableStream to be consumed.
4030
+ * @returns {Promise<void>} A promise that resolves when the stream is fully consumed.
3877
4031
  */
3878
- declare const wrapLanguageModel: ({ model, middleware: middlewareArg, modelId, providerId, }: {
3879
- model: LanguageModelV3;
3880
- middleware: LanguageModelMiddleware | LanguageModelMiddleware[];
3881
- modelId?: string;
3882
- providerId?: string;
3883
- }) => LanguageModelV3;
4032
+ declare function consumeStream({ stream, onError, }: {
4033
+ stream: ReadableStream;
4034
+ onError?: (error: unknown) => void;
4035
+ }): Promise<void>;
3884
4036
 
3885
4037
  /**
3886
- * Wraps a ProviderV3 instance with middleware functionality.
3887
- * This function allows you to apply middleware to all language models
3888
- * from the provider, enabling you to transform parameters, wrap generate
3889
- * operations, and wrap stream operations for every language model.
4038
+ * Calculates the cosine similarity between two vectors. This is a useful metric for
4039
+ * comparing the similarity of two vectors such as embeddings.
3890
4040
  *
3891
- * @param options - Configuration options for wrapping the provider.
3892
- * @param options.provider - The original ProviderV3 instance to be wrapped.
3893
- * @param options.languageModelMiddleware - The middleware to be applied to all language models from the provider. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.
3894
- * @returns A new ProviderV3 instance with middleware applied to all language models.
4041
+ * @param vector1 - The first vector.
4042
+ * @param vector2 - The second vector.
4043
+ *
4044
+ * @returns The cosine similarity between vector1 and vector2.
4045
+ * @returns 0 if either vector is the zero vector.
4046
+ *
4047
+ * @throws {InvalidArgumentError} If the vectors do not have the same length.
3895
4048
  */
3896
- declare function wrapProvider({ provider, languageModelMiddleware, }: {
3897
- provider: ProviderV3 | ProviderV2;
3898
- languageModelMiddleware: LanguageModelMiddleware | LanguageModelMiddleware[];
3899
- }): ProviderV3;
4049
+ declare function cosineSimilarity(vector1: number[], vector2: number[]): number;
3900
4050
 
3901
4051
  /**
3902
- * Creates a custom provider with specified language models, text embedding models, image models, transcription models, speech models, and an optional fallback provider.
3903
- *
3904
- * @param {Object} options - The options for creating the custom provider.
3905
- * @param {Record<string, LanguageModel>} [options.languageModels] - A record of language models, where keys are model IDs and values are LanguageModel instances.
3906
- * @param {Record<string, EmbeddingModel<string>>} [options.textEmbeddingModels] - A record of text embedding models, where keys are model IDs and values are EmbeddingModel<string> instances.
3907
- * @param {Record<string, ImageModel>} [options.imageModels] - A record of image models, where keys are model IDs and values are ImageModel instances.
3908
- * @param {Record<string, TranscriptionModel>} [options.transcriptionModels] - A record of transcription models, where keys are model IDs and values are TranscriptionModel instances.
3909
- * @param {Record<string, SpeechModel>} [options.speechModels] - A record of speech models, where keys are model IDs and values are SpeechModel instances.
3910
- * @param {Provider} [options.fallbackProvider] - An optional fallback provider to use when a requested model is not found in the custom provider.
3911
- * @returns {Provider} A Provider object with languageModel, textEmbeddingModel, imageModel, transcriptionModel, and speechModel methods.
3912
- *
3913
- * @throws {NoSuchModelError} Throws when a requested model is not found and no fallback provider is available.
4052
+ * Converts a data URL of type text/* to a text string.
3914
4053
  */
3915
- declare function customProvider<LANGUAGE_MODELS extends Record<string, LanguageModelV3>, EMBEDDING_MODELS extends Record<string, EmbeddingModelV3<string>>, IMAGE_MODELS extends Record<string, ImageModelV3>, TRANSCRIPTION_MODELS extends Record<string, TranscriptionModelV3>, SPEECH_MODELS extends Record<string, SpeechModelV3>>({ languageModels, textEmbeddingModels, imageModels, transcriptionModels, speechModels, fallbackProvider, }: {
3916
- languageModels?: LANGUAGE_MODELS;
3917
- textEmbeddingModels?: EMBEDDING_MODELS;
3918
- imageModels?: IMAGE_MODELS;
3919
- transcriptionModels?: TRANSCRIPTION_MODELS;
3920
- speechModels?: SPEECH_MODELS;
3921
- fallbackProvider?: ProviderV3 | ProviderV2;
3922
- }): ProviderV3 & {
3923
- languageModel(modelId: ExtractModelId<LANGUAGE_MODELS>): LanguageModelV3;
3924
- textEmbeddingModel(modelId: ExtractModelId<EMBEDDING_MODELS>): EmbeddingModelV3<string>;
3925
- imageModel(modelId: ExtractModelId<IMAGE_MODELS>): ImageModelV3;
3926
- transcriptionModel(modelId: ExtractModelId<TRANSCRIPTION_MODELS>): TranscriptionModelV3;
3927
- speechModel(modelId: ExtractModelId<SPEECH_MODELS>): SpeechModelV3;
3928
- };
4054
+ declare function getTextFromDataUrl(dataUrl: string): string;
4055
+
3929
4056
  /**
3930
- * @deprecated Use `customProvider` instead.
4057
+ * Performs a deep-equal comparison of two parsed JSON objects.
4058
+ *
4059
+ * @param {any} obj1 - The first object to compare.
4060
+ * @param {any} obj2 - The second object to compare.
4061
+ * @returns {boolean} - Returns true if the two objects are deeply equal, false otherwise.
3931
4062
  */
3932
- declare const experimental_customProvider: typeof customProvider;
3933
- type ExtractModelId<MODELS extends Record<string, unknown>> = Extract<keyof MODELS, string>;
4063
+ declare function isDeepEqualData(obj1: any, obj2: any): boolean;
3934
4064
 
3935
- declare const symbol: unique symbol;
3936
- declare class NoSuchProviderError extends NoSuchModelError {
3937
- private readonly [symbol];
3938
- readonly providerId: string;
3939
- readonly availableProviders: string[];
3940
- constructor({ modelId, modelType, providerId, availableProviders, message, }: {
3941
- modelId: string;
3942
- modelType: 'languageModel' | 'textEmbeddingModel' | 'imageModel' | 'transcriptionModel' | 'speechModel';
3943
- providerId: string;
3944
- availableProviders: string[];
3945
- message?: string;
3946
- });
3947
- static isInstance(error: unknown): error is NoSuchProviderError;
3948
- }
4065
+ declare function parsePartialJson(jsonText: string | undefined): Promise<{
4066
+ value: JSONValue$1 | undefined;
4067
+ state: 'undefined-input' | 'successful-parse' | 'repaired-parse' | 'failed-parse';
4068
+ }>;
3949
4069
 
3950
- type ExtractLiteralUnion<T> = T extends string ? string extends T ? never : T : never;
3951
- interface ProviderRegistryProvider<PROVIDERS extends Record<string, ProviderV3> = Record<string, ProviderV3>, SEPARATOR extends string = ':'> {
3952
- languageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['languageModel']>>[0]>}` : never): LanguageModelV3;
3953
- languageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): LanguageModelV3;
3954
- textEmbeddingModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['textEmbeddingModel']>>[0]>}` : never): EmbeddingModelV3<string>;
3955
- textEmbeddingModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): EmbeddingModelV3<string>;
3956
- imageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['imageModel']>>[0]>}` : never): ImageModelV3;
3957
- imageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): ImageModelV3;
3958
- transcriptionModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['transcriptionModel']>>[0]>}` : never): TranscriptionModelV3;
3959
- transcriptionModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): TranscriptionModelV3;
3960
- speechModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['speechModel']>>[0]>}` : never): SpeechModelV3;
3961
- speechModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): SpeechModelV3;
4070
+ type Job = () => Promise<void>;
4071
+
4072
+ declare class SerialJobExecutor {
4073
+ private queue;
4074
+ private isProcessing;
4075
+ private processQueue;
4076
+ run(job: Job): Promise<void>;
3962
4077
  }
4078
+
3963
4079
  /**
3964
- * Creates a registry for the given providers with optional middleware functionality.
3965
- * This function allows you to register multiple providers and optionally apply middleware
3966
- * to all language models from the registry, enabling you to transform parameters, wrap generate
3967
- * operations, and wrap stream operations for every language model accessed through the registry.
4080
+ * Creates a ReadableStream that emits the provided values with an optional delay between each value.
3968
4081
  *
3969
- * @param providers - A record of provider instances to be registered in the registry.
3970
- * @param options - Configuration options for the provider registry.
3971
- * @param options.separator - The separator used between provider ID and model ID in the combined identifier. Defaults to ':'.
3972
- * @param options.languageModelMiddleware - Optional middleware to be applied to all language models from the registry. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.
3973
- * @returns A new ProviderRegistryProvider instance that provides access to all registered providers with optional middleware applied to language models.
3974
- */
3975
- declare function createProviderRegistry<PROVIDERS extends Record<string, ProviderV3>, SEPARATOR extends string = ':'>(providers: PROVIDERS, { separator, languageModelMiddleware, }?: {
3976
- separator?: SEPARATOR;
3977
- languageModelMiddleware?: LanguageModelMiddleware | LanguageModelMiddleware[];
3978
- }): ProviderRegistryProvider<PROVIDERS, SEPARATOR>;
3979
- /**
3980
- * @deprecated Use `createProviderRegistry` instead.
4082
+ * @param options - The configuration options
4083
+ * @param options.chunks - Array of values to be emitted by the stream
4084
+ * @param options.initialDelayInMs - Optional initial delay in milliseconds before emitting the first value (default: 0). Can be set to `null` to skip the initial delay. The difference between `initialDelayInMs: null` and `initialDelayInMs: 0` is that `initialDelayInMs: null` will emit the values without any delay, while `initialDelayInMs: 0` will emit the values with a delay of 0 milliseconds.
4085
+ * @param options.chunkDelayInMs - Optional delay in milliseconds between emitting each value (default: 0). Can be set to `null` to skip the delay. The difference between `chunkDelayInMs: null` and `chunkDelayInMs: 0` is that `chunkDelayInMs: null` will emit the values without any delay, while `chunkDelayInMs: 0` will emit the values with a delay of 0 milliseconds.
4086
+ * @returns A ReadableStream that emits the provided values
3981
4087
  */
3982
- declare const experimental_createProviderRegistry: typeof createProviderRegistry;
3983
-
3984
- declare function createTextStreamResponse({ status, statusText, headers, textStream, }: ResponseInit & {
3985
- textStream: ReadableStream<string>;
3986
- }): Response;
3987
-
3988
- declare function pipeTextStreamToResponse({ response, status, statusText, headers, textStream, }: {
3989
- response: ServerResponse;
3990
- textStream: ReadableStream<string>;
3991
- } & ResponseInit): void;
3992
-
3993
- declare const JSONRPCRequestSchema: z.ZodObject<{
3994
- jsonrpc: z.ZodLiteral<"2.0">;
3995
- id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
3996
- method: z.ZodString;
3997
- params: z.ZodOptional<z.ZodObject<{
3998
- _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
3999
- }, z.core.$loose>>;
4000
- }, z.core.$strict>;
4001
- type JSONRPCRequest = z.infer<typeof JSONRPCRequestSchema>;
4002
- declare const JSONRPCResponseSchema: z.ZodObject<{
4003
- jsonrpc: z.ZodLiteral<"2.0">;
4004
- id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
4005
- result: z.ZodObject<{
4006
- _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4007
- }, z.core.$loose>;
4008
- }, z.core.$strict>;
4009
- type JSONRPCResponse = z.infer<typeof JSONRPCResponseSchema>;
4010
- declare const JSONRPCErrorSchema: z.ZodObject<{
4011
- jsonrpc: z.ZodLiteral<"2.0">;
4012
- id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
4013
- error: z.ZodObject<{
4014
- code: z.ZodNumber;
4015
- message: z.ZodString;
4016
- data: z.ZodOptional<z.ZodUnknown>;
4017
- }, z.core.$strip>;
4018
- }, z.core.$strict>;
4019
- type JSONRPCError = z.infer<typeof JSONRPCErrorSchema>;
4020
- declare const JSONRPCNotificationSchema: z.ZodObject<{
4021
- jsonrpc: z.ZodLiteral<"2.0">;
4022
- method: z.ZodString;
4023
- params: z.ZodOptional<z.ZodObject<{
4024
- _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4025
- }, z.core.$loose>>;
4026
- }, z.core.$strict>;
4027
- type JSONRPCNotification = z.infer<typeof JSONRPCNotificationSchema>;
4028
- declare const JSONRPCMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
4029
- jsonrpc: z.ZodLiteral<"2.0">;
4030
- id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
4031
- method: z.ZodString;
4032
- params: z.ZodOptional<z.ZodObject<{
4033
- _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4034
- }, z.core.$loose>>;
4035
- }, z.core.$strict>, z.ZodObject<{
4036
- jsonrpc: z.ZodLiteral<"2.0">;
4037
- method: z.ZodString;
4038
- params: z.ZodOptional<z.ZodObject<{
4039
- _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4040
- }, z.core.$loose>>;
4041
- }, z.core.$strict>, z.ZodObject<{
4042
- jsonrpc: z.ZodLiteral<"2.0">;
4043
- id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
4044
- result: z.ZodObject<{
4045
- _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4046
- }, z.core.$loose>;
4047
- }, z.core.$strict>, z.ZodObject<{
4048
- jsonrpc: z.ZodLiteral<"2.0">;
4049
- id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
4050
- error: z.ZodObject<{
4051
- code: z.ZodNumber;
4052
- message: z.ZodString;
4053
- data: z.ZodOptional<z.ZodUnknown>;
4054
- }, z.core.$strip>;
4055
- }, z.core.$strict>]>;
4056
- type JSONRPCMessage = z.infer<typeof JSONRPCMessageSchema>;
4088
+ declare function simulateReadableStream<T>({ chunks, initialDelayInMs, chunkDelayInMs, _internal, }: {
4089
+ chunks: T[];
4090
+ initialDelayInMs?: number | null;
4091
+ chunkDelayInMs?: number | null;
4092
+ _internal?: {
4093
+ delay?: (ms: number | null) => Promise<void>;
4094
+ };
4095
+ }): ReadableStream<T>;
4057
4096
 
4058
4097
  /**
4059
- * Transport interface for MCP (Model Context Protocol) communication.
4060
- * Maps to the `Transport` interface in the MCP spec.
4098
+ The result of a `streamObject` call that contains the partial object stream and additional information.
4061
4099
  */
4062
- interface MCPTransport {
4100
+ interface StreamObjectResult<PARTIAL, RESULT, ELEMENT_STREAM> {
4063
4101
  /**
4064
- * Initialize and start the transport
4065
- */
4066
- start(): Promise<void>;
4102
+ Warnings from the model provider (e.g. unsupported settings)
4103
+ */
4104
+ readonly warnings: Promise<CallWarning[] | undefined>;
4067
4105
  /**
4068
- * Send a JSON-RPC message through the transport
4069
- * @param message The JSON-RPC message to send
4070
- */
4071
- send(message: JSONRPCMessage): Promise<void>;
4106
+ The token usage of the generated response. Resolved when the response is finished.
4107
+ */
4108
+ readonly usage: Promise<LanguageModelUsage>;
4072
4109
  /**
4073
- * Clean up and close the transport
4110
+ Additional provider-specific metadata. They are passed through
4111
+ from the provider to the AI SDK and enable provider-specific
4112
+ results that can be fully encapsulated in the provider.
4074
4113
  */
4075
- close(): Promise<void>;
4114
+ readonly providerMetadata: Promise<ProviderMetadata | undefined>;
4076
4115
  /**
4077
- * Event handler for transport closure
4078
- */
4079
- onclose?: () => void;
4116
+ Additional request information from the last step.
4117
+ */
4118
+ readonly request: Promise<LanguageModelRequestMetadata>;
4080
4119
  /**
4081
- * Event handler for transport errors
4082
- */
4083
- onerror?: (error: Error) => void;
4120
+ Additional response information.
4121
+ */
4122
+ readonly response: Promise<LanguageModelResponseMetadata>;
4084
4123
  /**
4085
- * Event handler for received messages
4086
- */
4087
- onmessage?: (message: JSONRPCMessage) => void;
4088
- }
4089
- type MCPTransportConfig = {
4090
- type: 'sse';
4124
+ The reason why the generation finished. Taken from the last step.
4125
+
4126
+ Resolved when the response is finished.
4127
+ */
4128
+ readonly finishReason: Promise<FinishReason>;
4091
4129
  /**
4092
- * The URL of the MCP server.
4093
- */
4094
- url: string;
4130
+ The generated object (typed according to the schema). Resolved when the response is finished.
4131
+ */
4132
+ readonly object: Promise<RESULT>;
4095
4133
  /**
4096
- * Additional HTTP headers to be sent with requests.
4134
+ Stream of partial objects. It gets more complete as the stream progresses.
4135
+
4136
+ Note that the partial object is not validated.
4137
+ If you want to be certain that the actual content matches your schema, you need to implement your own validation for partial results.
4138
+ */
4139
+ readonly partialObjectStream: AsyncIterableStream<PARTIAL>;
4140
+ /**
4141
+ * Stream over complete array elements. Only available if the output strategy is set to `array`.
4097
4142
  */
4098
- headers?: Record<string, string>;
4099
- };
4100
-
4101
- type ToolSchemas = Record<string, {
4102
- inputSchema: FlexibleSchema<JSONObject | unknown>;
4103
- }> | 'automatic' | undefined;
4104
- type McpToolSet<TOOL_SCHEMAS extends ToolSchemas = 'automatic'> = TOOL_SCHEMAS extends Record<string, {
4105
- inputSchema: FlexibleSchema<any>;
4106
- }> ? {
4107
- [K in keyof TOOL_SCHEMAS]: TOOL_SCHEMAS[K] extends {
4108
- inputSchema: FlexibleSchema<infer INPUT>;
4109
- } ? Tool<INPUT, CallToolResult> & Required<Pick<Tool<INPUT, CallToolResult>, 'execute'>> : never;
4110
- } : McpToolSet<Record<string, {
4111
- inputSchema: FlexibleSchema<unknown>;
4112
- }>>;
4113
- declare const CallToolResultSchema: z.ZodUnion<[z.ZodObject<{
4114
- _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4115
- content: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
4116
- type: z.ZodLiteral<"text">;
4117
- text: z.ZodString;
4118
- }, z.core.$loose>, z.ZodObject<{
4119
- type: z.ZodLiteral<"image">;
4120
- data: z.ZodBase64;
4121
- mimeType: z.ZodString;
4122
- }, z.core.$loose>, z.ZodObject<{
4123
- type: z.ZodLiteral<"resource">;
4124
- resource: z.ZodUnion<readonly [z.ZodObject<{
4125
- uri: z.ZodString;
4126
- mimeType: z.ZodOptional<z.ZodString>;
4127
- text: z.ZodString;
4128
- }, z.core.$loose>, z.ZodObject<{
4129
- uri: z.ZodString;
4130
- mimeType: z.ZodOptional<z.ZodString>;
4131
- blob: z.ZodBase64;
4132
- }, z.core.$loose>]>;
4133
- }, z.core.$loose>]>>;
4134
- isError: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
4135
- }, z.core.$loose>, z.ZodObject<{
4136
- _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4137
- toolResult: z.ZodUnknown;
4138
- }, z.core.$loose>]>;
4139
- type CallToolResult = z.infer<typeof CallToolResultSchema>;
4140
-
4141
- interface MCPClientConfig {
4142
- /** Transport configuration for connecting to the MCP server */
4143
- transport: MCPTransportConfig | MCPTransport;
4144
- /** Optional callback for uncaught errors */
4145
- onUncaughtError?: (error: unknown) => void;
4146
- /** Optional client name, defaults to 'ai-sdk-mcp-client' */
4147
- name?: string;
4148
- }
4149
- declare function createMCPClient(config: MCPClientConfig): Promise<MCPClient>;
4150
- interface MCPClient {
4151
- tools<TOOL_SCHEMAS extends ToolSchemas = 'automatic'>(options?: {
4152
- schemas?: TOOL_SCHEMAS;
4153
- }): Promise<McpToolSet<TOOL_SCHEMAS>>;
4154
- close: () => Promise<void>;
4155
- }
4156
-
4157
- /**
4158
- The result of a `transcribe` call.
4159
- It contains the transcript and additional information.
4160
- */
4161
- interface TranscriptionResult {
4162
- /**
4163
- * The complete transcribed text from the audio.
4164
- */
4165
- readonly text: string;
4166
- /**
4167
- * Array of transcript segments with timing information.
4168
- * Each segment represents a portion of the transcribed text with start and end times.
4169
- */
4170
- readonly segments: Array<{
4171
- /**
4172
- * The text content of this segment.
4173
- */
4174
- readonly text: string;
4175
- /**
4176
- * The start time of this segment in seconds.
4177
- */
4178
- readonly startSecond: number;
4179
- /**
4180
- * The end time of this segment in seconds.
4181
- */
4182
- readonly endSecond: number;
4183
- }>;
4184
- /**
4185
- * The detected language of the audio content, as an ISO-639-1 code (e.g., 'en' for English).
4186
- * May be undefined if the language couldn't be detected.
4187
- */
4188
- readonly language: string | undefined;
4143
+ readonly elementStream: ELEMENT_STREAM;
4189
4144
  /**
4190
- * The total duration of the audio file in seconds.
4191
- * May be undefined if the duration couldn't be determined.
4192
- */
4193
- readonly durationInSeconds: number | undefined;
4145
+ Text stream of the JSON representation of the generated object. It contains text chunks.
4146
+ When the stream is finished, the object is valid JSON that can be parsed.
4147
+ */
4148
+ readonly textStream: AsyncIterableStream<string>;
4194
4149
  /**
4195
- Warnings for the call, e.g. unsupported settings.
4150
+ Stream of different types of events, including partial objects, errors, and finish events.
4151
+ Only errors that stop the stream, such as network errors, are thrown.
4196
4152
  */
4197
- readonly warnings: Array<TranscriptionWarning>;
4153
+ readonly fullStream: AsyncIterableStream<ObjectStreamPart<PARTIAL>>;
4198
4154
  /**
4199
- Response metadata from the provider. There may be multiple responses if we made multiple calls to the model.
4200
- */
4201
- readonly responses: Array<TranscriptionModelResponseMetadata>;
4155
+ Writes text delta output to a Node.js response-like object.
4156
+ It sets a `Content-Type` header to `text/plain; charset=utf-8` and
4157
+ writes each text delta as a separate chunk.
4158
+
4159
+ @param response A Node.js response-like object (ServerResponse).
4160
+ @param init Optional headers, status code, and status text.
4161
+ */
4162
+ pipeTextStreamToResponse(response: ServerResponse$1, init?: ResponseInit): void;
4202
4163
  /**
4203
- Provider metadata from the provider.
4204
- */
4205
- readonly providerMetadata: Record<string, Record<string, JSONValue$1>>;
4164
+ Creates a simple text stream response.
4165
+ The response has a `Content-Type` header set to `text/plain; charset=utf-8`.
4166
+ Each text delta is encoded as UTF-8 and sent as a separate chunk.
4167
+ Non-text-delta events are ignored.
4168
+
4169
+ @param init Optional headers, status code, and status text.
4170
+ */
4171
+ toTextStreamResponse(init?: ResponseInit): Response;
4206
4172
  }
4173
+ type ObjectStreamPart<PARTIAL> = {
4174
+ type: 'object';
4175
+ object: PARTIAL;
4176
+ } | {
4177
+ type: 'text-delta';
4178
+ textDelta: string;
4179
+ } | {
4180
+ type: 'error';
4181
+ error: unknown;
4182
+ } | {
4183
+ type: 'finish';
4184
+ finishReason: FinishReason;
4185
+ usage: LanguageModelUsage;
4186
+ response: LanguageModelResponseMetadata;
4187
+ providerMetadata?: ProviderMetadata;
4188
+ };
4207
4189
 
4208
4190
  /**
4209
- Generates transcripts using a transcription model.
4191
+ Callback that is set using the `onError` option.
4210
4192
 
4211
- @param model - The transcription model to use.
4212
- @param audio - The audio data to transcribe as DataContent (string | Uint8Array | ArrayBuffer | Buffer) or a URL.
4213
- @param providerOptions - Additional provider-specific options that are passed through to the provider
4214
- as body parameters.
4215
- @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
4216
- @param abortSignal - An optional abort signal that can be used to cancel the call.
4217
- @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
4193
+ @param event - The event that is passed to the callback.
4194
+ */
4195
+ type StreamObjectOnErrorCallback = (event: {
4196
+ error: unknown;
4197
+ }) => Promise<void> | void;
4198
+ /**
4199
+ Callback that is set using the `onFinish` option.
4218
4200
 
4219
- @returns A result object that contains the generated transcript.
4201
+ @param event - The event that is passed to the callback.
4220
4202
  */
4221
- declare function transcribe({ model, audio, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, }: {
4222
- /**
4223
- The transcription model to use.
4224
- */
4225
- model: TranscriptionModel;
4226
- /**
4227
- The audio data to transcribe.
4228
- */
4229
- audio: DataContent | URL;
4203
+ type StreamObjectOnFinishCallback<RESULT> = (event: {
4230
4204
  /**
4231
- Additional provider-specific options that are passed through to the provider
4232
- as body parameters.
4233
-
4234
- The outer record is keyed by the provider name, and the inner
4235
- record is keyed by the provider-specific metadata key.
4236
- ```ts
4237
- {
4238
- "openai": {
4239
- "temperature": 0
4240
- }
4241
- }
4242
- ```
4243
- */
4244
- providerOptions?: ProviderOptions;
4205
+ The token usage of the generated response.
4206
+ */
4207
+ usage: LanguageModelUsage;
4245
4208
  /**
4246
- Maximum number of retries per transcript model call. Set to 0 to disable retries.
4247
-
4248
- @default 2
4249
- */
4250
- maxRetries?: number;
4209
+ The generated object. Can be undefined if the final object does not match the schema.
4210
+ */
4211
+ object: RESULT | undefined;
4251
4212
  /**
4252
- Abort signal.
4253
- */
4254
- abortSignal?: AbortSignal;
4213
+ Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.
4214
+ */
4215
+ error: unknown | undefined;
4255
4216
  /**
4256
- Additional headers to include in the request.
4257
- Only applicable for HTTP-based providers.
4217
+ Response metadata.
4258
4218
  */
4259
- headers?: Record<string, string>;
4260
- }): Promise<TranscriptionResult>;
4261
-
4262
- declare const getOriginalFetch: () => typeof fetch;
4263
- declare function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol, setCompletion, setLoading, setError, setAbortController, onFinish, onError, fetch, }: {
4264
- api: string;
4265
- prompt: string;
4266
- credentials: RequestCredentials | undefined;
4267
- headers: HeadersInit | undefined;
4268
- body: Record<string, any>;
4269
- streamProtocol: 'data' | 'text' | undefined;
4270
- setCompletion: (completion: string) => void;
4271
- setLoading: (loading: boolean) => void;
4272
- setError: (error: Error | undefined) => void;
4273
- setAbortController: (abortController: AbortController | null) => void;
4274
- onFinish: ((prompt: string, completion: string) => void) | undefined;
4275
- onError: ((error: Error) => void) | undefined;
4276
- fetch: ReturnType<typeof getOriginalFetch> | undefined;
4277
- }): Promise<string | null | undefined>;
4278
-
4279
- interface UIMessageStreamWriter<UI_MESSAGE extends UIMessage = UIMessage> {
4280
- /**
4281
- * Appends a data stream part to the stream.
4282
- */
4283
- write(part: InferUIMessageChunk<UI_MESSAGE>): void;
4219
+ response: LanguageModelResponseMetadata;
4284
4220
  /**
4285
- * Merges the contents of another stream to this stream.
4286
- */
4287
- merge(stream: ReadableStream<InferUIMessageChunk<UI_MESSAGE>>): void;
4221
+ Warnings from the model provider (e.g. unsupported settings).
4222
+ */
4223
+ warnings?: CallWarning[];
4288
4224
  /**
4289
- * Error handler that is used by the data stream writer.
4290
- * This is intended for forwarding when merging streams
4291
- * to prevent duplicated error masking.
4292
- */
4293
- onError: ErrorHandler | undefined;
4294
- }
4225
+ Additional provider-specific metadata. They are passed through
4226
+ to the provider from the AI SDK and enable provider-specific
4227
+ functionality that can be fully encapsulated in the provider.
4228
+ */
4229
+ providerMetadata: ProviderMetadata | undefined;
4230
+ }) => Promise<void> | void;
4231
+ /**
4232
+ Generate a structured, typed object for a given prompt and schema using a language model.
4295
4233
 
4296
- declare function createUIMessageStream<UI_MESSAGE extends UIMessage>({ execute, onError, originalMessages, onFinish, generateId, }: {
4297
- execute: (options: {
4298
- writer: UIMessageStreamWriter<UI_MESSAGE>;
4299
- }) => Promise<void> | void;
4300
- onError?: (error: unknown) => string;
4301
- /**
4302
- * The original messages. If they are provided, persistence mode is assumed,
4303
- * and a message ID is provided for the response message.
4304
- */
4305
- originalMessages?: UI_MESSAGE[];
4306
- onFinish?: UIMessageStreamOnFinishCallback<UI_MESSAGE>;
4307
- generateId?: IdGenerator;
4308
- }): ReadableStream<InferUIMessageChunk<UI_MESSAGE>>;
4234
+ This function streams the output. If you do not want to stream the output, use `generateObject` instead.
4309
4235
 
4310
- declare function createUIMessageStreamResponse({ status, statusText, headers, stream, consumeSseStream, }: UIMessageStreamResponseInit & {
4311
- stream: ReadableStream<UIMessageChunk>;
4312
- }): Response;
4236
+ @param model - The language model to use.
4237
+ @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.
4313
4238
 
4314
- declare class JsonToSseTransformStream extends TransformStream<unknown, string> {
4315
- constructor();
4316
- }
4239
+ @param system - A system message that will be part of the prompt.
4240
+ @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.
4241
+ @param messages - A list of messages. You can either use `prompt` or `messages` but not both.
4317
4242
 
4318
- declare function pipeUIMessageStreamToResponse({ response, status, statusText, headers, stream, consumeSseStream, }: {
4319
- response: ServerResponse;
4320
- stream: ReadableStream<UIMessageChunk>;
4321
- } & UIMessageStreamResponseInit): void;
4243
+ @param maxOutputTokens - Maximum number of tokens to generate.
4244
+ @param temperature - Temperature setting.
4245
+ The value is passed through to the provider. The range depends on the provider and model.
4246
+ It is recommended to set either `temperature` or `topP`, but not both.
4247
+ @param topP - Nucleus sampling.
4248
+ The value is passed through to the provider. The range depends on the provider and model.
4249
+ It is recommended to set either `temperature` or `topP`, but not both.
4250
+ @param topK - Only sample from the top K options for each subsequent token.
4251
+ Used to remove "long tail" low probability responses.
4252
+ Recommended for advanced use cases only. You usually only need to use temperature.
4253
+ @param presencePenalty - Presence penalty setting.
4254
+ It affects the likelihood of the model to repeat information that is already in the prompt.
4255
+ The value is passed through to the provider. The range depends on the provider and model.
4256
+ @param frequencyPenalty - Frequency penalty setting.
4257
+ It affects the likelihood of the model to repeatedly use the same words or phrases.
4258
+ The value is passed through to the provider. The range depends on the provider and model.
4259
+ @param stopSequences - Stop sequences.
4260
+ If set, the model will stop generating text when one of the stop sequences is generated.
4261
+ @param seed - The seed (integer) to use for random sampling.
4262
+ If set and supported by the model, calls will generate deterministic results.
4322
4263
 
4323
- /**
4324
- * Transforms a stream of `UIMessageChunk`s into an `AsyncIterableStream` of `UIMessage`s.
4325
- *
4326
- * @param options.message - The last assistant message to use as a starting point when the conversation is resumed. Otherwise undefined.
4327
- * @param options.stream - The stream of `UIMessageChunk`s to read.
4328
- * @param options.terminateOnError - Whether to terminate the stream if an error occurs.
4329
- * @param options.onError - A function that is called when an error occurs.
4330
- *
4331
- * @returns An `AsyncIterableStream` of `UIMessage`s. Each stream part is a different state of the same message
4332
- * as it is being completed.
4333
- */
4334
- declare function readUIMessageStream<UI_MESSAGE extends UIMessage>({ message, stream, onError, terminateOnError, }: {
4335
- message?: UI_MESSAGE;
4336
- stream: ReadableStream<UIMessageChunk>;
4337
- onError?: (error: unknown) => void;
4338
- terminateOnError?: boolean;
4339
- }): AsyncIterableStream<UI_MESSAGE>;
4264
+ @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
4265
+ @param abortSignal - An optional abort signal that can be used to cancel the call.
4266
+ @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
4340
4267
 
4341
- declare const UI_MESSAGE_STREAM_HEADERS: {
4342
- 'content-type': string;
4343
- 'cache-control': string;
4344
- connection: string;
4345
- 'x-vercel-ai-ui-message-stream': string;
4346
- 'x-accel-buffering': string;
4347
- };
4268
+ @param schema - The schema of the object that the model should generate.
4269
+ @param schemaName - Optional name of the output that should be generated.
4270
+ Used by some providers for additional LLM guidance, e.g.
4271
+ via tool or schema name.
4272
+ @param schemaDescription - Optional description of the output that should be generated.
4273
+ Used by some providers for additional LLM guidance, e.g.
4274
+ via tool or schema description.
4348
4275
 
4349
- /**
4350
- * Transport interface for handling chat message communication and streaming.
4351
- *
4352
- * The `ChatTransport` interface provides fine-grained control over how messages
4353
- * are sent to API endpoints and how responses are processed. This enables
4354
- * alternative communication protocols like WebSockets, custom authentication
4355
- * patterns, or specialized backend integrations.
4356
- *
4357
- * @template UI_MESSAGE - The UI message type extending UIMessage
4276
+ @param output - The type of the output.
4277
+
4278
+ - 'object': The output is an object.
4279
+ - 'array': The output is an array.
4280
+ - 'enum': The output is an enum.
4281
+ - 'no-schema': The output is not a schema.
4282
+
4283
+ @param experimental_telemetry - Optional telemetry configuration (experimental).
4284
+
4285
+ @param providerOptions - Additional provider-specific options. They are passed through
4286
+ to the provider from the AI SDK and enable provider-specific
4287
+ functionality that can be fully encapsulated in the provider.
4288
+
4289
+ @returns
4290
+ A result object for accessing the partial object stream and additional information.
4358
4291
  */
4359
- interface ChatTransport<UI_MESSAGE extends UIMessage> {
4292
+ declare function streamObject<SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<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' ? {
4360
4293
  /**
4361
- * Sends messages to the chat API endpoint and returns a streaming response.
4362
- *
4363
- * This method handles both new message submission and message regeneration.
4364
- * It supports real-time streaming of responses through UIMessageChunk events.
4365
- *
4366
- * @param options - Configuration object containing:
4367
- * @param options.trigger - The type of message submission:
4368
- * - `'submit-message'`: Submitting a new user message
4369
- * - `'regenerate-message'`: Regenerating an assistant response
4370
- * @param options.chatId - Unique identifier for the chat session
4371
- * @param options.messageId - ID of the message to regenerate (for regenerate-message trigger) or undefined for new messages
4372
- * @param options.messages - Array of UI messages representing the conversation history
4373
- * @param options.abortSignal - Signal to abort the request if needed
4374
- * @param options.headers - Additional HTTP headers to include in the request
4375
- * @param options.body - Additional JSON properties to include in the request body
4376
- * @param options.metadata - Custom metadata to attach to the request
4377
- *
4378
- * @returns Promise resolving to a ReadableStream of UIMessageChunk objects.
4379
- * The stream emits various chunk types like:
4380
- * - `text-start`, `text-delta`, `text-end`: For streaming text content
4381
- * - `tool-input-start`, `tool-input-delta`, `tool-input-available`: For tool calls
4382
- * - `data-part-start`, `data-part-delta`, `data-part-available`: For data parts
4383
- * - `error`: For error handling
4384
- *
4385
- * @throws Error when the API request fails or response is invalid
4294
+ The enum values that the model should use.
4295
+ */
4296
+ enum: Array<RESULT>;
4297
+ mode?: 'json';
4298
+ output: 'enum';
4299
+ } : OUTPUT extends 'no-schema' ? {} : {
4300
+ /**
4301
+ The schema of the object that the model should generate.
4302
+ */
4303
+ schema: SCHEMA;
4304
+ /**
4305
+ Optional name of the output that should be generated.
4306
+ Used by some providers for additional LLM guidance, e.g.
4307
+ via tool or schema name.
4308
+ */
4309
+ schemaName?: string;
4310
+ /**
4311
+ Optional description of the output that should be generated.
4312
+ Used by some providers for additional LLM guidance, e.g.
4313
+ via tool or schema description.
4314
+ */
4315
+ schemaDescription?: string;
4316
+ /**
4317
+ The mode to use for object generation.
4318
+
4319
+ The schema is converted into a JSON schema and used in one of the following ways
4320
+
4321
+ - 'auto': The provider will choose the best mode for the model.
4322
+ - 'tool': A tool with the JSON schema as parameters is provided and the provider is instructed to use it.
4323
+ - 'json': The JSON schema and an instruction are injected into the prompt. If the provider supports JSON mode, it is enabled. If the provider supports JSON grammars, the grammar is used.
4324
+
4325
+ Please note that most providers do not support all modes.
4326
+
4327
+ Default and recommended: 'auto' (best mode for the model).
4328
+ */
4329
+ mode?: 'auto' | 'json' | 'tool';
4330
+ }) & {
4331
+ output?: OUTPUT;
4332
+ /**
4333
+ The language model to use.
4334
+ */
4335
+ model: LanguageModel;
4336
+ /**
4337
+ A function that attempts to repair the raw output of the model
4338
+ to enable JSON parsing.
4386
4339
  */
4387
- sendMessages: (options: {
4388
- /** The type of message submission - either new message or regeneration */
4389
- trigger: 'submit-message' | 'regenerate-message';
4390
- /** Unique identifier for the chat session */
4391
- chatId: string;
4392
- /** ID of the message to regenerate, or undefined for new messages */
4393
- messageId: string | undefined;
4394
- /** Array of UI messages representing the conversation history */
4395
- messages: UI_MESSAGE[];
4396
- /** Signal to abort the request if needed */
4397
- abortSignal: AbortSignal | undefined;
4398
- } & ChatRequestOptions) => Promise<ReadableStream<UIMessageChunk>>;
4340
+ experimental_repairText?: RepairTextFunction;
4399
4341
  /**
4400
- * Reconnects to an existing streaming response for the specified chat session.
4401
- *
4402
- * This method is used to resume streaming when a connection is interrupted
4403
- * or when resuming a chat session. It's particularly useful for maintaining
4404
- * continuity in long-running conversations or recovering from network issues.
4405
- *
4406
- * @param options - Configuration object containing:
4407
- * @param options.chatId - Unique identifier for the chat session to reconnect to
4408
- * @param options.headers - Additional HTTP headers to include in the reconnection request
4409
- * @param options.body - Additional JSON properties to include in the request body
4410
- * @param options.metadata - Custom metadata to attach to the request
4411
- *
4412
- * @returns Promise resolving to:
4413
- * - `ReadableStream<UIMessageChunk>`: If an active stream is found and can be resumed
4414
- * - `null`: If no active stream exists for the specified chat session (e.g., response already completed)
4415
- *
4416
- * @throws Error when the reconnection request fails or response is invalid
4342
+ Optional telemetry configuration (experimental).
4417
4343
  */
4418
- reconnectToStream: (options: {
4419
- /** Unique identifier for the chat session to reconnect to */
4420
- chatId: string;
4421
- } & ChatRequestOptions) => Promise<ReadableStream<UIMessageChunk> | null>;
4422
- }
4423
-
4424
- type CreateUIMessage<UI_MESSAGE extends UIMessage> = Omit<UI_MESSAGE, 'id' | 'role'> & {
4425
- id?: UI_MESSAGE['id'];
4426
- role?: UI_MESSAGE['role'];
4427
- };
4428
- type UIDataPartSchemas = Record<string, FlexibleSchema>;
4429
- type UIDataTypesToSchemas<T extends UIDataTypes> = {
4430
- [K in keyof T]: FlexibleSchema<T[K]>;
4431
- };
4432
- type InferUIDataParts<T extends UIDataPartSchemas> = {
4433
- [K in keyof T]: InferSchema<T[K]>;
4434
- };
4435
- type ChatRequestOptions = {
4344
+ experimental_telemetry?: TelemetrySettings;
4436
4345
  /**
4437
- Additional headers that should be to be passed to the API endpoint.
4346
+ Custom download function to use for URLs.
4347
+
4348
+ By default, files are downloaded if the model does not support the URL for the given media type.
4438
4349
  */
4439
- headers?: Record<string, string> | Headers;
4350
+ experimental_download?: DownloadFunction | undefined;
4440
4351
  /**
4441
- Additional body JSON properties that should be sent to the API endpoint.
4352
+ Additional provider-specific options. They are passed through
4353
+ to the provider from the AI SDK and enable provider-specific
4354
+ functionality that can be fully encapsulated in the provider.
4355
+ */
4356
+ providerOptions?: ProviderOptions;
4357
+ /**
4358
+ Callback that is invoked when an error occurs during streaming.
4359
+ You can use it to log errors.
4360
+ The stream processing will pause until the callback promise is resolved.
4361
+ */
4362
+ onError?: StreamObjectOnErrorCallback;
4363
+ /**
4364
+ Callback that is called when the LLM response and the final object validation are finished.
4365
+ */
4366
+ onFinish?: StreamObjectOnFinishCallback<RESULT>;
4367
+ /**
4368
+ * Internal. For test use only. May change without notice.
4442
4369
  */
4443
- body?: object;
4444
- metadata?: unknown;
4445
- };
4370
+ _internal?: {
4371
+ generateId?: () => string;
4372
+ currentDate?: () => Date;
4373
+ now?: () => number;
4374
+ };
4375
+ }): 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>;
4376
+
4446
4377
  /**
4447
- * Function that can be called to add a tool approval response to the chat.
4378
+ * A generated audio file.
4448
4379
  */
4449
- type ChatAddToolApproveResponseFunction = ({ id, approved, reason, }: {
4450
- id: string;
4451
- /**
4452
- * Flag indicating whether the approval was granted or denied.
4453
- */
4454
- approved: boolean;
4380
+ interface GeneratedAudioFile extends GeneratedFile {
4455
4381
  /**
4456
- * Optional reason for the approval or denial.
4382
+ * Audio format of the file (e.g., 'mp3', 'wav', etc.)
4457
4383
  */
4458
- reason?: string;
4459
- }) => void | PromiseLike<void>;
4460
- type ChatStatus = 'submitted' | 'streaming' | 'ready' | 'error';
4461
- interface ChatState<UI_MESSAGE extends UIMessage> {
4462
- status: ChatStatus;
4463
- error: Error | undefined;
4464
- messages: UI_MESSAGE[];
4465
- pushMessage: (message: UI_MESSAGE) => void;
4466
- popMessage: () => void;
4467
- replaceMessage: (index: number, message: UI_MESSAGE) => void;
4468
- snapshot: <T>(thing: T) => T;
4384
+ readonly format: string;
4469
4385
  }
4470
- type ChatOnErrorCallback = (error: Error) => void;
4471
- type ChatOnToolCallCallback<UI_MESSAGE extends UIMessage = UIMessage> = (options: {
4472
- toolCall: InferUIMessageToolCall<UI_MESSAGE>;
4473
- }) => void | PromiseLike<void>;
4474
- type ChatOnDataCallback<UI_MESSAGE extends UIMessage> = (dataPart: DataUIPart<InferUIMessageData<UI_MESSAGE>>) => void;
4386
+
4475
4387
  /**
4476
- * Function that is called when the assistant response has finished streaming.
4388
+ The result of a `generateSpeech` call.
4389
+ It contains the audio data and additional information.
4390
+ */
4391
+ interface SpeechResult {
4392
+ /**
4393
+ * The audio data as a base64 encoded string or binary data.
4394
+ */
4395
+ readonly audio: GeneratedAudioFile;
4396
+ /**
4397
+ Warnings for the call, e.g. unsupported settings.
4398
+ */
4399
+ readonly warnings: Array<SpeechWarning>;
4400
+ /**
4401
+ Response metadata from the provider. There may be multiple responses if we made multiple calls to the model.
4402
+ */
4403
+ readonly responses: Array<SpeechModelResponseMetadata>;
4404
+ /**
4405
+ Provider metadata from the provider.
4406
+ */
4407
+ readonly providerMetadata: Record<string, Record<string, JSONValue$1>>;
4408
+ }
4409
+
4410
+ /**
4411
+ Generates speech audio using a speech model.
4412
+
4413
+ @param model - The speech model to use.
4414
+ @param text - The text to convert to speech.
4415
+ @param voice - The voice to use for speech generation.
4416
+ @param outputFormat - The output format to use for speech generation e.g. "mp3", "wav", etc.
4417
+ @param instructions - Instructions for the speech generation e.g. "Speak in a slow and steady tone".
4418
+ @param speed - The speed of the speech generation.
4419
+ @param providerOptions - Additional provider-specific options that are passed through to the provider
4420
+ as body parameters.
4421
+ @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
4422
+ @param abortSignal - An optional abort signal that can be used to cancel the call.
4423
+ @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
4424
+
4425
+ @returns A result object that contains the generated audio data.
4426
+ */
4427
+ declare function generateSpeech({ model, text, voice, outputFormat, instructions, speed, language, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, }: {
4428
+ /**
4429
+ The speech model to use.
4430
+ */
4431
+ model: SpeechModel;
4432
+ /**
4433
+ The text to convert to speech.
4434
+ */
4435
+ text: string;
4436
+ /**
4437
+ The voice to use for speech generation.
4438
+ */
4439
+ voice?: string;
4440
+ /**
4441
+ * The desired output format for the audio e.g. "mp3", "wav", etc.
4442
+ */
4443
+ outputFormat?: 'mp3' | 'wav' | (string & {});
4444
+ /**
4445
+ Instructions for the speech generation e.g. "Speak in a slow and steady tone".
4446
+ */
4447
+ instructions?: string;
4448
+ /**
4449
+ The speed of the speech generation.
4450
+ */
4451
+ speed?: number;
4452
+ /**
4453
+ The language for speech generation. This should be an ISO 639-1 language code (e.g. "en", "es", "fr")
4454
+ or "auto" for automatic language detection. Provider support varies.
4455
+ */
4456
+ language?: string;
4457
+ /**
4458
+ Additional provider-specific options that are passed through to the provider
4459
+ as body parameters.
4460
+
4461
+ The outer record is keyed by the provider name, and the inner
4462
+ record is keyed by the provider-specific metadata key.
4463
+ ```ts
4464
+ {
4465
+ "openai": {}
4466
+ }
4467
+ ```
4468
+ */
4469
+ providerOptions?: ProviderOptions;
4470
+ /**
4471
+ Maximum number of retries per speech model call. Set to 0 to disable retries.
4472
+
4473
+ @default 2
4474
+ */
4475
+ maxRetries?: number;
4476
+ /**
4477
+ Abort signal.
4478
+ */
4479
+ abortSignal?: AbortSignal;
4480
+ /**
4481
+ Additional headers to include in the request.
4482
+ Only applicable for HTTP-based providers.
4483
+ */
4484
+ headers?: Record<string, string>;
4485
+ }): Promise<SpeechResult>;
4486
+
4487
+ type Warning = LanguageModelV3CallWarning | ImageModelV3CallWarning | SpeechModelV3CallWarning | TranscriptionModelV3CallWarning;
4488
+ type LogWarningsFunction = (warnings: Warning[]) => void;
4489
+
4490
+ /**
4491
+ * Applies default settings for a language model.
4492
+ */
4493
+ declare function defaultSettingsMiddleware({ settings, }: {
4494
+ settings: Partial<{
4495
+ maxOutputTokens?: LanguageModelV3CallOptions['maxOutputTokens'];
4496
+ temperature?: LanguageModelV3CallOptions['temperature'];
4497
+ stopSequences?: LanguageModelV3CallOptions['stopSequences'];
4498
+ topP?: LanguageModelV3CallOptions['topP'];
4499
+ topK?: LanguageModelV3CallOptions['topK'];
4500
+ presencePenalty?: LanguageModelV3CallOptions['presencePenalty'];
4501
+ frequencyPenalty?: LanguageModelV3CallOptions['frequencyPenalty'];
4502
+ responseFormat?: LanguageModelV3CallOptions['responseFormat'];
4503
+ seed?: LanguageModelV3CallOptions['seed'];
4504
+ tools?: LanguageModelV3CallOptions['tools'];
4505
+ toolChoice?: LanguageModelV3CallOptions['toolChoice'];
4506
+ headers?: LanguageModelV3CallOptions['headers'];
4507
+ providerOptions?: LanguageModelV3CallOptions['providerOptions'];
4508
+ }>;
4509
+ }): LanguageModelMiddleware;
4510
+
4511
+ /**
4512
+ * Extract an XML-tagged reasoning section from the generated text and exposes it
4513
+ * as a `reasoning` property on the result.
4477
4514
  *
4478
- * @param message The assistant message that was streamed.
4479
- * @param messages The full chat history, including the assistant message.
4515
+ * @param tagName - The name of the XML tag to extract reasoning from.
4516
+ * @param separator - The separator to use between reasoning and text sections.
4517
+ * @param startWithReasoning - Whether to start with reasoning tokens.
4518
+ */
4519
+ declare function extractReasoningMiddleware({ tagName, separator, startWithReasoning, }: {
4520
+ tagName: string;
4521
+ separator?: string;
4522
+ startWithReasoning?: boolean;
4523
+ }): LanguageModelMiddleware;
4524
+
4525
+ /**
4526
+ * Simulates streaming chunks with the response from a generate call.
4527
+ */
4528
+ declare function simulateStreamingMiddleware(): LanguageModelMiddleware;
4529
+
4530
+ /**
4531
+ * Wraps a LanguageModelV3 instance with middleware functionality.
4532
+ * This function allows you to apply middleware to transform parameters,
4533
+ * wrap generate operations, and wrap stream operations of a language model.
4480
4534
  *
4481
- * @param isAbort Indicates whether the request has been aborted.
4482
- * @param isDisconnect Indicates whether the request has been ended by a network error.
4483
- * @param isError Indicates whether the request has been ended by an error.
4535
+ * @param options - Configuration options for wrapping the language model.
4536
+ * @param options.model - The original LanguageModelV3 instance to be wrapped.
4537
+ * @param options.middleware - The middleware to be applied to the language model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.
4538
+ * @param options.modelId - Optional custom model ID to override the original model's ID.
4539
+ * @param options.providerId - Optional custom provider ID to override the original model's provider ID.
4540
+ * @returns A new LanguageModelV3 instance with middleware applied.
4484
4541
  */
4485
- type ChatOnFinishCallback<UI_MESSAGE extends UIMessage> = (options: {
4486
- message: UI_MESSAGE;
4487
- messages: UI_MESSAGE[];
4488
- isAbort: boolean;
4489
- isDisconnect: boolean;
4490
- isError: boolean;
4491
- }) => void;
4492
- interface ChatInit<UI_MESSAGE extends UIMessage> {
4542
+ declare const wrapLanguageModel: ({ model, middleware: middlewareArg, modelId, providerId, }: {
4543
+ model: LanguageModelV3;
4544
+ middleware: LanguageModelMiddleware | LanguageModelMiddleware[];
4545
+ modelId?: string;
4546
+ providerId?: string;
4547
+ }) => LanguageModelV3;
4548
+
4549
+ /**
4550
+ * Wraps a ProviderV3 instance with middleware functionality.
4551
+ * This function allows you to apply middleware to all language models
4552
+ * from the provider, enabling you to transform parameters, wrap generate
4553
+ * operations, and wrap stream operations for every language model.
4554
+ *
4555
+ * @param options - Configuration options for wrapping the provider.
4556
+ * @param options.provider - The original ProviderV3 instance to be wrapped.
4557
+ * @param options.languageModelMiddleware - The middleware to be applied to all language models from the provider. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.
4558
+ * @returns A new ProviderV3 instance with middleware applied to all language models.
4559
+ */
4560
+ declare function wrapProvider({ provider, languageModelMiddleware, }: {
4561
+ provider: ProviderV3 | ProviderV2;
4562
+ languageModelMiddleware: LanguageModelMiddleware | LanguageModelMiddleware[];
4563
+ }): ProviderV3;
4564
+
4565
+ /**
4566
+ * Creates a custom provider with specified language models, text embedding models, image models, transcription models, speech models, and an optional fallback provider.
4567
+ *
4568
+ * @param {Object} options - The options for creating the custom provider.
4569
+ * @param {Record<string, LanguageModel>} [options.languageModels] - A record of language models, where keys are model IDs and values are LanguageModel instances.
4570
+ * @param {Record<string, EmbeddingModel<string>>} [options.textEmbeddingModels] - A record of text embedding models, where keys are model IDs and values are EmbeddingModel<string> instances.
4571
+ * @param {Record<string, ImageModel>} [options.imageModels] - A record of image models, where keys are model IDs and values are ImageModel instances.
4572
+ * @param {Record<string, TranscriptionModel>} [options.transcriptionModels] - A record of transcription models, where keys are model IDs and values are TranscriptionModel instances.
4573
+ * @param {Record<string, SpeechModel>} [options.speechModels] - A record of speech models, where keys are model IDs and values are SpeechModel instances.
4574
+ * @param {Provider} [options.fallbackProvider] - An optional fallback provider to use when a requested model is not found in the custom provider.
4575
+ * @returns {Provider} A Provider object with languageModel, textEmbeddingModel, imageModel, transcriptionModel, and speechModel methods.
4576
+ *
4577
+ * @throws {NoSuchModelError} Throws when a requested model is not found and no fallback provider is available.
4578
+ */
4579
+ declare function customProvider<LANGUAGE_MODELS extends Record<string, LanguageModelV3>, EMBEDDING_MODELS extends Record<string, EmbeddingModelV3<string>>, IMAGE_MODELS extends Record<string, ImageModelV3>, TRANSCRIPTION_MODELS extends Record<string, TranscriptionModelV3>, SPEECH_MODELS extends Record<string, SpeechModelV3>>({ languageModels, textEmbeddingModels, imageModels, transcriptionModels, speechModels, fallbackProvider, }: {
4580
+ languageModels?: LANGUAGE_MODELS;
4581
+ textEmbeddingModels?: EMBEDDING_MODELS;
4582
+ imageModels?: IMAGE_MODELS;
4583
+ transcriptionModels?: TRANSCRIPTION_MODELS;
4584
+ speechModels?: SPEECH_MODELS;
4585
+ fallbackProvider?: ProviderV3 | ProviderV2;
4586
+ }): ProviderV3 & {
4587
+ languageModel(modelId: ExtractModelId<LANGUAGE_MODELS>): LanguageModelV3;
4588
+ textEmbeddingModel(modelId: ExtractModelId<EMBEDDING_MODELS>): EmbeddingModelV3<string>;
4589
+ imageModel(modelId: ExtractModelId<IMAGE_MODELS>): ImageModelV3;
4590
+ transcriptionModel(modelId: ExtractModelId<TRANSCRIPTION_MODELS>): TranscriptionModelV3;
4591
+ speechModel(modelId: ExtractModelId<SPEECH_MODELS>): SpeechModelV3;
4592
+ };
4593
+ /**
4594
+ * @deprecated Use `customProvider` instead.
4595
+ */
4596
+ declare const experimental_customProvider: typeof customProvider;
4597
+ type ExtractModelId<MODELS extends Record<string, unknown>> = Extract<keyof MODELS, string>;
4598
+
4599
+ declare const symbol: unique symbol;
4600
+ declare class NoSuchProviderError extends NoSuchModelError {
4601
+ private readonly [symbol];
4602
+ readonly providerId: string;
4603
+ readonly availableProviders: string[];
4604
+ constructor({ modelId, modelType, providerId, availableProviders, message, }: {
4605
+ modelId: string;
4606
+ modelType: 'languageModel' | 'textEmbeddingModel' | 'imageModel' | 'transcriptionModel' | 'speechModel';
4607
+ providerId: string;
4608
+ availableProviders: string[];
4609
+ message?: string;
4610
+ });
4611
+ static isInstance(error: unknown): error is NoSuchProviderError;
4612
+ }
4613
+
4614
+ type ExtractLiteralUnion<T> = T extends string ? string extends T ? never : T : never;
4615
+ interface ProviderRegistryProvider<PROVIDERS extends Record<string, ProviderV3> = Record<string, ProviderV3>, SEPARATOR extends string = ':'> {
4616
+ languageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['languageModel']>>[0]>}` : never): LanguageModelV3;
4617
+ languageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): LanguageModelV3;
4618
+ textEmbeddingModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['textEmbeddingModel']>>[0]>}` : never): EmbeddingModelV3<string>;
4619
+ textEmbeddingModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): EmbeddingModelV3<string>;
4620
+ imageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['imageModel']>>[0]>}` : never): ImageModelV3;
4621
+ imageModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): ImageModelV3;
4622
+ transcriptionModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['transcriptionModel']>>[0]>}` : never): TranscriptionModelV3;
4623
+ transcriptionModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): TranscriptionModelV3;
4624
+ speechModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion<Parameters<NonNullable<PROVIDERS[KEY]['speechModel']>>[0]>}` : never): SpeechModelV3;
4625
+ speechModel<KEY extends keyof PROVIDERS>(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): SpeechModelV3;
4626
+ }
4627
+ /**
4628
+ * Creates a registry for the given providers with optional middleware functionality.
4629
+ * This function allows you to register multiple providers and optionally apply middleware
4630
+ * to all language models from the registry, enabling you to transform parameters, wrap generate
4631
+ * operations, and wrap stream operations for every language model accessed through the registry.
4632
+ *
4633
+ * @param providers - A record of provider instances to be registered in the registry.
4634
+ * @param options - Configuration options for the provider registry.
4635
+ * @param options.separator - The separator used between provider ID and model ID in the combined identifier. Defaults to ':'.
4636
+ * @param options.languageModelMiddleware - Optional middleware to be applied to all language models from the registry. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model.
4637
+ * @returns A new ProviderRegistryProvider instance that provides access to all registered providers with optional middleware applied to language models.
4638
+ */
4639
+ declare function createProviderRegistry<PROVIDERS extends Record<string, ProviderV3>, SEPARATOR extends string = ':'>(providers: PROVIDERS, { separator, languageModelMiddleware, }?: {
4640
+ separator?: SEPARATOR;
4641
+ languageModelMiddleware?: LanguageModelMiddleware | LanguageModelMiddleware[];
4642
+ }): ProviderRegistryProvider<PROVIDERS, SEPARATOR>;
4643
+ /**
4644
+ * @deprecated Use `createProviderRegistry` instead.
4645
+ */
4646
+ declare const experimental_createProviderRegistry: typeof createProviderRegistry;
4647
+
4648
+ declare function createTextStreamResponse({ status, statusText, headers, textStream, }: ResponseInit & {
4649
+ textStream: ReadableStream<string>;
4650
+ }): Response;
4651
+
4652
+ declare function pipeTextStreamToResponse({ response, status, statusText, headers, textStream, }: {
4653
+ response: ServerResponse;
4654
+ textStream: ReadableStream<string>;
4655
+ } & ResponseInit): void;
4656
+
4657
+ declare const JSONRPCRequestSchema: z.ZodObject<{
4658
+ jsonrpc: z.ZodLiteral<"2.0">;
4659
+ id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
4660
+ method: z.ZodString;
4661
+ params: z.ZodOptional<z.ZodObject<{
4662
+ _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4663
+ }, z.core.$loose>>;
4664
+ }, z.core.$strict>;
4665
+ type JSONRPCRequest = z.infer<typeof JSONRPCRequestSchema>;
4666
+ declare const JSONRPCResponseSchema: z.ZodObject<{
4667
+ jsonrpc: z.ZodLiteral<"2.0">;
4668
+ id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
4669
+ result: z.ZodObject<{
4670
+ _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4671
+ }, z.core.$loose>;
4672
+ }, z.core.$strict>;
4673
+ type JSONRPCResponse = z.infer<typeof JSONRPCResponseSchema>;
4674
+ declare const JSONRPCErrorSchema: z.ZodObject<{
4675
+ jsonrpc: z.ZodLiteral<"2.0">;
4676
+ id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
4677
+ error: z.ZodObject<{
4678
+ code: z.ZodNumber;
4679
+ message: z.ZodString;
4680
+ data: z.ZodOptional<z.ZodUnknown>;
4681
+ }, z.core.$strip>;
4682
+ }, z.core.$strict>;
4683
+ type JSONRPCError = z.infer<typeof JSONRPCErrorSchema>;
4684
+ declare const JSONRPCNotificationSchema: z.ZodObject<{
4685
+ jsonrpc: z.ZodLiteral<"2.0">;
4686
+ method: z.ZodString;
4687
+ params: z.ZodOptional<z.ZodObject<{
4688
+ _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4689
+ }, z.core.$loose>>;
4690
+ }, z.core.$strict>;
4691
+ type JSONRPCNotification = z.infer<typeof JSONRPCNotificationSchema>;
4692
+ declare const JSONRPCMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
4693
+ jsonrpc: z.ZodLiteral<"2.0">;
4694
+ id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
4695
+ method: z.ZodString;
4696
+ params: z.ZodOptional<z.ZodObject<{
4697
+ _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4698
+ }, z.core.$loose>>;
4699
+ }, z.core.$strict>, z.ZodObject<{
4700
+ jsonrpc: z.ZodLiteral<"2.0">;
4701
+ method: z.ZodString;
4702
+ params: z.ZodOptional<z.ZodObject<{
4703
+ _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4704
+ }, z.core.$loose>>;
4705
+ }, z.core.$strict>, z.ZodObject<{
4706
+ jsonrpc: z.ZodLiteral<"2.0">;
4707
+ id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
4708
+ result: z.ZodObject<{
4709
+ _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4710
+ }, z.core.$loose>;
4711
+ }, z.core.$strict>, z.ZodObject<{
4712
+ jsonrpc: z.ZodLiteral<"2.0">;
4713
+ id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
4714
+ error: z.ZodObject<{
4715
+ code: z.ZodNumber;
4716
+ message: z.ZodString;
4717
+ data: z.ZodOptional<z.ZodUnknown>;
4718
+ }, z.core.$strip>;
4719
+ }, z.core.$strict>]>;
4720
+ type JSONRPCMessage = z.infer<typeof JSONRPCMessageSchema>;
4721
+
4722
+ /**
4723
+ * Transport interface for MCP (Model Context Protocol) communication.
4724
+ * Maps to the `Transport` interface in the MCP spec.
4725
+ */
4726
+ interface MCPTransport {
4493
4727
  /**
4494
- * A unique identifier for the chat. If not provided, a random one will be
4495
- * generated.
4728
+ * Initialize and start the transport
4496
4729
  */
4497
- id?: string;
4498
- messageMetadataSchema?: FlexibleSchema<InferUIMessageMetadata<UI_MESSAGE>>;
4499
- dataPartSchemas?: UIDataTypesToSchemas<InferUIMessageData<UI_MESSAGE>>;
4500
- messages?: UI_MESSAGE[];
4730
+ start(): Promise<void>;
4501
4731
  /**
4502
- * A way to provide a function that is going to be used for ids for messages and the chat.
4503
- * If not provided the default AI SDK `generateId` is used.
4732
+ * Send a JSON-RPC message through the transport
4733
+ * @param message The JSON-RPC message to send
4504
4734
  */
4505
- generateId?: IdGenerator;
4506
- transport?: ChatTransport<UI_MESSAGE>;
4735
+ send(message: JSONRPCMessage): Promise<void>;
4507
4736
  /**
4508
- * Callback function to be called when an error is encountered.
4737
+ * Clean up and close the transport
4509
4738
  */
4510
- onError?: ChatOnErrorCallback;
4511
- /**
4512
- Optional callback function that is invoked when a tool call is received.
4513
- Intended for automatic client-side tool execution.
4514
-
4515
- You can optionally return a result for the tool call,
4516
- either synchronously or asynchronously.
4517
- */
4518
- onToolCall?: ChatOnToolCallCallback<UI_MESSAGE>;
4739
+ close(): Promise<void>;
4519
4740
  /**
4520
- * Function that is called when the assistant response has finished streaming.
4741
+ * Event handler for transport closure
4521
4742
  */
4522
- onFinish?: ChatOnFinishCallback<UI_MESSAGE>;
4743
+ onclose?: () => void;
4523
4744
  /**
4524
- * Optional callback function that is called when a data part is received.
4525
- *
4526
- * @param data The data part that was received.
4745
+ * Event handler for transport errors
4527
4746
  */
4528
- onData?: ChatOnDataCallback<UI_MESSAGE>;
4747
+ onerror?: (error: Error) => void;
4529
4748
  /**
4530
- * When provided, this function will be called when the stream is finished or a tool call is added
4531
- * to determine if the current messages should be resubmitted.
4749
+ * Event handler for received messages
4532
4750
  */
4533
- sendAutomaticallyWhen?: (options: {
4534
- messages: UI_MESSAGE[];
4535
- }) => boolean | PromiseLike<boolean>;
4751
+ onmessage?: (message: JSONRPCMessage) => void;
4536
4752
  }
4537
- declare abstract class AbstractChat<UI_MESSAGE extends UIMessage> {
4538
- readonly id: string;
4539
- readonly generateId: IdGenerator;
4540
- protected state: ChatState<UI_MESSAGE>;
4541
- private messageMetadataSchema;
4542
- private dataPartSchemas;
4543
- private readonly transport;
4544
- private onError?;
4545
- private onToolCall?;
4546
- private onFinish?;
4547
- private onData?;
4548
- private sendAutomaticallyWhen?;
4549
- private activeResponse;
4550
- private jobExecutor;
4551
- constructor({ generateId, id, transport, messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen, }: Omit<ChatInit<UI_MESSAGE>, 'messages'> & {
4552
- state: ChatState<UI_MESSAGE>;
4553
- });
4554
- /**
4555
- * Hook status:
4556
- *
4557
- * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
4558
- * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
4559
- * - `ready`: The full response has been received and processed; a new user message can be submitted.
4560
- * - `error`: An error occurred during the API request, preventing successful completion.
4561
- */
4562
- get status(): ChatStatus;
4563
- protected setStatus({ status, error, }: {
4564
- status: ChatStatus;
4565
- error?: Error;
4566
- }): void;
4567
- get error(): Error | undefined;
4568
- get messages(): UI_MESSAGE[];
4569
- get lastMessage(): UI_MESSAGE | undefined;
4570
- set messages(messages: UI_MESSAGE[]);
4571
- /**
4572
- * Appends or replaces a user message to the chat list. This triggers the API call to fetch
4573
- * the assistant's response.
4574
- *
4575
- * If a messageId is provided, the message will be replaced.
4576
- */
4577
- sendMessage: (message?: (CreateUIMessage<UI_MESSAGE> & {
4578
- text?: never;
4579
- files?: never;
4580
- messageId?: string;
4581
- }) | {
4582
- text: string;
4583
- files?: FileList | FileUIPart[];
4584
- metadata?: InferUIMessageMetadata<UI_MESSAGE>;
4585
- parts?: never;
4586
- messageId?: string;
4587
- } | {
4588
- files: FileList | FileUIPart[];
4589
- metadata?: InferUIMessageMetadata<UI_MESSAGE>;
4590
- parts?: never;
4591
- messageId?: string;
4592
- }, options?: ChatRequestOptions) => Promise<void>;
4593
- /**
4594
- * Regenerate the assistant message with the provided message id.
4595
- * If no message id is provided, the last assistant message will be regenerated.
4596
- */
4597
- regenerate: ({ messageId, ...options }?: {
4598
- messageId?: string;
4599
- } & ChatRequestOptions) => Promise<void>;
4600
- /**
4601
- * Attempt to resume an ongoing streaming response.
4602
- */
4603
- resumeStream: (options?: ChatRequestOptions) => Promise<void>;
4753
+ type MCPTransportConfig = {
4754
+ type: 'sse';
4604
4755
  /**
4605
- * Clear the error state and set the status to ready if the chat is in an error state.
4756
+ * The URL of the MCP server.
4606
4757
  */
4607
- clearError: () => void;
4608
- addToolApprovalResponse: ChatAddToolApproveResponseFunction;
4609
- addToolResult: <TOOL extends keyof InferUIMessageTools<UI_MESSAGE>>({ state, tool, toolCallId, output, errorText, }: {
4610
- state?: "output-available";
4611
- tool: TOOL;
4612
- toolCallId: string;
4613
- output: InferUIMessageTools<UI_MESSAGE>[TOOL]["output"];
4614
- errorText?: never;
4615
- } | {
4616
- state: "output-error";
4617
- tool: TOOL;
4618
- toolCallId: string;
4619
- output?: never;
4620
- errorText: string;
4621
- }) => Promise<void>;
4758
+ url: string;
4622
4759
  /**
4623
- * Abort the current request immediately, keep the generated tokens if any.
4760
+ * Additional HTTP headers to be sent with requests.
4624
4761
  */
4625
- stop: () => Promise<void>;
4626
- private makeRequest;
4627
- }
4628
-
4629
- declare function convertFileListToFileUIParts(files: FileList | undefined): Promise<Array<FileUIPart>>;
4630
-
4631
- /**
4632
- Converts an array of UI messages from useChat into an array of ModelMessages that can be used
4633
- with the AI functions (e.g. `streamText`, `generateText`).
4762
+ headers?: Record<string, string>;
4763
+ };
4634
4764
 
4635
- @param messages - The UI messages to convert.
4636
- @param options.tools - The tools to use.
4637
- @param options.ignoreIncompleteToolCalls - Whether to ignore incomplete tool calls. Default is `false`.
4765
+ type ToolSchemas = Record<string, {
4766
+ inputSchema: FlexibleSchema<JSONObject | unknown>;
4767
+ }> | 'automatic' | undefined;
4768
+ type McpToolSet<TOOL_SCHEMAS extends ToolSchemas = 'automatic'> = TOOL_SCHEMAS extends Record<string, {
4769
+ inputSchema: FlexibleSchema<any>;
4770
+ }> ? {
4771
+ [K in keyof TOOL_SCHEMAS]: TOOL_SCHEMAS[K] extends {
4772
+ inputSchema: FlexibleSchema<infer INPUT>;
4773
+ } ? Tool<INPUT, CallToolResult> & Required<Pick<Tool<INPUT, CallToolResult>, 'execute'>> : never;
4774
+ } : McpToolSet<Record<string, {
4775
+ inputSchema: FlexibleSchema<unknown>;
4776
+ }>>;
4777
+ declare const CallToolResultSchema: z.ZodUnion<[z.ZodObject<{
4778
+ _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4779
+ content: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
4780
+ type: z.ZodLiteral<"text">;
4781
+ text: z.ZodString;
4782
+ }, z.core.$loose>, z.ZodObject<{
4783
+ type: z.ZodLiteral<"image">;
4784
+ data: z.ZodBase64;
4785
+ mimeType: z.ZodString;
4786
+ }, z.core.$loose>, z.ZodObject<{
4787
+ type: z.ZodLiteral<"resource">;
4788
+ resource: z.ZodUnion<readonly [z.ZodObject<{
4789
+ uri: z.ZodString;
4790
+ mimeType: z.ZodOptional<z.ZodString>;
4791
+ text: z.ZodString;
4792
+ }, z.core.$loose>, z.ZodObject<{
4793
+ uri: z.ZodString;
4794
+ mimeType: z.ZodOptional<z.ZodString>;
4795
+ blob: z.ZodBase64;
4796
+ }, z.core.$loose>]>;
4797
+ }, z.core.$loose>]>>;
4798
+ isError: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
4799
+ }, z.core.$loose>, z.ZodObject<{
4800
+ _meta: z.ZodOptional<z.ZodObject<{}, z.core.$loose>>;
4801
+ toolResult: z.ZodUnknown;
4802
+ }, z.core.$loose>]>;
4803
+ type CallToolResult = z.infer<typeof CallToolResultSchema>;
4638
4804
 
4639
- @returns An array of ModelMessages.
4640
- */
4641
- declare function convertToModelMessages(messages: Array<Omit<UIMessage, 'id'>>, options?: {
4642
- tools?: ToolSet;
4643
- ignoreIncompleteToolCalls?: boolean;
4644
- }): ModelMessage[];
4645
- /**
4646
- @deprecated Use `convertToModelMessages` instead.
4647
- */
4648
- declare const convertToCoreMessages: typeof convertToModelMessages;
4805
+ interface MCPClientConfig {
4806
+ /** Transport configuration for connecting to the MCP server */
4807
+ transport: MCPTransportConfig | MCPTransport;
4808
+ /** Optional callback for uncaught errors */
4809
+ onUncaughtError?: (error: unknown) => void;
4810
+ /** Optional client name, defaults to 'ai-sdk-mcp-client' */
4811
+ name?: string;
4812
+ }
4813
+ declare function createMCPClient(config: MCPClientConfig): Promise<MCPClient>;
4814
+ interface MCPClient {
4815
+ tools<TOOL_SCHEMAS extends ToolSchemas = 'automatic'>(options?: {
4816
+ schemas?: TOOL_SCHEMAS;
4817
+ }): Promise<McpToolSet<TOOL_SCHEMAS>>;
4818
+ close: () => Promise<void>;
4819
+ }
4649
4820
 
4650
- type PrepareSendMessagesRequest<UI_MESSAGE extends UIMessage> = (options: {
4651
- id: string;
4652
- messages: UI_MESSAGE[];
4653
- requestMetadata: unknown;
4654
- body: Record<string, any> | undefined;
4655
- credentials: RequestCredentials | undefined;
4656
- headers: HeadersInit | undefined;
4657
- api: string;
4658
- } & {
4659
- trigger: 'submit-message' | 'regenerate-message';
4660
- messageId: string | undefined;
4661
- }) => {
4662
- body: object;
4663
- headers?: HeadersInit;
4664
- credentials?: RequestCredentials;
4665
- api?: string;
4666
- } | PromiseLike<{
4667
- body: object;
4668
- headers?: HeadersInit;
4669
- credentials?: RequestCredentials;
4670
- api?: string;
4671
- }>;
4672
- type PrepareReconnectToStreamRequest = (options: {
4673
- id: string;
4674
- requestMetadata: unknown;
4675
- body: Record<string, any> | undefined;
4676
- credentials: RequestCredentials | undefined;
4677
- headers: HeadersInit | undefined;
4678
- api: string;
4679
- }) => {
4680
- headers?: HeadersInit;
4681
- credentials?: RequestCredentials;
4682
- api?: string;
4683
- } | PromiseLike<{
4684
- headers?: HeadersInit;
4685
- credentials?: RequestCredentials;
4686
- api?: string;
4687
- }>;
4688
4821
  /**
4689
- * Options for the `HttpChatTransport` class.
4690
- *
4691
- * @param UI_MESSAGE - The type of message to be used in the chat.
4822
+ The result of a `transcribe` call.
4823
+ It contains the transcript and additional information.
4692
4824
  */
4693
- type HttpChatTransportInitOptions<UI_MESSAGE extends UIMessage> = {
4825
+ interface TranscriptionResult {
4694
4826
  /**
4695
- * The API URL to be used for the chat transport.
4696
- * Defaults to '/api/chat'.
4827
+ * The complete transcribed text from the audio.
4697
4828
  */
4698
- api?: string;
4829
+ readonly text: string;
4699
4830
  /**
4700
- * The credentials mode to be used for the fetch request.
4701
- * Possible values are: 'omit', 'same-origin', 'include'.
4702
- * Defaults to 'same-origin'.
4831
+ * Array of transcript segments with timing information.
4832
+ * Each segment represents a portion of the transcribed text with start and end times.
4703
4833
  */
4704
- credentials?: Resolvable<RequestCredentials>;
4834
+ readonly segments: Array<{
4835
+ /**
4836
+ * The text content of this segment.
4837
+ */
4838
+ readonly text: string;
4839
+ /**
4840
+ * The start time of this segment in seconds.
4841
+ */
4842
+ readonly startSecond: number;
4843
+ /**
4844
+ * The end time of this segment in seconds.
4845
+ */
4846
+ readonly endSecond: number;
4847
+ }>;
4705
4848
  /**
4706
- * HTTP headers to be sent with the API request.
4849
+ * The detected language of the audio content, as an ISO-639-1 code (e.g., 'en' for English).
4850
+ * May be undefined if the language couldn't be detected.
4707
4851
  */
4708
- headers?: Resolvable<Record<string, string> | Headers>;
4852
+ readonly language: string | undefined;
4709
4853
  /**
4710
- * Extra body object to be sent with the API request.
4711
- * @example
4712
- * Send a `sessionId` to the API along with the messages.
4713
- * ```js
4714
- * useChat({
4715
- * body: {
4716
- * sessionId: '123',
4717
- * }
4718
- * })
4719
- * ```
4854
+ * The total duration of the audio file in seconds.
4855
+ * May be undefined if the duration couldn't be determined.
4720
4856
  */
4721
- body?: Resolvable<object>;
4857
+ readonly durationInSeconds: number | undefined;
4722
4858
  /**
4723
- Custom fetch implementation. You can use it as a middleware to intercept requests,
4724
- or to provide a custom fetch implementation for e.g. testing.
4725
- */
4726
- fetch?: FetchFunction;
4859
+ Warnings for the call, e.g. unsupported settings.
4860
+ */
4861
+ readonly warnings: Array<TranscriptionWarning>;
4727
4862
  /**
4728
- * When a function is provided, it will be used
4729
- * to prepare the request body for the chat API. This can be useful for
4730
- * customizing the request body based on the messages and data in the chat.
4731
- *
4732
- * @param id The id of the chat.
4733
- * @param messages The current messages in the chat.
4734
- * @param requestBody The request body object passed in the chat request.
4863
+ Response metadata from the provider. There may be multiple responses if we made multiple calls to the model.
4735
4864
  */
4736
- prepareSendMessagesRequest?: PrepareSendMessagesRequest<UI_MESSAGE>;
4865
+ readonly responses: Array<TranscriptionModelResponseMetadata>;
4737
4866
  /**
4738
- * When a function is provided, it will be used
4739
- * to prepare the request body for the chat API. This can be useful for
4740
- * customizing the request body based on the messages and data in the chat.
4741
- *
4742
- * @param id The id of the chat.
4743
- * @param messages The current messages in the chat.
4744
- * @param requestBody The request body object passed in the chat request.
4867
+ Provider metadata from the provider.
4745
4868
  */
4746
- prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest;
4747
- };
4748
- declare abstract class HttpChatTransport<UI_MESSAGE extends UIMessage> implements ChatTransport<UI_MESSAGE> {
4749
- protected api: string;
4750
- protected credentials: HttpChatTransportInitOptions<UI_MESSAGE>['credentials'];
4751
- protected headers: HttpChatTransportInitOptions<UI_MESSAGE>['headers'];
4752
- protected body: HttpChatTransportInitOptions<UI_MESSAGE>['body'];
4753
- protected fetch?: FetchFunction;
4754
- protected prepareSendMessagesRequest?: PrepareSendMessagesRequest<UI_MESSAGE>;
4755
- protected prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest;
4756
- constructor({ api, credentials, headers, body, fetch, prepareSendMessagesRequest, prepareReconnectToStreamRequest, }: HttpChatTransportInitOptions<UI_MESSAGE>);
4757
- sendMessages({ abortSignal, ...options }: Parameters<ChatTransport<UI_MESSAGE>['sendMessages']>[0]): Promise<ReadableStream<UIMessageChunk>>;
4758
- reconnectToStream(options: Parameters<ChatTransport<UI_MESSAGE>['reconnectToStream']>[0]): Promise<ReadableStream<UIMessageChunk> | null>;
4759
- protected abstract processResponseStream(stream: ReadableStream<Uint8Array<ArrayBufferLike>>): ReadableStream<UIMessageChunk>;
4760
- }
4761
-
4762
- declare class DefaultChatTransport<UI_MESSAGE extends UIMessage> extends HttpChatTransport<UI_MESSAGE> {
4763
- constructor(options?: HttpChatTransportInitOptions<UI_MESSAGE>);
4764
- protected processResponseStream(stream: ReadableStream<Uint8Array<ArrayBufferLike>>): ReadableStream<UIMessageChunk>;
4869
+ readonly providerMetadata: Record<string, Record<string, JSONValue$1>>;
4765
4870
  }
4766
4871
 
4767
4872
  /**
4768
- Check if the last message is an assistant message with completed tool call approvals.
4769
- The last step of the message must have at least one tool approval response and
4770
- all tool approvals must have a response.
4771
- */
4772
- declare function lastAssistantMessageIsCompleteWithApprovalResponses({ messages, }: {
4773
- messages: UIMessage[];
4774
- }): boolean;
4775
-
4776
- /**
4777
- Check if the message is an assistant message with completed tool calls.
4778
- The last step of the message must have at least one tool invocation and
4779
- all tool invocations must have a result.
4780
- */
4781
- declare function lastAssistantMessageIsCompleteWithToolCalls({ messages, }: {
4782
- messages: UIMessage[];
4783
- }): boolean;
4873
+ Generates transcripts using a transcription model.
4784
4874
 
4785
- declare class TextStreamChatTransport<UI_MESSAGE extends UIMessage> extends HttpChatTransport<UI_MESSAGE> {
4786
- constructor(options?: HttpChatTransportInitOptions<UI_MESSAGE>);
4787
- protected processResponseStream(stream: ReadableStream<Uint8Array<ArrayBufferLike>>): ReadableStream<UIMessageChunk>;
4788
- }
4875
+ @param model - The transcription model to use.
4876
+ @param audio - The audio data to transcribe as DataContent (string | Uint8Array | ArrayBuffer | Buffer) or a URL.
4877
+ @param providerOptions - Additional provider-specific options that are passed through to the provider
4878
+ as body parameters.
4879
+ @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
4880
+ @param abortSignal - An optional abort signal that can be used to cancel the call.
4881
+ @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
4789
4882
 
4790
- type CompletionRequestOptions = {
4791
- /**
4792
- An optional object of headers to be passed to the API endpoint.
4793
- */
4794
- headers?: Record<string, string> | Headers;
4883
+ @returns A result object that contains the generated transcript.
4884
+ */
4885
+ declare function transcribe({ model, audio, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, }: {
4795
4886
  /**
4796
- An optional object to be passed to the API endpoint.
4887
+ The transcription model to use.
4797
4888
  */
4798
- body?: object;
4799
- };
4800
- type UseCompletionOptions = {
4801
- /**
4802
- * The API endpoint that accepts a `{ prompt: string }` object and returns
4803
- * a stream of tokens of the AI completion response. Defaults to `/api/completion`.
4804
- */
4805
- api?: string;
4806
- /**
4807
- * An unique identifier for the chat. If not provided, a random one will be
4808
- * generated. When provided, the `useChat` hook with the same `id` will
4809
- * have shared states across components.
4810
- */
4811
- id?: string;
4812
- /**
4813
- * Initial prompt input of the completion.
4814
- */
4815
- initialInput?: string;
4816
- /**
4817
- * Initial completion result. Useful to load an existing history.
4818
- */
4819
- initialCompletion?: string;
4820
- /**
4821
- * Callback function to be called when the completion is finished streaming.
4822
- */
4823
- onFinish?: (prompt: string, completion: string) => void;
4824
- /**
4825
- * Callback function to be called when an error is encountered.
4826
- */
4827
- onError?: (error: Error) => void;
4889
+ model: TranscriptionModel;
4828
4890
  /**
4829
- * The credentials mode to be used for the fetch request.
4830
- * Possible values are: 'omit', 'same-origin', 'include'.
4831
- * Defaults to 'same-origin'.
4891
+ The audio data to transcribe.
4832
4892
  */
4833
- credentials?: RequestCredentials;
4893
+ audio: DataContent | URL;
4834
4894
  /**
4835
- * HTTP headers to be sent with the API request.
4836
- */
4837
- headers?: Record<string, string> | Headers;
4895
+ Additional provider-specific options that are passed through to the provider
4896
+ as body parameters.
4897
+
4898
+ The outer record is keyed by the provider name, and the inner
4899
+ record is keyed by the provider-specific metadata key.
4900
+ ```ts
4901
+ {
4902
+ "openai": {
4903
+ "temperature": 0
4904
+ }
4905
+ }
4906
+ ```
4907
+ */
4908
+ providerOptions?: ProviderOptions;
4838
4909
  /**
4839
- * Extra body object to be sent with the API request.
4840
- * @example
4841
- * Send a `sessionId` to the API along with the prompt.
4842
- * ```js
4843
- * useChat({
4844
- * body: {
4845
- * sessionId: '123',
4846
- * }
4847
- * })
4848
- * ```
4910
+ Maximum number of retries per transcript model call. Set to 0 to disable retries.
4911
+
4912
+ @default 2
4849
4913
  */
4850
- body?: object;
4914
+ maxRetries?: number;
4851
4915
  /**
4852
- Streaming protocol that is used. Defaults to `data`.
4853
- */
4854
- streamProtocol?: 'data' | 'text';
4916
+ Abort signal.
4917
+ */
4918
+ abortSignal?: AbortSignal;
4855
4919
  /**
4856
- Custom fetch implementation. You can use it as a middleware to intercept requests,
4857
- or to provide a custom fetch implementation for e.g. testing.
4858
- */
4859
- fetch?: FetchFunction;
4860
- };
4861
-
4862
- type SafeValidateUIMessagesResult<UI_MESSAGE extends UIMessage> = {
4863
- success: true;
4864
- data: Array<UI_MESSAGE>;
4865
- } | {
4866
- success: false;
4867
- error: Error;
4868
- };
4869
- /**
4870
- * Validates a list of UI messages like `validateUIMessages`,
4871
- * but instead of throwing it returns `{ success: true, data }`
4872
- * or `{ success: false, error }`.
4873
- */
4874
- declare function safeValidateUIMessages<UI_MESSAGE extends UIMessage>({ messages, metadataSchema, dataSchemas, tools, }: {
4875
- messages: unknown;
4876
- metadataSchema?: FlexibleSchema<UIMessage['metadata']>;
4877
- dataSchemas?: {
4878
- [NAME in keyof InferUIMessageData<UI_MESSAGE> & string]?: FlexibleSchema<InferUIMessageData<UI_MESSAGE>[NAME]>;
4879
- };
4880
- tools?: {
4881
- [NAME in keyof InferUIMessageTools<UI_MESSAGE> & string]?: Tool<InferUIMessageTools<UI_MESSAGE>[NAME]['input'], InferUIMessageTools<UI_MESSAGE>[NAME]['output']>;
4882
- };
4883
- }): Promise<SafeValidateUIMessagesResult<UI_MESSAGE>>;
4884
- /**
4885
- * Validates a list of UI messages.
4886
- *
4887
- * Metadata, data parts, and generic tool call structures are only validated if
4888
- * the corresponding schemas are provided. Otherwise, they are assumed to be
4889
- * valid.
4890
- */
4891
- declare function validateUIMessages<UI_MESSAGE extends UIMessage>({ messages, metadataSchema, dataSchemas, tools, }: {
4892
- messages: unknown;
4893
- metadataSchema?: FlexibleSchema<UIMessage['metadata']>;
4894
- dataSchemas?: {
4895
- [NAME in keyof InferUIMessageData<UI_MESSAGE> & string]?: FlexibleSchema<InferUIMessageData<UI_MESSAGE>[NAME]>;
4896
- };
4897
- tools?: {
4898
- [NAME in keyof InferUIMessageTools<UI_MESSAGE> & string]?: Tool<InferUIMessageTools<UI_MESSAGE>[NAME]['input'], InferUIMessageTools<UI_MESSAGE>[NAME]['output']>;
4899
- };
4900
- }): Promise<Array<UI_MESSAGE>>;
4920
+ Additional headers to include in the request.
4921
+ Only applicable for HTTP-based providers.
4922
+ */
4923
+ headers?: Record<string, string>;
4924
+ }): Promise<TranscriptionResult>;
4901
4925
 
4902
4926
  declare global {
4903
4927
  /**
@@ -4919,4 +4943,4 @@ declare global {
4919
4943
  var AI_SDK_LOG_WARNINGS: LogWarningsFunction | undefined | false;
4920
4944
  }
4921
4945
 
4922
- export { AbstractChat, Agent, AsyncIterableStream, CallSettings, CallWarning, ChatAddToolApproveResponseFunction, ChatInit, ChatOnDataCallback, ChatOnErrorCallback, ChatOnFinishCallback, ChatOnToolCallCallback, ChatRequestOptions, ChatState, ChatStatus, ChatTransport, ChunkDetector, CompletionRequestOptions, CoreAssistantMessage, CoreMessage, CoreSystemMessage, CoreToolMessage, CoreUserMessage, CreateUIMessage, DataUIPart, DeepPartial, DefaultChatTransport, DownloadError, DynamicToolCall, DynamicToolError, DynamicToolResult, DynamicToolUIPart, EmbedManyResult, EmbedResult, Embedding, EmbeddingModel, EmbeddingModelUsage, ErrorHandler, ToolLoopAgent as Experimental_Agent, ToolLoopAgentSettings as Experimental_AgentSettings, DownloadFunction as Experimental_DownloadFunction, GenerateImageResult as Experimental_GenerateImageResult, GeneratedFile as Experimental_GeneratedImage, InferAgentUIMessage as Experimental_InferAgentUIMessage, LogWarningsFunction as Experimental_LogWarningsFunction, SpeechResult as Experimental_SpeechResult, TranscriptionResult as Experimental_TranscriptionResult, Warning as Experimental_Warning, FileUIPart, FinishReason, GenerateObjectResult, GenerateTextOnFinishCallback, GenerateTextOnStepFinishCallback, GenerateTextResult, GeneratedAudioFile, GeneratedFile, HttpChatTransport, HttpChatTransportInitOptions, ImageModel, ImageGenerationWarning as ImageModelCallWarning, ImageModelProviderMetadata, ImageModelResponseMetadata, InferAgentUIMessage, InferUIDataParts, InferUIMessageChunk, InferUITool, InferUITools, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidStreamPartError, InvalidToolInputError, JSONRPCError, JSONRPCMessage, JSONRPCNotification, JSONRPCRequest, JSONRPCResponse, JSONValue, JsonToSseTransformStream, LanguageModel, LanguageModelMiddleware, LanguageModelRequestMetadata, LanguageModelResponseMetadata, LanguageModelUsage, MCPClientError, MCPTransport, MessageConversionError, NoImageGeneratedError, NoObjectGeneratedError, NoOutputGeneratedError, NoOutputSpecifiedError, NoSpeechGeneratedError, NoSuchProviderError, NoSuchToolError, ObjectStreamPart, output as Output, PrepareReconnectToStreamRequest, PrepareSendMessagesRequest, PrepareStepFunction, PrepareStepResult, Prompt, Provider, ProviderMetadata, ProviderRegistryProvider, ReasoningOutput, ReasoningUIPart, RepairTextFunction, RetryError, SafeValidateUIMessagesResult, SerialJobExecutor, SourceDocumentUIPart, SourceUrlUIPart, SpeechModel, SpeechModelResponseMetadata, SpeechWarning, StaticToolCall, StaticToolError, StaticToolOutputDenied, StaticToolResult, StepResult, StepStartUIPart, StopCondition, StreamObjectOnFinishCallback, StreamObjectResult, StreamTextOnChunkCallback, StreamTextOnErrorCallback, StreamTextOnFinishCallback, StreamTextOnStepFinishCallback, StreamTextResult, StreamTextTransform, TelemetrySettings, TextStreamChatTransport, TextStreamPart, TextUIPart, ToolApprovalRequestOutput, ToolCallRepairError, ToolCallRepairFunction, ToolChoice, ToolLoopAgent, ToolLoopAgentOnFinishCallback, ToolLoopAgentOnStepFinishCallback, ToolLoopAgentSettings, ToolSet, ToolUIPart, TranscriptionModel, TranscriptionModelResponseMetadata, TranscriptionWarning, TypedToolCall, TypedToolError, TypedToolOutputDenied, TypedToolResult, UIDataPartSchemas, UIDataTypes, UIMessage, UIMessageChunk, UIMessagePart, UIMessageStreamOnFinishCallback, UIMessageStreamOptions, UIMessageStreamWriter, UITool, UIToolInvocation, UITools, UI_MESSAGE_STREAM_HEADERS, UnsupportedModelVersionError, UseCompletionOptions, assistantModelMessageSchema, callCompletionApi, consumeStream, convertFileListToFileUIParts, convertToCoreMessages, convertToModelMessages, coreAssistantMessageSchema, coreMessageSchema, coreSystemMessageSchema, coreToolMessageSchema, coreUserMessageSchema, cosineSimilarity, createAgentStreamResponse, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, defaultSettingsMiddleware, embed, embedMany, MCPClient as experimental_MCPClient, MCPClientConfig as experimental_MCPClientConfig, createMCPClient as experimental_createMCPClient, experimental_createProviderRegistry, experimental_customProvider, generateImage as experimental_generateImage, generateSpeech as experimental_generateSpeech, transcribe as experimental_transcribe, extractReasoningMiddleware, generateObject, generateText, getTextFromDataUrl, getToolName, getToolOrDynamicToolName, hasToolCall, isDataUIPart, isDeepEqualData, isToolOrDynamicToolUIPart, isToolUIPart, lastAssistantMessageIsCompleteWithApprovalResponses, lastAssistantMessageIsCompleteWithToolCalls, modelMessageSchema, parsePartialJson, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, pruneMessages, readUIMessageStream, safeValidateUIMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, stepCountIs, streamObject, streamText, systemModelMessageSchema, toolModelMessageSchema, uiMessageChunkSchema, userModelMessageSchema, validateUIMessages, wrapLanguageModel, wrapProvider };
4946
+ export { AbstractChat, Agent, AsyncIterableStream, CallSettings, CallWarning, ChatAddToolApproveResponseFunction, ChatInit, ChatOnDataCallback, ChatOnErrorCallback, ChatOnFinishCallback, ChatOnToolCallCallback, ChatRequestOptions, ChatState, ChatStatus, ChatTransport, ChunkDetector, CompletionRequestOptions, CoreAssistantMessage, CoreMessage, CoreSystemMessage, CoreToolMessage, CoreUserMessage, CreateUIMessage, DataUIPart, DeepPartial, DefaultChatTransport, DownloadError, DynamicToolCall, DynamicToolError, DynamicToolResult, DynamicToolUIPart, EmbedManyResult, EmbedResult, Embedding, EmbeddingModel, EmbeddingModelUsage, ErrorHandler, ToolLoopAgent as Experimental_Agent, ToolLoopAgentSettings as Experimental_AgentSettings, DownloadFunction as Experimental_DownloadFunction, GenerateImageResult as Experimental_GenerateImageResult, GeneratedFile as Experimental_GeneratedImage, InferAgentUIMessage as Experimental_InferAgentUIMessage, LogWarningsFunction as Experimental_LogWarningsFunction, SpeechResult as Experimental_SpeechResult, TranscriptionResult as Experimental_TranscriptionResult, Warning as Experimental_Warning, FileUIPart, FinishReason, GenerateObjectResult, GenerateTextOnFinishCallback, GenerateTextOnStepFinishCallback, GenerateTextResult, GeneratedAudioFile, GeneratedFile, HttpChatTransport, HttpChatTransportInitOptions, ImageModel, ImageGenerationWarning as ImageModelCallWarning, ImageModelProviderMetadata, ImageModelResponseMetadata, InferAgentUIMessage, InferUIDataParts, InferUIMessageChunk, InferUITool, InferUITools, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidStreamPartError, InvalidToolInputError, JSONRPCError, JSONRPCMessage, JSONRPCNotification, JSONRPCRequest, JSONRPCResponse, JSONValue, JsonToSseTransformStream, LanguageModel, LanguageModelMiddleware, LanguageModelRequestMetadata, LanguageModelResponseMetadata, LanguageModelUsage, MCPClientError, MCPTransport, MessageConversionError, NoImageGeneratedError, NoObjectGeneratedError, NoOutputGeneratedError, NoOutputSpecifiedError, NoSpeechGeneratedError, NoSuchProviderError, NoSuchToolError, ObjectStreamPart, output as Output, PrepareReconnectToStreamRequest, PrepareSendMessagesRequest, PrepareStepFunction, PrepareStepResult, Prompt, Provider, ProviderMetadata, ProviderRegistryProvider, ReasoningOutput, ReasoningUIPart, RepairTextFunction, RetryError, SafeValidateUIMessagesResult, SerialJobExecutor, SourceDocumentUIPart, SourceUrlUIPart, SpeechModel, SpeechModelResponseMetadata, SpeechWarning, StaticToolCall, StaticToolError, StaticToolOutputDenied, StaticToolResult, StepResult, StepStartUIPart, StopCondition, StreamObjectOnFinishCallback, StreamObjectResult, StreamTextOnChunkCallback, StreamTextOnErrorCallback, StreamTextOnFinishCallback, StreamTextOnStepFinishCallback, StreamTextResult, StreamTextTransform, TelemetrySettings, TextStreamChatTransport, TextStreamPart, TextUIPart, ToolApprovalRequestOutput, ToolCallRepairError, ToolCallRepairFunction, ToolChoice, ToolLoopAgent, ToolLoopAgentOnFinishCallback, ToolLoopAgentOnStepFinishCallback, ToolLoopAgentSettings, ToolSet, ToolUIPart, TranscriptionModel, TranscriptionModelResponseMetadata, TranscriptionWarning, TypedToolCall, TypedToolError, TypedToolOutputDenied, TypedToolResult, UIDataPartSchemas, UIDataTypes, UIMessage, UIMessageChunk, UIMessagePart, UIMessageStreamOnFinishCallback, UIMessageStreamOptions, UIMessageStreamWriter, UITool, UIToolInvocation, UITools, UI_MESSAGE_STREAM_HEADERS, UnsupportedModelVersionError, UseCompletionOptions, assistantModelMessageSchema, callCompletionApi, consumeStream, convertFileListToFileUIParts, convertToCoreMessages, convertToModelMessages, coreAssistantMessageSchema, coreMessageSchema, coreSystemMessageSchema, coreToolMessageSchema, coreUserMessageSchema, cosineSimilarity, createAgentUIStream, createAgentUIStreamResponse, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, defaultSettingsMiddleware, embed, embedMany, MCPClient as experimental_MCPClient, MCPClientConfig as experimental_MCPClientConfig, createMCPClient as experimental_createMCPClient, experimental_createProviderRegistry, experimental_customProvider, generateImage as experimental_generateImage, generateSpeech as experimental_generateSpeech, transcribe as experimental_transcribe, extractReasoningMiddleware, generateObject, generateText, getTextFromDataUrl, getToolName, getToolOrDynamicToolName, hasToolCall, isDataUIPart, isDeepEqualData, isToolOrDynamicToolUIPart, isToolUIPart, lastAssistantMessageIsCompleteWithApprovalResponses, lastAssistantMessageIsCompleteWithToolCalls, modelMessageSchema, parsePartialJson, pipeAgentUIStreamToResponse, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, pruneMessages, readUIMessageStream, safeValidateUIMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, stepCountIs, streamObject, streamText, systemModelMessageSchema, toolModelMessageSchema, uiMessageChunkSchema, userModelMessageSchema, validateUIMessages, wrapLanguageModel, wrapProvider };