ai 5.0.0-canary.18 → 5.0.0-canary.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,12 +1,47 @@
1
- import { ToolCall, ToolResult, FetchFunction, ToolResultContent, Schema, IdGenerator as IdGenerator$1 } from '@ai-sdk/provider-utils';
1
+ import { ToolCall, ToolResult, IdGenerator, FetchFunction, ToolResultContent, Schema } from '@ai-sdk/provider-utils';
2
2
  export { IdGenerator, Schema, ToolCall, ToolResult, asSchema, createIdGenerator, generateId, jsonSchema } from '@ai-sdk/provider-utils';
3
- import * as _ai_sdk_provider from '@ai-sdk/provider';
3
+ import { AttributeValue, Tracer } from '@opentelemetry/api';
4
4
  import { EmbeddingModelV2, EmbeddingModelV2Embedding, ImageModelV2, ImageModelV2CallWarning, ImageModelV2ProviderMetadata, JSONValue as JSONValue$1, LanguageModelV2, LanguageModelV2FinishReason, LanguageModelV2CallWarning, LanguageModelV2Source, SharedV2ProviderMetadata, SharedV2ProviderOptions, SpeechModelV1, SpeechModelV1CallWarning, TranscriptionModelV1, TranscriptionModelV1CallWarning, LanguageModelV2Usage, JSONObject, LanguageModelV2CallOptions, AISDKError, LanguageModelV2ToolCall, JSONSchema7, JSONParseError, TypeValidationError, LanguageModelV2Middleware, ProviderV2, NoSuchModelError } from '@ai-sdk/provider';
5
5
  export { AISDKError, APICallError, EmptyResponseBodyError, InvalidPromptError, InvalidResponseDataError, JSONParseError, JSONSchema7, LoadAPIKeyError, NoContentGeneratedError, NoSuchModelError, TypeValidationError, UnsupportedFunctionalityError } from '@ai-sdk/provider';
6
- import { ServerResponse } from 'node:http';
7
- import { AttributeValue, Tracer } from '@opentelemetry/api';
8
6
  import { z } from 'zod';
9
7
  import { ServerResponse as ServerResponse$1 } from 'http';
8
+ import { ServerResponse } from 'node:http';
9
+
10
+ /**
11
+ * Telemetry configuration.
12
+ */
13
+ type TelemetrySettings = {
14
+ /**
15
+ * Enable or disable telemetry. Disabled by default while experimental.
16
+ */
17
+ isEnabled?: boolean;
18
+ /**
19
+ * Enable or disable input recording. Enabled by default.
20
+ *
21
+ * You might want to disable input recording to avoid recording sensitive
22
+ * information, to reduce data transfers, or to increase performance.
23
+ */
24
+ recordInputs?: boolean;
25
+ /**
26
+ * Enable or disable output recording. Enabled by default.
27
+ *
28
+ * You might want to disable output recording to avoid recording sensitive
29
+ * information, to reduce data transfers, or to increase performance.
30
+ */
31
+ recordOutputs?: boolean;
32
+ /**
33
+ * Identifier for this function. Used to group telemetry data by function.
34
+ */
35
+ functionId?: string;
36
+ /**
37
+ * Additional information to include in the telemetry data.
38
+ */
39
+ metadata?: Record<string, AttributeValue>;
40
+ /**
41
+ * A custom tracer to use for the telemetry data.
42
+ */
43
+ tracer?: Tracer;
44
+ };
10
45
 
11
46
  /**
12
47
  Embedding model that is used by the AI SDK Core functions.
@@ -232,7 +267,6 @@ type EmbeddingModelUsage = {
232
267
  tokens: number;
233
268
  };
234
269
 
235
- type IdGenerator = () => string;
236
270
  /**
237
271
  Tool invocations are either tool calls or tool results. For each assistant tool call,
238
272
  there is one tool invocation. While the call is in progress, the invocation is a tool call.
@@ -265,10 +299,6 @@ interface UIMessage {
265
299
  */
266
300
  createdAt?: Date;
267
301
  /**
268
- Text content of the message. Use parts when possible.
269
- */
270
- content: string;
271
- /**
272
302
  The role of the message.
273
303
  */
274
304
  role: 'system' | 'user' | 'assistant';
@@ -571,330 +601,6 @@ type UseCompletionOptions = {
571
601
  fetch?: FetchFunction;
572
602
  };
573
603
 
