UNPKG

ai

Version:

AI SDK by Vercel - The AI Toolkit for TypeScript and JavaScript

1,513 lines (1,395 loc) • 90.6 kB
import { DataStreamString, ToolInvocation, Attachment, Schema, DeepPartial, JSONValue as JSONValue$1, AssistantMessage, DataMessage } from '@ai-sdk/ui-utils'; export { AssistantMessage, AssistantStatus, Attachment, ChatRequest, ChatRequestOptions, CreateMessage, DataMessage, DataStreamPart, DeepPartial, IdGenerator, JSONValue, Message, RequestOptions, Schema, ToolInvocation, UseAssistantOptions, formatAssistantStreamPart, formatDataStreamPart, jsonSchema, parseAssistantStreamPart, parseDataStreamPart, processDataStream, processTextStream } from '@ai-sdk/ui-utils'; export { ToolCall as CoreToolCall, ToolResult as CoreToolResult, generateId } from '@ai-sdk/provider-utils'; import { JSONValue, EmbeddingModelV1, EmbeddingModelV1Embedding, LanguageModelV1, LanguageModelV1FinishReason, LanguageModelV1LogProbs, LanguageModelV1CallWarning, LanguageModelV1ProviderMetadata, ImageModelV1, LanguageModelV1CallOptions, AISDKError, LanguageModelV1FunctionToolCall, JSONSchema7, NoSuchModelError } from '@ai-sdk/provider'; export { AISDKError, APICallError, EmptyResponseBodyError, InvalidPromptError, InvalidResponseDataError, JSONParseError, LanguageModelV1, LanguageModelV1CallOptions, LanguageModelV1Prompt, LanguageModelV1StreamPart, LoadAPIKeyError, NoContentGeneratedError, NoSuchModelError, TypeValidationError, UnsupportedFunctionalityError } from '@ai-sdk/provider'; import { ServerResponse } from 'node:http'; import { AttributeValue, Tracer } from '@opentelemetry/api'; import { z } from 'zod'; import { ServerResponse as ServerResponse$1 } from 'http'; interface DataStreamWriter { /** * Appends a data part to the stream. */ writeData(value: JSONValue): void; /** * Appends a message annotation to the stream. */ writeMessageAnnotation(value: JSONValue): void; /** * Merges the contents of another stream to this stream. */ merge(stream: ReadableStream<DataStreamString>): void; /** * Error handler that is used by the data stream writer. * This is intended for forwarding when merging streams * to prevent duplicated error masking. */ onError: ((error: unknown) => string) | undefined; } declare function createDataStream({ execute, onError, }: { execute: (dataStream: DataStreamWriter) => Promise<void> | void; onError?: (error: unknown) => string; }): ReadableStream<DataStreamString>; declare function createDataStreamResponse({ status, statusText, headers, execute, onError, }: ResponseInit & { execute: (dataStream: DataStreamWriter) => Promise<void> | void; onError?: (error: unknown) => string; }): Response; declare function pipeDataStreamToResponse(response: ServerResponse, { status, statusText, headers, execute, onError, }: ResponseInit & { execute: (writer: DataStreamWriter) => Promise<void> | void; onError?: (error: unknown) => string; }): void; /** * Telemetry configuration. */ type TelemetrySettings = { /** * Enable or disable telemetry. Disabled by default while experimental. */ isEnabled?: boolean; /** * Enable or disable input recording. Enabled by default. * * You might want to disable input recording to avoid recording sensitive * information, to reduce data transfers, or to increase performance. */ recordInputs?: boolean; /** * Enable or disable output recording. Enabled by default. * * You might want to disable output recording to avoid recording sensitive * information, to reduce data transfers, or to increase performance. */ recordOutputs?: boolean; /** * Identifier for this function. Used to group telemetry data by function. */ functionId?: string; /** * Additional information to include in the telemetry data. */ metadata?: Record<string, AttributeValue>; /** * A custom tracer to use for the telemetry data. */ tracer?: Tracer; }; /** Embedding model that is used by the AI SDK Core functions. */ type EmbeddingModel<VALUE> = EmbeddingModelV1<VALUE>; /** Embedding. */ type Embedding = EmbeddingModelV1Embedding; /** Language model that is used by the AI SDK Core functions. */ type LanguageModel = LanguageModelV1; /** Reason why a language model finished generating a response. Can be one of the following: - `stop`: model generated stop sequence - `length`: model generated maximum number of tokens - `content-filter`: content filter violation stopped the model - `tool-calls`: model triggered tool calls - `error`: model stopped because of an error - `other`: model stopped for other reasons */ type FinishReason = LanguageModelV1FinishReason; /** Log probabilities for each token and its top log probabilities. @deprecated Will become a provider extension in the future. */ type LogProbs = LanguageModelV1LogProbs; /** Warning from the model provider for this call. The call will proceed, but e.g. some settings might not be supported, which can lead to suboptimal results. */ type CallWarning = LanguageModelV1CallWarning; /** Tool choice for the generation. It supports the following settings: - `auto` (default): the model can choose whether and which tools to call. - `required`: the model must call a tool. It can choose which tool to call. - `none`: the model must not call tools - `{ type: 'tool', toolName: string (typed) }`: the model must call the specified tool */ type CoreToolChoice<TOOLS extends Record<string, unknown>> = 'auto' | 'none' | 'required' | { type: 'tool'; toolName: keyof TOOLS; }; type LanguageModelRequestMetadata = { /** Raw request HTTP body that was sent to the provider API as a string (JSON should be stringified). */ body?: string; }; type LanguageModelResponseMetadata = { /** ID for the generated response. */ id: string; /** Timestamp for the start of the generated response. */ timestamp: Date; /** The ID of the response model that was used to generate the response. */ modelId: string; /** Response headers. */ headers?: Record<string, string>; }; /** * Provider for language and text embedding models. */ type Provider = { /** Returns the language model with the given id. The model id is then passed to the provider function to get the model. @param {string} id - The id of the model to return. @returns {LanguageModel} The language model associated with the id @throws {NoSuchModelError} If no such model exists. */ languageModel(modelId: string): LanguageModel; /** Returns the text embedding model with the given id. The model id is then passed to the provider function to get the model. @param {string} id - The id of the model to return. @returns {LanguageModel} The language model associated with the id @throws {NoSuchModelError} If no such model exists. */ textEmbeddingModel(modelId: string): EmbeddingModel<string>; }; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ type ProviderMetadata = LanguageModelV1ProviderMetadata; /** Represents the number of tokens used in a prompt and completion. */ type LanguageModelUsage = { /** The number of tokens used in the prompt. */ promptTokens: number; /** The number of tokens used in the completion. */ completionTokens: number; /** The total number of tokens used (promptTokens + completionTokens). */ totalTokens: number; }; /** Represents the number of tokens used in an embedding. */ type EmbeddingModelUsage = { /** The number of tokens used in the embedding. */ tokens: number; }; /** The result of an `embed` call. It contains the embedding, the value, and additional information. */ interface EmbedResult<VALUE> { /** The value that was embedded. */ readonly value: VALUE; /** The embedding of the value. */ readonly embedding: Embedding; /** The embedding token usage. */ readonly usage: EmbeddingModelUsage; /** Optional raw response data. */ readonly rawResponse?: { /** Response headers. */ headers?: Record<string, string>; }; } /** Embed a value using an embedding model. The type of the value is defined by the embedding model. @param model - The embedding model to use. @param value - The value that should be embedded. @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. @param abortSignal - An optional abort signal that can be used to cancel the call. @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. @returns A result object that contains the embedding, the value, and additional information. */ declare function embed<VALUE>({ model, value, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry: telemetry, }: { /** The embedding model to use. */ model: EmbeddingModel<VALUE>; /** The value that should be embedded. */ value: VALUE; /** Maximum number of retries per embedding model call. Set to 0 to disable retries. @default 2 */ maxRetries?: number; /** Abort signal. */ abortSignal?: AbortSignal; /** Additional headers to include in the request. Only applicable for HTTP-based providers. */ headers?: Record<string, string>; /** * Optional telemetry configuration (experimental). */ experimental_telemetry?: TelemetrySettings; }): Promise<EmbedResult<VALUE>>; /** The result of a `embedMany` call. It contains the embeddings, the values, and additional information. */ interface EmbedManyResult<VALUE> { /** The values that were embedded. */ readonly values: Array<VALUE>; /** The embeddings. They are in the same order as the values. */ readonly embeddings: Array<Embedding>; /** The embedding token usage. */ readonly usage: EmbeddingModelUsage; } /** Embed several values using an embedding model. The type of the value is defined by the embedding model. `embedMany` automatically splits large requests into smaller chunks if the model has a limit on how many embeddings can be generated in a single call. @param model - The embedding model to use. @param values - The values that should be embedded. @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. @param abortSignal - An optional abort signal that can be used to cancel the call. @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. @returns A result object that contains the embeddings, the value, and additional information. */ declare function embedMany<VALUE>({ model, values, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry: telemetry, }: { /** The embedding model to use. */ model: EmbeddingModel<VALUE>; /** The values that should be embedded. */ values: Array<VALUE>; /** Maximum number of retries per embedding model call. Set to 0 to disable retries. @default 2 */ maxRetries?: number; /** Abort signal. */ abortSignal?: AbortSignal; /** Additional headers to include in the request. Only applicable for HTTP-based providers. */ headers?: Record<string, string>; /** * Optional telemetry configuration (experimental). */ experimental_telemetry?: TelemetrySettings; }): Promise<EmbedManyResult<VALUE>>; /** The result of a `generateImage` call. It contains the images and additional information. */ interface GenerateImageResult { /** The first image that was generated. */ readonly image: GeneratedImage; /** The images that were generated. */ readonly images: Array<GeneratedImage>; } interface GeneratedImage { /** Image as a base64 encoded string. */ readonly base64: string; /** Image as a Uint8Array. */ readonly uint8Array: Uint8Array; } /** Generates images using an image model. @param model - The image model to use. @param prompt - The prompt that should be used to generate the image. @param n - Number of images to generate. Default: 1. @param size - Size of the images to generate. Must have the format `{width}x{height}`. @param providerOptions - Additional provider-specific options that are passed through to the provider as body parameters. @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2. @param abortSignal - An optional abort signal that can be used to cancel the call. @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. @returns A result object that contains the generated images. */ declare function generateImage({ model, prompt, n, size, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, }: { /** The image model to use. */ model: ImageModelV1; /** The prompt that should be used to generate the image. */ prompt: string; /** Number of images to generate. */ n?: number; /** Size of the images to generate. Must have the format `{width}x{height}`. */ size?: `${number}x${number}`; /** Additional provider-specific options that are passed through to the provider as body parameters. The outer record is keyed by the provider name, and the inner record is keyed by the provider-specific metadata key. ```ts { "openai": { "style": "vivid" } } ``` */ providerOptions?: Record<string, Record<string, JSONValue>>; /** Maximum number of retries per embedding model call. Set to 0 to disable retries. @default 2 */ maxRetries?: number; /** Abort signal. */ abortSignal?: AbortSignal; /** Additional headers to include in the request. Only applicable for HTTP-based providers. */ headers?: Record<string, string>; }): Promise<GenerateImageResult>; type CallSettings = { /** Maximum number of tokens to generate. */ maxTokens?: number; /** Temperature setting. This is a number between 0 (almost no randomness) and 1 (very random). It is recommended to set either `temperature` or `topP`, but not both. @default 0 */ temperature?: number; /** Nucleus sampling. This is a number between 0 and 1. E.g. 0.1 would mean that only tokens with the top 10% probability mass are considered. It is recommended to set either `temperature` or `topP`, but not both. */ topP?: number; /** Only sample from the top K options for each subsequent token. Used to remove "long tail" low probability responses. Recommended for advanced use cases only. You usually only need to use temperature. */ topK?: number; /** Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt. The presence penalty is a number between -1 (increase repetition) and 1 (maximum penalty, decrease repetition). 0 means no penalty. */ presencePenalty?: number; /** Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases. The frequency penalty is a number between -1 (increase repetition) and 1 (maximum penalty, decrease repetition). 0 means no penalty. */ frequencyPenalty?: number; /** Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated. Providers may have limits on the number of stop sequences. */ stopSequences?: string[]; /** The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results. */ seed?: number; /** Maximum number of retries. Set to 0 to disable retries. @default 2 */ maxRetries?: number; /** Abort signal. */ abortSignal?: AbortSignal; /** Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. */ headers?: Record<string, string | undefined>; }; /** Data content. Can either be a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer. */ type DataContent = string | Uint8Array | ArrayBuffer | Buffer; type ToolResultContent = Array<{ type: 'text'; text: string; } | { type: 'image'; data: string; mimeType?: string; }>; /** Text content part of a prompt. It contains a string of text. */ interface TextPart { type: 'text'; /** The text content. */ text: string; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; } /** Image content part of a prompt. It contains an image. */ interface ImagePart { type: 'image'; /** Image data. Can either be: - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer - URL: a URL that points to the image */ image: DataContent | URL; /** Optional mime type of the image. */ mimeType?: string; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; } /** File content part of a prompt. It contains a file. */ interface FilePart { type: 'file'; /** File data. Can either be: - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer - URL: a URL that points to the image */ data: DataContent | URL; /** Mime type of the file. */ mimeType: string; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; } /** Tool call content part of a prompt. It contains a tool call (usually generated by the AI model). */ interface ToolCallPart { type: 'tool-call'; /** ID of the tool call. This ID is used to match the tool call with the tool result. */ toolCallId: string; /** Name of the tool that is being called. */ toolName: string; /** Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema. */ args: unknown; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; } /** Tool result content part of a prompt. It contains the result of the tool call with the matching ID. */ interface ToolResultPart { type: 'tool-result'; /** ID of the tool call that this result is associated with. */ toolCallId: string; /** Name of the tool that generated this result. */ toolName: string; /** Result of the tool call. This is a JSON-serializable object. */ result: unknown; /** Multi-part content of the tool result. Only for tools that support multipart results. */ experimental_content?: ToolResultContent; /** Optional flag if the result is an error or an error message. */ isError?: boolean; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; } /** A system message. It can contain system information. Note: using the "system" part of the prompt is strongly preferred to increase the resilience against prompt injection attacks, and because not all providers support several system messages. */ type CoreSystemMessage = { role: 'system'; content: string; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; }; /** A user message. It can contain text or a combination of text and images. */ type CoreUserMessage = { role: 'user'; content: UserContent; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; }; /** Content of a user message. It can be a string or an array of text and image parts. */ type UserContent = string | Array<TextPart | ImagePart | FilePart>; /** An assistant message. It can contain text, tool calls, or a combination of text and tool calls. */ type CoreAssistantMessage = { role: 'assistant'; content: AssistantContent; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; }; /** Content of an assistant message. It can be a string or an array of text and tool call parts. */ type AssistantContent = string | Array<TextPart | ToolCallPart>; /** A tool message. It contains the result of one or more tool calls. */ type CoreToolMessage = { role: 'tool'; content: ToolContent; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; }; /** Content of a tool message. It is an array of tool result parts. */ type ToolContent = Array<ToolResultPart>; /** A message that can be used in the `messages` field of a prompt. It can be a user message, an assistant message, or a tool message. */ type CoreMessage = CoreSystemMessage | CoreUserMessage | CoreAssistantMessage | CoreToolMessage; type UIMessage = { role: 'system' | 'user' | 'assistant' | 'data'; content: string; toolInvocations?: ToolInvocation[]; experimental_attachments?: Attachment[]; }; /** Prompt part of the AI function options. It contains a system message, a simple text prompt, or a list of messages. */ type Prompt = { /** System message to include in the prompt. Can be used with `prompt` or `messages`. */ system?: string; /** A simple text prompt. You can either use `prompt` or `messages` but not both. */ prompt?: string; /** A list of messages. You can either use `prompt` or `messages` but not both. */ messages?: Array<CoreMessage> | Array<UIMessage>; }; /** The result of a `generateObject` call. */ interface GenerateObjectResult<OBJECT> { /** The generated object (typed according to the schema). */ readonly object: OBJECT; /** The reason why the generation finished. */ readonly finishReason: FinishReason; /** The token usage of the generated text. */ readonly usage: LanguageModelUsage; /** Warnings from the model provider (e.g. unsupported settings). */ readonly warnings: CallWarning[] | undefined; /** Additional request information. */ readonly request: LanguageModelRequestMetadata; /** Additional response information. */ readonly response: LanguageModelResponseMetadata; /** Logprobs for the completion. `undefined` if the mode does not support logprobs or if was not enabled. @deprecated Will become a provider extension in the future. */ readonly logprobs: LogProbs | undefined; /** Additional provider-specific metadata. They are passed through from the provider to the AI SDK and enable provider-specific results that can be fully encapsulated in the provider. */ readonly experimental_providerMetadata: ProviderMetadata | undefined; /** Converts the object to a JSON response. The response will have a status code of 200 and a content type of `application/json; charset=utf-8`. */ toJsonResponse(init?: ResponseInit): Response; } /** Generate a structured, typed object for a given prompt and schema using a language model. This function does not stream the output. If you want to stream the output, use `streamObject` instead. @returns A result object that contains the generated object, the finish reason, the token usage, and additional information. */ declare function generateObject<OBJECT>(options: Omit<CallSettings, 'stopSequences'> & Prompt & { output?: 'object' | undefined; /** The language model to use. */ model: LanguageModel; /** The schema of the object that the model should generate. */ schema: z.Schema<OBJECT, z.ZodTypeDef, any> | Schema<OBJECT>; /** Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. */ schemaName?: string; /** Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description. */ schemaDescription?: string; /** The mode to use for object generation. The schema is converted into a JSON schema and used in one of the following ways - 'auto': The provider will choose the best mode for the model. - 'tool': A tool with the JSON schema as parameters is provided and the provider is instructed to use it. - '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. Please note that most providers do not support all modes. Default and recommended: 'auto' (best mode for the model). */ mode?: 'auto' | 'json' | 'tool'; /** Optional telemetry configuration (experimental). */ experimental_telemetry?: TelemetrySettings; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: () => string; currentDate?: () => Date; }; }): Promise<GenerateObjectResult<OBJECT>>; /** Generate an array with structured, typed elements for a given prompt and element schema using a language model. This function does not stream the output. If you want to stream the output, use `streamObject` instead. @return A result object that contains the generated object, the finish reason, the token usage, and additional information. */ declare function generateObject<ELEMENT>(options: Omit<CallSettings, 'stopSequences'> & Prompt & { output: 'array'; /** The language model to use. */ model: LanguageModel; /** The element schema of the array that the model should generate. */ schema: z.Schema<ELEMENT, z.ZodTypeDef, any> | Schema<ELEMENT>; /** Optional name of the array that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. */ schemaName?: string; /** Optional description of the array that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description. */ schemaDescription?: string; /** The mode to use for object generation. The schema is converted into a JSON schema and used in one of the following ways - 'auto': The provider will choose the best mode for the model. - 'tool': A tool with the JSON schema as parameters is provided and the provider is instructed to use it. - '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. Please note that most providers do not support all modes. Default and recommended: 'auto' (best mode for the model). */ mode?: 'auto' | 'json' | 'tool'; /** Optional telemetry configuration (experimental). */ experimental_telemetry?: TelemetrySettings; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: () => string; currentDate?: () => Date; }; }): Promise<GenerateObjectResult<Array<ELEMENT>>>; /** Generate a value from an enum (limited list of string values) using a language model. This function does not stream the output. @return A result object that contains the generated value, the finish reason, the token usage, and additional information. */ declare function generateObject<ENUM extends string>(options: Omit<CallSettings, 'stopSequences'> & Prompt & { output: 'enum'; /** The language model to use. */ model: LanguageModel; /** The enum values that the model should use. */ enum: Array<ENUM>; /** The mode to use for object generation. The schema is converted into a JSON schema and used in one of the following ways - 'auto': The provider will choose the best mode for the model. - 'tool': A tool with the JSON schema as parameters is provided and the provider is instructed to use it. - '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. Please note that most providers do not support all modes. Default and recommended: 'auto' (best mode for the model). */ mode?: 'auto' | 'json' | 'tool'; /** Optional telemetry configuration (experimental). */ experimental_telemetry?: TelemetrySettings; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: () => string; currentDate?: () => Date; }; }): Promise<GenerateObjectResult<ENUM>>; /** Generate JSON with any schema for a given prompt using a language model. This function does not stream the output. If you want to stream the output, use `streamObject` instead. @returns A result object that contains the generated object, the finish reason, the token usage, and additional information. */ declare function generateObject(options: Omit<CallSettings, 'stopSequences'> & Prompt & { output: 'no-schema'; /** The language model to use. */ model: LanguageModel; /** The mode to use for object generation. Must be "json" for no-schema output. */ mode?: 'json'; /** Optional telemetry configuration (experimental). */ experimental_telemetry?: TelemetrySettings; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: () => string; currentDate?: () => Date; }; }): Promise<GenerateObjectResult<JSONValue>>; type AsyncIterableStream<T> = AsyncIterable<T> & ReadableStream<T>; /** The result of a `streamObject` call that contains the partial object stream and additional information. */ interface StreamObjectResult<PARTIAL, RESULT, ELEMENT_STREAM> { /** Warnings from the model provider (e.g. unsupported settings) */ readonly warnings: Promise<CallWarning[] | undefined>; /** The token usage of the generated response. Resolved when the response is finished. */ readonly usage: Promise<LanguageModelUsage>; /** Additional provider-specific metadata. They are passed through from the provider to the AI SDK and enable provider-specific results that can be fully encapsulated in the provider. */ readonly experimental_providerMetadata: Promise<ProviderMetadata | undefined>; /** Additional request information from the last step. */ readonly request: Promise<LanguageModelRequestMetadata>; /** Additional response information. */ readonly response: Promise<LanguageModelResponseMetadata>; /** The generated object (typed according to the schema). Resolved when the response is finished. */ readonly object: Promise<RESULT>; /** Stream of partial objects. It gets more complete as the stream progresses. Note that the partial object is not validated. If you want to be certain that the actual content matches your schema, you need to implement your own validation for partial results. */ readonly partialObjectStream: AsyncIterableStream<PARTIAL>; /** * Stream over complete array elements. Only available if the output strategy is set to `array`. */ readonly elementStream: ELEMENT_STREAM; /** Text stream of the JSON representation of the generated object. It contains text chunks. When the stream is finished, the object is valid JSON that can be parsed. */ readonly textStream: AsyncIterableStream<string>; /** Stream of different types of events, including partial objects, errors, and finish events. Only errors that stop the stream, such as network errors, are thrown. */ readonly fullStream: AsyncIterableStream<ObjectStreamPart<PARTIAL>>; /** Writes text delta output to a Node.js response-like object. It sets a `Content-Type` header to `text/plain; charset=utf-8` and writes each text delta as a separate chunk. @param response A Node.js response-like object (ServerResponse). @param init Optional headers, status code, and status text. */ pipeTextStreamToResponse(response: ServerResponse$1, init?: ResponseInit): void; /** Creates a simple text stream response. The response has a `Content-Type` header set to `text/plain; charset=utf-8`. Each text delta is encoded as UTF-8 and sent as a separate chunk. Non-text-delta events are ignored. @param init Optional headers, status code, and status text. */ toTextStreamResponse(init?: ResponseInit): Response; } type ObjectStreamPart<PARTIAL> = { type: 'object'; object: PARTIAL; } | { type: 'text-delta'; textDelta: string; } | { type: 'error'; error: unknown; } | { type: 'finish'; finishReason: FinishReason; logprobs?: LogProbs; usage: LanguageModelUsage; response: LanguageModelResponseMetadata; providerMetadata?: ProviderMetadata; }; type OnFinishCallback<RESULT> = (event: { /** The token usage of the generated response. */ usage: LanguageModelUsage; /** The generated object. Can be undefined if the final object does not match the schema. */ object: RESULT | undefined; /** Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema. */ error: unknown | undefined; /** Response metadata. */ response: LanguageModelResponseMetadata; /** Warnings from the model provider (e.g. unsupported settings). */ warnings?: CallWarning[]; /** Additional provider-specific metadata. They are passed through from the provider to the AI SDK and enable provider-specific results that can be fully encapsulated in the provider. */ experimental_providerMetadata: ProviderMetadata | undefined; }) => Promise<void> | void; /** Generate a structured, typed object for a given prompt and schema using a language model. This function streams the output. If you do not want to stream the output, use `generateObject` instead. @return A result object for accessing the partial object stream and additional information. */ declare function streamObject<OBJECT>(options: Omit<CallSettings, 'stopSequences'> & Prompt & { output?: 'object' | undefined; /** The language model to use. */ model: LanguageModel; /** The schema of the object that the model should generate. */ schema: z.Schema<OBJECT, z.ZodTypeDef, any> | Schema<OBJECT>; /** Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. */ schemaName?: string; /** Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description. */ schemaDescription?: string; /** The mode to use for object generation. The schema is converted into a JSON schema and used in one of the following ways - 'auto': The provider will choose the best mode for the model. - 'tool': A tool with the JSON schema as parameters is provided and the provider is instructed to use it. - '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. Please note that most providers do not support all modes. Default and recommended: 'auto' (best mode for the model). */ mode?: 'auto' | 'json' | 'tool'; /** Optional telemetry configuration (experimental). */ experimental_telemetry?: TelemetrySettings; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; /** Callback that is called when the LLM response and the final object validation are finished. */ onFinish?: OnFinishCallback<OBJECT>; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: () => string; currentDate?: () => Date; now?: () => number; }; }): StreamObjectResult<DeepPartial<OBJECT>, OBJECT, never>; /** Generate an array with structured, typed elements for a given prompt and element schema using a language model. This function streams the output. If you do not want to stream the output, use `generateObject` instead. @return A result object for accessing the partial object stream and additional information. */ declare function streamObject<ELEMENT>(options: Omit<CallSettings, 'stopSequences'> & Prompt & { output: 'array'; /** The language model to use. */ model: LanguageModel; /** The element schema of the array that the model should generate. */ schema: z.Schema<ELEMENT, z.ZodTypeDef, any> | Schema<ELEMENT>; /** Optional name of the array that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. */ schemaName?: string; /** Optional description of the array that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description. */ schemaDescription?: string; /** The mode to use for object generation. The schema is converted into a JSON schema and used in one of the following ways - 'auto': The provider will choose the best mode for the model. - 'tool': A tool with the JSON schema as parameters is provided and the provider is instructed to use it. - '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. Please note that most providers do not support all modes. Default and recommended: 'auto' (best mode for the model). */ mode?: 'auto' | 'json' | 'tool'; /** Optional telemetry configuration (experimental). */ experimental_telemetry?: TelemetrySettings; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; /** Callback that is called when the LLM response and the final object validation are finished. */ onFinish?: OnFinishCallback<Array<ELEMENT>>; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: () => string; currentDate?: () => Date; now?: () => number; }; }): StreamObjectResult<Array<ELEMENT>, Array<ELEMENT>, AsyncIterableStream<ELEMENT>>; /** Generate JSON with any schema for a given prompt using a language model. This function streams the output. If you do not want to stream the output, use `generateObject` instead. @return A result object for accessing the partial object stream and additional information. */ declare function streamObject(options: Omit<CallSettings, 'stopSequences'> & Prompt & { output: 'no-schema'; /** The language model to use. */ model: LanguageModel; /** The mode to use for object generation. Must be "json" for no-schema output. */ mode?: 'json'; /** Optional telemetry configuration (experimental). */ experimental_telemetry?: TelemetrySettings; /** Additional provider-specific metadata. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider. */ experimental_providerMetadata?: ProviderMetadata; /** Callback that is called when the LLM response and the final object validation are finished. */ onFinish?: OnFinishCallback<JSONValue>; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: () => string; currentDate?: () => Date; now?: () => number; }; }): StreamObjectResult<JSONValue, JSONValue, never>; type Parameters = z.ZodTypeAny | Schema<any>; type inferParameters<PARAMETERS extends Parameters> = PARAMETERS extends Schema<any> ? PARAMETERS['_type'] : PARAMETERS extends z.ZodTypeAny ? z.infer<PARAMETERS> : never; interface ToolExecutionOptions { /** * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data. */ toolCallId: string; /** * Messages that were sent to the language model to initiate the response that contained the tool call. * The messages **do not** include the system prompt nor the assistant response that contained the tool call. */ messages: CoreMessage[]; /** * An optional abort signal that indicates that the overall operation should be aborted. */ abortSignal?: AbortSignal; } /** A tool contains the description and the schema of the input that the tool expects. This enables the language model to generate the input. The tool can also contain an optional execute function for the actual execution function of the tool. */ type CoreTool<PARAMETERS extends Parameters = any, RESULT = any> = { /** The schema of the input that the tool expects. The language model will use this to generate the input. It is also used to validate the output of the language model. Use descriptions to make the input understandable for the language model. */ parameters: PARAMETERS; /** Optional conversion function that maps the tool result to multi-part tool content for LLMs. */ experimental_toToolResultContent?: (result: RESULT) => ToolResultContent; /** An async function that is called with the arguments from the tool call and produces a result. If not provided, the tool will not be executed automatically. @args is the input of the tool call. @options.abortSignal is a signal that can be used to abort the tool call. */ execute?: (args: inferParameters<PARAMETERS>, options: ToolExecutionOptions) => PromiseLike<RESULT>; } & ({ /** Function tool. */ type?: undefined | 'function'; /** An optional description of what the tool does. Will be used by the language model to decide whether to use the tool. */ description?: string; } | { /** Provider-defined tool. */ type: 'provider-defined'; /** The ID of the tool. Should follow the format `<provider-name>.<tool-name>`. */ id: `${string}.${string}`; /** The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool. */ args: Record<string, unknown>; }); /** Helper function for inferring the execute args of a tool. */ declare function tool<PARAMETERS extends Parameters, RESULT>(tool: CoreTool<PARAMETERS, RESULT> & { execute: (args: inferParameters<PARAMETERS>, options: ToolExecutionOptions) => PromiseLike<RESULT>; }): CoreTool<PARAMETERS, RESULT> & { execute: (args: inferParameters<PARAMETERS>, options: ToolExecutionOptions) => PromiseLike<RESULT>; }; declare function tool<PARAMETERS extends Parameters, RESULT>(tool: CoreTool<PARAMETERS, RESULT> & { execute?: undefined; }): CoreTool<PARAMETERS, RESULT> & { execute: undefined; }; /** Converts an array of messages from useChat into an array of CoreMessages that can be used with the AI core functions (e.g. `streamText`). */ declare function convertToCoreMessages<TOOLS extends Record<string, CoreTool> = never>(messages: Array<UIMessage>, options?: { tools?: TOOLS; }): CoreMessage[]; /** Create a union of the given object's values, and optionally specify which keys to get the values from. Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31438) if you want to have this type as a built-in in TypeScript. @example ``` // data.json { 'foo': 1, 'bar': 2, 'biz': 3 } // main.ts import type {ValueOf} from 'type-fest'; import data = require('./data.json'); export function getData(name: string): ValueOf<typeof data> { return data[name]; } export function onlyBar(name: string): ValueOf<typeof data, 'bar'> { return data[name]; } // file.ts import {getData, onlyBar} from './main'; getData('foo'); //=> 1 onlyBar('foo'); //=> TypeError ... onlyBar('bar'); //=> 2 ``` * @see https://github.com/sindresorhus/type-fest/blob/main/source/value-of.d.ts */ type ValueOf<ObjectType, ValueType extends keyof ObjectType = keyof ObjectType> = ObjectType[ValueType]; type ToolCallUnion<TOOLS extends Record<string, CoreTool>> = ValueOf<{ [NAME in keyof TOOLS]: { type: 'tool-call'; toolCallId: string; toolName: NAME & string; args: inferParameters<TOOLS[NAME]['parameters']>; }; }>; type ToolCallArray<TOOLS extends Record<string, CoreTool>> = Array<ToolCallUnion<TOOLS>>; type ToToolsWithExecute<TOOLS extends Record<string, CoreTool>> = { [K in keyof TOOLS as TOOLS[K] extends { execute: any; } ? K : never]: TOOLS[K]; }; type ToToolsWithDefinedExecute<TOOLS extends Record<string, CoreTool>> = { [K in keyof TOOLS as TOOLS[K]['execute'] extends undefined ? never : K]: TOOLS[K]; }; type ToToolResultObject<TOOLS extends Record<string, CoreTool>> = ValueOf<{ [NAME in keyof TOOLS]: { type: 'tool-result'; toolCallId: string; toolName: NAME & string; args: inferParameters<TOOLS[NAME]['parameters']>; result: Awaited<ReturnType<Exclude<TOOLS[NAME]['execute'], undefined>>>; }; }>; type ToolResultUnion<TOOLS extends Record<string, CoreTool>> = ToToolResultObject<ToToolsWithDefinedExecute<ToToolsWithExecute<TOOLS>>>; type ToolResultArray<TOOLS extends Record<string, CoreTool>> = Array<ToolResultUnion<TOOLS>>; /** * The result of a single step in the generation process. */ type StepResult<TOOLS extends Record<string, CoreTool>> = { /** The generated text. */ readonly text: string; /** The tool calls that were made during the generation. */ readonly toolCalls: ToolCallArray<TOOLS>; /** The results of the tool calls. */ readonly toolResults: ToolResultArray<TOOLS>; /** The reason why the generation finished. */ readonly finishReason: FinishReason; /** The token usage of the generated text. */ readonly usage: LanguageModelUsage; /** Warnings from the model provider (e.g. unsupported settings). */ readonly warnings: CallWarning[] | undefined; /** Logprobs for the completion. `undefined` if the mode does not support logprobs or if was not enabled. */ readonly logprobs: LogProbs | undefined; /** Additional request information. */ readonly request: LanguageModelRequestMetadata; /** Additional response information. */ readonly response: LanguageModelResponseMetadata & { /** The response messages that were generated during the call. It consists of an assistant message, potentially containing tool calls. */ readonly messages: Array<CoreAssistantMessage | CoreToolMessage>; }; /** Additional provider-specific metadata. They are passed through from the provider to the AI SDK and enable provider-specific results that