574
- declare const getOriginalFetch$1: () => typeof fetch;
575
- declare function callChatApi({ api, body, streamProtocol, credentials, headers, abortController, onResponse, onUpdate, onFinish, onToolCall, generateId, fetch, lastMessage, getCurrentDate, requestType, }: {
576
- api: string;
577
- body: Record<string, any>;
578
- streamProtocol: 'data' | 'text' | undefined;
579
- credentials: RequestCredentials | undefined;
580
- headers: HeadersInit | undefined;
581
- abortController: (() => AbortController | null) | undefined;
582
- onResponse: ((response: Response) => void | Promise<void>) | undefined;
583
- onUpdate: (options: {
584
- message: UIMessage;
585
- data: JSONValue$1[] | undefined;
586
- replaceLastMessage: boolean;
587
- }) => void;
588
- onFinish: UseChatOptions['onFinish'];
589
- onToolCall: UseChatOptions['onToolCall'];
590
- generateId: IdGenerator;
591
- fetch: ReturnType<typeof getOriginalFetch$1> | undefined;
592
- lastMessage: UIMessage | undefined;
593
- getCurrentDate: () => Date;
594
- requestType?: 'generate' | 'resume';
595
- }): Promise<void>;
596
-
597
- declare const getOriginalFetch: () => typeof fetch;
598
- declare function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol, setCompletion, setLoading, setError, setAbortController, onResponse, onFinish, onError, onData, fetch, }: {
599
- api: string;
600
- prompt: string;
601
- credentials: RequestCredentials | undefined;
602
- headers: HeadersInit | undefined;
603
- body: Record<string, any>;
604
- streamProtocol: 'data' | 'text' | undefined;
605
- setCompletion: (completion: string) => void;
606
- setLoading: (loading: boolean) => void;
607
- setError: (error: Error | undefined) => void;
608
- setAbortController: (abortController: AbortController | null) => void;
609
- onResponse: ((response: Response) => void | Promise<void>) | undefined;
610
- onFinish: ((prompt: string, completion: string) => void) | undefined;
611
- onError: ((error: Error) => void) | undefined;
612
- onData: ((data: JSONValue[]) => void) | undefined;
613
- fetch: ReturnType<typeof getOriginalFetch> | undefined;
614
- }): Promise<string | null | undefined>;
615
-
616
- declare function convertFileListToFileUIParts(files: FileList | undefined): Promise<Array<FileUIPart>>;
617
-
618
- type DataStreamString = `${(typeof DataStreamStringPrefixes)[keyof typeof DataStreamStringPrefixes]}:${string}\n`;
619
- interface DataStreamPart<CODE extends string, NAME extends string, TYPE> {
620
- code: CODE;
621
- name: NAME;
622
- parse: (value: JSONValue) => {
623
- type: NAME;
624
- value: TYPE;
625
- };
626
- }
627
- declare const dataStreamParts: readonly [DataStreamPart<"0", "text", string>, DataStreamPart<"2", "data", _ai_sdk_provider.JSONValue[]>, DataStreamPart<"3", "error", string>, DataStreamPart<"8", "message_annotations", _ai_sdk_provider.JSONValue[]>, DataStreamPart<"9", "tool_call", ToolCall<string, any>>, DataStreamPart<"a", "tool_result", Omit<ToolResult<string, any, any>, "args" | "toolName">>, DataStreamPart<"b", "tool_call_streaming_start", {
628
- toolCallId: string;
629
- toolName: string;
630
- }>, DataStreamPart<"c", "tool_call_delta", {
631
- toolCallId: string;
632
- argsTextDelta: string;
633
- }>, DataStreamPart<"d", "finish_message", {
634
- finishReason: LanguageModelV2FinishReason;
635
- usage?: LanguageModelV2Usage;
636
- }>, DataStreamPart<"e", "finish_step", {
637
- isContinued: boolean;
638
- finishReason: LanguageModelV2FinishReason;
639
- usage?: LanguageModelV2Usage;
640
- }>, DataStreamPart<"f", "start_step", {
641
- messageId: string;
642
- }>, DataStreamPart<"g", "reasoning", {
643
- text: string;
644
- providerMetadata?: Record<string, any> | undefined;
645
- }>, DataStreamPart<"h", "source", LanguageModelV2Source>, DataStreamPart<"l", "reasoning_part_finish", {}>, DataStreamPart<"k", "file", {
646
- url: string;
647
- mediaType: string;
648
- }>];
649
- type DataStreamParts = (typeof dataStreamParts)[number];
650
- /**
651
- * Maps the type of a stream part to its value type.
652
- */
653
- type DataStreamPartValueType = {
654
- [P in DataStreamParts as P['name']]: ReturnType<P['parse']>['value'];
655
- };
656
- type DataStreamPartType = ReturnType<DataStreamParts['parse']>;
657
- /**
658
- * The map of prefixes for data in the stream
659
- *
660
- * - 0: Text from the LLM response
661
- * - 1: (OpenAI) function_call responses
662
- * - 2: custom JSON added by the user using `Data`
663
- * - 6: (OpenAI) tool_call responses
664
- *
665
- * Example:
666
- * ```
667
- * 0:Vercel
668
- * 0:'s
669
- * 0: AI
670
- * 0: AI
671
- * 0: SDK
672
- * 0: is great
673
- * 0:!
674
- * 2: { "someJson": "value" }
675
- * 1: {"function_call": {"name": "get_current_weather", "arguments": "{\\n\\"location\\": \\"Charlottesville, Virginia\\",\\n\\"format\\": \\"celsius\\"\\n}"}}
676
- * 6: {"tool_call": {"id": "tool_0", "type": "function", "function": {"name": "get_current_weather", "arguments": "{\\n\\"location\\": \\"Charlottesville, Virginia\\",\\n\\"format\\": \\"celsius\\"\\n}"}}}
677
- *```
678
- */
679
- declare const DataStreamStringPrefixes: { [K in DataStreamParts["name"]]: (typeof dataStreamParts)[number]["code"]; };
680
- /**
681
- Parses a stream part from a string.
682
-
683
- @param line The string to parse.
684
- @returns The parsed stream part.
685
- @throws An error if the string cannot be parsed.
686
- */
687
- declare const parseDataStreamPart: (line: string) => DataStreamPartType;
688
- /**
689
- Prepends a string with a prefix from the `StreamChunkPrefixes`, converts it to JSON,
690
- and appends a new line.
691
-
692
- It ensures type-safety for the part type and value.
693
- */
694
- declare function formatDataStreamPart<T extends keyof DataStreamPartValueType>(type: T, value: DataStreamPartValueType[T]): DataStreamString;
695
-
696
- /**
697
- * Converts a data URL of type text/* to a text string.
698
- */
699
- declare function getTextFromDataUrl(dataUrl: string): string;
700
-
701
- /**
702
- Create a type from an object with all keys and nested keys set to optional.
703
- The helper supports normal objects and Zod schemas (which are resolved automatically).
704
- It always recurses into arrays.
705
-
706
- Adopted from [type-fest](https://github.com/sindresorhus/type-fest/tree/main) PartialDeep.
707
- */
708
- type DeepPartial<T> = T extends z.ZodTypeAny ? DeepPartialInternal<z.infer<T>> : DeepPartialInternal<T>;
709
- type DeepPartialInternal<T> = T extends null | undefined | string | number | boolean | symbol | bigint | void | Date | RegExp | ((...arguments_: any[]) => unknown) | (new (...arguments_: any[]) => unknown) ? T : T extends Map<infer KeyType, infer ValueType> ? PartialMap<KeyType, ValueType> : T extends Set<infer ItemType> ? PartialSet<ItemType> : T extends ReadonlyMap<infer KeyType, infer ValueType> ? PartialReadonlyMap<KeyType, ValueType> : T extends ReadonlySet<infer ItemType> ? PartialReadonlySet<ItemType> : T extends object ? T extends ReadonlyArray<infer ItemType> ? ItemType[] extends T ? readonly ItemType[] extends T ? ReadonlyArray<DeepPartialInternal<ItemType | undefined>> : Array<DeepPartialInternal<ItemType | undefined>> : PartialObject<T> : PartialObject<T> : unknown;
710
- type PartialMap<KeyType, ValueType> = {} & Map<DeepPartialInternal<KeyType>, DeepPartialInternal<ValueType>>;
711
- type PartialSet<T> = {} & Set<DeepPartialInternal<T>>;
712
- type PartialReadonlyMap<KeyType, ValueType> = {} & ReadonlyMap<DeepPartialInternal<KeyType>, DeepPartialInternal<ValueType>>;
713
- type PartialReadonlySet<T> = {} & ReadonlySet<DeepPartialInternal<T>>;
714
- type PartialObject<ObjectType extends object> = {
715
- [KeyType in keyof ObjectType]?: DeepPartialInternal<ObjectType[KeyType]>;
716
- };
717
-
718
- declare function extractMaxToolInvocationStep(toolInvocations: ToolInvocation[] | undefined): number | undefined;
719
-
720
- /**
721
- * Performs a deep-equal comparison of two parsed JSON objects.
722
- *
723
- * @param {any} obj1 - The first object to compare.
724
- * @param {any} obj2 - The second object to compare.
725
- * @returns {boolean} - Returns true if the two objects are deeply equal, false otherwise.
726
- */
727
- declare function isDeepEqualData(obj1: any, obj2: any): boolean;
728
-
729
- declare function parsePartialJson(jsonText: string | undefined): Promise<{
730
- value: JSONValue$1 | undefined;
731
- state: 'undefined-input' | 'successful-parse' | 'repaired-parse' | 'failed-parse';
732
- }>;
733
-
734
- declare function processDataStream({ stream, onTextPart, onReasoningPart, onReasoningPartFinish, onSourcePart, onFilePart, onDataPart, onErrorPart, onToolCallStreamingStartPart, onToolCallDeltaPart, onToolCallPart, onToolResultPart, onMessageAnnotationsPart, onFinishMessagePart, onFinishStepPart, onStartStepPart, }: {
735
- stream: ReadableStream<Uint8Array>;
736
- onTextPart?: (streamPart: (DataStreamPartType & {
737
- type: 'text';
738
- })['value']) => Promise<void> | void;
739
- onReasoningPart?: (streamPart: (DataStreamPartType & {
740
- type: 'reasoning';
741
- })['value']) => Promise<void> | void;
742
- onReasoningPartFinish?: (streamPart: (DataStreamPartType & {
743
- type: 'reasoning_part_finish';
744
- })['value']) => Promise<void> | void;
745
- onFilePart?: (streamPart: (DataStreamPartType & {
746
- type: 'file';
747
- })['value']) => Promise<void> | void;
748
- onSourcePart?: (streamPart: (DataStreamPartType & {
749
- type: 'source';
750
- })['value']) => Promise<void> | void;
751
- onDataPart?: (streamPart: (DataStreamPartType & {
752
- type: 'data';
753
- })['value']) => Promise<void> | void;
754
- onErrorPart?: (streamPart: (DataStreamPartType & {
755
- type: 'error';
756
- })['value']) => Promise<void> | void;
757
- onToolCallStreamingStartPart?: (streamPart: (DataStreamPartType & {
758
- type: 'tool_call_streaming_start';
759
- })['value']) => Promise<void> | void;
760
- onToolCallDeltaPart?: (streamPart: (DataStreamPartType & {
761
- type: 'tool_call_delta';
762
- })['value']) => Promise<void> | void;
763
- onToolCallPart?: (streamPart: (DataStreamPartType & {
764
- type: 'tool_call';
765
- })['value']) => Promise<void> | void;
766
- onToolResultPart?: (streamPart: (DataStreamPartType & {
767
- type: 'tool_result';
768
- })['value']) => Promise<void> | void;
769
- onMessageAnnotationsPart?: (streamPart: (DataStreamPartType & {
770
- type: 'message_annotations';
771
- })['value']) => Promise<void> | void;
772
- onFinishMessagePart?: (streamPart: (DataStreamPartType & {
773
- type: 'finish_message';
774
- })['value']) => Promise<void> | void;
775
- onFinishStepPart?: (streamPart: (DataStreamPartType & {
776
- type: 'finish_step';
777
- })['value']) => Promise<void> | void;
778
- onStartStepPart?: (streamPart: (DataStreamPartType & {
779
- type: 'start_step';
780
- })['value']) => Promise<void> | void;
781
- }): Promise<void>;
782
-
783
- declare function processTextStream({ stream, onTextPart, }: {
784
- stream: ReadableStream<Uint8Array>;
785
- onTextPart: (chunk: string) => Promise<void> | void;
786
- }): Promise<void>;
787
-
788
- declare function shouldResubmitMessages({ originalMaxToolInvocationStep, originalMessageCount, maxSteps, messages, }: {
789
- originalMaxToolInvocationStep: number | undefined;
790
- originalMessageCount: number;
791
- maxSteps: number;
792
- messages: UIMessage[];
793
- }): boolean;
794
- /**
795
- Check if the message is an assistant message with completed tool calls.
796
- The last step of the message must have at least one tool invocation and
797
- all tool invocations must have a result.
798
- */
799
- declare function isAssistantMessageWithCompletedToolCalls(message: UIMessage): message is UIMessage & {
800
- role: 'assistant';
801
- };
802
-
803
- /**
804
- * Updates the result of a specific tool invocation in the last message of the given messages array.
805
- *
806
- * @param {object} params - The parameters object.
807
- * @param {UIMessage[]} params.messages - An array of messages, from which the last one is updated.
808
- * @param {string} params.toolCallId - The unique identifier for the tool invocation to update.
809
- * @param {unknown} params.toolResult - The result object to attach to the tool invocation.
810
- * @returns {void} This function does not return anything.
811
- */
812
- declare function updateToolCallResult({ messages, toolCallId, toolResult: result, }: {
813
- messages: UIMessage[];
814
- toolCallId: string;
815
- toolResult: unknown;
816
- }): void;
817
-
818
- interface DataStreamWriter {
819
- /**
820
- * Appends a data part to the stream.
821
- */
822
- write(data: DataStreamString): void;
823
- /**
824
- * Appends a data part to the stream.
825
- */
826
- writeData(value: JSONValue$1): void;
827
- /**
828
- * Appends a message annotation to the stream.
829
- */
830
- writeMessageAnnotation(value: JSONValue$1): void;
831
- /**
832
- * Appends a source part to the stream.
833
- */
834
- writeSource(source: Source): void;
835
- /**
836
- * Merges the contents of another stream to this stream.
837
- */
838
- merge(stream: ReadableStream<DataStreamString>): void;
839
- /**
840
- * Error handler that is used by the data stream writer.
841
- * This is intended for forwarding when merging streams
842
- * to prevent duplicated error masking.
843
- */
844
- onError: ((error: unknown) => string) | undefined;
845
- }
846
-
847
- declare function createDataStream({ execute, onError, }: {
848
- execute: (dataStream: DataStreamWriter) => Promise<void> | void;
849
- onError?: (error: unknown) => string;
850
- }): ReadableStream<DataStreamString>;
851
-
852
- declare function createDataStreamResponse({ status, statusText, headers, execute, onError, }: ResponseInit & {
853
- execute: (dataStream: DataStreamWriter) => Promise<void> | void;
854
- onError?: (error: unknown) => string;
855
- }): Response;
856
-
857
- declare function pipeDataStreamToResponse(response: ServerResponse, { status, statusText, headers, execute, onError, }: ResponseInit & {
858
- execute: (writer: DataStreamWriter) => Promise<void> | void;
859
- onError?: (error: unknown) => string;
860
- }): void;
861
-
862
- /**
863
- * Telemetry configuration.
864
- */
865
- type TelemetrySettings = {
866
- /**
867
- * Enable or disable telemetry. Disabled by default while experimental.
868
- */
869
- isEnabled?: boolean;
870
- /**
871
- * Enable or disable input recording. Enabled by default.
872
- *
873
- * You might want to disable input recording to avoid recording sensitive
874
- * information, to reduce data transfers, or to increase performance.
875
- */
876
- recordInputs?: boolean;
877
- /**
878
- * Enable or disable output recording. Enabled by default.
879
- *
880
- * You might want to disable output recording to avoid recording sensitive
881
- * information, to reduce data transfers, or to increase performance.
882
- */
883
- recordOutputs?: boolean;
884
- /**
885
- * Identifier for this function. Used to group telemetry data by function.
886
- */
887
- functionId?: string;
888
- /**
889
- * Additional information to include in the telemetry data.
890
- */
891
- metadata?: Record<string, AttributeValue>;
892
- /**
893
- * A custom tracer to use for the telemetry data.
894
- */
895
- tracer?: Tracer;
896
- };
897
-
898
604
  /**
899
605
  The result of an `embed` call.
900
606
  It contains the embedding, the value, and additional information.
@@ -1511,26 +1217,26 @@ declare const JSONRPCErrorSchema: z.ZodObject<{
1511
1217
  message: z.ZodString;
1512
1218
  data: z.ZodOptional<z.ZodUnknown>;
1513
1219
  }, "strip", z.ZodTypeAny, {
1514
- code: number;
1515
1220
  message: string;
1221
+ code: number;
1516
1222
  data?: unknown;
1517
1223
  }, {
1518
- code: number;
1519
1224
  message: string;
1225
+ code: number;
1520
1226
  data?: unknown;
1521
1227
  }>;
1522
1228
  }, "strict", z.ZodTypeAny, {
1523
1229
  error: {
1524
- code: number;
1525
1230
  message: string;
1231
+ code: number;
1526
1232
  data?: unknown;
1527
1233
  };
1528
1234
  id: string | number;
1529
1235
  jsonrpc: "2.0";
1530
1236
  }, {
1531
1237
  error: {
1532
- code: number;
1533
1238
  message: string;
1239
+ code: number;
1534
1240
  data?: unknown;
1535
1241
  };
1536
1242
  id: string | number;
@@ -1645,26 +1351,26 @@ declare const JSONRPCMessageSchema: z.ZodUnion<[z.ZodObject<z.objectUtil.extendS
1645
1351
  message: z.ZodString;
1646
1352
  data: z.ZodOptional<z.ZodUnknown>;
1647
1353
  }, "strip", z.ZodTypeAny, {
1648
- code: number;
1649
1354
  message: string;
1355
+ code: number;
1650
1356
  data?: unknown;
1651
1357
  }, {
1652
- code: number;
1653
1358
  message: string;
1359
+ code: number;
1654
1360
  data?: unknown;
1655
1361
  }>;
1656
1362
  }, "strict", z.ZodTypeAny, {
1657
1363
  error: {
1658
- code: number;
1659
1364
  message: string;
1365
+ code: number;
1660
1366
  data?: unknown;
1661
1367
  };
1662
1368
  id: string | number;
1663
1369
  jsonrpc: "2.0";
1664
1370
  }, {
1665
1371
  error: {
1666
- code: number;
1667
1372
  message: string;
1373
+ code: number;
1668
1374
  data?: unknown;
1669
1375
  };
1670
1376
  id: string | number;
@@ -1673,48 +1379,165 @@ declare const JSONRPCMessageSchema: z.ZodUnion<[z.ZodObject<z.objectUtil.extendS
1673
1379
  type JSONRPCMessage = z.infer<typeof JSONRPCMessageSchema>;
1674
1380
 
1675
1381
  /**
1676
- * Transport interface for MCP (Model Context Protocol) communication.
1677
- * Maps to the `Transport` interface in the MCP spec.
1382
+ * Transport interface for MCP (Model Context Protocol) communication.
1383
+ * Maps to the `Transport` interface in the MCP spec.
1384
+ */
1385
+ interface MCPTransport {
1386
+ /**
1387
+ * Initialize and start the transport
1388
+ */
1389
+ start(): Promise<void>;
1390
+ /**
1391
+ * Send a JSON-RPC message through the transport
1392
+ * @param message The JSON-RPC message to send
1393
+ */
1394
+ send(message: JSONRPCMessage): Promise<void>;
1395
+ /**
1396
+ * Clean up and close the transport
1397
+ */
1398
+ close(): Promise<void>;
1399
+ /**
1400
+ * Event handler for transport closure
1401
+ */
1402
+ onclose?: () => void;
1403
+ /**
1404
+ * Event handler for transport errors
1405
+ */
1406
+ onerror?: (error: Error) => void;
1407
+ /**
1408
+ * Event handler for received messages
1409
+ */
1410
+ onmessage?: (message: JSONRPCMessage) => void;
1411
+ }
1412
+ type MCPTransportConfig = {
1413
+ type: 'sse';
1414
+ /**
1415
+ * The URL of the MCP server.
1416
+ */
1417
+ url: string;
1418
+ /**
1419
+ * Additional HTTP headers to be sent with requests.
1420
+ */
1421
+ headers?: Record<string, string>;
1422
+ };
1423
+
1424
+ declare const getOriginalFetch$1: () => typeof fetch;
1425
+ declare function callChatApi({ api, body, streamProtocol, credentials, headers, abortController, onResponse, onUpdate, onFinish, onToolCall, generateId, fetch, lastMessage, getCurrentDate, requestType, }: {
1426
+ api: string;
1427
+ body: Record<string, any>;
1428
+ streamProtocol: 'data' | 'text' | undefined;
1429
+ credentials: RequestCredentials | undefined;
1430
+ headers: HeadersInit | undefined;
1431
+ abortController: (() => AbortController | null) | undefined;
1432
+ onResponse: ((response: Response) => void | Promise<void>) | undefined;
1433
+ onUpdate: (options: {
1434
+ message: UIMessage;
1435
+ data: JSONValue$1[] | undefined;
1436
+ replaceLastMessage: boolean;
1437
+ }) => void;
1438
+ onFinish: UseChatOptions['onFinish'];
1439
+ onToolCall: UseChatOptions['onToolCall'];
1440
+ generateId: IdGenerator;
1441
+ fetch: ReturnType<typeof getOriginalFetch$1> | undefined;
1442
+ lastMessage: UIMessage | undefined;
1443
+ getCurrentDate: () => Date;
1444
+ requestType?: 'generate' | 'resume';
1445
+ }): Promise<void>;
1446
+
1447
+ declare const getOriginalFetch: () => typeof fetch;
1448
+ declare function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol, setCompletion, setLoading, setError, setAbortController, onResponse, onFinish, onError, onData, fetch, }: {
1449
+ api: string;
1450
+ prompt: string;
1451
+ credentials: RequestCredentials | undefined;
1452
+ headers: HeadersInit | undefined;
1453
+ body: Record<string, any>;
1454
+ streamProtocol: 'data' | 'text' | undefined;
1455
+ setCompletion: (completion: string) => void;
1456
+ setLoading: (loading: boolean) => void;
1457
+ setError: (error: Error | undefined) => void;
1458
+ setAbortController: (abortController: AbortController | null) => void;
1459
+ onResponse: ((response: Response) => void | Promise<void>) | undefined;
1460
+ onFinish: ((prompt: string, completion: string) => void) | undefined;
1461
+ onError: ((error: Error) => void) | undefined;
1462
+ onData: ((data: JSONValue$1[]) => void) | undefined;
1463
+ fetch: ReturnType<typeof getOriginalFetch> | undefined;
1464
+ }): Promise<string | null | undefined>;
1465
+
1466
+ declare function convertFileListToFileUIParts(files: FileList | undefined): Promise<Array<FileUIPart>>;
1467
+
1468
+ /**
1469
+ * Converts a data URL of type text/* to a text string.
1470
+ */
1471
+ declare function getTextFromDataUrl(dataUrl: string): string;
1472
+
1473
+ /**
1474
+ Create a type from an object with all keys and nested keys set to optional.
1475
+ The helper supports normal objects and Zod schemas (which are resolved automatically).
1476
+ It always recurses into arrays.
1477
+
1478
+ Adopted from [type-fest](https://github.com/sindresorhus/type-fest/tree/main) PartialDeep.
1479
+ */
1480
+ type DeepPartial<T> = T extends z.ZodTypeAny ? DeepPartialInternal<z.infer<T>> : DeepPartialInternal<T>;
1481
+ type DeepPartialInternal<T> = T extends null | undefined | string | number | boolean | symbol | bigint | void | Date | RegExp | ((...arguments_: any[]) => unknown) | (new (...arguments_: any[]) => unknown) ? T : T extends Map<infer KeyType, infer ValueType> ? PartialMap<KeyType, ValueType> : T extends Set<infer ItemType> ? PartialSet<ItemType> : T extends ReadonlyMap<infer KeyType, infer ValueType> ? PartialReadonlyMap<KeyType, ValueType> : T extends ReadonlySet<infer ItemType> ? PartialReadonlySet<ItemType> : T extends object ? T extends ReadonlyArray<infer ItemType> ? ItemType[] extends T ? readonly ItemType[] extends T ? ReadonlyArray<DeepPartialInternal<ItemType | undefined>> : Array<DeepPartialInternal<ItemType | undefined>> : PartialObject<T> : PartialObject<T> : unknown;
1482
+ type PartialMap<KeyType, ValueType> = {} & Map<DeepPartialInternal<KeyType>, DeepPartialInternal<ValueType>>;
1483
+ type PartialSet<T> = {} & Set<DeepPartialInternal<T>>;
1484
+ type PartialReadonlyMap<KeyType, ValueType> = {} & ReadonlyMap<DeepPartialInternal<KeyType>, DeepPartialInternal<ValueType>>;
1485
+ type PartialReadonlySet<T> = {} & ReadonlySet<DeepPartialInternal<T>>;
1486
+ type PartialObject<ObjectType extends object> = {
1487
+ [KeyType in keyof ObjectType]?: DeepPartialInternal<ObjectType[KeyType]>;
1488
+ };
1489
+
1490
+ declare function extractMaxToolInvocationStep(toolInvocations: ToolInvocation[] | undefined): number | undefined;
1491
+
1492
+ /**
1493
+ * Performs a deep-equal comparison of two parsed JSON objects.
1494
+ *
1495
+ * @param {any} obj1 - The first object to compare.
1496
+ * @param {any} obj2 - The second object to compare.
1497
+ * @returns {boolean} - Returns true if the two objects are deeply equal, false otherwise.
1498
+ */
1499
+ declare function isDeepEqualData(obj1: any, obj2: any): boolean;
1500
+
1501
+ declare function parsePartialJson(jsonText: string | undefined): Promise<{
1502
+ value: JSONValue$1 | undefined;
1503
+ state: 'undefined-input' | 'successful-parse' | 'repaired-parse' | 'failed-parse';
1504
+ }>;
1505
+
1506
+ declare function processTextStream({ stream, onTextPart, }: {
1507
+ stream: ReadableStream<Uint8Array>;
1508
+ onTextPart: (chunk: string) => Promise<void> | void;
1509
+ }): Promise<void>;
1510
+
1511
+ declare function shouldResubmitMessages({ originalMaxToolInvocationStep, originalMessageCount, maxSteps, messages, }: {
1512
+ originalMaxToolInvocationStep: number | undefined;
1513
+ originalMessageCount: number;
1514
+ maxSteps: number;
1515
+ messages: UIMessage[];
1516
+ }): boolean;
1517
+ /**
1518
+ Check if the message is an assistant message with completed tool calls.
1519
+ The last step of the message must have at least one tool invocation and
1520
+ all tool invocations must have a result.
1678
1521
  */
1679
- interface MCPTransport {
1680
- /**
1681
- * Initialize and start the transport
1682
- */
1683
- start(): Promise<void>;
1684
- /**
1685
- * Send a JSON-RPC message through the transport
1686
- * @param message The JSON-RPC message to send
1687
- */
1688
- send(message: JSONRPCMessage): Promise<void>;
1689
- /**
1690
- * Clean up and close the transport
1691
- */
1692
- close(): Promise<void>;
1693
- /**
1694
- * Event handler for transport closure
1695
- */
1696
- onclose?: () => void;
1697
- /**
1698
- * Event handler for transport errors
1699
- */
1700
- onerror?: (error: Error) => void;
1701
- /**
1702
- * Event handler for received messages
1703
- */
1704
- onmessage?: (message: JSONRPCMessage) => void;
1705
- }
1706
- type MCPTransportConfig = {
1707
- type: 'sse';
1708
- /**
1709
- * The URL of the MCP server.
1710
- */
1711
- url: string;
1712
- /**
1713
- * Additional HTTP headers to be sent with requests.
1714
- */
1715
- headers?: Record<string, string>;
1522
+ declare function isAssistantMessageWithCompletedToolCalls(message: UIMessage): message is UIMessage & {
1523
+ role: 'assistant';
1716
1524
  };
1717
1525
 
1526
+ /**
1527
+ * Updates the result of a specific tool invocation in the last message of the given messages array.
1528
+ *
1529
+ * @param {object} params - The parameters object.
1530
+ * @param {UIMessage[]} params.messages - An array of messages, from which the last one is updated.
1531
+ * @param {string} params.toolCallId - The unique identifier for the tool invocation to update.
1532
+ * @param {unknown} params.toolResult - The result object to attach to the tool invocation.
1533
+ * @returns {void} This function does not return anything.
1534
+ */
1535
+ declare function updateToolCallResult({ messages, toolCallId, toolResult: result, }: {
1536
+ messages: UIMessage[];
1537
+ toolCallId: string;
1538
+ toolResult: unknown;
1539
+ }): void;
1540
+
1718
1541
  type ToolParameters<T = JSONObject> = z.Schema<T> | Schema<T>;
1719
1542
  interface ToolExecutionOptions {
1720
1543
  /**
@@ -2644,7 +2467,7 @@ type ToolResultArray<TOOLS extends ToolSet> = Array<ToolResultUnion<TOOLS>>;
2644
2467
  A message that was generated during the generation process.
2645
2468
  It can be either an assistant message or a tool message.
2646
2469
  */
2647
- type ResponseMessage = (CoreAssistantMessage | CoreToolMessage) & {
2470
+ type ResponseMessage = (AssistantModelMessage | ToolModelMessage) & {
2648
2471
  /**
2649
2472
  Message ID generated by the AI SDK.
2650
2473
  */
@@ -3017,7 +2840,7 @@ By default, it's set to 1, which means that only a single LLM call is made.
3017
2840
  /**
3018
2841
  Generate a unique ID for each message.
3019
2842
  */
3020
- experimental_generateMessageId?: IdGenerator$1;
2843
+ experimental_generateMessageId?: IdGenerator;
3021
2844
  /**
3022
2845
  When enabled, the model will perform additional steps if the finish reason is "length" (experimental).
3023
2846
 
@@ -3077,31 +2900,422 @@ A function that attempts to repair a tool call that failed to parse.
3077
2900
  * Internal. For test use only. May change without notice.
3078
2901
  */
3079
2902
  _internal?: {
3080
- generateId?: IdGenerator$1;
2903
+ generateId?: IdGenerator;
3081
2904
  currentDate?: () => Date;
3082
2905
  };
3083
2906
  }): Promise<GenerateTextResult<TOOLS, OUTPUT>>;
3084
2907
 
3085
- /**
3086
- * A stream wrapper to send custom JSON-encoded data back to the client.
3087
- *
3088
- * @deprecated Please use `createDataStream`, `createDataStreamResponse`, and `pipeDataStreamToResponse` instead.
3089
- */
3090
- declare class StreamData {
3091
- private encoder;
3092
- private controller;
3093
- stream: ReadableStream<Uint8Array>;
3094
- private isClosed;
3095
- private warningTimeout;
3096
- constructor();
3097
- close(): Promise<void>;
3098
- append(value: JSONValue): void;
3099
- appendMessageAnnotation(value: JSONValue): void;
3100
- }
2908
+ declare const dataStreamPartSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
2909
+ type: z.ZodLiteral<"text">;
2910
+ value: z.ZodString;
2911
+ }, "strip", z.ZodTypeAny, {
2912
+ value: string;
2913
+ type: "text";
2914
+ }, {
2915
+ value: string;
2916
+ type: "text";
2917
+ }>, z.ZodObject<{
2918
+ type: z.ZodLiteral<"data">;
2919
+ value: z.ZodArray<z.ZodAny, "many">;
2920
+ }, "strip", z.ZodTypeAny, {
2921
+ value: any[];
2922
+ type: "data";
2923
+ }, {
2924
+ value: any[];
2925
+ type: "data";
2926
+ }>, z.ZodObject<{
2927
+ type: z.ZodLiteral<"error">;
2928
+ value: z.ZodString;
2929
+ }, "strip", z.ZodTypeAny, {
2930
+ value: string;
2931
+ type: "error";
2932
+ }, {
2933
+ value: string;
2934
+ type: "error";
2935
+ }>, z.ZodObject<{
2936
+ type: z.ZodLiteral<"message-annotations">;
2937
+ value: z.ZodArray<z.ZodAny, "many">;
2938
+ }, "strip", z.ZodTypeAny, {
2939
+ value: any[];
2940
+ type: "message-annotations";
2941
+ }, {
2942
+ value: any[];
2943
+ type: "message-annotations";
2944
+ }>, z.ZodObject<{
2945
+ type: z.ZodLiteral<"tool-call">;
2946
+ value: z.ZodObject<{
2947
+ toolCallId: z.ZodString;
2948
+ toolName: z.ZodString;
2949
+ args: z.ZodUnknown;
2950
+ }, "strip", z.ZodTypeAny, {
2951
+ toolName: string;
2952
+ toolCallId: string;
2953
+ args?: unknown;
2954
+ }, {
2955
+ toolName: string;
2956
+ toolCallId: string;
2957
+ args?: unknown;
2958
+ }>;
2959
+ }, "strip", z.ZodTypeAny, {
2960
+ value: {
2961
+ toolName: string;
2962
+ toolCallId: string;
2963
+ args?: unknown;
2964
+ };
2965
+ type: "tool-call";
2966
+ }, {
2967
+ value: {
2968
+ toolName: string;
2969
+ toolCallId: string;
2970
+ args?: unknown;
2971
+ };
2972
+ type: "tool-call";
2973
+ }>, z.ZodObject<{
2974
+ type: z.ZodLiteral<"tool-result">;
2975
+ value: z.ZodObject<{
2976
+ toolCallId: z.ZodString;
2977
+ result: z.ZodUnknown;
2978
+ providerMetadata: z.ZodOptional<z.ZodAny>;
2979
+ }, "strip", z.ZodTypeAny, {
2980
+ toolCallId: string;
2981
+ result?: unknown;
2982
+ providerMetadata?: any;
2983
+ }, {
2984
+ toolCallId: string;
2985
+ result?: unknown;
2986
+ providerMetadata?: any;
2987
+ }>;
2988
+ }, "strip", z.ZodTypeAny, {
2989
+ value: {
2990
+ toolCallId: string;
2991
+ result?: unknown;
2992
+ providerMetadata?: any;
2993
+ };
2994
+ type: "tool-result";
2995
+ }, {
2996
+ value: {
2997
+ toolCallId: string;
2998
+ result?: unknown;
2999
+ providerMetadata?: any;
3000
+ };
3001
+ type: "tool-result";
3002
+ }>, z.ZodObject<{
3003
+ type: z.ZodLiteral<"tool-call-streaming-start">;
3004
+ value: z.ZodObject<{
3005
+ toolCallId: z.ZodString;
3006
+ toolName: z.ZodString;
3007
+ }, "strip", z.ZodTypeAny, {
3008
+ toolName: string;
3009
+ toolCallId: string;
3010
+ }, {
3011
+ toolName: string;
3012
+ toolCallId: string;
3013
+ }>;
3014
+ }, "strip", z.ZodTypeAny, {
3015
+ value: {
3016
+ toolName: string;
3017
+ toolCallId: string;
3018
+ };
3019
+ type: "tool-call-streaming-start";
3020
+ }, {
3021
+ value: {
3022
+ toolName: string;
3023
+ toolCallId: string;
3024
+ };
3025
+ type: "tool-call-streaming-start";
3026
+ }>, z.ZodObject<{
3027
+ type: z.ZodLiteral<"tool-call-delta">;
3028
+ value: z.ZodObject<{
3029
+ toolCallId: z.ZodString;
3030
+ argsTextDelta: z.ZodString;
3031
+ }, "strip", z.ZodTypeAny, {
3032
+ toolCallId: string;
3033
+ argsTextDelta: string;
3034
+ }, {
3035
+ toolCallId: string;
3036
+ argsTextDelta: string;
3037
+ }>;
3038
+ }, "strip", z.ZodTypeAny, {
3039
+ value: {
3040
+ toolCallId: string;
3041
+ argsTextDelta: string;
3042
+ };
3043
+ type: "tool-call-delta";
3044
+ }, {
3045
+ value: {
3046
+ toolCallId: string;
3047
+ argsTextDelta: string;
3048
+ };
3049
+ type: "tool-call-delta";
3050
+ }>, z.ZodObject<{
3051
+ type: z.ZodLiteral<"finish-message">;
3052
+ value: z.ZodObject<{
3053
+ finishReason: z.ZodEnum<["stop", "length", "tool-calls", "content-filter", "other", "error", "unknown"]>;
3054
+ usage: z.ZodOptional<z.ZodObject<{
3055
+ inputTokens: z.ZodOptional<z.ZodNumber>;
3056
+ outputTokens: z.ZodOptional<z.ZodNumber>;
3057
+ totalTokens: z.ZodOptional<z.ZodNumber>;
3058
+ reasoningTokens: z.ZodOptional<z.ZodNumber>;
3059
+ cachedInputTokens: z.ZodOptional<z.ZodNumber>;
3060
+ }, "strip", z.ZodTypeAny, {
3061
+ inputTokens?: number | undefined;
3062
+ outputTokens?: number | undefined;
3063
+ totalTokens?: number | undefined;
3064
+ reasoningTokens?: number | undefined;
3065
+ cachedInputTokens?: number | undefined;
3066
+ }, {
3067
+ inputTokens?: number | undefined;
3068
+ outputTokens?: number | undefined;
3069
+ totalTokens?: number | undefined;
3070
+ reasoningTokens?: number | undefined;
3071
+ cachedInputTokens?: number | undefined;
3072
+ }>>;
3073
+ }, "strip", z.ZodTypeAny, {
3074
+ finishReason: "length" | "unknown" | "stop" | "content-filter" | "tool-calls" | "error" | "other";
3075
+ usage?: {
3076
+ inputTokens?: number | undefined;
3077
+ outputTokens?: number | undefined;
3078
+ totalTokens?: number | undefined;
3079
+ reasoningTokens?: number | undefined;
3080
+ cachedInputTokens?: number | undefined;
3081
+ } | undefined;
3082
+ }, {
3083
+ finishReason: "length" | "unknown" | "stop" | "content-filter" | "tool-calls" | "error" | "other";
3084
+ usage?: {
3085
+ inputTokens?: number | undefined;
3086
+ outputTokens?: number | undefined;
3087
+ totalTokens?: number | undefined;
3088
+ reasoningTokens?: number | undefined;
3089
+ cachedInputTokens?: number | undefined;
3090
+ } | undefined;
3091
+ }>;
3092
+ }, "strip", z.ZodTypeAny, {
3093
+ value: {
3094
+ finishReason: "length" | "unknown" | "stop" | "content-filter" | "tool-calls" | "error" | "other";
3095
+ usage?: {
3096
+ inputTokens?: number | undefined;
3097
+ outputTokens?: number | undefined;
3098
+ totalTokens?: number | undefined;
3099
+ reasoningTokens?: number | undefined;
3100
+ cachedInputTokens?: number | undefined;
3101
+ } | undefined;
3102
+ };
3103
+ type: "finish-message";
3104
+ }, {
3105
+ value: {
3106
+ finishReason: "length" | "unknown" | "stop" | "content-filter" | "tool-calls" | "error" | "other";
3107
+ usage?: {
3108
+ inputTokens?: number | undefined;
3109
+ outputTokens?: number | undefined;
3110
+ totalTokens?: number | undefined;
3111
+ reasoningTokens?: number | undefined;
3112
+ cachedInputTokens?: number | undefined;
3113
+ } | undefined;
3114
+ };
3115
+ type: "finish-message";
3116
+ }>, z.ZodObject<{
3117
+ type: z.ZodLiteral<"finish-step">;
3118
+ value: z.ZodObject<{
3119
+ isContinued: z.ZodBoolean;
3120
+ finishReason: z.ZodEnum<["stop", "length", "tool-calls", "content-filter", "other", "error", "unknown"]>;
3121
+ usage: z.ZodOptional<z.ZodObject<{
3122
+ inputTokens: z.ZodOptional<z.ZodNumber>;
3123
+ outputTokens: z.ZodOptional<z.ZodNumber>;
3124
+ totalTokens: z.ZodOptional<z.ZodNumber>;
3125
+ reasoningTokens: z.ZodOptional<z.ZodNumber>;
3126
+ cachedInputTokens: z.ZodOptional<z.ZodNumber>;
3127
+ }, "strip", z.ZodTypeAny, {
3128
+ inputTokens?: number | undefined;
3129
+ outputTokens?: number | undefined;
3130
+ totalTokens?: number | undefined;
3131
+ reasoningTokens?: number | undefined;
3132
+ cachedInputTokens?: number | undefined;
3133
+ }, {
3134
+ inputTokens?: number | undefined;
3135
+ outputTokens?: number | undefined;
3136
+ totalTokens?: number | undefined;
3137
+ reasoningTokens?: number | undefined;
3138
+ cachedInputTokens?: number | undefined;
3139
+ }>>;
3140
+ }, "strip", z.ZodTypeAny, {
3141
+ finishReason: "length" | "unknown" | "stop" | "content-filter" | "tool-calls" | "error" | "other";
3142
+ isContinued: boolean;
3143
+ usage?: {
3144
+ inputTokens?: number | undefined;
3145
+ outputTokens?: number | undefined;
3146
+ totalTokens?: number | undefined;
3147
+ reasoningTokens?: number | undefined;
3148
+ cachedInputTokens?: number | undefined;
3149
+ } | undefined;
3150
+ }, {
3151
+ finishReason: "length" | "unknown" | "stop" | "content-filter" | "tool-calls" | "error" | "other";
3152
+ isContinued: boolean;
3153
+ usage?: {
3154
+ inputTokens?: number | undefined;
3155
+ outputTokens?: number | undefined;
3156
+ totalTokens?: number | undefined;
3157
+ reasoningTokens?: number | undefined;
3158
+ cachedInputTokens?: number | undefined;
3159
+ } | undefined;
3160
+ }>;
3161
+ }, "strip", z.ZodTypeAny, {
3162
+ value: {
3163
+ finishReason: "length" | "unknown" | "stop" | "content-filter" | "tool-calls" | "error" | "other";
3164
+ isContinued: boolean;
3165
+ usage?: {
3166
+ inputTokens?: number | undefined;
3167
+ outputTokens?: number | undefined;
3168
+ totalTokens?: number | undefined;
3169
+ reasoningTokens?: number | undefined;
3170
+ cachedInputTokens?: number | undefined;
3171
+ } | undefined;
3172
+ };
3173
+ type: "finish-step";
3174
+ }, {
3175
+ value: {
3176
+ finishReason: "length" | "unknown" | "stop" | "content-filter" | "tool-calls" | "error" | "other";
3177
+ isContinued: boolean;
3178
+ usage?: {
3179
+ inputTokens?: number | undefined;
3180
+ outputTokens?: number | undefined;
3181
+ totalTokens?: number | undefined;
3182
+ reasoningTokens?: number | undefined;
3183
+ cachedInputTokens?: number | undefined;
3184
+ } | undefined;
3185
+ };
3186
+ type: "finish-step";
3187
+ }>, z.ZodObject<{
3188
+ type: z.ZodLiteral<"start-step">;
3189
+ value: z.ZodObject<{
3190
+ messageId: z.ZodString;
3191
+ }, "strip", z.ZodTypeAny, {
3192
+ messageId: string;
3193
+ }, {
3194
+ messageId: string;
3195
+ }>;
3196
+ }, "strip", z.ZodTypeAny, {
3197
+ value: {
3198
+ messageId: string;
3199
+ };
3200
+ type: "start-step";
3201
+ }, {
3202
+ value: {
3203
+ messageId: string;
3204
+ };
3205
+ type: "start-step";
3206
+ }>, z.ZodObject<{
3207
+ type: z.ZodLiteral<"reasoning">;
3208
+ value: z.ZodObject<{
3209
+ text: z.ZodString;
3210
+ providerMetadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
3211
+ }, "strip", z.ZodTypeAny, {
3212
+ text: string;
3213
+ providerMetadata?: Record<string, any> | undefined;
3214
+ }, {
3215
+ text: string;
3216
+ providerMetadata?: Record<string, any> | undefined;
3217
+ }>;
3218
+ }, "strip", z.ZodTypeAny, {
3219
+ value: {
3220
+ text: string;
3221
+ providerMetadata?: Record<string, any> | undefined;
3222
+ };
3223
+ type: "reasoning";
3224
+ }, {
3225
+ value: {
3226
+ text: string;
3227
+ providerMetadata?: Record<string, any> | undefined;
3228
+ };
3229
+ type: "reasoning";
3230
+ }>, z.ZodObject<{
3231
+ type: z.ZodLiteral<"source">;
3232
+ value: z.ZodObject<{
3233
+ type: z.ZodLiteral<"source">;
3234
+ sourceType: z.ZodLiteral<"url">;
3235
+ id: z.ZodString;
3236
+ url: z.ZodString;
3237
+ title: z.ZodOptional<z.ZodString>;
3238
+ providerMetadata: z.ZodOptional<z.ZodAny>;
3239
+ }, "strip", z.ZodTypeAny, {
3240
+ type: "source";
3241
+ id: string;
3242
+ sourceType: "url";
3243
+ url: string;
3244
+ providerMetadata?: any;
3245
+ title?: string | undefined;
3246
+ }, {
3247
+ type: "source";
3248
+ id: string;
3249
+ sourceType: "url";
3250
+ url: string;
3251
+ providerMetadata?: any;
3252
+ title?: string | undefined;
3253
+ }>;
3254
+ }, "strip", z.ZodTypeAny, {
3255
+ value: {
3256
+ type: "source";
3257
+ id: string;
3258
+ sourceType: "url";
3259
+ url: string;
3260
+ providerMetadata?: any;
3261
+ title?: string | undefined;
3262
+ };
3263
+ type: "source";
3264
+ }, {
3265
+ value: {
3266
+ type: "source";
3267
+ id: string;
3268
+ sourceType: "url";
3269
+ url: string;
3270
+ providerMetadata?: any;
3271
+ title?: string | undefined;
3272
+ };
3273
+ type: "source";
3274
+ }>, z.ZodObject<{
3275
+ type: z.ZodLiteral<"file">;
3276
+ value: z.ZodObject<{
3277
+ url: z.ZodString;
3278
+ mediaType: z.ZodString;
3279
+ }, "strip", z.ZodTypeAny, {
3280
+ mediaType: string;
3281
+ url: string;
3282
+ }, {
3283
+ mediaType: string;
3284
+ url: string;
3285
+ }>;
3286
+ }, "strip", z.ZodTypeAny, {
3287
+ value: {
3288
+ mediaType: string;
3289
+ url: string;
3290
+ };
3291
+ type: "file";
3292
+ }, {
3293
+ value: {
3294
+ mediaType: string;
3295
+ url: string;
3296
+ };
3297
+ type: "file";
3298
+ }>, z.ZodObject<{
3299
+ type: z.ZodLiteral<"reasoning-part-finish">;
3300
+ value: z.ZodNull;
3301
+ }, "strip", z.ZodTypeAny, {
3302
+ value: null;
3303
+ type: "reasoning-part-finish";
3304
+ }, {
3305
+ value: null;
3306
+ type: "reasoning-part-finish";
3307
+ }>]>;
3308
+ type DataStreamPart = z.infer<typeof dataStreamPartSchema>;
3101
3309
 
3102
3310
  type AsyncIterableStream<T> = AsyncIterable<T> & ReadableStream<T>;
3103
3311
 
3104
3312
  type DataStreamOptions = {
3313
+ /**
3314
+ * Process an error, e.g. to log it. Default to `() => 'An error occurred.'`.
3315
+ *
3316
+ * @return error message to include in the data stream.
3317
+ */
3318
+ onError?: (error: unknown) => string;
3105
3319
  /**
3106
3320
  * Send usage parts to the client.
3107
3321
  * Default to true.
@@ -3263,45 +3477,31 @@ interface StreamTextResult<TOOLS extends ToolSet, PARTIAL_OUTPUT> {
3263
3477
  /**
3264
3478
  Converts the result to a data stream.
3265
3479
 
3266
- @param data an optional StreamData object that will be merged into the stream.
3267
- @param getErrorMessage an optional function that converts an error to an error message.
3268
- @param sendUsage whether to send the usage information to the client. Defaults to true.
3269
- @param sendReasoning whether to send the reasoning information to the client. Defaults to false.
3480
+ @param options.getErrorMessage an optional function that converts an error to an error message.
3481
+ @param options.sendUsage whether to send the usage information to the client. Defaults to true.
3482
+ @param options.sendReasoning whether to send the reasoning information to the client. Defaults to false.
3483
+ @param options.sendSources whether to send the sources information to the client. Defaults to false.
3484
+ @param options.experimental_sendFinish whether to send the finish information to the client. Defaults to true.
3485
+ @param options.experimental_sendStart whether to send the start information to the client. Defaults to true.
3486
+
3270
3487
  @return A data stream.
3271
3488
  */
3272
- toDataStream(options?: {
3273
- data?: StreamData;
3274
- getErrorMessage?: (error: unknown) => string;
3275
- } & DataStreamOptions): ReadableStream<Uint8Array>;
3276
- /**
3277
- * Merges the result as a data stream into another data stream.
3278
- *
3279
- * @param dataStream A data stream writer.
3280
- * @param options.sendUsage Whether to send the usage information to the client. Defaults to true.
3281
- * @param options.sendReasoning Whether to send the reasoning information to the client. Defaults to false.
3282
- */
3283
- mergeIntoDataStream(dataStream: DataStreamWriter, options?: DataStreamOptions): void;
3489
+ toDataStream(options?: DataStreamOptions): ReadableStream<DataStreamPart>;
3284
3490
  /**
3285
3491
  Writes data stream output to a Node.js response-like object.
3286
-
3287
3492
  @param response A Node.js response-like object (ServerResponse).
3288
3493
  @param options.status The status code.
3289
3494
  @param options.statusText The status text.
3290
3495
  @param options.headers The headers.
3291
- @param options.data The stream data.
3292
3496
  @param options.getErrorMessage An optional function that converts an error to an error message.
3293
3497
  @param options.sendUsage Whether to send the usage information to the client. Defaults to true.
3294
3498
  @param options.sendReasoning Whether to send the reasoning information to the client. Defaults to false.
3295
3499
  */
3296
- pipeDataStreamToResponse(response: ServerResponse, options?: ResponseInit & {
3297
- data?: StreamData;
3298
- getErrorMessage?: (error: unknown) => string;
3299
- } & DataStreamOptions): void;
3500
+ pipeDataStreamToResponse(response: ServerResponse, options?: ResponseInit & DataStreamOptions): void;
3300
3501
  /**
3301
3502
  Writes text delta output to a Node.js response-like object.
3302
3503
  It sets a `Content-Type` header to `text/plain; charset=utf-8` and
3303
3504
  writes each text delta as a separate chunk.
3304
-
3305
3505
  @param response A Node.js response-like object (ServerResponse).
3306
3506
  @param init Optional headers, status code, and status text.
3307
3507
  */
@@ -3309,7 +3509,6 @@ interface StreamTextResult<TOOLS extends ToolSet, PARTIAL_OUTPUT> {
3309
3509
  /**
3310
3510
  Converts the result to a streamed response object with a stream data part stream.
3311
3511
  It can be used with the `useChat` and `useCompletion` hooks.
3312
-
3313
3512
  @param options.status The status code.
3314
3513
  @param options.statusText The status text.
3315
3514
  @param options.headers The headers.
@@ -3317,18 +3516,13 @@ interface StreamTextResult<TOOLS extends ToolSet, PARTIAL_OUTPUT> {
3317
3516
  @param options.getErrorMessage An optional function that converts an error to an error message.
3318
3517
  @param options.sendUsage Whether to send the usage information to the client. Defaults to true.
3319
3518
  @param options.sendReasoning Whether to send the reasoning information to the client. Defaults to false.
3320
-
3321
3519
  @return A response object.
3322
3520
  */
3323
- toDataStreamResponse(options?: ResponseInit & {
3324
- data?: StreamData;
3325
- getErrorMessage?: (error: unknown) => string;
3326
- } & DataStreamOptions): Response;
3521
+ toDataStreamResponse(options?: ResponseInit & DataStreamOptions): Response;
3327
3522
  /**
3328
3523
  Creates a simple text stream response.
3329
3524
  Each text delta is encoded as UTF-8 and sent as a separate chunk.
3330
3525
  Non-text-delta events are ignored.
3331
-
3332
3526
  @param init Optional headers, status code, and status text.
3333
3527
  */
3334
3528
  toTextStreamResponse(init?: ResponseInit): Response;
@@ -3536,7 +3730,7 @@ By default, it's set to 1, which means that only a single LLM call is made.
3536
3730
  /**
3537
3731
  Generate a unique ID for each message.
3538
3732
  */
3539
- experimental_generateMessageId?: IdGenerator$1;
3733
+ experimental_generateMessageId?: IdGenerator;
3540
3734
  /**
3541
3735
  When enabled, the model will perform additional steps if the finish reason is "length" (experimental).
3542
3736
 
@@ -3607,7 +3801,7 @@ Internal. For test use only. May change without notice.
3607
3801
  */
3608
3802
  _internal?: {
3609
3803
  now?: () => number;
3610
- generateId?: IdGenerator$1;
3804
+ generateId?: IdGenerator;
3611
3805
  currentDate?: () => Date;
3612
3806
  };
3613
3807
  }): StreamTextResult<TOOLS, PARTIAL_OUTPUT>;
@@ -4388,6 +4582,8 @@ declare const experimental_createProviderRegistry: typeof createProviderRegistry
4388
4582
 
4389
4583
  declare function getToolInvocations(message: UIMessage): ToolInvocation[];
4390
4584
 
4585
+ declare function getUIText(parts: UIMessagePart[]): string;
4586
+
4391
4587
  /**
4392
4588
  * Calculates the cosine similarity between two vectors. This is a useful metric for
4393
4589
  * comparing the similarity of two vectors such as embeddings.
@@ -4420,6 +4616,95 @@ declare function simulateReadableStream<T>({ chunks, initialDelayInMs, chunkDela
4420
4616
  };
4421
4617
  }): ReadableStream<T>;
4422
4618
 
4619
+ interface DataStreamWriter {
4620
+ /**
4621
+ * Appends a data stream part to the stream.
4622
+ */
4623
+ write(part: DataStreamPart): void;
4624
+ /**
4625
+ * Merges the contents of another stream to this stream.
4626
+ */
4627
+ merge(stream: ReadableStream<DataStreamPart>): void;
4628
+ /**
4629
+ * Error handler that is used by the data stream writer.
4630
+ * This is intended for forwarding when merging streams
4631
+ * to prevent duplicated error masking.
4632
+ */
4633
+ onError: ((error: unknown) => string) | undefined;
4634
+ }
4635
+
4636
+ declare function createDataStream({ execute, onError, }: {
4637
+ execute: (writer: DataStreamWriter) => Promise<void> | void;
4638
+ onError?: (error: unknown) => string;
4639
+ }): ReadableStream<DataStreamPart>;
4640
+
4641
+ declare function createDataStreamResponse({ status, statusText, headers, dataStream, }: ResponseInit & {
4642
+ dataStream: ReadableStream<DataStreamPart>;
4643
+ }): Response;
4644
+
4645
+ declare function pipeDataStreamToResponse({ response, status, statusText, headers, dataStream, }: {
4646
+ response: ServerResponse;
4647
+ dataStream: ReadableStream<DataStreamPart>;
4648
+ } & ResponseInit): void;
4649
+
4650
+ declare function processDataStream({ stream, onTextPart, onReasoningPart, onReasoningPartFinish, onSourcePart, onFilePart, onDataPart, onErrorPart, onToolCallStreamingStartPart, onToolCallDeltaPart, onToolCallPart, onToolResultPart, onMessageAnnotationsPart, onFinishMessagePart, onFinishStepPart, onStartStepPart, }: {
4651
+ stream: ReadableStream<Uint8Array>;
4652
+ onTextPart?: (streamPart: (DataStreamPart & {
4653
+ type: 'text';
4654
+ })['value']) => Promise<void> | void;
4655
+ onReasoningPart?: (streamPart: (DataStreamPart & {
4656
+ type: 'reasoning';
4657
+ })['value']) => Promise<void> | void;
4658
+ onReasoningPartFinish?: (streamPart: (DataStreamPart & {
4659
+ type: 'reasoning-part-finish';
4660
+ })['value']) => Promise<void> | void;
4661
+ onFilePart?: (streamPart: (DataStreamPart & {
4662
+ type: 'file';
4663
+ })['value']) => Promise<void> | void;
4664
+ onSourcePart?: (streamPart: (DataStreamPart & {
4665
+ type: 'source';
4666
+ })['value']) => Promise<void> | void;
4667
+ onDataPart?: (streamPart: (DataStreamPart & {
4668
+ type: 'data';
4669
+ })['value']) => Promise<void> | void;
4670
+ onErrorPart?: (streamPart: (DataStreamPart & {
4671
+ type: 'error';
4672
+ })['value']) => Promise<void> | void;
4673
+ onToolCallStreamingStartPart?: (streamPart: (DataStreamPart & {
4674
+ type: 'tool-call-streaming-start';
4675
+ })['value']) => Promise<void> | void;
4676
+ onToolCallDeltaPart?: (streamPart: (DataStreamPart & {
4677
+ type: 'tool-call-delta';
4678
+ })['value']) => Promise<void> | void;
4679
+ onToolCallPart?: (streamPart: ToolCall<string, any>) => Promise<void> | void;
4680
+ onToolResultPart?: (streamPart: ToolResult<string, any, any>) => Promise<void> | void;
4681
+ onMessageAnnotationsPart?: (streamPart: (DataStreamPart & {
4682
+ type: 'message-annotations';
4683
+ })['value']) => Promise<void> | void;
4684
+ onFinishMessagePart?: (streamPart: (DataStreamPart & {
4685
+ type: 'finish-message';
4686
+ })['value']) => Promise<void> | void;
4687
+ onFinishStepPart?: (streamPart: (DataStreamPart & {
4688
+ type: 'finish-step';
4689
+ })['value']) => Promise<void> | void;
4690
+ onStartStepPart?: (streamPart: (DataStreamPart & {
4691
+ type: 'start-step';
4692
+ })['value']) => Promise<void> | void;
4693
+ }): Promise<void>;
4694
+
4695
+ declare class DataStreamToSSETransformStream extends TransformStream<DataStreamPart, string> {
4696
+ constructor();
4697
+ }
4698
+
4699
+ declare function createTextStreamResponse({ status, statusText, headers, textStream, }: ResponseInit & {
4700
+ textStream: ReadableStream<string>;
4701
+ }): Response;
4702
+
4703
+ declare function pipeTextStreamToResponse({ response, status, statusText, headers, textStream, }: {
4704
+ response: ServerResponse;
4705
+ textStream: ReadableStream<string>;
4706
+ } & ResponseInit): void;
4707
+
4423
4708
  declare const symbol$c: unique symbol;
4424
4709
  declare class InvalidArgumentError extends AISDKError {
4425
4710
  private readonly [symbol$c];
@@ -4670,4 +4955,4 @@ declare class RetryError extends AISDKError {
4670
4955
  static isInstance(error: unknown): error is RetryError;
4671
4956
  }
4672
4957
 
4673
- export { AssistantContent, AssistantModelMessage, CallSettings, CallWarning, ChatRequest, ChatRequestOptions, ChunkDetector, CoreAssistantMessage, CoreMessage, CoreSystemMessage, CoreToolMessage, CoreUserMessage, CreateUIMessage, DataContent, DataStreamOptions, DataStreamPart, DataStreamString, DataStreamWriter, DeepPartial, DownloadError, EmbedManyResult, EmbedResult, Embedding, EmbeddingModel, EmbeddingModelUsage, GenerateImageResult as Experimental_GenerateImageResult, GeneratedFile as Experimental_GeneratedImage, SpeechResult as Experimental_SpeechResult, TranscriptionResult as Experimental_TranscriptionResult, FilePart, FileUIPart, FinishReason, GenerateObjectResult, GenerateTextOnStepFinishCallback, GenerateTextResult, GeneratedAudioFile, GeneratedFile, ImageModel, ImageGenerationWarning as ImageModelCallWarning, ImageModelProviderMetadata, ImageModelResponseMetadata, ImagePart, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidStreamPartError, InvalidToolArgumentsError, JSONRPCError, JSONRPCMessage, JSONRPCNotification, JSONRPCRequest, JSONRPCResponse, JSONValue, LanguageModel, LanguageModelRequestMetadata, LanguageModelResponseMetadata, LanguageModelUsage, MCPClientError, MCPTransport, MessageConversionError, ModelMessage, NoImageGeneratedError, NoObjectGeneratedError, NoOutputSpecifiedError, NoSuchProviderError, NoSuchToolError, ObjectStreamPart, output as Output, Prompt, Provider, ProviderMetadata, ProviderOptions, ProviderRegistryProvider, ReasoningUIPart, RepairTextFunction, RequestOptions, RetryError, SourceUIPart, SpeechModel, SpeechModelResponseMetadata, SpeechWarning, StepResult, StepStartUIPart, StreamData, StreamObjectOnFinishCallback, StreamObjectResult, StreamTextOnChunkCallback, StreamTextOnErrorCallback, StreamTextOnFinishCallback, StreamTextOnStepFinishCallback, StreamTextResult, StreamTextTransform, SystemModelMessage, TelemetrySettings, TextPart, TextStreamPart, TextUIPart, Tool, ToolCallPart, ToolCallRepairError, ToolCallRepairFunction, ToolCallUnion, ToolChoice, ToolContent, ToolExecutionError, ToolExecutionOptions, ToolInvocation, ToolInvocationUIPart, ToolModelMessage, ToolResultPart, ToolResultUnion, ToolSet, TranscriptionModel, TranscriptionModelResponseMetadata, TranscriptionWarning, UIMessage, UIMessagePart, UseChatOptions, UseCompletionOptions, UserContent, UserModelMessage, appendClientMessage, appendResponseMessages, assistantModelMessageSchema, callChatApi, callCompletionApi, convertFileListToFileUIParts, convertToCoreMessages, convertToModelMessages, coreAssistantMessageSchema, coreMessageSchema, coreSystemMessageSchema, coreToolMessageSchema, coreUserMessageSchema, cosineSimilarity, createDataStream, createDataStreamResponse, createProviderRegistry, customProvider, defaultSettingsMiddleware, embed, embedMany, createMCPClient as experimental_createMCPClient, experimental_createProviderRegistry, experimental_customProvider, generateImage as experimental_generateImage, generateSpeech as experimental_generateSpeech, transcribe as experimental_transcribe, extractMaxToolInvocationStep, extractReasoningMiddleware, formatDataStreamPart, generateObject, generateText, getTextFromDataUrl, getToolInvocations, isAssistantMessageWithCompletedToolCalls, isDeepEqualData, modelMessageSchema, parseDataStreamPart, parsePartialJson, pipeDataStreamToResponse, processDataStream, processTextStream, shouldResubmitMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, streamObject, streamText, systemModelMessageSchema, tool, toolModelMessageSchema, updateToolCallResult, userModelMessageSchema, wrapLanguageModel };
4958
+ export { AssistantContent, AssistantModelMessage, CallSettings, CallWarning, ChatRequest, ChatRequestOptions, ChunkDetector, CoreAssistantMessage, CoreMessage, CoreSystemMessage, CoreToolMessage, CoreUserMessage, CreateUIMessage, DataContent, DataStreamOptions, DataStreamPart, DataStreamToSSETransformStream, DataStreamWriter, DeepPartial, DownloadError, EmbedManyResult, EmbedResult, Embedding, EmbeddingModel, EmbeddingModelUsage, GenerateImageResult as Experimental_GenerateImageResult, GeneratedFile as Experimental_GeneratedImage, SpeechResult as Experimental_SpeechResult, TranscriptionResult as Experimental_TranscriptionResult, FilePart, FileUIPart, FinishReason, GenerateObjectResult, GenerateTextOnStepFinishCallback, GenerateTextResult, GeneratedAudioFile, GeneratedFile, ImageModel, ImageGenerationWarning as ImageModelCallWarning, ImageModelProviderMetadata, ImageModelResponseMetadata, ImagePart, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidStreamPartError, InvalidToolArgumentsError, JSONRPCError, JSONRPCMessage, JSONRPCNotification, JSONRPCRequest, JSONRPCResponse, JSONValue, LanguageModel, LanguageModelRequestMetadata, LanguageModelResponseMetadata, LanguageModelUsage, MCPClientError, MCPTransport, MessageConversionError, ModelMessage, NoImageGeneratedError, NoObjectGeneratedError, NoOutputSpecifiedError, NoSuchProviderError, NoSuchToolError, ObjectStreamPart, output as Output, Prompt, Provider, ProviderMetadata, ProviderOptions, ProviderRegistryProvider, ReasoningUIPart, RepairTextFunction, RequestOptions, RetryError, SourceUIPart, SpeechModel, SpeechModelResponseMetadata, SpeechWarning, StepResult, StepStartUIPart, StreamObjectOnFinishCallback, StreamObjectResult, StreamTextOnChunkCallback, StreamTextOnErrorCallback, StreamTextOnFinishCallback, StreamTextOnStepFinishCallback, StreamTextResult, StreamTextTransform, SystemModelMessage, TelemetrySettings, TextPart, TextStreamPart, TextUIPart, Tool, ToolCallPart, ToolCallRepairError, ToolCallRepairFunction, ToolCallUnion, ToolChoice, ToolContent, ToolExecutionError, ToolExecutionOptions, ToolInvocation, ToolInvocationUIPart, ToolModelMessage, ToolResultPart, ToolResultUnion, ToolSet, TranscriptionModel, TranscriptionModelResponseMetadata, TranscriptionWarning, UIMessage, UIMessagePart, UseChatOptions, UseCompletionOptions, UserContent, UserModelMessage, appendClientMessage, appendResponseMessages, assistantModelMessageSchema, callChatApi, callCompletionApi, convertFileListToFileUIParts, convertToCoreMessages, convertToModelMessages, coreAssistantMessageSchema, coreMessageSchema, coreSystemMessageSchema, coreToolMessageSchema, coreUserMessageSchema, cosineSimilarity, createDataStream, createDataStreamResponse, createProviderRegistry, createTextStreamResponse, customProvider, defaultSettingsMiddleware, embed, embedMany, createMCPClient as experimental_createMCPClient, experimental_createProviderRegistry, experimental_customProvider, generateImage as experimental_generateImage, generateSpeech as experimental_generateSpeech, transcribe as experimental_transcribe, extractMaxToolInvocationStep, extractReasoningMiddleware, generateObject, generateText, getTextFromDataUrl, getToolInvocations, getUIText, isAssistantMessageWithCompletedToolCalls, isDeepEqualData, modelMessageSchema, parsePartialJson, pipeDataStreamToResponse, pipeTextStreamToResponse, processDataStream, processTextStream, shouldResubmitMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, streamObject, streamText, systemModelMessageSchema, tool, toolModelMessageSchema, updateToolCallResult, userModelMessageSchema, wrapLanguageModel };