import { C as __exportAll, S as TracingLevel, _ as MaskInputOptions, a as HumanEvaluator, b as SpanType, c as InitializeOptions, d as LaminarClient, f as Dataset, g as LaminarSpanContext, h as Event, i as EvaluatorFunctionReturn, l as EvaluationDataset, m as EvaluationDatapointDatasetLink, o as evaluate, p as EvaluationDatapoint, r as EvaluatorFunction, s as StringUUID, t as Datapoint, u as LaminarDataset, v as PushDatapointsResponse, x as TraceType, y as SessionRecordingOptions } from "./evaluations-CbHnDCAY.cjs"; import { ServerResponse } from "node:http"; import { ReadableSpan, SpanExporter, SpanProcessor, TimedEvent } from "@opentelemetry/sdk-trace-base"; import { AttributeValue, Attributes, Context, Exception, HrTime, Link, Span, Span as Span$1, SpanContext, SpanKind, SpanStatus, TimeInput, Tracer, TracerProvider } from "@opentelemetry/api"; import { JSONSchema7, JSONSchema7 as JSONSchema7$1 } from "json-schema"; import { InstrumentationScope } from "@opentelemetry/core"; import * as z3 from "zod/v3"; import { $ZodType } from "zod/v4/core"; import { ServerResponse as ServerResponse$1 } from "http"; import { ZodType } from "zod/v4"; import { Instrumentation } from "@opentelemetry/instrumentation"; //#region src/decorators.d.ts interface ObserveOptions { name?: string; sessionId?: string; userId?: string; traceType?: TraceType; spanType?: "DEFAULT" | "LLM" | "TOOL" | "EVALUATOR" | "EVALUATION" | "EXECUTOR"; input?: unknown; ignoreInput?: boolean; ignoreOutput?: boolean; parentSpanContext?: string | LaminarSpanContext; metadata?: Record; tags?: string[]; } /** * The main decorator entrypoint for Laminar. This is used to wrap * functions and methods to create spans. * * @param options - Configuration options for the span * @param options.name - Name of the span. Function name is used if not specified. * @param options.sessionId - Session ID to associate with the span and the following context. * @param options.userId - User ID to associate with the span and the following context. * This is different from the id of a Laminar user. * @param options.traceType - Type of the trace. Unless it is within evaluation, it should be * 'DEFAULT'. * @param options.spanType - Type of the span. 'DEFAULT' is used if not specified. If the type * is 'LLM', you must manually specify some attributes. See `Laminar.setSpanAttributes` * for more information. * @param options.input - Force override the input for the span. If not specified, the * input will be the arguments passed to the function. * @param options.ignoreInput - Whether to ignore the input altogether. * @param options.ignoreOutput - Whether to ignore the output altogether. * @param options.parentSpanContext - Parent span context to associate with this span. * @param options.metadata - Metadata to add to a trace for further filtering. Must be * JSON serializable. * @param options.tags - Tags to associate with the span. * @param fn - The function to wrap * @param args - Arguments to pass to the function * @returns Promise with the result of the wrapped function. * @throws Exception - Re-throws the exception if the wrapped function throws an exception. * * @example * ```typescript * await observe({ name: 'my_function' }, async (x: string) => { * // Your code here * return x.toUpperCase(); * }, 'hello'); * ``` */ declare function observe ReturnType>(options: ObserveOptions, fn: F, ...args: A): ReturnType; /** * Sets the tracing level for any spans inside the function. This is useful for * conditionally disabling the tracing for certain functions. * Tracing level must be one of the values in {@link TracingLevel}. Returns the * result of the wrapped function, so you can use it in an `await` statement if * needed. * * @param tracingLevel - The tracing level to set. * @returns The result of the wrapped function. * * @example * ```typescript * import { withTracingLevel, TracingLevel } from '@lmnr-ai/lmnr'; * * const result = await withTracingLevel(TracingLevel.META_ONLY, () => { * openai.chat.completions.create({}); * }); * ``` */ declare function withTracingLevel ReturnType>(tracingLevel: TracingLevel, fn: F, ...args: A): ReturnType; /** * Decorator that wraps a method to automatically observe it with Laminar tracing. * This decorator uses the TypeScript 5.0+ standard decorator syntax. * * **Important**: Use this decorator only if your `tsconfig.json` does NOT have * `experimentalDecorators: true`. If you're using experimental decorators, use * {@link observeExperimentalDecorator} instead. * * This decorator can be used on class methods to automatically create spans. * * @param config - Configuration for the observe decorator, can be static or a function * @returns A method decorator * * @example * ```typescript * // In your tsconfig.json, ensure experimentalDecorators is NOT enabled: * // { * // "compilerOptions": { * // "experimentalDecorators": false // or omit this line * // } * // } * * import { observeDecorator } from '@lmnr-ai/lmnr'; * * class MyService { * @observeDecorator({ name: 'processData', spanType: 'DEFAULT' }) * async processData(input: string) { * // Your code here * return `processed: ${input}`; * } * * @observeDecorator((thisArg, ...args) => ({ * name: `dynamicMethod_${args[0]}`, * sessionId: thisArg.sessionId * })) * async dynamicMethod(id: string) { * // Your code here * } * } * ``` */ declare function observeDecorator(config: Partial | ((thisArg: This, ...funcArgs: Args) => Partial)): (originalMethod: (this: This, ...args: Args) => Return, context: ClassMethodDecoratorContext Return>) => (this: This, ...args: Args) => Return; /** * Decorator that wraps a method to automatically observe it with Laminar tracing. * This decorator uses the legacy experimental decorator syntax * (requires `--experimentalDecorators` flag). * * **Important**: Use this decorator only if your `tsconfig.json` has * `experimentalDecorators: true` in the `compilerOptions` section * (or if you compile with the `--experimentalDecorators` flag). * For TypeScript 5.0+ projects without experimental decorators, use * {@link observeDecorator} instead. * * This decorator can be used on class methods to automatically create spans. * * Use this only if you need the legacy experimental decorator syntax. * @param config - Configuration for the observe decorator, can be static or a function * @returns A method decorator * * @example * ```typescript * // In your tsconfig.json, ensure experimentalDecorators is enabled: * // { * // "compilerOptions": { * // "experimentalDecorators": true * // } * // } * * import { observeExperimentalDecorator } from '@lmnr-ai/lmnr'; * * class MyService { * @observeExperimentalDecorator({ name: 'processData', spanType: 'DEFAULT' }) * async processData(input: string) { * // Your code here * return `processed: ${input}`; * } * * @observeExperimentalDecorator((thisArg, ...args) => ({ * name: `dynamicMethod_${args[0]}`, * sessionId: thisArg.sessionId * })) * async dynamicMethod(id: string) { * // Your code here * } * } * ``` */ declare function observeExperimentalDecorator(config: Partial | ((thisArg: unknown, ...funcArgs: unknown[]) => Partial)): (_target: unknown, propertyKey: string, descriptor: PropertyDescriptor) => void; //#endregion //#region src/integrations/eve.d.ts /** * Narrow local mirrors of eve's `eve/evals` types. We intentionally do NOT * import from `eve` so the SDK carries no peer dependency on it (same pattern * as the Mastra exporter). The fields mirror eve 0.22.x; every field a reporter * reads is optional so a shape change on eve's side degrades gracefully instead * of throwing. Array fields must stay `readonly` — eve's own types are * readonly, and a mutable mirror is not assignable to them (TS2322 for users * registering the reporter). */ interface EveEval { /** Path-derived stable id of the eval, e.g. "brooklyn-forecast". */ id?: string; description?: string; metadata?: Record; } interface EveEvalTarget { /** "local" for a dev server the runner boots, "remote" for a deployment. */ kind?: string; /** Base HTTP URL the eval client connects to. */ url?: string; [key: string]: any; } /** How a failing assertion affects the verdict. */ type EveAssertionSeverity = "gate" | "soft"; /** The recorded outcome of one assertion eve ran against an eval. */ interface EveAssertionResult { name?: string; /** Score in [0, 1]; boolean assertions score exactly 0 or 1. */ score?: number; /** "gate" (hard) or "soft" (tracked / thresholded). */ severity?: EveAssertionSeverity; threshold?: number; passed?: boolean; /** Human-readable failure detail. */ message?: string; metadata?: Record; } /** One tool call eve extracted from the captured stream. */ interface EveEvalToolCall { name?: string; [key: string]: any; } /** Execution facts eve derives from a completed session's stream. */ interface EveEvalDerivedFacts { toolCalls?: readonly EveEvalToolCall[]; toolCallCount?: number; subagentCallCount?: number; messageCount?: number; reasoningBlockCount?: number; parked?: boolean; failureCode?: string; } /** Runtime identity eve captures from the `session.started` stream event. */ interface EveRuntimeIdentity { agentId?: string; agentName?: string; eveVersion?: string; modelId?: string; } /** Result of executing one eval against an eve agent. */ interface EveEvalTaskResult { /** Final structured data, or the last assistant message when absent. */ output?: any; /** The agent's last assistant message, or null when none was produced. */ finalMessage?: string | null; /** eve session id after the first successful send. */ sessionId?: string; /** How the run's final turn ended. */ status?: "completed" | "failed" | "waiting"; logs?: readonly string[]; derived?: EveEvalDerivedFacts; runtimeIdentity?: EveRuntimeIdentity; } /** Per-eval verdict computed by the runner. */ type EveEvalVerdict = "passed" | "failed" | "scored" | "skipped"; /** Result of executing and asserting one eval. eve hands this to reporters. */ interface EveEvalResult { /** Path-derived eval id (e.g. "weather"). */ id?: string; /** Execution result (output, session, derived facts). */ result?: EveEvalTaskResult; /** Every assertion recorded by the eval's `test(t)`, in record order. */ assertions?: readonly EveAssertionResult[]; /** Per-eval verdict. */ verdict?: EveEvalVerdict; /** Execution error message, when the eval threw. */ error?: string; /** Reason supplied to `t.skip(reason)`. */ skipReason?: string; startedAt?: string; completedAt?: string; } interface EveEvalRunSummary { total?: number; passed?: number; failed?: number; scored?: number; skipped?: number; errored?: number; [key: string]: any; } /** * The contract eve invokes. Mirrors `EvalReporter` from `eve/evals/reporters`. */ interface EvalReporter { onRunStart(evaluations: readonly EveEval[], target: EveEvalTarget): void | Promise; onEvalComplete(result: EveEvalResult): void | Promise; onRunComplete(summary: EveEvalRunSummary): void | Promise; } interface LaminarReporterOptions { /** Name of the Laminar evaluation created for the run. */ name?: string; /** Group name to chart regressions across runs of the same eval suite. */ groupName?: string; /** Metadata attached to the Laminar evaluation. */ metadata?: Record; /** Project API key. Falls back to `LMNR_PROJECT_API_KEY`. */ projectApiKey?: string; /** Override the Laminar API base URL (e.g. for self-hosted). */ baseUrl?: string; /** * Provide a pre-constructed client (e.g. to share auth across reporters). * When set, `projectApiKey` / `baseUrl` are ignored. */ client?: LaminarClient; /** * Span processor for the tracing this reporter initializes. Intended for * tests; production defaults to Laminar's. Ignored when something already * called `Laminar.initialize()` — see {@link LaminarReporter.ensureTracing}. */ spanProcessor?: SpanProcessor; /** * Mint the trace in the runner and push it to the agent as a `traceparent` * header (see {@link patchEveClientSession}). Defaults to `true`. Set `false` * only to disable the patch — every datapoint then links to a reporter-owned * trace that holds the grade but none of the agent's work. */ propagateTraceContext?: boolean; } /** * A Laminar reporter for eve evals. Register it globally in `evals.config.ts` * or per-eval via the `reporters` field — eve runs and grades each eval, then * hands the graded result here, and this reporter ships it to Laminar as an * evaluation run with one datapoint per eval. * * The datapoint's trace id is never looked up — the reporter OWNS the trace. * `patchEveClientSession` wraps eve's `ClientSession.send` and mints the * EVALUATION root + EXECUTOR child on the first turn of each session, so the * runner already knows the trace id and pushes it to the agent as a * `traceparent` header. The eve session id is only the in-process key that ties * the send we instrumented to the graded result eve hands back later. * * Two outcomes, recorded on `metadata.traceResolution`: * * 1. `"propagated"` — the normal path, above. The agent joins the trace only * when `agent/instrumentation.ts` sets `traceChannelRequests: true` and the * agent process runs with `WORKFLOW_TRACE_MODE=continuous`. * 2. `"reporter-fallback"` — no session trace was minted (propagation disabled, * or eve produced no session id). The reporter opens its own EVALUATION span * so the grade still lands somewhere debuggable; it holds no agent work. * * `t.judge.autoevals.*` model calls run in the RUNNER process, and they reach * Laminar only when the runner registers an AI SDK telemetry integration. eve * imports `generateText` inside its own bundle, so `wrapAISDK` cannot reach it — * but AI SDK v7 reads registered integrations off `globalThis`, which does. One * line in `evals.config.ts`: * * ```ts * registerTelemetry(new LaminarAiSdkTelemetry()); * ``` * * Judge spans and eve eval spans then share ONE tracer provider — whichever of * the two initialized Laminar first (see {@link LaminarReporter.ensureTracing}). * Each judge gets its own span under the eval's root — see * {@link bindEvalContext}, and {@link LaminarReporter.flush} for how spans ship. * Without that line the reporter still records every assertion's score as an * EVALUATOR span; only the model call is missing. * * @example * ```ts * import { defineEvalConfig } from "eve/evals"; * import { LaminarReporter } from "@lmnr-ai/lmnr"; * * export default defineEvalConfig({ * reporters: [new LaminarReporter({ name: "weather-agent" })], * }); * ``` */ declare class LaminarReporter implements EvalReporter { private readonly options; private client?; private evalId?; private evalsById; private index; /** Session traces minted this run and not yet graded. */ private openSessionTraces; /** Stable identity so `onRunComplete` only clears its own registration. */ private readonly sessionTraceFactory; constructor(options?: LaminarReporterOptions); onRunStart(evaluations: readonly EveEval[], target: EveEvalTarget): Promise; onEvalComplete(result: EveEvalResult): Promise; onRunComplete(): Promise; /** * Point the process's Laminar tracing at this reporter's project, unless * something already initialized it. Mirrors `LaminarAiSdkTelemetry`, which * initializes the same way for judge spans — so eve eval spans and judge * spans share ONE tracer provider however the run was set up. Without this, * `getTracer()` returns a noop whenever nobody registered the AI SDK * integration, and every eve span would be dropped silently. */ private ensureTracing; /** * Flush the process's Laminar pipeline — eve eval spans AND judge spans, which * now share one provider. eve ends `eve eval` with `process.exit()` (skipping * `beforeExit`), so these calls are the only points at which spans ship. * Never `shutdown()`: the pipeline may belong to the host, not to us. */ private flush; /** * Open the eval's Laminar spans for one eve client session: an EVALUATION * root plus the EXECUTOR child the agent's turn is parented to. Called from * the patched `send`, so it must never throw into the user's eval. */ private mintSessionTrace; /** Grade, close and release one session trace. Idempotent. */ private finishSessionTrace; /** * One EVALUATOR span per eve assertion, judge or not. They are created at * grade time (the assertions only exist then) as short children of the * still-open root. No explicit parent path is needed: the root keeps the name * it was minted with, so the processor's cached path for it is still correct. */ private recordEvaluatorSpans; private finishOpenSessionTraces; /** * Resolve the trace this datapoint links to. There is no lookup: either * `patchEveClientSession` already minted the session's trace (and we know its * id), or we open a reporter-owned EVALUATION span to hold the grade. */ private resolveDatapointTrace; } //#endregion //#region ../../node_modules/.pnpm/@ai-sdk+provider@4.0.7/node_modules/@ai-sdk/provider/dist/index.d.ts /** * Audio format configuration shared by provider V4 model specifications. */ type SharedV4AudioFormat = { /** * Audio format type, e.g. `audio/pcm`, `audio/pcmu`, or `audio/pcma`. */ type: string; /** * Sample rate in Hz. Only applicable for formats that require a rate. */ rate?: number; }; /** * A mapping of provider names to provider-specific file identifiers. * * Provider references allow files to be identified across different * providers without re-uploading, by storing each provider's own * identifier for the same logical file. * * ```ts * { * "openai": "file-abc123", * "anthropic": "file-xyz789" * } * ``` * * The `type?: never` constraint excludes any object that has a `type` * property, so a `SharedV4ProviderReference` cannot be confused with a * tagged file-data shape (e.g. `{ type: 'data', data }` or * `{ type: 'reference', reference }`) when both appear in the same union. */ type SharedV4ProviderReference = Record & { type?: never; }; /** * File data variant containing raw bytes (`Uint8Array`) or a base64-encoded * string. */ interface SharedV4FileDataData { type: 'data'; data: Uint8Array | string; } /** * File data variant containing a URL that points to the file. */ interface SharedV4FileDataUrl { type: 'url'; url: URL; } /** * File data variant containing a provider reference (`{ [provider]: id }`). */ interface SharedV4FileDataReference { type: 'reference'; reference: SharedV4ProviderReference; } /** * File data variant containing inline text content (e.g. an inline text * document). */ interface SharedV4FileDataText { type: 'text'; text: string; } /** * File data as a tagged discriminated union: * * - `{ type: 'data', data }`: raw bytes (`Uint8Array`) or base64-encoded string. * - `{ type: 'url', url }`: a URL that points to the file. * - `{ type: 'reference', reference }`: a provider reference (`{ [provider]: id }`). * - `{ type: 'text', text }`: inline text content (e.g. an inline text document). */ type SharedV4FileData = SharedV4FileDataData | SharedV4FileDataUrl | SharedV4FileDataReference | SharedV4FileDataText; type SharedV4Headers = Record; /** * A JSON value can be a string, number, boolean, object, array, or null. * JSON values can be serialized and deserialized by the JSON.stringify and JSON.parse methods. */ type JSONValue$3 = null | string | number | boolean | JSONObject$2 | JSONArray$2; type JSONObject$2 = { [key: string]: JSONValue$3 | undefined; }; type JSONArray$2 = JSONValue$3[]; /** * Additional provider-specific metadata. * Metadata are additional outputs from the provider. * They are passed through to the provider from the AI SDK * and enable provider-specific functionality * that can be fully encapsulated in the provider. * * This enables us to quickly ship provider-specific functionality * without affecting the core AI SDK. * * The outer record is keyed by the provider name, and the inner * record is keyed by the provider-specific metadata key. * * ```ts * { * "anthropic": { * "cacheControl": { "type": "ephemeral" } * } * } * ``` */ type SharedV4ProviderMetadata = Record; /** * Additional provider-specific options. * Options are additional input to the provider. * They are passed through to the provider from the AI SDK * and enable provider-specific functionality * that can be fully encapsulated in the provider. * * This enables us to quickly ship provider-specific functionality * without affecting the core AI SDK. * * The outer record is keyed by the provider name, and the inner * record is keyed by the provider-specific metadata key. * * ```ts * { * "anthropic": { * "cacheControl": { "type": "ephemeral" } * } * } * ``` */ type SharedV4ProviderOptions = Record; /** * Warning from the model. * * For example, that certain features are unsupported or compatibility * functionality is used (which might lead to suboptimal results). */ type SharedV4Warning = { /** * A feature is not supported by the model. */ type: 'unsupported'; /** * The feature that is not supported. */ feature: string; /** * Additional details about the warning. */ details?: string; } | { /** * A compatibility feature is used that might lead to suboptimal results. */ type: 'compatibility'; /** * The feature that is used in a compatibility mode. */ feature: string; /** * Additional details about the warning. */ details?: string; } | { /** * A deprecated feature or option is being used. */ type: 'deprecated'; /** * The deprecated setting or feature name. */ setting: string; /** * A human-readable message explaining what to use instead. */ message: string; } | { /** * Other warning. */ type: 'other'; /** * The message of the warning. */ message: string; }; type SharedV3Headers$1 = Record; /** * Additional provider-specific metadata. * Metadata are additional outputs from the provider. * They are passed through to the provider from the AI SDK * and enable provider-specific functionality * that can be fully encapsulated in the provider. * * This enables us to quickly ship provider-specific functionality * without affecting the core AI SDK. * * The outer record is keyed by the provider name, and the inner * record is keyed by the provider-specific metadata key. * * ```ts * { * "anthropic": { * "cacheControl": { "type": "ephemeral" } * } * } * ``` */ type SharedV3ProviderMetadata$1 = Record; /** * Additional provider-specific options. * Options are additional input to the provider. * They are passed through to the provider from the AI SDK * and enable provider-specific functionality * that can be fully encapsulated in the provider. * * This enables us to quickly ship provider-specific functionality * without affecting the core AI SDK. * * The outer record is keyed by the provider name, and the inner * record is keyed by the provider-specific metadata key. * * ```ts * { * "anthropic": { * "cacheControl": { "type": "ephemeral" } * } * } * ``` */ type SharedV3ProviderOptions$1 = Record; /** * Warning from the model. * * For example, that certain features are unsupported or compatibility * functionality is used (which might lead to suboptimal results). */ type SharedV3Warning$1 = { /** * A feature is not supported by the model. */ type: 'unsupported'; /** * The feature that is not supported. */ feature: string; /** * Additional details about the warning. */ details?: string; } | { /** * A compatibility feature is used that might lead to suboptimal results. */ type: 'compatibility'; /** * The feature that is used in a compatibility mode. */ feature: string; /** * Additional details about the warning. */ details?: string; } | { /** * Other warning. */ type: 'other'; /** * The message of the warning. */ message: string; }; type SharedV2Headers$1 = Record; /** * Additional provider-specific metadata. * Metadata are additional outputs from the provider. * They are passed through to the provider from the AI SDK * and enable provider-specific functionality * that can be fully encapsulated in the provider. * * This enables us to quickly ship provider-specific functionality * without affecting the core AI SDK. * * The outer record is keyed by the provider name, and the inner * record is keyed by the provider-specific metadata key. * * ```ts * { * "anthropic": { * "cacheControl": { "type": "ephemeral" } * } * } * ``` */ type SharedV2ProviderMetadata$1 = Record>; /** * Additional provider-specific options. * Options are additional input to the provider. * They are passed through to the provider from the AI SDK * and enable provider-specific functionality * that can be fully encapsulated in the provider. * * This enables us to quickly ship provider-specific functionality * without affecting the core AI SDK. * * The outer record is keyed by the provider name, and the inner * record is keyed by the provider-specific metadata key. * * ```ts * { * "anthropic": { * "cacheControl": { "type": "ephemeral" } * } * } * ``` */ type SharedV2ProviderOptions$1 = Record>; /** * Serializable error information for a batch or batch item. */ type BatchV4Error = { readonly message: string; readonly type?: string; readonly code?: string; readonly statusCode?: number; }; /** * Normalized lifecycle status for a batch. */ type BatchV4Status = { readonly status: 'pending' | 'completed' | 'failed'; readonly rawStatus?: string; readonly requestCounts?: { readonly total: number; readonly pending: number; readonly completed: number; readonly failed: number; }; readonly error?: BatchV4Error; readonly createdAt?: string; readonly expiresAt?: string; readonly providerMetadata?: SharedV4ProviderMetadata; }; /** * Options for starting a batch. */ type BatchV4StartOptions = { readonly requests: ReadonlyArray; readonly providerOptions?: SharedV4ProviderOptions; readonly abortSignal?: AbortSignal; readonly headers?: Record; }; /** * Result of starting a batch. */ type BatchV4StartResult = BatchV4Status & { readonly batchId: string; readonly warnings: Array<{ readonly requestId?: string; readonly warning: SharedV4Warning; }>; }; /** * Options for a batch status or results operation. */ type BatchV4OperationOptions = { readonly batchId: string; readonly providerOptions?: SharedV4ProviderOptions; readonly abortSignal?: AbortSignal; readonly headers?: Record; }; /** * A complete terminal result for one request in a batch. */ type BatchV4ItemResult = { readonly id: string; readonly status: 'succeeded'; readonly result: RESULT; } | { readonly id: string; readonly status: 'failed'; readonly error: BatchV4Error; readonly providerMetadata?: SharedV4ProviderMetadata; } | { readonly id: string; readonly status: 'cancelled' | 'expired'; readonly error?: BatchV4Error; readonly providerMetadata?: SharedV4ProviderMetadata; }; /** * Experimental structural capability for models that support durable batch * processing. */ type BatchModelV4 = { experimental_doStartBatch(options: BatchV4StartOptions): PromiseLike; experimental_doGetBatchStatus(options: BatchV4OperationOptions): PromiseLike; experimental_doGetBatchResults(options: BatchV4OperationOptions): PromiseLike>>; }; type EmbeddingModelV4CallOptions = { /** * List of text values to generate embeddings for. */ values: Array; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV4ProviderOptions; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: SharedV4Headers; }; /** * An embedding is a vector, i.e. an array of numbers. * It is e.g. used to represent a text as a vector of word embeddings. */ type EmbeddingModelV4Embedding = Array; /** * The result of a embedding model doEmbed call. */ type EmbeddingModelV4Result = { /** * Generated embeddings. They are in the same order as the input values. */ embeddings: Array; /** * Token usage. We only have input tokens for embeddings. */ usage?: { tokens: number; }; /** * 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. */ providerMetadata?: SharedV4ProviderMetadata; /** * Optional response information for debugging purposes. */ response?: { /** * Response headers. */ headers?: SharedV4Headers; /** * The response body. */ body?: unknown; }; /** * Warnings for the call, e.g. unsupported settings. */ warnings: Array; }; /** * Specification for an embedding model that implements the embedding model * interface version 4. * * It is specific to text embeddings. */ type EmbeddingModelV4 = { /** * The embedding model must specify which embedding model interface * version it implements. This will allow us to evolve the embedding * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v4'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Limit of how many embeddings can be generated in a single API call. * * Use Infinity for models that do not have a limit. */ readonly maxEmbeddingsPerCall: PromiseLike | number | undefined; /** * True if the model can handle multiple embedding calls in parallel. */ readonly supportsParallelCalls: PromiseLike | boolean; /** * Generates a list of embeddings for the given input text. * * Naming: "do" prefix to prevent accidental direct usage of the method * by the user. */ doEmbed(options: EmbeddingModelV4CallOptions): PromiseLike; }; type EmbeddingModelV3CallOptions = { /** * List of text values to generate embeddings for. */ values: Array; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions$1; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: SharedV3Headers$1; }; /** * An embedding is a vector, i.e. an array of numbers. * It is e.g. used to represent a text as a vector of word embeddings. */ type EmbeddingModelV3Embedding = Array; /** * The result of a embedding model doEmbed call. */ type EmbeddingModelV3Result = { /** * Generated embeddings. They are in the same order as the input values. */ embeddings: Array; /** * Token usage. We only have input tokens for embeddings. */ usage?: { tokens: number; }; /** * 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. */ providerMetadata?: SharedV3ProviderMetadata$1; /** * Optional response information for debugging purposes. */ response?: { /** * Response headers. */ headers?: SharedV3Headers$1; /** * The response body. */ body?: unknown; }; /** * Warnings for the call, e.g. unsupported settings. */ warnings: Array; }; /** * Specification for an embedding model that implements the embedding model * interface version 3. * * It is specific to text embeddings. */ type EmbeddingModelV3 = { /** * The embedding model must specify which embedding model interface * version it implements. This will allow us to evolve the embedding * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v3'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Limit of how many embeddings can be generated in a single API call. * * Use Infinity for models that do not have a limit. */ readonly maxEmbeddingsPerCall: PromiseLike | number | undefined; /** * True if the model can handle multiple embedding calls in parallel. */ readonly supportsParallelCalls: PromiseLike | boolean; /** * Generates a list of embeddings for the given input text. * * Naming: "do" prefix to prevent accidental direct usage of the method * by the user. */ doEmbed(options: EmbeddingModelV3CallOptions): PromiseLike; }; /** * An embedding is a vector, i.e. an array of numbers. * It is e.g. used to represent a text as a vector of word embeddings. */ type EmbeddingModelV2Embedding = Array; /** * Specification for an embedding model that implements the embedding model * interface version 2. * * VALUE is the type of the values that the model can embed. * This will allow us to go beyond text embeddings in the future, * e.g. to support image embeddings */ type EmbeddingModelV2 = { /** * The embedding model must specify which embedding model interface * version it implements. This will allow us to evolve the embedding * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v2'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Limit of how many embeddings can be generated in a single API call. * * Use Infinity for models that do not have a limit. */ readonly maxEmbeddingsPerCall: PromiseLike | number | undefined; /** * True if the model can handle multiple embedding calls in parallel. */ readonly supportsParallelCalls: PromiseLike | boolean; /** * Generates a list of embeddings for the given input text. * * Naming: "do" prefix to prevent accidental direct usage of the method * by the user. */ doEmbed(options: { /** * List of values to embed. */ values: Array; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions$1; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; }): PromiseLike<{ /** * Generated embeddings. They are in the same order as the input values. */ embeddings: Array; /** * Token usage. We only have input tokens for embeddings. */ usage?: { tokens: number; }; /** * 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. */ providerMetadata?: SharedV2ProviderMetadata$1; /** * Optional response information for debugging purposes. */ response?: { /** * Response headers. */ headers?: SharedV2Headers$1; /** * The response body. */ body?: unknown; }; }>; }; declare const symbol$e$1: unique symbol; /** * Custom error class for AI SDK related errors. * @extends Error */ declare class AISDKError extends Error { private readonly [symbol$e$1]; /** * The underlying cause of the error, if any. */ readonly cause?: unknown; /** * Creates an AI SDK Error. * * @param {Object} params - The parameters for creating the error. * @param {string} params.name - The name of the error. * @param {string} params.message - The error message. * @param {unknown} [params.cause] - The underlying cause of the error. */ constructor({ name, message, cause }: { name: string; message: string; cause?: unknown; }); /** * Checks if the given error is an AI SDK Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is an AI SDK Error, false otherwise. */ static isInstance(error: unknown): error is AISDKError; protected static hasMarker(error: unknown, marker: string): boolean; } declare const symbol$d$1: unique symbol; declare class APICallError extends AISDKError { private readonly [symbol$d$1]; readonly url: string; readonly requestBodyValues: unknown; readonly statusCode?: number; readonly responseHeaders?: Record; readonly responseBody?: string; readonly isRetryable: boolean; readonly data?: unknown; constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable, // server error data }: { message: string; url: string; requestBodyValues: unknown; statusCode?: number; responseHeaders?: Record; responseBody?: string; cause?: unknown; isRetryable?: boolean; data?: unknown; }); static isInstance(error: unknown): error is APICallError; } declare const symbol$c$1: unique symbol; declare class EmptyResponseBodyError extends AISDKError { private readonly [symbol$c$1]; constructor({ message }?: { message?: string; }); static isInstance(error: unknown): error is EmptyResponseBodyError; } declare const symbol$a$1: unique symbol; /** * A prompt is invalid. This error should be thrown by providers when they cannot * process a prompt. */ declare class InvalidPromptError extends AISDKError { private readonly [symbol$a$1]; readonly prompt: unknown; constructor({ prompt, message, cause }: { prompt: unknown; message: string; cause?: unknown; }); static isInstance(error: unknown): error is InvalidPromptError; } declare const symbol$9$1: unique symbol; /** * Server returned a response with invalid data content. * This should be thrown by providers when they cannot parse the response from the API. */ declare class InvalidResponseDataError extends AISDKError { private readonly [symbol$9$1]; readonly data: unknown; constructor({ data, message }: { data: unknown; message?: string; }); static isInstance(error: unknown): error is InvalidResponseDataError; } declare const symbol$8$1: unique symbol; declare class JSONParseError extends AISDKError { private readonly [symbol$8$1]; readonly text: string; constructor({ text, cause }: { text: string; cause: unknown; }); static isInstance(error: unknown): error is JSONParseError; } declare const symbol$7$1: unique symbol; declare class LoadAPIKeyError extends AISDKError { private readonly [symbol$7$1]; constructor({ message }: { message: string; }); static isInstance(error: unknown): error is LoadAPIKeyError; } declare const symbol$6$1: unique symbol; declare class LoadSettingError extends AISDKError { private readonly [symbol$6$1]; constructor({ message }: { message: string; }); static isInstance(error: unknown): error is LoadSettingError; } declare const symbol$5$1: unique symbol; /** * Thrown when the AI provider fails to generate any content. */ declare class NoContentGeneratedError extends AISDKError { private readonly [symbol$5$1]; constructor({ message }?: { message?: string; }); static isInstance(error: unknown): error is NoContentGeneratedError; } declare const symbol$4$1: unique symbol; declare class NoSuchModelError extends AISDKError { private readonly [symbol$4$1]; readonly modelId: string; readonly modelType: 'languageModel' | 'embeddingModel' | 'imageModel' | 'transcriptionModel' | 'speechModel' | 'rerankingModel' | 'videoModel'; constructor({ errorName, modelId, modelType, message }: { errorName?: string; modelId: string; modelType: 'languageModel' | 'embeddingModel' | 'imageModel' | 'transcriptionModel' | 'speechModel' | 'rerankingModel' | 'videoModel'; message?: string; }); static isInstance(error: unknown): error is NoSuchModelError; } declare const symbol$3$1: unique symbol; /** * Thrown when a provider reference cannot be resolved because the specified * provider is not found in the provider reference mapping. */ declare class NoSuchProviderReferenceError extends AISDKError { private readonly [symbol$3$1]; readonly provider: string; readonly reference: SharedV4ProviderReference; constructor({ provider, reference, message }: { provider: string; reference: SharedV4ProviderReference; message?: string; }); static isInstance(error: unknown): error is NoSuchProviderReferenceError; } declare const symbol$2$1: unique symbol; declare class TooManyEmbeddingValuesForCallError extends AISDKError { private readonly [symbol$2$1]; readonly provider: string; readonly modelId: string; readonly maxEmbeddingsPerCall: number; readonly values: Array; constructor(options: { provider: string; modelId: string; maxEmbeddingsPerCall: number; values: Array; }); static isInstance(error: unknown): error is TooManyEmbeddingValuesForCallError; } declare const symbol$1$2: unique symbol; interface TypeValidationContext { /** * Field path in dot notation (e.g., "message.metadata", "message.parts[3].data") */ field?: string; /** * Entity name (e.g., tool name, data type name) */ entityName?: string; /** * Entity identifier (e.g., message ID, tool call ID) */ entityId?: string; } declare class TypeValidationError extends AISDKError { private readonly [symbol$1$2]; readonly value: unknown; readonly context?: TypeValidationContext; constructor({ value, cause, context }: { value: unknown; cause: unknown; context?: TypeValidationContext; }); static isInstance(error: unknown): error is TypeValidationError; /** * Wraps an error into a TypeValidationError. * If the cause is already a TypeValidationError with the same value and context, it returns the cause. * Otherwise, it creates a new TypeValidationError. * * @param {Object} params - The parameters for wrapping the error. * @param {unknown} params.value - The value that failed validation. * @param {unknown} params.cause - The original error or cause of the validation failure. * @param {TypeValidationContext} params.context - Optional context about what is being validated. * @returns {TypeValidationError} A TypeValidationError instance. */ static wrap({ value, cause, context }: { value: unknown; cause: unknown; context?: TypeValidationContext; }): TypeValidationError; } declare const symbol$10: unique symbol; declare class UnsupportedFunctionalityError extends AISDKError { private readonly [symbol$10]; readonly functionality: string; constructor({ functionality, message }: { functionality: string; message?: string; }); static isInstance(error: unknown): error is UnsupportedFunctionalityError; } /** * Options for uploading a file via the files interface. */ type FilesV4UploadFileCallOptions = { /** * The file data. * * - `{ type: 'data', data }`: raw bytes (`Uint8Array`) or a base64-encoded string. * - `{ type: 'text', text }`: inline text (UTF-8). */ data: SharedV4FileDataData | SharedV4FileDataText; /** * The IANA media type of the file (e.g. `'application/pdf'`). */ mediaType: string; /** * The filename of the file. */ filename?: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV4ProviderOptions; }; /** * Result of uploading a file via the files interface. */ type FilesV4UploadFileResult = { /** * A provider reference mapping provider names to provider-specific file identifiers. */ providerReference: SharedV4ProviderReference; /** * The IANA media type of the uploaded file, if available from the provider. */ mediaType?: string; /** * The filename of the uploaded file, if available from the provider. */ filename?: 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. */ providerMetadata?: SharedV4ProviderMetadata; /** * Warnings from the provider. */ warnings: Array; }; /** * Specification for a file management interface that implements the files interface version 4. */ type FilesV4 = { /** * The files interface must specify which files interface version it implements. */ readonly specificationVersion: 'v4'; /** * Provider ID. */ readonly provider: string; /** * Uploads a file to the provider and returns a provider reference * that can be used in subsequent API calls. */ uploadFile(options: FilesV4UploadFileCallOptions): PromiseLike; }; /** * An image file that can be used for image editing or variation generation. */ type ImageModelV4File = { type: 'file'; /** * The IANA media type of the file, e.g. `image/png`. Any string is supported. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Generated file data as base64 encoded strings or binary data. * * The file data should be returned without any unnecessary conversion. * If the API returns base64 encoded strings, the file data should be returned * as base64 encoded strings. If the API returns binary data, the file data should * be returned as binary data. */ data: string | Uint8Array; /** * Optional provider-specific metadata for the file part. */ providerOptions?: SharedV4ProviderMetadata; } | { type: 'url'; /** * The URL of the image file. */ url: string; /** * Optional provider-specific metadata for the file part. */ providerOptions?: SharedV4ProviderMetadata; }; type ImageModelV4CallOptions = { /** * Prompt for the image generation. Some operations, like upscaling, may not require a prompt. */ prompt: string | undefined; /** * Number of images to generate. */ n: number; /** * Size of the images to generate. * Must have the format `{width}x{height}`. * `undefined` will use the provider's default size. */ size: `${number}x${number}` | undefined; /** * Aspect ratio of the images to generate. * Must have the format `{width}:{height}`. * `undefined` will use the provider's default aspect ratio. */ aspectRatio: `${number}:${number}` | undefined; /** * Seed for the image generation. * `undefined` will use the provider's default seed. */ seed: number | undefined; /** * Array of images for image editing or variation generation. * The images should be provided as base64 encoded strings or binary data. */ files: ImageModelV4File[] | undefined; /** * Mask image for inpainting operations. * The mask should be provided as base64 encoded strings or binary data. */ mask: ImageModelV4File | undefined; /** * 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: SharedV4ProviderOptions; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; }; /** * Usage information for an image model call. */ type ImageModelV4Usage = { /** * The number of input (prompt) tokens used. */ inputTokens: number | undefined; /** * The number of output tokens used, if reported by the provider. */ outputTokens: number | undefined; /** * The total number of tokens as reported by the provider. */ totalTokens: number | undefined; }; type ImageModelV4ProviderMetadata = Record; /** * The result of an image model doGenerate call. */ type ImageModelV4Result = { /** * Generated images as base64 encoded strings or binary data. * The images should be returned without any unnecessary conversion. * If the API returns base64 encoded strings, the images should be returned * as base64 encoded strings. If the API returns binary data, the images should * be returned as binary data. */ images: Array | Array; /** * Warnings for the call, e.g. unsupported features. */ warnings: Array; /** * 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. * * The outer record is keyed by the provider name, and the inner * record is provider-specific metadata. It always includes an * `images` key with image-specific metadata * * ```ts * { * "openai": { * "images": ["revisedPrompt": "Revised prompt here."] * } * } * ``` */ providerMetadata?: ImageModelV4ProviderMetadata; /** * Response information for telemetry and debugging purposes. */ response: { /** * 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 | undefined; }; /** * Optional token usage for the image generation call (if the provider reports it). */ usage?: ImageModelV4Usage; }; type GetMaxImagesPerCallFunction$2 = (options: { modelId: string; }) => PromiseLike | number | undefined; /** * Image generation model specification version 4. */ type ImageModelV4 = { /** * The image model must specify which image model interface * version it implements. This will allow us to evolve the image * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v4'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Limit of how many images can be generated in a single API call. * Can be set to a number for a fixed limit, to undefined to use * the global limit, or a function that returns a number or undefined, * optionally as a promise. */ readonly maxImagesPerCall: number | undefined | GetMaxImagesPerCallFunction$2; /** * Generates an array of images. */ doGenerate(options: ImageModelV4CallOptions): PromiseLike; }; /** * Usage information for an image model call. */ type ImageModelV3Usage = { /** * The number of input (prompt) tokens used. */ inputTokens: number | undefined; /** * The number of output tokens used, if reported by the provider. */ outputTokens: number | undefined; /** * The total number of tokens as reported by the provider. */ totalTokens: number | undefined; }; /** * An image file that can be used for image editing or variation generation. */ type ImageModelV3File = { type: 'file'; /** * The IANA media type of the file, e.g. `image/png`. Any string is supported. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Generated file data as base64 encoded strings or binary data. * * The file data should be returned without any unnecessary conversion. * If the API returns base64 encoded strings, the file data should be returned * as base64 encoded strings. If the API returns binary data, the file data should * be returned as binary data. */ data: string | Uint8Array; /** * Optional provider-specific metadata for the file part. */ providerOptions?: SharedV3ProviderMetadata$1; } | { type: 'url'; /** * The URL of the image file. */ url: string; /** * Optional provider-specific metadata for the file part. */ providerOptions?: SharedV3ProviderMetadata$1; }; type ImageModelV3CallOptions = { /** * Prompt for the image generation. Some operations, like upscaling, may not require a prompt. */ prompt: string | undefined; /** * Number of images to generate. */ n: number; /** * Size of the images to generate. * Must have the format `{width}x{height}`. * `undefined` will use the provider's default size. */ size: `${number}x${number}` | undefined; /** * Aspect ratio of the images to generate. * Must have the format `{width}:{height}`. * `undefined` will use the provider's default aspect ratio. */ aspectRatio: `${number}:${number}` | undefined; /** * Seed for the image generation. * `undefined` will use the provider's default seed. */ seed: number | undefined; /** * Array of images for image editing or variation generation. * The images should be provided as base64 encoded strings or binary data. */ files: ImageModelV3File[] | undefined; /** * Mask image for inpainting operations. * The mask should be provided as base64 encoded strings or binary data. */ mask: ImageModelV3File | undefined; /** * 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: SharedV3ProviderOptions$1; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; }; type ImageModelV3ProviderMetadata = Record; type GetMaxImagesPerCallFunction$1 = (options: { modelId: string; }) => PromiseLike | number | undefined; /** * Image generation model specification version 3. */ type ImageModelV3 = { /** * The image model must specify which image model interface * version it implements. This will allow us to evolve the image * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v3'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Limit of how many images can be generated in a single API call. * Can be set to a number for a fixed limit, to undefined to use * the global limit, or a function that returns a number or undefined, * optionally as a promise. */ readonly maxImagesPerCall: number | undefined | GetMaxImagesPerCallFunction$1; /** * Generates an array of images. */ doGenerate(options: ImageModelV3CallOptions): PromiseLike<{ /** * Generated images as base64 encoded strings or binary data. * The images should be returned without any unnecessary conversion. * If the API returns base64 encoded strings, the images should be returned * as base64 encoded strings. If the API returns binary data, the images should * be returned as binary data. */ images: Array | Array; /** * Warnings for the call, e.g. unsupported features. */ warnings: Array; /** * 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. * * The outer record is keyed by the provider name, and the inner * record is provider-specific metadata. It always includes an * `images` key with image-specific metadata * * ```ts * { * "openai": { * "images": ["revisedPrompt": "Revised prompt here."] * } * } * ``` */ providerMetadata?: ImageModelV3ProviderMetadata; /** * Response information for telemetry and debugging purposes. */ response: { /** * 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 | undefined; }; /** * Optional token usage for the image generation call (if the provider reports it). */ usage?: ImageModelV3Usage; }>; }; type ImageModelV2CallOptions = { /** * Prompt for the image generation. */ prompt: string; /** * Number of images to generate. */ n: number; /** * Size of the images to generate. * Must have the format `{width}x{height}`. * `undefined` will use the provider's default size. */ size: `${number}x${number}` | undefined; /** * Aspect ratio of the images to generate. * Must have the format `{width}:{height}`. * `undefined` will use the provider's default aspect ratio. */ aspectRatio: `${number}:${number}` | undefined; /** * Seed for the image generation. * `undefined` will use the provider's default seed. */ seed: number | undefined; /** * 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: SharedV2ProviderOptions$1; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; }; /** * 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 ImageModelV2CallWarning = { type: 'unsupported-setting'; setting: keyof ImageModelV2CallOptions; details?: string; } | { type: 'other'; message: string; }; type ImageModelV2ProviderMetadata = Record; type GetMaxImagesPerCallFunction = (options: { modelId: string; }) => PromiseLike | number | undefined; /** * Image generation model specification version 2. */ type ImageModelV2 = { /** * The image model must specify which image model interface * version it implements. This will allow us to evolve the image * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v2'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Limit of how many images can be generated in a single API call. * Can be set to a number for a fixed limit, to undefined to use * the global limit, or a function that returns a number or undefined, * optionally as a promise. */ readonly maxImagesPerCall: number | undefined | GetMaxImagesPerCallFunction; /** * Generates an array of images. */ doGenerate(options: ImageModelV2CallOptions): PromiseLike<{ /** * Generated images as base64 encoded strings or binary data. * The images should be returned without any unnecessary conversion. * If the API returns base64 encoded strings, the images should be returned * as base64 encoded strings. If the API returns binary data, the images should * be returned as binary data. */ images: Array | Array; /** * Warnings for the call, e.g. unsupported settings. */ warnings: Array; /** * 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. * * The outer record is keyed by the provider name, and the inner * record is provider-specific metadata. It always includes an * `images` key with image-specific metadata * * ```ts * { * "openai": { * "images": ["revisedPrompt": "Revised prompt here."] * } * } * ``` */ providerMetadata?: ImageModelV2ProviderMetadata; /** * Response information for telemetry and debugging purposes. */ response: { /** * 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 | undefined; }; }>; }; /** * Middleware for ImageModelV4. * This type defines the structure for middleware that can be used to modify * the behavior of ImageModelV4 operations. */ type ImageModelV4Middleware = { /** * Middleware specification version. Use `v4` for the current version. */ readonly specificationVersion: 'v4'; /** * Override the provider name if desired. * @param options.model - The image model instance. */ overrideProvider?: (options: { model: ImageModelV4; }) => string; /** * Override the model ID if desired. * @param options.model - The image model instance. */ overrideModelId?: (options: { model: ImageModelV4; }) => string; /** * Override the limit of how many images can be generated in a single API call if desired. * @param options.model - The image model instance. */ overrideMaxImagesPerCall?: (options: { model: ImageModelV4; }) => ImageModelV4['maxImagesPerCall']; /** * Transforms the parameters before they are passed to the image model. * @param options - Object containing the parameters. * @param options.params - The original parameters for the image model call. * @returns A promise that resolves to the transformed parameters. */ transformParams?: (options: { params: ImageModelV4CallOptions; model: ImageModelV4; }) => PromiseLike; /** * Wraps the generate operation of the image model. * * @param options - Object containing the generate function, parameters, and model. * @param options.doGenerate - The original generate function. * @param options.params - The parameters for the generate call. If the * `transformParams` middleware is used, this will be the transformed parameters. * @param options.model - The image model instance. * @returns A promise that resolves to the result of the generate operation. */ wrapGenerate?: (options: { doGenerate: () => ReturnType; params: ImageModelV4CallOptions; model: ImageModelV4; }) => Promise>>; }; /** * Middleware for ImageModelV3. * This type defines the structure for middleware that can be used to modify * the behavior of ImageModelV3 operations. */ /** * A tool has a name, a description, and a set of parameters. * * Note: this is **not** the user-facing tool definition. The AI SDK methods will * map the user-facing tool definitions to this format. */ type LanguageModelV4FunctionTool = { /** * The type of the tool (always 'function'). */ type: 'function'; /** * The name of the tool. Unique within this model call. */ name: string; /** * A description of the tool. The language model uses this to understand the * tool's purpose and to provide better completion suggestions. */ description?: string; /** * The parameters that the tool expects. The language model uses this to * understand the tool's input requirements and to provide matching suggestions. */ inputSchema: JSONSchema7; /** * An optional list of input examples that show the language * model what the input should look like. */ inputExamples?: Array<{ input: JSONObject$2; }>; /** * Strict mode setting for the tool. * * Providers that support strict mode will use this setting to determine * how the input should be generated. Strict mode will always produce * valid inputs, but it might limit what input schemas are supported. */ strict?: boolean; /** * The provider-specific options for the tool. */ providerOptions?: SharedV4ProviderOptions; }; /** * A prompt is a list of messages. * * Note: Not all models and prompt formats support multi-modal inputs and * tool calls. The validation happens at runtime. * * Note: This is not a user-facing prompt. The AI SDK methods will map the * user-facing prompt types such as chat or instruction prompts to this format. */ type LanguageModelV4Prompt = Array; type LanguageModelV4Message = ({ role: 'system'; content: string; } | { role: 'user'; content: Array; } | { role: 'assistant'; content: Array; } | { role: 'tool'; content: Array; }) & { /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV4ProviderOptions; }; /** * Text content part of a prompt. It contains a string of text. */ interface LanguageModelV4TextPart { type: 'text'; /** * The text content. */ text: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV4ProviderOptions; } /** * Reasoning content part of a prompt. It contains a string of reasoning text. */ interface LanguageModelV4ReasoningPart { type: 'reasoning'; /** * The reasoning text. */ text: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV4ProviderOptions; } /** * Reasoning file content part of a prompt. It contains a file generated as part of reasoning. */ interface LanguageModelV4ReasoningFilePart { type: 'reasoning-file'; /** * File data as a tagged discriminated union: * * - `{ type: 'data', data }`: raw bytes (Uint8Array) or base64-encoded string. * - `{ type: 'url', url }`: a URL that points to the file. */ data: SharedV4FileDataData | SharedV4FileDataUrl; /** * IANA media type of the file. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV4ProviderOptions; } /** * Provider-specific content part of a prompt. It contains no standardized * payload beyond provider-specific options. */ interface LanguageModelV4CustomPart { type: 'custom'; /** * The kind of custom content, in the format `{provider}.{provider-type}`. */ kind: `${string}.${string}`; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV4ProviderOptions; } /** * File content part of a prompt. It contains a file. */ interface LanguageModelV4FilePart { type: 'file'; /** * Optional filename of the file. */ filename?: string; /** * File data as a tagged discriminated union: * * - `{ type: 'data', data }`: raw bytes (Uint8Array) or base64-encoded string. * - `{ type: 'url', url }`: a URL that points to the file. * - `{ type: 'reference', reference }`: a provider reference (`{ [provider]: id }`). * - `{ type: 'text', text }`: inline text content (e.g. an inline text document). */ data: SharedV4FileData; /** * Either a full IANA media type (`type/subtype`, e.g. `image/png`) or just * the top-level IANA segment (e.g. `image`, `audio`, `video`, `text`). * * `*`-subtype wildcards (e.g. `image/*`) are normalized as equivalent to the * top-level segment alone (e.g. `image`). Providers can use the helpers in * `@ai-sdk/provider-utils` (`isFullMediaType`, `getTopLevelMediaType`, * `detectMediaType`) to resolve the field according to their API * requirements. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV4ProviderOptions; } /** * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model). */ interface LanguageModelV4ToolCallPart { 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. */ input: unknown; /** * Whether the tool call will be executed by the provider. * If this flag is not set or is false, the tool call will be executed by the client. */ providerExecuted?: boolean; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV4ProviderOptions; } /** * Tool result content part of a prompt. It contains the result of the tool call with the matching ID. */ interface LanguageModelV4ToolResultPart { 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. */ output: LanguageModelV4ToolResultOutput; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV4ProviderOptions; } /** * Tool approval response content part of a prompt. It contains the user's * decision to approve or deny a provider-executed tool call. */ interface LanguageModelV4ToolApprovalResponsePart { type: 'tool-approval-response'; /** * ID of the approval request that this response refers to. */ approvalId: string; /** * Whether the approval was granted (true) or denied (false). */ approved: boolean; /** * Optional reason for approval or denial. */ reason?: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV4ProviderOptions; } /** * Result of a tool call. */ type LanguageModelV4ToolResultOutput = { /** * Text tool output that should be directly sent to the API. */ type: 'text'; value: string; /** * Provider-specific options. */ providerOptions?: SharedV4ProviderOptions; } | { type: 'json'; value: JSONValue$3; /** * Provider-specific options. */ providerOptions?: SharedV4ProviderOptions; } | { /** * Type when the user has denied the execution of the tool call. */ type: 'execution-denied'; /** * Optional reason for the execution denial. */ reason?: string; /** * Provider-specific options. */ providerOptions?: SharedV4ProviderOptions; } | { type: 'error-text'; value: string; /** * Provider-specific options. */ providerOptions?: SharedV4ProviderOptions; } | { type: 'error-json'; value: JSONValue$3; /** * Provider-specific options. */ providerOptions?: SharedV4ProviderOptions; } | { type: 'content'; value: Array<{ type: 'text'; /** * Text content. */ text: string; /** * Provider-specific options. */ providerOptions?: SharedV4ProviderOptions; } | { type: 'file'; /** * File data as a tagged discriminated union: * * - `{ type: 'data', data }`: raw bytes (Uint8Array) or base64-encoded string. * - `{ type: 'url', url }`: a URL that points to the file. * - `{ type: 'reference', reference }`: a provider reference (`{ [provider]: id }`). * - `{ type: 'text', text }`: inline text content (e.g. an inline text document). */ data: SharedV4FileData; /** * Either a full IANA media type (`type/subtype`, e.g. `image/png`) or just * the top-level IANA segment (e.g. `image`, `audio`, `video`, `text`). * * `*`-subtype wildcards (e.g. `image/*`) are normalized as equivalent to the * top-level segment alone (e.g. `image`). Providers can use the helpers in * `@ai-sdk/provider-utils` (`isFullMediaType`, `getTopLevelMediaType`, * `detectMediaType`) to resolve the field according to their API * requirements. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Optional filename of the file. */ filename?: string; /** * Provider-specific options. */ providerOptions?: SharedV4ProviderOptions; } | { /** * Custom content part. This can be used to implement * provider-specific content parts. */ type: 'custom'; /** * Provider-specific options. */ providerOptions?: SharedV4ProviderOptions; }>; }; /** * The configuration of a provider tool. * * Provider tools are tools that are specific to a certain provider. * The input and output schemas are defined be the provider, and * some of the tools are also executed on the provider systems. */ type LanguageModelV4ProviderTool = { /** * The type of the tool (always 'provider'). */ type: 'provider'; /** * The ID of the tool. Should follow the format `.`. */ id: `${string}.${string}`; /** * The name of the tool. Unique within this model call. */ name: string; /** * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool. */ args: Record; }; type LanguageModelV4ToolChoice = { type: 'auto'; } | { type: 'none'; } | { type: 'required'; } | { type: 'tool'; toolName: string; }; type LanguageModelV4CallOptions = { /** * A language mode prompt is a standardized prompt type. * * Note: This is **not** the user-facing prompt. The AI SDK methods will map the * user-facing prompt types such as chat or instruction prompts to this format. * That approach allows us to evolve the user facing prompts without breaking * the language model interface. */ prompt: LanguageModelV4Prompt; /** * Maximum number of tokens to generate. */ maxOutputTokens?: number; /** * Temperature setting. The range depends on the provider and model. */ temperature?: 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[]; /** * Nucleus sampling. */ 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. */ presencePenalty?: number; /** * Frequency penalty setting. It affects the likelihood of the model * to repeatedly use the same words or phrases. */ frequencyPenalty?: number; /** * Response format. The output can either be text or JSON. Default is text. * * If JSON is selected, a schema can optionally be provided to guide the LLM. */ responseFormat?: { type: 'text'; } | { type: 'json'; /** * JSON schema that the generated output should conform to. */ schema?: JSONSchema7; /** * Name of output that should be generated. Used by some providers for additional LLM guidance. */ name?: string; /** * Description of the output that should be generated. Used by some providers for additional LLM guidance. */ description?: string; }; /** * The seed (integer) to use for random sampling. If set and supported * by the model, calls will generate deterministic results. */ seed?: number; /** * The tools that are available for the model. */ tools?: Array; /** * Specifies how the tool should be selected. Defaults to 'auto'. */ toolChoice?: LanguageModelV4ToolChoice; /** * Include raw chunks in the stream. Only applicable for streaming calls. */ includeRawChunks?: boolean; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; /** * Reasoning effort level for the model. Controls how much reasoning * the model performs before generating a response. Defaults to 'provider-default'. */ reasoning?: 'provider-default' | 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV4ProviderOptions; }; /** * A provider-specific content block that does not map to another standardized * content part type. */ type LanguageModelV4CustomContent = { type: 'custom'; /** * The kind of custom content, in the format `{provider}.{provider-type}`. */ kind: `${string}.${string}`; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerMetadata?: SharedV4ProviderMetadata; }; /** * A file that has been generated by the model. * Generated files as base64 encoded strings or binary data. * The files should be returned without any unnecessary conversion. */ type LanguageModelV4File = { type: 'file'; /** * The IANA media type of the file, e.g. `image/png` or `audio/mp3`. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Generated file data as a tagged discriminated union: * * - `{ type: 'data', data }`: raw bytes (Uint8Array) or base64-encoded string. * - `{ type: 'url', url }`: a URL that points to the file. * * The file data should be returned without any unnecessary conversion. * If the API returns base64 encoded strings, the file data should be returned * as base64 encoded strings. If the API returns binary data, the file data should * be returned as binary data. */ data: SharedV4FileDataData | SharedV4FileDataUrl; /** * Optional provider-specific metadata for the file part. */ providerMetadata?: SharedV4ProviderMetadata; }; /** * Reasoning that the model has generated. */ type LanguageModelV4Reasoning = { type: 'reasoning'; text: string; /** * Optional provider-specific metadata for the reasoning part. */ providerMetadata?: SharedV4ProviderMetadata; }; /** * A file that has been generated by the model as part of reasoning. * Generated files as base64 encoded strings or binary data. * The files should be returned without any unnecessary conversion. */ type LanguageModelV4ReasoningFile = { type: 'reasoning-file'; /** * The IANA media type of the file, e.g. `image/png` or `audio/mp3`. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Generated file data as a tagged discriminated union: * * - `{ type: 'data', data }`: raw bytes (Uint8Array) or base64-encoded string. * - `{ type: 'url', url }`: a URL that points to the file. * * The file data should be returned without any unnecessary conversion. * If the API returns base64 encoded strings, the file data should be returned * as base64 encoded strings. If the API returns binary data, the file data should * be returned as binary data. */ data: SharedV4FileDataData | SharedV4FileDataUrl; /** * Optional provider-specific metadata for the reasoning file part. */ providerMetadata?: SharedV4ProviderMetadata; }; /** * A source that has been used as input to generate the response. */ type LanguageModelV4Source = { type: 'source'; /** * The type of source - URL sources reference web content. */ sourceType: 'url'; /** * The ID of the source. */ id: string; /** * The URL of the source. */ url: string; /** * The title of the source. */ title?: string; /** * Additional provider metadata for the source. */ providerMetadata?: SharedV4ProviderMetadata; } | { type: 'source'; /** * The type of source - document sources reference files/documents. */ sourceType: 'document'; /** * The ID of the source. */ id: string; /** * IANA media type of the document (e.g., 'application/pdf'). */ mediaType: string; /** * The title of the document. */ title: string; /** * Optional filename of the document. */ filename?: string; /** * Additional provider metadata for the source. */ providerMetadata?: SharedV4ProviderMetadata; }; /** * Text that the model has generated. */ type LanguageModelV4Text = { type: 'text'; /** * The text content. */ text: string; providerMetadata?: SharedV4ProviderMetadata; }; /** * Tool approval request emitted by a provider for a provider-executed tool call. * * This is used for flows where the provider executes the tool (e.g. MCP tools) * but requires an explicit user approval before continuing. */ type LanguageModelV4ToolApprovalRequest = { type: 'tool-approval-request'; /** * ID of the approval request. This ID is referenced by the subsequent * tool-approval-response (tool message) to approve or deny execution. */ approvalId: string; /** * The tool call ID that this approval request is for. */ toolCallId: string; /** * Additional provider-specific metadata for the approval request. */ providerMetadata?: SharedV4ProviderMetadata; }; /** * Tool calls that the model has generated. */ type LanguageModelV4ToolCall = { type: 'tool-call'; /** * The identifier of the tool call. It must be unique across all tool calls. */ toolCallId: string; /** * The name of the tool that should be called. */ toolName: string; /** * Stringified JSON object with the tool call arguments. Must match the * parameters schema of the tool. */ input: string; /** * Whether the tool call will be executed by the provider. * If this flag is not set or is false, the tool call will be executed by the client. */ providerExecuted?: boolean; /** * Whether the tool is dynamic, i.e. defined at runtime. * For example, MCP (Model Context Protocol) tools that are executed by the provider. */ dynamic?: boolean; /** * Additional provider-specific metadata for the tool call. */ providerMetadata?: SharedV4ProviderMetadata; }; /** * Result of a tool call that has been executed by the provider. */ type LanguageModelV4ToolResult = { type: 'tool-result'; /** * The 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: NonNullable; /** * Optional flag if the result is an error or an error message. */ isError?: boolean; /** * Whether the tool result is preliminary. * * Preliminary tool results replace each other, e.g. image previews. * There always has to be a final, non-preliminary tool result. * * If this flag is set to true, the tool result is preliminary. * If this flag is not set or is false, the tool result is not preliminary. */ preliminary?: boolean; /** * Whether the tool is dynamic, i.e. defined at runtime. * For example, MCP (Model Context Protocol) tools that are executed by the provider. */ dynamic?: boolean; /** * Additional provider-specific metadata for the tool result. */ providerMetadata?: SharedV4ProviderMetadata; }; type LanguageModelV4Content = LanguageModelV4Text | LanguageModelV4Reasoning | LanguageModelV4CustomContent | LanguageModelV4ReasoningFile | LanguageModelV4File | LanguageModelV4ToolApprovalRequest | LanguageModelV4Source | LanguageModelV4ToolCall | LanguageModelV4ToolResult; /** * Reason why a language model finished generating a response. * * Contains both a unified finish reason and a raw finish reason from the provider. * The unified finish reason is used to provide a consistent finish reason across different providers. * The raw finish reason is used to provide the original finish reason from the provider. */ type LanguageModelV4FinishReason = { /** * Unified finish reason. This enables using the same finish reason across different providers. * * 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 */ unified: 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other'; /** * Raw finish reason from the provider. * This is the original finish reason from the provider. */ raw: string | undefined; }; interface LanguageModelV4ResponseMetadata { /** * ID for the generated response, if the provider sends one. */ id?: string; /** * Timestamp for the start of the generated response, if the provider sends one. */ timestamp?: Date; /** * The ID of the response model that was used to generate the response, if the provider sends one. */ modelId?: string; } /** * Usage information for a language model call. */ type LanguageModelV4Usage = { /** * Information about the input tokens. */ inputTokens: { /** * The total number of input (prompt) tokens used. */ total: number | undefined; /** * The number of non-cached input (prompt) tokens used. */ noCache: number | undefined; /** * The number of cached input (prompt) tokens read. */ cacheRead: number | undefined; /** * The number of cached input (prompt) tokens written. */ cacheWrite: number | undefined; }; /** * Information about the output tokens. */ outputTokens: { /** * The total number of output (completion) tokens used. */ total: number | undefined; /** * The number of text tokens used. */ text: number | undefined; /** * The number of reasoning tokens used. */ reasoning: number | undefined; }; /** * Raw usage information from the provider. * * This is the usage information in the shape that the provider returns. * It can include additional information that is not part of the standard usage information. */ raw?: JSONObject$2; }; /** * The result of a language model doGenerate call. */ type LanguageModelV4GenerateResult = { /** * Ordered content that the model has generated. */ content: Array; /** * The finish reason. */ finishReason: LanguageModelV4FinishReason; /** * The usage information. */ usage: LanguageModelV4Usage; /** * 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. */ providerMetadata?: SharedV4ProviderMetadata; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Request HTTP body that was sent to the provider API. */ body?: unknown; }; /** * Optional response information for telemetry and debugging purposes. */ response?: LanguageModelV4ResponseMetadata & { /** * Response headers. */ headers?: SharedV4Headers; /** * Response HTTP body. */ body?: unknown; }; /** * Warnings for the call, e.g. unsupported settings. */ warnings: Array; }; type LanguageModelV4StreamPart = { type: 'text-start'; providerMetadata?: SharedV4ProviderMetadata; id: string; } | { type: 'text-delta'; id: string; providerMetadata?: SharedV4ProviderMetadata; delta: string; } | { type: 'text-end'; providerMetadata?: SharedV4ProviderMetadata; id: string; } | { type: 'reasoning-start'; providerMetadata?: SharedV4ProviderMetadata; id: string; } | { type: 'reasoning-delta'; id: string; providerMetadata?: SharedV4ProviderMetadata; delta: string; } | { type: 'reasoning-end'; id: string; providerMetadata?: SharedV4ProviderMetadata; } | { type: 'tool-input-start'; id: string; toolName: string; providerMetadata?: SharedV4ProviderMetadata; providerExecuted?: boolean; dynamic?: boolean; title?: string; } | { type: 'tool-input-delta'; id: string; delta: string; providerMetadata?: SharedV4ProviderMetadata; } | { type: 'tool-input-end'; id: string; providerMetadata?: SharedV4ProviderMetadata; } | LanguageModelV4ToolApprovalRequest | LanguageModelV4ToolCall | LanguageModelV4ToolResult | LanguageModelV4CustomContent | LanguageModelV4File | LanguageModelV4ReasoningFile | LanguageModelV4Source | { type: 'stream-start'; warnings: Array; } | ({ type: 'response-metadata'; } & LanguageModelV4ResponseMetadata) | { type: 'finish'; usage: LanguageModelV4Usage; finishReason: LanguageModelV4FinishReason; providerMetadata?: SharedV4ProviderMetadata; } | { type: 'raw'; rawValue: unknown; } | { type: 'error'; error: unknown; }; /** * The result of a language model doStream call. */ type LanguageModelV4StreamResult = { /** * The stream. */ stream: ReadableStream; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Request HTTP body that was sent to the provider API. */ body?: unknown; }; /** * Optional response data. */ response?: { /** * Response headers. */ headers?: SharedV4Headers; }; }; /** * Specification for a language model that implements the language model interface version 4. */ type LanguageModelV4 = { /** * The language model must specify which language model interface version it implements. */ readonly specificationVersion: 'v4'; /** * Provider ID. */ readonly provider: string; /** * Provider-specific model ID. */ readonly modelId: string; /** * Supported URL patterns by media type for the provider. * * The keys are media type patterns or full media types (e.g. `*\/*` for everything, `audio/*`, `video/*`, or `application/pdf`). * and the values are arrays of regular expressions that match the URL paths. * * The matching should be against lower-case URLs. * * Matched URLs are supported natively by the model and are not downloaded. * * @returns A map of supported URL patterns by media type (as a promise or a plain object). */ supportedUrls: PromiseLike> | Record; /** * Generates a language model output (non-streaming). * * Naming: "do" prefix to prevent accidental direct usage of the method * by the user. */ doGenerate(options: LanguageModelV4CallOptions): PromiseLike; /** * Generates a language model output (streaming). * * Naming: "do" prefix to prevent accidental direct usage of the method * by the user. * * @return A stream of higher-level language model output parts. */ doStream(options: LanguageModelV4CallOptions): PromiseLike; }; /** * Experimental middleware for LanguageModelV4. * This type defines the structure for middleware that can be used to modify * the behavior of LanguageModelV4 operations. */ type LanguageModelV4Middleware = { /** * Middleware specification version. Use `v4` for the current version. */ readonly specificationVersion: 'v4'; /** * Override the provider name if desired. * @param options.model - The language model instance. */ overrideProvider?: (options: { model: LanguageModelV4; }) => string; /** * Override the model ID if desired. * @param options.model - The language model instance. */ overrideModelId?: (options: { model: LanguageModelV4; }) => string; /** * Override the supported URLs if desired. * @param options.model - The language model instance. */ overrideSupportedUrls?: (options: { model: LanguageModelV4; }) => PromiseLike> | Record; /** * Transforms the parameters before they are passed to the language model. * @param options - Object containing the type of operation and the parameters. * @param options.type - The type of operation ('generate' or 'stream'). * @param options.params - The original parameters for the language model call. * @returns A promise that resolves to the transformed parameters. */ transformParams?: (options: { type: 'generate' | 'stream'; params: LanguageModelV4CallOptions; model: LanguageModelV4; }) => PromiseLike; /** * Wraps the generate operation of the language model. * @param options - Object containing the generate function, parameters, and model. * @param options.doGenerate - The original generate function. * @param options.doStream - The original stream function. * @param options.params - The parameters for the generate call. If the * `transformParams` middleware is used, this will be the transformed parameters. * @param options.model - The language model instance. * @returns A promise that resolves to the result of the generate operation. */ wrapGenerate?: (options: { doGenerate: () => PromiseLike; doStream: () => PromiseLike; params: LanguageModelV4CallOptions; model: LanguageModelV4; }) => PromiseLike; /** * Wraps the stream operation of the language model. * * @param options - Object containing the stream function, parameters, and model. * @param options.doGenerate - The original generate function. * @param options.doStream - The original stream function. * @param options.params - The parameters for the stream call. If the * `transformParams` middleware is used, this will be the transformed parameters. * @param options.model - The language model instance. * @returns A promise that resolves to the result of the stream operation. */ wrapStream?: (options: { doGenerate: () => PromiseLike; doStream: () => PromiseLike; params: LanguageModelV4CallOptions; model: LanguageModelV4; }) => PromiseLike; }; /** * A tool has a name, a description, and a set of parameters. * * Note: this is **not** the user-facing tool definition. The AI SDK methods will * map the user-facing tool definitions to this format. */ type LanguageModelV3FunctionTool$1 = { /** * The type of the tool (always 'function'). */ type: 'function'; /** * The name of the tool. Unique within this model call. */ name: string; /** * A description of the tool. The language model uses this to understand the * tool's purpose and to provide better completion suggestions. */ description?: string; /** * The parameters that the tool expects. The language model uses this to * understand the tool's input requirements and to provide matching suggestions. */ inputSchema: JSONSchema7; /** * An optional list of input examples that show the language * model what the input should look like. */ inputExamples?: Array<{ input: JSONObject$2; }>; /** * Strict mode setting for the tool. * * Providers that support strict mode will use this setting to determine * how the input should be generated. Strict mode will always produce * valid inputs, but it might limit what input schemas are supported. */ strict?: boolean; /** * The provider-specific options for the tool. */ providerOptions?: SharedV3ProviderOptions$1; }; /** * Data content. Can be a Uint8Array, base64 encoded data as a string or a URL. */ type LanguageModelV3DataContent$1 = Uint8Array | string | URL; /** * A prompt is a list of messages. * * Note: Not all models and prompt formats support multi-modal inputs and * tool calls. The validation happens at runtime. * * Note: This is not a user-facing prompt. The AI SDK methods will map the * user-facing prompt types such as chat or instruction prompts to this format. */ type LanguageModelV3Prompt$1 = Array; type LanguageModelV3Message$1 = ({ role: 'system'; content: string; } | { role: 'user'; content: Array; } | { role: 'assistant'; content: Array; } | { role: 'tool'; content: Array; }) & { /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions$1; }; /** * Text content part of a prompt. It contains a string of text. */ interface LanguageModelV3TextPart$1 { type: 'text'; /** * The text content. */ text: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions$1; } /** * Reasoning content part of a prompt. It contains a string of reasoning text. */ interface LanguageModelV3ReasoningPart$1 { type: 'reasoning'; /** * The reasoning text. */ text: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions$1; } /** * File content part of a prompt. It contains a file. */ interface LanguageModelV3FilePart$1 { type: 'file'; /** * Optional filename of the file. */ filename?: string; /** * File data. Can be a Uint8Array, base64 encoded data as a string or a URL. */ data: LanguageModelV3DataContent$1; /** * IANA media type of the file. * * Can support wildcards, e.g. `image/*` (in which case the provider needs to take appropriate action). * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions$1; } /** * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model). */ interface LanguageModelV3ToolCallPart$1 { 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. */ input: unknown; /** * Whether the tool call will be executed by the provider. * If this flag is not set or is false, the tool call will be executed by the client. */ providerExecuted?: boolean; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions$1; } /** * Tool result content part of a prompt. It contains the result of the tool call with the matching ID. */ interface LanguageModelV3ToolResultPart$1 { 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. */ output: LanguageModelV3ToolResultOutput$1; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions$1; } /** * Tool approval response content part of a prompt. It contains the user's * decision to approve or deny a provider-executed tool call. */ interface LanguageModelV3ToolApprovalResponsePart$1 { type: 'tool-approval-response'; /** * ID of the approval request that this response refers to. */ approvalId: string; /** * Whether the approval was granted (true) or denied (false). */ approved: boolean; /** * Optional reason for approval or denial. */ reason?: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions$1; } /** * Result of a tool call. */ type LanguageModelV3ToolResultOutput$1 = { /** * Text tool output that should be directly sent to the API. */ type: 'text'; value: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions$1; } | { type: 'json'; value: JSONValue$3; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions$1; } | { /** * Type when the user has denied the execution of the tool call. */ type: 'execution-denied'; /** * Optional reason for the execution denial. */ reason?: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions$1; } | { type: 'error-text'; value: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions$1; } | { type: 'error-json'; value: JSONValue$3; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions$1; } | { type: 'content'; value: Array<{ type: 'text'; /** * Text content. */ text: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions$1; } | { type: 'file-data'; /** * Base-64 encoded media data. */ data: string; /** * IANA media type. * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Optional filename of the file. */ filename?: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions$1; } | { type: 'file-url'; /** * URL of the file. */ url: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions$1; } | { type: 'file-id'; /** * ID of the file. * * If you use multiple providers, you need to * specify the provider specific ids using * the Record option. The key is the provider * name, e.g. 'openai' or 'anthropic'. */ fileId: string | Record; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions$1; } | { /** * Images that are referenced using base64 encoded data. */ type: 'image-data'; /** * Base-64 encoded image data. */ data: string; /** * IANA media type. * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions$1; } | { /** * Images that are referenced using a URL. */ type: 'image-url'; /** * URL of the image. */ url: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions$1; } | { /** * Images that are referenced using a provider file id. */ type: 'image-file-id'; /** * Image that is referenced using a provider file id. * * If you use multiple providers, you need to * specify the provider specific ids using * the Record option. The key is the provider * name, e.g. 'openai' or 'anthropic'. */ fileId: string | Record; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions$1; } | { /** * Custom content part. This can be used to implement * provider-specific content parts. */ type: 'custom'; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions$1; }>; }; /** * The configuration of a provider tool. * * Provider tools are tools that are specific to a certain provider. * The input and output schemas are defined be the provider, and * some of the tools are also executed on the provider systems. */ type LanguageModelV3ProviderTool$1 = { /** * The type of the tool (always 'provider'). */ type: 'provider'; /** * The ID of the tool. Should follow the format `.`. */ id: `${string}.${string}`; /** * The name of the tool. Unique within this model call. */ name: string; /** * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool. */ args: Record; }; type LanguageModelV3ToolChoice$1 = { type: 'auto'; } | { type: 'none'; } | { type: 'required'; } | { type: 'tool'; toolName: string; }; type LanguageModelV3CallOptions$1 = { /** * A language mode prompt is a standardized prompt type. * * Note: This is **not** the user-facing prompt. The AI SDK methods will map the * user-facing prompt types such as chat or instruction prompts to this format. * That approach allows us to evolve the user facing prompts without breaking * the language model interface. */ prompt: LanguageModelV3Prompt$1; /** * Maximum number of tokens to generate. */ maxOutputTokens?: number; /** * Temperature setting. The range depends on the provider and model. */ temperature?: 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[]; /** * Nucleus sampling. */ 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. */ presencePenalty?: number; /** * Frequency penalty setting. It affects the likelihood of the model * to repeatedly use the same words or phrases. */ frequencyPenalty?: number; /** * Response format. The output can either be text or JSON. Default is text. * * If JSON is selected, a schema can optionally be provided to guide the LLM. */ responseFormat?: { type: 'text'; } | { type: 'json'; /** * JSON schema that the generated output should conform to. */ schema?: JSONSchema7; /** * Name of output that should be generated. Used by some providers for additional LLM guidance. */ name?: string; /** * Description of the output that should be generated. Used by some providers for additional LLM guidance. */ description?: string; }; /** * The seed (integer) to use for random sampling. If set and supported * by the model, calls will generate deterministic results. */ seed?: number; /** * The tools that are available for the model. */ tools?: Array; /** * Specifies how the tool should be selected. Defaults to 'auto'. */ toolChoice?: LanguageModelV3ToolChoice$1; /** * Include raw chunks in the stream. Only applicable for streaming calls. */ includeRawChunks?: boolean; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions$1; }; /** * A file that has been generated by the model. * Generated files as base64 encoded strings or binary data. * The files should be returned without any unnecessary conversion. */ type LanguageModelV3File$1 = { type: 'file'; /** * The IANA media type of the file, e.g. `image/png` or `audio/mp3`. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Generated file data as base64 encoded strings or binary data. * * The file data should be returned without any unnecessary conversion. * If the API returns base64 encoded strings, the file data should be returned * as base64 encoded strings. If the API returns binary data, the file data should * be returned as binary data. */ data: string | Uint8Array; /** * Optional provider-specific metadata for the file part. */ providerMetadata?: SharedV3ProviderMetadata$1; }; /** * Reasoning that the model has generated. */ type LanguageModelV3Reasoning$1 = { type: 'reasoning'; text: string; /** * Optional provider-specific metadata for the reasoning part. */ providerMetadata?: SharedV3ProviderMetadata$1; }; /** * A source that has been used as input to generate the response. */ type LanguageModelV3Source$1 = { type: 'source'; /** * The type of source - URL sources reference web content. */ sourceType: 'url'; /** * The ID of the source. */ id: string; /** * The URL of the source. */ url: string; /** * The title of the source. */ title?: string; /** * Additional provider metadata for the source. */ providerMetadata?: SharedV3ProviderMetadata$1; } | { type: 'source'; /** * The type of source - document sources reference files/documents. */ sourceType: 'document'; /** * The ID of the source. */ id: string; /** * IANA media type of the document (e.g., 'application/pdf'). */ mediaType: string; /** * The title of the document. */ title: string; /** * Optional filename of the document. */ filename?: string; /** * Additional provider metadata for the source. */ providerMetadata?: SharedV3ProviderMetadata$1; }; /** * Text that the model has generated. */ type LanguageModelV3Text$1 = { type: 'text'; /** * The text content. */ text: string; providerMetadata?: SharedV3ProviderMetadata$1; }; /** * Tool approval request emitted by a provider for a provider-executed tool call. * * This is used for flows where the provider executes the tool (e.g. MCP tools) * but requires an explicit user approval before continuing. */ type LanguageModelV3ToolApprovalRequest$1 = { type: 'tool-approval-request'; /** * ID of the approval request. This ID is referenced by the subsequent * tool-approval-response (tool message) to approve or deny execution. */ approvalId: string; /** * The tool call ID that this approval request is for. */ toolCallId: string; /** * Additional provider-specific metadata for the approval request. */ providerMetadata?: SharedV3ProviderMetadata$1; }; /** * Tool calls that the model has generated. */ type LanguageModelV3ToolCall$1 = { type: 'tool-call'; /** * The identifier of the tool call. It must be unique across all tool calls. */ toolCallId: string; /** * The name of the tool that should be called. */ toolName: string; /** * Stringified JSON object with the tool call arguments. Must match the * parameters schema of the tool. */ input: string; /** * Whether the tool call will be executed by the provider. * If this flag is not set or is false, the tool call will be executed by the client. */ providerExecuted?: boolean; /** * Whether the tool is dynamic, i.e. defined at runtime. * For example, MCP (Model Context Protocol) tools that are executed by the provider. */ dynamic?: boolean; /** * Additional provider-specific metadata for the tool call. */ providerMetadata?: SharedV3ProviderMetadata$1; }; /** * Result of a tool call that has been executed by the provider. */ type LanguageModelV3ToolResult$1 = { type: 'tool-result'; /** * The 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: NonNullable; /** * Optional flag if the result is an error or an error message. */ isError?: boolean; /** * Whether the tool result is preliminary. * * Preliminary tool results replace each other, e.g. image previews. * There always has to be a final, non-preliminary tool result. * * If this flag is set to true, the tool result is preliminary. * If this flag is not set or is false, the tool result is not preliminary. */ preliminary?: boolean; /** * Whether the tool is dynamic, i.e. defined at runtime. * For example, MCP (Model Context Protocol) tools that are executed by the provider. */ dynamic?: boolean; /** * Additional provider-specific metadata for the tool result. */ providerMetadata?: SharedV3ProviderMetadata$1; }; type LanguageModelV3Content$1 = LanguageModelV3Text$1 | LanguageModelV3Reasoning$1 | LanguageModelV3File$1 | LanguageModelV3ToolApprovalRequest$1 | LanguageModelV3Source$1 | LanguageModelV3ToolCall$1 | LanguageModelV3ToolResult$1; /** * Reason why a language model finished generating a response. * * Contains both a unified finish reason and a raw finish reason from the provider. * The unified finish reason is used to provide a consistent finish reason across different providers. * The raw finish reason is used to provide the original finish reason from the provider. */ type LanguageModelV3FinishReason$1 = { /** * Unified finish reason. This enables using the same finish reason across different providers. * * 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 */ unified: 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other'; /** * Raw finish reason from the provider. * This is the original finish reason from the provider. */ raw: string | undefined; }; interface LanguageModelV3ResponseMetadata$1 { /** * ID for the generated response, if the provider sends one. */ id?: string; /** * Timestamp for the start of the generated response, if the provider sends one. */ timestamp?: Date; /** * The ID of the response model that was used to generate the response, if the provider sends one. */ modelId?: string; } /** * Usage information for a language model call. */ type LanguageModelV3Usage$1 = { /** * Information about the input tokens. */ inputTokens: { /** * The total number of input (prompt) tokens used. */ total: number | undefined; /** * The number of non-cached input (prompt) tokens used. */ noCache: number | undefined; /** * The number of cached input (prompt) tokens read. */ cacheRead: number | undefined; /** * The number of cached input (prompt) tokens written. */ cacheWrite: number | undefined; }; /** * Information about the output tokens. */ outputTokens: { /** * The total number of output (completion) tokens used. */ total: number | undefined; /** * The number of text tokens used. */ text: number | undefined; /** * The number of reasoning tokens used. */ reasoning: number | undefined; }; /** * Raw usage information from the provider. * * This is the usage information in the shape that the provider returns. * It can include additional information that is not part of the standard usage information. */ raw?: JSONObject$2; }; /** * The result of a language model doGenerate call. */ type LanguageModelV3GenerateResult$1 = { /** * Ordered content that the model has generated. */ content: Array; /** * The finish reason. */ finishReason: LanguageModelV3FinishReason$1; /** * The usage information. */ usage: LanguageModelV3Usage$1; /** * 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. */ providerMetadata?: SharedV3ProviderMetadata$1; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Request HTTP body that was sent to the provider API. */ body?: unknown; }; /** * Optional response information for telemetry and debugging purposes. */ response?: LanguageModelV3ResponseMetadata$1 & { /** * Response headers. */ headers?: SharedV3Headers$1; /** * Response HTTP body. */ body?: unknown; }; /** * Warnings for the call, e.g. unsupported settings. */ warnings: Array; }; type LanguageModelV3StreamPart$1 = { type: 'text-start'; providerMetadata?: SharedV3ProviderMetadata$1; id: string; } | { type: 'text-delta'; id: string; providerMetadata?: SharedV3ProviderMetadata$1; delta: string; } | { type: 'text-end'; providerMetadata?: SharedV3ProviderMetadata$1; id: string; } | { type: 'reasoning-start'; providerMetadata?: SharedV3ProviderMetadata$1; id: string; } | { type: 'reasoning-delta'; id: string; providerMetadata?: SharedV3ProviderMetadata$1; delta: string; } | { type: 'reasoning-end'; id: string; providerMetadata?: SharedV3ProviderMetadata$1; } | { type: 'tool-input-start'; id: string; toolName: string; providerMetadata?: SharedV3ProviderMetadata$1; providerExecuted?: boolean; dynamic?: boolean; title?: string; } | { type: 'tool-input-delta'; id: string; delta: string; providerMetadata?: SharedV3ProviderMetadata$1; } | { type: 'tool-input-end'; id: string; providerMetadata?: SharedV3ProviderMetadata$1; } | LanguageModelV3ToolApprovalRequest$1 | LanguageModelV3ToolCall$1 | LanguageModelV3ToolResult$1 | LanguageModelV3File$1 | LanguageModelV3Source$1 | { type: 'stream-start'; warnings: Array; } | ({ type: 'response-metadata'; } & LanguageModelV3ResponseMetadata$1) | { type: 'finish'; usage: LanguageModelV3Usage$1; finishReason: LanguageModelV3FinishReason$1; providerMetadata?: SharedV3ProviderMetadata$1; } | { type: 'raw'; rawValue: unknown; } | { type: 'error'; error: unknown; }; /** * The result of a language model doStream call. */ type LanguageModelV3StreamResult$1 = { /** * The stream. */ stream: ReadableStream; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Request HTTP body that was sent to the provider API. */ body?: unknown; }; /** * Optional response data. */ response?: { /** * Response headers. */ headers?: SharedV3Headers$1; }; }; /** * Specification for a language model that implements the language model interface version 3. */ type LanguageModelV3$1 = { /** * The language model must specify which language model interface version it implements. */ readonly specificationVersion: 'v3'; /** * Provider ID. */ readonly provider: string; /** * Provider-specific model ID. */ readonly modelId: string; /** * Supported URL patterns by media type for the provider. * * The keys are media type patterns or full media types (e.g. `*\/*` for everything, `audio/*`, `video/*`, or `application/pdf`). * and the values are arrays of regular expressions that match the URL paths. * * The matching should be against lower-case URLs. * * Matched URLs are supported natively by the model and are not downloaded. * * @returns A map of supported URL patterns by media type (as a promise or a plain object). */ supportedUrls: PromiseLike> | Record; /** * Generates a language model output (non-streaming). * Naming: "do" prefix to prevent accidental direct usage of the method * by the user. */ doGenerate(options: LanguageModelV3CallOptions$1): PromiseLike; /** * Generates a language model output (streaming). * * Naming: "do" prefix to prevent accidental direct usage of the method * by the user. * * @return A stream of higher-level language model output parts. */ doStream(options: LanguageModelV3CallOptions$1): PromiseLike; }; /** * Experimental middleware for LanguageModelV3. * This type defines the structure for middleware that can be used to modify * the behavior of LanguageModelV3 operations. */ /** * A tool has a name, a description, and a set of parameters. * * Note: this is **not** the user-facing tool definition. The AI SDK methods will * map the user-facing tool definitions to this format. */ type LanguageModelV2FunctionTool$1 = { /** * The type of the tool (always 'function'). */ type: 'function'; /** * The name of the tool. Unique within this model call. */ name: string; /** * A description of the tool. The language model uses this to understand the * tool's purpose and to provide better completion suggestions. */ description?: string; /** * The parameters that the tool expects. The language model uses this to * understand the tool's input requirements and to provide matching suggestions. */ inputSchema: JSONSchema7; /** * The provider-specific options for the tool. */ providerOptions?: SharedV2ProviderOptions$1; }; /** * Data content. Can be a Uint8Array, base64 encoded data as a string or a URL. */ type LanguageModelV2DataContent$1 = Uint8Array | string | URL; /** * A prompt is a list of messages. * * Note: Not all models and prompt formats support multi-modal inputs and * tool calls. The validation happens at runtime. * * Note: This is not a user-facing prompt. The AI SDK methods will map the * user-facing prompt types such as chat or instruction prompts to this format. */ type LanguageModelV2Prompt$1 = Array; type LanguageModelV2Message$1 = ({ role: 'system'; content: string; } | { role: 'user'; content: Array; } | { role: 'assistant'; content: Array; } | { role: 'tool'; content: Array; }) & { /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions$1; }; /** * Text content part of a prompt. It contains a string of text. */ interface LanguageModelV2TextPart$1 { type: 'text'; /** * The text content. */ text: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions$1; } /** * Reasoning content part of a prompt. It contains a string of reasoning text. */ interface LanguageModelV2ReasoningPart$1 { type: 'reasoning'; /** * The reasoning text. */ text: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions$1; } /** * File content part of a prompt. It contains a file. */ interface LanguageModelV2FilePart$1 { type: 'file'; /** * Optional filename of the file. */ filename?: string; /** * File data. Can be a Uint8Array, base64 encoded data as a string or a URL. */ data: LanguageModelV2DataContent$1; /** * IANA media type of the file. * * Can support wildcards, e.g. `image/*` (in which case the provider needs to take appropriate action). * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions$1; } /** * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model). */ interface LanguageModelV2ToolCallPart$1 { 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. */ input: unknown; /** * Whether the tool call will be executed by the provider. * If this flag is not set or is false, the tool call will be executed by the client. */ providerExecuted?: boolean; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions$1; } /** * Tool result content part of a prompt. It contains the result of the tool call with the matching ID. */ interface LanguageModelV2ToolResultPart$1 { 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. */ output: LanguageModelV2ToolResultOutput$1; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions$1; } type LanguageModelV2ToolResultOutput$1 = { type: 'text'; value: string; } | { type: 'json'; value: JSONValue$3; } | { type: 'error-text'; value: string; } | { type: 'error-json'; value: JSONValue$3; } | { type: 'content'; value: Array<{ type: 'text'; /** * Text content. */ text: string; } | { type: 'media'; /** * Base-64 encoded media data. */ data: string; /** * IANA media type. * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; }>; }; /** * The configuration of a tool that is defined by the provider. */ type LanguageModelV2ProviderDefinedTool$1 = { /** * The type of the tool (always 'provider-defined'). */ type: 'provider-defined'; /** * The ID of the tool. Should follow the format `.`. */ id: `${string}.${string}`; /** * The name of the tool that the user must use in the tool set. */ name: string; /** * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool. */ args: Record; }; type LanguageModelV2ToolChoice$1 = { type: 'auto'; } | { type: 'none'; } | { type: 'required'; } | { type: 'tool'; toolName: string; }; type LanguageModelV2CallOptions$1 = { /** * A language mode prompt is a standardized prompt type. * * Note: This is **not** the user-facing prompt. The AI SDK methods will map the * user-facing prompt types such as chat or instruction prompts to this format. * That approach allows us to evolve the user facing prompts without breaking * the language model interface. */ prompt: LanguageModelV2Prompt$1; /** * Maximum number of tokens to generate. */ maxOutputTokens?: number; /** * Temperature setting. The range depends on the provider and model. */ temperature?: 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[]; /** * Nucleus sampling. */ 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. */ presencePenalty?: number; /** * Frequency penalty setting. It affects the likelihood of the model * to repeatedly use the same words or phrases. */ frequencyPenalty?: number; /** * Response format. The output can either be text or JSON. Default is text. * * If JSON is selected, a schema can optionally be provided to guide the LLM. */ responseFormat?: { type: 'text'; } | { type: 'json'; /** * JSON schema that the generated output should conform to. */ schema?: JSONSchema7; /** * Name of output that should be generated. Used by some providers for additional LLM guidance. */ name?: string; /** * Description of the output that should be generated. Used by some providers for additional LLM guidance. */ description?: string; }; /** * The seed (integer) to use for random sampling. If set and supported * by the model, calls will generate deterministic results. */ seed?: number; /** * The tools that are available for the model. */ tools?: Array; /** * Specifies how the tool should be selected. Defaults to 'auto'. */ toolChoice?: LanguageModelV2ToolChoice$1; /** * Include raw chunks in the stream. Only applicable for streaming calls. */ includeRawChunks?: boolean; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions$1; }; /** * 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 LanguageModelV2CallWarning$1 = { type: 'unsupported-setting'; setting: Omit; details?: string; } | { type: 'unsupported-tool'; tool: LanguageModelV2FunctionTool$1 | LanguageModelV2ProviderDefinedTool$1; details?: string; } | { type: 'other'; message: string; }; /** * A file that has been generated by the model. * Generated files as base64 encoded strings or binary data. * The files should be returned without any unnecessary conversion. */ type LanguageModelV2File$1 = { type: 'file'; /** * The IANA media type of the file, e.g. `image/png` or `audio/mp3`. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Generated file data as base64 encoded strings or binary data. * * The file data should be returned without any unnecessary conversion. * If the API returns base64 encoded strings, the file data should be returned * as base64 encoded strings. If the API returns binary data, the file data should * be returned as binary data. */ data: string | Uint8Array; }; /** * Reasoning that the model has generated. */ type LanguageModelV2Reasoning$1 = { type: 'reasoning'; text: string; /** * Optional provider-specific metadata for the reasoning part. */ providerMetadata?: SharedV2ProviderMetadata$1; }; /** * A source that has been used as input to generate the response. */ type LanguageModelV2Source$1 = { type: 'source'; /** * The type of source - URL sources reference web content. */ sourceType: 'url'; /** * The ID of the source. */ id: string; /** * The URL of the source. */ url: string; /** * The title of the source. */ title?: string; /** * Additional provider metadata for the source. */ providerMetadata?: SharedV2ProviderMetadata$1; } | { type: 'source'; /** * The type of source - document sources reference files/documents. */ sourceType: 'document'; /** * The ID of the source. */ id: string; /** * IANA media type of the document (e.g., 'application/pdf'). */ mediaType: string; /** * The title of the document. */ title: string; /** * Optional filename of the document. */ filename?: string; /** * Additional provider metadata for the source. */ providerMetadata?: SharedV2ProviderMetadata$1; }; /** * Text that the model has generated. */ type LanguageModelV2Text$1 = { type: 'text'; /** * The text content. */ text: string; providerMetadata?: SharedV2ProviderMetadata$1; }; /** * Tool calls that the model has generated. */ type LanguageModelV2ToolCall$1 = { type: 'tool-call'; /** * The identifier of the tool call. It must be unique across all tool calls. */ toolCallId: string; /** * The name of the tool that should be called. */ toolName: string; /** * Stringified JSON object with the tool call arguments. Must match the * parameters schema of the tool. */ input: string; /** * Whether the tool call will be executed by the provider. * If this flag is not set or is false, the tool call will be executed by the client. */ providerExecuted?: boolean; /** * Additional provider-specific metadata for the tool call. */ providerMetadata?: SharedV2ProviderMetadata$1; }; /** * Result of a tool call that has been executed by the provider. */ type LanguageModelV2ToolResult$1 = { type: 'tool-result'; /** * The 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; /** * Optional flag if the result is an error or an error message. */ isError?: boolean; /** * Whether the tool result was generated by the provider. * If this flag is set to true, the tool result was generated by the provider. * If this flag is not set or is false, the tool result was generated by the client. */ providerExecuted?: boolean; /** * Additional provider-specific metadata for the tool result. */ providerMetadata?: SharedV2ProviderMetadata$1; }; type LanguageModelV2Content$1 = LanguageModelV2Text$1 | LanguageModelV2Reasoning$1 | LanguageModelV2File$1 | LanguageModelV2Source$1 | LanguageModelV2ToolCall$1 | LanguageModelV2ToolResult$1; /** * 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 * - `unknown`: the model has not transmitted a finish reason */ type LanguageModelV2FinishReason$1 = 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'; interface LanguageModelV2ResponseMetadata$1 { /** * ID for the generated response, if the provider sends one. */ id?: string; /** * Timestamp for the start of the generated response, if the provider sends one. */ timestamp?: Date; /** * The ID of the response model that was used to generate the response, if the provider sends one. */ modelId?: string; } /** * Usage information for a language model call. * * If your API return additional usage information, you can add it to the * provider metadata under your provider's key. */ type LanguageModelV2Usage$1 = { /** * The number of input (prompt) tokens used. */ inputTokens: number | undefined; /** * The number of output (completion) tokens used. */ outputTokens: number | undefined; /** * The total number of tokens as reported by the provider. * This number might be different from the sum of `inputTokens` and `outputTokens` * and e.g. include reasoning tokens or other overhead. */ totalTokens: number | undefined; /** * The number of reasoning tokens used. */ reasoningTokens?: number | undefined; /** * The number of cached input tokens. */ cachedInputTokens?: number | undefined; }; type LanguageModelV2StreamPart$1 = { type: 'text-start'; providerMetadata?: SharedV2ProviderMetadata$1; id: string; } | { type: 'text-delta'; id: string; providerMetadata?: SharedV2ProviderMetadata$1; delta: string; } | { type: 'text-end'; providerMetadata?: SharedV2ProviderMetadata$1; id: string; } | { type: 'reasoning-start'; providerMetadata?: SharedV2ProviderMetadata$1; id: string; } | { type: 'reasoning-delta'; id: string; providerMetadata?: SharedV2ProviderMetadata$1; delta: string; } | { type: 'reasoning-end'; id: string; providerMetadata?: SharedV2ProviderMetadata$1; } | { type: 'tool-input-start'; id: string; toolName: string; providerMetadata?: SharedV2ProviderMetadata$1; providerExecuted?: boolean; } | { type: 'tool-input-delta'; id: string; delta: string; providerMetadata?: SharedV2ProviderMetadata$1; } | { type: 'tool-input-end'; id: string; providerMetadata?: SharedV2ProviderMetadata$1; } | LanguageModelV2ToolCall$1 | LanguageModelV2ToolResult$1 | LanguageModelV2File$1 | LanguageModelV2Source$1 | { type: 'stream-start'; warnings: Array; } | ({ type: 'response-metadata'; } & LanguageModelV2ResponseMetadata$1) | { type: 'finish'; usage: LanguageModelV2Usage$1; finishReason: LanguageModelV2FinishReason$1; providerMetadata?: SharedV2ProviderMetadata$1; } | { type: 'raw'; rawValue: unknown; } | { type: 'error'; error: unknown; }; /** * Specification for a language model that implements the language model interface version 2. */ type LanguageModelV2$1 = { /** * The language model must specify which language model interface version it implements. */ readonly specificationVersion: 'v2'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Supported URL patterns by media type for the provider. * * The keys are media type patterns or full media types (e.g. `*\/*` for everything, `audio/*`, `video/*`, or `application/pdf`). * and the values are arrays of regular expressions that match the URL paths. * * The matching should be against lower-case URLs. * * Matched URLs are supported natively by the model and are not downloaded. * * @returns A map of supported URL patterns by media type (as a promise or a plain object). */ supportedUrls: PromiseLike> | Record; /** * Generates a language model output (non-streaming). * * Naming: "do" prefix to prevent accidental direct usage of the method * by the user. */ doGenerate(options: LanguageModelV2CallOptions$1): PromiseLike<{ /** * Ordered content that the model has generated. */ content: Array; /** * Finish reason. */ finishReason: LanguageModelV2FinishReason$1; /** * Usage information. */ usage: LanguageModelV2Usage$1; /** * 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. */ providerMetadata?: SharedV2ProviderMetadata$1; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Request HTTP body that was sent to the provider API. */ body?: unknown; }; /** * Optional response information for telemetry and debugging purposes. */ response?: LanguageModelV2ResponseMetadata$1 & { /** * Response headers. */ headers?: SharedV2Headers$1; /** * Response HTTP body. */ body?: unknown; }; /** * Warnings for the call, e.g. unsupported settings. */ warnings: Array; }>; /** * Generates a language model output (streaming). * * Naming: "do" prefix to prevent accidental direct usage of the method * by the user. * * @return A stream of higher-level language model output parts. */ doStream(options: LanguageModelV2CallOptions$1): PromiseLike<{ stream: ReadableStream; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Request HTTP body that was sent to the provider API. */ body?: unknown; }; /** * Optional response data. */ response?: { /** * Response headers. */ headers?: SharedV2Headers$1; }; }>; }; /** * Experimental middleware for LanguageModelV2. * This type defines the structure for middleware that can be used to modify * the behavior of LanguageModelV2 operations. */ /** * Middleware for EmbeddingModelV4. * This type defines the structure for middleware that can be used to modify * the behavior of EmbeddingModelV4 operations. */ type EmbeddingModelV4Middleware = { /** * Middleware specification version. Use `v4` for the current version. */ readonly specificationVersion: 'v4'; /** * Override the provider name if desired. * @param options.model - The embedding model instance. */ overrideProvider?: (options: { model: EmbeddingModelV4; }) => string; /** * Override the model ID if desired. * @param options.model - The embedding model instance. */ overrideModelId?: (options: { model: EmbeddingModelV4; }) => string; /** * Override the limit of how many embeddings can be generated in a single API call if desired. * @param options.model - The embedding model instance. */ overrideMaxEmbeddingsPerCall?: (options: { model: EmbeddingModelV4; }) => PromiseLike | number | undefined; /** * Override support for handling multiple embedding calls in parallel, if desired.. * @param options.model - The embedding model instance. */ overrideSupportsParallelCalls?: (options: { model: EmbeddingModelV4; }) => PromiseLike | boolean; /** * Transforms the parameters before they are passed to the embed model. * @param options - Object containing the type of operation and the parameters. * @param options.params - The original parameters for the embedding model call. * @returns A promise that resolves to the transformed parameters. */ transformParams?: (options: { params: EmbeddingModelV4CallOptions; model: EmbeddingModelV4; }) => PromiseLike; /** * Wraps the embed operation of the embedding model. * * @param options - Object containing the embed function, parameters, and model. * @param options.doEmbed - The original embed function. * @param options.params - The parameters for the embed call. If the * `transformParams` middleware is used, this will be the transformed parameters. * @param options.model - The embedding model instance. * @returns A promise that resolves to the result of the generate operation. */ wrapEmbed?: (options: { doEmbed: () => ReturnType; params: EmbeddingModelV4CallOptions; model: EmbeddingModelV4; }) => Promise>>; }; /** * Middleware for EmbeddingModelV3. * This type defines the structure for middleware that can be used to modify * the behavior of EmbeddingModelV3 operations. */ /** * A normalized language model call within a batch. */ type LanguageModelV4BatchRequest = { /** * Application-provided identifier used to correlate the request with its * result. */ readonly id: string; /** * Normalized text-generation options for the request. */ readonly options: Pick; }; /** * Language model V4 with durable batch-processing support. */ type BatchLanguageModelV4 = LanguageModelV4 & BatchModelV4; type RerankingModelV4CallOptions = { /** * Documents to rerank. * Either a list of texts or a list of JSON objects. */ documents: { type: 'text'; values: string[]; } | { type: 'object'; values: JSONObject$2[]; }; /** * The query is a string that represents the query to rerank the documents against. */ query: string; /** * Optional limit returned documents to the top n documents. */ topN?: number; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV4ProviderOptions; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: SharedV4Headers; }; /** * The result of a reranking model doRerank call. */ type RerankingModelV4Result = { /** * Ordered list of reranked documents (via index before reranking). * The documents are sorted by the descending order of relevance scores. */ ranking: Array<{ /** * The index of the document in the original list of documents before reranking. */ index: number; /** * The relevance score of the document after reranking. */ relevanceScore: number; }>; /** * 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. */ providerMetadata?: SharedV4ProviderMetadata; /** * Warnings for the call, e.g. unsupported settings. */ warnings?: Array; /** * Optional response information for debugging purposes. */ response?: { /** * ID for the generated response, if the provider sends one. */ id?: string; /** * Timestamp for the start of the generated response, if the provider sends one. */ timestamp?: Date; /** * The ID of the response model that was used to generate the response, if the provider sends one. */ modelId?: string; /** * Response headers. */ headers?: SharedV4Headers; /** * Response body. */ body?: unknown; }; }; /** * Specification for a reranking model that implements the reranking model interface version 4. */ type RerankingModelV4 = { /** * The reranking model must specify which reranking model interface version it implements. */ readonly specificationVersion: 'v4'; /** * Provider ID. */ readonly provider: string; /** * Provider-specific model ID. */ readonly modelId: string; /** * Reranking a list of documents using the query. */ doRerank(options: RerankingModelV4CallOptions): PromiseLike; }; type SpeechModelV4ProviderOptions = Record; type SpeechModelV4CallOptions = { /** * Text to convert to speech. */ text: string; /** * The voice to use for speech synthesis. * This is provider-specific and may be a voice ID, name, or other identifier. */ voice?: string; /** * The desired output format for the audio e.g. "mp3", "wav", etc. */ outputFormat?: string; /** * Instructions for the speech generation e.g. "Speak in a slow and steady tone". */ instructions?: string; /** * The speed of the speech generation. */ speed?: number; /** * The language for speech generation. This should be an ISO 639-1 language code (e.g. "en", "es", "fr") * or "auto" for automatic language detection. Provider support varies. */ language?: string; /** * 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": {} * } * ``` */ providerOptions?: SpeechModelV4ProviderOptions; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; }; /** * The result of a speech model doGenerate call. */ type SpeechModelV4Result = { /** * Generated audio as an ArrayBuffer. * The audio should be returned without any unnecessary conversion. * If the API returns base64 encoded strings, the audio should be returned * as base64 encoded strings. If the API returns binary data, the audio * should be returned as binary data. */ audio: string | Uint8Array; /** * Warnings for the call, e.g. unsupported settings. */ warnings: Array; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Response body (available only for providers that use HTTP requests). */ body?: unknown; }; /** * Response information for telemetry and debugging purposes. */ response: { /** * 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?: SharedV2Headers$1; /** * Response body. */ body?: unknown; }; /** * 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. */ providerMetadata?: Record; }; /** * Speech model specification version 4. */ type SpeechModelV4 = { /** * The speech model must specify which speech model interface * version it implements. This will allow us to evolve the speech * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v4'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Generates speech audio from text. */ doGenerate(options: SpeechModelV4CallOptions): PromiseLike; }; type TranscriptionModelV4ProviderOptions$1 = Record; type TranscriptionModelV4CallOptions = { /** * Audio data to transcribe. * Accepts a `Uint8Array` or `string`, where `string` is a base64 encoded audio file. */ audio: Uint8Array | string; /** * The IANA media type of the audio data. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * 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": { * "timestampGranularities": ["word"] * } * } * ``` */ providerOptions?: TranscriptionModelV4ProviderOptions$1; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; }; /** * The result of a transcription model doGenerate call. */ type TranscriptionModelV4Result = { /** * The complete transcribed text from the audio. */ text: string; /** * Array of transcript segments with timing information. * Each segment represents a portion of the transcribed text with start and end times. */ segments: Array<{ /** * The text content of this segment. */ text: string; /** * The start time of this segment in seconds. */ startSecond: number; /** * The end time of this segment in seconds. */ endSecond: number; }>; /** * The detected language of the audio content, as an ISO-639-1 code (e.g., 'en' for English). * May be undefined if the language couldn't be detected. */ language: string | undefined; /** * The total duration of the audio file in seconds. * May be undefined if the duration couldn't be determined. */ durationInSeconds: number | undefined; /** * Warnings for the call, e.g. unsupported settings. */ warnings: Array; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Raw request HTTP body that was sent to the provider API as a string (JSON should be stringified). * Non-HTTP(s) providers should not set this. */ body?: string; }; /** * Response information for telemetry and debugging purposes. */ response: { /** * 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?: SharedV4Headers; /** * Response body. */ body?: unknown; }; /** * 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. */ providerMetadata?: Record; }; type TranscriptionModelV4ProviderOptions = Record; type TranscriptionModelV4StreamOptions = { /** * Audio chunks to transcribe. * * `Uint8Array` chunks contain raw audio bytes. `string` chunks contain * base64-encoded raw audio bytes. */ audio: ReadableStream; /** * The input audio format for the raw audio chunks. */ inputAudioFormat: SharedV4AudioFormat; /** * Additional provider-specific options that are passed through to the provider. * * The outer record is keyed by the provider name, and the inner record is keyed * by provider-specific option names. */ providerOptions?: TranscriptionModelV4ProviderOptions; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP/WebSocket-based providers that support headers. */ headers?: Record; /** * When true, providers should include raw provider chunks in the stream. */ includeRawChunks?: boolean; }; type TranscriptionModelV4StreamPart = { /** * Stream start event with warnings for the call, e.g. unsupported settings. */ type: 'stream-start'; warnings: Array; } | { /** * Append-only transcript delta. */ type: 'transcript-delta'; id?: string; delta: string; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Non-final transcript text. The text may be revised by later parts. */ type: 'transcript-partial'; id?: string; text: string; startSecond?: number; durationInSeconds?: number; channelIndex?: number; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Final transcript text for a provider-defined segment or utterance. */ type: 'transcript-final'; id?: string; text: string; startSecond?: number; endSecond?: number; channelIndex?: number; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Metadata for the response, emitted once available. */ type: 'response-metadata'; timestamp?: Date; modelId?: string; headers?: SharedV4Headers; body?: unknown; } | { /** * Metadata that is available after the stream is finished. */ type: 'finish'; text: string; segments: Array<{ text: string; startSecond: number; endSecond: number; }>; language?: string; durationInSeconds?: number; providerMetadata?: Record; } | { /** * Raw provider chunks if enabled. */ type: 'raw'; rawValue: unknown; } | { /** * Error parts are streamed, allowing for multiple errors. */ type: 'error'; error: unknown; }; /** * The result of a transcription model doStream call. */ type TranscriptionModelV4StreamResult = { /** * The stream. */ stream: ReadableStream; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Request body or setup payload that was sent to the provider API. */ body?: unknown; }; /** * Optional response data. */ response?: { /** * Timestamp for the start of the streamed response. */ timestamp?: Date; /** * The ID of the response model that was used to generate the response. */ modelId?: string; /** * Response headers. */ headers?: SharedV4Headers; /** * Response body. */ body?: unknown; }; }; /** * Transcription model specification version 4. */ type TranscriptionModelV4 = { /** * The transcription model must specify which transcription model interface * version it implements. This will allow us to evolve the transcription * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v4'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Generates a transcript. */ doGenerate(options: TranscriptionModelV4CallOptions): PromiseLike; /** * Streams a transcript for live audio. * * Experimental: the streaming transcription contract may change in patch * releases while `experimental_streamTranscribe` is experimental. The * stream option/part/result types are exported with `Experimental_` * prefixes for this reason. */ doStream?(options: TranscriptionModelV4StreamOptions): PromiseLike; }; interface SkillsV4File { /** * The path of the file relative to the skill root. */ path: string; /** * The file data. * * - `{ type: 'data', data }`: raw bytes (`Uint8Array`) or a base64-encoded string. * - `{ type: 'text', text }`: inline text (UTF-8). */ data: SharedV4FileDataData | SharedV4FileDataText; } interface SkillsV4UploadSkillCallOptions { /** * The files that make up the skill. */ files: SkillsV4File[]; /** * Optional human-readable title for the skill. */ displayTitle?: string; /** * Additional provider-specific options. */ providerOptions?: SharedV4ProviderOptions; } interface SkillsV4UploadSkillResult { /** * A provider reference mapping provider names to provider-specific skill identifiers. */ providerReference: SharedV4ProviderReference; /** * Optional human-readable title for the uploaded skill. */ displayTitle?: string; /** * Optional name of the uploaded skill. */ name?: string; /** * Optional description of what the uploaded skill does. */ description?: string; /** * Optional latest version identifier of the uploaded skill. */ latestVersion?: string; /** * Additional provider-specific metadata. */ providerMetadata?: SharedV4ProviderMetadata; /** * Warnings for the call, e.g. unsupported settings. */ warnings: SharedV4Warning[]; } /** * Skills specification version 4. */ interface SkillsV4 { /** * The skills implementation must specify which skills interface * version it implements. This will allow us to evolve the skills * interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v4'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Uploads a new skill from the given files. */ uploadSkill(params: SkillsV4UploadSkillCallOptions): PromiseLike; } /** * Provider for language, text embedding, and image generation models. */ interface ProviderV4 { readonly specificationVersion: 'v4'; /** * Returns the language model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {LanguageModelV4} The language model associated with the id * * @throws {NoSuchModelError} If no such model exists. */ languageModel(modelId: string): LanguageModelV4; /** * 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} modelId - The id of the model to return. * * @returns {EmbeddingModelV4} The embedding model associated with the id * * @throws {NoSuchModelError} If no such model exists. */ embeddingModel(modelId: string): EmbeddingModelV4; /** * Returns the image model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {ImageModelV4} The image model associated with the id */ imageModel(modelId: string): ImageModelV4; /** * Returns the transcription model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {TranscriptionModelV4} The transcription model associated with the id */ transcriptionModel?(modelId: string): TranscriptionModelV4; /** * Returns the speech model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {SpeechModelV4} The speech model associated with the id */ speechModel?(modelId: string): SpeechModelV4; /** * Returns the reranking model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {RerankingModelV4} The reranking model associated with the id * * @throws {NoSuchModelError} If no such model exists. */ rerankingModel?(modelId: string): RerankingModelV4; /** * Returns the files interface for uploading files to the provider. * The returned interface can be passed to the `uploadFile` function. * * @returns {FilesV4} The files interface for this provider. */ files?(): FilesV4; /** * Returns the skills interface for uploading skills to the provider. * The returned interface can be passed to the `uploadSkill` function. */ skills?(): SkillsV4; } type RerankingModelV3CallOptions = { /** * Documents to rerank. * Either a list of texts or a list of JSON objects. */ documents: { type: 'text'; values: string[]; } | { type: 'object'; values: JSONObject$2[]; }; /** * The query is a string that represents the query to rerank the documents against. */ query: string; /** * Optional limit returned documents to the top n documents. */ topN?: number; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions$1; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: SharedV3Headers$1; }; /** * Specification for a reranking model that implements the reranking model interface version 3. */ type RerankingModelV3 = { /** * The reranking model must specify which reranking model interface version it implements. */ readonly specificationVersion: 'v3'; /** * Provider ID. */ readonly provider: string; /** * Provider-specific model ID. */ readonly modelId: string; /** * Reranking a list of documents using the query. */ doRerank(options: RerankingModelV3CallOptions): PromiseLike<{ /** * Ordered list of reranked documents (via index before reranking). * The documents are sorted by the descending order of relevance scores. */ ranking: Array<{ /** * The index of the document in the original list of documents before reranking. */ index: number; /** * The relevance score of the document after reranking. */ relevanceScore: number; }>; /** * 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. */ providerMetadata?: SharedV3ProviderMetadata$1; /** * Warnings for the call, e.g. unsupported settings. */ warnings?: Array; /** * Optional response information for debugging purposes. */ response?: { /** * ID for the generated response, if the provider sends one. */ id?: string; /** * Timestamp for the start of the generated response, if the provider sends one. */ timestamp?: Date; /** * The ID of the response model that was used to generate the response, if the provider sends one. */ modelId?: string; /** * Response headers. */ headers?: SharedV3Headers$1; /** * Response body. */ body?: unknown; }; }>; }; type SpeechModelV3ProviderOptions = Record; type SpeechModelV3CallOptions = { /** * Text to convert to speech. */ text: string; /** * The voice to use for speech synthesis. * This is provider-specific and may be a voice ID, name, or other identifier. */ voice?: string; /** * The desired output format for the audio e.g. "mp3", "wav", etc. */ outputFormat?: string; /** * Instructions for the speech generation e.g. "Speak in a slow and steady tone". */ instructions?: string; /** * The speed of the speech generation. */ speed?: number; /** * The language for speech generation. This should be an ISO 639-1 language code (e.g. "en", "es", "fr") * or "auto" for automatic language detection. Provider support varies. */ language?: string; /** * 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": {} * } * ``` */ providerOptions?: SpeechModelV3ProviderOptions; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; }; /** * Speech model specification version 3. */ type SpeechModelV3 = { /** * The speech model must specify which speech model interface * version it implements. This will allow us to evolve the speech * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v3'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Generates speech audio from text. */ doGenerate(options: SpeechModelV3CallOptions): PromiseLike<{ /** * Generated audio as an ArrayBuffer. * The audio should be returned without any unnecessary conversion. * If the API returns base64 encoded strings, the audio should be returned * as base64 encoded strings. If the API returns binary data, the audio * should be returned as binary data. */ audio: string | Uint8Array; /** * Warnings for the call, e.g. unsupported settings. */ warnings: Array; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Response body (available only for providers that use HTTP requests). */ body?: unknown; }; /** * Response information for telemetry and debugging purposes. */ response: { /** * 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?: SharedV2Headers$1; /** * Response body. */ body?: unknown; }; /** * 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. */ providerMetadata?: Record; }>; }; type TranscriptionModelV3ProviderOptions = Record; type TranscriptionModelV3CallOptions = { /** * Audio data to transcribe. * Accepts a `Uint8Array` or `string`, where `string` is a base64 encoded audio file. */ audio: Uint8Array | string; /** * The IANA media type of the audio data. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * 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": { * "timestampGranularities": ["word"] * } * } * ``` */ providerOptions?: TranscriptionModelV3ProviderOptions; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; }; /** * Transcription model specification version 3. */ type TranscriptionModelV3 = { /** * The transcription model must specify which transcription model interface * version it implements. This will allow us to evolve the transcription * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v3'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Generates a transcript. */ doGenerate(options: TranscriptionModelV3CallOptions): PromiseLike<{ /** * The complete transcribed text from the audio. */ text: string; /** * Array of transcript segments with timing information. * Each segment represents a portion of the transcribed text with start and end times. */ segments: Array<{ /** * The text content of this segment. */ text: string; /** * The start time of this segment in seconds. */ startSecond: number; /** * The end time of this segment in seconds. */ endSecond: number; }>; /** * The detected language of the audio content, as an ISO-639-1 code (e.g., 'en' for English). * May be undefined if the language couldn't be detected. */ language: string | undefined; /** * The total duration of the audio file in seconds. * May be undefined if the duration couldn't be determined. */ durationInSeconds: number | undefined; /** * Warnings for the call, e.g. unsupported settings. */ warnings: Array; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Raw request HTTP body that was sent to the provider API as a string (JSON should be stringified). * Non-HTTP(s) providers should not set this. */ body?: string; }; /** * Response information for telemetry and debugging purposes. */ response: { /** * 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?: SharedV3Headers$1; /** * Response body. */ body?: unknown; }; /** * 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. */ providerMetadata?: Record; }>; }; /** * Provider for language, text embedding, and image generation models. */ interface ProviderV3 { readonly specificationVersion: 'v3'; /** * Returns the language model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - 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): LanguageModelV3$1; /** * 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} modelId - The id of the model to return. * * @returns {LanguageModel} The language model associated with the id * * @throws {NoSuchModelError} If no such model exists. */ embeddingModel(modelId: string): EmbeddingModelV3; /** * 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} modelId - The id of the model to return. * * @returns {EmbeddingModel} The embedding model associated with the id * * @throws {NoSuchModelError} If no such model exists. * * @deprecated Use `embeddingModel` instead. */ textEmbeddingModel?(modelId: string): EmbeddingModelV3; /** * Returns the image model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {ImageModel} The image model associated with the id */ imageModel(modelId: string): ImageModelV3; /** * Returns the transcription model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {TranscriptionModel} The transcription model associated with the id */ transcriptionModel?(modelId: string): TranscriptionModelV3; /** * Returns the speech model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {SpeechModel} The speech model associated with the id */ speechModel?(modelId: string): SpeechModelV3; /** * Returns the reranking model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {RerankingModel} The reranking model associated with the id * * @throws {NoSuchModelError} If no such model exists. */ rerankingModel?(modelId: string): RerankingModelV3; } type SpeechModelV2ProviderOptions = Record>; type SpeechModelV2CallOptions = { /** * Text to convert to speech. */ text: string; /** * The voice to use for speech synthesis. * This is provider-specific and may be a voice ID, name, or other identifier. */ voice?: string; /** * The desired output format for the audio e.g. "mp3", "wav", etc. */ outputFormat?: string; /** * Instructions for the speech generation e.g. "Speak in a slow and steady tone". */ instructions?: string; /** * The speed of the speech generation. */ speed?: number; /** * The language for speech generation. This should be an ISO 639-1 language code (e.g. "en", "es", "fr") * or "auto" for automatic language detection. Provider support varies. */ language?: string; /** * 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": {} * } * ``` */ providerOptions?: SpeechModelV2ProviderOptions; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; }; /** * 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 SpeechModelV2CallWarning = { type: 'unsupported-setting'; setting: keyof SpeechModelV2CallOptions; details?: string; } | { type: 'other'; message: string; }; /** * Speech model specification version 2. */ type SpeechModelV2 = { /** * The speech model must specify which speech model interface * version it implements. This will allow us to evolve the speech * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v2'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Generates speech audio from text. */ doGenerate(options: SpeechModelV2CallOptions): PromiseLike<{ /** * Generated audio as an ArrayBuffer. * The audio should be returned without any unnecessary conversion. * If the API returns base64 encoded strings, the audio should be returned * as base64 encoded strings. If the API returns binary data, the audio * should be returned as binary data. */ audio: string | Uint8Array; /** * Warnings for the call, e.g. unsupported settings. */ warnings: Array; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Response body (available only for providers that use HTTP requests). */ body?: unknown; }; /** * Response information for telemetry and debugging purposes. */ response: { /** * 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?: SharedV2Headers$1; /** * Response body. */ body?: unknown; }; /** * 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. */ providerMetadata?: Record>; }>; }; type TranscriptionModelV2ProviderOptions = Record>; type TranscriptionModelV2CallOptions = { /** * Audio data to transcribe. * Accepts a `Uint8Array` or `string`, where `string` is a base64 encoded audio file. */ audio: Uint8Array | string; /** * The IANA media type of the audio data. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * 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": { * "timestampGranularities": ["word"] * } * } * ``` */ providerOptions?: TranscriptionModelV2ProviderOptions; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; }; /** * 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 TranscriptionModelV2CallWarning = { type: 'unsupported-setting'; setting: keyof TranscriptionModelV2CallOptions; details?: string; } | { type: 'other'; message: string; }; /** * Transcription model specification version 2. */ type TranscriptionModelV2 = { /** * The transcription model must specify which transcription model interface * version it implements. This will allow us to evolve the transcription * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v2'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Generates a transcript. */ doGenerate(options: TranscriptionModelV2CallOptions): PromiseLike<{ /** * The complete transcribed text from the audio. */ text: string; /** * Array of transcript segments with timing information. * Each segment represents a portion of the transcribed text with start and end times. */ segments: Array<{ /** * The text content of this segment. */ text: string; /** * The start time of this segment in seconds. */ startSecond: number; /** * The end time of this segment in seconds. */ endSecond: number; }>; /** * The detected language of the audio content, as an ISO-639-1 code (e.g., 'en' for English). * May be undefined if the language couldn't be detected. */ language: string | undefined; /** * The total duration of the audio file in seconds. * May be undefined if the duration couldn't be determined. */ durationInSeconds: number | undefined; /** * Warnings for the call, e.g. unsupported settings. */ warnings: Array; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Raw request HTTP body that was sent to the provider API as a string (JSON should be stringified). * Non-HTTP(s) providers should not set this. */ body?: string; }; /** * Response information for telemetry and debugging purposes. */ response: { /** * 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?: SharedV2Headers$1; /** * Response body. */ body?: unknown; }; /** * 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. */ providerMetadata?: Record>; }>; }; /** * Provider for language, text embedding, and image generation models. */ interface ProviderV2 { /** * Returns the language model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - 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): LanguageModelV2$1; /** * 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} modelId - 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): EmbeddingModelV2; /** * Returns the image model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {ImageModel} The image model associated with the id */ imageModel(modelId: string): ImageModelV2; /** * Returns the transcription model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {TranscriptionModel} The transcription model associated with the id */ transcriptionModel?(modelId: string): TranscriptionModelV2; /** * Returns the speech model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {SpeechModel} The speech model associated with the id */ speechModel?(modelId: string): SpeechModelV2; } /** * A tool definition for realtime models. Sent as part of the session * configuration so the model knows which functions it can call. */ type RealtimeModelV4ToolDefinition = { /** * The type of the tool (always 'function'). */ type: 'function'; /** * The name of the tool. Unique within the session. */ name: string; /** * A description of what the tool does. The model uses this to decide * whether to call the tool. */ description?: string; /** * JSON Schema describing the parameters the tool expects. */ parameters: JSONSchema7; }; /** * Provider-neutral configuration for a realtime session. * Each provider maps this to their specific session.update payload. */ type RealtimeModelV4SessionConfig = { /** * System instructions for the model. */ instructions?: string; /** * Voice to use for audio output. */ voice?: string; /** * Which output modalities the model should produce. */ outputModalities?: Array<'text' | 'audio'>; /** * Audio format configuration for input audio. */ inputAudioFormat?: SharedV4AudioFormat; /** * Input audio transcription configuration. * * When enabled, providers that support input transcription emit normalized * `input-transcription-completed` events that can be rendered as user * messages. */ inputAudioTranscription?: { /** * Provider-specific transcription model. */ model?: string; /** * Optional language hint for the input audio. */ language?: string; /** * Optional prompt to guide transcription. */ prompt?: string; }; /** * Output audio transcription configuration. * * When enabled, providers that support output transcription emit normalized * `audio-transcript-delta` / `audio-transcript-done` events for the model's * spoken response. Some providers transcribe output by default; setting this * makes the behavior explicit rather than relying on that default. */ outputAudioTranscription?: { /** * Provider-specific transcription model. */ model?: string; /** * Optional language hint for the output audio. */ language?: string; /** * Optional prompt to guide transcription. */ prompt?: string; }; /** * Audio format configuration for output audio. */ outputAudioFormat?: SharedV4AudioFormat; /** * Voice activity detection configuration. * Set to null or type 'disabled' to turn off VAD (push-to-talk mode). */ turnDetection?: { /** * VAD mode. 'server-vad' for automatic detection, * 'semantic-vad' for OpenAI's semantic detection, * 'disabled' to turn off VAD. */ type: 'server-vad' | 'semantic-vad' | 'disabled'; /** * VAD activation threshold (0.0-1.0). * Higher values require louder audio to trigger. */ threshold?: number; /** * How long the user must be silent (in ms) before * the server ends the turn. */ silenceDurationMs?: number; /** * Amount of audio (in ms) to include before the * detected start of speech. */ prefixPaddingMs?: number; } | null; /** * Tool definitions available to the model in this session. */ tools?: RealtimeModelV4ToolDefinition[]; /** * Provider-specific options that are passed through to the provider. */ providerOptions?: Record; }; /** * Options for creating an ephemeral client secret for browser-side * WebSocket connections to a realtime model. */ type RealtimeModelV4ClientSecretOptions = { /** * Number of seconds until the client secret expires. */ expiresAfterSeconds?: number; /** * Optional session configuration to embed in the token request. * Some providers (e.g. Google) require the full session config at token creation time. */ sessionConfig?: RealtimeModelV4SessionConfig; }; /** * Result of creating an ephemeral client secret. */ type RealtimeModelV4ClientSecretResult = { /** * The ephemeral token value. Used as a Bearer token or in the * WebSocket subprotocol header for authentication. */ token: string; /** * The WebSocket URL to connect to. Includes any provider-specific * query parameters (e.g. model ID). */ url: string; /** * Unix timestamp (seconds) when this client secret expires. */ expiresAt?: number; }; /** * A conversation item that can be created by the client and sent to * the model via the conversation.item.create event. */ type RealtimeModelV4ConversationItem = RealtimeModelV4TextMessage | RealtimeModelV4AudioMessage | RealtimeModelV4FunctionCallOutput; /** * A text message from the user. */ type RealtimeModelV4TextMessage = { type: 'text-message'; role: 'user'; text: string; }; /** * An audio message from the user (complete audio, not streamed). */ type RealtimeModelV4AudioMessage = { type: 'audio-message'; role: 'user'; /** * Base64-encoded audio data. */ audio: string; }; /** * The output of a function call, sent back to the model so it can * continue generating a response using the tool result. */ type RealtimeModelV4FunctionCallOutput = { type: 'function-call-output'; /** * The call ID from the function-call-arguments-done event. * Must match so the model knows which function call this result is for. */ callId: string; /** * The name of the function that was called. * Required by some providers (e.g. Google) in the tool response routing. */ name?: string; /** * JSON string containing the function call result. */ output: string; }; /** * Normalized events sent from the browser to the realtime model. * Each provider maps this to its native event format before sending * over the WebSocket. */ type RealtimeModelV4ClientEvent = { type: 'session-update'; config: RealtimeModelV4SessionConfig; } | { type: 'input-audio-append'; /** * Base64-encoded audio chunk to append to the input buffer. */ audio: string; } | { type: 'input-audio-commit'; } | { type: 'input-audio-clear'; } | { type: 'conversation-item-create'; item: RealtimeModelV4ConversationItem; } | { type: 'conversation-item-truncate'; /** * The ID of the assistant message item to truncate. */ itemId: string; /** * The index of the content part to truncate. */ contentIndex: number; /** * Truncate audio after this many milliseconds. */ audioEndMs: number; } | { type: 'response-create'; options?: { modalities?: string[]; instructions?: string; metadata?: Record; }; } | { type: 'response-cancel'; }; /** * Normalized events emitted by the realtime model (model → browser). * Each provider maps its native event format to this discriminated union. * * Every event includes a `raw` field with the original provider-specific * event data for debugging and provider-specific access. */ type RealtimeModelV4ServerEvent = { type: 'session-created'; sessionId?: string; raw: unknown; } | { type: 'session-updated'; raw: unknown; } | { type: 'speech-started'; itemId?: string; raw: unknown; } | { type: 'speech-stopped'; itemId?: string; raw: unknown; } | { type: 'audio-committed'; itemId?: string; previousItemId?: string; raw: unknown; } | { type: 'conversation-item-added'; itemId: string; item: unknown; raw: unknown; } | { type: 'input-transcription-completed'; itemId: string; transcript: string; raw: unknown; } | { type: 'response-created'; responseId: string; raw: unknown; } | { type: 'response-done'; responseId: string; status: string; raw: unknown; } | { type: 'output-item-added'; responseId: string; itemId: string; raw: unknown; } | { type: 'output-item-done'; responseId: string; itemId: string; raw: unknown; } | { type: 'content-part-added'; responseId: string; itemId: string; raw: unknown; } | { type: 'content-part-done'; responseId: string; itemId: string; raw: unknown; } | { type: 'audio-delta'; responseId: string; itemId: string; /** * Base64-encoded audio chunk. */ delta: string; raw: unknown; } | { type: 'audio-done'; responseId: string; itemId: string; raw: unknown; } | { type: 'audio-transcript-delta'; responseId: string; itemId: string; /** * Text chunk of the audio transcript. */ delta: string; raw: unknown; } | { type: 'audio-transcript-done'; responseId: string; itemId: string; transcript?: string; raw: unknown; } | { type: 'text-delta'; responseId: string; itemId: string; /** * Text chunk of the model's text response. */ delta: string; raw: unknown; } | { type: 'text-done'; responseId: string; itemId: string; text?: string; raw: unknown; } | { type: 'function-call-arguments-delta'; responseId: string; itemId: string; callId: string; /** * Partial JSON string of function call arguments. */ delta: string; raw: unknown; } | { type: 'function-call-arguments-done'; responseId: string; itemId: string; callId: string; /** * The name of the function to call. */ name: string; /** * Complete JSON string of function call arguments. */ arguments: string; raw: unknown; } | { type: 'error'; message: string; code?: string; raw: unknown; } | { type: 'custom'; /** * The original event type string from the provider. */ rawType: string; raw: unknown; }; /** * Specification for a realtime model that supports bidirectional * audio/text communication over WebSocket. * * Providers implement this interface to enable realtime voice * conversations through the AI SDK. */ type RealtimeModelV4 = { /** * The realtime model must specify which interface version it implements. */ readonly specificationVersion: 'v4'; /** * Provider ID (e.g. 'openai', 'xai'). */ readonly provider: string; /** * Provider-specific model ID (e.g. 'gpt-4o-realtime', 'grok-3'). */ readonly modelId: string; /** * Server-side: Creates an ephemeral client secret for authenticating * browser-side WebSocket connections. The secret is short-lived and * safe to expose to client code. * * Naming: "do" prefix to prevent accidental direct usage by the user. */ doCreateClientSecret(options: RealtimeModelV4ClientSecretOptions): PromiseLike; /** * Browser-side: Returns the WebSocket URL and subprotocols to use * when connecting. Each provider has its own authentication mechanism * (e.g. OpenAI uses subprotocol headers, xAI may use query params). */ getWebSocketConfig(options: { token: string; url: string; }): { url: string; protocols?: string[]; }; /** * Browser-side: Parses a raw JSON event received over the WebSocket * and returns one or more normalized events. Providers map their native * event format to the common RealtimeModelV4ServerEvent union. * * Returns an array when a single provider message maps to multiple * normalized events (e.g. Google's serverContent can contain audio, * text, and turn-complete data in one message). */ parseServerEvent(raw: unknown): RealtimeModelV4ServerEvent | RealtimeModelV4ServerEvent[]; /** * Browser-side: Serializes a normalized client event into the * provider's native JSON format for sending over the WebSocket. */ serializeClientEvent(event: RealtimeModelV4ClientEvent): unknown | PromiseLike; /** * Browser-side: Builds the provider-specific session configuration * payload from a normalized session config. Used to construct the * session.update event sent after WebSocket connection. */ buildSessionConfig(config: RealtimeModelV4SessionConfig): unknown; /** * Browser-side: Returns a message to auto-send back over the WebSocket * in response to a raw incoming message, or null if no response is needed. * * Used for provider-specific keepalive protocols (e.g. ping/pong). * Called by the session layer before parseServerEvent. */ getHealthCheckResponse?(raw: unknown): unknown | null; }; type RealtimeFactoryV4GetTokenOptions = { model: string; } & RealtimeModelV4ClientSecretOptions; type RealtimeFactoryV4GetTokenResult = { token: string; url: string; expiresAt?: number; }; interface RealtimeFactoryV4 { (modelId: string): RealtimeModelV4; getToken(options: RealtimeFactoryV4GetTokenOptions): Promise; } type SpeechTranslationModelV4ProviderOptions = Record; /** * Options for a speech translation model stream call. */ type SpeechTranslationModelV4StreamOptions = { /** * Source audio chunks to transform. * * `Uint8Array` chunks contain raw audio bytes. `string` chunks contain * base64-encoded raw audio bytes. */ audio: ReadableStream; /** * The input audio format for the raw audio chunks. */ inputAudioFormat: SharedV4AudioFormat; /** * The language to produce output audio and text in, as a BCP-47-style * language tag (e.g. `en`, `es`, `fr-CA`). Supported values are * provider-specific and validated by the provider. */ targetLanguage: string; /** * The language of the source audio, as a BCP-47-style language tag. * When absent, providers should auto-detect the source language. */ sourceLanguage?: string; /** * The desired audio format for output audio chunks. * When absent, the provider default output format is used. */ outputAudioFormat?: SharedV4AudioFormat; /** * Additional provider-specific options that are passed through to the provider. * * The outer record is keyed by the provider name, and the inner record is keyed * by provider-specific option names. */ providerOptions?: SpeechTranslationModelV4ProviderOptions; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP/WebSocket-based providers that support headers. */ headers?: Record; /** * When true, providers should include raw provider chunks in the stream. */ includeRawChunks?: boolean; }; /** * Usage information for a speech translation call. * * All fields are optional because providers report usage with different * granularity (seconds of audio, audio tokens, and/or text tokens). */ type SpeechTranslationModelV4Usage = { /** * Seconds of input audio that were processed, if reported. */ inputAudioSeconds?: number; /** * Number of input audio tokens, if reported. */ inputAudioTokens?: number; /** * Number of output audio tokens, if reported. */ outputAudioTokens?: number; /** * Number of input text tokens, if reported. */ inputTextTokens?: number; /** * Number of output text tokens, if reported. */ outputTextTokens?: number; }; type SpeechTranslationModelV4StreamPart = { /** * Stream start event with warnings for the call, e.g. unsupported settings. */ type: 'stream-start'; warnings: Array; } | { /** * Output audio chunk. * * `Uint8Array` chunks contain raw audio bytes. `string` chunks contain * base64-encoded raw audio bytes. */ type: 'audio'; id?: string; audio: Uint8Array | string; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Append-only output text delta. * * Output text is append-only: providers stream `output-text-delta` * parts and finalize per-utterance with `output-text-final`. There is * no partial/revision part for output text by design for now. */ type: 'output-text-delta'; id?: string; delta: string; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Final output text for a provider-defined segment or utterance. * * Output text is append-only: providers stream `output-text-delta` * parts and finalize per-utterance with `output-text-final`. There is * no partial/revision part for output text by design for now. */ type: 'output-text-final'; id?: string; text: string; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Append-only source transcript delta. */ type: 'source-transcript-delta'; id?: string; delta: string; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Non-final source transcript text. The text may be revised by later parts. */ type: 'source-transcript-partial'; id?: string; text: string; startSecond?: number; endSecond?: number; channelIndex?: number; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Final source transcript text for a provider-defined segment or utterance. */ type: 'source-transcript-final'; id?: string; text: string; startSecond?: number; endSecond?: number; channelIndex?: number; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Metadata for the response, emitted once available. */ type: 'response-metadata'; timestamp?: Date; modelId?: string; headers?: SharedV4Headers; body?: unknown; } | { /** * Metadata that is available after the stream is finished. */ type: 'finish'; /** * The final source-language transcript of the input audio. */ sourceText: string; /** * The final output text. May be an empty string for providers that * produce only audio output. */ outputText: string; /** * The duration of the source audio in seconds, if available. */ durationInSeconds?: number; /** * Usage information for the call, if reported by the provider. */ usage?: SpeechTranslationModelV4Usage; /** * Additional provider-specific metadata. */ providerMetadata?: Record; } | { /** * Raw provider chunks if enabled. */ type: 'raw'; rawValue: unknown; } | { /** * Error parts are streamed, allowing for multiple errors. */ type: 'error'; error: unknown; }; /** * The result of a speech translation model doStream call. */ type SpeechTranslationModelV4StreamResult = { /** * The stream. */ stream: ReadableStream; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Request body or setup payload that was sent to the provider API. */ body?: unknown; }; /** * Optional response data. */ response?: { /** * Timestamp for the start of the streamed response. */ timestamp?: Date; /** * The ID of the response model that was used to generate the response. */ modelId?: string; /** * Response headers. */ headers?: SharedV4Headers; /** * Response body. */ body?: unknown; }; }; /** * Speech translation model specification version 4. * * Speech translation is a streaming-only modality: models translate live * source audio into target-language audio and text. * * Experimental: the speech translation model contract may change in patch * releases while the functions built on it are experimental. All types of * this modality are exported with `Experimental_` prefixes for this reason. */ type SpeechTranslationModelV4 = { /** * The speech translation model must specify which speech translation model * interface version it implements. This will allow us to evolve the * speech translation model interface and retain backwards compatibility. * The different implementation versions can be handled as a discriminated * union on our side. */ readonly specificationVersion: 'v4'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Streams a speech translation for live audio. */ doStream(options: SpeechTranslationModelV4StreamOptions): PromiseLike; }; /** * A video or image file that can be used for video editing or image-to-video generation. * Supports both image inputs (for image-to-video) and video inputs (for editing). */ type VideoModelV4File = { type: 'file'; /** * The IANA media type of the file. * Video types: 'video/mp4', 'video/webm', 'video/quicktime' * Image types: 'image/png', 'image/jpeg', 'image/webp' */ mediaType: string; /** * File data as base64 encoded string or binary data. */ data: string | Uint8Array; /** * Optional provider-specific metadata for the file part. */ providerOptions?: SharedV4ProviderMetadata; } | { type: 'url'; /** * The URL of the video or image file. */ url: string; /** * The media type of the referenced file, when known. * Video types: 'video/mp4', 'video/webm', 'video/quicktime' * Image types: 'image/png', 'image/jpeg', 'image/webp' */ mediaType?: string; /** * Optional provider-specific metadata for the file part. */ providerOptions?: SharedV4ProviderMetadata; }; /** * The role a frame image plays in video generation. * * - `first_frame`: the starting frame the model animates from * - `last_frame`: the ending frame the model animates towards */ type VideoModelV4FrameType = 'first_frame' | 'last_frame'; /** * A role-tagged image input for image-to-video and first-last-frame generation. */ type VideoModelV4FrameImage = { /** * The image file used for this frame. */ image: VideoModelV4File; /** * Which frame this image represents. */ frameType: VideoModelV4FrameType; }; type VideoModelV4CallOptions = { /** * Text prompt for the video generation. */ prompt: string | undefined; /** * Number of videos to generate. Default: 1. * Most video models only support n=1 due to computational cost. */ n: number; /** * Aspect ratio of the videos to generate. * Must have the format `{width}:{height}`, or `'adaptive'` to inherit the * ratio from the input media. * `undefined` will use the provider's default aspect ratio. * Common values: '16:9', '9:16', '1:1', '21:9', '4:3' */ aspectRatio: `${number}:${number}` | 'adaptive' | undefined; /** * Resolution of the video to generate. * Format: `{width}x{height}` (e.g., '1280x720', '1920x1080') * `undefined` will use the provider's default resolution. */ resolution: `${number}x${number}` | undefined; /** * Duration of the video in seconds. * `undefined` will use the provider's default duration. * Typically 3-10 seconds for most models. */ duration: number | undefined; /** * Frames per second (FPS) for the video. * `undefined` will use the provider's default FPS. * Common values: 24, 30, 60 */ fps: number | undefined; /** * Seed for deterministic video generation. * `undefined` will use a random seed. */ seed: number | undefined; /** * Input image for image-to-video generation. * The image serves as the starting frame that the model will animate. */ image: VideoModelV4File | undefined; /** * Role-tagged image inputs for first-last-frame generation. * Each entry declares whether it is the `first_frame` or the * `last_frame` of the generated video. */ frameImages: Array | undefined; /** * Reference inputs for reference-to-video generation. * * Each entry is an image or video file. Providers route each reference by * its media type (image vs. video) and warn when a reference kind is * unsupported. */ inputReferences: Array | undefined; /** * Whether the model should generate audio alongside the video. */ generateAudio: boolean | undefined; /** * Additional provider-specific options that are passed through to the provider * as body parameters. * * Example: * { * "fal": { * "loop": true, * "motionStrength": 0.8 * } * } */ providerOptions: SharedV4ProviderOptions; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; }; /** * Generated video data. Can be a URL, base64-encoded string, or binary data. */ type VideoModelV4VideoData = { /** * Video available as a URL (most common for video providers). */ type: 'url'; url: string; mediaType: string; } | { /** * Video as base64-encoded string. */ type: 'base64'; data: string; mediaType: string; } | { /** * Video as binary data. */ type: 'binary'; data: Uint8Array; mediaType: string; }; /** * The result of a video model doGenerate call. */ type VideoModelV4Result = { /** * Generated videos as URLs, base64 strings, or binary data. * * Most providers return URLs to video files (MP4, WebM) due to large file sizes. * Use the discriminated union to indicate the type of video data being returned. */ videos: Array; /** * Warnings for the call, e.g. unsupported features. */ warnings: Array; /** * 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. * * The outer record is keyed by the provider name, and the inner * record is provider-specific metadata. * * ```ts * { * "fal": { * "videos": [{ * "duration": 5.0, * "fps": 24, * "width": 1280, * "height": 720 * }] * } * } * ``` */ providerMetadata?: SharedV4ProviderMetadata; /** * Response information for telemetry and debugging purposes. */ response: { /** * 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 | undefined; }; }; /** * Result returned by `doStart` when initiating an asynchronous video generation. */ type VideoModelV4OperationStartResult = { /** * JSON-serializable opaque reference passed to `doStatus` to check the * status of the generation (e.g., a task ID or prediction URL). */ operation: JSONValue$3; /** * Warnings for the call, e.g. unsupported features. */ warnings: Array; /** * Additional provider-specific metadata. */ providerMetadata?: SharedV4ProviderMetadata; /** * Response information for telemetry and debugging purposes. */ response: { /** * Timestamp for the start of the response. */ timestamp: Date; /** * The ID of the response model that was used. */ modelId: string; /** * Response headers. */ headers: Record | undefined; }; }; /** * Result returned by `doStatus` when checking the status of an * asynchronous video generation. */ type VideoModelV4OperationStatusResult = { /** * The video generation is still in progress. */ status: 'pending'; /** * Warnings for the call. */ warnings?: Array; /** * Additional provider-specific metadata. */ providerMetadata?: SharedV4ProviderMetadata; /** * Response information for telemetry and debugging purposes. */ response: { timestamp: Date; modelId: string; headers: Record | undefined; }; } | { /** * The video generation is complete. */ status: 'completed'; /** * Generated videos. */ videos: Array; /** * Warnings for the call. */ warnings: Array; /** * Additional provider-specific metadata. */ providerMetadata?: SharedV4ProviderMetadata; /** * Response information for telemetry and debugging purposes. */ response: { timestamp: Date; modelId: string; headers: Record | undefined; }; } | { /** * The video generation failed. */ status: 'error'; /** * A human-readable error message describing why the generation failed. */ error: string; /** * Additional provider-specific metadata. */ providerMetadata?: SharedV4ProviderMetadata; /** * Response information for telemetry and debugging purposes. */ response: { timestamp: Date; modelId: string; headers: Record | undefined; }; }; /** * Data received from a webhook notification during asynchronous video * generation. Generic over the body type so providers/consumers can * narrow it to a specific shape. */ type VideoModelV4OperationWebhook = { headers: Record; body: TBody; }; type GetMaxVideosPerCallFunction$1 = (options: { modelId: string; }) => PromiseLike | number | undefined; /** * Video generation model specification version 4. */ type VideoModelV4 = { /** * The video model must specify which video model interface * version it implements. This will allow us to evolve the video * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v4'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Limit of how many videos can be generated in a single API call. * Can be set to a number for a fixed limit, to undefined to use * the global limit, or a function that returns a number or undefined, * optionally as a promise. * * Most video models only support generating 1 video at a time due to * computational cost. Default is typically 1. */ readonly maxVideosPerCall: number | undefined | GetMaxVideosPerCallFunction$1; /** * Generates an array of videos. * * Optional when `doStart` and `doStatus` are provided to support * the asynchronous start/status flow. */ doGenerate?(options: VideoModelV4CallOptions): PromiseLike; /** * Optional method that handles the user's `webhook` option for the * asynchronous start/status flow. * * Its presence on the model signals that the provider's API natively * supports webhooks. The SDK checks for this method before invoking the * user-provided `webhook` factory: * * - **Present**: The SDK calls this method with the user's webhook factory. * The implementation should invoke the factory to obtain a webhook URL * and a `received` promise. The URL is then forwarded to `doStart` via * `webhookUrl`, and the SDK awaits `received` instead of polling. * * - **Absent**: The SDK never calls the user's `webhook` factory and falls * back to polling via `doStatus`. This avoids unnecessary webhook * endpoint creation for providers whose APIs have no native webhook * mechanism. * * This method exists because the SDK must decide whether to invoke the * user's webhook factory — which may create real HTTP endpoints or * external resources — *before* calling `doStart`. Without an explicit * capability signal on the model, the SDK would eagerly create a webhook * endpoint for every provider, even those that silently ignore the URL. */ handleWebhookOption?: (options: { webhook: () => PromiseLike<{ url: string; received: PromiseLike; }>; }) => PromiseLike<{ webhookUrl: string; received: PromiseLike; }>; /** * Starts an asynchronous video generation and returns an opaque operation * reference that can be passed to `doStatus` to poll for completion. * * When both `doStart` and `doStatus` are implemented, the SDK core can * orchestrate polling or webhook-based completion instead of requiring * the provider to implement its own polling loop in `doGenerate`. */ doStart?(options: VideoModelV4CallOptions & { /** * When provided, the provider should register this URL to receive * a webhook notification when the video generation completes. */ webhookUrl?: string; }): PromiseLike; /** * Checks the status of an asynchronous video generation that was * started with `doStart`. * * Returns either a `pending` status or a `completed` status with the * generated videos. */ doStatus?(options: { /** * The JSON-serializable opaque operation reference returned by `doStart`. */ operation: JSONValue$3; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers. */ headers?: Record; }): PromiseLike; }; /** * A video or image file that can be used for video editing or image-to-video generation. * Supports both image inputs (for image-to-video) and video inputs (for editing). */ type VideoModelV3File = { type: 'file'; /** * The IANA media type of the file. * Video types: 'video/mp4', 'video/webm', 'video/quicktime' * Image types: 'image/png', 'image/jpeg', 'image/webp' */ mediaType: string; /** * File data as base64 encoded string or binary data. */ data: string | Uint8Array; /** * Optional provider-specific metadata for the file part. */ providerOptions?: SharedV3ProviderMetadata$1; } | { type: 'url'; /** * The URL of the video or image file. */ url: string; /** * Optional provider-specific metadata for the file part. */ providerOptions?: SharedV3ProviderMetadata$1; }; /** * The role a frame image plays in video generation. * * - `first_frame`: the starting frame the model animates from * - `last_frame`: the ending frame the model animates towards */ type VideoModelV3FrameType = 'first_frame' | 'last_frame'; /** * A role-tagged image input for image-to-video and first-last-frame generation. */ type VideoModelV3FrameImage = { /** * The image file used for this frame. */ image: VideoModelV3File; /** * Which frame this image represents. */ frameType: VideoModelV3FrameType; }; type VideoModelV3CallOptions = { /** * Text prompt for the video generation. */ prompt: string | undefined; /** * Number of videos to generate. Default: 1. * Most video models only support n=1 due to computational cost. */ n: number; /** * Aspect ratio of the videos to generate. * Must have the format `{width}:{height}`, or `'adaptive'` to inherit the * ratio from the input media. * `undefined` will use the provider's default aspect ratio. * Common values: '16:9', '9:16', '1:1', '21:9', '4:3' */ aspectRatio: `${number}:${number}` | 'adaptive' | undefined; /** * Resolution of the video to generate. * Format: `{width}x{height}` (e.g., '1280x720', '1920x1080') * `undefined` will use the provider's default resolution. */ resolution: `${number}x${number}` | undefined; /** * Duration of the video in seconds. * `undefined` will use the provider's default duration. * Typically 3-10 seconds for most models. */ duration: number | undefined; /** * Frames per second (FPS) for the video. * `undefined` will use the provider's default FPS. * Common values: 24, 30, 60 */ fps: number | undefined; /** * Seed for deterministic video generation. * `undefined` will use a random seed. */ seed: number | undefined; /** * Input image for image-to-video generation. * The image serves as the starting frame that the model will animate. */ image: VideoModelV3File | undefined; /** * Role-tagged image inputs for first-last-frame generation. * Each entry declares whether it is the `first_frame` or the * `last_frame` of the generated video. */ frameImages: Array | undefined; /** * Reference inputs for reference-to-video generation. * * Each entry is an image or video file. Providers route each reference by * its media type (image vs. video) and warn when a reference kind is * unsupported. */ inputReferences: Array | undefined; /** * Whether the model should generate audio alongside the video. */ generateAudio: boolean | undefined; /** * Additional provider-specific options that are passed through to the provider * as body parameters. * * Example: * { * "fal": { * "loop": true, * "motionStrength": 0.8 * } * } */ providerOptions: SharedV3ProviderOptions$1; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; }; type GetMaxVideosPerCallFunction = (options: { modelId: string; }) => PromiseLike | number | undefined; /** * Generated video data. Can be a URL, base64-encoded string, or binary data. */ type VideoModelV3VideoData = { /** * Video available as a URL (most common for video providers). */ type: 'url'; url: string; mediaType: string; } | { /** * Video as base64-encoded string. */ type: 'base64'; data: string; mediaType: string; } | { /** * Video as binary data. */ type: 'binary'; data: Uint8Array; mediaType: string; }; /** * Video generation model specification version 3. */ type VideoModelV3 = { /** * The video model must specify which video model interface * version it implements. This will allow us to evolve the video * model interface and retain backwards compatibility. The different * implementation versions can be handled as a discriminated union * on our side. */ readonly specificationVersion: 'v3'; /** * Name of the provider for logging purposes. */ readonly provider: string; /** * Provider-specific model ID for logging purposes. */ readonly modelId: string; /** * Limit of how many videos can be generated in a single API call. * Can be set to a number for a fixed limit, to undefined to use * the global limit, or a function that returns a number or undefined, * optionally as a promise. * * Most video models only support generating 1 video at a time due to * computational cost. Default is typically 1. */ readonly maxVideosPerCall: number | undefined | GetMaxVideosPerCallFunction; /** * Generates an array of videos. */ doGenerate(options: VideoModelV3CallOptions): PromiseLike<{ /** * Generated videos as URLs, base64 strings, or binary data. * * Most providers return URLs to video files (MP4, WebM) due to large file sizes. * Use the discriminated union to indicate the type of video data being returned. */ videos: Array; /** * Warnings for the call, e.g. unsupported features. */ warnings: Array; /** * 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. * * The outer record is keyed by the provider name, and the inner * record is provider-specific metadata. * * ```ts * { * "fal": { * "videos": [{ * "duration": 5.0, * "fps": 24, * "width": 1280, * "height": 720 * }] * } * } * ``` */ providerMetadata?: SharedV3ProviderMetadata$1; /** * Response information for telemetry and debugging purposes. */ response: { /** * 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 | undefined; }; }>; }; //#endregion //#region ../../node_modules/.pnpm/@ai-sdk+provider@2.0.3/node_modules/@ai-sdk/provider/dist/index.d.ts type SharedV2Headers = Record; /** A JSON value can be a string, number, boolean, object, array, or null. JSON values can be serialized and deserialized by the JSON.stringify and JSON.parse methods. */ type JSONValue$2 = null | string | number | boolean | JSONObject$1 | JSONArray$1; type JSONObject$1 = { [key: string]: JSONValue$2; }; type JSONArray$1 = JSONValue$2[]; /** * Additional provider-specific metadata. * Metadata are additional outputs from the provider. * They are passed through to the provider from the AI SDK * and enable provider-specific functionality * that can be fully encapsulated in the provider. * * This enables us to quickly ship provider-specific functionality * without affecting the core AI SDK. * * The outer record is keyed by the provider name, and the inner * record is keyed by the provider-specific metadata key. * * ```ts * { * "anthropic": { * "cacheControl": { "type": "ephemeral" } * } * } * ``` */ type SharedV2ProviderMetadata = Record>; /** * Additional provider-specific options. * Options are additional input to the provider. * They are passed through to the provider from the AI SDK * and enable provider-specific functionality * that can be fully encapsulated in the provider. * * This enables us to quickly ship provider-specific functionality * without affecting the core AI SDK. * * The outer record is keyed by the provider name, and the inner * record is keyed by the provider-specific metadata key. * * ```ts * { * "anthropic": { * "cacheControl": { "type": "ephemeral" } * } * } * ``` */ type SharedV2ProviderOptions = Record>; /** An embedding is a vector, i.e. an array of numbers. It is e.g. used to represent a text as a vector of word embeddings. */ /** A tool has a name, a description, and a set of parameters. Note: this is **not** the user-facing tool definition. The AI SDK methods will map the user-facing tool definitions to this format. */ type LanguageModelV2FunctionTool = { /** The type of the tool (always 'function'). */ type: 'function'; /** The name of the tool. Unique within this model call. */ name: string; /** A description of the tool. The language model uses this to understand the tool's purpose and to provide better completion suggestions. */ description?: string; /** The parameters that the tool expects. The language model uses this to understand the tool's input requirements and to provide matching suggestions. */ inputSchema: JSONSchema7; /** The provider-specific options for the tool. */ providerOptions?: SharedV2ProviderOptions; }; /** Data content. Can be a Uint8Array, base64 encoded data as a string or a URL. */ type LanguageModelV2DataContent = Uint8Array | string | URL; /** A prompt is a list of messages. Note: Not all models and prompt formats support multi-modal inputs and tool calls. The validation happens at runtime. Note: This is not a user-facing prompt. The AI SDK methods will map the user-facing prompt types such as chat or instruction prompts to this format. */ type LanguageModelV2Prompt = Array; type LanguageModelV2Message = ({ role: 'system'; content: string; } | { role: 'user'; content: Array; } | { role: 'assistant'; content: Array; } | { role: 'tool'; content: Array; }) & { /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions; }; /** Text content part of a prompt. It contains a string of text. */ interface LanguageModelV2TextPart { type: 'text'; /** The text content. */ text: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions; } /** Reasoning content part of a prompt. It contains a string of reasoning text. */ interface LanguageModelV2ReasoningPart { type: 'reasoning'; /** The reasoning text. */ text: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions; } /** File content part of a prompt. It contains a file. */ interface LanguageModelV2FilePart { type: 'file'; /** * Optional filename of the file. */ filename?: string; /** File data. Can be a Uint8Array, base64 encoded data as a string or a URL. */ data: LanguageModelV2DataContent; /** IANA media type of the file. Can support wildcards, e.g. `image/*` (in which case the provider needs to take appropriate action). @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions; } /** Tool call content part of a prompt. It contains a tool call (usually generated by the AI model). */ interface LanguageModelV2ToolCallPart { 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. */ input: unknown; /** * Whether the tool call will be executed by the provider. * If this flag is not set or is false, the tool call will be executed by the client. */ providerExecuted?: boolean; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions; } /** Tool result content part of a prompt. It contains the result of the tool call with the matching ID. */ interface LanguageModelV2ToolResultPart { 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. */ output: LanguageModelV2ToolResultOutput; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions; } type LanguageModelV2ToolResultOutput = { type: 'text'; value: string; } | { type: 'json'; value: JSONValue$2; } | { type: 'error-text'; value: string; } | { type: 'error-json'; value: JSONValue$2; } | { type: 'content'; value: Array<{ type: 'text'; /** Text content. */ text: string; } | { type: 'media'; /** Base-64 encoded media data. */ data: string; /** IANA media type. @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; }>; }; /** The configuration of a tool that is defined by the provider. */ type LanguageModelV2ProviderDefinedTool = { /** The type of the tool (always 'provider-defined'). */ type: 'provider-defined'; /** The ID of the tool. Should follow the format `.`. */ id: `${string}.${string}`; /** The name of the tool that the user must use in the tool set. */ name: string; /** The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool. */ args: Record; }; type LanguageModelV2ToolChoice = { type: 'auto'; } | { type: 'none'; } | { type: 'required'; } | { type: 'tool'; toolName: string; }; type LanguageModelV2CallOptions = { /** A language mode prompt is a standardized prompt type. Note: This is **not** the user-facing prompt. The AI SDK methods will map the user-facing prompt types such as chat or instruction prompts to this format. That approach allows us to evolve the user facing prompts without breaking the language model interface. */ prompt: LanguageModelV2Prompt; /** Maximum number of tokens to generate. */ maxOutputTokens?: number; /** Temperature setting. The range depends on the provider and model. */ temperature?: 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[]; /** Nucleus sampling. */ 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. */ presencePenalty?: number; /** Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases. */ frequencyPenalty?: number; /** Response format. The output can either be text or JSON. Default is text. If JSON is selected, a schema can optionally be provided to guide the LLM. */ responseFormat?: { type: 'text'; } | { type: 'json'; /** * JSON schema that the generated output should conform to. */ schema?: JSONSchema7; /** * Name of output that should be generated. Used by some providers for additional LLM guidance. */ name?: string; /** * Description of the output that should be generated. Used by some providers for additional LLM guidance. */ description?: string; }; /** The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results. */ seed?: number; /** The tools that are available for the model. */ tools?: Array; /** Specifies how the tool should be selected. Defaults to 'auto'. */ toolChoice?: LanguageModelV2ToolChoice; /** Include raw chunks in the stream. Only applicable for streaming calls. */ includeRawChunks?: boolean; /** Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. */ headers?: Record; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV2ProviderOptions; }; /** 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 LanguageModelV2CallWarning = { type: 'unsupported-setting'; setting: Omit; details?: string; } | { type: 'unsupported-tool'; tool: LanguageModelV2FunctionTool | LanguageModelV2ProviderDefinedTool; details?: string; } | { type: 'other'; message: string; }; /** A file that has been generated by the model. Generated files as base64 encoded strings or binary data. The files should be returned without any unnecessary conversion. */ type LanguageModelV2File = { type: 'file'; /** The IANA media type of the file, e.g. `image/png` or `audio/mp3`. @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** Generated file data as base64 encoded strings or binary data. The file data should be returned without any unnecessary conversion. If the API returns base64 encoded strings, the file data should be returned as base64 encoded strings. If the API returns binary data, the file data should be returned as binary data. */ data: string | Uint8Array; }; /** Reasoning that the model has generated. */ type LanguageModelV2Reasoning = { type: 'reasoning'; text: string; /** * Optional provider-specific metadata for the reasoning part. */ providerMetadata?: SharedV2ProviderMetadata; }; /** A source that has been used as input to generate the response. */ type LanguageModelV2Source = { type: 'source'; /** * The type of source - URL sources reference web content. */ sourceType: 'url'; /** * The ID of the source. */ id: string; /** * The URL of the source. */ url: string; /** * The title of the source. */ title?: string; /** * Additional provider metadata for the source. */ providerMetadata?: SharedV2ProviderMetadata; } | { type: 'source'; /** * The type of source - document sources reference files/documents. */ sourceType: 'document'; /** * The ID of the source. */ id: string; /** * IANA media type of the document (e.g., 'application/pdf'). */ mediaType: string; /** * The title of the document. */ title: string; /** * Optional filename of the document. */ filename?: string; /** * Additional provider metadata for the source. */ providerMetadata?: SharedV2ProviderMetadata; }; /** Text that the model has generated. */ type LanguageModelV2Text = { type: 'text'; /** The text content. */ text: string; providerMetadata?: SharedV2ProviderMetadata; }; /** * Tool calls that the model has generated. */ type LanguageModelV2ToolCall = { type: 'tool-call'; /** * The identifier of the tool call. It must be unique across all tool calls. */ toolCallId: string; /** * The name of the tool that should be called. */ toolName: string; /** * Stringified JSON object with the tool call arguments. Must match the * parameters schema of the tool. */ input: string; /** * Whether the tool call will be executed by the provider. * If this flag is not set or is false, the tool call will be executed by the client. */ providerExecuted?: boolean; /** * Additional provider-specific metadata for the tool call. */ providerMetadata?: SharedV2ProviderMetadata; }; /** Result of a tool call that has been executed by the provider. */ type LanguageModelV2ToolResult = { type: 'tool-result'; /** * The 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; /** * Optional flag if the result is an error or an error message. */ isError?: boolean; /** * Whether the tool result was generated by the provider. * If this flag is set to true, the tool result was generated by the provider. * If this flag is not set or is false, the tool result was generated by the client. */ providerExecuted?: boolean; /** * Additional provider-specific metadata for the tool result. */ providerMetadata?: SharedV2ProviderMetadata; }; type LanguageModelV2Content = LanguageModelV2Text | LanguageModelV2Reasoning | LanguageModelV2File | LanguageModelV2Source | LanguageModelV2ToolCall | LanguageModelV2ToolResult; /** 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 - `unknown`: the model has not transmitted a finish reason */ type LanguageModelV2FinishReason = 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'; interface LanguageModelV2ResponseMetadata { /** ID for the generated response, if the provider sends one. */ id?: string; /** Timestamp for the start of the generated response, if the provider sends one. */ timestamp?: Date; /** The ID of the response model that was used to generate the response, if the provider sends one. */ modelId?: string; } /** Usage information for a language model call. If your API return additional usage information, you can add it to the provider metadata under your provider's key. */ type LanguageModelV2Usage = { /** The number of input (prompt) tokens used. */ inputTokens: number | undefined; /** The number of output (completion) tokens used. */ outputTokens: number | undefined; /** The total number of tokens as reported by the provider. This number might be different from the sum of `inputTokens` and `outputTokens` and e.g. include reasoning tokens or other overhead. */ totalTokens: number | undefined; /** The number of reasoning tokens used. */ reasoningTokens?: number | undefined; /** The number of cached input tokens. */ cachedInputTokens?: number | undefined; }; type LanguageModelV2StreamPart = { type: 'text-start'; providerMetadata?: SharedV2ProviderMetadata; id: string; } | { type: 'text-delta'; id: string; providerMetadata?: SharedV2ProviderMetadata; delta: string; } | { type: 'text-end'; providerMetadata?: SharedV2ProviderMetadata; id: string; } | { type: 'reasoning-start'; providerMetadata?: SharedV2ProviderMetadata; id: string; } | { type: 'reasoning-delta'; id: string; providerMetadata?: SharedV2ProviderMetadata; delta: string; } | { type: 'reasoning-end'; id: string; providerMetadata?: SharedV2ProviderMetadata; } | { type: 'tool-input-start'; id: string; toolName: string; providerMetadata?: SharedV2ProviderMetadata; providerExecuted?: boolean; } | { type: 'tool-input-delta'; id: string; delta: string; providerMetadata?: SharedV2ProviderMetadata; } | { type: 'tool-input-end'; id: string; providerMetadata?: SharedV2ProviderMetadata; } | LanguageModelV2ToolCall | LanguageModelV2ToolResult | LanguageModelV2File | LanguageModelV2Source | { type: 'stream-start'; warnings: Array; } | ({ type: 'response-metadata'; } & LanguageModelV2ResponseMetadata) | { type: 'finish'; usage: LanguageModelV2Usage; finishReason: LanguageModelV2FinishReason; providerMetadata?: SharedV2ProviderMetadata; } | { type: 'raw'; rawValue: unknown; } | { type: 'error'; error: unknown; }; /** Specification for a language model that implements the language model interface version 2. */ type LanguageModelV2 = { /** The language model must specify which language model interface version it implements. */ readonly specificationVersion: 'v2'; /** Name of the provider for logging purposes. */ readonly provider: string; /** Provider-specific model ID for logging purposes. */ readonly modelId: string; /** Supported URL patterns by media type for the provider. The keys are media type patterns or full media types (e.g. `*\/*` for everything, `audio/*`, `video/*`, or `application/pdf`). and the values are arrays of regular expressions that match the URL paths. The matching should be against lower-case URLs. Matched URLs are supported natively by the model and are not downloaded. @returns A map of supported URL patterns by media type (as a promise or a plain object). */ supportedUrls: PromiseLike> | Record; /** Generates a language model output (non-streaming). Naming: "do" prefix to prevent accidental direct usage of the method by the user. */ doGenerate(options: LanguageModelV2CallOptions): PromiseLike<{ /** Ordered content that the model has generated. */ content: Array; /** Finish reason. */ finishReason: LanguageModelV2FinishReason; /** Usage information. */ usage: LanguageModelV2Usage; /** 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. */ providerMetadata?: SharedV2ProviderMetadata; /** Optional request information for telemetry and debugging purposes. */ request?: { /** Request HTTP body that was sent to the provider API. */ body?: unknown; }; /** Optional response information for telemetry and debugging purposes. */ response?: LanguageModelV2ResponseMetadata & { /** Response headers. */ headers?: SharedV2Headers; /** Response HTTP body. */ body?: unknown; }; /** Warnings for the call, e.g. unsupported settings. */ warnings: Array; }>; /** Generates a language model output (streaming). Naming: "do" prefix to prevent accidental direct usage of the method by the user. * @return A stream of higher-level language model output parts. */ doStream(options: LanguageModelV2CallOptions): PromiseLike<{ stream: ReadableStream; /** Optional request information for telemetry and debugging purposes. */ request?: { /** Request HTTP body that was sent to the provider API. */ body?: unknown; }; /** Optional response data. */ response?: { /** Response headers. */ headers?: SharedV2Headers; }; }>; }; /** * Experimental middleware for LanguageModelV2. * This type defines the structure for middleware that can be used to modify * the behavior of LanguageModelV2 operations. */ //#endregion //#region ../../node_modules/.pnpm/@ai-sdk+provider@3.0.15/node_modules/@ai-sdk/provider/dist/index.d.ts type SharedV3Headers = Record; /** * A JSON value can be a string, number, boolean, object, array, or null. * JSON values can be serialized and deserialized by the JSON.stringify and JSON.parse methods. */ type JSONValue$1 = null | string | number | boolean | JSONObject | JSONArray; type JSONObject = { [key: string]: JSONValue$1 | undefined; }; type JSONArray = JSONValue$1[]; /** * Additional provider-specific metadata. * Metadata are additional outputs from the provider. * They are passed through to the provider from the AI SDK * and enable provider-specific functionality * that can be fully encapsulated in the provider. * * This enables us to quickly ship provider-specific functionality * without affecting the core AI SDK. * * The outer record is keyed by the provider name, and the inner * record is keyed by the provider-specific metadata key. * * ```ts * { * "anthropic": { * "cacheControl": { "type": "ephemeral" } * } * } * ``` */ type SharedV3ProviderMetadata = Record; /** * Additional provider-specific options. * Options are additional input to the provider. * They are passed through to the provider from the AI SDK * and enable provider-specific functionality * that can be fully encapsulated in the provider. * * This enables us to quickly ship provider-specific functionality * without affecting the core AI SDK. * * The outer record is keyed by the provider name, and the inner * record is keyed by the provider-specific metadata key. * * ```ts * { * "anthropic": { * "cacheControl": { "type": "ephemeral" } * } * } * ``` */ type SharedV3ProviderOptions = Record; /** * Warning from the model. * * For example, that certain features are unsupported or compatibility * functionality is used (which might lead to suboptimal results). */ type SharedV3Warning = { /** * A feature is not supported by the model. */ type: 'unsupported'; /** * The feature that is not supported. */ feature: string; /** * Additional details about the warning. */ details?: string; } | { /** * A compatibility feature is used that might lead to suboptimal results. */ type: 'compatibility'; /** * The feature that is used in a compatibility mode. */ feature: string; /** * Additional details about the warning. */ details?: string; } | { /** * Other warning. */ type: 'other'; /** * The message of the warning. */ message: string; }; /** * A tool has a name, a description, and a set of parameters. * * Note: this is **not** the user-facing tool definition. The AI SDK methods will * map the user-facing tool definitions to this format. */ type LanguageModelV3FunctionTool = { /** * The type of the tool (always 'function'). */ type: 'function'; /** * The name of the tool. Unique within this model call. */ name: string; /** * A description of the tool. The language model uses this to understand the * tool's purpose and to provide better completion suggestions. */ description?: string; /** * The parameters that the tool expects. The language model uses this to * understand the tool's input requirements and to provide matching suggestions. */ inputSchema: JSONSchema7; /** * An optional list of input examples that show the language * model what the input should look like. */ inputExamples?: Array<{ input: JSONObject; }>; /** * Strict mode setting for the tool. * * Providers that support strict mode will use this setting to determine * how the input should be generated. Strict mode will always produce * valid inputs, but it might limit what input schemas are supported. */ strict?: boolean; /** * The provider-specific options for the tool. */ providerOptions?: SharedV3ProviderOptions; }; /** * Data content. Can be a Uint8Array, base64 encoded data as a string or a URL. */ type LanguageModelV3DataContent = Uint8Array | string | URL; /** * A prompt is a list of messages. * * Note: Not all models and prompt formats support multi-modal inputs and * tool calls. The validation happens at runtime. * * Note: This is not a user-facing prompt. The AI SDK methods will map the * user-facing prompt types such as chat or instruction prompts to this format. */ type LanguageModelV3Prompt = Array; type LanguageModelV3Message = ({ role: 'system'; content: string; } | { role: 'user'; content: Array; } | { role: 'assistant'; content: Array; } | { role: 'tool'; content: Array; }) & { /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions; }; /** * Text content part of a prompt. It contains a string of text. */ interface LanguageModelV3TextPart { type: 'text'; /** * The text content. */ text: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions; } /** * Reasoning content part of a prompt. It contains a string of reasoning text. */ interface LanguageModelV3ReasoningPart { type: 'reasoning'; /** * The reasoning text. */ text: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions; } /** * File content part of a prompt. It contains a file. */ interface LanguageModelV3FilePart { type: 'file'; /** * Optional filename of the file. */ filename?: string; /** * File data. Can be a Uint8Array, base64 encoded data as a string or a URL. */ data: LanguageModelV3DataContent; /** * IANA media type of the file. * * Can support wildcards, e.g. `image/*` (in which case the provider needs to take appropriate action). * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions; } /** * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model). */ interface LanguageModelV3ToolCallPart { 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. */ input: unknown; /** * Whether the tool call will be executed by the provider. * If this flag is not set or is false, the tool call will be executed by the client. */ providerExecuted?: boolean; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions; } /** * Tool result content part of a prompt. It contains the result of the tool call with the matching ID. */ interface LanguageModelV3ToolResultPart { 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. */ output: LanguageModelV3ToolResultOutput; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions; } /** * Tool approval response content part of a prompt. It contains the user's * decision to approve or deny a provider-executed tool call. */ interface LanguageModelV3ToolApprovalResponsePart { type: 'tool-approval-response'; /** * ID of the approval request that this response refers to. */ approvalId: string; /** * Whether the approval was granted (true) or denied (false). */ approved: boolean; /** * Optional reason for approval or denial. */ reason?: string; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions; } /** * Result of a tool call. */ type LanguageModelV3ToolResultOutput = { /** * Text tool output that should be directly sent to the API. */ type: 'text'; value: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions; } | { type: 'json'; value: JSONValue$1; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions; } | { /** * Type when the user has denied the execution of the tool call. */ type: 'execution-denied'; /** * Optional reason for the execution denial. */ reason?: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions; } | { type: 'error-text'; value: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions; } | { type: 'error-json'; value: JSONValue$1; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions; } | { type: 'content'; value: Array<{ type: 'text'; /** * Text content. */ text: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions; } | { type: 'file-data'; /** * Base-64 encoded media data. */ data: string; /** * IANA media type. * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Optional filename of the file. */ filename?: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions; } | { type: 'file-url'; /** * URL of the file. */ url: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions; } | { type: 'file-id'; /** * ID of the file. * * If you use multiple providers, you need to * specify the provider specific ids using * the Record option. The key is the provider * name, e.g. 'openai' or 'anthropic'. */ fileId: string | Record; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions; } | { /** * Images that are referenced using base64 encoded data. */ type: 'image-data'; /** * Base-64 encoded image data. */ data: string; /** * IANA media type. * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions; } | { /** * Images that are referenced using a URL. */ type: 'image-url'; /** * URL of the image. */ url: string; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions; } | { /** * Images that are referenced using a provider file id. */ type: 'image-file-id'; /** * Image that is referenced using a provider file id. * * If you use multiple providers, you need to * specify the provider specific ids using * the Record option. The key is the provider * name, e.g. 'openai' or 'anthropic'. */ fileId: string | Record; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions; } | { /** * Custom content part. This can be used to implement * provider-specific content parts. */ type: 'custom'; /** * Provider-specific options. */ providerOptions?: SharedV3ProviderOptions; }>; }; /** * The configuration of a provider tool. * * Provider tools are tools that are specific to a certain provider. * The input and output schemas are defined be the provider, and * some of the tools are also executed on the provider systems. */ type LanguageModelV3ProviderTool = { /** * The type of the tool (always 'provider'). */ type: 'provider'; /** * The ID of the tool. Should follow the format `.`. */ id: `${string}.${string}`; /** * The name of the tool. Unique within this model call. */ name: string; /** * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool. */ args: Record; }; type LanguageModelV3ToolChoice = { type: 'auto'; } | { type: 'none'; } | { type: 'required'; } | { type: 'tool'; toolName: string; }; type LanguageModelV3CallOptions = { /** * A language mode prompt is a standardized prompt type. * * Note: This is **not** the user-facing prompt. The AI SDK methods will map the * user-facing prompt types such as chat or instruction prompts to this format. * That approach allows us to evolve the user facing prompts without breaking * the language model interface. */ prompt: LanguageModelV3Prompt; /** * Maximum number of tokens to generate. */ maxOutputTokens?: number; /** * Temperature setting. The range depends on the provider and model. */ temperature?: 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[]; /** * Nucleus sampling. */ 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. */ presencePenalty?: number; /** * Frequency penalty setting. It affects the likelihood of the model * to repeatedly use the same words or phrases. */ frequencyPenalty?: number; /** * Response format. The output can either be text or JSON. Default is text. * * If JSON is selected, a schema can optionally be provided to guide the LLM. */ responseFormat?: { type: 'text'; } | { type: 'json'; /** * JSON schema that the generated output should conform to. */ schema?: JSONSchema7; /** * Name of output that should be generated. Used by some providers for additional LLM guidance. */ name?: string; /** * Description of the output that should be generated. Used by some providers for additional LLM guidance. */ description?: string; }; /** * The seed (integer) to use for random sampling. If set and supported * by the model, calls will generate deterministic results. */ seed?: number; /** * The tools that are available for the model. */ tools?: Array; /** * Specifies how the tool should be selected. Defaults to 'auto'. */ toolChoice?: LanguageModelV3ToolChoice; /** * Include raw chunks in the stream. Only applicable for streaming calls. */ includeRawChunks?: boolean; /** * Abort signal for cancelling the operation. */ abortSignal?: AbortSignal; /** * Additional HTTP headers to be sent with the request. * Only applicable for HTTP-based providers. */ headers?: Record; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: SharedV3ProviderOptions; }; /** * A file that has been generated by the model. * Generated files as base64 encoded strings or binary data. * The files should be returned without any unnecessary conversion. */ type LanguageModelV3File = { type: 'file'; /** * The IANA media type of the file, e.g. `image/png` or `audio/mp3`. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Generated file data as base64 encoded strings or binary data. * * The file data should be returned without any unnecessary conversion. * If the API returns base64 encoded strings, the file data should be returned * as base64 encoded strings. If the API returns binary data, the file data should * be returned as binary data. */ data: string | Uint8Array; /** * Optional provider-specific metadata for the file part. */ providerMetadata?: SharedV3ProviderMetadata; }; /** * Reasoning that the model has generated. */ type LanguageModelV3Reasoning = { type: 'reasoning'; text: string; /** * Optional provider-specific metadata for the reasoning part. */ providerMetadata?: SharedV3ProviderMetadata; }; /** * A source that has been used as input to generate the response. */ type LanguageModelV3Source = { type: 'source'; /** * The type of source - URL sources reference web content. */ sourceType: 'url'; /** * The ID of the source. */ id: string; /** * The URL of the source. */ url: string; /** * The title of the source. */ title?: string; /** * Additional provider metadata for the source. */ providerMetadata?: SharedV3ProviderMetadata; } | { type: 'source'; /** * The type of source - document sources reference files/documents. */ sourceType: 'document'; /** * The ID of the source. */ id: string; /** * IANA media type of the document (e.g., 'application/pdf'). */ mediaType: string; /** * The title of the document. */ title: string; /** * Optional filename of the document. */ filename?: string; /** * Additional provider metadata for the source. */ providerMetadata?: SharedV3ProviderMetadata; }; /** * Text that the model has generated. */ type LanguageModelV3Text = { type: 'text'; /** * The text content. */ text: string; providerMetadata?: SharedV3ProviderMetadata; }; /** * Tool approval request emitted by a provider for a provider-executed tool call. * * This is used for flows where the provider executes the tool (e.g. MCP tools) * but requires an explicit user approval before continuing. */ type LanguageModelV3ToolApprovalRequest = { type: 'tool-approval-request'; /** * ID of the approval request. This ID is referenced by the subsequent * tool-approval-response (tool message) to approve or deny execution. */ approvalId: string; /** * The tool call ID that this approval request is for. */ toolCallId: string; /** * Additional provider-specific metadata for the approval request. */ providerMetadata?: SharedV3ProviderMetadata; }; /** * Tool calls that the model has generated. */ type LanguageModelV3ToolCall = { type: 'tool-call'; /** * The identifier of the tool call. It must be unique across all tool calls. */ toolCallId: string; /** * The name of the tool that should be called. */ toolName: string; /** * Stringified JSON object with the tool call arguments. Must match the * parameters schema of the tool. */ input: string; /** * Whether the tool call will be executed by the provider. * If this flag is not set or is false, the tool call will be executed by the client. */ providerExecuted?: boolean; /** * Whether the tool is dynamic, i.e. defined at runtime. * For example, MCP (Model Context Protocol) tools that are executed by the provider. */ dynamic?: boolean; /** * Additional provider-specific metadata for the tool call. */ providerMetadata?: SharedV3ProviderMetadata; }; /** * Result of a tool call that has been executed by the provider. */ type LanguageModelV3ToolResult = { type: 'tool-result'; /** * The 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: NonNullable; /** * Optional flag if the result is an error or an error message. */ isError?: boolean; /** * Whether the tool result is preliminary. * * Preliminary tool results replace each other, e.g. image previews. * There always has to be a final, non-preliminary tool result. * * If this flag is set to true, the tool result is preliminary. * If this flag is not set or is false, the tool result is not preliminary. */ preliminary?: boolean; /** * Whether the tool is dynamic, i.e. defined at runtime. * For example, MCP (Model Context Protocol) tools that are executed by the provider. */ dynamic?: boolean; /** * Additional provider-specific metadata for the tool result. */ providerMetadata?: SharedV3ProviderMetadata; }; type LanguageModelV3Content = LanguageModelV3Text | LanguageModelV3Reasoning | LanguageModelV3File | LanguageModelV3ToolApprovalRequest | LanguageModelV3Source | LanguageModelV3ToolCall | LanguageModelV3ToolResult; /** * Reason why a language model finished generating a response. * * Contains both a unified finish reason and a raw finish reason from the provider. * The unified finish reason is used to provide a consistent finish reason across different providers. * The raw finish reason is used to provide the original finish reason from the provider. */ type LanguageModelV3FinishReason = { /** * Unified finish reason. This enables using the same finish reason across different providers. * * 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 */ unified: 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other'; /** * Raw finish reason from the provider. * This is the original finish reason from the provider. */ raw: string | undefined; }; interface LanguageModelV3ResponseMetadata { /** * ID for the generated response, if the provider sends one. */ id?: string; /** * Timestamp for the start of the generated response, if the provider sends one. */ timestamp?: Date; /** * The ID of the response model that was used to generate the response, if the provider sends one. */ modelId?: string; } /** * Usage information for a language model call. */ type LanguageModelV3Usage = { /** * Information about the input tokens. */ inputTokens: { /** * The total number of input (prompt) tokens used. */ total: number | undefined; /** * The number of non-cached input (prompt) tokens used. */ noCache: number | undefined; /** * The number of cached input (prompt) tokens read. */ cacheRead: number | undefined; /** * The number of cached input (prompt) tokens written. */ cacheWrite: number | undefined; }; /** * Information about the output tokens. */ outputTokens: { /** * The total number of output (completion) tokens used. */ total: number | undefined; /** * The number of text tokens used. */ text: number | undefined; /** * The number of reasoning tokens used. */ reasoning: number | undefined; }; /** * Raw usage information from the provider. * * This is the usage information in the shape that the provider returns. * It can include additional information that is not part of the standard usage information. */ raw?: JSONObject; }; /** * The result of a language model doGenerate call. */ type LanguageModelV3GenerateResult = { /** * Ordered content that the model has generated. */ content: Array; /** * The finish reason. */ finishReason: LanguageModelV3FinishReason; /** * The usage information. */ usage: LanguageModelV3Usage; /** * 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. */ providerMetadata?: SharedV3ProviderMetadata; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Request HTTP body that was sent to the provider API. */ body?: unknown; }; /** * Optional response information for telemetry and debugging purposes. */ response?: LanguageModelV3ResponseMetadata & { /** * Response headers. */ headers?: SharedV3Headers; /** * Response HTTP body. */ body?: unknown; }; /** * Warnings for the call, e.g. unsupported settings. */ warnings: Array; }; type LanguageModelV3StreamPart = { type: 'text-start'; providerMetadata?: SharedV3ProviderMetadata; id: string; } | { type: 'text-delta'; id: string; providerMetadata?: SharedV3ProviderMetadata; delta: string; } | { type: 'text-end'; providerMetadata?: SharedV3ProviderMetadata; id: string; } | { type: 'reasoning-start'; providerMetadata?: SharedV3ProviderMetadata; id: string; } | { type: 'reasoning-delta'; id: string; providerMetadata?: SharedV3ProviderMetadata; delta: string; } | { type: 'reasoning-end'; id: string; providerMetadata?: SharedV3ProviderMetadata; } | { type: 'tool-input-start'; id: string; toolName: string; providerMetadata?: SharedV3ProviderMetadata; providerExecuted?: boolean; dynamic?: boolean; title?: string; } | { type: 'tool-input-delta'; id: string; delta: string; providerMetadata?: SharedV3ProviderMetadata; } | { type: 'tool-input-end'; id: string; providerMetadata?: SharedV3ProviderMetadata; } | LanguageModelV3ToolApprovalRequest | LanguageModelV3ToolCall | LanguageModelV3ToolResult | LanguageModelV3File | LanguageModelV3Source | { type: 'stream-start'; warnings: Array; } | ({ type: 'response-metadata'; } & LanguageModelV3ResponseMetadata) | { type: 'finish'; usage: LanguageModelV3Usage; finishReason: LanguageModelV3FinishReason; providerMetadata?: SharedV3ProviderMetadata; } | { type: 'raw'; rawValue: unknown; } | { type: 'error'; error: unknown; }; /** * The result of a language model doStream call. */ type LanguageModelV3StreamResult = { /** * The stream. */ stream: ReadableStream; /** * Optional request information for telemetry and debugging purposes. */ request?: { /** * Request HTTP body that was sent to the provider API. */ body?: unknown; }; /** * Optional response data. */ response?: { /** * Response headers. */ headers?: SharedV3Headers; }; }; /** * Specification for a language model that implements the language model interface version 3. */ type LanguageModelV3 = { /** * The language model must specify which language model interface version it implements. */ readonly specificationVersion: 'v3'; /** * Provider ID. */ readonly provider: string; /** * Provider-specific model ID. */ readonly modelId: string; /** * Supported URL patterns by media type for the provider. * * The keys are media type patterns or full media types (e.g. `*\/*` for everything, `audio/*`, `video/*`, or `application/pdf`). * and the values are arrays of regular expressions that match the URL paths. * * The matching should be against lower-case URLs. * * Matched URLs are supported natively by the model and are not downloaded. * * @returns A map of supported URL patterns by media type (as a promise or a plain object). */ supportedUrls: PromiseLike> | Record; /** * Generates a language model output (non-streaming). * Naming: "do" prefix to prevent accidental direct usage of the method * by the user. */ doGenerate(options: LanguageModelV3CallOptions): PromiseLike; /** * Generates a language model output (streaming). * * Naming: "do" prefix to prevent accidental direct usage of the method * by the user. * * @return A stream of higher-level language model output parts. */ doStream(options: LanguageModelV3CallOptions): PromiseLike; }; /** * Experimental middleware for LanguageModelV3. * This type defines the structure for middleware that can be used to modify * the behavior of LanguageModelV3 operations. */ //#endregion //#region src/opentelemetry-lib/tracing/processor.d.ts interface LaminarSpanProcessorOptions { /** * The base URL of the Laminar API. Optional. * Defaults to https://api.lmnr.ai. */ baseUrl?: string; /** * The port of the Laminar API. Optional. * Defaults to 8443. */ port?: number; /** * Laminar project API key. Optional. * If not provided, the LMNR_PROJECT_API_KEY environment variable will be used. */ apiKey?: string; /** * The maximum number of spans to export at a time. Optional. * Defaults to 512. */ maxExportBatchSize?: number; /** * Whether to disable batching. Optional. * Defaults to false. */ disableBatch?: boolean; /** * Approximate maximum size, in bytes, of the spans buffered in a single batch. * Only used when `flushBySize` is true. Optional. * Defaults to 32 MiB. */ maxExportBatchSizeBytes?: number; /** * Whether to also flush batches by approximate payload size. Optional. * Defaults to false. */ flushBySize?: boolean; /** * Whether to force HTTP and use OpenTelemetry HTTP/protobuf exporter. * Not recommended with Laminar backends. * Optional. * Defaults to false. */ forceHttp?: boolean; /** * The timeout for sending traces data. Optional. * Defaults to 30 seconds. */ traceExportTimeoutMillis?: number; /** * The exporter to use. Optional. If specified, some of the other options will be ignored. * Defaults to a new LaminarSpanExporter. */ exporter?: SpanExporter; /** * The span processor to use. If passed, some of the other options will be ignored. * If passed, wraps the underlying span processor. */ spanProcessor?: SpanProcessor; /** * The HTTP port to use. Optional. * If not provided, the `port` option will be used. */ httpPort?: number; } declare class LaminarSpanProcessor implements SpanProcessor { private instance; private logger; private readonly _spanIdToPath; private readonly _spanIdLists; /** * @param {object} options - The options for the Laminar span processor. * @param {string} options.baseUrl - The base URL of the Laminar API. * @param {number} options.port - The port of the Laminar API. * @param {string} options.apiKey - Laminar project API key or any other * authorization set as bearer token. * @param {boolean} options.disableBatch - Whether to disable batching (uses SimpleSpanProcessor). * @param {number} options.maxExportBatchSize - The maximum number of spans to export at a time * if disableBatch is false. * @param {number} options.traceExportTimeoutMillis - The timeout for sending traces data. * Defaults to 30 seconds. * @param {boolean} options.forceHttp - Whether to force HTTP and use OpenTelemetry * HTTP/protobuf exporter. * Not recommended with Laminar backends. */ constructor(options?: LaminarSpanProcessorOptions); forceFlush(): Promise; shutdown(): Promise; onStart(spanArg: any, parentContext: Context): void; /** * Record the root trace id on the debug runtime, if this is a debug run. * * No-op when debug mode is off. Best-effort: never break tracing. */ private recordDebugTraceId; onEnd(span: any): void; /** * Set parent path information for a given span ID. * Used when initializing context from environment variables. * * @param parentSpanId - The span ID to set path information for * @param spanPath - The span path (array of span names) * @param spanIdsPath - The span IDs path (array of span ID UUIDs) */ setParentPathInfo(parentSpanId: string, spanPath: string[], spanIdsPath: StringUUID[]): void; /** * Drop cached path entries for a given span id. For exporters that stamp * their own span id over the SDK-allocated one after `startSpan` has fired * `onStart` — without this, `onEnd` reads the mutated id and its delete is * a no-op, so the original entry leaks one pair of map entries per span. */ dropPathInfo(spanId: string): void; clear(): void; } //#endregion //#region src/opentelemetry-lib/tracing/attributes.d.ts declare const LaminarAttributes: { INPUT_TOKEN_COUNT: string; OUTPUT_TOKEN_COUNT: string; TOTAL_TOKEN_COUNT: string; PROVIDER: string; REQUEST_MODEL: string; RESPONSE_MODEL: string; INPUT_COST: string; OUTPUT_COST: string; TOTAL_COST: string; }; //#endregion //#region src/opentelemetry-lib/tracing/span.d.ts declare class LaminarSpan implements Span$1, ReadableSpan { private _span; private _activated; private _globalActiveContext?; constructor(span: Span$1, activated?: boolean); name: string; kind: SpanKind; parentSpanId?: string | undefined; startTime: HrTime; endTime: HrTime; status: SpanStatus; attributes: Attributes; links: Link[]; events: TimedEvent[]; duration: HrTime; ended: boolean; resource: any; instrumentationLibrary: any; droppedAttributesCount: number; droppedEventsCount: number; droppedLinksCount: number; spanContext(): SpanContext; setAttribute(key: string, value: AttributeValue): this; setAttributes(attributes: Attributes): this; addEvent(name: string, attributesOrStartTime?: Attributes | TimeInput, startTime?: TimeInput): this; addLink(link: Link): this; addLinks(links: Link[]): this; setStatus(status: SpanStatus): this; updateName(name: string): this; end(endTime?: TimeInput): void; setGlobalActiveContext(context: Context): void; set activated(activated: boolean); isRecording(): boolean; recordException(exception: Exception, time?: TimeInput): void; setTraceSessionId(sessionId: string): void; setTraceUserId(userId: string): void; setTraceMetadata(metadata: Record): void; setInput(input: any): void; setOutput(output: any): void; setTags(tags: string[]): void; addTags(tags: string[]): void; getLaminarSpanContext(): LaminarSpanContext; spanId(format?: "otel" | "uuid"): string; traceId(format?: "otel" | "uuid"): string; get tags(): string[]; get laminarAssociationProperties(): { metadata?: Record; userId?: string; sessionId?: string; traceType?: TraceType; tracingLevel?: TracingLevel; }; makeOtelV2Compatible(): void; get instrumentationScope(): InstrumentationScope; get parentSpanContext(): SpanContext | undefined; getParentSpanId(): string | undefined; get isActivated(): boolean; } //#endregion //#region src/laminar.d.ts interface LaminarInitializeProps { projectApiKey?: string; baseUrl?: string; baseHttpUrl?: string; httpPort?: number; grpcPort?: number; instrumentModules?: InitializeOptions["instrumentModules"]; disableBatch?: boolean; traceExportTimeoutMillis?: number; logLevel?: "debug" | "info" | "warn" | "error"; maxExportBatchSize?: number; maxExportBatchSizeBytes?: number; flushBySize?: boolean; forceHttp?: boolean; sessionRecordingOptions?: SessionRecordingOptions; metadata?: Record; inheritGlobalContext?: boolean; spanProcessor?: SpanProcessor; } type LaminarAttributesProp = Record<(typeof LaminarAttributes)[keyof typeof LaminarAttributes], AttributeValue>; declare class Laminar { private static baseHttpUrl; private static projectApiKey; private static isInitialized; private static globalMetadata; private static debugExitHook; private static baseUrlForDebug; private static httpPortForDebug; /** * Process-wide latch for debug-replay v2: once any LLM call gets a cache MISS, * every subsequent call runs live (skipping the cache lookup) for the rest of * the process. A COLD/`live` outcome runs that single call live WITHOUT * setting this flag. Read by the AI SDK wrapper's caching path; reset in * {@link shutdown} so an init/shutdown loop (tests) starts clean. */ static debugRunLive: boolean; /** * Initialize Laminar context across the application. * This method must be called before using any other Laminar methods or decorators. * * @param {LaminarInitializeProps} props - Configuration object. * @param {string} props.projectApiKey - Laminar project api key. You can generate one by going * to the projects settings page on the Laminar dashboard. * If not specified, it will try to read from the LMNR_PROJECT_API_KEY environment variable. * @param {string} props.baseUrl - Laminar API url. Do not include the port, use * `httpPort` and `grpcPort` instead. * If not specified, defaults to https://api.lmnr.ai. * @param {string} props.baseHttpUrl - Laminar API http url. If not specified, defaults to * baseUrl. Only use this if you want to proxy HTTP requests through a different host. * @param {number} props.httpPort - Laminar API http port. * If not specified, defaults to 443. * @param {number} props.grpcPort - Laminar API grpc port. * If not specified, defaults to 8443. * @param {InitializeOptions["instrumentModules"]} props.instrumentModules - Record * of modules to instrument. * If not specified, all auto-instrumentable modules will be instrumented, which include * LLM calls (OpenAI, Anthropic, etc), Langchain, VectorDB calls (Pinecone, Qdrant, etc). * Pass an empty object {} to disable any kind of automatic instrumentation. * If you only want to auto-instrument specific modules, then pass them in the object. * @param {boolean} props.disableBatch - Whether to disable batching of spans. Useful for debug * environments. If true, spans will be sent immediately using {@link SimpleSpanProcessor} * instead of {@link BatchSpanProcessor}. * @param {number} props.traceExportTimeoutMillis - Timeout for trace export. * Defaults to 30_000 (30 seconds), * which is over the default OTLP exporter timeout of 10_000 (10 seconds). * @param {string} props.logLevel - OTel log level. Defaults to "error". * @param {number} props.maxExportBatchSize - Maximum number of spans to export in a single batch. * Ignored when `disableBatch` is true. * @param {boolean} props.flushBySize - Whether to also flush batches by approximate payload * size, not just by span count and schedule delay. The batch is flushed when the next span * would push it past `maxExportBatchSizeBytes`, so a few large spans are exported without * waiting for `maxExportBatchSize` spans to accumulate. Useful when spans carry large prompts * or completions and exports get rejected for being too big. Defaults to false. * @param {number} props.maxExportBatchSizeBytes - Approximate maximum size, in bytes, of the * spans buffered in one batch. Only used when `flushBySize` is true. Defaults to 32 MiB. * @param {boolean} props.forceHttp - Whether to force HTTP export. Not recommended. * @param {SessionRecordingOptions} props.sessionRecordingOptions - Options for browser * session recording. * Currently supports 'maskInputOptions' to control whether input fields are masked during * recording. Defaults to undefined (uses default masking behavior). * @param {Record} props.metadata - Global metadata to associate with all spans. * This metadata will be associated with all spans, and merged with any metadata passed to * each span. Must be JSON serializable. * @param {boolean} props.inheritGlobalContext - Whether to inherit the global OpenTelemetry * context. Defaults to false. This is useful if your library is instrumented with OpenTelemetry * and you want Laminar spans to be children of the existing spans. * @param {SpanProcessor} props.spanProcessor - The span processor to use. If passed, some of * the other options will be ignored. * * @example * import { Laminar } from '@lmnr-ai/lmnr'; * import { OpenAI } from 'openai'; * import * as ChainsModule from "langchain/chains"; * * // Initialize Laminar while auto-instrumenting Langchain and OpenAI modules. * Laminar.initialize({ * projectApiKey: "", * instrumentModules: { * langchain: { * chainsModule: ChainsModule * }, * openAI: OpenAI * } * }); * * @throws {Error} - If project API key is not set */ static initialize({ projectApiKey, baseUrl, baseHttpUrl, httpPort, grpcPort, instrumentModules, disableBatch, traceExportTimeoutMillis, logLevel, maxExportBatchSize, maxExportBatchSizeBytes, flushBySize, forceHttp, sessionRecordingOptions, metadata, inheritGlobalContext, spanProcessor }?: LaminarInitializeProps): void; /** * Initialize Laminar context from the LMNR_SPAN_CONTEXT environment variable. * This allows continuing traces across process boundaries. * @private */ private static _initializeContextFromEnv; /** * Build the in-process debug runtime (§4, §5) when LMNR_DEBUG is set. * * On a debug run the session id from the config is stamped into the global * trace metadata as `rollout.session_id`, and a process-exit hook emits the * run pointer once the root trace id is known. When debug mode is off this is * a no-op and the SDK behaves exactly as before. * @private */ private static _initDebugRuntime; /** * Arm OR refresh the debug runtime from a propagated `DebugContext`. * * Called from `_startSpan` (the funnel for explicit span creation) and from * `observeBase` (the funnel for `observe()` / the observe decorators), when a * parent `LaminarSpanContext` carrying an armed debug block parses — so a * downstream service joins the upstream debug run regardless of how its spans * originate (auto-instrumentation, manual observe, external library). * * The coordinates carried in the span context are DYNAMIC: a long-lived * downstream service handling many requests must follow each request's * session / replay-trace / cache-until, not freeze on the first context it * ever saw. So the transport (client) is built once and reused, while the * replay coordinates are refreshed in place on every new context. An env-origin * runtime is the exception — it owns the process, so a propagated context never * overrides it. A context-armed (downstream) runtime reuses the upstream * session and may consult the cache, but — unlike the local-origin path — does * NOT open the browser, print the session URL, or register an exit-time pointer * hook (the origin owns those). It (re-)registers the session and re-stamps * `rollout.session_id` only when the session id actually changes. * * Never throws: any failure leaves debug inert. * * @internal Public only so `observeBase` (in opentelemetry-lib) can reach it * without an import cycle; not part of the supported API. */ static _armDebugRuntimeFromContext(debug: LaminarSpanContext["debug"]): void; /** * Patch modules manually. Use this in setups where {@link Laminar.initialize()} * and in particular its `instrumentModules` option is not working, e.g. in * Next.js place Laminar initialize in `instrumentation.ts`, and then patch * the modules in server components or API routes. * * Make sure to call this after {@link Laminar.initialize()}. * * @param {InitializeOptions["instrumentModules"]} modules - Record of modules to instrument. */ static patch(modules: InitializeOptions["instrumentModules"]): void; /** * Check if Laminar has been initialized. Utility to make sure other methods * are called after initialization. */ static initialized(): boolean; /** * Associates an event with the current span. If the event is created outside * of a span context, a new span is created and the event is associated with it. * * @param {object} options * @param {string} options.name - The name of the event. * @param {Record} options.attributes - The attributes of the event. * Values must be of a supported type. * @param {TimeInput} options.timestamp - The timestamp of the event. If not specified, relies on * the underlying OpenTelemetry implementation. * If specified as an integer, it must be epoch nanoseconds. * @param {string} options.sessionId - The session ID to associate with the event. * If not specified, the session ID of the current trace is used. * @param {string} options.userId - The user ID to associate with the event. If not specified, * the user ID of the current trace is used. */ static event({ name, attributes, timestamp, sessionId, userId }: { name: string; attributes?: Record; timestamp?: TimeInput; sessionId?: string; userId?: string; }): void; static getCurrentSpan(context?: Context): LaminarSpan | undefined; /** * Set attributes for the current span. Useful for manual * instrumentation. * @param {LaminarAttributesProp} attributes - The attributes to set for the current span. * * @example * import { Laminar as L, observe } from '@lmnr-ai/laminar'; * await observe({ name: 'mySpanName', spanType: 'LLM' }, async (msg: string) => { * const response = await myCustomCallToOpenAI(msg); * L.setSpanAttributes({ * [LaminarAttributes.PROVIDER]: 'openai', * [LaminarAttributes.REQUEST_MODEL]: "requested_model", * [LaminarAttributes.RESPONSE_MODEL]: response.model, * [LaminarAttributes.INPUT_TOKEN_COUNT]: response.usage.prompt_tokens, * [LaminarAttributes.OUTPUT_TOKEN_COUNT]: response.usage.completion_tokens, * }) * }, userMessage); */ static setSpanAttributes(attributes: LaminarAttributesProp): void; /** * Set the output of the current span. Useful for manual instrumentation. * @param output - Output of the span. Will be sent as an attribute, so must * be serializable to JSON. */ static setSpanOutput(output: any): void; static setTraceMetadata(metadata: Record): void; static setTraceSessionId(sessionId: string): void; static setTraceUserId(userId: string): void; static setSpanTags(tags: string[]): void; static addSpanTags(tags: string[]): void; /** * Start a new span, but don't set it as active. Useful for * manual instrumentation. If span type is 'LLM', you should report usage * manually. See {@link setSpanAttributes} for more information. * * @param {Object} options * @param {string} options.name - name of the span * @param {any} options.input - input to the span. Will be sent as an attribute, so must * be JSON serializable * @param {string} options.spanType - type of the span. Defaults to 'DEFAULT' * @param {Context} options.context - raw OpenTelemetry context to bind the span to. * @param {string | LaminarSpanContext} options.parentSpanContext - parent span context * to bind the span to. * @param {string[]} options.tags - tags to associate with the span. * @param {string} options.userId - user ID to associate with the span. * @param {string} options.sessionId - session ID to associate with the span. * @param {Record} options.metadata - metadata to associate with the span. * @returns The started span. * * @example * import { Laminar, observe } from '@lmnr-ai/lmnr'; * const foo = async (span: Span) => { * await Laminar.withSpan(span, async () => { * await observe({ name: 'foo' }, async () => { * // Your code here * }) * }) * }; * const bar = async (span: Span) => { * await Laminar.withSpan(span, async () => { * await openai_client.chat.completions.create(); * }) * }; * * const parentSpan = Laminar.startSpan({name: "outer"}); * foo(parentSpan); * await bar(parentSpan); * // IMPORTANT: Don't forget to end the span! * parentSpan.end(); * * // Results in: * // | outer * // | | foo * // | | | ... * // | | openai.chat */ static startSpan({ name, input, spanType, context, parentSpanContext, tags, userId, sessionId, metadata, startTime }: { name: string; input?: any; spanType?: SpanType; context?: Context; parentSpanContext?: string | LaminarSpanContext; tags?: string[]; userId?: string; sessionId?: string; metadata?: Record; startTime?: TimeInput; }): Span$1; /** * Start a new span, and set it as active. It is the caller's responsibility * to end the span. It is important to end the span, to avoid context mixing up. * We suggest ending the span in a finally block. * This is useful for manual instrumentation. * If span type is 'LLM', you should report usage manually. * See {@link setSpanAttributes} for more information. * * @param {Object} options * @param {string} options.name - name of the span * @param {any} options.input - input to the span. Will be sent as an attribute, so must * be JSON serializable * @param {string} options.spanType - type of the span. Defaults to 'DEFAULT' * @param {Context} options.context - raw OpenTelemetry context to bind the span to. * @param {string | LaminarSpanContext} options.parentSpanContext - parent span context * to bind the span to. * @param {string[]} options.tags - tags to associate with the span. * @param {string} options.userId - user ID to associate with the span. * @param {string} options.sessionId - session ID to associate with the span. * @param {Record} options.metadata - metadata to associate with the span. * @param {boolean} options.global - when true, the span is registered on a * process-global context stack so that any subsequent `startSpan` / * `startActiveSpan` call (including from unrelated async tasks) uses it as * the parent. Use this for spans that span multiple disconnected async * callbacks — e.g. the root span of an OpenAI Agents trace, where child * spans are created from independent `TracingProcessor` callbacks that do * not share an async context. Defaults to false; the span still activates * within the current async context as usual. * @returns The started span. * * @example * import { Laminar, observe } from '@lmnr-ai/lmnr'; * const foo = async () => { * await observe({ name: 'foo' }, async () => { * // Your code here * }) * }; * const bar = async (span: Span) => { * await observe({ name: 'bar' }, async () => { * await openai_client.chat.completions.create(); * }) * }; * * try { * const parentSpan = Laminar.startActiveSpan({name: "outer"}); * foo(); * await bar(); * } finally { * parentSpan.end(); * } * * // Results in: * // | outer * // | | foo * // | | | ... * // | | bar * // | | | openai.chat */ static startActiveSpan({ name, input, spanType, context, parentSpanContext, tags, userId, sessionId, metadata, startTime, global }: { name: string; input?: any; spanType?: SpanType; context?: Context; parentSpanContext?: string | LaminarSpanContext; tags?: string[]; userId?: string; sessionId?: string; metadata?: Record; startTime?: TimeInput; global?: boolean; }): Span$1; private static _startSpan; /** * A utility wrapper around OpenTelemetry's `context.with()`. Useful for * passing spans around in manual instrumentation: * * @param {Span} span - Parent span to bind the execution to. * @param {Function} fn - Function to execute within the span context. * @param {boolean} endOnExit - Whether to end the span after the function has * executed. Defaults to `false`. If `false`, you MUST manually call * `span.end()` at the end of the execution, so that spans are not lost. * @returns The result of the function execution. * * See {@link startSpan} docs for a usage example */ static withSpan(span: Span$1, fn: () => T, endOnExit?: boolean): T; static serializeLaminarSpanContext(span?: Span$1): string | null; static getLaminarSpanContext(span?: Span$1): LaminarSpanContext | null; /** * Get the trace id of the current span. Returns null if there is no active span. * @returns {StringUUID | null} The trace id of the current span. */ static getTraceId(): StringUUID | null; static flush(): Promise; static shutdown(): Promise; static getHttpUrl(): string; static getProjectApiKey(): string; /** * Instrument the claude-agent-sdk query function. * Use this when you need to import the query function before calling Laminar.initialize(). * * @param originalQuery - The original query function from @anthropic-ai/claude-agent-sdk * @returns The instrumented query function * * @example * ```typescript * import { query as originalQuery } from "@anthropic-ai/claude-agent-sdk"; * import { Laminar } from "@lmnr-ai/lmnr"; * * Laminar.initialize({ projectApiKey: "..." }); * * const query = Laminar.instrumentClaudeAgentQuery(originalQuery); * * // Now use the instrumented query function * const result = query({ prompt: "Hello!" }); * ``` */ static wrapClaudeAgentQuery(originalQuery: T): T; } //#endregion //#region ../../node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts /** The Standard Typed interface. This is a base type extended by other specs. */ interface StandardTypedV1 { /** The Standard properties. */ readonly "~standard": StandardTypedV1.Props; } declare namespace StandardTypedV1 { /** The Standard Typed properties interface. */ interface Props { /** The version number of the standard. */ readonly version: 1; /** The vendor name of the schema library. */ readonly vendor: string; /** Inferred types associated with the schema. */ readonly types?: Types | undefined; } /** The Standard Typed types interface. */ interface Types { /** The input type of the schema. */ readonly input: Input; /** The output type of the schema. */ readonly output: Output; } /** Infers the input type of a Standard Typed. */ type InferInput = NonNullable["input"]; /** Infers the output type of a Standard Typed. */ type InferOutput = NonNullable["output"]; } /** The Standard Schema interface. */ interface StandardSchemaV1 { /** The Standard Schema properties. */ readonly "~standard": StandardSchemaV1.Props; } declare namespace StandardSchemaV1 { /** The Standard Schema properties interface. */ interface Props extends StandardTypedV1.Props { /** Validates unknown input values. */ readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result | Promise>; } /** The result interface of the validate function. */ type Result = SuccessResult | FailureResult; /** The result interface if validation succeeds. */ interface SuccessResult { /** The typed output value. */ readonly value: Output; /** A falsy value for `issues` indicates success. */ readonly issues?: undefined; } interface Options { /** Explicit support for additional vendor-specific parameters, if needed. */ readonly libraryOptions?: Record | undefined; } /** The result interface if validation fails. */ interface FailureResult { /** The issues of failed validation. */ readonly issues: ReadonlyArray; } /** The issue interface of the failure output. */ interface Issue { /** The error message of the issue. */ readonly message: string; /** The path of the issue, if any. */ readonly path?: ReadonlyArray | undefined; } /** The path segment interface of the issue. */ interface PathSegment { /** The key representing a path segment. */ readonly key: PropertyKey; } /** The Standard types interface. */ interface Types extends StandardTypedV1.Types {} /** Infers the input type of a Standard. */ type InferInput = StandardTypedV1.InferInput; /** Infers the output type of a Standard. */ type InferOutput = StandardTypedV1.InferOutput; } /** The Standard JSON Schema interface. */ interface StandardJSONSchemaV1 { /** The Standard JSON Schema properties. */ readonly "~standard": StandardJSONSchemaV1.Props; } declare namespace StandardJSONSchemaV1 { /** The Standard JSON Schema properties interface. */ interface Props extends StandardTypedV1.Props { /** Methods for generating the input/output JSON Schema. */ readonly jsonSchema: StandardJSONSchemaV1.Converter; } /** The Standard JSON Schema converter interface. */ interface Converter { /** Converts the input type to JSON Schema. May throw if conversion is not supported. */ readonly input: (options: StandardJSONSchemaV1.Options) => Record; /** Converts the output type to JSON Schema. May throw if conversion is not supported. */ readonly output: (options: StandardJSONSchemaV1.Options) => Record; } /** * The target version of the generated JSON Schema. * * It is *strongly recommended* that implementers support `"draft-2020-12"` and `"draft-07"`, as they are both in wide use. All other targets can be implemented on a best-effort basis. Libraries should throw if they don't support a specified target. * * The `"openapi-3.0"` target is intended as a standardized specifier for OpenAPI 3.0 which is a superset of JSON Schema `"draft-04"`. */ type Target = "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string); /** The options for the input/output methods. */ interface Options { /** Specifies the target version of the generated JSON Schema. Support for all versions is on a best-effort basis. If a given version is not supported, the library should throw. */ readonly target: Target; /** Explicit support for additional vendor-specific parameters, if needed. */ readonly libraryOptions?: Record | undefined; } /** The Standard types interface. */ interface Types extends StandardTypedV1.Types {} /** Infers the input type of a Standard. */ type InferInput = StandardTypedV1.InferInput; /** Infers the output type of a Standard. */ type InferOutput = StandardTypedV1.InferOutput; } //#endregion //#region ../../node_modules/.pnpm/@ai-sdk+provider-utils@5.0.27_zod@4.4.3/node_modules/@ai-sdk/provider-utils/dist/index.d.ts /** * A value that can be provided either as a single item, an array of items, * or be left undefined. */ type Arrayable = T | T[] | undefined; /** * Normalizes a possibly undefined or non-array value into an array. */ type WebSocketLike = { readyState: number; /** Bytes queued by `send` but not yet transmitted (native + `ws`). */ readonly bufferedAmount?: number; send(data: string | Uint8Array | ArrayBuffer): void; close(code?: number, reason?: string): void; onopen: ((event: unknown) => void) | null; onmessage: ((event: { data: unknown; }) => void) | null; onerror: ((event: unknown) => void) | null; onclose: ((event: unknown) => void) | null; }; type WebSocketConstructor = new (url: string | URL, protocols?: string | string[], options?: { headers?: Record; }) => WebSocketLike; /** * Data content. Can either be a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer. */ type DataContent = string | Uint8Array | ArrayBuffer | Buffer; /** * File data variant containing raw bytes (`Uint8Array`, `ArrayBuffer`, or * `Buffer`) or a base64-encoded string. * * This is slightly more permissive than `SharedV4FileDataData`. */ interface FileDataData { type: 'data'; data: DataContent; } /** * File data variant containing a URL that points to the file. */ type FileDataUrl = SharedV4FileDataUrl; /** * File data variant containing a provider reference (`{ [provider]: id }`). */ type FileDataReference = SharedV4FileDataReference; /** * File data variant containing inline text content (e.g. an inline text * document). */ type FileDataText = SharedV4FileDataText; /** * File data as a tagged discriminated union: * * - `{ type: 'data', data }`: raw bytes (`Uint8Array`, `ArrayBuffer`, or * `Buffer`) or a base64-encoded string. * - `{ type: 'url', url }`: a URL that points to the file. * - `{ type: 'reference', reference }`: a provider reference (`{ [provider]: id }`). * - `{ type: 'text', text }`: inline text content (e.g. an inline text document). */ type FileData = FileDataData | FileDataUrl | FileDataReference | FileDataText; /** * Additional provider-specific options. * * 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 ProviderOptions = SharedV4ProviderOptions; /** * A mapping of provider names to provider-specific file identifiers. * * Provider references allow files to be identified across different * providers without re-uploading, by storing each provider's own * identifier for the same logical file. */ type ProviderReference$1 = SharedV4ProviderReference; /** * 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. */ providerOptions?: ProviderOptions; } /** * Image content part of a prompt. It contains an image. * * @deprecated Use `FilePart` with `mediaType: 'image'` instead: * `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`. */ 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 * - ProviderReference: a provider reference from `uploadFile` */ image: DataContent | URL | ProviderReference$1; /** * Optional IANA media type of the image. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType?: 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. */ providerOptions?: ProviderOptions; } /** * File content part of a prompt. It contains a file. */ interface FilePart { type: 'file'; /** * File data. Either a tagged shape or a bare shorthand: * * - `{ type: 'data', data }` or bare `DataContent`: raw bytes * (base64 string, Uint8Array, ArrayBuffer, Buffer) * - `{ type: 'url', url }` or bare `URL`: a URL that points to the file * - `{ type: 'reference', reference }` or bare `ProviderReference`: * a provider reference from `uploadFile` * - `{ type: 'text', text }`: inline text content (tagged only) */ data: FileData | DataContent | URL | ProviderReference$1; /** * Optional filename of the file. */ filename?: string; /** * Either a full IANA media type (`type/subtype`, e.g. `image/png`) or just * the top-level IANA segment (e.g. `image`, `audio`, `video`, `text`). * * `*`-subtype wildcards (e.g. `image/*`) are normalized as equivalent to the * top-level segment alone (e.g. `image`). Providers can use the helpers in * `@ai-sdk/provider-utils` (`isFullMediaType`, `getTopLevelMediaType`, * `detectMediaType`) to resolve the field according to their API * requirements. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: 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. */ providerOptions?: ProviderOptions; } /** * Reasoning content part of a prompt. It contains a reasoning. */ interface ReasoningPart { type: 'reasoning'; /** * The reasoning text. */ 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. */ providerOptions?: ProviderOptions; } /** * Custom content part of a prompt. It contains no standardized payload beyond * provider-specific options. */ interface CustomPart { type: 'custom'; /** * The kind of custom content, in the format `{provider}.{provider-type}`. */ kind: `${string}.${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. */ providerOptions?: ProviderOptions; } /** * Reasoning file content part of a prompt. It contains a file generated as part of reasoning. */ interface ReasoningFilePart { type: 'reasoning-file'; /** * Reasoning file data. * * Reasoning files originate from a model's reasoning output and are always * raw bytes or a fetchable URL. Unlike `FilePart.data`, the `reference` and * `text` shapes are not supported here: provider references describe files * uploaded by the user (not produced as model output), and reasoning text is * carried by `ReasoningPart` rather than as a file. * * Either a tagged shape or a bare shorthand: * * - `{ type: 'data', data }` or bare `DataContent`: raw bytes * (base64 string, Uint8Array, ArrayBuffer, Buffer) * - `{ type: 'url', url }` or bare `URL`: a URL that points to the file */ data: FileDataData | FileDataUrl | DataContent | URL; /** * IANA media type of the file. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: 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. */ providerOptions?: ProviderOptions; } /** * 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. */ input: 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. */ providerOptions?: ProviderOptions; /** * Whether the tool call was executed by the provider. */ providerExecuted?: boolean; } /** * 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. */ output: ToolResultOutput; /** * 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. */ providerOptions?: ProviderOptions; } /** * Output of a tool result. */ type ToolResultOutput = { /** * Text tool output that should be directly sent to the API. */ type: 'text'; value: string; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { type: 'json'; value: JSONValue$3; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { /** * Type when the user has denied the execution of the tool call. */ type: 'execution-denied'; /** * Optional reason for the execution denial. */ reason?: string; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { type: 'error-text'; value: string; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { type: 'error-json'; value: JSONValue$3; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { type: 'content'; value: Array<{ type: 'text'; /** * Text content. */ text: string; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { type: 'file'; /** * File data as a tagged discriminated union: * * - `{ type: 'data', data }`: raw bytes * (base64 string, Uint8Array, ArrayBuffer, Buffer) * - `{ type: 'url', url }`: a URL that points to the file * - `{ type: 'reference', reference }`: a provider reference * from `uploadFile` * - `{ type: 'text', text }`: inline text content (e.g. an inline * text document) */ data: FileData; /** * Either a full IANA media type (`type/subtype`, e.g. `image/png`) or just * the top-level IANA segment (e.g. `image`, `audio`, `video`, `text`). * * `*`-subtype wildcards (e.g. `image/*`) are normalized as equivalent to the * top-level segment alone (e.g. `image`). Providers can use the helpers in * `@ai-sdk/provider-utils` (`isFullMediaType`, `getTopLevelMediaType`, * `detectMediaType`) to resolve the field according to their API * requirements. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Optional filename of the file. */ filename?: string; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { /** * @deprecated Use 'file' with mediaType + tagged data instead: * `{ type: 'file', mediaType, data: { type: 'data', data } }`. */ type: 'file-data'; /** * Base-64 encoded media data. */ data: string; /** * IANA media type. * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Optional filename of the file. */ filename?: string; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { /** * @deprecated Use 'file' with mediaType and tagged data instead: * `{ type: 'file', mediaType, data: { type: 'url', url: new URL(url) } }`. */ type: 'file-url'; /** * URL of the file. */ url: string; /** * IANA media type. * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType?: string; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { /** * @deprecated Use 'file' with tagged data instead: * `{ type: 'file', mediaType, data: { type: 'reference', reference } }`. */ type: 'file-id'; /** * ID of the file. * * If you use multiple providers, you need to * specify the provider specific ids using * the Record option. The key is the provider * name, e.g. 'openai' or 'anthropic'. */ fileId: string | Record; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { /** * @deprecated Use 'file' with tagged data instead: * `{ type: 'file', mediaType, data: { type: 'reference', reference } }`. */ type: 'file-reference'; /** * Provider-specific references for the file. * The key is the provider name, e.g. 'openai' or 'anthropic'. */ providerReference: ProviderReference$1; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { /** * @deprecated Use 'file' with mediaType (e.g. 'image' or a specific * `image/*` subtype) and tagged data instead: * `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`. */ type: 'image-data'; /** * Base-64 encoded image data. */ data: string; /** * IANA media type. * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { /** * @deprecated Use 'file' with `mediaType: 'image'` (or a specific * `image/*` subtype) and tagged data instead: * `{ type: 'file', mediaType: 'image', data: { type: 'url', url: new URL(url) } }`. */ type: 'image-url'; /** * URL of the image. */ url: string; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { /** * @deprecated Use 'file' with `mediaType: 'image'` (or a specific * `image/*` subtype) and tagged data instead: * `{ type: 'file', mediaType: 'image', data: { type: 'reference', reference } }`. */ type: 'image-file-id'; /** * Image that is referenced using a provider file id. * * If you use multiple providers, you need to * specify the provider specific ids using * the Record option. The key is the provider * name, e.g. 'openai' or 'anthropic'. */ fileId: string | Record; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { /** * @deprecated Use 'file' with `mediaType: 'image'` (or a specific * `image/*` subtype) and tagged data instead: * `{ type: 'file', mediaType: 'image', data: { type: 'reference', reference } }`. */ type: 'image-file-reference'; /** * Provider-specific references for the image file. * The key is the provider name, e.g. 'openai' or 'anthropic'. */ providerReference: ProviderReference$1; /** * Provider-specific options. */ providerOptions?: ProviderOptions; } | { /** * Custom content part. This can be used to implement * provider-specific content parts. */ type: 'custom'; /** * Provider-specific options. */ providerOptions?: ProviderOptions; }>; }; declare const symbol$1$1: unique symbol; declare class DownloadError extends AISDKError { private readonly [symbol$1$1]; readonly url: string; readonly statusCode?: number; readonly statusText?: string; constructor({ url, statusCode, statusText, cause, message }: { url: string; statusCode?: number; statusText?: string; message?: string; cause?: unknown; }); static isInstance(error: unknown): error is DownloadError; } /** * Fetch function type (standardizes the version of fetch used). */ type FetchFunction = typeof globalThis.fetch; /** * Fetches a URL while enforcing the download guard on every hop. * * Redirects are followed manually (`redirect: 'manual'`) so each hop is * validated with {@link validateDownloadUrl} *before* it is requested. Relying * on the default `redirect: 'follow'` would issue the request to a redirect * target (e.g. an internal address) before we ever see its URL, defeating the * guard. * * Request headers are also protected: {@link sanitizeRequestHeaders} strips * proxy/metadata/cookie/hop-by-hop headers before the first request, and all * caller headers except `User-Agent` are dropped on a cross-origin redirect. * The fetch spec only strips `Authorization` on cross-origin redirects because * in a browser, CORS preflighting protects custom headers; there is no CORS on * the server, so provider API keys carried in custom headers (e.g. `x-key`) * must be dropped here as well. * * A `redirect: 'manual'` request yields an unreadable opaque response in the * browser (and in other spec-compliant fetch implementations), so the redirect * target cannot be validated here. In a real browser this is safe to follow * natively because reaching an internal network is not possible (fetch is * constrained by CORS and cannot reach a server's internal network or * cloud-metadata). On any other runtime we cannot validate the hop, so we fail * closed rather than follow it blindly and bypass the guard. * * A hop that is same-origin with `trustedOrigin` (the developer-configured * provider endpoint) skips target validation: that origin is exactly what an * unvalidated, config-derived request would fetch anyway, and validating it * would break legitimate self-hosted / localhost deployments whose response * URLs point back at the configured host. Hops on any other origin are always * validated. * * The returned response is the final (non-redirect) response. The caller is * responsible for checking `response.ok` and reading the body. * * On Node.js, the default fetch resolves every hostname through a validating * lookup hook and passes those exact addresses to the connector, preventing * hostname-to-private-IP and DNS-rebinding bypasses. An injected fetch is * responsible for equivalent connect-time validation. Other runtimes should * constrain egress at the network layer when handling untrusted URLs. * * @throws DownloadError if a hop is unsafe, the redirect limit is exceeded, or * a redirect cannot be validated on a non-browser runtime. */ /** * Creates an ID generator. * The total length of the ID is the sum of the prefix, separator, and random part length. * Not cryptographically secure. * * @param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'. * @param prefix - The prefix of the ID to generate. Optional. * @param separator - The separator between the prefix and the random part of the ID. Default: '-'. * @param size - The size of the random part of the ID to generate. Default: 16. */ declare const createIdGenerator: ({ prefix, size, alphabet, separator }?: { prefix?: string; separator?: string; size?: number; alphabet?: string; }) => IdGenerator; /** * A function that generates an ID. */ type IdGenerator = () => string; /** * Generates a 16-character random string to use for IDs. * Not cryptographically secure. */ declare const generateId$1: IdGenerator; /** * Used to mark schemas so we can support both Zod and custom schemas. */ declare const schemaSymbol: unique symbol; type ValidationResult = { success: true; value: OBJECT; } | { success: false; error: Error; }; type Schema = { /** * Used to mark schemas so we can support both Zod and custom schemas. */ [schemaSymbol]: true; /** * Schema type for inference. */ _type: OBJECT; /** * Optional. Validates that the structure of a value matches this schema, * and returns a typed version of the value if it does. */ readonly validate?: (value: unknown) => ValidationResult | PromiseLike>; /** * The JSON Schema for the schema. It is passed to the providers. */ readonly jsonSchema: JSONSchema7$1 | PromiseLike; }; /** * Creates a schema with deferred creation. * This is important to reduce the startup time of the library * and to avoid initializing unused validators. * * @param createValidator A function that creates a schema. * @returns A function that returns a schema. */ type LazySchema = () => Schema; type ZodSchema = z3.Schema | $ZodType; type StandardSchema = StandardSchemaV1 & { readonly '~standard': StandardSchemaV1.Props & { readonly jsonSchema?: StandardJSONSchemaV1.Converter; }; }; type FlexibleSchema = Schema | LazySchema | ZodSchema | StandardSchema; type InferSchema = SCHEMA extends ZodSchema ? T : SCHEMA extends StandardSchema ? T : SCHEMA extends LazySchema ? T : SCHEMA extends Schema ? T : never; /** * Create a schema using a JSON Schema. * * @param jsonSchema The JSON Schema for the schema. * @param options.validate Optional. A validation function for the schema. */ declare function jsonSchema(jsonSchema: JSONSchema7$1 | PromiseLike | (() => JSONSchema7$1 | PromiseLike), { validate }?: { validate?: (value: unknown) => ValidationResult | PromiseLike>; }): Schema; declare function asSchema(schema: FlexibleSchema | undefined): Schema; declare function zodSchema(zodSchema: $ZodType | z3.Schema, options?: { /** * Enables support for references in the schema. * This is required for recursive schemas, e.g. with `z.lazy`. * However, not all language models and providers support such references. * Defaults to `false`. */ useReferences?: boolean; }): Schema; /** * Parses a JSON string into an unknown object. * * @param text - The JSON string to parse. * @returns {JSONValue} - The parsed JSON object. */ type ParseResult = { success: true; value: T; rawValue: unknown; } | { success: false; error: JSONParseError | TypeValidationError; rawValue: unknown; }; /** * Safely parses a JSON string and returns the result as an object of type `unknown`. * * @param text - The JSON string to parse. * @returns {Promise} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred. */ /** * Checks if an object has required keys. * @param OBJECT - The object to check. * @returns True if the object has required keys, false otherwise. */ type HasRequiredKey = {} extends OBJECT ? false : true; /** * A value that can be provided either synchronously or as a promise-like. */ type MaybePromiseLike = T | PromiseLike; /** * Maps a media type to its corresponding file extension. * It was originally introduced to set a filename for audio file uploads * in https://github.com/vercel/ai/pull/8159. * * @param mediaType The media type to map. * @returns The corresponding file extension * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types */ /** * Parses a JSON event stream into a stream of parsed JSON objects. */ declare function parseJsonEventStream({ stream, schema }: { stream: ReadableStream; schema: FlexibleSchema; }): ReadableStream>; /** * A context object that is passed into tool execution. */ type Context$1 = Record; /** * A tool that is guaranteed to expose an execute function. */ type ExecutableTool = TOOL & { execute: NonNullable; }; /** * Checks whether a tool exposes an execute function. */ type NeverOptional = 0 extends 1 & N ? Partial : [N] extends [never] ? Partial> : T; /** * Tool approval request prompt part. */ type ToolApprovalRequest = { type: 'tool-approval-request'; /** * ID of the tool approval. */ approvalId: string; /** * ID of the tool call that the approval request is for. */ toolCallId: string; /** * Flag indicating whether the tool was automatically approved or denied. * * @default false */ isAutomatic?: boolean; /** * HMAC-SHA256 signature binding this approval to its tool call. * Present only when `experimental_toolApprovalSecret` is configured. */ signature?: string; }; /** * An assistant message. It can contain text, tool calls, or a combination of text and tool calls. */ type AssistantModelMessage = { 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. */ providerOptions?: ProviderOptions; }; /** * Content of an assistant message. * It can be a string or an array of text, image, reasoning, redacted reasoning, and tool call parts. */ type AssistantContent = string | Array; /** * 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 SystemModelMessage = { 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. */ providerOptions?: ProviderOptions; }; /** * Tool approval response prompt part. */ type ToolApprovalResponse = { type: 'tool-approval-response'; /** * ID of the tool approval. */ approvalId: string; /** * Flag indicating whether the approval was granted or denied. */ approved: boolean; /** * Optional reason for the approval or denial. */ reason?: string; /** * Flag indicating whether the tool call is provider-executed. * Only provider-executed tool approval responses should be sent to the model. */ providerExecuted?: boolean; }; /** * A tool message. It contains the result of one or more tool calls. */ type ToolModelMessage = { 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. */ providerOptions?: ProviderOptions; }; /** * Content of a tool message. It is an array of tool result parts. */ type ToolContent = Array; /** * A user message. It can contain text or a combination of text and images. */ type UserModelMessage = { 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. */ providerOptions?: ProviderOptions; }; /** * Content of a user message. It can be a string or an array of text and image parts. */ type UserContent = string | Array; /** * 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 ModelMessage = SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage; /** * Options for executing a command in the sandbox via `run` or `spawn`. */ type SandboxProcessOptions = { /** * Command to execute in the sandbox. */ command: string; /** * Working directory to execute the command in. */ workingDirectory?: string; /** * Environment variables to set for this command. Merged with the * sandbox's default environment; values here take precedence. * Supporting environment variables as an option is preferable from a * security perspective, e.g. to avoid them leaking in logs. */ env?: Record; /** * Signal that can be used to abort the command. When aborted, the running * process is killed; for `spawn`, `wait()` rejects with the abort reason. */ abortSignal?: AbortSignal; }; /** * Options for reading a file from the sandbox. */ type ReadFileOptions = { /** * Path of the file to read. */ path: string; /** * Signal that can be used to abort the read. */ abortSignal?: AbortSignal; }; /** * Options for writing a file to the sandbox. `CONTENT` is the payload written * to the file: a byte stream, raw bytes, or a string. */ type WriteFileOptions = { /** * Path of the file to write. */ path: string; /** * Content to write to the file. */ content: CONTENT; /** * Signal that can be used to abort the write. */ abortSignal?: AbortSignal; }; /** * Sandbox session that can execute commands and read/write files. */ type SandboxSession = { /** * Description of the sandbox environment that can be added to the agent's instructions * so that the agent knows about relevant details such as the root directory, exposed * ports, the public hostname, etc. */ readonly description: string; /** * Read one file from the sandbox as a stream of bytes. Resolves to `null` * when the file does not exist. * * Relative path handling is implementation-defined. This is the lowest-level * read primitive; prefer `readBinaryFile` or `readTextFile` unless you need * to stream bytes. */ readonly readFile: (options: ReadFileOptions) => PromiseLike | null>; /** * Read one file from the sandbox as raw bytes. Resolves to `null` when the * file does not exist. */ readonly readBinaryFile: (options: ReadFileOptions) => PromiseLike; /** * Read one text file from the sandbox, decoded using the requested encoding. * Resolves to `null` when the file does not exist. * * Line ranges are 1-based and inclusive. When `endLine` is past EOF the read * returns through EOF without error. */ readonly readTextFile: (options: ReadFileOptions & { /** * Text encoding used to decode the file bytes. Defaults to `"utf-8"`. */ encoding?: string; /** * 1-based inclusive start line. Defaults to 1. */ startLine?: number; /** * 1-based inclusive end line. When past the file's line count, the read * returns through EOF without error. */ endLine?: number; }) => PromiseLike; /** * Write one file to the sandbox from a stream of bytes. Creates parent * directories recursively and overwrites any existing file. * * This is the lowest-level write primitive; prefer `writeBinaryFile` or * `writeTextFile` when the full content is already materialized in memory. */ readonly writeFile: (options: WriteFileOptions>) => PromiseLike; /** * Write one file to the sandbox from raw bytes. Creates parent directories * recursively and overwrites any existing file. */ readonly writeBinaryFile: (options: WriteFileOptions) => PromiseLike; /** * Write one file to the sandbox from a string, encoded using the requested * encoding. Creates parent directories recursively and overwrites any * existing file. */ readonly writeTextFile: (options: WriteFileOptions & { /** * Text encoding used to encode the string to bytes. Defaults to `"utf-8"`. */ encoding?: string; }) => PromiseLike; /** * Spawn a long-running process in the sandbox. Returns immediately with a * handle that streams stdout/stderr, can be waited on, and can be killed. * * `run` is conceptually a thin wrapper over this primitive: spawn, * collect both streams to strings, await `wait()`, return the result. */ readonly spawn: (options: SandboxProcessOptions) => PromiseLike; /** * Run a command in the sandbox. */ readonly run: (options: SandboxProcessOptions) => PromiseLike<{ /** * Exit code returned by the command. */ exitCode: number; /** * Standard output produced by the command. */ stdout: string; /** * Standard error produced by the command. */ stderr: string; }>; }; /** * Handle to a long-running process started via `SandboxSession.spawn`. */ type SandboxProcess = { /** * Process identifier, if the sandbox implementation exposes one. */ readonly pid?: number; /** * Stream of bytes written by the process to standard output. */ readonly stdout: ReadableStream; /** * Stream of bytes written by the process to standard error. */ readonly stderr: ReadableStream; /** * Resolve when the process exits, yielding its exit code. */ wait(): PromiseLike<{ exitCode: number; }>; /** * Terminate the process. Idempotent. */ kill(): PromiseLike; }; /** * Additional options that are sent into each tool execution. */ 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: ModelMessage[]; /** * An optional abort signal that indicates that the overall operation should be aborted. */ abortSignal?: AbortSignal; /** * Tool context as defined by the tool's context schema. * The tool context is specific to the tool and is passed to the tool execution. * * Treat the context object as immutable inside tools. * Mutating the context object can lead to race conditions and unexpected results * when tools are called in parallel. * * If you need to mutate the context, analyze the tool calls and results * in `prepareStep` and update it there. */ context: CONTEXT; /** * The sandbox environment that the tool is operating in. */ experimental_sandbox?: SandboxSession; } /** * Function that executes the tool and returns either a single result or a stream of results. */ type ToolExecuteFunction = (input: INPUT, options: ToolExecutionOptions) => AsyncIterable | PromiseLike | OUTPUT; /** * Function that is called to determine if the tool needs approval before it can be executed. * * @deprecated Tool approval is handled on a `generateText` / `streamText` level now. */ type ToolNeedsApprovalFunction = (input: INPUT, options: { /** * 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: ModelMessage[]; /** * Tool context as defined by the tool's context schema. * The tool context is specific to the tool and is passed to the tool execution. * * Treat the context object as immutable inside tools. * Mutating the context object can lead to race conditions and unexpected results * when tools are called in parallel. * * If you need to mutate the context, analyze the tool calls and results * in `prepareStep` and update it there. */ context: CONTEXT; }) => boolean | PromiseLike; /** * Helper type to determine the outputSchema and execute function properties of a tool. */ type ToolOutputProperties = NeverOptional; /** * 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: ToolExecuteFunction; } | { /** * The schema of the output that the tool produces. * * Required when no execute function is provided. */ outputSchema: FlexibleSchema; execute?: never; }>; /** * Common properties shared by all tool kinds. */ type BaseTool = { /** * An optional title of the tool. * * @deprecated Use `providerMetadata` for source-specific tool display metadata. */ title?: 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. */ providerOptions?: ProviderOptions; /** * Optional metadata about the tool itself (e.g. its source). * * Unlike `providerOptions`, this metadata is not sent to the language * model. Instead, it is propagated onto the resulting tool call's * `toolMetadata` so consumers can read it from tool call / result parts * and UI message parts. This is useful for sources of dynamic tools (e.g. * an MCP server) to identify themselves. */ metadata?: JSONObject$2; /** * 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. * * You can use descriptions on the schema properties to make the input understandable for the language model. */ inputSchema: FlexibleSchema; /** * An optional schema describing the context that the tool expects. * * The context is passed to execute function as part of the execution options. */ contextSchema?: FlexibleSchema; /** * Whether the tool needs approval before it can be executed. * * @deprecated Tool approval is handled on a `generateText` / `streamText` level now. */ needsApproval?: boolean | ToolNeedsApprovalFunction<[INPUT] extends [never] ? unknown : INPUT, NoInfer>; /** * Optional function that is called when the model starts generating the tool input. * In non-streaming contexts, it is called immediately before `onInputAvailable`. */ onInputStart?: (options: ToolExecutionOptions>) => void | PromiseLike; /** * Optional function that is called when an argument streaming delta is available. * Only called when the tool is used in a streaming context. */ onInputDelta?: (options: { inputTextDelta: string; } & ToolExecutionOptions>) => void | PromiseLike; /** * Optional function that is called when a tool call can be started, * even if the execute function is not provided. */ onInputAvailable?: (options: { input: [INPUT] extends [never] ? unknown : INPUT; } & ToolExecutionOptions>) => void | PromiseLike; /** * Optional conversion function that maps the tool result to an output that can be used by the language model. * * If not provided, the tool result will be sent as a JSON object. * * This function is invoked on the server by `convertToModelMessages`, so ensure that you pass the same "tools" (ToolSet) to both "convertToModelMessages" and "streamText" (or other generation APIs). */ toModelOutput?: (options: { /** * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data. */ toolCallId: string; /** * The input of the tool call. */ input: [INPUT] extends [never] ? unknown : INPUT; /** * The output of the tool call. */ output: 0 extends 1 & OUTPUT ? any : [OUTPUT] extends [never] ? any : NoInfer; }) => ToolResultOutput | PromiseLike; } & ToolOutputProperties>; /** * Common properties shared by function-style tools. */ type BaseFunctionTool = BaseTool & { /** * Optional description of what the tool does. * * Included in the tool definition sent to the language model so it can * decide when and how to call the tool. * * Provide a string for a fixed description, or a function that returns a * string from the current `context` (and optional `experimental_sandbox`) when the * description should vary per call. */ description?: string | ((options: { context: NoInfer; experimental_sandbox?: SandboxSession; }) => string); /** * Strict mode setting for the tool. * * Providers that support strict mode will use this setting to determine * how the input should be generated. Strict mode will always produce * valid inputs, but it might limit what input schemas are supported. */ strict?: boolean; /** * An optional list of input examples that show the language * model what the input should look like. */ inputExamples?: Array<{ input: NoInfer; }>; id?: never; isProviderExecuted?: never; args?: never; supportsDeferredResults?: never; }; /** * Tool with user-defined input and output schemas that is executed by the AI SDK. */ type FunctionTool = BaseFunctionTool & { type?: undefined | 'function'; }; /** * Tool that is defined at runtime. * The types of input and output are not known at development time. * * For example, MCP tools that are not known at development time. */ type DynamicTool = BaseFunctionTool & { type: 'dynamic'; }; /** * Common properties shared by provider tools. */ type BaseProviderTool = BaseTool & { type: 'provider'; /** * The ID of the tool. Must follow the format `.`. */ id: `${string}.${string}`; /** * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool. */ args: Record; description?: never; strict?: never; inputExamples?: never; }; /** * Tool with provider-defined input and output schemas that is executed by the * user. * * For example, shell tools that are executed in a local shell, but have provider-defined input and output schemas. */ type ProviderDefinedTool = BaseProviderTool & { /** * Flag that indicates whether the tool is executed by the provider. */ isProviderExecuted: false; supportsDeferredResults?: never; }; /** * Tool with provider-defined input and output schemas that is executed by the * provider. * * For example, web search tools and code execution tools that are executed by the provider itself. */ type ProviderExecutedTool = BaseProviderTool & { /** * Flag that indicates whether the tool is executed by the provider. */ isProviderExecuted: true; /** * Whether this provider-executed tool supports deferred results. * * When true, the tool result may not be returned in the same turn as the * tool call (e.g., when using programmatic tool calling where a server tool * triggers a client-executed tool, and the server tool's result is deferred * until the client tool is resolved). * * This flag allows the AI SDK to handle tool results that arrive without * a matching tool call in the current response. * * @default false */ supportsDeferredResults?: boolean; }; /** * A tool can either be user-defined or provider-defined. * * It contains the schemas and metadata needed for the language model to call * the tool and can include an execute function for tools that are executed by * the AI SDK. */ type Tool = FunctionTool | DynamicTool | ProviderDefinedTool | ProviderExecutedTool; /** * Infer the tool type from a tool object. * * This is useful for type inference when working with tool objects. * * When the input has an `execute` function, the return type narrows to * `ExecutableTool>` so that `.execute` is non-nullable without * needing `isExecutableTool` or a `!` assertion at the call site. */ declare function tool$1(tool: Tool & { execute: ToolExecuteFunction; }): ExecutableTool>; declare function tool$1(tool: Tool): Tool; declare function tool$1(tool: Tool): Tool; declare function tool$1(tool: Tool): Tool; declare function tool$1(tool: Tool): Tool; /** * Define a dynamic tool. */ declare function dynamicTool(tool: Omit, 'type'>): DynamicTool; /** * A provider-defined tool is a tool for which the provider defines the input * and output schemas, but does not execute the tool. */ /** * A provider-executed tool is a tool for which the provider executes the tool. */ type ProviderExecutedToolFactory = (options: ARGS & { onInputStart?: Tool['onInputStart']; onInputDelta?: Tool['onInputDelta']; onInputAvailable?: Tool['onInputAvailable']; }) => ProviderExecutedTool; /** * A value or a lazy provider of a value, each of which may be synchronous or asynchronous. * * @template T The resolved type after {@link resolve} runs. * * One of: * - A plain value of type {@link T} * - A {@link PromiseLike} of {@link T} (e.g. a `Promise`) * - A zero-argument function that returns a plain {@link T} * - A zero-argument function that returns a {@link PromiseLike} of {@link T} * * The function form is only invoked when passed to {@link resolve}; it is not distinguished from * a {@link T} that happens to be a function—callers should wrap function values if disambiguation * is required. */ type Resolvable = MaybePromiseLike | (() => MaybePromiseLike); /** * Resolves a value that could be a raw value, a Promise, a function returning a value, * or a function returning a Promise. */ /** * Detects the `any` type so untyped tools can be treated as having no explicit * context type. */ type IsAny = 0 extends 1 & T ? true : false; /** * Detects exact empty object contexts, including `{}` combined with * `undefined`, which do not provide tool-specific context properties. */ type IsEmptyObject$1 = keyof NonNullable extends never ? true : false; /** * Detects context types that come from omitted or broad context declarations * rather than a concrete tool context schema. */ type IsUntypedContext = IsAny extends true ? true : unknown extends CONTEXT ? true : IsEmptyObject$1 extends true ? true : string extends keyof CONTEXT ? CONTEXT extends Context$1 ? true : false : false; /** * Infer the context type of a tool. */ type InferToolContext = TOOL extends Tool ? IsUntypedContext extends true ? never : CONTEXT : never; /** * Infer the input type of a tool. */ type InferToolInput> = TOOL extends Tool ? INPUT : never; /** * Infer the output type of a tool. */ type InferToolOutput> = TOOL extends Tool ? OUTPUT : never; /** * Executes a tool function and normalizes its results into a stream of outputs. * * - If the tool's `execute` function returns an `AsyncIterable`, each yielded value is emitted as * `{ type: "preliminary", output }`. After iteration completes, the last yielded value is emitted * again as `{ type: "final", output }`. * - If the tool returns a direct value or Promise, a single `{ type: "final", output }` is yielded. * * @param params.tool The tool whose `execute` function should be invoked. * @param params.input The input value to pass to the tool. * @param params.options Additional options for tool execution. * @yields A preliminary output for each streamed value, followed by a final output, or a single final * output for non-streaming tools. */ /** * A mapping of tool names to tool definitions. */ type ToolSet = Record | Tool | Tool | Tool) & Pick, 'execute' | 'onInputAvailable' | 'onInputStart' | 'onInputDelta' | 'needsApproval'>>; /** * Builds the required portion of the tool context map for tools whose context * type does not include `undefined`. */ type RequiredToolSetContext = { [K in keyof TOOLS as InferToolContext> extends never ? never : undefined extends InferToolContext> ? never : K]: InferToolContext> }; /** * Builds the optional portion of the tool context map for tools whose context * object itself may be `undefined`. */ type OptionalToolSetContext = { [K in keyof TOOLS as InferToolContext> extends never ? never : undefined extends InferToolContext> ? K : never]?: InferToolContext> }; /** * Flattens intersected mapped types so type equality assertions and editor * hovers show the resulting object shape. */ type Normalize = { [KEY in keyof OBJECT]: OBJECT[KEY] }; /** * Infer the context type for a tool set. * * The inferred type maps each contextual tool name to its context type. * * Tools without concrete context are omitted. Tool contexts that include * `undefined` are represented as optional properties. */ type InferToolSetContext = Normalize & OptionalToolSetContext>; /** * Typed tool call that is returned by generateText and streamText. * It contains the tool call ID, the tool name, and the tool arguments. */ interface ToolCall { /** * 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: NAME; /** * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema. */ input: INPUT; /** * Whether the tool call will be executed by the provider. * If this flag is not set or is false, the tool call will be executed by the client. */ providerExecuted?: boolean; /** * Whether the tool is dynamic. */ dynamic?: boolean; } type ToolCallerDefinition = { type: 'local'; bind: (tools: ToolSet) => Tool; } | { type: 'provider'; prepareProviderOptions: (providerOptions: ProviderOptions | undefined) => ProviderOptions; }; type ToolCallerTool = TOOL & { readonly experimental_toolCaller: ToolCallerDefinition; }; declare function toolCaller(tool: TOOL, definition: ToolCallerDefinition): ToolCallerTool; //#endregion //#region ../../node_modules/.pnpm/@ai-sdk+gateway@4.0.52_zod@4.4.3/node_modules/@ai-sdk/gateway/dist/index.d.ts type GatewayEmbeddingModelId = 'alibaba/qwen3-embedding-0.6b' | 'alibaba/qwen3-embedding-4b' | 'alibaba/qwen3-embedding-8b' | 'amazon/titan-embed-text-v2' | 'cohere/embed-v4.0' | 'google/gemini-embedding-001' | 'google/gemini-embedding-2' | 'google/text-embedding-005' | 'google/text-multilingual-embedding-002' | 'mistral/codestral-embed' | 'mistral/mistral-embed' | 'openai/text-embedding-3-large' | 'openai/text-embedding-3-small' | 'openai/text-embedding-ada-002' | 'perplexity/pplx-embed-v1-0.6b' | 'perplexity/pplx-embed-v1-4b' | 'voyage/voyage-3-large' | 'voyage/voyage-3.5' | 'voyage/voyage-3.5-lite' | 'voyage/voyage-4' | 'voyage/voyage-4-large' | 'voyage/voyage-4-lite' | 'voyage/voyage-code-2' | 'voyage/voyage-code-3' | 'voyage/voyage-finance-2' | 'voyage/voyage-law-2' | (string & {}); type GatewayImageModelId = 'bfl/flux-2-flex' | 'bfl/flux-2-klein-4b' | 'bfl/flux-2-klein-9b' | 'bfl/flux-2-max' | 'bfl/flux-2-pro' | 'bfl/flux-kontext-max' | 'bfl/flux-kontext-pro' | 'bfl/flux-pro-1.0-fill' | 'bfl/flux-pro-1.1' | 'bfl/flux-pro-1.1-ultra' | 'bytedance/seedream-4.0' | 'bytedance/seedream-4.5' | 'bytedance/seedream-5.0-lite' | 'bytedance/seedream-5.0-pro' | 'google/imagen-4.0-fast-generate-001' | 'google/imagen-4.0-generate-001' | 'google/imagen-4.0-ultra-generate-001' | 'openai/gpt-image-1' | 'openai/gpt-image-1-mini' | 'openai/gpt-image-1.5' | 'openai/gpt-image-2' | 'prodia/flux-fast-schnell' | 'quiverai/arrow-1.1' | 'recraft/recraft-v2' | 'recraft/recraft-v3' | 'recraft/recraft-v4' | 'recraft/recraft-v4-pro' | 'recraft/recraft-v4.1' | 'recraft/recraft-v4.1-pro' | 'recraft/recraft-v4.1-utility' | 'recraft/recraft-v4.1-utility-pro' | 'xai/grok-imagine-image' | 'xai/grok-imagine-image-2.0' | (string & {}); type GatewayModelId = 'alibaba/qwen-3-14b' | 'alibaba/qwen-3-235b' | 'alibaba/qwen-3-30b' | 'alibaba/qwen-3-32b' | 'alibaba/qwen-3.6-max-preview' | 'alibaba/qwen3-235b-a22b-thinking' | 'alibaba/qwen3-coder' | 'alibaba/qwen3-coder-30b-a3b' | 'alibaba/qwen3-coder-next' | 'alibaba/qwen3-coder-plus' | 'alibaba/qwen3-max' | 'alibaba/qwen3-max-preview' | 'alibaba/qwen3-max-thinking' | 'alibaba/qwen3-next-80b-a3b-instruct' | 'alibaba/qwen3-next-80b-a3b-thinking' | 'alibaba/qwen3-vl-235b-a22b-instruct' | 'alibaba/qwen3-vl-instruct' | 'alibaba/qwen3-vl-thinking' | 'alibaba/qwen3.5-flash' | 'alibaba/qwen3.5-plus' | 'alibaba/qwen3.6-27b' | 'alibaba/qwen3.6-plus' | 'alibaba/qwen3.7-flash' | 'alibaba/qwen3.7-max' | 'alibaba/qwen3.7-plus' | 'alibaba/qwen3.8-max' | 'amazon/nova-2-lite' | 'amazon/nova-lite' | 'amazon/nova-micro' | 'amazon/nova-pro' | 'anthropic/claude-3-haiku' | 'anthropic/claude-fable-5' | 'anthropic/claude-haiku-4.5' | 'anthropic/claude-opus-4' | 'anthropic/claude-opus-4.5' | 'anthropic/claude-opus-4.6' | 'anthropic/claude-opus-4.7' | 'anthropic/claude-opus-4.8' | 'anthropic/claude-opus-4.8-fast' | 'anthropic/claude-opus-5' | 'anthropic/claude-opus-5-fast' | 'anthropic/claude-sonnet-4' | 'anthropic/claude-sonnet-4.5' | 'anthropic/claude-sonnet-4.6' | 'anthropic/claude-sonnet-5' | 'arcee-ai/trinity-large-thinking' | 'arcee-ai/trinity-mini' | 'bytedance/seed-1.6' | 'bytedance/seed-1.8' | 'cohere/command-a' | 'deepseek/deepseek-r1' | 'deepseek/deepseek-v3' | 'deepseek/deepseek-v3.1' | 'deepseek/deepseek-v3.1-terminus' | 'deepseek/deepseek-v3.2' | 'deepseek/deepseek-v3.2-thinking' | 'deepseek/deepseek-v4-flash' | 'deepseek/deepseek-v4-flash-0731' | 'deepseek/deepseek-v4-pro' | 'deepseek/deepseek-v4-pro-0813' | 'google/gemini-2.5-flash' | 'google/gemini-2.5-flash-image' | 'google/gemini-2.5-flash-lite' | 'google/gemini-2.5-pro' | 'google/gemini-3-flash' | 'google/gemini-3-pro-image' | 'google/gemini-3.1-flash-image' | 'google/gemini-3.1-flash-image-preview' | 'google/gemini-3.1-flash-lite' | 'google/gemini-3.1-flash-lite-image' | 'google/gemini-3.1-pro-preview' | 'google/gemini-3.5-flash' | 'google/gemini-3.5-flash-lite' | 'google/gemini-3.6-flash' | 'google/gemini-3.7-flash' | 'google/gemini-omni-flash-preview' | 'google/gemma-4-26b-a4b-it' | 'google/gemma-4-31b-it' | 'inception/mercury-2' | 'inception/mercury-coder-small' | 'inclusionai/ling-3.0-flash' | 'inclusionai/ling-3.0-tiny-free' | 'interfaze/interfaze-beta' | 'kwaipilot/kat-coder-air-v2.5' | 'kwaipilot/kat-coder-pro-v1' | 'kwaipilot/kat-coder-pro-v2' | 'kwaipilot/kat-coder-pro-v2.5' | 'meta/llama-3.1-70b' | 'meta/llama-3.1-8b' | 'meta/llama-3.3-70b' | 'meta/llama-4-maverick' | 'meta/llama-4-scout' | 'meta/muse-glimmer-30b' | 'meta/muse-spark-1.1' | 'meta/muse-spark-1.2' | 'meta/muse-spark-1.2-contributor' | 'minimax/minimax-m2' | 'minimax/minimax-m2.1' | 'minimax/minimax-m2.1-lightning' | 'minimax/minimax-m2.5' | 'minimax/minimax-m2.5-highspeed' | 'minimax/minimax-m2.7' | 'minimax/minimax-m2.7-highspeed' | 'minimax/minimax-m3' | 'mistral/codestral' | 'mistral/devstral-2' | 'mistral/devstral-small-2' | 'mistral/magistral-medium' | 'mistral/magistral-small' | 'mistral/ministral-14b' | 'mistral/ministral-3b' | 'mistral/ministral-8b' | 'mistral/mistral-large-3' | 'mistral/mistral-medium' | 'mistral/mistral-medium-3.5' | 'mistral/mistral-nemo' | 'mistral/mistral-small' | 'mistral/pixtral-12b' | 'moonshotai/kimi-k2' | 'moonshotai/kimi-k2-thinking' | 'moonshotai/kimi-k2.5' | 'moonshotai/kimi-k2.6' | 'moonshotai/kimi-k2.7-code' | 'moonshotai/kimi-k2.7-code-highspeed' | 'moonshotai/kimi-k3' | 'moonshotai/kimi-k3-fast' | 'morph/morph-v3-fast' | 'morph/morph-v3-large' | 'nvidia/nemotron-3-nano-30b-a3b' | 'nvidia/nemotron-3-super-120b-a12b' | 'nvidia/nemotron-3-ultra-550b-a55b' | 'nvidia/nemotron-nano-12b-v2-vl' | 'nvidia/nemotron-nano-9b-v2' | 'openai/gpt-3.5-turbo' | 'openai/gpt-4-turbo' | 'openai/gpt-4.1' | 'openai/gpt-4.1-mini' | 'openai/gpt-4.1-nano' | 'openai/gpt-4o' | 'openai/gpt-4o-mini' | 'openai/gpt-4o-mini-search-preview' | 'openai/gpt-5' | 'openai/gpt-5-codex' | 'openai/gpt-5-mini' | 'openai/gpt-5-nano' | 'openai/gpt-5-pro' | 'openai/gpt-5.1-codex' | 'openai/gpt-5.1-codex-max' | 'openai/gpt-5.1-codex-mini' | 'openai/gpt-5.1-thinking' | 'openai/gpt-5.2' | 'openai/gpt-5.2-codex' | 'openai/gpt-5.2-pro' | 'openai/gpt-5.3-codex' | 'openai/gpt-5.4' | 'openai/gpt-5.4-mini' | 'openai/gpt-5.4-nano' | 'openai/gpt-5.4-pro' | 'openai/gpt-5.5' | 'openai/gpt-5.5-pro' | 'openai/gpt-5.6-luna' | 'openai/gpt-5.6-sol' | 'openai/gpt-5.6-terra' | 'openai/gpt-oss-120b' | 'openai/gpt-oss-20b' | 'openai/gpt-oss-safeguard-20b' | 'openai/o1' | 'openai/o3' | 'openai/o3-deep-research' | 'openai/o3-mini' | 'openai/o3-pro' | 'openai/o4-mini' | 'perplexity/sonar' | 'perplexity/sonar-pro' | 'perplexity/sonar-reasoning-pro' | 'poolside/laguna-s-2.1' | 'poolside/laguna-s-2.1-free' | 'sakana/fugu-ultra' | 'sakana/namazu' | 'stepfun/step-3.5-flash' | 'stepfun/step-3.7-flash' | 'tencent/hy3' | 'thinkingmachines/inkling' | 'thinkingmachines/inkling-small' | 'xai/grok-4.1-fast-non-reasoning' | 'xai/grok-4.1-fast-reasoning' | 'xai/grok-4.20-multi-agent' | 'xai/grok-4.20-multi-agent-beta' | 'xai/grok-4.20-non-reasoning' | 'xai/grok-4.20-non-reasoning-beta' | 'xai/grok-4.20-reasoning' | 'xai/grok-4.20-reasoning-beta' | 'xai/grok-4.3' | 'xai/grok-4.5' | 'xai/grok-4.6' | 'xai/grok-build-0.1' | 'xiaomi/mimo-v2.5' | 'xiaomi/mimo-v2.5-pro' | 'zai/glm-4.5' | 'zai/glm-4.5-air' | 'zai/glm-4.5v' | 'zai/glm-4.6' | 'zai/glm-4.6v' | 'zai/glm-4.6v-flash' | 'zai/glm-4.7' | 'zai/glm-4.7-flash' | 'zai/glm-4.7-flashx' | 'zai/glm-5' | 'zai/glm-5-turbo' | 'zai/glm-5.1' | 'zai/glm-5.2' | 'zai/glm-5.2-fast' | 'zai/glm-5v-turbo' | (string & {}); /** * Shared WebSocket subprotocol contract for AI Gateway realtime and streaming * transcription auth. * * The browser `WebSocket` API cannot set request headers, so the Gateway auth * (bearer) token is carried through the `Sec-WebSocket-Protocol` handshake * instead of an `Authorization` header — the same workaround OpenAI uses for * `openai-insecure-api-key.`. * * This module is the single source of truth for that contract so the client and * the Gateway server can't drift: the client encodes values with * `getGatewayRealtimeProtocols` / `getGatewayTranscriptionProtocols`, and the * Gateway server decodes them with `getGatewayRealtimeAuthToken` / * `getGatewayRealtimeTeamIdOrSlug`. * * WebSocket subprotocol values must fit the RFC token grammar. The auth token is * sent as-is, so callers must use tokens that are valid subprotocol tokens; the * optional team scope is base64url-encoded by this module. Keep the complete * `Sec-WebSocket-Protocol` header compact (target under an 8 KiB safe header * budget) because intermediaries may reject large upgrade headers. */ /** * Marker subprotocol offered on every realtime handshake so the Gateway can * echo a negotiated subprotocol on the 101 response (some clients require the * server to select one of the offered subprotocols). */ type GatewayRerankingModelId = 'cohere/rerank-v3.5' | 'cohere/rerank-v4-fast' | 'cohere/rerank-v4-pro' | 'voyage/rerank-2.5' | 'voyage/rerank-2.5-lite' | (string & {}); type GatewaySpeechModelId = 'fish-audio/s1' | 'fish-audio/s2-pro' | 'fish-audio/s2.1-pro' | 'openai/tts-1' | 'openai/tts-1-hd' | 'xai/grok-tts' | (string & {}); type GatewayTranscriptionModelId = 'fish-audio/transcribe-1' | 'openai/gpt-4o-mini-transcribe' | 'openai/gpt-4o-transcribe' | 'openai/gpt-realtime-whisper' | 'openai/whisper-1' | 'xai/grok-stt' | (string & {}); type GatewayVideoModelId = 'alibaba/wan-v2.5-t2v-preview' | 'alibaba/wan-v2.6-i2v' | 'alibaba/wan-v2.6-i2v-flash' | 'alibaba/wan-v2.6-r2v' | 'alibaba/wan-v2.6-r2v-flash' | 'alibaba/wan-v2.6-t2v' | 'alibaba/wan-v2.7-r2v' | 'alibaba/wan-v2.7-t2v' | 'bfl/flux-3-video' | 'bytedance/seedance-2.0' | 'bytedance/seedance-2.0-fast' | 'bytedance/seedance-2.5' | 'bytedance/seedance-v1.0-pro' | 'bytedance/seedance-v1.0-pro-fast' | 'bytedance/seedance-v1.5-pro' | 'google/veo-3.0-fast-generate-001' | 'google/veo-3.0-generate-001' | 'google/veo-3.1-fast-generate-001' | 'google/veo-3.1-generate-001' | 'google/veo-3.1-lite-generate-001' | 'klingai/kling-v2.5-turbo-i2v' | 'klingai/kling-v2.5-turbo-t2v' | 'klingai/kling-v2.6-i2v' | 'klingai/kling-v2.6-motion-control' | 'klingai/kling-v2.6-t2v' | 'klingai/kling-v3.0-i2v' | 'klingai/kling-v3.0-motion-control' | 'klingai/kling-v3.0-t2v' | 'minimax/minimax-h3' | 'xai/grok-imagine-video' | 'xai/grok-imagine-video-1.5' | 'xai/grok-imagine-video-1.5-preview' | (string & {}); declare const KNOWN_MODEL_TYPES: readonly ["embedding", "image", "language", "realtime", "reranking", "speech", "transcription", "video"]; type KnownModelType = (typeof KNOWN_MODEL_TYPES)[number]; interface GatewayLanguageModelEntry { /** * The model id used by the remote provider in model settings and for specifying the * intended model for text generation. */ id: string; /** * The display name of the model for presentation in user-facing contexts. */ name: string; /** * Optional description of the model. */ description?: string | null; /** * Optional pricing information for the model. */ pricing?: { /** * Cost per input token in USD. */ input: string; /** * Cost per output token in USD. */ output: string; /** * Cost per cached input token in USD. * Only present for providers/models that support prompt caching. */ cachedInputTokens?: string; /** * Cost per input token to create/write cache entries in USD. * Only present for providers/models that support prompt caching. */ cacheCreationInputTokens?: string; } | null; /** * Additional AI SDK language model specifications for the model. */ specification: GatewayLanguageModelSpecification; /** * Optional field to differentiate between model types. */ modelType?: KnownModelType | null; } type GatewayLanguageModelSpecification = Pick; interface GatewayFetchMetadataResponse { models: GatewayLanguageModelEntry[]; } interface GatewayCreditsResponse { /** The remaining gateway credit balance available for API usage */ balance: string; /** The total amount of gateway credits that have been consumed */ totalUsed: string; } interface GatewaySpendReportParams { /** Start date in YYYY-MM-DD format (inclusive) */ startDate: string; /** End date in YYYY-MM-DD format (inclusive) */ endDate: string; /** Primary aggregation dimension. Defaults to 'day'. */ groupBy?: 'day' | 'user' | 'model' | 'tag' | 'provider' | 'credential_type'; /** Time granularity when groupBy is 'day'. */ datePart?: 'day' | 'hour'; /** Filter to a specific user's spend. */ userId?: string; /** Filter to a specific model (e.g. 'anthropic/claude-sonnet-4.5'). */ model?: string; /** Filter to a specific provider (e.g. 'anthropic'). */ provider?: string; /** Filter to BYOK or system credentials. */ credentialType?: 'byok' | 'system'; /** Filter to requests with these tags. */ tags?: string[]; } interface GatewaySpendReportRow { /** Date string (present when groupBy is 'day') */ day?: string; /** Hour timestamp (present when groupBy is 'day' and datePart is 'hour') */ hour?: string; /** User identifier (present when groupBy is 'user') */ user?: string; /** Model identifier (present when groupBy is 'model') */ model?: string; /** Tag value (present when groupBy is 'tag') */ tag?: string; /** Provider name (present when groupBy is 'provider') */ provider?: string; /** Credential type (present when groupBy is 'credential_type') */ credentialType?: 'byok' | 'system'; /** Total cost in USD */ totalCost: number; /** Market cost in USD */ marketCost?: number; /** Number of input tokens */ inputTokens?: number; /** Number of output tokens */ outputTokens?: number; /** Number of cached input tokens */ cachedInputTokens?: number; /** Number of cache creation input tokens */ cacheCreationInputTokens?: number; /** Number of reasoning tokens */ reasoningTokens?: number; /** Number of requests */ requestCount?: number; } interface GatewaySpendReportResponse { results: GatewaySpendReportRow[]; } interface GatewayGenerationInfoParams { /** The generation ID to look up (format: gen_) */ id: string; } interface GatewayGenerationInfo { /** The generation ID */ id: string; /** Total cost in USD */ totalCost: number; /** Upstream inference cost in USD (BYOK only) */ upstreamInferenceCost: number; /** Usage cost in USD (same as totalCost) */ usage: number; /** ISO 8601 timestamp when the generation was created */ createdAt: string; /** Model identifier */ model: string; /** Whether BYOK credentials were used */ isByok: boolean; /** Provider that served this generation */ providerName: string; /** Whether streaming was used */ streamed: boolean; /** Finish reason (e.g. 'stop') */ finishReason: string; /** Time to first token in milliseconds */ latency: number; /** Total generation time in milliseconds */ generationTime: number; /** Number of prompt tokens */ promptTokens: number; /** Number of completion tokens */ completionTokens: number; /** Reasoning tokens used */ reasoningTokens: number; /** Cached tokens used */ cachedTokens: number; /** Cache creation input tokens */ cacheCreationTokens: number; /** Billable web search calls */ billableWebSearchCalls: number; } interface PerplexitySearchConfig { /** * Default maximum number of search results to return (1-20, default: 10). */ maxResults?: number; /** * Default maximum tokens to extract per search result page (256-2048, default: 2048). */ maxTokensPerPage?: number; /** * Default maximum total tokens across all search results (default: 25000, max: 1000000). */ maxTokens?: number; /** * Default two-letter ISO 3166-1 alpha-2 country code for regional search results. * Examples: 'US', 'GB', 'FR' */ country?: string; /** * Default list of domains to include or exclude from search results (max 20). * To include: ['nature.com', 'science.org'] * To exclude: ['-example.com', '-spam.net'] */ searchDomainFilter?: string[]; /** * Default list of ISO 639-1 language codes to filter results (max 10, lowercase). * Examples: ['en', 'fr', 'de'] */ searchLanguageFilter?: string[]; /** * Default recency filter for results. * Cannot be combined with searchAfterDate/searchBeforeDate at runtime. */ searchRecencyFilter?: 'day' | 'week' | 'month' | 'year'; } interface PerplexitySearchResult { /** Title of the search result */ title: string; /** URL of the search result */ url: string; /** Text snippet/preview of the content */ snippet: string; /** Publication date of the content */ date?: string; /** Last updated date of the content */ lastUpdated?: string; } interface PerplexitySearchResponse { /** Array of search results */ results: PerplexitySearchResult[]; /** Unique identifier for this search request */ id: string; } interface PerplexitySearchError { /** Error type */ error: 'api_error' | 'rate_limit' | 'timeout' | 'invalid_input' | 'unknown'; /** HTTP status code if applicable */ statusCode?: number; /** Human-readable error message */ message: string; } interface PerplexitySearchInput { /** * Search query (string) or multiple queries (array of up to 5 strings). * Multi-query searches return combined results from all queries. */ query: string | string[]; /** * Maximum number of search results to return (1-20, default: 10). */ max_results?: number; /** * Maximum number of tokens to extract per search result page (256-2048, default: 2048). */ max_tokens_per_page?: number; /** * Maximum total tokens across all search results (default: 25000, max: 1000000). */ max_tokens?: number; /** * Two-letter ISO 3166-1 alpha-2 country code for regional search results. * Examples: 'US', 'GB', 'FR' */ country?: string; /** * List of domains to include or exclude from search results (max 20). * To include: ['nature.com', 'science.org'] * To exclude: ['-example.com', '-spam.net'] */ search_domain_filter?: string[]; /** * List of ISO 639-1 language codes to filter results (max 10, lowercase). * Examples: ['en', 'fr', 'de'] */ search_language_filter?: string[]; /** * Include only results published after this date. * Format: 'MM/DD/YYYY' (e.g., '3/1/2025') * Cannot be used with search_recency_filter. */ search_after_date?: string; /** * Include only results published before this date. * Format: 'MM/DD/YYYY' (e.g., '3/15/2025') * Cannot be used with search_recency_filter. */ search_before_date?: string; /** * Include only results last updated after this date. * Format: 'MM/DD/YYYY' (e.g., '3/1/2025') * Cannot be used with search_recency_filter. */ last_updated_after_filter?: string; /** * Include only results last updated before this date. * Format: 'MM/DD/YYYY' (e.g., '3/15/2025') * Cannot be used with search_recency_filter. */ last_updated_before_filter?: string; /** * Filter results by relative time period. * Cannot be used with search_after_date or search_before_date. */ search_recency_filter?: 'day' | 'week' | 'month' | 'year'; } type PerplexitySearchOutput = PerplexitySearchResponse | PerplexitySearchError; declare const perplexitySearchToolFactory: ProviderExecutedToolFactory; interface ParallelSearchSourcePolicy { /** * List of domains to include in search results. * Example: ['wikipedia.org', 'nature.com'] */ includeDomains?: string[]; /** * List of domains to exclude from search results. * Example: ['reddit.com', 'twitter.com'] */ excludeDomains?: string[]; /** * Only include results published after this date (ISO 8601 format). * Example: '2024-01-01' */ afterDate?: string; } interface ParallelSearchExcerpts { /** * Maximum characters per result. */ maxCharsPerResult?: number; /** * Maximum total characters across all results. */ maxCharsTotal?: number; } interface ParallelSearchFetchPolicy { /** * Maximum age in seconds for cached content. * Set to 0 to always fetch fresh content. */ maxAgeSeconds?: number; } interface ParallelSearchConfig { /** * Mode preset for different use cases: * - "one-shot": Comprehensive results with longer excerpts for single-response answers (default) * - "agentic": Concise, token-efficient results for multi-step agentic workflows */ mode?: 'one-shot' | 'agentic'; /** * Default maximum number of results to return (1-20). * Defaults to 10 if not specified. */ maxResults?: number; /** * Default source policy for controlling which domains to include/exclude. */ sourcePolicy?: ParallelSearchSourcePolicy; /** * Default excerpt configuration for controlling result length. */ excerpts?: ParallelSearchExcerpts; /** * Default fetch policy for controlling content freshness. */ fetchPolicy?: ParallelSearchFetchPolicy; } interface ParallelSearchResult { /** URL of the search result */ url: string; /** Title of the search result */ title: string; /** Extracted text excerpt/content from the page */ excerpt: string; /** Publication date of the content (may be null) */ publishDate?: string | null; /** Relevance score for the result */ relevanceScore?: number; } interface ParallelSearchResponse { /** Unique identifier for this search request */ searchId: string; /** Array of search results */ results: ParallelSearchResult[]; } interface ParallelSearchError { /** Error type */ error: 'api_error' | 'rate_limit' | 'timeout' | 'invalid_input' | 'configuration_error' | 'unknown'; /** HTTP status code if applicable */ statusCode?: number; /** Human-readable error message */ message: string; } interface ParallelSearchInput { /** * Natural-language description of the web research goal. * Include source or freshness guidance and broader context from the task. * Maximum 5000 characters. */ objective: string; /** * Optional search queries to supplement the objective. * Maximum 200 characters per query. */ search_queries?: string[]; /** * Mode preset for different use cases: * - "one-shot": Comprehensive results with longer excerpts * - "agentic": Concise, token-efficient results for multi-step workflows */ mode?: 'one-shot' | 'agentic'; /** * Maximum number of results to return (1-20). * Defaults to 10 if not specified. */ max_results?: number; /** * Source policy for controlling which domains to include/exclude. */ source_policy?: { include_domains?: string[]; exclude_domains?: string[]; after_date?: string; }; /** * Excerpt configuration for controlling result length. */ excerpts?: { max_chars_per_result?: number; max_chars_total?: number; }; /** * Fetch policy for controlling content freshness. */ fetch_policy?: { max_age_seconds?: number; }; } type ParallelSearchOutput = ParallelSearchResponse | ParallelSearchError; declare const parallelSearchToolFactory: ProviderExecutedToolFactory; type ExaSearchType = 'auto' | 'fast' | 'instant'; type ExaSearchCategory = 'company' | 'people' | 'research paper' | 'news' | 'personal site' | 'financial report'; type ExaTextSection = 'header' | 'navigation' | 'banner' | 'body' | 'sidebar' | 'footer' | 'metadata'; interface ExaSearchTextConfig { maxCharacters?: number; includeHtmlTags?: boolean; verbosity?: 'compact' | 'standard' | 'full'; includeSections?: ExaTextSection[]; excludeSections?: ExaTextSection[]; } interface ExaSearchHighlightsConfig { query?: string; maxCharacters?: number; } interface ExaSearchExtrasConfig { links?: number; imageLinks?: number; } interface ExaSearchContentsConfig { text?: boolean | ExaSearchTextConfig; highlights?: boolean | ExaSearchHighlightsConfig; maxAgeHours?: number; livecrawlTimeout?: number; subpages?: number; subpageTarget?: string | string[]; extras?: ExaSearchExtrasConfig; } interface ExaSearchConfig { /** * Default search method. Exa defaults to auto when omitted. */ type?: ExaSearchType; /** * Default maximum number of results to return (1-100, default: 10). */ numResults?: number; /** * Default category filter for result types. */ category?: ExaSearchCategory; /** * Default two-letter ISO country code for location-aware search. */ userLocation?: string; /** * Default domains to include or exclude. */ includeDomains?: string[]; excludeDomains?: string[]; /** * Default published date filters in ISO 8601 format. */ startPublishedDate?: string; endPublishedDate?: string; /** * Default content extraction controls. */ contents?: ExaSearchContentsConfig; } interface ExaSearchResult { title: string; url: string; id: string; publishedDate?: string | null; author?: string | null; image?: string | null; favicon?: string | null; text?: string; highlights?: string[]; highlightScores?: number[]; summary?: string; subpages?: ExaSearchResult[]; extras?: { links?: string[]; imageLinks?: string[]; }; } interface ExaSearchResponse { requestId: string; searchType?: string; resolvedSearchType?: string; results: ExaSearchResult[]; costDollars?: { total?: number; search?: Record; }; } interface ExaSearchError { error: 'api_error' | 'rate_limit' | 'timeout' | 'invalid_input' | 'configuration_error' | 'execution_error' | 'unknown'; statusCode?: number; message: string; } interface ExaSearchInput { query: string; type?: ExaSearchType; num_results?: number; category?: ExaSearchCategory; user_location?: string; include_domains?: string[]; exclude_domains?: string[]; start_published_date?: string; end_published_date?: string; contents?: { text?: boolean | { max_characters?: number; include_html_tags?: boolean; verbosity?: 'compact' | 'standard' | 'full'; include_sections?: ExaTextSection[]; exclude_sections?: ExaTextSection[]; }; highlights?: boolean | { query?: string; max_characters?: number; }; max_age_hours?: number; livecrawl_timeout?: number; subpages?: number; subpage_target?: string | string[]; extras?: { links?: number; image_links?: number; }; }; } type ExaSearchOutput = ExaSearchResponse | ExaSearchError; declare const exaSearchToolFactory: ProviderExecutedToolFactory; /** * Gateway-specific provider-defined tools. */ declare const gatewayTools: { /** * Search the web using Exa for current information and token-efficient * excerpts optimized for agent workflows. * * Supports search type, category, domain, date, location, and content * extraction controls. */ exaSearch: (config?: ExaSearchConfig) => ReturnType; /** * Search the web using Parallel AI's Search API for LLM-optimized excerpts. * * Takes a natural language objective and returns relevant excerpts, * replacing multiple keyword searches with a single call for broad * or complex queries. Supports different search types for depth vs * breadth tradeoffs. */ parallelSearch: (config?: ParallelSearchConfig) => ReturnType; /** * Search the web using Perplexity's Search API for real-time information, * news, research papers, and articles. * * Provides ranked search results with advanced filtering options including * domain, language, date range, and recency filters. */ perplexitySearch: (config?: PerplexitySearchConfig) => ReturnType; }; interface GatewayProvider extends ProviderV4 { (modelId: GatewayModelId): LanguageModelV4; /** * Creates a model for text generation. */ chat(modelId: GatewayModelId): LanguageModelV4; /** * Creates a model for text generation. */ languageModel(modelId: GatewayModelId): LanguageModelV4; /** * Returns available providers and models for use with the remote provider. */ getAvailableModels(): Promise; /** * Returns credit information for the authenticated user. */ getCredits(): Promise; /** * Returns a spend report with cost, token, and request count data, * aggregated by the specified dimension. */ getSpendReport(params: GatewaySpendReportParams): Promise; /** * Returns detailed information about a specific generation by its ID, * including cost, token usage, latency, and provider details. */ getGenerationInfo(params: GatewayGenerationInfoParams): Promise; /** * Creates a model for generating text embeddings. */ embedding(modelId: GatewayEmbeddingModelId): EmbeddingModelV4; /** * Creates a model for generating text embeddings. */ embeddingModel(modelId: GatewayEmbeddingModelId): EmbeddingModelV4; /** * @deprecated Use `embeddingModel` instead. */ textEmbeddingModel(modelId: GatewayEmbeddingModelId): EmbeddingModelV4; /** * Creates a model for generating images. */ image(modelId: GatewayImageModelId): ImageModelV4; /** * Creates a model for generating images. */ imageModel(modelId: GatewayImageModelId): ImageModelV4; /** * Creates a model for generating videos. */ video(modelId: GatewayVideoModelId): VideoModelV4; /** * Creates a model for generating videos. */ videoModel(modelId: GatewayVideoModelId): VideoModelV4; /** * Creates a model for reranking documents. */ reranking(modelId: GatewayRerankingModelId): RerankingModelV4; /** * Creates a model for reranking documents. */ rerankingModel(modelId: GatewayRerankingModelId): RerankingModelV4; /** * Creates a model for text-to-speech generation. */ speech(modelId: GatewaySpeechModelId): SpeechModelV4; /** * Creates a model for text-to-speech generation. */ speechModel(modelId: GatewaySpeechModelId): SpeechModelV4; /** * Creates a model for audio transcription. */ transcription(modelId: GatewayTranscriptionModelId): TranscriptionModelV4; /** * Creates a model for audio transcription. */ transcriptionModel(modelId: GatewayTranscriptionModelId): TranscriptionModelV4; /** * Creates an experimental realtime model for bidirectional audio/text * communication over WebSocket, normalized through the AI Gateway. */ experimental_realtime: RealtimeFactoryV4; /** * Experimental streaming-transcription entry point. Callable like * `transcription(modelId)`, plus `getToken` for minting a short-lived * client secret (`vcst_`) a browser can use to open the streaming * transcription WebSocket without holding the Gateway credential. */ experimental_transcription: GatewayTranscriptionFactory; /** * Gateway-specific tools executed server-side. */ tools: typeof gatewayTools; } type GatewayTranscriptionFactoryGetTokenOptions = { model: GatewayTranscriptionModelId; /** Token lifetime in seconds. Gateway default is 60s (max 300s). */ expiresAfterSeconds?: number; }; type GatewayTranscriptionFactoryGetTokenResult = { /** The minted `vcst_` client secret. */token: string; /** WebSocket URL of the streaming transcription surface for this model. */ url: string; /** Token expiry, epoch seconds. */ expiresAt?: number; }; /** * Streaming-transcription factory: callable like `transcription(modelId)`, * plus a server-side `getToken` that mints a transcription-bound short-lived * client secret (`vcst_`). The browser connects with * `createGateway({ apiKey: token }).transcription(modelId)` — the token rides * the same auth subprotocol an API key does, without exposing the credential. */ interface GatewayTranscriptionFactory { (modelId: GatewayTranscriptionModelId): TranscriptionModelV4; getToken(options: GatewayTranscriptionFactoryGetTokenOptions): Promise; } interface GatewayProviderSettings { /** * The base URL prefix for API calls. Defaults to `https://ai-gateway.vercel.sh/v4/ai`. */ baseURL?: string; /** * API key or Vercel access token that is being sent using the `Authorization` * header. It defaults to the `AI_GATEWAY_API_KEY` environment variable. */ apiKey?: string; /** * Vercel team ID or slug to scope requests for access tokens that can access * multiple teams. */ teamIdOrSlug?: string; /** * Custom headers to include in the requests. */ headers?: Record; /** * Custom fetch implementation. You can use it as a middleware to intercept requests, * or to provide a custom fetch implementation for e.g. testing. */ fetch?: FetchFunction; /** * Custom WebSocket implementation used for streaming transcription. This is * useful for testing or for runtimes without a global WebSocket. A * header-capable implementation is not required — Gateway WebSocket auth is * carried in the subprotocols. */ webSocket?: WebSocketConstructor; /** * How frequently to refresh the metadata cache in milliseconds. */ metadataCacheRefreshMillis?: number; } /** * Create a remote provider instance. */ declare function createGateway(options?: GatewayProviderSettings): GatewayProvider; declare const gateway: GatewayProvider; declare namespace index_d_exports { export { AISDKError, AI_SDK_TELEMETRY_TRACING_CHANNEL, APICallError, AbstractChat, ActiveTools, Agent$1 as Agent, AgentCallParameters, AgentStreamParameters, AssistantContent, AssistantModelMessage, AsyncIterableStream, CallSettings, CallWarning, ChatAddToolApproveResponseFunction, ChatAddToolOutputFunction, ChatInit, ChatOnDataCallback, ChatOnErrorCallback, ChatOnFinishCallback, ChatOnToolCallCallback, ChatRequestOptions, ChatState, ChatStatus, ChatTransport, ChunkDetector, CompletionRequestOptions, ContentPart, CreateUIMessage, CustomContentUIPart, DataContent, DataUIPart, DeepPartial, DefaultChatTransport, DefaultGeneratedFile, DirectChatTransport, DirectChatTransportOptions, DownloadError, DynamicToolCall, DynamicToolError, DynamicToolResult, DynamicToolUIPart, EmbedEndEvent, EmbedManyResult, EmbedResult, EmbedStartEvent, Embedding, EmbeddingModel, EmbeddingModelCallEndEvent, EmbeddingModelCallStartEvent, EmbeddingModelMiddleware, EmbeddingModelUsage, EmptyResponseBodyError, ErrorHandler, AbstractRealtimeSession as Experimental_AbstractRealtimeSession, ToolLoopAgent as Experimental_Agent, ToolLoopAgentSettings as Experimental_AgentSettings, BatchError as Experimental_BatchError, BatchLanguageModel as Experimental_BatchLanguageModel, BatchOperationOptions as Experimental_BatchOperationOptions, BatchReference as Experimental_BatchReference, BatchStatus as Experimental_BatchStatus, DownloadFunction as Experimental_DownloadFunction, Experimental_GeneratedImage, InferAgentUIMessage as Experimental_InferAgentUIMessage, LanguageModelStreamPart as Experimental_LanguageModelStreamPart, LogWarningsFunction as Experimental_LogWarningsFunction, RealtimeClientEvent as Experimental_RealtimeClientEvent, RealtimeFactory as Experimental_RealtimeFactory, RealtimeFactoryGetTokenOptions as Experimental_RealtimeFactoryGetTokenOptions, RealtimeFactoryGetTokenResult as Experimental_RealtimeFactoryGetTokenResult, RealtimeModel as Experimental_RealtimeModel, RealtimeServerEvent as Experimental_RealtimeServerEvent, RealtimeSessionConfig as Experimental_RealtimeSessionConfig, RealtimeSessionOptions as Experimental_RealtimeSessionOptions, RealtimeSetupResponse as Experimental_RealtimeSetupResponse, RealtimeState as Experimental_RealtimeState, RealtimeStatus as Experimental_RealtimeStatus, RealtimeToolDefinition as Experimental_RealtimeToolDefinition, SandboxProcess as Experimental_SandboxProcess, SandboxSession as Experimental_SandboxSession, Experimental_SpeechResult, StartTextBatchOptions as Experimental_StartTextBatchOptions, StartTextBatchResult as Experimental_StartTextBatchResult, StreamTranslationResult as Experimental_StreamTranslationResult, TextBatch as Experimental_TextBatch, TextBatchGenerationResult as Experimental_TextBatchGenerationResult, TextBatchItemResult as Experimental_TextBatchItemResult, TextBatchReference as Experimental_TextBatchReference, TextBatchRequest as Experimental_TextBatchRequest, ToolCallerTool as Experimental_ToolCallerTool, Experimental_ToolCallers, Experimental_TranscriptionResult, TranslationStreamPart as Experimental_TranslationStreamPart, FilePart, FileUIPart, FinishReason, FlexibleSchema, GatewayModelId, GenerateImageResult, GenerateObjectEndEvent, GenerateObjectResult, GenerateObjectStartEvent, GenerateObjectStepEndEvent, GenerateObjectStepStartEvent, GenerateTextAbortEvent, GenerateTextEndEvent, GenerateTextInclude, GenerateTextOnAbortCallback, GenerateTextOnEndCallback, GenerateTextOnFinishCallback, GenerateTextOnStartCallback, GenerateTextOnStepEndCallback, GenerateTextOnStepFinishCallback, GenerateTextOnStepStartCallback, GenerateTextResult, GenerateTextStartEvent, GenerateTextStepEndEvent, GenerateTextStepStartEvent, GenerateVideoPrompt, GenerateVideoResult, GeneratedAudioFile, GeneratedFile, GenericToolApprovalFunction, HttpChatTransport, HttpChatTransportInitOptions, IdGenerator, ImageModel, ImageModelMiddleware, ImageModelProviderMetadata, ImageModelResponseMetadata, ImageModelUsage, ImagePart, InferAgentUIMessage, InferCompleteOutput as InferGenerateOutput, InferSchema, InferPartialOutput as InferStreamOutput, InferTelemetryEvent, InferToolInput, InferToolOutput, InferUIDataParts, InferUIMessageChunk, InferUITool, InferUITools, Instructions, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidPromptError, InvalidResponseDataError, InvalidStreamPartError, InvalidToolApprovalError, InvalidToolApprovalSignatureError, InvalidToolInputError, JSONParseError, JSONSchema7$1 as JSONSchema7, JSONValue, JsonToSseTransformStream, LanguageModel, LanguageModelCallEndEvent, LanguageModelCallOptions, LanguageModelCallStartEvent, LanguageModelMiddleware, LanguageModelRequestMetadata, LanguageModelResponseMetadata, LanguageModelUsage, LoadAPIKeyError, LoadSettingError, LogWarningsFunction, MessageConversionError, MissingToolResultsError, ModelInfo, ModelMessage, NoContentGeneratedError, NoImageGeneratedError, NoObjectGeneratedError, NoOutputGeneratedError, NoSpeechGeneratedError, NoSuchModelError, NoSuchProviderError, NoSuchProviderReferenceError, NoSuchToolError, NoTranscriptGeneratedError, NoTranslationGeneratedError, NoVideoGeneratedError, ObjectStreamPart, OnFinishEvent, OnLanguageModelCallEndCallback, OnLanguageModelCallStartCallback, OnStartEvent, OnStepFinishEvent, OnStepStartEvent, OnToolCallFinishEvent, OnToolCallStartEvent, OnToolExecutionEndCallback, OnToolExecutionStartCallback, output as Output, OutputChunkTimingStats, Output as OutputInterface, PrepareReconnectToStreamRequest, PrepareSendMessagesRequest, PrepareStepFunction, PrepareStepResult, Prompt, Provider, ProviderMetadata, ProviderReference, ProviderRegistryProvider, ReasoningFileOutput, ReasoningFileUIPart, ReasoningOutput, ReasoningUIPart, RepairTextFunction, RequestOptions, RerankEndEvent, RerankResult, RerankStartEvent, RerankingModel, RerankingModelCallEndEvent, RerankingModelCallStartEvent, RetryError, SafeValidateUIMessagesResult, Schema, SerialJobExecutor, SingleToolApprovalFunction, SourceDocumentUIPart, SourceUrlUIPart, SpeechModel, SpeechModelResponseMetadata, SpeechResult, StaticToolCall, StaticToolError, StaticToolOutputDenied, StaticToolResult, StepResult, StepResultPerformance, StepStartUIPart, StopCondition, StreamObjectOnFinishCallback, StreamObjectResult, StreamTextInclude, StreamTextOnChunkCallback, StreamTextOnErrorCallback, StreamTextResult, StreamTextTransform, StreamTranscriptionResult, SystemModelMessage, Telemetry, TelemetryOptions, TelemetryTracingChannelMessage, TelemetryTracingEventType, TextPart, TextStreamChatTransport, TextStreamPart, TextUIPart, TimeoutConfiguration, ToUIMessageChunkOptions, TooManyEmbeddingValuesForCallError, Tool, ToolApprovalConfiguration, ToolApprovalRequest, ToolApprovalRequestOutput, ToolApprovalResponse, ToolApprovalResponseOutput, ToolApprovalStatus, ToolCallNotFoundForApprovalError, ToolCallPart, ToolCallRepairError, ToolCallRepairFunction, ToolChoice, ToolContent, ToolExecuteFunction, ToolExecutionEndEvent, ToolExecutionOptions, ToolExecutionStartEvent, ToolInputRefinement, ToolLoopAgent, ToolLoopAgentSettings, ToolModelMessage, ToolOrder, ToolResultPart, ToolSet, ToolUIPart, TranscriptionModel, TranscriptionModelResponseMetadata, TranscriptionResult, TranscriptionStreamPart, TypeValidationError, TypedToolCall, TypedToolError, TypedToolOutputDenied, TypedToolResult, UIDataPartSchemas, UIDataTypes, UIMessage, UIMessageChunk, UIMessagePart, UIMessageStreamError, UIMessageStreamOnEndCallback, UIMessageStreamOnFinishCallback, UIMessageStreamOnStepEndCallback, UIMessageStreamOnStepFinishCallback, UIMessageStreamOptions, UIMessageStreamWriter, UITool, UIToolInvocation, UITools, UI_MESSAGE_STREAM_HEADERS, UnsupportedFunctionalityError, UnsupportedModelVersionError, UploadFileResult, UploadSkillResult, UseCompletionOptions, UserContent, UserModelMessage, Warning, addToolInputExamplesMiddleware, asSchema, assistantModelMessageSchema, callCompletionApi, consumeStream, convertDataContentToBase64String, convertFileListToFileUIParts, convertToModelMessages, cosineSimilarity, createAgentUIStream, createAgentUIStreamResponse, createDownload, createGateway, createIdGenerator, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, defaultEmbeddingSettingsMiddleware, defaultInstructionsMiddleware, defaultSettingsMiddleware, detectToolDrift, dynamicTool, embed, embedMany, experimental_createProviderRegistry, decodeRealtimeAudio as experimental_decodeRealtimeAudio, encodeRealtimeAudio as experimental_encodeRealtimeAudio, filterActiveTools as experimental_filterActiveTools, experimental_generateSpeech, experimental_generateVideo, getBatchResults as experimental_getBatchResults, getBatchStatus as experimental_getBatchStatus, getRealtimeToolDefinitions as experimental_getRealtimeToolDefinitions, resampleAudio as experimental_resampleAudio, startTextBatch as experimental_startTextBatch, streamLanguageModelCall as experimental_streamLanguageModelCall, streamTranscribe as experimental_streamTranscribe, streamTranslate as experimental_streamTranslate, toolCaller as experimental_toolCaller, experimental_transcribe, extractJsonMiddleware, extractReasoningMiddleware, fingerprintTools, gateway, generateId$1 as generateId, generateImage, generateObject, generateSpeech, generateText, getChunkTimeoutMs, getFirstChunkTimeoutMs, getStaticToolName, getStepTimeoutMs, getTextFromDataUrl, getToolName, getToolOrDynamicToolName, getToolTimeoutMs, getTotalTimeoutMs, hasToolCall, isCustomContentUIPart, isDataUIPart, isDeepEqualData, isDynamicToolUIPart, isFileUIPart, isLoopFinished, isReasoningFileUIPart, isReasoningUIPart, isStaticToolUIPart, isStepCount, isTextUIPart, isToolUIPart, jsonSchema, lastAssistantMessageIsCompleteWithApprovalResponses, lastAssistantMessageIsCompleteWithToolCalls, modelMessageSchema, parseJsonEventStream, parsePartialJson, pipeAgentUIStreamToResponse, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, pruneMessages, readUIMessageStream, registerTelemetry, rerank, safeValidateUIMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, isStepCount as stepCountIs, streamObject, streamText, systemModelMessageSchema, toTextStream, toUIMessageChunk, toUIMessageStream, tool$1 as tool, toolModelMessageSchema, transcribe, uiMessageChunkSchema, uploadFile, uploadSkill, userModelMessageSchema, validateUIMessages, wrapEmbeddingModel, wrapImageModel, wrapLanguageModel$1 as wrapLanguageModel, wrapProvider, zodSchema }; } /** * Embedding model that is used by the AI SDK. */ type EmbeddingModel = string | EmbeddingModelV4 | EmbeddingModelV3 | EmbeddingModelV2; /** * Embedding. */ type Embedding = EmbeddingModelV4Embedding; /** * Middleware for embedding models. * Accepts both V3 and V4 middleware types for backward compatibility. * * Uses EmbeddingModelV4Middleware as the base but relaxes specificationVersion * to accept any string (including 'v3') and makes it optional. */ type EmbeddingModelMiddleware = Omit & { readonly specificationVersion?: string; }; /** * Image model that is used by the AI SDK. */ type ImageModel = string | ImageModelV4 | ImageModelV3 | ImageModelV2; /** * Metadata from the model provider for this call. */ type ImageModelProviderMetadata = ImageModelV4ProviderMetadata | ImageModelV2ProviderMetadata; /** * Middleware for image models. * Accepts both V3 and V4 middleware types for backward compatibility. * * Uses ImageModelV4Middleware as the base but relaxes specificationVersion * to accept any string (including 'v3') and makes it optional. */ type ImageModelMiddleware = Omit & { readonly specificationVersion?: string; }; type ImageModelResponseMetadata = { /** * 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; }; type JSONValue = JSONValue$3; declare global { /** * Global interface that can be augmented by third-party packages to register custom model IDs. * * You can register model IDs in two ways: * * 1. Register based on Model IDs from a provider package: * @example * ```typescript * import { openai } from '@ai-sdk/openai'; * type OpenAIResponsesModelId = Parameters[0]; * * declare global { * interface RegisteredProviderModels { * openai: OpenAIResponsesModelId; * } * } * ``` * * 2. Register individual model IDs directly as keys: * @example * ```typescript * declare global { * interface RegisteredProviderModels { * 'my-provider:my-model': any; * 'my-provider:another-model': any; * } * } * ``` */ interface RegisteredProviderModels {} } /** * Global provider model ID type that defaults to GatewayModelId but can be augmented * by third-party packages via declaration merging. */ type GlobalProviderModelId = [keyof RegisteredProviderModels] extends [never] ? GatewayModelId : keyof RegisteredProviderModels | RegisteredProviderModels[keyof RegisteredProviderModels]; /** * Language model that is used by the AI SDK. */ type LanguageModel = GlobalProviderModelId | LanguageModelV4 | LanguageModelV3$1 | LanguageModelV2$1; /** * 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 = 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other'; /** * 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 = SharedV4Warning; /** * A source that has been used as input to generate the response. */ type Source = LanguageModelV4Source; /** * 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 ToolChoice> = 'auto' | 'none' | 'required' | { type: 'tool'; toolName: Extract; }; /** * Middleware for language models. * Accepts both V3 and V4 middleware types for backward compatibility. * * Uses LanguageModelV4Middleware as the base but relaxes specificationVersion * to accept any string (including 'v3') and makes it optional. */ type LanguageModelMiddleware = Omit & { readonly specificationVersion?: string; }; /** * Metadata for a language model request. */ type LanguageModelRequestMetadata = { /** * The input messages that were sent to the model for this step. */ readonly messages?: Array; /** * Request HTTP body that was sent to the provider API. */ readonly body?: unknown; }; /** * A message that was generated during the generation process. * It can be either an assistant message or a tool message. */ type ResponseMessage = AssistantModelMessage | ToolModelMessage; /** * Metadata for a language model response. */ type LanguageModelResponseMetadata = { /** * The response messages that were generated during the call. * Response messages can be either assistant messages or tool messages. * They contain a generated id. */ readonly messages: Array; /** * ID for the generated response. */ readonly id: string; /** * Timestamp for the start of the generated response. */ readonly timestamp: Date; /** * The ID of the response model that was used to generate the response. */ readonly modelId: string; /** * Response headers (available only for providers that use HTTP requests). */ readonly headers?: Record; /** * Response body (available only for providers that use HTTP requests). */ readonly body?: unknown; }; /** * Reranking model that is used by the AI SDK. */ type RerankingModel = string | RerankingModelV4 | RerankingModelV3; /** * Provider for language, text embedding, and image 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} modelId - 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} modelId - The id of the model to return. * * @returns {EmbeddingModel} The embedding model associated with the id * * @throws {NoSuchModelError} If no such model exists. */ embeddingModel(modelId: string): EmbeddingModel; /** * Returns the image model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {ImageModel} The image model associated with the id */ imageModel(modelId: string): ImageModel; /** * Returns the reranking model with the given id. * The model id is then passed to the provider function to get the model. * * @param {string} modelId - The id of the model to return. * * @returns {RerankingModel} The reranking model associated with the id * * @throws {NoSuchModelError} If no such model exists. */ rerankingModel?(modelId: string): RerankingModel; }; /** * Additional provider-specific metadata that is returned from the provider. * * This is needed to enable provider-specific functionality that can be * fully encapsulated in the provider. */ type ProviderMetadata = SharedV4ProviderMetadata; type ProviderReference = SharedV4ProviderReference; /** * Speech model that is used by the AI SDK. */ type SpeechModel = string | SpeechModelV4 | SpeechModelV3 | SpeechModelV2; type SpeechModelResponseMetadata = { /** * 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; /** * Response body. */ body?: unknown; }; /** * Transcription model that is used by the AI SDK. */ type TranscriptionModel = string | TranscriptionModelV4 | TranscriptionModelV3 | TranscriptionModelV2; type TranscriptionModelResponseMetadata = { /** * 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; }; /** * Represents the number of tokens used in a prompt and completion. */ type LanguageModelUsage = { /** * The total number of input (prompt) tokens used. */ inputTokens: number | undefined; /** * Detailed information about the input tokens. */ inputTokenDetails: { /** * The number of non-cached input (prompt) tokens used. */ noCacheTokens: number | undefined; /** * The number of cached input (prompt) tokens read. */ cacheReadTokens: number | undefined; /** * The number of cached input (prompt) tokens written. */ cacheWriteTokens: number | undefined; }; /** * The number of total output (completion) tokens used. */ outputTokens: number | undefined; /** * Detailed information about the output tokens. */ outputTokenDetails: { /** * The number of text tokens used. */ textTokens: number | undefined; /** * The number of reasoning tokens used. */ reasoningTokens: number | undefined; }; /** * The total number of tokens used. */ totalTokens: number | undefined; /** * Raw usage information from the provider. * * This is the usage information in the shape that the provider returns. * It can include additional information that is not part of the standard usage information. */ raw?: JSONObject$2; }; /** * Represents the number of tokens used in an embedding. */ type EmbeddingModelUsage = { /** * The number of tokens used in the embedding. */ tokens: number; }; /** * Usage information for an image model call. */ type ImageModelUsage = ImageModelV4Usage; /** * 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 Warning = SharedV4Warning; /** * A function for logging warnings. * * You can assign it to the `AI_SDK_LOG_WARNINGS` global variable to use it as the default warning logger. * * @example * ```ts * globalThis.AI_SDK_LOG_WARNINGS = (options) => { * console.log('WARNINGS:', options.warnings, options.provider, options.model); * }; * ``` */ type LogWarningsFunction = (options: { /** * The warnings returned by the model provider. */ warnings: Warning[]; /** * The provider id used for the call, if scoped to a specific provider. */ provider?: string; /** * The model id used for the call, if scoped to a specific provider. */ model?: string; }) => void; /** * Event passed to the `onStart` callback for embed and embedMany operations. * * Called when the operation begins, before the embedding model is called. */ type EmbedStartEvent = { /** Unique identifier for this embed call, used to correlate events. */readonly callId: string; /** Identifies the operation type (e.g. 'ai.embed' or 'ai.embedMany'). */ readonly operationId: string; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'text-embedding-3-small'). */ readonly modelId: string; /** The value(s) being embedded. A string for embed, an array for embedMany. */ readonly value: string | Array; /** Maximum number of retries for failed requests. */ readonly maxRetries: number; /** Additional HTTP headers sent with the request. */ readonly headers: Record | undefined; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions | undefined; }; /** * Event passed to the `onEnd` callback for embed and embedMany operations. * * Called when the operation completes, after the embedding model returns. */ type EmbedEndEvent = { /** Unique identifier for this embed call, used to correlate events. */readonly callId: string; /** Identifies the operation type (e.g. 'ai.embed' or 'ai.embedMany'). */ readonly operationId: string; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'text-embedding-3-small'). */ readonly modelId: string; /** The value(s) that were embedded. A string for embed, an array for embedMany. */ readonly value: string | Array; /** The resulting embedding(s). A single vector for embed, an array for embedMany. */ readonly embedding: Embedding | Array; /** Token usage for the embedding operation. */ readonly usage: EmbeddingModelUsage; /** Warnings from the embedding model, e.g. unsupported settings. */ readonly warnings: Array; /** Optional provider-specific metadata. */ readonly providerMetadata: ProviderMetadata | undefined; /** Response data including headers and body. A single response for embed, an array for embedMany. */ readonly response: { headers?: Record; body?: unknown; } | Array<{ headers?: Record; body?: unknown; } | undefined> | undefined; }; /** * Event fired when an individual embedding model call (inner operation doEmbed) begins. * * For `embed`, there is one call. For `embedMany`, there may be multiple * calls when values are chunked. */ type EmbeddingModelCallStartEvent = { /** Unique identifier for this embed call, used to correlate events. */readonly callId: string; /** Unique identifier for this individual doEmbed invocation, used to correlate start/finish within parallel chunks. */ readonly embedCallId: string; /** Identifies the inner operation (e.g. 'ai.embed.doEmbed' or 'ai.embedMany.doEmbed'). */ readonly operationId: string; /** The provider identifier. */ readonly provider: string; /** The specific model identifier. */ readonly modelId: string; /** The values being embedded in this particular model call. */ readonly values: Array; }; /** * Event fired when an individual embedding model call (doEmbed) completes. * * Contains the embeddings, usage, and any warnings from the model response. */ type EmbeddingModelCallEndEvent = { /** Unique identifier for this embed call, used to correlate events. */readonly callId: string; /** Unique identifier for this individual doEmbed invocation, used to correlate start/finish within parallel chunks. */ readonly embedCallId: string; /** Identifies the inner operation (e.g. 'ai.embed.doEmbed' or 'ai.embedMany.doEmbed'). */ readonly operationId: string; /** The provider identifier. */ readonly provider: string; /** The specific model identifier. */ readonly modelId: string; /** The values that were embedded in this particular model call. */ readonly values: Array; /** The resulting embeddings from the model call. */ readonly embeddings: Array; /** Token usage for this model call. */ readonly usage: EmbeddingModelUsage; }; /** * Model-facing generation controls. These settings influence how the model * generates its response (token limits, sampling, penalties, stop sequences, * seed, reasoning). */ type LanguageModelCallOptions = { /** * Maximum number of tokens to generate. */ maxOutputTokens?: number; /** * Temperature setting. The range depends on the provider and model. * * It is recommended to set either `temperature` or `topP`, but not both. */ 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; /** * Reasoning effort level for the model. Controls how much reasoning * the model performs before generating a response. * * Use `'provider-default'` to use the provider's default reasoning level. * Use `'none'` to disable reasoning (if supported by the provider). */ reasoning?: LanguageModelV4CallOptions['reasoning']; }; /** * Timeout configuration for API calls. Can be specified as: * - A number representing milliseconds * - An object with `totalMs` property for the total timeout in milliseconds * - An object with `stepMs` property for the timeout of each step in milliseconds * - An object with `firstChunkMs` property for the timeout until the first content chunk of each step (streaming only) * - An object with `chunkMs` property for the timeout between content chunks (streaming only) * - An object with `toolMs` property for the default timeout for all tool executions * - An object with `tools` property for per-tool timeout overrides using `{toolName}Ms` keys */ type TimeoutConfiguration = number | { totalMs?: number; stepMs?: number; firstChunkMs?: number; chunkMs?: number; toolMs?: number; tools?: Partial>; }; /** * Extracts the total timeout value in milliseconds from a TimeoutConfiguration. * * @param timeout - The timeout configuration. * @returns The total timeout in milliseconds, or undefined if no timeout is configured. */ declare function getTotalTimeoutMs(timeout: TimeoutConfiguration | undefined): number | undefined; /** * Extracts the step timeout value in milliseconds from a TimeoutConfiguration. * * @param timeout - The timeout configuration. * @returns The step timeout in milliseconds, or undefined if no step timeout is configured. */ declare function getStepTimeoutMs(timeout: TimeoutConfiguration | undefined): number | undefined; /** * Extracts the first chunk timeout value in milliseconds from a TimeoutConfiguration. * This timeout is for streaming only - it aborts if no content chunk is received within the specified duration. * * @param timeout - The timeout configuration. * @returns The first chunk timeout in milliseconds, or undefined if no first chunk timeout is configured. */ declare function getFirstChunkTimeoutMs(timeout: TimeoutConfiguration | undefined): number | undefined; /** * Extracts the chunk timeout value in milliseconds from a TimeoutConfiguration. * This timeout is for streaming only - it aborts if no new content chunk is received within the specified duration. * * @param timeout - The timeout configuration. * @returns The chunk timeout in milliseconds, or undefined if no chunk timeout is configured. */ declare function getChunkTimeoutMs(timeout: TimeoutConfiguration | undefined): number | undefined; declare function getToolTimeoutMs(timeout: TimeoutConfiguration | undefined, toolName: keyof TOOLS & string): number | undefined; /** * Request-facing controls. These settings affect transport, retries, * cancellation, headers, and timeout – not model generation behavior. */ type RequestOptions = { /** * 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; /** * Timeout configuration for the request. */ timeout?: TimeoutConfiguration; }; declare const systemModelMessageSchema: ZodType; declare const userModelMessageSchema: ZodType; declare const assistantModelMessageSchema: ZodType; declare const toolModelMessageSchema: ZodType; declare const modelMessageSchema: ZodType; /** * Instructions to include in the prompt. Can be used with `prompt` or `messages`. */ type Instructions = string | SystemModelMessage | Array; /** * Prompt part of the AI function options. * It contains instructions, a simple text prompt, or a list of messages. */ type Prompt = { /** * Instructions to include in the prompt. Can be used with `prompt` or `messages`. */ instructions?: Instructions; /** * Instructions to include in the prompt. Can be used with `prompt` or `messages`. * * @deprecated Use `instructions` instead. */ system?: Instructions; /** * Whether system messages are allowed in the `prompt` or `messages` fields. * * When disabled, system messages must be provided through the `instructions` * option. * * @default false */ allowSystemInMessages?: boolean; } & ({ /** * A prompt. It can be either a text prompt or a list of messages. * * You can either use `prompt` or `messages` but not both. */ prompt: string | Array; /** * A list of messages. * * You can either use `prompt` or `messages` but not both. */ messages?: never; } | { /** * A list of messages. * * You can either use `prompt` or `messages` but not both. */ messages: Array; /** * A prompt. It can be either a text prompt or a list of messages. * * You can either use `prompt` or `messages` but not both. */ prompt?: never; }); /** * Converts data content to a base64-encoded string. * * @param content - Data content to convert. * @returns Base64-encoded string. */ declare function convertDataContentToBase64String(content: DataContent): string; /** @deprecated Use `LanguageModelCallOptions` combined with `RequestOptions` instead. */ type CallSettings = LanguageModelCallOptions & Omit; /** * Event passed to the `onStart` callback of * `generateObject` and `streamObject`. * * Called when the operation begins, before any LLM call. * * @deprecated */ interface GenerateObjectStartEvent { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** Identifies the operation type (e.g. `'ai.generateObject'` or `'ai.streamObject'`). */ readonly operationId: string; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** The system message(s) provided to the model. */ readonly system: Instructions | undefined; /** The prompt string or array of messages if using the prompt option. */ readonly prompt: string | Array | undefined; /** The messages array if using the messages option. */ readonly messages: Array | undefined; /** Maximum number of tokens to generate. */ readonly maxOutputTokens: number | undefined; /** Sampling temperature for generation. */ readonly temperature: number | undefined; /** Top-p (nucleus) sampling parameter. */ readonly topP: number | undefined; /** Top-k sampling parameter. */ readonly topK: number | undefined; /** Presence penalty for generation. */ readonly presencePenalty: number | undefined; /** Frequency penalty for generation. */ readonly frequencyPenalty: number | undefined; /** Random seed for reproducible generation. */ readonly seed: number | undefined; /** Maximum number of retries for failed requests. */ readonly maxRetries: number; /** Additional HTTP headers sent with the request. */ readonly headers: Record | undefined; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions | undefined; /** The output strategy type. */ readonly output: 'object' | 'array' | 'enum' | 'no-schema'; /** The JSON Schema used for object generation, if any. */ readonly schema: Record | undefined; /** Optional name of the schema. */ readonly schemaName: string | undefined; /** Optional description of the schema. */ readonly schemaDescription: string | undefined; } /** * Event passed to the `onStepStart` callback of * `generateObject` and `streamObject`. * * Called when the model call (step) begins, before the provider is called. * For object generation, there is always exactly one step (step 0). * * @deprecated */ interface GenerateObjectStepStartEvent { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** Zero-based index of the current step. Always `0` for object generation. */ readonly stepNumber: 0; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions | undefined; /** Additional HTTP headers sent with the request. */ readonly headers: Record | undefined; /** The prompt messages in provider format (for telemetry). */ readonly promptMessages?: LanguageModelV4Prompt; } /** * Event passed to the `onStepEnd` callback of * `generateObject` and `streamObject`. * * Called when the model call (step) completes, with the raw result * before JSON parsing and schema validation. * * @deprecated */ interface GenerateObjectStepEndEvent { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** Zero-based index of the current step. Always `0` for object generation. */ readonly stepNumber: 0; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** The unified reason why the generation finished. */ readonly finishReason: FinishReason; /** The token usage of the generated response. */ readonly usage: LanguageModelUsage; /** The raw text output from the model (before JSON parsing). */ readonly objectText: string; /** The reasoning generated by the model, if any. */ readonly reasoning: string | undefined; /** Warnings from the model provider (e.g. unsupported settings). */ readonly warnings: CallWarning[] | undefined; /** Additional request information. */ readonly request: Omit; /** Additional response information. */ readonly response: Omit; /** Additional provider-specific metadata. */ readonly providerMetadata: ProviderMetadata | undefined; /** Milliseconds from the start of the stream to the first chunk (streaming only). */ readonly msToFirstChunk: number | undefined; } /** * Event passed to the `onFinish` callback of * `generateObject` and `streamObject`. * * Called when the entire operation completes, including JSON parsing * and schema validation. For `streamObject`, the object may be undefined * if validation failed (the error is provided in that case). * * @deprecated */ interface GenerateObjectEndEvent { /** Unique identifier for this generation call, used to correlate events. */ readonly callId: string; /** * The generated object (typed according to the schema). * Always defined for `generateObject`. May be `undefined` for `streamObject` * when parsing or validation fails. */ readonly object: RESULT | undefined; /** * Error from parsing or schema validation, if any. * Always `undefined` for `generateObject` (which throws instead). */ readonly error: unknown | undefined; /** The reasoning generated by the model, if any. */ readonly reasoning: string | undefined; /** The unified reason why the generation finished. */ readonly finishReason: FinishReason; /** The token usage of the generated response. */ readonly usage: LanguageModelUsage; /** Warnings from the model provider (e.g. unsupported settings). */ readonly warnings: CallWarning[] | undefined; /** Additional request information. */ readonly request: Omit; /** Additional response information. */ readonly response: Omit; /** Additional provider-specific metadata. */ readonly providerMetadata: ProviderMetadata | undefined; } type StandardizedPrompt = { /** * Instructions. */ instructions: Instructions | undefined; /** * Messages. */ messages: ModelMessage[]; }; /** * A callback function that can be used with `notify`. */ type Callback = (event: EVENT) => PromiseLike | void; /** * Tool names that are enabled for a generation step. * * `undefined` means no tool restriction is applied. Tool names are object keys * at runtime, so the type is restricted to the string keys of the configured * tool set. */ type ActiveTools = ReadonlyArray | undefined; /** * Create a type from an object with all keys and nested keys set to optional. * The helper supports normal objects and schemas (which are resolved automatically). * It always recurses into arrays. * * Adopted from [type-fest](https://github.com/sindresorhus/type-fest/tree/main) PartialDeep. */ type DeepPartial = T extends FlexibleSchema ? DeepPartialInternal> : DeepPartialInternal; type DeepPartialInternal = T extends null | undefined | string | number | boolean | symbol | bigint | void | Date | RegExp | ((...arguments_: any[]) => unknown) | (new (...arguments_: any[]) => unknown) ? T : T extends Map ? PartialMap : T extends Set ? PartialSet : T extends ReadonlyMap ? PartialReadonlyMap : T extends ReadonlySet ? PartialReadonlySet : T extends object ? T extends ReadonlyArray ? ItemType[] extends T ? readonly ItemType[] extends T ? ReadonlyArray> : Array> : PartialObject : PartialObject : unknown; type PartialMap = {} & Map, DeepPartialInternal>; type PartialSet = {} & Set>; type PartialReadonlyMap = {} & ReadonlyMap, DeepPartialInternal>; type PartialReadonlySet = {} & ReadonlySet>; type PartialObject = { [KeyType in keyof ObjectType]?: DeepPartialInternal }; type IncludedContext = { [KEY in keyof NoInfer]?: boolean } | undefined; type IncludedToolsContext = { [TOOL_NAME in keyof NoInfer>]?: IncludedContext[TOOL_NAME]>> } | undefined; /** * Telemetry configuration. */ type TelemetryOptions = { /** * Enable or disable telemetry. Enabled by default when a telemetry * integration is registered. Set to `false` to opt out. */ 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; /** * Top-level runtime context properties that should be included in telemetry. * Runtime context properties are excluded unless they are explicitly set to `true`. */ includeRuntimeContext?: IncludedContext; /** * Top-level tool context properties that should be included in telemetry, * configured per tool. * * Tool context properties are excluded unless they are explicitly set to `true`. */ includeToolsContext?: IncludedToolsContext; /** * Per-call telemetry integrations that receive lifecycle events during generation. * * When provided, these integrations will take precedence over the globally registered * integrations for this call. */ integrations?: Arrayable; }; /** * Experimental. Can change in patch versions without warning. * * Download function. Called with the array of URLs and a boolean indicating * whether the URL is supported by the model. * * The download function can decide for each URL: * - to return null (which means that the URL should be passed to the model) * - to download the asset and return the data (incl. retries, authentication, etc.) * * Should throw DownloadError if the download fails. * * Should return an array of objects sorted by the order of the requested downloads. * For each object, the data should be a Uint8Array if the URL was downloaded. * For each object, the mediaType should be the media type of the downloaded asset. * For each object, the data should be null if the URL should be passed through as is. */ type DownloadFunction = (options: Array<{ url: URL; isUrlSupportedByModel: boolean; }>) => PromiseLike>; /** * A generated file. */ interface GeneratedFile { /** * File as a base64 encoded string. */ readonly base64: string; /** * File as a Uint8Array. */ readonly uint8Array: Uint8Array; /** * The IANA media type of the file. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ readonly mediaType: string; } /** * @deprecated Use `GeneratedFile` instead. This alias will be removed in v8. */ type Experimental_GeneratedImage = GeneratedFile; declare class DefaultGeneratedFile implements GeneratedFile { private base64Data; private uint8ArrayData; readonly mediaType: string; constructor({ data, mediaType }: { data: string | Uint8Array; mediaType: string; }); get base64(): string; get uint8Array(): Uint8Array; } /** * Reasoning output of a text generation. It contains a reasoning. */ interface ReasoningOutput { type: 'reasoning'; /** * The reasoning text. */ 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. */ providerMetadata?: ProviderMetadata; } /** * Reasoning file output of a text generation. * It contains a file generated as part of reasoning. */ interface ReasoningFileOutput { type: 'reasoning-file'; /** * The generated file. */ file: GeneratedFile; /** * 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. */ providerMetadata?: ProviderMetadata; } /** * 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 { * return data[name]; * } * * export function onlyBar(name: string): ValueOf { * 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]; type BaseToolCall = { type: 'tool-call'; toolCallId: string; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject$2; }; /** * A tool call whose `toolName` maps to a tool in the declared tool set, * with an `input` type inferred from that tool's input schema. */ type StaticToolCall = ValueOf<{ [NAME in keyof TOOLS]: BaseToolCall & { toolName: NAME & string; input: InferToolInput; dynamic?: false | undefined; invalid?: false | undefined; error?: never; title?: string; } }>; /** * A tool call whose `toolName` is only known at runtime, such as an invalid * or otherwise untyped call that cannot be matched to the declared tool set. */ type DynamicToolCall = BaseToolCall & { toolName: string; input: unknown; dynamic: true; title?: string; /** * True if this is caused by an unparsable tool call or * a tool that does not exist. */ invalid?: boolean; /** * The error that caused the tool call to be invalid. */ error?: unknown; }; /** * A tool call returned by text generation, either statically typed from the * declared tool set or dynamically typed when the tool cannot be inferred. */ type TypedToolCall = StaticToolCall | DynamicToolCall; /** * Output part that indicates that a tool approval request has been made. * * The tool approval request can be approved or denied in the next tool message. */ type ToolApprovalRequestOutput = { type: 'tool-approval-request'; /** * ID of the tool approval request. */ approvalId: string; /** * Tool call that the approval request is for. */ toolCall: TypedToolCall; /** * Flag indicating whether the tool was automatically approved or denied. * * @default false */ isAutomatic?: boolean; /** * HMAC-SHA256 signature binding this approval request to its tool call. */ signature?: string; }; /** * Output part that indicates that a tool approval response is available. */ type ToolApprovalResponseOutput = { type: 'tool-approval-response'; /** * ID of the tool approval. */ approvalId: string; /** * Tool call that the approval response is for. */ toolCall: TypedToolCall; /** * Flag indicating whether the approval was granted or denied. */ approved: boolean; /** * Optional reason for the approval or denial. */ reason?: string; /** * Flag indicating whether the tool call is provider-executed. * Only provider-executed tool approval responses should be sent to the model. */ providerExecuted?: boolean; }; type StaticToolError = ValueOf<{ [NAME in keyof TOOLS]: { type: 'tool-error'; toolCallId: string; toolName: NAME & string; input: InferToolInput; error: unknown; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject$2; dynamic?: false | undefined; title?: string; } }>; type DynamicToolError = { type: 'tool-error'; toolCallId: string; toolName: string; input: unknown; error: unknown; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject$2; dynamic: true; title?: string; }; type TypedToolError = StaticToolError | DynamicToolError; type StaticToolResult = ValueOf<{ [NAME in keyof TOOLS]: { type: 'tool-result'; toolCallId: string; toolName: NAME & string; input: InferToolInput; output: InferToolOutput; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject$2; dynamic?: false | undefined; preliminary?: boolean; title?: string; } }>; type DynamicToolResult = { type: 'tool-result'; toolCallId: string; toolName: string; input: unknown; output: unknown; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject$2; dynamic: true; preliminary?: boolean; title?: string; }; type TypedToolResult = StaticToolResult | DynamicToolResult; type ContentPart = { type: 'text'; text: string; providerMetadata?: ProviderMetadata; } | { type: 'custom'; kind: `${string}.${string}`; providerMetadata?: ProviderMetadata; } | ReasoningOutput | ReasoningFileOutput | ({ type: 'source'; } & Source) | { type: 'file'; file: GeneratedFile; providerMetadata?: ProviderMetadata; } | ({ type: 'tool-call'; } & TypedToolCall & { providerMetadata?: ProviderMetadata; }) | ({ type: 'tool-result'; } & TypedToolResult & { providerMetadata?: ProviderMetadata; }) | ({ type: 'tool-error'; } & TypedToolError & { providerMetadata?: ProviderMetadata; }) | ToolApprovalRequestOutput | ToolApprovalResponseOutput; /** * Timing statistics for the gaps between generated output chunks. */ type OutputChunkTimingStats = { /** Shortest observed time between output chunks in milliseconds. */readonly min: number; /** 10th percentile time between output chunks in milliseconds. */ readonly p10: number; /** Median time between output chunks in milliseconds. */ readonly median: number; /** Average time between output chunks in milliseconds. */ readonly avg: number; /** 90th percentile time between output chunks in milliseconds. */ readonly p90: number; /** Longest observed time between output chunks in milliseconds. */ readonly max: number; }; /** * Performance metrics for a single step in the generation process. */ type StepResultPerformance = { /** * Effective number of output tokens per second over the full language model * response. * * Calculated as `outputTokens / requestSeconds`. */ readonly effectiveOutputTokensPerSecond: number; /** * Number of output tokens per second after the first generated output chunk * was received. * * Only available for streaming steps. * * Calculated as `outputTokens / outputStreamSeconds`. */ readonly outputTokensPerSecond: number | undefined; /** * Number of input tokens processed per second before the first generated * output chunk was received. * * Only available for streaming steps. * * Calculated as `inputTokens / ttftSeconds`. */ readonly inputTokensPerSecond: number | undefined; /** * Effective number of input and output tokens per second over the full * language model response. * * Calculated as `(inputTokens + outputTokens) / requestSeconds`. */ readonly effectiveTotalTokensPerSecond: number; /** * Total time spent on the step in milliseconds. */ readonly stepTimeMs: number; /** * Time spent waiting for the language model response in milliseconds. */ readonly responseTimeMs: number; /** * Time spent executing each client-side tool call in milliseconds, keyed by * tool call ID. */ readonly toolExecutionMs: Readonly>; /** * Time until the first generated output chunk was received in milliseconds. * * This includes text deltas, reasoning deltas, generated files, reasoning * files, tool input deltas, and tool calls. * * Only available for streaming steps. */ readonly timeToFirstOutputMs: number | undefined; /** * Timing statistics for the gaps between generated output chunks in * milliseconds. * * Only available for streaming steps with at least two generated output * chunks. */ readonly timeBetweenOutputChunksMs?: OutputChunkTimingStats; }; /** * The result of a single step in the generation process. */ type StepResult = { /** * Unique identifier for the generation call this step belongs to. */ readonly callId: string; /** * Zero-based index of this step. */ readonly stepNumber: number; /** * Information about the model that produced this step. */ readonly model: { /** The provider of the model. */readonly provider: string; /** The ID of the model. */ readonly modelId: string; }; /** * Tool context. */ readonly toolsContext: InferToolSetContext; /** * The runtime context that was used as input for the step. */ readonly runtimeContext: RUNTIME_CONTEXT; /** * The content that was generated in the last step. */ readonly content: Array>; /** * The concatenation of all text parts generated in this step. * It is an empty string if the step contains no text parts. */ readonly text: string; /** * The reasoning that was generated during the generation. */ readonly reasoning: Array; /** * The reasoning text that was generated during the generation. * * It is a concatenation of all reasoning parts (but excluding reasoning file parts). * Can be undefined if the model has only generated text. */ readonly reasoningText: string | undefined; /** * The files that were generated during the generation. */ readonly files: Array; /** * The sources that were used to generate the text. */ readonly sources: Array; /** * The tool calls that were made during the generation. */ readonly toolCalls: Array>; /** * The static tool calls that were made in the last step. */ readonly staticToolCalls: Array>; /** * The dynamic tool calls that were made in the last step. */ readonly dynamicToolCalls: Array; /** * The results of the tool calls. */ readonly toolResults: Array>; /** * The static tool results that were made in the last step. */ readonly staticToolResults: Array>; /** * The dynamic tool results that were made in the last step. */ readonly dynamicToolResults: Array; /** * The unified reason why the generation finished. */ readonly finishReason: FinishReason; /** * The raw reason why the generation finished (from the provider). */ readonly rawFinishReason: string | undefined; /** * The token usage of the generated text. */ readonly usage: LanguageModelUsage; /** * Performance metrics for the step. */ readonly performance: StepResultPerformance; /** * 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; /** * 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 providerMetadata: ProviderMetadata | undefined; }; /** * Common model information used across callback events. */ type ModelInfo = { /** The provider identifier (e.g., 'openai', 'anthropic'). */readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; }; /** * Event passed to the `onLanguageModelCallStart` callback. * * Called immediately before the provider model call begins. * Unlike `onStepStart`, this only represents model invocation work. */ type LanguageModelCallStartEvent = ModelInfo & { /** Unique identifier for this generation call, used to correlate events. */readonly callId: string; /** Prepared tool definitions for the model call, if any. */ readonly tools: ReadonlyArray> | undefined; } & StandardizedPrompt & LanguageModelCallOptions; /** * Event passed to the `onLanguageModelCallEnd` callback. * * Called after the model response has been normalized and parsed, but before * any client-side tool execution begins. */ type LanguageModelCallEndEvent = ModelInfo & { /** Unique identifier for this generation call, used to correlate events. */readonly callId: string; /** The unified reason why the model call finished. */ readonly finishReason: FinishReason; /** The token usage reported by the model call. */ readonly usage: LanguageModelUsage; /** The content parts produced by the model call. */ readonly content: ReadonlyArray>; /** The provider-returned response id for this model call. */ readonly responseId: string; /** Optional provider-specific metadata for this model call. */ readonly providerMetadata?: ProviderMetadata; /** Performance metrics for the model call. */ readonly performance: { /** Time spent waiting for the language model response in milliseconds. */readonly responseTimeMs: number; /** * Effective number of output tokens per second over the full language * model response. */ readonly effectiveOutputTokensPerSecond: number; /** * Number of output tokens per second after the first generated output * chunk was received. * * Only available for streaming calls. */ readonly outputTokensPerSecond: number | undefined; /** * Number of input tokens processed per second before the first generated * output chunk was received. * * Only available for streaming calls. */ readonly inputTokensPerSecond: number | undefined; /** * Effective number of input and output tokens per second over the full * language model response. */ readonly effectiveTotalTokensPerSecond: number; /** * Time until the first generated output chunk was received in * milliseconds. */ readonly timeToFirstOutputMs: number | undefined; /** * Timing statistics for the gaps between generated output chunks in * milliseconds. * * Only available for streaming calls with at least two output chunks. */ readonly timeBetweenOutputChunksMs?: OutputChunkTimingStats; }; }; /** * Callback that is set using the `onLanguageModelCallStart` option. * * Called immediately before the provider model call begins. * Unlike step-start callbacks, this is scoped to model work only and * excludes any later client-side tool execution. * * @param event - The event object containing model-call-specific inputs. */ type OnLanguageModelCallStartCallback = Callback; /** * Callback that is set using the `onLanguageModelCallEnd` option. * * Called after the model response has been normalized and parsed, but before * any client-side tool execution begins. * * @param event - The event object containing model-call-specific outputs. */ type OnLanguageModelCallEndCallback = Callback>; /** * Tool names that define the order in which tools are sent to the provider. * * Tool names are object keys at runtime, so the type is restricted to the * string keys of the configured tool set. The list can be partial; tools not * listed in `toolOrder` are sent after the listed tools, sorted alphabetically. */ type ToolOrder = ReadonlyArray | undefined; /** * Function that you can use to provide different settings for a step. * * @param options - The options for the step. * @param options.steps - The steps that have been executed so far. * @param options.stepNumber - The number of the step that is being executed. * @param options.model - The model that is being used. * @param options.instructions - The instructions that will be sent to the model for the current step. * @param options.initialInstructions - The initial instructions that were passed into generateText or streamText. * @param options.messages - The messages that will be sent to the model for the current step. If you return a `messages` override, those messages carry forward to later steps. * @param options.initialMessages - The initial messages that were passed into generateText or streamText. * @param options.responseMessages - The response messages that have been accumulated from previous steps. * @param options.runtimeContext - The user-defined runtime context. * * @returns An object that contains the settings for the step. * If you return undefined (or for undefined settings), the settings from the outer level will be used. */ type PrepareStepFunction = (options: { /** * The steps that have been executed so far. */ steps: Array, NoInfer>>; /** * The number of the step that is being executed. */ stepNumber: number; /** * The model instance that is being used for this step. */ model: LanguageModel; /** * The instructions that will be sent to the model for the current step. */ instructions: Instructions | undefined; /** * The initial instructions that were passed into generateText or streamText. */ initialInstructions: Instructions | undefined; /** * The messages that will be sent to the model for the current step. * If you return a `messages` override, those messages carry forward to later steps. */ messages: Array; /** * The initial messages that were passed into generateText or streamText. */ initialMessages: Array; /** * The response messages that have been accumulated from all previous steps. */ responseMessages: Array; /** * Tool context. */ toolsContext: InferToolSetContext; /** * User-defined runtime context. */ runtimeContext: RUNTIME_CONTEXT; /** * The sandbox environment that the step is operating in. */ experimental_sandbox?: SandboxSession; }) => PromiseLike> | PrepareStepResult; /** * The result type returned by a {@link PrepareStepFunction}, * allowing per-step overrides of model call settings, model, tools, * instructions, or messages. * * Model call setting overrides apply only to the current step. Undefined * settings fall back to the outer call settings. */ type PrepareStepResult = ({ /** * Optionally override which LanguageModel instance is used for this step. */ model?: LanguageModel; /** * Optionally set which tool the model must call, or provide tool call configuration * for this step. */ toolChoice?: ToolChoice>; /** * If provided, only these tools are enabled/available for this step. */ activeTools?: ActiveTools>; /** * Optionally override the order in which tools are sent to the provider * for this step. */ toolOrder?: ToolOrder>; /** * Optionally override the instructions sent to the model for this step. * The override carries forward to later steps. */ instructions?: Instructions; /** * Optionally override the instructions sent to the model for this step. * * @deprecated Use `instructions` instead. */ system?: Instructions; /** * Optionally override the full set of messages sent to the model * for this step. The override carries forward to later steps. */ messages?: Array; /** * Tool context. * * Changing the toolsContext will affect the toolsContext in this step * and all subsequent steps. * * The toolsContext is passed into tool execution. */ toolsContext?: InferToolSetContext; /** * Runtime context. * * Changing the runtimeContext will affect the runtimeContext in this step * and all subsequent steps. */ runtimeContext?: RUNTIME_CONTEXT; /** * The sandbox environment that the step is operating in. * * Changing the sandbox will affect tool execution in this step only. */ experimental_sandbox?: SandboxSession; /** * Additional provider-specific options for this step. * * Can be used to pass provider-specific configuration such as * container IDs for Anthropic's code execution. */ providerOptions?: ProviderOptions; } & LanguageModelCallOptions) | undefined; /** * A predicate that decides whether a tool-calling loop should stop after the * current step. * * A tool calling loop continues until one of the following conditions is met: * - The model returns a finish reason other than `tool-calls` * - A tool without an execute function is called * - A tool call needs approval * - One of the provided stop conditions returns `true` */ type StopCondition = (options: { steps: Array>; }) => PromiseLike | boolean; /** * Creates a stop condition that returns `true` when the number of completed * steps equals `stepCount`. * * @param stepCount - The number of steps to allow before stopping. */ declare function isStepCount(stepCount: number): StopCondition; /** * Creates a stop condition that never returns `true`. * * This lets the tool-calling loop continue until it reaches one of its * natural termination conditions. */ declare function isLoopFinished(): StopCondition; /** * Creates a stop condition that returns `true` when the most recent step * contains a tool call with any of the specified names. * * @param toolName - The names of the tools that should stop the loop. */ declare function hasToolCall(...toolName: Array): StopCondition; /** * The data types that can be used in the UI message for the UI message data parts. */ type UIDataTypes = Record; type UITool = { input: unknown; output: unknown | undefined; }; /** * Infer the input and output types of a tool so it can be used as a UI tool. */ type InferUITool = { input: InferToolInput; output: InferToolOutput; }; /** * Infer the input and output types of a tool set so it can be used as a UI tool set. */ type InferUITools = { [NAME in keyof TOOLS & string]: InferUITool }; type UITools = Record; /** * AI SDK UI Messages. They are used in the client and to communicate between the frontend and the API routes. */ interface UIMessage { /** * A unique identifier for the message. */ id: string; /** * The role of the message. */ role: 'system' | 'user' | 'assistant'; /** * The metadata of the message. */ metadata?: METADATA; /** * The parts of the message. Use this for rendering the message in the UI. * * System messages should be avoided (set the system prompt on the server instead). * They can have text parts. * * User messages can have text parts and file parts. * * Assistant messages can have text, reasoning, tool invocation, and file parts. */ parts: Array>; } type UIMessagePart = TextUIPart | CustomContentUIPart | ReasoningUIPart | ToolUIPart | DynamicToolUIPart | SourceUrlUIPart | SourceDocumentUIPart | FileUIPart | ReasoningFileUIPart | DataUIPart | StepStartUIPart; /** * A text part of a message. */ type TextUIPart = { type: 'text'; /** * The text content. */ text: string; /** * The state of the text part. */ state?: 'streaming' | 'done'; /** * The provider metadata. */ providerMetadata?: ProviderMetadata; }; /** * A provider-specific part of a message. */ type CustomContentUIPart = { type: 'custom'; /** * The kind of custom content, in the format `{provider}.{provider-type}`. */ kind: `${string}.${string}`; /** * The provider metadata. */ providerMetadata?: ProviderMetadata; }; /** * A reasoning part of a message. */ type ReasoningUIPart = { type: 'reasoning'; /** * The reasoning part ID. */ id?: string; /** * The reasoning text. */ text: string; /** * The state of the reasoning part. */ state?: 'streaming' | 'done'; /** * The provider metadata. */ providerMetadata?: ProviderMetadata; }; /** * A source part of a message. */ type SourceUrlUIPart = { type: 'source-url'; sourceId: string; url: string; title?: string; providerMetadata?: ProviderMetadata; }; /** * A document source part of a message. */ type SourceDocumentUIPart = { type: 'source-document'; sourceId: string; mediaType: string; title: string; filename?: string; providerMetadata?: ProviderMetadata; }; /** * A file part of a message. */ type FileUIPart = { type: 'file'; /** * Either a full IANA media type (`type/subtype`, e.g. `image/png`) or just * the top-level IANA segment (e.g. `image`, `audio`, `video`, `text`). * * `*`-subtype wildcards (e.g. `image/*`) are normalized as equivalent to the * top-level segment alone (e.g. `image`). Providers can use the helpers in * `@ai-sdk/provider-utils` (`isFullMediaType`, `getTopLevelMediaType`, * `detectMediaType`) to resolve the field according to their API * requirements. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * Optional filename of the file. */ filename?: string; /** * The URL of the file. * It can either be a URL to a hosted file or a [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs). */ url: string; /** * Provider reference for files uploaded via `uploadFile`. * Maps provider names to provider-specific file identifiers. * When present, takes precedence over `url` in model messages. */ providerReference?: ProviderReference; /** * The provider metadata. */ providerMetadata?: ProviderMetadata; }; /** * A reasoning file part of a message. */ type ReasoningFileUIPart = { type: 'reasoning-file'; /** * IANA media type of the file. * * @see https://www.iana.org/assignments/media-types/media-types.xhtml */ mediaType: string; /** * The URL of the file. * It can either be a URL to a hosted file or a [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs). */ url: string; /** * The provider metadata. */ providerMetadata?: ProviderMetadata; }; /** * A step boundary part of a message. */ type StepStartUIPart = { type: 'step-start'; }; type DataUIPart = ValueOf<{ [NAME in keyof DATA_TYPES & string]: { type: `data-${NAME}`; id?: string; data: DATA_TYPES[NAME]; } }>; type asUITool = TOOL extends Tool ? InferUITool : TOOL; /** * Check if a message part is a data part. */ declare function isDataUIPart(part: UIMessagePart): part is DataUIPart; /** * A UI tool invocation contains all the information needed to render a tool invocation in the UI. * It can be derived from a tool without knowing the tool name, and can be used to define * UI components for the tool. */ type UIToolInvocation = { /** * ID of the tool call. */ toolCallId: string; title?: string; toolMetadata?: JSONObject$2; /** * Whether the tool call was executed by the provider. */ providerExecuted?: boolean; } & ({ state: 'input-streaming'; input?: DeepPartial['input']> | undefined; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval?: never; } | { state: 'input-available'; input: asUITool['input']; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval?: never; } | { state: 'approval-requested'; input: asUITool['input']; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval: { id: string; approved?: never; reason?: never; isAutomatic?: boolean; signature?: string; }; } | { state: 'approval-responded'; input: asUITool['input']; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval: { id: string; approved: boolean; reason?: string; isAutomatic?: boolean; signature?: string; }; } | { state: 'output-available'; input: asUITool['input']; output: asUITool['output']; errorText?: never; callProviderMetadata?: ProviderMetadata; resultProviderMetadata?: ProviderMetadata; preliminary?: boolean; approval?: { id: string; approved: true; reason?: string; isAutomatic?: boolean; signature?: string; }; } | { state: 'output-error'; input: asUITool['input'] | undefined; rawInput?: unknown; output?: never; errorText: string; callProviderMetadata?: ProviderMetadata; resultProviderMetadata?: ProviderMetadata; approval?: { id: string; approved: true; reason?: string; isAutomatic?: boolean; signature?: string; }; } | { state: 'output-denied'; input: asUITool['input']; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval: { id: string; approved: false; reason?: string; isAutomatic?: boolean; signature?: string; }; }); type ToolUIPart = ValueOf<{ [NAME in keyof TOOLS & string]: { type: `tool-${NAME}`; } & UIToolInvocation }>; type DynamicToolUIPart = { type: 'dynamic-tool'; /** * Name of the tool that is being called. */ toolName: string; /** * ID of the tool call. */ toolCallId: string; title?: string; toolMetadata?: JSONObject$2; /** * Whether the tool call was executed by the provider. */ providerExecuted?: boolean; } & ({ state: 'input-streaming'; input?: unknown; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval?: never; } | { state: 'input-available'; input: unknown; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval?: never; } | { state: 'approval-requested'; input: unknown; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval: { id: string; approved?: never; reason?: never; isAutomatic?: boolean; signature?: string; }; } | { state: 'approval-responded'; input: unknown; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval: { id: string; approved: boolean; reason?: string; isAutomatic?: boolean; signature?: string; }; } | { state: 'output-available'; input: unknown; output: unknown; errorText?: never; callProviderMetadata?: ProviderMetadata; resultProviderMetadata?: ProviderMetadata; preliminary?: boolean; approval?: { id: string; approved: true; reason?: string; isAutomatic?: boolean; signature?: string; }; } | { state: 'output-error'; input: unknown; output?: never; errorText: string; callProviderMetadata?: ProviderMetadata; resultProviderMetadata?: ProviderMetadata; approval?: { id: string; approved: true; reason?: string; isAutomatic?: boolean; signature?: string; }; } | { state: 'output-denied'; input: unknown; output?: never; errorText?: never; callProviderMetadata?: ProviderMetadata; approval: { id: string; approved: false; reason?: string; isAutomatic?: boolean; signature?: string; }; }); /** * Type guard to check if a message part is a text part. */ declare function isTextUIPart(part: UIMessagePart): part is TextUIPart; /** * Type guard to check if a message part is a custom part. */ declare function isCustomContentUIPart(part: UIMessagePart): part is CustomContentUIPart; /** * Type guard to check if a message part is a file part. */ declare function isFileUIPart(part: UIMessagePart): part is FileUIPart; /** * Type guard to check if a message part is a reasoning file part. */ declare function isReasoningFileUIPart(part: UIMessagePart): part is ReasoningFileUIPart; /** * Type guard to check if a message part is a reasoning part. */ declare function isReasoningUIPart(part: UIMessagePart): part is ReasoningUIPart; /** * Check if a message part is a static tool part. * * Static tools are tools for which the types are known at development time. */ declare function isStaticToolUIPart(part: UIMessagePart): part is ToolUIPart; /** * Check if a message part is a dynamic tool part. * * Dynamic tools are tools for which the input and output types are unknown. */ declare function isDynamicToolUIPart(part: UIMessagePart): part is DynamicToolUIPart; /** * Check if a message part is a tool part. * * Tool parts are either static or dynamic tools. * * Use `isStaticToolUIPart` or `isDynamicToolUIPart` to check the type of the tool. */ declare function isToolUIPart(part: UIMessagePart): part is ToolUIPart | DynamicToolUIPart; /** * Returns the name of the static tool. * * The possible values are the keys of the tool set. */ declare function getStaticToolName(part: ToolUIPart): keyof TOOLS; /** * Returns the name of the tool (static or dynamic). * * This function will not restrict the name to the keys of the tool set. * If you need to restrict the name to the keys of the tool set, use `getStaticToolName` instead. */ declare function getToolName(part: ToolUIPart | DynamicToolUIPart): string; /** * @deprecated Use getToolName instead. */ declare const getToolOrDynamicToolName: typeof getToolName; type InferUIMessageMetadata = T extends UIMessage ? METADATA : unknown; type InferUIMessageData = T extends UIMessage ? DATA_TYPES : UIDataTypes; type InferUIMessageTools = T extends UIMessage ? TOOLS : UITools; type InferUIMessageToolCall = ValueOf<{ [NAME in keyof InferUIMessageTools]: ToolCall[NAME] extends { input: infer INPUT; } ? INPUT : never> & { dynamic?: false; } }> | (ToolCall & { dynamic: true; }); declare const uiMessageChunkSchema: LazySchema>; type DataUIMessageChunk = ValueOf<{ [NAME in keyof DATA_TYPES & string]: { type: `data-${NAME}`; id?: string; data: DATA_TYPES[NAME]; transient?: boolean; } }>; type UIMessageChunk = { type: 'text-start'; id: string; providerMetadata?: ProviderMetadata; } | { type: 'text-delta'; delta: string; id: string; providerMetadata?: ProviderMetadata; } | { type: 'text-end'; id: string; providerMetadata?: ProviderMetadata; } | { type: 'reasoning-start'; id: string; providerMetadata?: ProviderMetadata; } | { type: 'reasoning-delta'; id: string; delta: string; providerMetadata?: ProviderMetadata; } | { type: 'reasoning-end'; id: string; providerMetadata?: ProviderMetadata; } | { type: 'custom'; kind: `${string}.${string}`; providerMetadata?: ProviderMetadata; } | { type: 'error'; errorText: string; } | { type: 'tool-input-available'; toolCallId: string; toolName: string; input: unknown; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject$2; dynamic?: boolean; title?: string; } | { type: 'tool-input-error'; toolCallId: string; toolName: string; input: unknown; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject$2; dynamic?: boolean; errorText: string; title?: string; } | { type: 'tool-approval-request'; approvalId: string; toolCallId: string; isAutomatic?: boolean; signature?: string; } | { type: 'tool-approval-response'; approvalId: string; approved: boolean; reason?: string; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; } | { type: 'tool-output-available'; toolCallId: string; output: unknown; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject$2; dynamic?: boolean; preliminary?: boolean; } | { type: 'tool-output-error'; toolCallId: string; errorText: string; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject$2; dynamic?: boolean; } | { type: 'tool-output-denied'; toolCallId: string; } | { type: 'tool-input-start'; toolCallId: string; toolName: string; providerExecuted?: boolean; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject$2; dynamic?: boolean; title?: string; } | { type: 'tool-input-delta'; toolCallId: string; inputTextDelta: string; } | { type: 'source-url'; sourceId: string; url: string; title?: string; providerMetadata?: ProviderMetadata; } | { type: 'source-document'; sourceId: string; mediaType: string; title: string; filename?: string; providerMetadata?: ProviderMetadata; } | { type: 'file'; url: string; mediaType: string; providerMetadata?: ProviderMetadata; } | { type: 'reasoning-file'; url: string; mediaType: string; providerMetadata?: ProviderMetadata; } | DataUIMessageChunk | { type: 'start-step'; } | { type: 'finish-step'; } | { type: 'start'; messageId?: string; messageMetadata?: METADATA; } | { type: 'finish'; finishReason?: FinishReason; messageMetadata?: METADATA; } | { type: 'abort'; reason?: string; } | { type: 'message-metadata'; messageMetadata: METADATA; }; type InferUIMessageChunk = UIMessageChunk, InferUIMessageData>; type UIMessageStreamOnEndCallback = (event: { /** * The updated list of UI messages. */ messages: UI_MESSAGE[]; /** * Indicates whether the response message is a continuation of the last original message, * or if a new message was created. */ isContinuation: boolean; /** * Indicates whether the stream was aborted. */ isAborted: boolean; /** * The message that was sent to the client as a response * (including the original message if it was extended). */ responseMessage: UI_MESSAGE; /** * The reason why the generation finished. */ finishReason?: FinishReason; }) => PromiseLike | void; /** * Options for creating a UI message stream response. * Extends the standard `ResponseInit` with additional streaming options. */ type UIMessageStreamResponseInit = ResponseInit & { /** * Optional callback to consume a copy of the SSE stream independently. * This is useful for logging, debugging, or processing the stream in parallel. * The callback receives a tee'd copy of the stream and does not block the response. */ consumeSseStream?: (options: { stream: ReadableStream; }) => PromiseLike | void; }; /** * A type that combines AsyncIterable and ReadableStream. * This allows a ReadableStream to be consumed using for-await-of syntax. */ type AsyncIterableStream = AsyncIterable & ReadableStream; type ErrorHandler = (error: unknown) => void; /** * Infers the complete output type from the output specification. */ type InferCompleteOutput = OUTPUT extends Output ? COMPLETE_OUTPUT : never; /** * Infers the partial output type from the output specification. */ type InferPartialOutput = OUTPUT extends Output ? PARTIAL_OUTPUT : never; /** * Infers the element type from an array output specification. */ type InferElementOutput = OUTPUT extends Output ? ELEMENT : never; /** * Tool output when the tool execution has been denied (for static tools). */ type StaticToolOutputDenied = ValueOf<{ [NAME in keyof TOOLS]: { type: 'tool-output-denied'; toolCallId: string; toolName: NAME & string; providerExecuted?: boolean; dynamic?: false | undefined; } }>; /** * Tool output when the tool execution has been denied. */ type TypedToolOutputDenied = StaticToolOutputDenied; type UIMessageStreamOptions = { /** * The original messages. If they are provided, persistence mode is assumed, * and a message ID is provided for the response message. */ originalMessages?: UI_MESSAGE[]; /** * Generate a message ID for the response message. * * If not provided, no message ID will be set for the response message (unless * the original messages are provided and the last message is an assistant message). */ generateMessageId?: IdGenerator; onEnd?: UIMessageStreamOnEndCallback; /** * @deprecated Use `onEnd` instead. */ onFinish?: UIMessageStreamOnEndCallback; /** * Extracts message metadata that will be sent to the client. * * Called on `start` and `finish` events. */ messageMetadata?: (options: { part: TextStreamPart; }) => InferUIMessageMetadata | undefined; /** * Send reasoning parts to the client. * Default to true. */ sendReasoning?: boolean; /** * Send source parts to the client. * Default to false. */ sendSources?: boolean; /** * Send the finish event to the client. * Set to false if you are using additional streamText calls * that send additional data. * Default to true. */ sendFinish?: boolean; /** * Send the message start event to the client. * Set to false if you are using additional streamText calls * and the message start event has already been sent. * Default to true. */ sendStart?: boolean; /** * Process an error, e.g. to log it. Default to `() => 'An error occurred.'`. * * @returns error message to include in the data stream. */ onError?: (error: unknown) => string; }; type ConsumeStreamOptions = { onError?: ErrorHandler; }; /** * A result object for accessing different stream types and additional information. */ interface StreamTextResult { /** * The content that was generated in all steps. * * Automatically consumes the stream. */ readonly content: PromiseLike>>; /** * The full text that has been generated by the final step. * * Automatically consumes the stream. */ readonly text: PromiseLike; /** * The full reasoning that the model has generated. * * Automatically consumes the stream. * * @deprecated Use `finalStep.reasoning` instead. */ readonly reasoning: PromiseLike>; /** * The reasoning that has been generated by the last step. * * Automatically consumes the stream. * * @deprecated Use `finalStep.reasoningText` instead. */ readonly reasoningText: PromiseLike; /** * Files that have been generated by the model in all steps. * * Automatically consumes the stream. */ readonly files: PromiseLike; /** * Sources that have been used as references in all steps. * * Automatically consumes the stream. */ readonly sources: PromiseLike; /** * The tool calls that have been executed in all steps. * * Automatically consumes the stream. */ readonly toolCalls: PromiseLike[]>; /** * The static tool calls that have been executed in all steps. * * Automatically consumes the stream. */ readonly staticToolCalls: PromiseLike[]>; /** * The dynamic tool calls that have been executed in all steps. * * Automatically consumes the stream. */ readonly dynamicToolCalls: PromiseLike; /** * The static tool results that have been generated in all steps. * * Automatically consumes the stream. */ readonly staticToolResults: PromiseLike[]>; /** * The dynamic tool results that have been generated in all steps. * * Automatically consumes the stream. */ readonly dynamicToolResults: PromiseLike; /** * The tool results that have been generated in all steps. * * Automatically consumes the stream. */ readonly toolResults: PromiseLike[]>; /** * The unified finish reason why the generation finished. Taken from the last step. * * Automatically consumes the stream. */ readonly finishReason: PromiseLike; /** * The raw reason why the generation finished (from the provider). Taken from the last step. * * Automatically consumes the stream. */ readonly rawFinishReason: PromiseLike; /** * The total token usage of the generated response. * When there are multiple steps, the usage is the sum of all step usages. * * Automatically consumes the stream. */ readonly usage: PromiseLike; /** * The total token usage of the generated response. * When there are multiple steps, the usage is the sum of all step usages. * * Automatically consumes the stream. * * @deprecated Use `usage` instead. */ readonly totalUsage: PromiseLike; /** * Warnings from the model provider (e.g. unsupported settings) in all steps. * * Automatically consumes the stream. */ readonly warnings: PromiseLike; /** * Details for all steps. * You can use this to get information about intermediate steps, * such as the tool calls or the response headers. * * Automatically consumes the stream. */ readonly steps: PromiseLike>>; /** * The final step. This is a shortcut for `steps.at(-1)`. * * Automatically consumes the stream. */ readonly finalStep: PromiseLike>; /** * Additional request information from the last step. * * Automatically consumes the stream. * * @deprecated Use `finalStep.request` instead. */ readonly request: PromiseLike; /** * Additional response information from the last step. * * Automatically consumes the stream. * * @deprecated Use `finalStep.response` instead. */ readonly response: PromiseLike; /** * The accumulated response messages of all steps that were generated during the call. * * Automatically consumes the stream. */ readonly responseMessages: PromiseLike>; /** * Additional provider-specific metadata from the last step. * Metadata is passed through from the provider to the AI SDK and * enables provider-specific results that can be fully encapsulated in the provider. * * @deprecated Use `finalStep.providerMetadata` instead. */ readonly providerMetadata: PromiseLike; /** * A text stream that returns only the generated text deltas. You can use it * as either an AsyncIterable or a ReadableStream. Error parts are not * surfaced in this stream. Use the `onError` callback or `stream` to observe * them. */ readonly textStream: AsyncIterableStream; /** * A stream with all events, including text deltas, tool calls, tool results, and * errors. * You can use it as either an AsyncIterable or a ReadableStream. * Only errors that stop the stream, such as network errors, are thrown. */ readonly stream: AsyncIterableStream>; /** * A stream with all events, including text deltas, tool calls, tool results, and * errors. * You can use it as either an AsyncIterable or a ReadableStream. * Only errors that stop the stream, such as network errors, are thrown. * * @deprecated Use `stream` instead. */ readonly fullStream: AsyncIterableStream>; /** * A stream of partial outputs. It uses the `output` specification. * * @deprecated Use `partialOutputStream` instead. */ readonly experimental_partialOutputStream: AsyncIterableStream>; /** * A stream of partial parsed outputs. It uses the `output` specification. */ readonly partialOutputStream: AsyncIterableStream>; /** * A stream of individual array elements as they complete. * Only available when using `output: Output.array()`. */ readonly elementStream: AsyncIterableStream>; /** * The complete parsed output. It uses the `output` specification. */ readonly output: PromiseLike>; /** * Consumes the stream without processing the parts. * This is useful to force the stream to finish. * It effectively removes the backpressure and allows the stream to finish, * triggering the `onEnd` callback and the promise resolution. * * If an error occurs, it is passed to the optional `onError` callback. */ consumeStream(options?: ConsumeStreamOptions): PromiseLike; /** * Converts the result to a UI message stream. * * @returns A UI message stream. * * @deprecated Use the standalone `toUIMessageStream` helper from * `'ai'` with `result.stream` instead. This method will be removed * in the next major release. */ toUIMessageStream(options?: UIMessageStreamOptions): AsyncIterableStream>; /** * Writes UI message stream output to a Node.js response-like object. * * @deprecated Use the standalone `toUIMessageStream` and * `pipeUIMessageStreamToResponse` helpers from `'ai'` with `result.stream` * instead. This method will be removed in the next major release. */ pipeUIMessageStreamToResponse(response: ServerResponse, options?: UIMessageStreamResponseInit & UIMessageStreamOptions): Promise; /** * 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. * * @deprecated Use the standalone `toTextStream` and * `pipeTextStreamToResponse` helpers from `'ai'` with `result.stream` * instead. This method will be removed in the next major release. */ pipeTextStreamToResponse(response: ServerResponse, init?: ResponseInit): Promise; /** * Converts the result to a streamed response object with a stream data part stream. * * @returns A response object. * * @deprecated Use the standalone `toUIMessageStream` and * `createUIMessageStreamResponse` helpers from `'ai'` with `result.stream` * instead. This method will be removed in the next major release. */ toUIMessageStreamResponse(options?: UIMessageStreamResponseInit & UIMessageStreamOptions): Response; /** * Creates a simple text stream response. * 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. * * @deprecated Use the standalone `toTextStream` and `createTextStreamResponse` * helpers from `'ai'` with `result.stream` instead. This method will be * removed in the next major release. */ toTextStreamResponse(init?: ResponseInit): Response; } type TextStreamTextDeltaPart = { type: 'text-delta'; id: string; providerMetadata?: ProviderMetadata; text: string; }; type TextStreamTextStartPart = { type: 'text-start'; id: string; providerMetadata?: ProviderMetadata; }; type TextStreamTextEndPart = { type: 'text-end'; id: string; providerMetadata?: ProviderMetadata; }; type TextStreamReasoningStartPart = { type: 'reasoning-start'; id: string; providerMetadata?: ProviderMetadata; }; type TextStreamReasoningEndPart = { type: 'reasoning-end'; id: string; providerMetadata?: ProviderMetadata; }; type TextStreamReasoningDeltaPart = { type: 'reasoning-delta'; providerMetadata?: ProviderMetadata; id: string; text: string; }; type TextStreamCustomPart = { type: 'custom'; kind: `${string}.${string}`; providerMetadata?: ProviderMetadata; }; type TextStreamToolInputStartPart = { type: 'tool-input-start'; id: string; toolName: string; providerMetadata?: ProviderMetadata; toolMetadata?: JSONObject$2; providerExecuted?: boolean; dynamic?: boolean; title?: string; }; type TextStreamToolInputEndPart = { type: 'tool-input-end'; id: string; providerMetadata?: ProviderMetadata; }; type TextStreamToolInputDeltaPart = { type: 'tool-input-delta'; id: string; delta: string; providerMetadata?: ProviderMetadata; }; type TextStreamSourcePart = { type: 'source'; } & Source; type TextStreamFilePart = { type: 'file'; file: GeneratedFile; providerMetadata?: ProviderMetadata; }; type TextStreamReasoningFilePart = { type: 'reasoning-file'; file: GeneratedFile; providerMetadata?: ProviderMetadata; }; type TextStreamToolCallPart = { type: 'tool-call'; } & TypedToolCall; type TextStreamToolResultPart = { type: 'tool-result'; } & TypedToolResult; type TextStreamToolErrorPart = { type: 'tool-error'; } & TypedToolError; type TextStreamToolOutputDeniedPart = { type: 'tool-output-denied'; } & StaticToolOutputDenied; type TextStreamToolApprovalRequestPart = ToolApprovalRequestOutput; type TextStreamToolApprovalResponsePart = ToolApprovalResponseOutput; type TextStreamStartStepPart = { type: 'start-step'; request: LanguageModelRequestMetadata; warnings: CallWarning[]; }; type TextStreamFinishStepPart = { type: 'finish-step'; response: Omit; usage: LanguageModelUsage; performance: StepResultPerformance; finishReason: FinishReason; rawFinishReason: string | undefined; providerMetadata: ProviderMetadata | undefined; }; type TextStreamStartPart = { type: 'start'; }; type TextStreamFinishPart = { type: 'finish'; finishReason: FinishReason; rawFinishReason: string | undefined; totalUsage: LanguageModelUsage; }; type TextStreamAbortPart = { type: 'abort'; reason?: string; }; type TextStreamErrorPart = { type: 'error'; error: unknown; }; type TextStreamRawPart = { type: 'raw'; rawValue: unknown; }; type TextStreamPart = TextStreamTextStartPart | TextStreamTextEndPart | TextStreamTextDeltaPart | TextStreamReasoningStartPart | TextStreamReasoningEndPart | TextStreamReasoningDeltaPart | TextStreamCustomPart | TextStreamToolInputStartPart | TextStreamToolInputEndPart | TextStreamToolInputDeltaPart | TextStreamSourcePart | TextStreamFilePart | TextStreamReasoningFilePart | TextStreamToolCallPart | TextStreamToolResultPart | TextStreamToolErrorPart | TextStreamToolOutputDeniedPart | TextStreamToolApprovalRequestPart | TextStreamToolApprovalResponsePart | TextStreamStartStepPart | TextStreamFinishStepPart | TextStreamStartPart | TextStreamFinishPart | TextStreamAbortPart | TextStreamErrorPart | TextStreamRawPart; /** * The approval status of a tool configuration. This can be one of the following: * * - 'not-applicable': The tool does not require approval. * - 'approved': The tool is automatically approved. * - 'denied': The tool is automatically denied. * - 'user-approval': The tool requires user approval. * * In addition to the string statuses, you can also use object statuses with a reason property. * * `undefined` is treated as the `not-applicable` status. */ type ToolApprovalStatus = undefined | 'not-applicable' | 'approved' | 'denied' | 'user-approval' | { type: 'not-applicable'; reason?: never; } | { type: 'approved'; reason?: string; } | { type: 'denied'; reason?: string; } | { type: 'user-approval'; reason?: never; }; /** * Function that is called to determine if the tool needs approval before it can be executed. * * Return `undefined` for the same effect as the `not-applicable` status. */ type SingleToolApprovalFunction = (input: INPUT, options: Omit, 'abortSignal' | 'context'> & { toolContext: TOOL_CONTEXT; runtimeContext: RUNTIME_CONTEXT; }) => MaybePromiseLike; /** * Function that is called to determine if a tool call needs approval before it can be executed. * * Return `undefined` for the same effect as the `not-applicable` status. */ type GenericToolApprovalFunction, RUNTIME_CONTEXT extends Context$1 | unknown | never> = (options: { /** * The tool call that needs approval. */ toolCall: TypedToolCall; /** * All tools that are available for the model to call. */ tools: TOOLS | undefined; /** * Tool context for all tools that are available for the model to call. */ toolsContext: TOOLS_CONTEXT; /** * Runtime context. */ runtimeContext: RUNTIME_CONTEXT; /** * 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: ModelMessage[]; }) => MaybePromiseLike; /** * Configure whether individual tools require approval before they can run. * * You can either use a generic function that is called for all tool calls, * or you can use a per-tool function. * * For the per-tool functions, each tool can be assigned either an approval status * or a function that produces an approval status at runtime. * * The approval status can be one of the following: * - 'not-applicable': The tool does not require approval. * - 'approved': The tool is automatically approved. * - 'denied': The tool is automatically denied. * - 'user-approval': The tool requires user approval. * * In addition to the string statuses, you can also use object statuses with a reason property. */ type ToolApprovalConfiguration = GenericToolApprovalFunction, RUNTIME_CONTEXT> | { [key in keyof TOOLS]?: ToolApprovalStatus | SingleToolApprovalFunction, InferToolContext, RUNTIME_CONTEXT> }; type ToolCallerName = { [NAME in keyof TOOLS]: TOOLS[NAME] extends ToolCallerTool ? NAME : never }[keyof TOOLS] & string; type Experimental_ToolCallers = { [NAME in keyof TOOLS]?: ReadonlyArray<'AI_SDK_DIRECT_TOOL_CALL' | ToolCallerName> }; declare const symbol$l: unique symbol; declare class InvalidToolInputError extends AISDKError { private readonly [symbol$l]; readonly toolName: string; readonly toolInput: string; constructor({ toolInput, toolName, cause, message }: { message?: string; toolInput: string; toolName: string; cause: unknown; }); static isInstance(error: unknown): error is InvalidToolInputError; } declare const symbol$k: unique symbol; declare class NoSuchToolError extends AISDKError { private readonly [symbol$k]; readonly toolName: string; readonly availableTools: string[] | undefined; constructor({ toolName, availableTools, message }: { toolName: string; availableTools?: string[] | undefined; message?: string; }); static isInstance(error: unknown): error is NoSuchToolError; } /** * A function that attempts to repair a tool call that failed to parse. * * It receives the error and the context as arguments and returns the repair * tool call JSON as text. * * @param options.instructions - The instructions provided to the model. * @param options.system - The instructions provided to the model. * @param options.messages - The messages in the current generation step. * @param options.toolCall - The tool call that failed to parse. * @param options.tools - The tools that are available. * @param options.inputSchema - A function that returns the JSON Schema for a tool. * @param options.error - The error that occurred while parsing the tool call. */ type ToolCallRepairFunction = (options: { instructions: Instructions | undefined; /** * @deprecated Use `instructions` instead. */ system: Instructions | undefined; messages: ModelMessage[]; toolCall: LanguageModelV4ToolCall; tools: TOOLS; inputSchema: (options: { toolName: string; }) => PromiseLike; error: NoSuchToolError | InvalidToolInputError; }) => Promise; type ToolOutput = TypedToolResult | TypedToolError; /** * Resolves a single tool's context type, falling back to `undefined` when the * tool does not declare a `contextSchema`. */ type ToolContextFor = [InferToolContext] extends [never] ? undefined : InferToolContext; type BaseToolExecutionStartFields = { /** Unique identifier for this generation call, used to correlate events. */readonly callId: 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. */ readonly messages: ModelMessage[]; }; /** * Precise start event union for statically known tools. * * Each union member ties a specific `toolCall.toolName` to that tool's * validated `toolContext` type. */ type StaticToolExecutionStartEvent = ValueOf<{ [NAME in keyof TOOLS]: BaseToolExecutionStartFields & { readonly toolCall: Extract, { toolName: NAME; }>; readonly toolContext: ToolContextFor; } }>; /** * Start event shape for dynamic or untyped tool calls. */ type DynamicToolExecutionStartEvent = BaseToolExecutionStartFields & { readonly toolCall: DynamicToolCall; readonly toolContext: unknown; }; /** * Broad start event shape used for the default `ToolSet` specialization. * * This keeps generic collectors ergonomic when the caller is not working with * a concrete tool set and therefore cannot benefit from per-tool narrowing. */ type WidenedToolExecutionStartEvent = BaseToolExecutionStartFields & { readonly toolCall: StaticToolCall | DynamicToolCall; readonly toolContext: unknown; }; /** * Event passed to the `onToolExecutionStart` callback. * * Called when a tool execution begins, before the tool's `execute` function is invoked. */ type ToolExecutionStartEvent = [ToolSet] extends [TOOLS] ? WidenedToolExecutionStartEvent : StaticToolExecutionStartEvent | DynamicToolExecutionStartEvent; type BaseToolExecutionEndFields = { /** Unique identifier for this generation call, used to correlate events. */readonly callId: string; /** Execution time of the tool call in milliseconds. */ readonly toolExecutionMs: number; /** * 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. */ readonly messages: ModelMessage[]; }; /** * Precise end event union for statically known tools. * * Each union member preserves the link between `toolCall.toolName`, the * corresponding validated `toolContext`, and the tool execution result. */ type StaticToolExecutionEndEvent = ValueOf<{ [NAME in keyof TOOLS]: BaseToolExecutionEndFields & { readonly toolCall: Extract, { toolName: NAME; }>; readonly toolContext: ToolContextFor; readonly toolOutput: ToolOutput; } }>; /** * End event shape for dynamic or untyped tool calls. */ type DynamicToolExecutionEndEvent = BaseToolExecutionEndFields & { readonly toolCall: DynamicToolCall; readonly toolContext: unknown; readonly toolOutput: ToolOutput; }; /** * Broad end event shape used for the default `ToolSet` specialization. * * This provides an assignable catch-all event type for generic consumers while * the concrete-tool specialization retains full per-tool narrowing. */ type WidenedToolExecutionEndEvent = BaseToolExecutionEndFields & { readonly toolCall: StaticToolCall | DynamicToolCall; readonly toolContext: unknown; readonly toolOutput: ToolOutput; }; /** * Event passed to the `onToolExecutionEnd` callback. * * Called when a tool execution completes, either successfully or with an error. * Uses the `toolOutput.type` discriminator to distinguish success and error. */ type ToolExecutionEndEvent = [ToolSet] extends [TOOLS] ? WidenedToolExecutionEndEvent : StaticToolExecutionEndEvent | DynamicToolExecutionEndEvent; /** * Callback that is set using the `onToolExecutionStart` option. * * Called when a tool execution begins, before the tool's `execute` function is invoked. * Use this for logging tool invocations, tracking tool usage, or pre-execution validation. * * @param event - The event object containing tool call information. */ type OnToolExecutionStartCallback = Callback>; /** * Callback that is set using the `onToolExecutionEnd` option. * * Called when a tool execution completes, either successfully or with an error. * Use this for logging tool results, tracking execution time, or error handling. * * The event uses a discriminated union on `toolOutput.type`: * - When `toolOutput.type === 'tool-result'`: `toolOutput.output` contains the tool result. * - When `toolOutput.type === 'tool-error'`: `toolOutput.error` contains the error. * * @param event - The event object containing tool call result information. */ type OnToolExecutionEndCallback = Callback>; /** @deprecated Use `ToolExecutionStartEvent` instead. */ type OnToolCallStartEvent = ToolExecutionStartEvent; /** @deprecated Use `ToolExecutionEndEvent` instead. */ type OnToolCallFinishEvent = ToolExecutionEndEvent; /** * Mapping of tool names to functions that refine parsed tool inputs. * * Each refinement function receives the typed input for its tool and must return * an input with the same type shape. Refined inputs are used for tool execution, * output parts, lifecycle callbacks, and telemetry. */ type ToolInputRefinement = { [NAME in keyof TOOLS]?: (input: InferToolInput) => MaybePromiseLike> }; /** * Checks whether a tool context map contains any contextual tool entries. */ type IsEmptyObject = keyof OBJECT extends never ? true : false; /** * Helper type to make the toolsContext parameter optional, required, or * unavailable based on the tool set. */ type ToolsContextParameter = { tools?: TOOLS; } & (IsEmptyObject> extends true ? { toolsContext?: never; } : HasRequiredKey> extends true ? { toolsContext: InferToolSetContext; } : { toolsContext?: InferToolSetContext; }); type StreamTextInclude = { /** * Whether to retain the request body in step results. * The request body can be large when sending images or files. * * @default false */ requestBody?: boolean; /** * Whether to retain the request messages in step results. * The request messages can be large when sending images or files. * * @default false */ requestMessages?: boolean; /** * Whether to include raw chunks from the provider in the stream. * * When enabled, you will receive raw chunks with type 'raw' that contain * the unprocessed data from the provider. * * This allows access to cutting-edge provider features not yet wrapped by * the AI SDK. * * @default false */ rawChunks?: boolean; }; /** * A transformation that is applied to the stream. * * @param stopStream - A function that stops the source stream. * @param tools - The tools that are accessible to and can be called by the model. The model needs to support calling tools. */ type StreamTextTransform = (options: { tools: TOOLS; stopStream: () => void; }) => TransformStream, TextStreamPart>; /** * Callback that is set using the `onError` option. * * @param event - The event that is passed to the callback. */ type StreamTextOnErrorCallback = Callback<{ error: unknown; }>; /** * Callback that is set using the `onChunk` option. * * @param event - The event that is passed to the callback. */ type StreamTextOnChunkCallback = (event: { chunk: TextStreamPart; }) => PromiseLike | void; /** * Callback that is set using the `onAbort` option. * * @param event - The event that is passed to the callback. */ type StreamTextOnAbortCallback = Callback<{ /** * Details for all previously finished steps. */ readonly steps: StepResult[]; }>; /** * Generate a text and call tools for a given prompt using a language model. * * This function streams the output. If you do not want to stream the output, use `generateText` instead. * * @param model - The language model to use. * @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools. * @param toolOrder - Controls the order in which tools are sent to the provider. Tools not listed are appended alphabetically. * * @param system - A system message that will be part of the prompt. * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both. * @param messages - A list of messages. You can either use `prompt` or `messages` but not both. * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false. * * @param maxOutputTokens - Maximum number of tokens to generate. * @param temperature - Temperature setting. * The value is passed through to the provider. The range depends on the provider and model. * It is recommended to set either `temperature` or `topP`, but not both. * @param topP - Nucleus sampling. * The value is passed through to the provider. The range depends on the provider and model. * It is recommended to set either `temperature` or `topP`, but not both. * @param topK - 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. * @param presencePenalty - Presence penalty setting. * It affects the likelihood of the model to repeat information that is already in the prompt. * The value is passed through to the provider. The range depends on the provider and model. * @param frequencyPenalty - Frequency penalty setting. * It affects the likelihood of the model to repeatedly use the same words or phrases. * The value is passed through to the provider. The range depends on the provider and model. * @param stopSequences - Stop sequences. * If set, the model will stop generating text when one of the stop sequences is generated. * @param seed - The seed (integer) to use for random sampling. * If set and supported by the model, calls will generate deterministic results. * * @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 timeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout. * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. * * @param experimental_sandbox - The sandbox environment that is passed through to tool execution. * @param runtimeContext - User-defined runtime context that flows through the entire generation lifecycle. * @param experimental_refineToolInput - Optional mapping of tool names to functions that refine parsed tool inputs before tools are executed and before outputs, callbacks, and telemetry are recorded. * * @param onChunk - Callback that is called for each chunk of the stream. The stream processing will pause until the callback promise is resolved. * @param onError - Callback that is called when an error occurs during streaming. You can use it to log errors. * @param onStart - Callback invoked when generation begins, before any LLM calls. * @param experimental_onStart - Deprecated alias for `onStart`. * @param onStepStart - Callback invoked when each step begins, before the provider is called. * @param experimental_onStepStart - Deprecated alias for `onStepStart`. * @param onLanguageModelCallStart - Callback invoked immediately before each provider model call begins. * @param experimental_onLanguageModelCallStart - Deprecated alias for `onLanguageModelCallStart`. * @param onLanguageModelCallEnd - Callback invoked after each provider model call response is normalized and parsed. * @param experimental_onLanguageModelCallEnd - Deprecated alias for `onLanguageModelCallEnd`. * @param onToolExecutionStart - Callback invoked before each tool execution begins. * @param experimental_onToolCallStart - Deprecated alias for `onToolExecutionStart`. * @param onToolExecutionEnd - Callback invoked after each tool execution completes. * @param experimental_onToolCallFinish - Deprecated alias for `onToolExecutionEnd`. * @param onStepEnd - Callback that is called when each step (LLM call) ends, including intermediate steps. * @param onStepFinish - Deprecated alias for `onStepEnd`. * @param onEnd - Callback that is called when all steps are finished and the response is complete. * @param onFinish - Deprecated alias for `onEnd`. * * @returns * A result object for accessing different stream types and additional information. */ declare function streamText>({ model, tools, toolChoice, instructions, system, prompt, messages, allowSystemInMessages, maxRetries, abortSignal, timeout, headers, stopWhen, experimental_sandbox: sandbox, output, toolApproval, experimental_toolCallers, experimental_toolApprovalSecret, experimental_telemetry, telemetry, prepareStep, providerOptions, activeTools, toolOrder, experimental_repairToolCall, repairToolCall, experimental_refineToolInput: refineToolInput, experimental_transform: transform, experimental_download: download, includeRawChunks, onChunk, onError, onFinish, onEnd, onAbort, onStepEnd, onStepFinish, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onLanguageModelCallStart, experimental_onLanguageModelCallStart, onLanguageModelCallEnd, experimental_onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, experimental_onToolCallStart, experimental_onToolCallFinish, runtimeContext, toolsContext, experimental_include, include, _internal: { now, generateId, generateCallId }, ...settings }: LanguageModelCallOptions & RequestOptions & Prompt & ToolsContextParameter & { /** * The language model to use. */ model: LanguageModel; /** * The tool choice strategy. Default: 'auto'. */ toolChoice?: ToolChoice; /** * Condition for stopping the generation when there are tool results in the last step. * When the condition is an array, any of the conditions can be met to stop the generation. * * @default isStepCount(1) */ stopWhen?: Arrayable, RUNTIME_CONTEXT>>; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions>; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions>; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * The sandbox environment that is passed through to tool execution. */ experimental_sandbox?: SandboxSession; /** * Runtime context. Treat runtime context as immutable. * If you need to mutate runtime context, update it in `prepareStep`. */ runtimeContext?: RUNTIME_CONTEXT; /** * Limits the tools that are available for the model to call without * changing the tool call and result types in the result. */ activeTools?: ActiveTools>; /** * Controls the order in which tools are sent to the provider. * * The list can be partial. Tools not listed in `toolOrder` are sent after * the listed tools, sorted alphabetically. This can improve provider-side * caching by keeping tool definitions in a stable order. */ toolOrder?: ToolOrder>; /** * Optional specification for parsing structured outputs from the LLM response. */ output?: OUTPUT; /** * Optional tool approval configuration. * * This configuration takes precedence over tool-defined approval settings. */ toolApproval?: ToolApprovalConfiguration; /** * Configures which caller tools may invoke each tool. */ experimental_toolCallers?: Experimental_ToolCallers>; /** * Secret for HMAC-signing tool approval requests. When set, the server * signs each approval request at issuance and verifies the signature when * the approval is replayed, preventing client-forged approvals. */ experimental_toolApprovalSecret?: string | Uint8Array; /** * Optional function that you can use to provide different settings for a step. * * @param options - The options for the step. * @param options.steps - The steps that have been executed so far. * @param options.stepNumber - The number of the step that is being executed. * @param options.model - The model that is being used. * * @returns An object that contains the settings for the step. * If you return undefined (or for undefined settings), the settings from the outer level will be used. */ prepareStep?: PrepareStepFunction, RUNTIME_CONTEXT>; /** * A function that attempts to repair a tool call that failed to parse. */ repairToolCall?: ToolCallRepairFunction; /** * A function that attempts to repair a tool call that failed to parse. * * @deprecated Use `repairToolCall` instead. */ experimental_repairToolCall?: ToolCallRepairFunction; /** * Optional mapping of tool names to functions that refine parsed tool inputs. * * The refined input must have the same type shape as the tool input. Refined * inputs are used for tool execution, stream parts, callbacks, and telemetry. */ experimental_refineToolInput?: ToolInputRefinement>; /** * Optional stream transformations. * They are applied in the order they are provided. * The stream transformations must maintain the stream structure for streamText to work correctly. */ experimental_transform?: Arrayable>; /** * Custom download function to use for URLs. * * By default, files are downloaded if the model does not support the URL for the given media type. */ experimental_download?: DownloadFunction | undefined; /** * Whether to include raw chunks from the provider in the stream. * When enabled, you will receive raw chunks with type 'raw' that contain the unprocessed data from the provider. * This allows access to cutting-edge provider features not yet wrapped by the AI SDK. * Defaults to false. * * @deprecated Use `include.rawChunks` instead. */ includeRawChunks?: boolean; /** * Callback that is called for each chunk of the stream. * The stream processing will pause until the callback promise is resolved. */ onChunk?: StreamTextOnChunkCallback; /** * Callback that is invoked when an error occurs during streaming. * You can use it to log errors. * The stream processing will pause until the callback promise is resolved. */ onError?: StreamTextOnErrorCallback; /** * Callback that is called when the LLM response and all request tool executions * (for tools that have an `execute` function) are finished. * * The usage is the combined usage of all steps. */ onEnd?: GenerateTextOnEndCallback, NoInfer>; /** * Callback that is called when the LLM response and all request tool executions * (for tools that have an `execute` function) are finished. * * The usage is the combined usage of all steps. * * @deprecated Use `onEnd` instead. */ onFinish?: GenerateTextOnEndCallback, NoInfer>; onAbort?: StreamTextOnAbortCallback, NoInfer>; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. */ onStepEnd?: GenerateTextOnStepEndCallback, NoInfer>; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: GenerateTextOnStepFinishCallback, NoInfer>; /** * Callback that is called when the streamText operation begins, * before any LLM calls are made. */ onStart?: GenerateTextOnStartCallback, NoInfer, NoInfer>; /** * Callback that is called when the streamText operation begins, * before any LLM calls are made. * * @deprecated Use `onStart` instead. */ experimental_onStart?: GenerateTextOnStartCallback, NoInfer, NoInfer>; /** * Callback that is called when a step (LLM call) begins, * before the provider is called. */ onStepStart?: GenerateTextOnStepStartCallback, NoInfer, NoInfer>; /** * Callback that is called when a step (LLM call) begins, * before the provider is called. * * @deprecated Use `onStepStart` instead. */ experimental_onStepStart?: GenerateTextOnStepStartCallback, NoInfer, NoInfer>; /** * Callback that is called immediately before the provider model call begins. */ onLanguageModelCallStart?: OnLanguageModelCallStartCallback; /** * Callback that is called immediately before the provider model call begins. * * @deprecated Use `onLanguageModelCallStart` instead. */ experimental_onLanguageModelCallStart?: OnLanguageModelCallStartCallback; /** * Callback that is called after the model response has been normalized and parsed, * but before any client-side tool execution begins. */ onLanguageModelCallEnd?: OnLanguageModelCallEndCallback>; /** * Callback that is called after the model response has been normalized and parsed, * but before any client-side tool execution begins. * * @deprecated Use `onLanguageModelCallEnd` instead. */ experimental_onLanguageModelCallEnd?: OnLanguageModelCallEndCallback>; /** * Callback that is called right before a tool's execute function runs. */ onToolExecutionStart?: OnToolExecutionStartCallback>; /** * Callback that is called right before a tool's execute function runs. * * @deprecated Use `onToolExecutionStart` instead. */ experimental_onToolCallStart?: OnToolExecutionStartCallback>; /** * Callback that is called right after a tool's execute function completes (or errors). */ onToolExecutionEnd?: OnToolExecutionEndCallback>; /** * Callback that is called right after a tool's execute function completes (or errors). * * @deprecated Use `onToolExecutionEnd` instead. */ experimental_onToolCallFinish?: OnToolExecutionEndCallback>; /** * Settings for controlling what data is included in step results. * Disabling inclusion can help reduce memory usage when processing * large payloads like images. * * By default, request bodies and request messages are excluded. */ include?: StreamTextInclude; /** * Settings for controlling what data is included in step results. * * @deprecated Use `include` instead. */ experimental_include?: StreamTextInclude; /** * Internal. For test use only. May change without notice. */ _internal?: { now?: () => number; generateId?: IdGenerator; generateCallId?: IdGenerator; }; }): StreamTextResult; type EnrichedStreamPart = { part: TextStreamPart; partialOutput: PARTIAL_OUTPUT | undefined; }; interface Output { /** * The name of the output mode. */ name: string; /** * The response format to use for the model. */ responseFormat: PromiseLike; /** * Parses the complete output of the model. */ parseCompleteOutput(options: { text: string; }, context: { response: Omit; usage: LanguageModelUsage; finishReason: FinishReason; }): Promise; /** * Parses the partial output of the model. */ parsePartialOutput(options: { text: string; }): Promise<{ partial: PARTIAL; } | undefined>; /** * Creates a stream transform that emits individual elements as they complete. */ createElementStreamTransform(): TransformStream, ELEMENT> | undefined; } /** * Output specification for text generation. * This is the default output mode that generates plain text. * * @returns An output specification for generating text. */ declare const text$1: () => Output; /** * Output specification for typed object generation using schemas. * When the model generates a text response, it will return an object that matches the schema. * * @param schema - The schema of the object to generate. * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description. * * @returns An output specification for generating objects with the specified schema. */ declare const object: ({ schema: inputSchema, name, description }: { schema: FlexibleSchema; /** * Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. via tool or schema name. */ name?: 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. */ description?: string; }) => Output, never>; /** * Output specification for array generation. * When the model generates a text response, it will return an array of elements. * * @param element - The schema of the array elements to generate. * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description. * * @returns An output specification for generating an array of elements. */ declare const array: ({ element: inputElementSchema, name, description }: { element: FlexibleSchema; /** * Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. via tool or schema name. */ name?: 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. */ description?: string; }) => Output, Array, ELEMENT>; /** * Output specification for choice generation. * When the model generates a text response, it will return a one of the choice options. * * @param options - The available choices. * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description. * * @returns An output specification for generating a choice. */ declare const choice: ({ options: choiceOptions, name, description }: { options: Array; /** * Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. via tool or schema name. */ name?: 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. */ description?: string; }) => Output; /** * Output specification for unstructured JSON generation. * When the model generates a text response, it will return a JSON object. * * @param name - Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema name. * @param description - Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g. via tool or schema description. * * @returns An output specification for generating JSON. */ declare const json: ({ name, description }?: { /** * Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. via tool or schema name. */ name?: 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. */ description?: string; }) => Output; type output_Output = Output; declare const output_array: typeof array; declare const output_choice: typeof choice; declare const output_json: typeof json; declare const output_object: typeof object; declare const output_text: typeof text$1; declare namespace output { export { output_Output as Output, output_array as array, output_choice as choice, output_json as json, output_object as object, output_text as text }; } /** * Event passed to the `onStart` callback. * * Called when the generation operation begins, before any LLM calls. */ type GenerateTextStartEvent = { /** Unique identifier for this generation call, used to correlate events. */readonly callId: string; /** Identifies the operation type (e.g. 'ai.generateText' or 'ai.streamText'). */ readonly operationId: string; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** The tools available for this generation. */ readonly tools: TOOLS | undefined; /** The tool choice strategy for this generation. */ readonly toolChoice: ToolChoice> | undefined; /** Limits which tools are available for the model to call. */ readonly activeTools: ActiveTools; /** Controls the order in which tools are sent to the provider. */ readonly toolOrder: ToolOrder; /** Maximum number of retries for failed requests. */ readonly maxRetries: number; /** * Timeout configuration for the generation. * Can be a number (milliseconds) or an object with totalMs, stepMs, * firstChunkMs (streaming only), chunkMs, toolMs, and per-tool overrides via tools. */ readonly timeout: TimeoutConfiguration | undefined; /** Additional HTTP headers sent with the request. */ readonly headers: Record | undefined; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions | undefined; /** The output specification for structured outputs, if configured. */ readonly output: OUTPUT | undefined; /** * Tool context. */ readonly toolsContext: InferToolSetContext; /** * User-defined runtime context. */ readonly runtimeContext: RUNTIME_CONTEXT; } & LanguageModelCallOptions & StandardizedPrompt; /** * Event passed to the `onStepStart` callback. * * Called when a step (LLM call) begins, before the provider is called. * Each step represents a single LLM invocation. */ type GenerateTextStepStartEvent = { /** Unique identifier for this generation call, used to correlate events. */readonly callId: string; /** The provider identifier (e.g., 'openai', 'anthropic'). */ readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** Zero-based index of the current step. */ readonly stepNumber: number; /** The tools available for this generation. */ readonly tools: TOOLS | undefined; /** The tool choice configuration for this step. */ readonly toolChoice: ToolChoice> | undefined; /** Limits which tools are available for this step. */ readonly activeTools: ActiveTools; /** Controls the order in which tools are sent to the provider for this step. */ readonly toolOrder: ToolOrder; /** Array of results from previous steps (empty for first step). */ readonly steps: ReadonlyArray>; /** Additional provider-specific options for this step. */ readonly providerOptions: ProviderOptions | undefined; /** The output specification for structured outputs, if configured. */ readonly output: OUTPUT | undefined; /** * Runtime context. May be updated from `prepareStep` between steps. */ readonly runtimeContext: RUNTIME_CONTEXT; /** * Tool context. May be updated from `prepareStep` between steps. */ readonly toolsContext: InferToolSetContext; } & StandardizedPrompt; /** * Event passed to the `onStepEnd` callback. * * Called when a step (LLM call) completes. * Includes the StepResult for that step along with the call identifier. */ type GenerateTextStepEndEvent = StepResult; /** * Event passed to the `onEnd` callback. * * Called when the entire generation completes (all steps finished). * Includes the final step's result along with aggregated data from all steps. */ type GenerateTextEndEvent = { /** Unique identifier for this generation call, used to correlate events. */readonly callId: string; /** Zero-based index of the final step. */ readonly stepNumber: number; /** Information about the model that produced the final step. */ readonly model: StepResult['model']; /** * Tool context from the final step. * * @deprecated Use `finalStep.toolsContext` instead. */ readonly toolsContext: InferToolSetContext; /** * Runtime context from the final step. * * @deprecated Use `finalStep.runtimeContext` instead. */ readonly runtimeContext: RUNTIME_CONTEXT; /** The content that was generated in all steps. */ readonly content: StepResult['content']; /** The text that was generated in the final step. */ readonly text: StepResult['text']; /** * The reasoning that was generated in the final step. * * @deprecated Use `finalStep.reasoning` instead. */ readonly reasoning: StepResult['reasoning']; /** * The reasoning text that was generated in the final step. * * @deprecated Use `finalStep.reasoningText` instead. */ readonly reasoningText: StepResult['reasoningText']; /** Files that were generated in all steps. */ readonly files: StepResult['files']; /** Sources that were used as references in all steps. */ readonly sources: StepResult['sources']; /** Tool calls that were made in all steps. */ readonly toolCalls: StepResult['toolCalls']; /** Static tool calls that were made in all steps. */ readonly staticToolCalls: StepResult['staticToolCalls']; /** Dynamic tool calls that were made in all steps. */ readonly dynamicToolCalls: StepResult['dynamicToolCalls']; /** Tool results that were generated in all steps. */ readonly toolResults: StepResult['toolResults']; /** Static tool results that were generated in all steps. */ readonly staticToolResults: StepResult['staticToolResults']; /** Dynamic tool results that were generated in all steps. */ readonly dynamicToolResults: StepResult['dynamicToolResults']; /** The unified reason why the generation finished. Taken from the final step. */ readonly finishReason: StepResult['finishReason']; /** The raw reason why the generation finished. Taken from the final step. */ readonly rawFinishReason: StepResult['rawFinishReason']; /** Aggregated token usage across all steps. */ readonly usage: LanguageModelUsage; /** * Aggregated token usage across all steps. * * @deprecated Use `usage` instead. */ readonly totalUsage: LanguageModelUsage; /** Warnings from the model provider in all steps. */ readonly warnings: StepResult['warnings']; /** * Additional request information from the final step. * * @deprecated Use `finalStep.request` instead. */ readonly request: StepResult['request']; /** * Additional response information from the final step. * * @deprecated Use `finalStep.response` instead. */ readonly response: StepResult['response']; /** * Additional provider-specific metadata from the final step. * * @deprecated Use `finalStep.providerMetadata` instead. */ readonly providerMetadata: StepResult['providerMetadata']; /** The response messages that were generated during the call. */ readonly responseMessages: ResponseMessage[]; /** Array containing results from all steps in the generation. */ readonly steps: StepResult[]; /** The final step. This is a shortcut for `steps.at(-1)`. */ readonly finalStep: StepResult; }; /** * Event passed to the telemetry `onAbort` callback. * * Called when a streaming text generation operation is aborted before it * completes. */ type GenerateTextAbortEvent = { /** Unique identifier for this generation call, used to correlate events. */readonly callId: string; /** Details for all previously finished steps. */ readonly steps: StepResult[]; /** The abort reason from the AbortSignal, when one is available. */ readonly reason?: unknown; }; /** @deprecated Use `GenerateTextStartEvent` instead. */ type OnStartEvent = GenerateTextStartEvent; /** @deprecated Use `GenerateTextStepStartEvent` instead. */ type OnStepStartEvent = GenerateTextStepStartEvent; /** @deprecated Use `GenerateTextStepEndEvent` instead. */ type OnStepFinishEvent = GenerateTextStepEndEvent; /** @deprecated Use `GenerateTextEndEvent` instead. */ type OnFinishEvent = GenerateTextEndEvent; /** * Callback that is set using the `onStart` option. * * Called when the generateText operation begins, before any LLM calls. * Use this callback for logging, analytics, or initializing state at the * start of a generation. * * @param event - The event object containing generation configuration. */ type GenerateTextOnStartCallback = Callback>; /** * Callback that is set using the `onStepStart` option. * * Called when a step (LLM call) begins, before the provider is called. * Each step represents a single LLM invocation. Multiple steps occur when * using tool calls (the model may be called multiple times in a loop). * * @param event - The event object containing step configuration. */ type GenerateTextOnStepStartCallback = Callback>; /** * Callback that is set using the `onStepEnd` option. * * Called when a step (LLM call) completes. The event includes all step result * properties (text, tool calls, usage, etc.) along with additional metadata. * * @param stepResult - The result of the step. */ type GenerateTextOnStepEndCallback = Callback>; /** * Callback that is set using the `onStepFinish` option. * * @deprecated Use `GenerateTextOnStepEndCallback` instead. */ type GenerateTextOnStepFinishCallback = GenerateTextOnStepEndCallback; /** * Callback that is set using the `onEnd` option. * * Called when the entire generation completes (all steps finished). * The event includes the final step's result properties along with * aggregated data from all steps. * * @param event - The final result along with aggregated step data. */ type GenerateTextOnEndCallback = Callback>; /** * Callback that is set using the telemetry `onAbort` option. * * Called when a streaming text generation operation is aborted before it * completes. * * @param event - The abort event, including finished steps and abort reason. */ type GenerateTextOnAbortCallback = Callback>; /** * Callback that is set using the `onFinish` option. * * @deprecated Use `GenerateTextOnEndCallback` instead. */ type GenerateTextOnFinishCallback = GenerateTextOnEndCallback; /** * Event passed to the `onStart` callback for rerank operations. * * Called when the operation begins, before the reranking model is called. */ type RerankStartEvent = { /** Unique identifier for this rerank call, used to correlate events. */readonly callId: string; /** Identifies the operation type ('ai.rerank'). */ readonly operationId: string; readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** The documents being reranked. */ readonly documents: Array; /** The query to rerank the documents against. */ readonly query: string; /** Number of top documents to return. */ readonly topN: number | undefined; /** Maximum number of retries for failed requests. */ readonly maxRetries: number; /** Additional HTTP headers sent with the request. */ readonly headers: Record | undefined; /** Additional provider-specific options. */ readonly providerOptions: ProviderOptions | undefined; }; /** * Event passed to the `onEnd` callback for rerank operations. * * Called when the operation completes, after the reranking model returns. */ type RerankEndEvent = { /** Unique identifier for this rerank call, used to correlate events. */readonly callId: string; /** Identifies the operation type ('ai.rerank'). */ readonly operationId: string; readonly provider: string; /** The specific model identifier (e.g., 'gpt-4o'). */ readonly modelId: string; /** The documents that were reranked. */ readonly documents: Array; /** The query that documents were reranked against. */ readonly query: string; /** The reranked results sorted by relevance score in descending order. */ readonly ranking: Array<{ originalIndex: number; score: number; document: JSONObject$2 | string; }>; /** Warnings from the reranking model. */ readonly warnings: Array; /** Optional provider-specific metadata. */ readonly providerMetadata: ProviderMetadata | undefined; /** Response data including headers and body. */ readonly response: { id?: string; timestamp: Date; modelId: string; headers?: Record; body?: unknown; }; }; /** * Event fired when an individual reranking model call (inner doRerank) begins. */ type RerankingModelCallStartEvent = { /** Unique identifier for this rerank call, used to correlate events. */readonly callId: string; /** Identifies the inner operation ('ai.rerank.doRerank'). */ readonly operationId: string; /** The provider identifier. */ readonly provider: string; /** The specific model identifier. */ readonly modelId: string; /** The documents being reranked. */ readonly documents: Array; /** The type of documents ('text' or 'object'). */ readonly documentsType: string; /** The query to rerank against. */ readonly query: string; /** Number of top documents to return. */ readonly topN: number | undefined; }; /** * Event fired when an individual reranking model call (doRerank) completes. * * Contains the ranking results from the model response. */ type RerankingModelCallEndEvent = { /** Unique identifier for this rerank call, used to correlate events. */readonly callId: string; /** Identifies the inner operation ('ai.rerank.doRerank'). */ readonly operationId: string; /** The provider identifier. */ readonly provider: string; /** The specific model identifier. */ readonly modelId: string; /** The type of documents ('text' or 'object'). */ readonly documentsType: string; /** The ranking results from the model. */ readonly ranking: Array<{ index: number; relevanceScore: number; }>; }; declare const AI_SDK_TELEMETRY_TRACING_CHANNEL = "ai:telemetry"; type TelemetryTracingEventType = 'generateText' | 'streamText' | 'step' | 'languageModelCall' | 'executeTool' | 'embed' | 'embedMany' | 'rerank'; type TelemetryTracingChannelMessage = { readonly type: TelemetryTracingEventType; readonly event: EVENT; }; type InferTelemetryEvent = EVENT & Omit; type OperationStartEvent = GenerateTextStartEvent | GenerateObjectStartEvent | EmbedStartEvent | RerankStartEvent; type OperationEndEvent = GenerateTextEndEvent | GenerateObjectEndEvent | EmbedEndEvent | RerankEndEvent; /** * Implement this interface to create custom telemetry integrations. * Methods can be sync or return a PromiseLike. */ interface Telemetry { /** * Called when an operation begins. Fired for text generation * (generateText/streamText), object generation (generateObject/streamObject), * embedding (embed/embedMany), and reranking operations. * * Use the `operationId` field to distinguish between operation types. */ onStart?: Callback>; /** * Called when an individual step (single LLM invocation) begins. * A generation may consist of multiple steps (e.g. when tool calls trigger * follow-up LLM calls). Use this to create per-step spans or record * step-level inputs. * * The event includes the step number, accumulated previous step results, * and the messages that will be sent to the model. */ onStepStart?: Callback>; /** * Called immediately before the provider model call begins. * Unlike `onStepStart`, this callback is scoped to model work only and * excludes any later client-side tool execution. */ onLanguageModelCallStart?: Callback>; /** * Called after the model response has been normalized and parsed, but before * any client-side tool execution begins. */ onLanguageModelCallEnd?: Callback>; /** * Called when a tool execution begins, before the tool's `execute` function * is invoked. Use this to create tool-level spans or log tool invocations. */ onToolExecutionStart?: Callback>; /** * Called when a tool execution completes, either successfully or with an error. * The event uses a discriminated union on the `success` field — check * `event.success` to determine whether `output` or `error` is available. * * The event includes execution time (`toolExecutionMs`) for performance tracking. */ onToolExecutionEnd?: Callback>; /** * Called when an individual step (single LLM invocation) completes. * The event is a `StepResult` containing the model's response, tool calls * and results, usage statistics, finish reason, and optional request/response * bodies. */ onStepEnd?: Callback>; /** * Called when an individual step (single LLM invocation) completes. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: Callback>; /** * Called when an object generation step (single LLM invocation) begins. * For generateObject/streamObject there is always exactly one step. * * @deprecated */ onObjectStepStart?: Callback>; /** * Called when an object generation step (single LLM invocation) completes, * with the raw result before JSON parsing and schema validation. * * @deprecated */ onObjectStepEnd?: Callback>; /** * Called when an individual embedding model call (doEmbed) begins. * For `embed`, there is one call. For `embedMany`, there may be multiple * calls when values are chunked. */ onEmbedStart?: Callback>; /** * Called when an individual embedding model call (doEmbed) completes. * Contains the embeddings, usage, and any warnings from the model response. */ onEmbedEnd?: Callback>; /** * Called when an individual reranking model call (doRerank) begins. * There is one call per `rerank` invocation. */ onRerankStart?: Callback>; /** * Called when an individual reranking model call (doRerank) completes. * Contains the ranking results from the model response. */ onRerankEnd?: Callback>; /** * Called when an operation completes. Fired for text generation * (generateText/streamText), object generation (generateObject/streamObject), * embedding (embed/embedMany), and reranking operations. * * Use the event shape or `operationId` to distinguish between operation types. */ onEnd?: Callback>; /** * Called when a streaming text generation operation is aborted before it * completes. */ onAbort?: Callback>>; /** * Called when an unrecoverable error occurs during the generation lifecycle. * The error value is untyped — it may be an `Error` instance, an `AISDKError`, * or any thrown value. * * Use this to record error details on telemetry spans and set error status. */ onError?: Callback; /** * Optionally runs the language model call in a telemetry-integration-specific context. This enables * auto-instrumented model provider requests to become children of the current * model-call span. * * The options carry the model-call start-event content as context (the event * fields are optional), alongside the always-present `callId` and the * `execute` function that performs the model call. */ executeLanguageModelCall?: (options: Partial> & { callId: string; execute: () => PromiseLike; }) => PromiseLike; /** * Optionally runs the tool execute function in a telemetry-integration-specific context. This enables * nested traces — e.g. when a tool's `execute` function calls `generateText`, * the inner call's spans become children of the tool span. * * The options carry the tool-execution start-event content as context (the * event fields are optional), alongside the always-present `callId`, * `toolCallId`, and the `execute` function to run. */ executeTool?: (options: Partial> & { callId: string; toolCallId: string; execute: () => PromiseLike; }) => PromiseLike; } declare global { /** * The default provider to use for the AI SDK. * String model ids are resolved to the default provider and model id. * * If not set, the default provider is the Vercel AI gateway provider. * * @see https://ai-sdk.dev/docs/ai-sdk-core/provider-management#global-provider-configuration */ var AI_SDK_DEFAULT_PROVIDER: ProviderV4 | ProviderV3 | ProviderV2 | undefined; /** * The warning logger to use for the AI SDK. * * If not set, the default logger is the console.warn function. * * If set to false, no warnings are logged. */ var AI_SDK_LOG_WARNINGS: LogWarningsFunction | undefined | false; /** * Globally registered telemetry integrations for the AI SDK. * * Integrations registered here receive lifecycle events (onStart, onStepStart, * etc.) from every `generateText`, `streamText`, and similar call. * * Prefer using `registerTelemetry()` from `'ai'` instead of * assigning this directly. */ var AI_SDK_TELEMETRY_INTEGRATIONS: Telemetry[] | undefined; } /** * The result of a `generateText` call. * It contains the generated text, the tool calls that were made during the generation, and the results of the tool calls. */ interface GenerateTextResult { /** * The content that was generated in all steps. */ readonly content: Array>; /** * The concatenation of all text parts generated in the final step. * It is an empty string if the final step contains no text parts. * Inspect `finalStep.content` to distinguish that case. */ readonly text: string; /** * The full reasoning that the model has generated in the last step. * * @deprecated Use `finalStep.reasoning` instead. */ readonly reasoning: Array; /** * The reasoning text that the model has generated in the last step. Can be undefined if the model * has only generated text. * * @deprecated Use `finalStep.reasoningText` instead. */ readonly reasoningText: string | undefined; /** * The files that were generated in all steps. * Empty array if no files were generated. */ readonly files: Array; /** * Sources that have been used as references in all steps. */ readonly sources: Array; /** * The tool calls that were made in all steps. */ readonly toolCalls: Array>; /** * The static tool calls that were made in all steps. */ readonly staticToolCalls: Array>; /** * The dynamic tool calls that were made in all steps. */ readonly dynamicToolCalls: Array; /** * The results of the tool calls from all steps. */ readonly toolResults: Array>; /** * The static tool results that were made in all steps. */ readonly staticToolResults: Array>; /** * The dynamic tool results that were made in all steps. */ readonly dynamicToolResults: Array; /** * The unified reason why the generation finished. */ readonly finishReason: FinishReason; /** * The raw reason why the generation finished (from the provider). */ readonly rawFinishReason: string | undefined; /** * The total token usage of all steps. * When there are multiple steps, the usage is the sum of all step usages. */ readonly usage: LanguageModelUsage; /** * The total token usage of all steps. * When there are multiple steps, the usage is the sum of all step usages. * * @deprecated Use `usage` instead. */ readonly totalUsage: LanguageModelUsage; /** * Warnings from the model provider (e.g. unsupported settings) in all steps. */ readonly warnings: CallWarning[] | undefined; /** * Additional request information from the last step. * * @deprecated Use `finalStep.request` instead. */ readonly request: StepResult['request']; /** * Additional response information from the last step. * * @deprecated Use `finalStep.response` instead. */ readonly response: LanguageModelResponseMetadata; /** * The accumulated response messages of all steps that were generated during the call. */ readonly responseMessages: Array; /** * Additional provider-specific metadata from the final step. They are passed * through from the provider to the AI SDK and enable provider-specific * results that can be fully encapsulated in the provider. * * @deprecated Use `finalStep.providerMetadata` instead. */ readonly providerMetadata: ProviderMetadata | undefined; /** * Details for all steps. * You can use this to get information about intermediate steps, * such as the tool calls or the response headers. */ readonly steps: Array>; /** * The final step. This is a shortcut for `steps.at(-1)`. */ readonly finalStep: StepResult; /** * The generated output according to the `output` specification. * * @throws {NoOutputGeneratedError} When no output is available, for example * when the final step does not finish with a `stop` reason. */ readonly output: InferCompleteOutput; } /** * Parameters for calling an agent. */ type AgentCallParameters = ([CALL_OPTIONS] extends [never] ? { options?: never; } : { options: CALL_OPTIONS; }) & ({ /** * A prompt. It can be either a text prompt or a list of messages. * * You can either use `prompt` or `messages` but not both. */ prompt: string | Array; /** * A list of messages. * * You can either use `prompt` or `messages` but not both. */ messages?: never; } | { /** * A list of messages. * * You can either use `prompt` or `messages` but not both. */ messages: Array; /** * A prompt. It can be either a text prompt or a list of messages. * * You can either use `prompt` or `messages` but not both. */ prompt?: never; }) & { /** * Abort signal. */ abortSignal?: AbortSignal; /** * Timeout in milliseconds. Can be specified as a number or as an object * with total, per-step, first-content, inter-content, and tool timeouts. * First-content and inter-content timeouts are only enforced by streaming * calls. */ timeout?: TimeoutConfiguration; /** * Callback that is called when the agent operation begins, before any LLM calls. */ onStart?: GenerateTextOnStartCallback; /** * Callback that is called when the agent operation begins, before any LLM calls. * * @deprecated Use `onStart` instead. */ experimental_onStart?: GenerateTextOnStartCallback; /** * Callback that is called when a step (LLM call) begins, before the provider is called. */ onStepStart?: GenerateTextOnStepStartCallback; /** * Callback that is called when a step (LLM call) begins, before the provider is called. * * @deprecated Use `onStepStart` instead. */ experimental_onStepStart?: GenerateTextOnStepStartCallback; /** * Callback that is called before each tool execution begins. */ onToolExecutionStart?: OnToolExecutionStartCallback; /** * Callback that is called before each tool execution begins. * * @deprecated Use `onToolExecutionStart` instead. */ experimental_onToolCallStart?: OnToolExecutionStartCallback; /** * Callback that is called after each tool execution completes. */ onToolExecutionEnd?: OnToolExecutionEndCallback; /** * Callback that is called after each tool execution completes. * * @deprecated Use `onToolExecutionEnd` instead. */ experimental_onToolCallFinish?: OnToolExecutionEndCallback; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. */ onStepEnd?: GenerateTextOnStepEndCallback; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: GenerateTextOnStepFinishCallback; /** * Callback that is called when all steps are finished and the response is complete. */ onEnd?: GenerateTextOnEndCallback; /** * Callback that is called when all steps are finished and the response is complete. * * @deprecated Use `onEnd` instead. */ onFinish?: GenerateTextOnEndCallback; /** * The sandbox environment that is passed through to tool execution. */ experimental_sandbox?: SandboxSession; }; /** * Parameters for streaming an output from an agent. */ type AgentStreamParameters = AgentCallParameters & { /** * Optional stream transformations. * They are applied in the order they are provided. * The stream transformations must maintain the stream structure for streamText to work correctly. */ experimental_transform?: Arrayable>; }; /** * An Agent receives a prompt (text or messages) and generates or streams an output * that consists of steps, tool calls, data parts, etc. * * You can implement your own Agent by implementing the `Agent` interface, * or use the `ToolLoopAgent` class. */ interface Agent$1 { /** * The specification version of the agent interface. This will enable * us to evolve the agent interface and retain backwards compatibility. */ readonly version: 'agent-v1'; /** * The id of the agent. */ readonly id: string | undefined; /** * The tools that the agent can use. */ readonly tools: TOOLS; /** * Generates an output from the agent (non-streaming). */ generate(options: AgentCallParameters): PromiseLike>; /** * Streams an output from the agent (streaming). */ stream(options: AgentStreamParameters): PromiseLike>; } type GenerateTextInclude = { /** * Whether to retain the request body in step results. * The request body can be large when sending images or files. * * @default false */ requestBody?: boolean; /** * Whether to retain the request messages in step results. * The request messages can be large when sending images or files. * * @default false */ requestMessages?: boolean; /** * Whether to retain the response body in step results. * * @default false */ responseBody?: boolean; }; /** * Generate a text and call tools for a given prompt using a language model. * * This function does not stream the output. If you want to stream the output, use `streamText` instead. * * @param model - The language model to use. * * @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools. * @param toolChoice - The tool choice strategy. Default: 'auto'. * @param toolOrder - Controls the order in which tools are sent to the provider. Tools not listed are appended alphabetically. * * @param system - A system message that will be part of the prompt. * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both. * @param messages - A list of messages. You can either use `prompt` or `messages` but not both. * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false. * * @param maxOutputTokens - Maximum number of tokens to generate. * @param temperature - Temperature setting. * The value is passed through to the provider. The range depends on the provider and model. * It is recommended to set either `temperature` or `topP`, but not both. * @param topP - Nucleus sampling. * The value is passed through to the provider. The range depends on the provider and model. * It is recommended to set either `temperature` or `topP`, but not both. * @param topK - 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. * @param presencePenalty - Presence penalty setting. * It affects the likelihood of the model to repeat information that is already in the prompt. * The value is passed through to the provider. The range depends on the provider and model. * @param frequencyPenalty - Frequency penalty setting. * It affects the likelihood of the model to repeatedly use the same words or phrases. * The value is passed through to the provider. The range depends on the provider and model. * @param stopSequences - Stop sequences. * If set, the model will stop generating text when one of the stop sequences is generated. * @param seed - The seed (integer) to use for random sampling. * If set and supported by the model, calls will generate deterministic results. * * @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 timeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout. * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers. * * @param experimental_sandbox - The sandbox environment that is passed through to tool execution. * @param runtimeContext - User-defined runtime context that flows through the entire generation lifecycle. * @param experimental_refineToolInput - Optional mapping of tool names to functions that refine parsed tool inputs before tools are executed and before outputs, callbacks, and telemetry are recorded. * @param onStart - Callback invoked when generation begins, before any LLM calls. * @param experimental_onStart - Deprecated alias for `onStart`. * @param onStepStart - Callback invoked when each step begins, before the provider is called. * @param experimental_onStepStart - Deprecated alias for `onStepStart`. * Receives step number, messages (in ModelMessage format), tools, and runtimeContext. * @param onLanguageModelCallStart - Callback invoked immediately before each provider model call begins. * @param experimental_onLanguageModelCallStart - Deprecated alias for `onLanguageModelCallStart`. * @param onLanguageModelCallEnd - Callback invoked after each provider model call response is normalized and parsed. * @param experimental_onLanguageModelCallEnd - Deprecated alias for `onLanguageModelCallEnd`. * @param onToolExecutionStart - Callback invoked before each tool execution begins. * Receives tool name, call ID, input, and context. * @param experimental_onToolCallStart - Deprecated alias for `onToolExecutionStart`. * @param onToolExecutionEnd - Callback invoked after each tool execution completes. * Uses a discriminated union: check `success` to determine if `output` or `error` is present. * @param experimental_onToolCallFinish - Deprecated alias for `onToolExecutionEnd`. * @param onStepFinish - Callback that is called when each step (LLM call) is finished, including intermediate steps. * @param onEnd - Callback that is called when all steps are finished and the response is complete. * @param onFinish - Deprecated alias for `onEnd`. * * @returns * A result object that contains the generated text, the results of the tool calls, and additional information. */ declare function generateText>({ model: modelArg, tools, toolChoice, instructions, system, prompt, messages, allowSystemInMessages, maxRetries: maxRetriesArg, abortSignal, timeout, headers, stopWhen, experimental_sandbox: sandbox, output, toolApproval, experimental_toolCallers, experimental_toolApprovalSecret, experimental_telemetry, telemetry, providerOptions, activeTools, toolOrder, prepareStep, experimental_repairToolCall, repairToolCall, experimental_refineToolInput: refineToolInput, experimental_download: download, runtimeContext, toolsContext, experimental_include, include, _internal: { generateId, generateCallId, now }, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onLanguageModelCallStart, experimental_onLanguageModelCallStart, onLanguageModelCallEnd, experimental_onLanguageModelCallEnd, onToolExecutionStart, onToolExecutionEnd, experimental_onToolCallStart, experimental_onToolCallFinish, onStepEnd, onStepFinish, onFinish, onEnd, ...settings }: LanguageModelCallOptions & RequestOptions & Prompt & ToolsContextParameter & { /** * The language model to use. */ model: LanguageModel; /** * The tool choice strategy. Default: 'auto'. */ toolChoice?: ToolChoice>; /** * Condition for stopping the generation when there are tool results in the last step. * When the condition is an array, any of the conditions can be met to stop the generation. * * @default isStepCount(1) */ stopWhen?: Arrayable, RUNTIME_CONTEXT>>; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions>; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions>; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * The sandbox environment that is passed through to tool execution. */ experimental_sandbox?: SandboxSession; /** * Runtime context. Treat runtime context as immutable. * If you need to mutate runtime context, update it in `prepareStep`. */ runtimeContext?: RUNTIME_CONTEXT; /** * Limits the tools that are available for the model to call without * changing the tool call and result types in the result. */ activeTools?: ActiveTools>; /** * Controls the order in which tools are sent to the provider. * * The list can be partial. Tools not listed in `toolOrder` are sent after * the listed tools, sorted alphabetically. This can improve provider-side * caching by keeping tool definitions in a stable order. */ toolOrder?: ToolOrder>; /** * Optional specification for parsing structured outputs from the LLM response. */ output?: OUTPUT; /** * Optional tool approval configuration. * * This configuration takes precedence over tool-defined approval settings. */ toolApproval?: ToolApprovalConfiguration; /** * Configures which caller tools may invoke each tool. */ experimental_toolCallers?: Experimental_ToolCallers>; /** * Secret for HMAC-signing tool approval requests. When set, the server * signs each approval request at issuance and verifies the signature when * the approval is replayed, preventing client-forged approvals. */ experimental_toolApprovalSecret?: string | Uint8Array; /** * Custom download function to use for URLs. * * By default, files are downloaded if the model does not support the URL for the given media type. */ experimental_download?: DownloadFunction | undefined; /** * Optional function that you can use to provide different settings for a step. */ prepareStep?: PrepareStepFunction, RUNTIME_CONTEXT>; /** * A function that attempts to repair a tool call that failed to parse. */ repairToolCall?: ToolCallRepairFunction>; /** * A function that attempts to repair a tool call that failed to parse. * * @deprecated Use `repairToolCall` instead. */ experimental_repairToolCall?: ToolCallRepairFunction>; /** * Optional mapping of tool names to functions that refine parsed tool inputs. * * The refined input must have the same type shape as the tool input. Refined * inputs are used for tool execution, outputs, callbacks, and telemetry. */ experimental_refineToolInput?: ToolInputRefinement>; /** * Callback that is called when the generateText operation begins, * before any LLM calls are made. */ onStart?: GenerateTextOnStartCallback, NoInfer, NoInfer>; /** * Callback that is called when the generateText operation begins, * before any LLM calls are made. * * @deprecated Use `onStart` instead. */ experimental_onStart?: GenerateTextOnStartCallback, NoInfer, NoInfer>; /** * Callback that is called when a step (LLM call) begins, * before the provider is called. */ onStepStart?: GenerateTextOnStepStartCallback, NoInfer, NoInfer>; /** * Callback that is called when a step (LLM call) begins, * before the provider is called. * * @deprecated Use `onStepStart` instead. */ experimental_onStepStart?: GenerateTextOnStepStartCallback, NoInfer, NoInfer>; /** * Callback that is called immediately before the provider model call begins. */ onLanguageModelCallStart?: OnLanguageModelCallStartCallback; /** * Callback that is called immediately before the provider model call begins. * * @deprecated Use `onLanguageModelCallStart` instead. */ experimental_onLanguageModelCallStart?: OnLanguageModelCallStartCallback; /** * Callback that is called after the model response has been normalized and parsed, * but before any client-side tool execution begins. */ onLanguageModelCallEnd?: OnLanguageModelCallEndCallback>; /** * Callback that is called after the model response has been normalized and parsed, * but before any client-side tool execution begins. * * @deprecated Use `onLanguageModelCallEnd` instead. */ experimental_onLanguageModelCallEnd?: OnLanguageModelCallEndCallback>; /** * Callback that is called right before a tool's execute function runs. */ onToolExecutionStart?: OnToolExecutionStartCallback>; /** * Callback that is called right before a tool's execute function runs. * * @deprecated Use `onToolExecutionStart` instead. */ experimental_onToolCallStart?: OnToolExecutionStartCallback>; /** * Callback that is called right after a tool's execute function completes (or errors). */ onToolExecutionEnd?: OnToolExecutionEndCallback>; /** * Callback that is called right after a tool's execute function completes (or errors). * * @deprecated Use `onToolExecutionEnd` instead. */ experimental_onToolCallFinish?: OnToolExecutionEndCallback>; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. */ onStepEnd?: GenerateTextOnStepEndCallback, NoInfer>; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: GenerateTextOnStepFinishCallback, NoInfer>; /** * Callback that is called when all steps are finished and the response is complete. */ onEnd?: GenerateTextOnEndCallback, NoInfer>; /** * Callback that is called when all steps are finished and the response is complete. * * @deprecated Use `onEnd` instead. */ onFinish?: GenerateTextOnEndCallback, NoInfer>; /** * Settings for controlling what data is included in step results. * Disabling inclusion can help reduce memory usage when processing * large payloads like images. * * By default, request bodies, request messages, and response bodies are * excluded. */ include?: GenerateTextInclude; /** * Settings for controlling what data is included in step results. * * @deprecated Use `include` instead. */ experimental_include?: GenerateTextInclude; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: IdGenerator; generateCallId?: IdGenerator; now?: () => number; }; }): Promise>; /** * Configuration options for an agent. */ type ToolLoopAgentSettings = LanguageModelCallOptions & Omit, 'abortSignal'> & ToolsContextParameter & { /** * The id of the agent. */ id?: string; /** * The instructions for the agent. * * It can be a string, or, if you need to pass additional provider options (e.g. for caching), a `SystemModelMessage`. */ instructions?: Instructions; /** * Whether system messages are allowed in the `prompt` or `messages` fields. * * When disabled, system messages must be provided through the `instructions` * option. * * @default false */ allowSystemInMessages?: boolean; /** * The language model to use. */ model: LanguageModel; /** * The tool choice strategy. Default: 'auto'. */ toolChoice?: ToolChoice>; /** * Condition for stopping the generation when there are tool results in the last step. * When the condition is an array, any of the conditions can be met to stop the generation. * * @default isStepCount(20) */ stopWhen?: Arrayable, RUNTIME_CONTEXT>>; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions>; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions>; /** * Limits the tools that are available for the model to call without * changing the tool call and result types in the result. */ activeTools?: ActiveTools>; /** * Controls the order in which tools are sent to the provider. * * The list can be partial. Tools not listed in `toolOrder` are sent after * the listed tools, sorted alphabetically. This can improve provider-side * caching by keeping tool definitions in a stable order. */ toolOrder?: ToolOrder>; /** * Optional specification for generating structured outputs. */ output?: OUTPUT; /** * Runtime context. Treat runtime context as immutable. * If you need to mutate runtime context, update it in `prepareStep`. */ runtimeContext?: RUNTIME_CONTEXT; /** * Optional tool approval configuration. * * This configuration takes precedence over tool-defined approval settings. */ toolApproval?: ToolApprovalConfiguration, RUNTIME_CONTEXT>; /** * Configures which caller tools may invoke each tool. */ experimental_toolCallers?: Experimental_ToolCallers>; /** * Optional function that you can use to provide different settings for a step. */ prepareStep?: PrepareStepFunction, RUNTIME_CONTEXT>; /** * A function that attempts to repair a tool call that failed to parse. */ repairToolCall?: ToolCallRepairFunction>; /** * A function that attempts to repair a tool call that failed to parse. * * @deprecated Use `repairToolCall` instead. */ experimental_repairToolCall?: ToolCallRepairFunction>; /** * Optional mapping of tool names to functions that refine parsed tool inputs. * * The refined input must have the same type shape as the tool input. Refined * inputs are used for tool execution, outputs, callbacks, and telemetry. */ experimental_refineToolInput?: ToolInputRefinement>; /** * Callback that is called when the agent operation begins, before any LLM calls. */ onStart?: GenerateTextOnStartCallback, RUNTIME_CONTEXT, NoInfer>; /** * Callback that is called when the agent operation begins, before any LLM calls. * * @deprecated Use `onStart` instead. */ experimental_onStart?: GenerateTextOnStartCallback, RUNTIME_CONTEXT, NoInfer>; /** * Callback that is called when a step (LLM call) begins, before the provider is called. */ onStepStart?: GenerateTextOnStepStartCallback, NoInfer, NoInfer>; /** * Callback that is called when a step (LLM call) begins, before the provider is called. * * @deprecated Use `onStepStart` instead. */ experimental_onStepStart?: GenerateTextOnStepStartCallback, NoInfer, NoInfer>; /** * Callback that is called before each tool execution begins. */ onToolExecutionStart?: OnToolExecutionStartCallback>; /** * Callback that is called after each tool execution completes. */ onToolExecutionEnd?: OnToolExecutionEndCallback>; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. */ onStepEnd?: GenerateTextOnStepEndCallback, NoInfer>; /** * Callback that is called when each step (LLM call) ends, including intermediate steps. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: GenerateTextOnStepFinishCallback, NoInfer>; /** * Callback that is called when all steps are finished and the response is complete. */ onEnd?: GenerateTextOnEndCallback, NoInfer>; /** * Callback that is called when all steps are finished and the response is complete. * * @deprecated Use `onEnd` instead. */ onFinish?: GenerateTextOnEndCallback, NoInfer>; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * Custom download function to use for URLs. * * By default, files are downloaded if the model does not support the URL for the given media type. */ experimental_download?: DownloadFunction | undefined; /** * Settings for controlling what data is included in step results. * Disabling inclusion can help reduce memory usage when processing * large payloads like images. * * By default, request and response bodies are included, and request * messages are excluded. */ include?: GenerateTextInclude & StreamTextInclude; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: IdGenerator; generateCallId?: IdGenerator; }; /** * The schema for the call options. */ callOptionsSchema?: FlexibleSchema; /** * Prepare the parameters for the generateText or streamText call. * * You can use this to have templates based on call options. * * The design requires you to pass call parameters as follows to * allow for the removal of parameters from the original settings * by setting them to `undefined`: * * ``` * prepareCall: ({ options, ...rest }) => ({ * ...rest, * }), * ``` */ prepareCall?: (options: Omit, NoInfer>, 'abortSignal' | 'timeout' | 'onStart' | 'experimental_onStart' | 'onStepStart' | 'experimental_onStepStart' | 'onToolExecutionStart' | 'onToolExecutionEnd' | 'onStepEnd' | 'onStepFinish' | 'onEnd' | 'onFinish'> & Pick>, 'model' | 'tools' | 'toolChoice' | 'maxRetries' | 'maxOutputTokens' | 'temperature' | 'topP' | 'topK' | 'presencePenalty' | 'frequencyPenalty' | 'stopSequences' | 'seed' | 'reasoning' | 'headers' | 'instructions' | 'allowSystemInMessages' | 'stopWhen' | 'telemetry' | 'experimental_telemetry' | 'activeTools' | 'toolOrder' | 'toolApproval' | 'experimental_toolCallers' | 'prepareStep' | 'repairToolCall' | 'experimental_repairToolCall' | 'providerOptions' | 'experimental_download' | 'experimental_refineToolInput' | 'include' | 'runtimeContext' | '_internal'> & { toolsContext: InferToolSetContext; }) => MaybePromiseLike>, 'model' | 'tools' | 'toolChoice' | 'maxRetries' | 'maxOutputTokens' | 'temperature' | 'topP' | 'topK' | 'presencePenalty' | 'frequencyPenalty' | 'stopSequences' | 'seed' | 'reasoning' | 'headers' | 'instructions' | 'allowSystemInMessages' | 'stopWhen' | 'telemetry' | 'experimental_telemetry' | 'activeTools' | 'toolOrder' | 'toolApproval' | 'experimental_toolCallers' | 'prepareStep' | 'repairToolCall' | 'experimental_repairToolCall' | 'providerOptions' | 'experimental_download' | 'experimental_refineToolInput' | 'include' | 'runtimeContext' | '_internal'> & Omit & { toolsContext: InferToolSetContext; }>; }; /** * A tool loop agent is an agent that runs tools in a loop. In each step, * it calls the LLM, and if there are tool calls, it executes the tools * and calls the LLM again in a new step with the tool results. * * The loop continues until: * - A finish reasoning other than tool-calls is returned, or * - A tool that is invoked does not have an execute function, or * - A tool call needs approval via `toolApproval` or tool-level `needsApproval`, or * - A stop condition is met (default stop condition is isStepCount(20)) */ declare class ToolLoopAgent implements Agent$1 { readonly version = "agent-v1"; private readonly settings; constructor(settings: ToolLoopAgentSettings); /** * The id of the agent. */ get id(): string | undefined; /** * The tools that the agent can use. */ get tools(): TOOLS; private prepareCall; /** * Tags outgoing requests so usage can be attributed to ToolLoopAgent. Chains * with the `ai/` and `ai-sdk//` suffixes added * downstream by generateText/streamText and the provider. */ private agentHeaders; /** * Generates an output from the agent (non-streaming). */ generate({ abortSignal, timeout, experimental_sandbox: sandbox, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onToolExecutionStart, onToolExecutionEnd, onStepEnd, onStepFinish, onFinish, onEnd, ...options }: AgentCallParameters): Promise>; /** * Streams an output from the agent (streaming). */ stream({ abortSignal, timeout, experimental_sandbox: sandbox, experimental_transform, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onToolExecutionStart, onToolExecutionEnd, onStepEnd, onStepFinish, onFinish, onEnd, ...options }: AgentStreamParameters): Promise>; } /** * Infer the type of the tools of an agent. */ type InferAgentTools = AGENT extends Agent$1 ? TOOLS : never; /** * Infer the UI message type of an agent. */ type InferAgentUIMessage = UIMessage>>; /** * Runs the agent and returns a response object with a UI message stream. * * @param agent - The agent to run. * @param uiMessages - The input UI messages. * @param abortSignal - Abort signal. Optional. * @param timeout - Timeout in milliseconds. Optional. * @param experimental_sandbox - The sandbox environment that is passed through to tool execution. Optional. * @param options - The options for the agent. Optional. * @param experimental_transform - Stream transformations. Optional. * @param onStepEnd - Callback that is called when each step ends. Optional. * @param onStepFinish - Deprecated alias for `onStepEnd`. Optional. * @param headers - Additional headers for the response. Optional. * @param status - The status code for the response. Optional. * @param statusText - The status text for the response. Optional. * @param consumeSseStream - Whether to consume the SSE stream. Optional. * * @returns The response object. */ declare function createAgentUIStreamResponse({ headers, status, statusText, consumeSseStream, ...options }: { agent: Agent$1; uiMessages: unknown[]; abortSignal?: AbortSignal; timeout?: TimeoutConfiguration; experimental_sandbox?: SandboxSession; options?: CALL_OPTIONS; experimental_transform?: Arrayable>; onStepEnd?: GenerateTextOnStepEndCallback; /** @deprecated Use `onStepEnd` instead. */ onStepFinish?: GenerateTextOnStepFinishCallback; } & UIMessageStreamResponseInit & UIMessageStreamOptions>>): Promise; /** * Callback that is called when a step ends during streaming. * This is useful for persisting intermediate UI messages during multi-step agent runs. */ type UIMessageStreamOnStepEndCallback = (event: { /** * The updated list of UI messages at the end of this step. */ messages: UI_MESSAGE[]; /** * Indicates whether the response message is a continuation of the last original message, * or if a new message was created. */ isContinuation: boolean; /** * The message that was sent to the client as a response * (including the original message if it was extended). */ responseMessage: UI_MESSAGE; }) => PromiseLike | void; /** * Callback that is called when a step finishes during streaming. * This is useful for persisting intermediate UI messages during multi-step agent runs. * * @deprecated Use `UIMessageStreamOnStepEndCallback` instead. */ type UIMessageStreamOnStepFinishCallback = UIMessageStreamOnStepEndCallback; declare const getOriginalFetch: () => typeof fetch; declare function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol, setCompletion, setLoading, setError, setAbortController, onFinish, onError, fetch }: { api: string; prompt: string; credentials: RequestCredentials | undefined; headers: HeadersInit | undefined; body: Record; streamProtocol: 'data' | 'text' | undefined; setCompletion: (completion: string) => void; setLoading: (loading: boolean) => void; setError: (error: Error | undefined) => void; setAbortController: (abortController: AbortController | null) => void; onFinish: ((prompt: string, completion: string) => void) | undefined; onError: ((error: Error) => void) | undefined; fetch: ReturnType | undefined; }): Promise; /** * Transport interface for handling chat message communication and streaming. * * The `ChatTransport` interface provides fine-grained control over how messages * are sent to API endpoints and how responses are processed. This enables * alternative communication protocols like WebSockets, custom authentication * patterns, or specialized backend integrations. * * @template UI_MESSAGE - The UI message type extending UIMessage */ interface ChatTransport { /** * Sends messages to the chat API endpoint and returns a streaming response. * * This method handles both new message submission and message regeneration. * It supports real-time streaming of responses through UIMessageChunk events. * * @param options - Configuration object containing: * @param options.trigger - The type of message submission: * - `'submit-message'`: Submitting a new user message * - `'regenerate-message'`: Regenerating an assistant response * @param options.chatId - Unique identifier for the chat session * @param options.messageId - ID of the message to regenerate (for regenerate-message trigger) or undefined for new messages * @param options.messages - Array of UI messages representing the conversation history * @param options.abortSignal - Signal to abort the request if needed * @param options.headers - Additional HTTP headers to include in the request * @param options.body - Additional JSON properties to include in the request body * @param options.metadata - Custom metadata to attach to the request * * @returns Promise resolving to a ReadableStream of UIMessageChunk objects. * The stream emits various chunk types like: * - `text-start`, `text-delta`, `text-end`: For streaming text content * - `tool-input-start`, `tool-input-delta`, `tool-input-available`: For tool calls * - `data-part-start`, `data-part-delta`, `data-part-available`: For data parts * - `error`: For error handling * * @throws Error when the API request fails or response is invalid */ sendMessages: (options: { /** The type of message submission - either new message or regeneration */trigger: 'submit-message' | 'regenerate-message'; /** Unique identifier for the chat session */ chatId: string; /** ID of the message to regenerate, or undefined for new messages */ messageId: string | undefined; /** Array of UI messages representing the conversation history */ messages: UI_MESSAGE[]; /** Signal to abort the request if needed */ abortSignal: AbortSignal | undefined; } & ChatRequestOptions) => Promise>; /** * Reconnects to an existing streaming response for the specified chat session. * * This method is used to resume streaming when a connection is interrupted * or when resuming a chat session. It's particularly useful for maintaining * continuity in long-running conversations or recovering from network issues. * * @param options - Configuration object containing: * @param options.chatId - Unique identifier for the chat session to reconnect to * @param options.abortSignal - Signal to abort the reconnection request if needed * @param options.headers - Additional HTTP headers to include in the reconnection request * @param options.body - Additional JSON properties to include in the request body * @param options.metadata - Custom metadata to attach to the request * * @returns Promise resolving to: * - `ReadableStream`: If an active stream is found and can be resumed * - `null`: If no active stream exists for the specified chat session (e.g., response already completed) * * @throws Error when the reconnection request fails or response is invalid */ reconnectToStream: (options: { /** Unique identifier for the chat session to reconnect to */chatId: string; /** Signal to abort the reconnection request if needed */ abortSignal?: AbortSignal; } & ChatRequestOptions) => Promise | null>; } type CreateUIMessage = Omit & { id?: UI_MESSAGE['id']; role?: UI_MESSAGE['role']; }; type UIDataPartSchemas = Record; type UIDataTypesToSchemas = { [K in keyof T]: FlexibleSchema }; type InferUIDataParts = { [K in keyof T]: InferSchema }; type ChatRequestOptions = { /** * Additional headers that should be to be passed to the API endpoint. */ headers?: Record | Headers; /** * Additional body JSON properties that should be sent to the API endpoint. */ body?: object; metadata?: unknown; }; /** * Function that can be called to add a tool approval response to the chat. */ type ChatAddToolApproveResponseFunction = ({ id, approved, reason, options }: { id: string; /** * Flag indicating whether the approval was granted or denied. */ approved: boolean; /** * Optional reason for the approval or denial. */ reason?: string; /** * Optional request options to be used if `sendAutomaticallyWhen` callback returns true. */ options?: ChatRequestOptions; }) => void | PromiseLike; /** * Function that can be called to add a tool output to the chat. */ type ChatAddToolOutputFunction = >({ state, tool, toolCallId, output, errorText, options }: { /** * Name of the tool that was called. */ tool: TOOL; /** * Identifier of the tool call to add output for. */ toolCallId: string; /** * Optional request options to be used if `sendAutomaticallyWhen` callback returns true. */ options?: ChatRequestOptions; } & ({ state?: 'output-available'; output: InferUIMessageTools[TOOL]['output']; errorText?: never; } | { state: 'output-error'; output?: never; errorText: string; })) => void | PromiseLike; type ChatStatus = 'submitted' | 'streaming' | 'ready' | 'error'; interface ChatState { status: ChatStatus; error: Error | undefined; messages: UI_MESSAGE[]; pushMessage: (message: UI_MESSAGE) => void; popMessage: () => void; replaceMessage: (index: number, message: UI_MESSAGE) => void; snapshot: (thing: T) => T; } type ChatOnErrorCallback = (error: Error) => void; type ChatOnToolCallCallback = (options: { toolCall: InferUIMessageToolCall; }) => void | PromiseLike; type ChatOnDataCallback = (dataPart: DataUIPart>) => void; /** * Function that is called when the assistant response has finished streaming. * * @param message The assistant message that was streamed. * @param messages The full chat history, including the assistant message. * * @param isAbort Indicates whether the request has been aborted. * @param isDisconnect Indicates whether the request has been ended by a network error. * @param isError Indicates whether the request has been ended by an error. * @param finishReason The reason why the generation finished. */ type ChatOnFinishCallback = (options: { message: UI_MESSAGE; messages: UI_MESSAGE[]; isAbort: boolean; isDisconnect: boolean; isError: boolean; finishReason?: FinishReason; }) => void; interface ChatInit { /** * A unique identifier for the chat. If not provided, a random one will be * generated. */ id?: string; messageMetadataSchema?: FlexibleSchema>; dataPartSchemas?: UIDataTypesToSchemas>; messages?: UI_MESSAGE[]; /** * A way to provide a function that is going to be used for ids for messages and the chat. * If not provided the default AI SDK `generateId` is used. */ generateId?: IdGenerator; transport?: ChatTransport; /** * Callback function to be called when an error is encountered. */ onError?: ChatOnErrorCallback; /** * Optional callback function that is invoked when a tool call is received. * Intended for automatic client-side tool execution. * * To add the tool output, call `addToolOutput` without awaiting it inside * this callback. The callback's return value is not used. */ onToolCall?: ChatOnToolCallCallback; /** * Function that is called when the assistant response has finished streaming. */ onFinish?: ChatOnFinishCallback; /** * Optional callback function that is called when a data part is received. * * @param data The data part that was received. */ onData?: ChatOnDataCallback; /** * When provided, this function will be called when the stream is finished or a tool call is added * to determine if the current messages should be resubmitted. */ sendAutomaticallyWhen?: (options: { messages: UI_MESSAGE[]; }) => boolean | PromiseLike; } declare abstract class AbstractChat { readonly id: string; readonly generateId: IdGenerator; protected state: ChatState; private messageMetadataSchema; private dataPartSchemas; private readonly transport; private onError?; private onToolCall?; private onFinish?; private onData?; private sendAutomaticallyWhen?; private pendingMessagePreparations; private activeResponse; private activeResumeRequest; private jobExecutor; constructor({ generateId, id, transport, messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen }: Omit, 'messages'> & { state: ChatState; }); /** * Hook status: * * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream. * - `streaming`: The response is actively streaming in from the API, receiving chunks of data. * - `ready`: The full response has been received and processed; a new user message can be submitted. * - `error`: An error occurred during the API request, preventing successful completion. */ get status(): ChatStatus; protected setStatus({ status, error }: { status: ChatStatus; error?: Error; }): void; get error(): Error | undefined; get messages(): UI_MESSAGE[]; get lastMessage(): UI_MESSAGE | undefined; set messages(messages: UI_MESSAGE[]); /** * Appends or replaces a user message to the chat list. This triggers the API call to fetch * the assistant's response. * * If a messageId is provided, the message will be replaced. */ sendMessage: (message?: (CreateUIMessage & { text?: never; files?: never; messageId?: string; }) | { text: string; files?: FileList | FileUIPart[]; metadata?: InferUIMessageMetadata; parts?: never; messageId?: string; } | { files: FileList | FileUIPart[]; metadata?: InferUIMessageMetadata; parts?: never; messageId?: string; }, options?: ChatRequestOptions) => Promise; /** * Regenerate the assistant message with the provided message id. * If no message id is provided, the last assistant message will be regenerated. */ regenerate: ({ messageId, ...options }?: { messageId?: string; } & ChatRequestOptions) => Promise; /** * Attempt to resume an ongoing streaming response. */ resumeStream: (options?: ChatRequestOptions) => Promise; /** * Clear the error state and set the status to ready if the chat is in an error state. */ clearError: () => void; addToolApprovalResponse: ChatAddToolApproveResponseFunction; addToolOutput: ChatAddToolOutputFunction; /** @deprecated Use addToolOutput */ addToolResult: ChatAddToolOutputFunction; /** * Abort the current request immediately, keep the generated tokens if any. */ stop: () => Promise; private shouldSendAutomatically; private makeRequest; } declare function convertFileListToFileUIParts(files: FileList | undefined): Promise>; /** * Converts an array of UI messages from useChat into an array of ModelMessages that can be used * with the AI functions (e.g. `streamText`, `generateText`). * * @param messages - The UI messages to convert. * @param options.tools - The tools to use. * @param options.ignoreIncompleteToolCalls - Whether to ignore incomplete tool calls. Default is `false`. * @param options.convertDataPart - Optional function to convert data parts to text or file model message parts. Returns `undefined` if the part should be ignored. * * @returns An array of ModelMessages. */ declare function convertToModelMessages(messages: Array>, options?: { tools?: ToolSet; ignoreIncompleteToolCalls?: boolean; convertDataPart?: (part: DataUIPart>) => TextPart | FilePart | undefined; }): Promise; type PrepareSendMessagesRequest = (options: { id: string; messages: UI_MESSAGE[]; requestMetadata: unknown; body: Record | undefined; credentials: RequestCredentials | undefined; headers: HeadersInit | undefined; api: string; } & { trigger: 'submit-message' | 'regenerate-message'; messageId: string | undefined; }) => { body: object; headers?: HeadersInit; credentials?: RequestCredentials; api?: string; } | PromiseLike<{ body: object; headers?: HeadersInit; credentials?: RequestCredentials; api?: string; }>; type PrepareReconnectToStreamRequest = (options: { id: string; requestMetadata: unknown; body: Record | undefined; credentials: RequestCredentials | undefined; headers: HeadersInit | undefined; api: string; }) => { headers?: HeadersInit; credentials?: RequestCredentials; api?: string; } | PromiseLike<{ headers?: HeadersInit; credentials?: RequestCredentials; api?: string; }>; /** * Options for the `HttpChatTransport` class. * * @param UI_MESSAGE - The type of message to be used in the chat. */ type HttpChatTransportInitOptions = { /** * The API URL to be used for the chat transport. * Defaults to '/api/chat'. */ api?: string; /** * The credentials mode to be used for the fetch request. * Possible values are: 'omit', 'same-origin', 'include'. * Defaults to 'same-origin'. */ credentials?: Resolvable; /** * HTTP headers to be sent with the API request. */ headers?: Resolvable | Headers>; /** * Extra body object to be sent with the API request. * @example * Send a `sessionId` to the API along with the messages. * ```js * useChat({ * body: { * sessionId: '123', * } * }) * ``` */ body?: Resolvable; /** * Custom fetch implementation. You can use it as a middleware to intercept requests, * or to provide a custom fetch implementation for e.g. testing. */ fetch?: FetchFunction; /** * When a function is provided, it will be used * to prepare the request body for the chat API. This can be useful for * customizing the request body based on the messages and data in the chat. */ prepareSendMessagesRequest?: PrepareSendMessagesRequest; /** * When a function is provided, it will be used * to prepare the reconnect request for the chat API. This can be useful for * customizing the request based on the chat session. */ prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest; }; declare abstract class HttpChatTransport implements ChatTransport { protected api: string; protected credentials: HttpChatTransportInitOptions['credentials']; protected headers: HttpChatTransportInitOptions['headers']; protected body: HttpChatTransportInitOptions['body']; protected fetch?: FetchFunction; protected prepareSendMessagesRequest?: PrepareSendMessagesRequest; protected prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest; constructor({ api, credentials, headers, body, fetch, prepareSendMessagesRequest, prepareReconnectToStreamRequest }: HttpChatTransportInitOptions); sendMessages({ abortSignal, ...options }: Parameters['sendMessages']>[0]): Promise>; reconnectToStream(options: Parameters['reconnectToStream']>[0]): Promise | null>; protected abstract processResponseStream(stream: ReadableStream>): ReadableStream; } declare class DefaultChatTransport extends HttpChatTransport { constructor(options?: HttpChatTransportInitOptions); protected processResponseStream(stream: ReadableStream>): ReadableStream; } /** * Options for the `DirectChatTransport` class. */ type DirectChatTransportOptions>> = { /** * The agent to use for generating responses. */ agent: Agent$1; /** * Options to pass to the agent when calling it. */ options?: CALL_OPTIONS; } & Omit, 'onFinish'>; /** * A transport that directly communicates with an Agent in-process, * without going through HTTP. This is useful for: * - Server-side rendering scenarios * - Testing without network * - Single-process applications * * @example * ```tsx * import { useChat } from '@ai-sdk/react'; * import { DirectChatTransport } from 'ai'; * import { myAgent } from './my-agent'; * * const { messages, sendMessage } = useChat({ * transport: new DirectChatTransport({ agent: myAgent }), * }); * ``` */ declare class DirectChatTransport> = UIMessage>> implements ChatTransport { private readonly agent; private readonly agentOptions; private readonly uiMessageStreamOptions; constructor({ agent, options, ...uiMessageStreamOptions }: DirectChatTransportOptions); sendMessages({ messages, abortSignal }: Parameters['sendMessages']>[0]): Promise>; /** * Direct transport does not support reconnection since there is no * persistent server-side stream to reconnect to. * * @returns Always returns `null` */ reconnectToStream(_options: Parameters['reconnectToStream']>[0]): Promise | null>; } /** * Check if the last message is an assistant message with completed tool call approvals. * The last step of the message must have at least one tool approval response and * all tool approvals must have a response. */ declare function lastAssistantMessageIsCompleteWithApprovalResponses({ messages }: { messages: UIMessage[]; }): boolean; /** * Check if the last message is an assistant message with completed tool calls. * The last step of the message must have at least one tool invocation and * all tool invocations must have a result. */ declare function lastAssistantMessageIsCompleteWithToolCalls({ messages }: { messages: UIMessage[]; }): boolean; declare class TextStreamChatTransport extends HttpChatTransport { constructor(options?: HttpChatTransportInitOptions); protected processResponseStream(stream: ReadableStream>): ReadableStream; } type CompletionRequestOptions = { /** * An optional object of headers to be passed to the API endpoint. */ headers?: Record | Headers; /** * An optional object to be passed to the API endpoint. */ body?: BODY; }; type UseCompletionOptions = { /** * The API endpoint that accepts a `{ prompt: string }` object and returns * a stream of tokens of the AI completion response. Defaults to `/api/completion`. */ api?: string; /** * A unique identifier for the completion. If not provided, a random one will be * generated. When provided, the `useCompletion` hook with the same `id` will * have shared states across components. */ id?: string; /** * Initial prompt input of the completion. */ initialInput?: string; /** * Initial completion result. Useful to load an existing history. */ initialCompletion?: string; /** * Callback function to be called when the completion is finished streaming. */ onFinish?: (prompt: string, completion: string) => void; /** * Callback function to be called when an error is encountered. */ onError?: (error: Error) => void; /** * The credentials mode to be used for the fetch request. * Possible values are: 'omit', 'same-origin', 'include'. * Defaults to 'same-origin'. */ credentials?: RequestCredentials; /** * HTTP headers to be sent with the API request. */ headers?: Record | Headers; /** * Extra body object to be sent with the API request. * @example * Send a `sessionId` to the API along with the prompt. * ```js * useCompletion({ * body: { * sessionId: '123', * } * }) * ``` */ body?: BODY; /** * Streaming protocol that is used. Defaults to `data`. */ streamProtocol?: 'data' | 'text'; /** * Custom fetch implementation. You can use it as a middleware to intercept requests, * or to provide a custom fetch implementation for e.g. testing. */ fetch?: FetchFunction; }; type SafeValidateUIMessagesResult = { success: true; data: Array; } | { success: false; error: Error; }; /** * Validates a list of UI messages like `validateUIMessages`, * but instead of throwing it returns `{ success: true, data }` * or `{ success: false, error }`. */ declare function safeValidateUIMessages({ messages, metadataSchema, dataSchemas, tools }: { messages: unknown; metadataSchema?: FlexibleSchema; dataSchemas?: { [NAME in keyof InferUIMessageData & string]?: FlexibleSchema[NAME]> }; tools?: { [NAME in keyof InferUIMessageTools & string]?: Tool[NAME]['input'], InferUIMessageTools[NAME]['output']> }; }): Promise>; /** * Validates a list of UI messages. * * Metadata, data parts, and generic tool call structures are only validated if * the corresponding schemas are provided. Otherwise, they are assumed to be * valid. */ declare function validateUIMessages({ messages, metadataSchema, dataSchemas, tools }: { messages: unknown; metadataSchema?: FlexibleSchema; dataSchemas?: { [NAME in keyof InferUIMessageData & string]?: FlexibleSchema[NAME]> }; tools?: { [NAME in keyof InferUIMessageTools & string]?: Tool[NAME]['input'], InferUIMessageTools[NAME]['output']> }; }): Promise>; interface UIMessageStreamWriter { /** * Appends a data stream part to the stream. */ write(part: InferUIMessageChunk): void; /** * Merges the contents of another stream to this stream. */ merge(stream: ReadableStream>): 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: ErrorHandler | undefined; } /** * Creates a UI message stream that can be used to send messages to the client. * * @param options.execute - A function that is called with a writer to write UI message chunks to the stream. * @param options.onError - A function that extracts an error message from an error. Defaults to `() => 'An error occurred.'` so server-side error details are not leaked to the client; supply your own to surface richer messages. * @param options.originalMessages - The original messages. If provided, persistence mode is assumed * and a message ID is provided for the response message. * @param options.onStepEnd - A callback that is called when each step ends. Useful for persisting intermediate messages. * @param options.onStepFinish - Deprecated alias for `onStepEnd`. * @param options.onEnd - A callback that is called when the stream ends. * @param options.onFinish - Deprecated alias for `onEnd`. * @param options.generateId - A function that generates a unique ID. Defaults to the built-in ID generator. * * @returns A `ReadableStream` of UI message chunks. */ declare function createUIMessageStream({ execute, onError, // prevent leaking server error details to the client by default originalMessages, onStepEnd, onStepFinish, onEnd, onFinish, generateId }: { execute: (options: { writer: UIMessageStreamWriter; }) => Promise | void; onError?: (error: unknown) => string; /** * The original messages. If they are provided, persistence mode is assumed, * and a message ID is provided for the response message. */ originalMessages?: UI_MESSAGE[]; /** * Callback that is called when each step ends during multi-step agent runs. */ onStepEnd?: UIMessageStreamOnStepEndCallback; /** * Callback that is called when each step ends during multi-step agent runs. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: UIMessageStreamOnStepFinishCallback; onEnd?: UIMessageStreamOnEndCallback; /** * @deprecated Use `onEnd` instead. */ onFinish?: UIMessageStreamOnEndCallback; generateId?: IdGenerator; }): ReadableStream>; /** * Creates a Response object from a UI message stream. * The stream is transformed to Server-Sent Events (SSE) format. * * @param options.status - The HTTP status code for the response. * @param options.statusText - The HTTP status text for the response. * @param options.headers - Additional HTTP headers to include in the response. * @param options.stream - The UI message chunk stream to send. * @param options.consumeSseStream - Optional callback to consume a copy of the SSE stream independently. * * @returns A `Response` object with the UI message stream as the body. */ declare function createUIMessageStreamResponse({ status, statusText, headers, stream, consumeSseStream }: UIMessageStreamResponseInit & { stream: ReadableStream; }): Response; /** * A TransformStream that converts JSON objects to Server-Sent Events (SSE) format. * Each object is serialized to JSON and wrapped in `data: ...\n\n` format. * When the stream ends, a `data: [DONE]\n\n` message is sent. */ declare class JsonToSseTransformStream extends TransformStream { constructor(); } /** * Pipes a UI message stream to a Node.js ServerResponse object. * The stream is transformed to Server-Sent Events (SSE) format. * * @param options.response - The Node.js ServerResponse object to write to. * @param options.status - The HTTP status code for the response. * @param options.statusText - The HTTP status text for the response. * @param options.headers - Additional HTTP headers to include in the response. * @param options.stream - The UI message chunk stream to send. * @param options.consumeSseStream - Optional callback to consume a copy of the SSE stream independently. * @returns A promise that resolves when the stream has been written. */ declare function pipeUIMessageStreamToResponse({ response, status, statusText, headers, stream, consumeSseStream }: { response: ServerResponse; stream: ReadableStream; } & UIMessageStreamResponseInit): Promise; /** * Transforms a stream of `UIMessageChunk`s into an `AsyncIterableStream` of `UIMessage`s. * * @param options.message - The last assistant message to use as a starting point when the conversation is resumed. Otherwise undefined. * @param options.stream - The stream of `UIMessageChunk`s to read. * @param options.terminateOnError - Whether to terminate the stream if an error occurs. * @param options.onError - A function that is called when an error occurs. * * @returns An `AsyncIterableStream` of `UIMessage`s. Each stream part is a different state of the same message * as it is being completed. */ declare function readUIMessageStream({ message, stream, onError, terminateOnError }: { message?: UI_MESSAGE; stream: ReadableStream; onError?: (error: unknown) => void; terminateOnError?: boolean; }): AsyncIterableStream; type ToUIMessageChunkOptions = { tools?: TOOLS; sendReasoning?: boolean; sendSources?: boolean; sendStart?: boolean; sendFinish?: boolean; onError?: (error: unknown) => string; messageMetadata?: InferUIMessageMetadata; responseMessageId?: string; }; /** * Converts a single `TextStreamPart` (as emitted by `streamText`'s * `stream`) into a `UIMessageChunk`. * * Returns `undefined` for stream parts that do not produce UI message chunks. */ declare function toUIMessageChunk(part: TextStreamPart, { tools, sendReasoning, sendSources, sendStart, sendFinish, onError, // prevent leaking server error details to the client by default messageMetadata, responseMessageId }?: ToUIMessageChunkOptions): InferUIMessageChunk | undefined; /** * Converts a stream of `TextStreamPart` chunks (as emitted by * `streamText`'s `stream`) into a stream of `UIMessageChunk`s suitable for * UI message streaming, including response message ID injection and * `onEnd` handling. */ declare function toUIMessageStream({ stream, tools, sendReasoning, sendSources, sendStart, sendFinish, onError, // prevent leaking server error details to the client by default messageMetadata, originalMessages, generateMessageId, onEnd, onFinish }: { stream: ReadableStream>; tools?: TOOLS; } & UIMessageStreamOptions): ReadableStream>; declare const UI_MESSAGE_STREAM_HEADERS: { 'content-type': string; 'cache-control': string; connection: string; 'x-vercel-ai-ui-message-stream': string; 'x-accel-buffering': string; }; /** * @deprecated Use `UIMessageStreamOnEndCallback` instead. */ type UIMessageStreamOnFinishCallback = UIMessageStreamOnEndCallback; /** * Runs the agent and stream the output as a UI message stream. * * @param agent - The agent to run. * @param uiMessages - The input UI messages. * @param abortSignal - The abort signal. Optional. * @param timeout - Timeout in milliseconds. Optional. * @param experimental_sandbox - The sandbox environment that is passed through to tool execution. Optional. * @param options - The options for the agent. * @param experimental_transform - The stream transformations. Optional. * @param onStepEnd - Callback that is called when each step ends. Optional. * @param onStepFinish - Deprecated alias for `onStepEnd`. Optional. * * @returns The UI message stream. */ declare function createAgentUIStream> = UIMessage>>({ agent, uiMessages, options, abortSignal, timeout, experimental_sandbox: sandbox, experimental_transform, onStepEnd, onStepFinish, ...uiMessageStreamOptions }: { agent: Agent$1; uiMessages: unknown[]; abortSignal?: AbortSignal; timeout?: TimeoutConfiguration; experimental_sandbox?: SandboxSession; options?: CALL_OPTIONS; experimental_transform?: Arrayable>; onStepEnd?: GenerateTextOnStepEndCallback; /** @deprecated Use `onStepEnd` instead. */ onStepFinish?: GenerateTextOnStepFinishCallback; } & UIMessageStreamOptions): Promise>>; /** * Pipes the agent UI message stream to a Node.js ServerResponse object. * * @param response - The Node.js ServerResponse object to pipe to. * @param agent - The agent to run. * @param uiMessages - The input UI messages. * @param abortSignal - Abort signal. Optional. * @param timeout - Timeout in milliseconds. Optional. * @param experimental_sandbox - The sandbox environment that is passed through to tool execution. Optional. * @param options - The options for the agent. Optional. * @param experimental_transform - Stream transformations. Optional. * @param onStepEnd - Callback that is called when each step ends. Optional. * @param onStepFinish - Deprecated alias for `onStepEnd`. Optional. * @param headers - Additional headers for the response. Optional. * @param status - The status code for the response. Optional. * @param statusText - The status text for the response. Optional. * @param consumeSseStream - Whether to consume the SSE stream. Optional. */ declare function pipeAgentUIStreamToResponse({ response, headers, status, statusText, consumeSseStream, ...options }: { response: ServerResponse; agent: Agent$1; uiMessages: unknown[]; abortSignal?: AbortSignal; timeout?: TimeoutConfiguration; experimental_sandbox?: SandboxSession; options?: CALL_OPTIONS; experimental_transform?: Arrayable>; onStepEnd?: GenerateTextOnStepEndCallback; /** @deprecated Use `onStepEnd` instead. */ onStepFinish?: GenerateTextOnStepFinishCallback; } & UIMessageStreamResponseInit & UIMessageStreamOptions>>): Promise; /** * Language model input that can be used for durable batch processing. * * String model IDs are resolved through the global provider and checked for * batch support at runtime. */ type BatchLanguageModel = GlobalProviderModelId | BatchLanguageModelV4; /** * The persisted reference for a text batch. */ type TextBatchReference = { readonly version: 1; readonly type: 'text'; readonly id: string; readonly provider: string; readonly modelId: string; }; /** * Persisted reference for any supported batch type. * * Additional modality-specific references can be added to this union. */ type BatchReference = TextBatchReference; /** * Serializable error information for a batch or batch item. */ type BatchError = BatchV4Error; /** * The latest normalized lifecycle status for a batch. */ type BatchStatus = BatchV4Status; /** * A text batch and its latest normalized lifecycle status. */ type TextBatch = TextBatchReference & BatchStatus; /** * One text generation request within a batch. */ type TextBatchRequest = Prompt & LanguageModelCallOptions & { id: string; providerOptions?: ProviderOptions; }; type BatchRequestOptions = { abortSignal?: AbortSignal; headers?: Record; timeout?: number | { totalMs?: number; }; }; /** * Options for starting a text batch. */ type StartTextBatchOptions = { model: BatchLanguageModel; requests: ReadonlyArray; providerOptions?: ProviderOptions; } & BatchRequestOptions; /** * The acknowledged text batch and warnings produced while starting it. */ type StartTextBatchResult = TextBatch & { readonly warnings: BatchV4StartResult['warnings']; }; /** * Options shared by batch status and result retrieval operations. */ type BatchOperationOptions = { model: BatchLanguageModel; batch: BatchReference; providerOptions?: ProviderOptions; maxRetries?: number; } & BatchRequestOptions; /** * A normalized result for a successful text batch item. */ type TextBatchGenerationResult = { readonly text: string; readonly finishReason: FinishReason; readonly rawFinishReason?: string; readonly usage: LanguageModelUsage; readonly response?: { readonly id?: string; readonly timestamp?: string; readonly modelId?: string; }; readonly providerMetadata?: ProviderMetadata; }; /** * A complete terminal result for one request in a text batch. */ type TextBatchItemResult = (TextBatchGenerationResult & { readonly id: string; readonly status: 'succeeded'; }) | { readonly id: string; readonly status: 'failed'; readonly error: BatchError; readonly providerMetadata?: ProviderMetadata; } | { readonly id: string; readonly status: 'cancelled' | 'expired'; readonly error?: BatchError; readonly providerMetadata?: ProviderMetadata; }; /** * Starts a durable text-generation batch. */ declare function startTextBatch({ model: modelArg, requests, providerOptions, abortSignal, headers, timeout }: StartTextBatchOptions): Promise; /** * Retrieves the latest normalized status for a durable batch. */ declare function getBatchStatus({ model: modelArg, batch, providerOptions, maxRetries, abortSignal, headers, timeout }: BatchOperationOptions): Promise; /** * Streams complete terminal results for the requests in a durable batch. */ declare function getBatchResults({ model: modelArg, batch, providerOptions, maxRetries, abortSignal, headers, timeout }: BatchOperationOptions): AsyncIterableStream; /** * The result of an `embed` call. * It contains the embedding, the value, and additional information. */ interface EmbedResult { /** * The value that was embedded. */ readonly value: string; /** * The embedding of the value. */ readonly embedding: Embedding; /** * The embedding token usage. */ readonly usage: EmbeddingModelUsage; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: Array; /** * Optional provider-specific metadata. */ readonly providerMetadata?: ProviderMetadata; /** * Optional response data. */ readonly response?: { /** * Response headers. */ headers?: Record; /** * The response body. */ body?: unknown; }; } /** * 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. * * @param telemetry - Optional telemetry configuration. * * @param providerOptions - Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. * * @returns A result object that contains the embedding, the value, and additional information. */ declare function embed({ model: modelArg, value, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry, telemetry, onStart, experimental_onStart, onEnd, experimental_onEnd, _internal: { generateCallId } }: { /** * The embedding model to use. */ model: EmbeddingModel; /** * The value that should be embedded. */ value: string; /** * 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; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions; /** * Callback that is called when the embed operation begins, * before the embedding model is called. */ onStart?: Callback; /** * Callback that is called when the embed operation begins, * before the embedding model is called. * * @deprecated Use `onStart` instead. */ experimental_onStart?: Callback; /** * Callback that is called when the embed operation completes, * after the embedding model returns. */ onEnd?: Callback; /** * Callback that is called when the embed operation completes, * after the embedding model returns. * * @deprecated Use `onEnd` instead. */ experimental_onEnd?: Callback; /** * Internal. For test use only. May change without notice. */ _internal?: { generateCallId?: () => string; }; }): Promise; /** * The result of an `embedMany` call. * It contains the embeddings, the values, and additional information. */ interface EmbedManyResult { /** * The values that were embedded. */ readonly values: Array; /** * The embeddings. They are in the same order as the values. */ readonly embeddings: Array; /** * The embedding token usage. */ readonly usage: EmbeddingModelUsage; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: Array; /** * Optional provider-specific metadata. */ readonly providerMetadata?: ProviderMetadata; /** * Optional raw response data. */ readonly responses?: Array<{ /** * Response headers. */ headers?: Record; /** * The response body. */ body?: unknown; } | undefined>; } /** * 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. * * @param maxParallelCalls - Maximum number of concurrent requests. Default: Infinity. * * @param telemetry - Optional telemetry configuration. * * @param providerOptions - Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. * * @returns A result object that contains the embeddings, the value, and additional information. */ declare function embedMany({ model: modelArg, values, maxParallelCalls, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry, telemetry, onStart, experimental_onStart, onEnd, experimental_onEnd, _internal: { generateCallId } }: { /** * The embedding model to use. */ model: EmbeddingModel; /** * The values that should be embedded. */ values: Array; /** * 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; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * Maximum number of concurrent requests. * * @default Infinity */ maxParallelCalls?: number; /** * Callback that is called when the embedMany operation begins, * before the embedding model is called. */ onStart?: Callback; /** * Callback that is called when the embedMany operation begins, * before the embedding model is called. * * @deprecated Use `onStart` instead. */ experimental_onStart?: Callback; /** * Callback that is called when the embedMany operation completes, * after all embedding model calls return. */ onEnd?: Callback; /** * Callback that is called when the embedMany operation completes, * after all embedding model calls return. * * @deprecated Use `onEnd` instead. */ experimental_onEnd?: Callback; /** * Internal. For test use only. May change without notice. */ _internal?: { generateCallId?: () => string; }; }): Promise; declare const symbol$j: unique symbol; declare class InvalidArgumentError extends AISDKError { private readonly [symbol$j]; readonly parameter: string; readonly value: unknown; constructor({ parameter, value, message }: { parameter: string; value: unknown; message: string; }); static isInstance(error: unknown): error is InvalidArgumentError; } type LanguageModelStreamPart = Exclude, { type: 'finish' | 'stream-start' | 'tool-output-denied' | 'start-step' | 'finish-step' | 'start' | 'abort'; }> | TextStreamTextDeltaPart | TextStreamReasoningDeltaPart | TextStreamFilePart | TextStreamReasoningFilePart | TextStreamToolApprovalRequestPart | TextStreamToolApprovalResponsePart | TextStreamToolCallPart | TextStreamToolResultPart | TextStreamToolErrorPart | { type: 'model-call-end'; finishReason: FinishReason; rawFinishReason: string | undefined; usage: LanguageModelUsage; providerMetadata?: ProviderMetadata; performance: { responseTimeMs: number; effectiveOutputTokensPerSecond: number; outputTokensPerSecond: number | undefined; inputTokensPerSecond: number | undefined; effectiveTotalTokensPerSecond: number; timeToFirstOutputMs: number | undefined; timeBetweenOutputChunksMs?: OutputChunkTimingStats; }; } | { type: 'model-call-start'; warnings: Array; } | { type: 'model-call-response-metadata'; /** * ID for the generated response, if the provider sends one. */ id?: string; /** * Timestamp for the start of the generated response, if the provider sends one. */ timestamp?: Date; /** * The ID of the response model that was used to generate the response, if the provider sends one. */ modelId?: string; }; /** * Streams a single language model call after standardizing the prompt and tools. * * The returned stream emits model call parts together with request and response * metadata when available. * * @param model - The language model to use. * @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools. * @param output - Output configuration that controls the response format requested from the model. * @param toolChoice - The tool choice strategy for the model call. * * @param system - A system message that will be part of the prompt. * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both. * @param messages - A list of messages. You can either use `prompt` or `messages` but not both. * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false. * * @param maxOutputTokens - Maximum number of tokens to generate. * @param temperature - Temperature setting. * The value is passed through to the provider. The range depends on the provider and model. * It is recommended to set either `temperature` or `topP`, but not both. * @param topP - Nucleus sampling. * The value is passed through to the provider. The range depends on the provider and model. * It is recommended to set either `temperature` or `topP`, but not both. * @param topK - 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. * @param presencePenalty - Presence penalty setting. * It affects the likelihood of the model to repeat information that is already in the prompt. * The value is passed through to the provider. The range depends on the provider and model. * @param frequencyPenalty - Frequency penalty setting. * It affects the likelihood of the model to repeatedly use the same words or phrases. * The value is passed through to the provider. The range depends on the provider and model. * @param stopSequences - Stop sequences. * If set, the model will stop generating text when one of the stop sequences is generated. * @param seed - The seed (integer) to use for random sampling. * If set and supported by the model, calls will generate deterministic results. * @param reasoning - Reasoning configuration for the model call. * * @param download - A function that downloads URLs as part of prompt conversion. * @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. * @param includeRawChunks - Whether to include raw provider stream chunks in the model stream. * @param providerOptions - Additional provider-specific options. * @param repairToolCall - A function that can repair invalid tool calls before they are emitted. * @param refineToolInput - Optional mapping of tool names to functions that refine parsed tool inputs before they are emitted, used for telemetry, or executed. * @param onStart - A callback that receives the fully converted prompt before the model call starts. * * @returns A stream of model call parts together with request and response metadata when available. */ declare function streamLanguageModelCall({ model, tools, toolOrder, output, toolChoice, prompt, system, instructions, messages, allowSystemInMessages, download, abortSignal, headers, includeRawChunks, providerOptions, repairToolCall, refineToolInput, executeLanguageModelCallInTelemetryContext, callId, toolsContext, experimental_sandbox: sandbox, _internal: { generateId, generateCallId, now }, onStart, onLanguageModelCallStart, onLanguageModelCallEnd, ...callSettings }: { model: LanguageModel; tools?: TOOLS; toolOrder?: ToolOrder; output?: OUTPUT; toolChoice?: ToolChoice; download?: DownloadFunction; abortSignal?: AbortSignal; headers?: Record; includeRawChunks?: boolean; providerOptions?: ProviderOptions; repairToolCall?: ToolCallRepairFunction | undefined; refineToolInput?: ToolInputRefinement | undefined; executeLanguageModelCallInTelemetryContext?: Telemetry['executeLanguageModelCall']; callId?: string; /** * Tool context used to resolve per-call tool metadata such as function * descriptions before sending tools to the model. */ toolsContext?: InferToolSetContext; /** * Sandbox session passed through for resolving tool descriptions that depend on it. */ experimental_sandbox?: SandboxSession; _internal?: { generateId?: IdGenerator; generateCallId?: IdGenerator; now?: () => number; }; onLanguageModelCallStart?: Arrayable; onLanguageModelCallEnd?: Arrayable>; onStart?: (args: { promptMessages: LanguageModelV4Prompt; }) => Promise | void; } & Prompt & LanguageModelCallOptions): Promise<{ stream: AsyncIterableStream>; request?: { /** * Request HTTP body that was sent to the provider API. */ body?: unknown; }; response?: { /** * Response headers. */ headers?: SharedV4Headers; }; }>; declare const symbol$i: unique symbol; declare class InvalidStreamPartError extends AISDKError { private readonly [symbol$i]; readonly chunk: LanguageModelStreamPart; constructor({ chunk, message }: { chunk: LanguageModelStreamPart; message: string; }); static isInstance(error: unknown): error is InvalidStreamPartError; } declare const symbol$h: unique symbol; declare class InvalidToolApprovalError extends AISDKError { private readonly [symbol$h]; readonly approvalId: string; constructor({ approvalId }: { approvalId: string; }); static isInstance(error: unknown): error is InvalidToolApprovalError; } declare const symbol$g: unique symbol; declare class InvalidToolApprovalSignatureError extends AISDKError { private readonly [symbol$g]; readonly approvalId: string; readonly toolCallId: string; constructor({ approvalId, toolCallId, reason }: { approvalId: string; toolCallId: string; reason: string; }); static isInstance(error: unknown): error is InvalidToolApprovalSignatureError; } declare const symbol$f: unique symbol; declare class ToolCallNotFoundForApprovalError extends AISDKError { private readonly [symbol$f]; readonly toolCallId: string; readonly approvalId: string; constructor({ toolCallId, approvalId }: { toolCallId: string; approvalId: string; }); static isInstance(error: unknown): error is ToolCallNotFoundForApprovalError; } declare const symbol$e: unique symbol; declare class MissingToolResultsError extends AISDKError { private readonly [symbol$e]; readonly toolCallIds: string[]; constructor({ toolCallIds }: { toolCallIds: string[]; }); static isInstance(error: unknown): error is MissingToolResultsError; } declare const symbol$d: unique symbol; /** * Thrown when no image could be generated. This can have multiple causes: * * - The model failed to generate a response. * - The model generated a response that could not be parsed. */ declare class NoImageGeneratedError extends AISDKError { private readonly [symbol$d]; /** * The response metadata for each call. */ readonly responses: Array | undefined; constructor({ message, cause, responses }: { message?: string; cause?: Error; responses?: Array; }); static isInstance(error: unknown): error is NoImageGeneratedError; } declare const symbol$c: unique symbol; /** * Thrown when no object could be generated. This can have several causes: * * - The model failed to generate a response. * - The model generated a response that could not be parsed. * - The model generated a response that could not be validated against the schema. * * The error contains the following properties: * * - `text`: The text that was generated by the model. This can be the raw text or the tool call text, depending on the model. */ declare class NoObjectGeneratedError extends AISDKError { private readonly [symbol$c]; /** * The text that was generated by the model. This can be the raw text or the tool call text, depending on the model. */ readonly text: string | undefined; /** * The response metadata. */ readonly response: Omit | undefined; /** * The usage of the model. */ readonly usage: LanguageModelUsage | undefined; /** * Reason why the model finished generating a response. */ readonly finishReason: FinishReason | undefined; constructor({ message, cause, text: text$1, response, usage, finishReason }: { message?: string; cause?: Error; text?: string; response: Omit; usage: LanguageModelUsage; finishReason: FinishReason; }); static isInstance(error: unknown): error is NoObjectGeneratedError; } declare const symbol$b: unique symbol; /** * Thrown when no LLM output was generated, e.g. because of errors. */ declare class NoOutputGeneratedError extends AISDKError { private readonly [symbol$b]; constructor({ message, cause }?: { message?: string; cause?: Error; }); static isInstance(error: unknown): error is NoOutputGeneratedError; } declare const symbol$a: unique symbol; /** * Error that is thrown when no speech audio was generated. */ declare class NoSpeechGeneratedError extends AISDKError { private readonly [symbol$a]; readonly responses: Array; constructor(options: { responses: Array; }); static isInstance(error: unknown): error is NoSpeechGeneratedError; } declare const symbol$9: unique symbol; /** * Error that is thrown when no transcript was generated. */ declare class NoTranscriptGeneratedError extends AISDKError { private readonly [symbol$9]; readonly responses: Array; constructor(options: { responses: Array; }); static isInstance(error: unknown): error is NoTranscriptGeneratedError; } /** * Response metadata for speech translation model calls. * * Experimental: part of the experimental speech translation modality and may * change in patch releases. */ type SpeechTranslationModelResponseMetadata = { /** * 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; }; declare const symbol$8: unique symbol; /** * Error that is thrown when no translation was generated. */ declare class NoTranslationGeneratedError extends AISDKError { private readonly [symbol$8]; readonly response: SpeechTranslationModelResponseMetadata; constructor(options: { response: SpeechTranslationModelResponseMetadata; }); static isInstance(error: unknown): error is NoTranslationGeneratedError; } /** * Response metadata for a video model call. */ type VideoModelResponseMetadata = { /** * 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; /** * Provider-specific metadata for this call. * When multiple calls are made (n > maxVideosPerCall), each response * contains its own providerMetadata, allowing lossless per-call access. */ providerMetadata?: SharedV4ProviderMetadata; }; declare const symbol$7: unique symbol; declare class NoVideoGeneratedError extends AISDKError { private readonly [symbol$7]; readonly responses: Array; constructor({ message, cause, responses }: { message?: string; cause?: unknown; responses: Array; }); static isInstance(error: unknown): error is NoVideoGeneratedError; /** * @deprecated use `isInstance` instead */ static isNoVideoGeneratedError(error: unknown): error is NoVideoGeneratedError; /** * @deprecated Do not use this method. It will be removed in the next major version. */ toJSON(): { name: string; message: string; stack: string | undefined; cause: unknown; responses: VideoModelResponseMetadata[]; }; } declare const symbol$6: unique symbol; declare class ToolCallRepairError extends AISDKError { private readonly [symbol$6]; readonly originalError: NoSuchToolError | InvalidToolInputError; constructor({ cause, originalError, message }: { message?: string; cause: unknown; originalError: NoSuchToolError | InvalidToolInputError; }); static isInstance(error: unknown): error is ToolCallRepairError; } /** * Error that is thrown when a model with an unsupported version is used. */ declare class UnsupportedModelVersionError extends AISDKError { readonly version: string; readonly provider: string; readonly modelId: string; constructor(options: { version: string; provider: string; modelId: string; }); } declare const symbol$5: unique symbol; /** * Error thrown when a UI message stream contains invalid or out-of-sequence chunks. * * This typically occurs when: * - A delta chunk is received without a corresponding start chunk * - An end chunk is received without a corresponding start chunk * - A tool invocation is not found for the given toolCallId * * @see https://ai-sdk.dev/docs/reference/ai-sdk-errors/ai-ui-message-stream-error */ declare class UIMessageStreamError extends AISDKError { private readonly [symbol$5]; /** * The type of chunk that caused the error (e.g., 'text-delta', 'reasoning-end'). */ readonly chunkType: string; /** * The ID associated with the failing chunk (part ID or toolCallId). */ readonly chunkId: string; constructor({ chunkType, chunkId, message }: { chunkType: string; chunkId: string; message: string; }); static isInstance(error: unknown): error is UIMessageStreamError; } declare const symbol$4: unique symbol; declare class InvalidDataContentError extends AISDKError { private readonly [symbol$4]; readonly content: unknown; constructor({ content, cause, message }: { content: unknown; cause?: unknown; message?: string; }); static isInstance(error: unknown): error is InvalidDataContentError; } declare const symbol$3: unique symbol; declare class InvalidMessageRoleError extends AISDKError { private readonly [symbol$3]; readonly role: string; constructor({ role, message }: { role: string; message?: string; }); static isInstance(error: unknown): error is InvalidMessageRoleError; } declare const symbol$2: unique symbol; declare class MessageConversionError extends AISDKError { private readonly [symbol$2]; readonly originalMessage: Omit; constructor({ originalMessage, message }: { originalMessage: Omit; message: string; }); static isInstance(error: unknown): error is MessageConversionError; } declare const symbol$1: unique symbol; type RetryErrorReason = 'maxRetriesExceeded' | 'errorNotRetryable' | 'abort'; declare class RetryError extends AISDKError { private readonly [symbol$1]; readonly reason: RetryErrorReason; readonly lastError: unknown; readonly errors: Array; constructor({ message, reason, errors }: { message: string; reason: RetryErrorReason; errors: Array; }); static isInstance(error: unknown): error is RetryError; } type ActiveToolSubset>> = TOOLS extends undefined ? undefined : [ACTIVE_TOOL_NAMES] extends [NonNullable>>] ? Pick, ACTIVE_TOOL_NAMES[number]> : TOOLS; /** * Filters the tools to only include the active tools. * When activeTools is provided, we only include the tools that are in the list. * * @param tools - The tools to filter. * @param activeTools - The active tools to include. * @returns The filtered tools. */ declare function filterActiveTools>>({ tools, activeTools }: { tools: TOOLS; activeTools: ACTIVE_TOOL_NAMES; }): ActiveToolSubset; /** * Prunes model messages from a list of model messages. * * @param messages - The list of model messages to prune. * @param reasoning - How to remove reasoning content from assistant messages. Default is `'none'`. * @param toolCalls - How to prune tool call/results/approval content. Default is `[]`. * @param emptyMessages - Whether to keep or remove messages whose content is empty after pruning. Default is `'remove'`. * * @returns The pruned list of model messages. */ declare function pruneMessages({ messages, reasoning, toolCalls, emptyMessages }: { messages: ModelMessage[]; reasoning?: 'all' | 'before-last-message' | 'none'; toolCalls?: 'all' | 'before-last-message' | `before-last-${number}-messages` | 'none' | Array<{ type: 'all' | 'before-last-message' | `before-last-${number}-messages`; tools?: string[]; }>; emptyMessages?: 'keep' | 'remove'; }): ModelMessage[]; /** * Detects the first chunk in a buffer. * * @param buffer - The buffer to detect the first chunk in. * * @returns The first detected chunk, or `undefined` if no chunk was detected. */ type ChunkDetector = (buffer: string) => string | undefined | null; /** * Smooths text and reasoning streaming output. * * @param delayInMs - The delay in milliseconds between each chunk. Defaults to 10ms. Can be set to `null` to skip the delay. * @param chunking - Controls how the text is chunked for streaming. Use "word" to stream word by word (default), "line" to stream line by line, provide a custom RegExp pattern for custom chunking, provide an Intl.Segmenter for locale-aware word segmentation (recommended for CJK languages), or provide a custom ChunkDetector function. * * @returns A transform stream that smooths text streaming output. */ declare function smoothStream({ delayInMs, chunking, _internal: { delay } }?: { delayInMs?: number | null; chunking?: 'word' | 'line' | RegExp | ChunkDetector | Intl.Segmenter; /** * Internal. For test use only. May change without notice. */ _internal?: { delay?: (delayInMs: number | null) => Promise; }; }): (options: { tools: TOOLS; }) => TransformStream, TextStreamPart>; /** * Fingerprint the server-controlled, security-relevant fields of each tool in a * `ToolSet`: `description` (string form only), the resolved input JSON schema, * and `title`. Returns a map of tool name to a stable digest. * * Capture a baseline at trust time (first connect, human-reviewed) and compare * later fetches with {@link detectToolDrift} to catch MCP tool-definition drift * ("rug pull"). Baseline storage and the drift response are the app's concern. */ declare function fingerprintTools(tools: ToolSet): Promise>; /** * Pure diff of two fingerprint maps produced by {@link fingerprintTools}. * `added`/`removed` are tools present in only one map; `changed` are tools whose * pinned definition differs. Uses own-property lookups so a tool literally named * `constructor` or `toString` diffs correctly. */ declare function detectToolDrift(current: Record, baseline: Record): { added: string[]; removed: string[]; changed: string[]; }; /** * The result of a `generateImage` call. * It contains the images and additional information. */ interface GenerateImageResult { /** * The first image that was generated. */ readonly image: GeneratedFile; /** * The images that were generated. */ readonly images: Array; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: Array; /** * Response metadata from the provider. There may be multiple responses if we made multiple calls to the model. */ readonly responses: Array; /** * 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 providerMetadata: ImageModelProviderMetadata; /** * Combined token usage across all underlying provider calls for this image generation. */ readonly usage: ImageModelUsage; } type GenerateImagePrompt = string | { images: Array; text?: string; mask?: DataContent; }; /** * 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 maxImagesPerCall - Maximum number of images to generate in a single API call. * @param size - Size of the images to generate. Must have the format `{width}x{height}`. * @param aspectRatio - Aspect ratio of the images to generate. Must have the format `{width}:{height}`. * @param seed - Seed for the image generation. * @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: modelArg, prompt: promptArg, n, maxImagesPerCall, size, aspectRatio, seed, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers }: { /** * The image model to use. */ model: ImageModel; /** * The prompt that should be used to generate the image. */ prompt: GenerateImagePrompt; /** * Number of images to generate. */ n?: number; /** * Maximum number of images to generate in a single API call. If not provided, the model's default will be used. */ maxImagesPerCall?: number; /** * Size of the images to generate. Must have the format `{width}x{height}`. If not provided, the default size will be used. */ size?: `${number}x${number}`; /** * Aspect ratio of the images to generate. Must have the format `{width}:{height}`. If not provided, the default aspect ratio will be used. */ aspectRatio?: `${number}:${number}`; /** * Seed for the image generation. If not provided, the default seed will be used. */ seed?: 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?: ProviderOptions; /** * Maximum number of retries per image 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; }): Promise; /** * The result of a `generateObject` call. */ interface GenerateObjectResult { /** * The generated object (typed according to the schema). */ readonly object: OBJECT; /** * The reasoning that was used to generate the object. * Concatenated from all reasoning parts. */ readonly reasoning: string | undefined; /** * The reason why the generation finished. */ readonly finishReason: FinishReason; /** * The token usage of the generated response. */ readonly usage: LanguageModelUsage; /** * Warnings from the model provider (e.g. unsupported settings). */ readonly warnings: CallWarning[] | undefined; /** * Additional request information. */ readonly request: Omit; /** * Additional response information. */ readonly response: Omit; /** * 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 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; } /** * A function that attempts to repair the raw output of the model * to enable JSON parsing. * * Should return the repaired text or null if the text cannot be repaired. */ type RepairTextFunction = (options: { text: string; error: JSONParseError | TypeValidationError; }) => Promise; /** * 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. * * @param model - The language model to use. * * @param system - A system message that will be part of the prompt. * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both. * @param messages - A list of messages. You can either use `prompt` or `messages` but not both. * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false. * * @param maxOutputTokens - Maximum number of tokens to generate. * @param temperature - Temperature setting. * The value is passed through to the provider. The range depends on the provider and model. * It is recommended to set either `temperature` or `topP`, but not both. * @param topP - Nucleus sampling. * The value is passed through to the provider. The range depends on the provider and model. * It is recommended to set either `temperature` or `topP`, but not both. * @param topK - 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. * @param presencePenalty - Presence penalty setting. * It affects the likelihood of the model to repeat information that is already in the prompt. * The value is passed through to the provider. The range depends on the provider and model. * @param frequencyPenalty - Frequency penalty setting. * It affects the likelihood of the model to repeatedly use the same words or phrases. * The value is passed through to the provider. The range depends on the provider and model. * @param stopSequences - Stop sequences. * If set, the model will stop generating text when one of the stop sequences is generated. * @param seed - The seed (integer) to use for random sampling. * If set and supported by the model, calls will generate deterministic results. * * @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. * * @param schema - The schema of the object that the model should generate. * @param schemaName - Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. * via tool or schema name. * @param schemaDescription - Optional description of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. * via tool or schema description. * * @param output - The type of the output. * * - 'object': The output is an object. * - 'array': The output is an array. * - 'enum': The output is an enum. * - 'no-schema': The output is not a schema. * * @param repairText - A function that attempts to repair the raw output of the model * to enable JSON parsing. * @param experimental_repairText - Deprecated alias for `repairText`. * * @param telemetry - Optional telemetry configuration. * * @param providerOptions - Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. * * @param onStart - Callback invoked when generation begins, before the LLM call. * @param experimental_onStart - Deprecated alias for `onStart`. * @param onStepStart - Callback invoked when the model call begins. * @param experimental_onStepStart - Deprecated alias for `onStepStart`. * @param onStepEnd - Callback invoked when the model call completes with the raw result. * @param onStepFinish - Deprecated alias for `onStepEnd`. * @param onFinish - Callback invoked when the entire operation completes with the parsed object. * * @returns * A result object that contains the generated object, the finish reason, the token usage, and additional information. * * @deprecated Use `generateText` with an `output` setting instead. */ declare function generateObject = FlexibleSchema, OUTPUT extends 'object' | 'array' | 'enum' | 'no-schema' = (InferSchema extends string ? 'enum' : 'object'), RESULT = (OUTPUT extends 'array' ? Array> : InferSchema)>(options: Omit & Omit & Prompt & (OUTPUT extends 'enum' ? { /** * The enum values that the model should use. */ enum: Array; output: 'enum'; } : OUTPUT extends 'no-schema' ? {} : { /** * The schema of the object that the model should generate. */ schema: SCHEMA; /** * 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; }) & { output?: OUTPUT; /** * The language model to use. */ model: LanguageModel; /** * A function that attempts to repair the raw output of the model * to enable JSON parsing. */ repairText?: RepairTextFunction; /** * A function that attempts to repair the raw output of the model * to enable JSON parsing. * * @deprecated Use `repairText` instead. */ experimental_repairText?: RepairTextFunction; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions; /** * Custom download function to use for URLs. * * By default, files are downloaded if the model does not support the URL for the given media type. */ experimental_download?: DownloadFunction | undefined; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * Callback that is called when the generateObject operation begins, * before the LLM call is made. */ onStart?: Callback; /** * Callback that is called when the generateObject operation begins, * before the LLM call is made. * * @deprecated Use `onStart` instead. */ experimental_onStart?: Callback; /** * Callback that is called when the model call (step) begins, * before the provider is called. */ onStepStart?: Callback; /** * Callback that is called when the model call (step) begins, * before the provider is called. * * @deprecated Use `onStepStart` instead. */ experimental_onStepStart?: Callback; /** * Callback that is called when the model call (step) completes, * with the raw result before JSON parsing. */ onStepEnd?: Callback; /** * Callback that is called when the model call (step) completes, * with the raw result before JSON parsing. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: Callback; /** * Callback that is called when the entire operation completes * with the final parsed and validated object. */ onFinish?: Callback>; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: () => string; currentDate?: () => Date; }; }): Promise>; /** * Consumes a ReadableStream until it's fully read. * * This function reads the stream chunk by chunk until the stream is exhausted. * It doesn't process or return the data from the stream; it simply ensures * that the entire stream is read. * * @param options - The options for consuming the stream. * @param options.stream - The ReadableStream to be consumed. * @param options.onError - Optional callback to handle errors that occur during consumption. * @returns A promise that resolves when the stream is fully consumed. */ declare function consumeStream({ stream, onError, abortSignal }: { stream: ReadableStream; onError?: (error: unknown) => void; abortSignal?: AbortSignal; }): Promise; /** * Calculates the cosine similarity between two vectors. This is a useful metric for * comparing the similarity of two vectors such as embeddings. * * @param vector1 - The first vector. * @param vector2 - The second vector. * * @returns The cosine similarity between vector1 and vector2, or 0 if either vector is the zero vector. * * @throws {InvalidArgumentError} If the vectors do not have the same length. */ declare function cosineSimilarity(vector1: number[], vector2: number[]): number; /** * Creates a download function with configurable options. * * @param options - Configuration options for the download function. * @param options.maxBytes - Maximum allowed download size in bytes. Default: 2 GiB. * @returns A download function that can be passed to `transcribe()` or `experimental_generateVideo()`. */ declare function createDownload(options?: { maxBytes?: number; }): ({ url, abortSignal }: { url: URL; abortSignal?: AbortSignal; }) => Promise<{ data: Uint8Array; mediaType: string | undefined; }>; /** * Converts a data URL of type text/* to a text string. */ declare function getTextFromDataUrl(dataUrl: string): string; /** * Performs a deep-equal comparison of two parsed JSON objects. * * @param {any} obj1 - The first object to compare. * @param {any} obj2 - The second object to compare. * @returns {boolean} - Returns true if the two objects are deeply equal, false otherwise. */ declare function isDeepEqualData(obj1: any, obj2: any): boolean; declare function parsePartialJson(jsonText: string | undefined): Promise<{ value: JSONValue$3 | undefined; state: 'undefined-input' | 'successful-parse' | 'repaired-parse' | 'failed-parse'; }>; type Job = () => Promise; declare class SerialJobExecutor { private queue; private isProcessing; private processQueue; run(job: Job): Promise; } /** * Creates a ReadableStream that emits the provided values with an optional delay between each value. * * @param options - The configuration options * @param options.chunks - Array of values to be emitted by the stream * @param options.initialDelayInMs - Optional initial delay in milliseconds before emitting the first value (default: 0). Can be set to `null` to skip the initial delay. The difference between `initialDelayInMs: null` and `initialDelayInMs: 0` is that `initialDelayInMs: null` will emit the values without any delay, while `initialDelayInMs: 0` will emit the values with a delay of 0 milliseconds. * @param options.chunkDelayInMs - Optional delay in milliseconds between emitting each value (default: 0). Can be set to `null` to skip the delay. The difference between `chunkDelayInMs: null` and `chunkDelayInMs: 0` is that `chunkDelayInMs: null` will emit the values without any delay, while `chunkDelayInMs: 0` will emit the values with a delay of 0 milliseconds. * @returns A ReadableStream that emits the provided values */ declare function simulateReadableStream({ chunks, initialDelayInMs, chunkDelayInMs, _internal }: { chunks: T[]; initialDelayInMs?: number | null; chunkDelayInMs?: number | null; _internal?: { delay?: (ms: number | null) => Promise; }; }): ReadableStream; /** * The result of a `streamObject` call that contains the partial object stream and additional information. */ interface StreamObjectResult { /** * Warnings from the model provider (e.g. unsupported settings) */ readonly warnings: Promise; /** * The token usage of the generated response. Resolved when the response is finished. */ readonly usage: Promise; /** * 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 providerMetadata: Promise; /** * Additional request information from the last step. */ readonly request: Promise>; /** * Additional response information. */ readonly response: Promise>; /** * The reason why the generation finished. Taken from the last step. * * Resolved when the response is finished. */ readonly finishReason: Promise; /** * The generated object (typed according to the schema). Resolved when the response is finished. */ readonly object: Promise; /** * 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; /** * 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; /** * 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>; /** * 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): Promise; /** * 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 = { type: 'object'; object: PARTIAL; } | { type: 'text-delta'; textDelta: string; } | { type: 'error'; error: unknown; } | { type: 'finish'; finishReason: FinishReason; usage: LanguageModelUsage; response: Omit; providerMetadata?: ProviderMetadata; }; /** * Callback that is set using the `onError` option. * * @param event - The event that is passed to the callback. */ type StreamObjectOnErrorCallback = (event: { error: unknown; }) => Promise | void; /** * Callback that is set using the `onFinish` option. * * @param event - The event that is passed to the callback. */ type StreamObjectOnFinishCallback = (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 * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerMetadata: ProviderMetadata | undefined; }) => Promise | 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. * * @param model - The language model to use. * * @param system - A system message that will be part of the prompt. * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both. * @param messages - A list of messages. You can either use `prompt` or `messages` but not both. * @param allowSystemInMessages - Whether system messages are allowed in the `prompt` or `messages` fields. Default: false. * * @param maxOutputTokens - Maximum number of tokens to generate. * @param temperature - Temperature setting. * The value is passed through to the provider. The range depends on the provider and model. * It is recommended to set either `temperature` or `topP`, but not both. * @param topP - Nucleus sampling. * The value is passed through to the provider. The range depends on the provider and model. * It is recommended to set either `temperature` or `topP`, but not both. * @param topK - 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. * @param presencePenalty - Presence penalty setting. * It affects the likelihood of the model to repeat information that is already in the prompt. * The value is passed through to the provider. The range depends on the provider and model. * @param frequencyPenalty - Frequency penalty setting. * It affects the likelihood of the model to repeatedly use the same words or phrases. * The value is passed through to the provider. The range depends on the provider and model. * @param stopSequences - Stop sequences. * If set, the model will stop generating text when one of the stop sequences is generated. * @param seed - The seed (integer) to use for random sampling. * If set and supported by the model, calls will generate deterministic results. * * @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. * * @param schema - The schema of the object that the model should generate. * @param schemaName - Optional name of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. * via tool or schema name. * @param schemaDescription - Optional description of the output that should be generated. * Used by some providers for additional LLM guidance, e.g. * via tool or schema description. * * @param output - The type of the output. * * - 'object': The output is an object. * - 'array': The output is an array. * - 'enum': The output is an enum. * - 'no-schema': The output is not a schema. * * @param repairText - A function that attempts to repair the raw output of the model * to enable JSON parsing. * @param experimental_repairText - Deprecated alias for `repairText`. * * @param telemetry - Optional telemetry configuration. * * @param providerOptions - Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. * * @returns * A result object for accessing the partial object stream and additional information. * * @deprecated Use `streamText` with an `output` setting instead. */ declare function streamObject = FlexibleSchema, OUTPUT extends 'object' | 'array' | 'enum' | 'no-schema' = (InferSchema extends string ? 'enum' : 'object'), RESULT = (OUTPUT extends 'array' ? Array> : InferSchema)>(options: Omit & Omit & Prompt & (OUTPUT extends 'enum' ? { /** * The enum values that the model should use. */ enum: Array; output: 'enum'; } : OUTPUT extends 'no-schema' ? {} : { /** * The schema of the object that the model should generate. */ schema: SCHEMA; /** * 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; }) & { output?: OUTPUT; /** * The language model to use. */ model: LanguageModel; /** * A function that attempts to repair the raw output of the model * to enable JSON parsing. */ repairText?: RepairTextFunction; /** * A function that attempts to repair the raw output of the model * to enable JSON parsing. * * @deprecated Use `repairText` instead. */ experimental_repairText?: RepairTextFunction; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions; /** * Custom download function to use for URLs. * * By default, files are downloaded if the model does not support the URL for the given media type. */ experimental_download?: DownloadFunction | undefined; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * Callback that is called when the streamObject operation begins, * before the LLM call is made. */ onStart?: Callback; /** * Callback that is called when the streamObject operation begins, * before the LLM call is made. * * @deprecated Use `onStart` instead. */ experimental_onStart?: Callback; /** * Callback that is called when the model call (step) begins, * before the provider is called. */ onStepStart?: Callback; /** * Callback that is called when the model call (step) begins, * before the provider is called. * * @deprecated Use `onStepStart` instead. */ experimental_onStepStart?: Callback; /** * Callback that is called when the model streaming step completes, * with the raw accumulated text before final schema validation. */ onStepEnd?: Callback; /** * Callback that is called when the model streaming step completes, * with the raw accumulated text before final schema validation. * * @deprecated Use `onStepEnd` instead. */ onStepFinish?: Callback; /** * Callback that is invoked when an error occurs during streaming. * You can use it to log errors. * The stream processing will pause until the callback promise is resolved. */ onError?: StreamObjectOnErrorCallback; /** * Callback that is called when the LLM response and the final object validation are finished. */ onFinish?: Callback>; /** * Internal. For test use only. May change without notice. */ _internal?: { generateId?: () => string; currentDate?: () => Date; now?: () => number; }; }): StreamObjectResult, OUTPUT extends 'array' ? RESULT : RESULT, OUTPUT extends 'array' ? RESULT extends Array ? AsyncIterableStream : never : never>; /** * A generated audio file. */ interface GeneratedAudioFile extends GeneratedFile { /** * Audio format of the file (e.g., 'mp3', 'wav', etc.) */ readonly format: string; } /** * The result of a `generateSpeech` call. * It contains the audio data and additional information. */ interface SpeechResult { /** * The generated audio file with the audio data. */ readonly audio: GeneratedAudioFile; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: Array; /** * Response metadata from the provider. There may be multiple responses if we made multiple calls to the model. */ readonly responses: Array; /** * Provider metadata from the provider. */ readonly providerMetadata: Record; } /** * Generates speech audio using a speech model. * * @param model - The speech model to use. * @param text - The text to convert to speech. * @param voice - The voice to use for speech generation. * @param outputFormat - The output format to use for speech generation e.g. "mp3", "wav", etc. * @param instructions - Instructions for the speech generation e.g. "Speak in a slow and steady tone". * @param speed - The speed of the speech generation. * @param language - The language for speech generation (ISO 639-1 code e.g. "en", "es", "fr") or "auto" for automatic detection. * @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 audio data. */ declare function generateSpeech({ model, text: text$1, voice, outputFormat, instructions, speed, language, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers }: { /** * The speech model to use. */ model: SpeechModel; /** * The text to convert to speech. */ text: string; /** * The voice to use for speech generation. */ voice?: string; /** * The desired output format for the audio e.g. "mp3", "wav", etc. */ outputFormat?: 'mp3' | 'wav' | (string & {}); /** * Instructions for the speech generation e.g. "Speak in a slow and steady tone". */ instructions?: string; /** * The speed of the speech generation. */ speed?: number; /** * The language for speech generation. This should be an ISO 639-1 language code (e.g. "en", "es", "fr") * or "auto" for automatic language detection. Provider support varies. */ language?: string; /** * 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": {} * } * ``` */ providerOptions?: ProviderOptions; /** * Maximum number of retries per speech 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; }): Promise; /** * @deprecated Use `generateSpeech` instead. */ declare const experimental_generateSpeech: typeof generateSpeech; /** * @deprecated Use `SpeechResult` instead. */ type Experimental_SpeechResult = SpeechResult; /** * A video model can be a string (model ID) or a video model object. */ type VideoModel = string | VideoModelV4 | VideoModelV3; type VideoModelProviderMetadata = SharedV4ProviderMetadata; /** * The result of an `experimental_generateVideo` call. * Contains the generated video and additional information. */ interface GenerateVideoResult { /** * The first video that was generated. */ readonly video: GeneratedFile; /** * All videos that were generated. */ readonly videos: Array; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: Array; /** * Response metadata from the provider. * May contain multiple responses if multiple calls were made. */ readonly responses: Array; /** * Provider-specific metadata passed through from the provider. */ readonly providerMetadata: VideoModelProviderMetadata; } type GenerateVideoPrompt = string | { image: DataContent; text?: string; }; /** * Polling configuration for models that support the asynchronous * start/status flow. * * When used with `webhook`, `timeoutMs` also limits how long the SDK waits for * the webhook notification. If the model does not support webhooks, these * options configure the automatic polling fallback. */ type GenerateVideoPollOptions = { /** * Interval between status checks in milliseconds. * * @default 5000 */ intervalMs?: number; /** * Maximum time to wait for completion in milliseconds. * * @default 600000 (10 minutes) */ timeoutMs?: number; /** * Custom delay implementation for polling intervals and webhook timeouts. * This can be used with durable workflow sleep functions. * * @default the built-in timer-based delay */ delay?: (delayInMs: number, options?: { abortSignal?: AbortSignal; }) => PromiseLike; }; /** * Webhook factory for models that support the asynchronous start/status flow. * * The factory should return a URL for the provider to send notifications to, * and a `received` promise that resolves when the notification arrives. */ type GenerateVideoWebhookFactory = () => PromiseLike<{ url: string; received: PromiseLike; }>; declare function experimental_generateVideo({ model: modelArg, prompt: promptArg, n, maxVideosPerCall, aspectRatio, resolution, duration, fps, seed, frameImages, inputReferences, generateAudio, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, download: downloadFn, poll, webhook }: { /** * The video model to use. */ model: VideoModel; /** * The prompt that should be used to generate the video. */ prompt: GenerateVideoPrompt; /** * Number of videos to generate. */ n?: number; /** * Maximum number of videos per API call. If not provided, the model's default will be used. */ maxVideosPerCall?: number; /** * Aspect ratio of the videos to generate. Must have the format * `{width}:{height}`, or `'adaptive'` to inherit the ratio from the input media. */ aspectRatio?: `${number}:${number}` | 'adaptive'; /** * Resolution of the videos to generate. Must have the format `{width}x${height}`. */ resolution?: `${number}x${number}`; /** * Duration of the video in seconds. */ duration?: number; /** * Frames per second for the video. */ fps?: number; /** * Seed for the video generation. */ seed?: number; /** * Role-tagged image inputs for image-to-video and first-last-frame generation. */ frameImages?: Array<{ /** * The image for this frame. */ image: DataContent; /** * Which frame this image represents. */ frameType: VideoModelV4FrameType; }>; /** * Reference inputs for reference-to-video generation. * * Each entry may be a plain image/video ({@link DataContent}), or an object * form that carries an explicit `mediaType`. */ inputReferences?: Array; /** * Whether the model should generate audio alongside the video. */ generateAudio?: boolean; /** * Additional provider-specific options that are passed through to the provider * as body parameters. */ providerOptions?: ProviderOptions; /** * Maximum number of retries per video 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; /** * Custom download function for fetching videos from URLs. * Use `createDownload()` from `ai` to create a download function with custom size limits. * * @default createDownload() (2 GiB limit) */ download?: (options: { url: URL; abortSignal?: AbortSignal; }) => Promise<{ data: Uint8Array; mediaType: string | undefined; }>; /** * Polling configuration for models that support the asynchronous * start/status flow. When provided and the model implements `doStart` * and `doStatus`, the SDK will orchestrate polling automatically. * * This option can be combined with `webhook`: `timeoutMs` limits the webhook * wait, and the polling settings apply if the model does not support * webhooks. */ poll?: GenerateVideoPollOptions; /** * Webhook factory for models that support the asynchronous * start/status flow. When provided and the model implements `doStart` * and `doStatus`, the SDK will use webhooks instead of polling. * * The factory should return a URL for the provider to send notifications to, * and a `received` promise that resolves when the notification arrives. * `poll` can also be provided to configure the webhook timeout and polling * fallback. */ webhook?: GenerateVideoWebhookFactory; }): Promise; /** * Applies default settings for an embedding model. */ declare function defaultEmbeddingSettingsMiddleware({ settings }: { settings: Partial<{ headers?: EmbeddingModelV4CallOptions['headers']; providerOptions?: EmbeddingModelV4CallOptions['providerOptions']; }>; }): EmbeddingModelMiddleware; /** * Applies default instructions to a language model when a call does not * already contain a system message. */ declare function defaultInstructionsMiddleware({ instructions }: { /** * Default instructions to prepend to calls that do not contain a system * message. */ instructions: Instructions; }): LanguageModelMiddleware; /** * Applies default settings for a language model. */ declare function defaultSettingsMiddleware({ settings }: { settings: Partial<{ maxOutputTokens?: LanguageModelV4CallOptions['maxOutputTokens']; temperature?: LanguageModelV4CallOptions['temperature']; stopSequences?: LanguageModelV4CallOptions['stopSequences']; topP?: LanguageModelV4CallOptions['topP']; topK?: LanguageModelV4CallOptions['topK']; presencePenalty?: LanguageModelV4CallOptions['presencePenalty']; frequencyPenalty?: LanguageModelV4CallOptions['frequencyPenalty']; responseFormat?: LanguageModelV4CallOptions['responseFormat']; seed?: LanguageModelV4CallOptions['seed']; tools?: LanguageModelV4CallOptions['tools']; toolChoice?: LanguageModelV4CallOptions['toolChoice']; headers?: LanguageModelV4CallOptions['headers']; providerOptions?: LanguageModelV4CallOptions['providerOptions']; }>; }): LanguageModelMiddleware; /** * Middleware that extracts JSON from text content by stripping * markdown code fences and other formatting. * * This is useful when using Output.object() with models that wrap * JSON responses in markdown code blocks. * * @param options - Configuration options for the middleware. * @param options.transform - Custom transform function. If provided, this will be * used instead of the default markdown fence stripping. */ declare function extractJsonMiddleware(options?: { /** * Custom transform function to apply to text content. * Receives the raw text and should return the transformed text. * If not provided, the default transform strips markdown code fences. */ transform?: (text: string) => string; }): LanguageModelMiddleware; /** * Extracts an XML-tagged reasoning section from the generated text and exposes it * as a `reasoning` property on the result. * * @param tagName - The name of the XML tag to extract reasoning from. * @param separator - The separator to use between reasoning and text sections. * @param startWithReasoning - Whether to start with reasoning tokens. */ declare function extractReasoningMiddleware({ tagName, separator, startWithReasoning }: { tagName: string; separator?: string; startWithReasoning?: boolean; }): LanguageModelMiddleware; /** * Simulates streaming chunks with the response from a generate call. */ declare function simulateStreamingMiddleware(): LanguageModelMiddleware; /** * Middleware that appends input examples to tool descriptions. * * This is useful for providers that don't natively support the `inputExamples` * property. The middleware serializes examples into the tool's description text. * * @param options - Configuration options for the middleware. * @param options.prefix - A prefix to prepend before the examples. Default: 'Input Examples:' * @param options.format - Optional custom formatter for each example. * Receives the example object and its index. Default: JSON.stringify(example.input) * @param options.remove - Whether to remove the inputExamples property * after adding them to the description. Default: true * * @example * ```ts * import { wrapLanguageModel, addToolInputExamplesMiddleware } from 'ai'; * * const model = wrapLanguageModel({ * model: yourModel, * middleware: addToolInputExamplesMiddleware(), * }); * ``` */ declare function addToolInputExamplesMiddleware({ prefix, format, remove }?: { /** * A prefix to prepend before the examples. */ prefix?: string; /** * Optional custom formatter for each example. * Receives the example object and its index. * Default: JSON.stringify(example.input) */ format?: (example: { input: JSONObject$2; }, index: number) => string; /** * Whether to remove the inputExamples property after adding them to the description. * Default: true */ remove?: boolean; }): LanguageModelMiddleware; /** * Wraps a LanguageModelV4 instance with middleware functionality. * This function allows you to apply middleware to transform parameters, * wrap generate operations, and wrap stream operations of a language model. * * @param options - Configuration options for wrapping the language model. * @param options.model - The original LanguageModelV4 instance to be wrapped. * @param options.middleware - The middleware to be applied to the language model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @param options.modelId - Optional custom model ID to override the original model's ID. * @param options.providerId - Optional custom provider ID to override the original model's provider ID. * @returns A new LanguageModelV4 instance with middleware applied. */ declare const wrapLanguageModel$1: ({ model: inputModel, middleware: middlewareArg, modelId, providerId }: { model: LanguageModelV2$1 | LanguageModelV3$1 | LanguageModelV4; middleware: LanguageModelMiddleware | LanguageModelMiddleware[]; modelId?: string; providerId?: string; }) => LanguageModelV4; /** * Wraps an EmbeddingModelV4 instance with middleware functionality. * This function allows you to apply middleware to transform parameters, * wrap embed operations of an embedding model. * * @param options - Configuration options for wrapping the embedding model. * @param options.model - The original EmbeddingModelV4 instance to be wrapped. * @param options.middleware - The middleware to be applied to the embedding model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @param options.modelId - Optional custom model ID to override the original model's ID. * @param options.providerId - Optional custom provider ID to override the original model's provider ID. * @returns A new EmbeddingModelV4 instance with middleware applied. */ declare const wrapEmbeddingModel: ({ model: inputModel, middleware: middlewareArg, modelId, providerId }: { model: EmbeddingModelV3 | EmbeddingModelV4; middleware: EmbeddingModelMiddleware | EmbeddingModelMiddleware[]; modelId?: string; providerId?: string; }) => EmbeddingModelV4; /** * Wraps an ImageModelV4 instance with middleware functionality. * This function allows you to apply middleware to transform parameters * and wrap generate operations of an image model. * * @param options - Configuration options for wrapping the image model. * @param options.model - The original ImageModelV4 instance to be wrapped. * @param options.middleware - The middleware to be applied to the image model. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @param options.modelId - Optional custom model ID to override the original model's ID. * @param options.providerId - Optional custom provider ID to override the original model's provider ID. * @returns A new ImageModelV4 instance with middleware applied. */ declare const wrapImageModel: ({ model: inputModel, middleware: middlewareArg, modelId, providerId }: { model: ImageModelV2 | ImageModelV3 | ImageModelV4; middleware: ImageModelMiddleware | ImageModelMiddleware[]; modelId?: string; providerId?: string; }) => ImageModelV4; /** * Wraps a ProviderV4 instance with middleware functionality. * This function allows you to apply middleware to all language models * from the provider, enabling you to transform parameters, wrap generate * operations, and wrap stream operations for every language model. * * @param options - Configuration options for wrapping the provider. * @param options.provider - The original ProviderV4 instance to be wrapped. * @param options.languageModelMiddleware - The middleware to be applied to all language models from the provider. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @param options.imageModelMiddleware - Optional middleware to be applied to all image models from the provider. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @returns A new ProviderV4 instance with middleware applied to all language models. */ declare function wrapProvider({ provider, languageModelMiddleware, imageModelMiddleware }: { provider: ProviderV4 | ProviderV3 | ProviderV2; languageModelMiddleware: LanguageModelMiddleware | LanguageModelMiddleware[]; imageModelMiddleware?: ImageModelMiddleware | ImageModelMiddleware[]; }): ProviderV4; /** * Converts Float32 audio samples to a base64-encoded PCM16 string * for sending to a realtime model via input_audio_buffer.append. * * Samples are expected to be in the range [-1.0, 1.0]. * Output is 16-bit signed integer, little-endian, base64-encoded. */ declare function encodeRealtimeAudio(float32Array: Float32Array): string; /** * Converts a base64-encoded PCM16 string (from a realtime model's * audio-delta event) back to Float32 audio samples. * * Input is expected to be 16-bit signed integer, little-endian, base64-encoded. * Output samples are in the range [-1.0, 1.0]. */ declare function decodeRealtimeAudio(base64Audio: string): Float32Array; /** * Resamples audio from one sample rate to another using linear * interpolation. Suitable for voice audio. * * @param input - Float32 audio samples at the input sample rate. * @param inputRate - The sample rate of the input audio (e.g. 48000). * @param outputRate - The desired output sample rate (e.g. 24000). * @returns Float32 audio samples at the output sample rate. */ declare function resampleAudio(input: Float32Array, inputRate: number, outputRate: number): Float32Array; type RealtimeFactory = RealtimeFactoryV4; type RealtimeFactoryGetTokenOptions = RealtimeFactoryV4GetTokenOptions; type RealtimeFactoryGetTokenResult = RealtimeFactoryV4GetTokenResult; type RealtimeModel = RealtimeModelV4; type RealtimeClientEvent = RealtimeModelV4ClientEvent; type RealtimeServerEvent = RealtimeModelV4ServerEvent; type RealtimeSessionConfig = RealtimeModelV4SessionConfig; type RealtimeToolDefinition = RealtimeModelV4ToolDefinition; declare function getRealtimeToolDefinitions({ tools, toolsContext }: { tools: TOOLS; toolsContext?: InferToolSetContext; }): Promise; type RealtimeStatus = 'disconnected' | 'connecting' | 'connected' | 'error'; interface RealtimeState { status: RealtimeStatus; messages: UIMessage[]; events: RealtimeServerEvent[]; isCapturing: boolean; isPlaying: boolean; } type RealtimeSessionOptions = { model: RealtimeModel; api: { token: string; }; sessionConfig?: Partial; sampleRate?: number; maxEvents?: number; onToolCall?: (args: { toolCall: { toolCallId: string; toolName: string; args: unknown; }; }) => Promise | unknown | undefined; onEvent?: (event: RealtimeServerEvent) => void; onError?: (error: Error) => void; }; declare abstract class AbstractRealtimeSession { protected state: RealtimeState; protected maxEvents: number; onToolCall: RealtimeSessionOptions['onToolCall']; onEvent: ((event: RealtimeServerEvent) => void) | undefined; onError: ((error: Error) => void) | undefined; private readonly model; private readonly api; private readonly sessionConfig; private readonly reducer; private readonly transport; private readonly audio; private currentResponseItemId; private readonly toolCallsInResponse; private readonly submittedToolOutputs; private responseToolCallsClosed; protected abstract setState(key: K, value: RealtimeState[K]): void; constructor(options: RealtimeSessionOptions); connect(): Promise; disconnect(): void; sendEvent(event: RealtimeClientEvent): void; sendTextMessage(text: string): void; sendAudio(base64Audio: string): void; commitAudio(): void; clearAudioBuffer(): void; requestResponse(options?: { modalities?: string[]; }): void; cancelResponse(): void; addToolOutput(callId: string, result: unknown): void; /** * Requests a single response once the tool-bearing response has finished * delivering its tool calls and every one of them has an output. Requesting a * response after each individual output can cause the model to continue * without the full tool context on multi-tool turns. */ private maybeRequestToolResponse; startAudioCapture(stream: MediaStream): void; stopAudioCapture(): void; stopPlayback(): void; dispose(): void; private applyState; private executeToolCall; private handleServerEvent; private handleReducerEffect; } /** * Response shape for the realtime setup/token endpoint. * The client uses this to establish a WebSocket connection and * configure the session with tool definitions. */ type RealtimeSetupResponse = { token: string; url: string; expiresAt?: number; tools: RealtimeToolDefinition[]; }; /** * Creates a custom provider with specified language models, text embedding models, image models, transcription models, speech models, file APIs, skill APIs, and an optional fallback provider. * * @param {Object} options - The options for creating the custom provider. * @param {Record} [options.languageModels] - A record of language models, where keys are model IDs and values are language model instances. * @param {Record} [options.embeddingModels] - A record of text embedding models, where keys are model IDs and values are embedding model instances. * @param {Record} [options.imageModels] - A record of image models, where keys are model IDs and values are image model instances. * @param {Record} [options.transcriptionModels] - A record of transcription models, where keys are model IDs and values are transcription model instances. * @param {Record} [options.speechModels] - A record of speech models, where keys are model IDs and values are speech model instances. * @param {Record} [options.rerankingModels] - A record of reranking models, where keys are model IDs and values are reranking model instances. * @param {Record} [options.videoModels] - A record of video models, where keys are model IDs and values are video model instances. * @param {FilesV4} [options.files] - A files interface for uploading files. * @param {SkillsV4} [options.skills] - A skills interface for uploading skills. * @param {ProviderV2 | ProviderV3 | ProviderV4} [options.fallbackProvider] - An optional fallback provider to use when a requested model is not found in the custom provider. * @returns {ProviderV4} A ProviderV4 object with languageModel, embeddingModel, imageModel, transcriptionModel, speechModel, rerankingModel, and videoModel methods. * * @throws {NoSuchModelError} Throws when a requested model is not found and no fallback provider is available. */ declare function customProvider, EMBEDDING_MODELS extends Record, IMAGE_MODELS extends Record, TRANSCRIPTION_MODELS extends Record, SPEECH_MODELS extends Record, RERANKING_MODELS extends Record, VIDEO_MODELS extends Record, FILES extends FilesV4 | undefined = undefined, SKILLS extends SkillsV4 | undefined = undefined, FALLBACK extends ProviderV2 | ProviderV3 | ProviderV4 | undefined = undefined>({ languageModels, embeddingModels, imageModels, transcriptionModels, speechModels, rerankingModels, videoModels, files, skills, fallbackProvider: fallbackProviderArg }: { languageModels?: LANGUAGE_MODELS; embeddingModels?: EMBEDDING_MODELS; imageModels?: IMAGE_MODELS; transcriptionModels?: TRANSCRIPTION_MODELS; speechModels?: SPEECH_MODELS; rerankingModels?: RERANKING_MODELS; videoModels?: VIDEO_MODELS; files?: FILES; skills?: SKILLS; fallbackProvider?: FALLBACK; }): ProviderV4 & { languageModel(modelId: ExtractModelId): LanguageModelV4; embeddingModel(modelId: ExtractModelId): EmbeddingModelV4; imageModel(modelId: ExtractModelId): ImageModelV4; transcriptionModel(modelId: ExtractModelId): TranscriptionModelV4; rerankingModel(modelId: ExtractModelId): RerankingModelV4; speechModel(modelId: ExtractModelId): SpeechModelV4; videoModel(modelId: ExtractModelId): VideoModelV4; } & (FILES extends FilesV4 ? { files(): FilesV4; } : [FALLBACK] extends [{ files: () => FilesV4; }] ? { files(): FilesV4; } : { files?(): FilesV4; }) & (SKILLS extends SkillsV4 ? { skills(): SkillsV4; } : [FALLBACK] extends [{ skills: () => SkillsV4; }] ? { skills(): SkillsV4; } : { skills?(): SkillsV4; }); type ExtractModelId> = Extract; declare const symbol: unique symbol; declare class NoSuchProviderError extends NoSuchModelError { private readonly [symbol]; readonly providerId: string; readonly availableProviders: string[]; constructor({ modelId, modelType, providerId, availableProviders, message }: { modelId: string; modelType: 'languageModel' | 'embeddingModel' | 'imageModel' | 'transcriptionModel' | 'speechModel' | 'rerankingModel' | 'videoModel'; providerId: string; availableProviders: string[]; message?: string; }); static isInstance(error: unknown): error is NoSuchProviderError; } /** * If `text` is exactly the wide `string` type, there are no string literals to * preserve, so this resolves to `never`. * * If `text` is a string literal or a union of string literals, this resolves * to that literal union unchanged. * * This is used when building template-literal model identifiers (for example * `"provider:modelId"`) so that editors can suggest concrete `modelId` values * when the underlying method parameter is narrowed, while falling back to a * generic `"provider:${string}"` style overload when the parameter is only * typed as `string`. */ type ExtractLiteralUnion = text extends string ? string extends text ? never : text : never; type ProviderVideoModelIdentifier = PROVIDER extends { videoModel: (...args: infer ARGS) => unknown; } ? ExtractLiteralUnion : never; interface ProviderRegistryProvider = Record, SEPARATOR extends string = ':'> { languageModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion>[0]>}` : never): LanguageModelV4; languageModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): LanguageModelV4; embeddingModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion>[0]>}` : never): EmbeddingModelV4; embeddingModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): EmbeddingModelV4; imageModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion>[0]>}` : never): ImageModelV4; imageModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): ImageModelV4; transcriptionModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion>[0]>}` : never): TranscriptionModelV4; transcriptionModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): TranscriptionModelV4; speechModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion>[0]>}` : never): SpeechModelV4; speechModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): SpeechModelV4; rerankingModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ExtractLiteralUnion>[0]>}` : never): RerankingModelV4; rerankingModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): RerankingModelV4; videoModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${ProviderVideoModelIdentifier}` : never): VideoModelV4; videoModel(id: KEY extends string ? `${KEY & string}${SEPARATOR}${string}` : never): VideoModelV4; files(id: KEY extends string ? KEY & string : never): FilesV4; skills(id: KEY extends string ? KEY & string : never): SkillsV4; } /** * Creates a registry for the given providers with optional middleware functionality. * This function allows you to register multiple providers and optionally apply middleware * to all language models from the registry, enabling you to transform parameters, wrap generate * operations, and wrap stream operations for every language model accessed through the registry. * * @param providers - A record of provider instances to be registered in the registry. * @param options - Configuration options for the provider registry. * @param options.separator - The separator used between provider ID and model ID in the combined identifier. Defaults to ':'. * @param options.languageModelMiddleware - Optional middleware to be applied to all language models from the registry. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @param options.imageModelMiddleware - Optional middleware to be applied to all image models from the registry. When multiple middlewares are provided, the first middleware will transform the input first, and the last middleware will be wrapped directly around the model. * @returns A new ProviderRegistryProvider instance that provides access to all registered providers with optional middleware applied to language and image models. */ declare function createProviderRegistry, SEPARATOR extends string = ':'>(providers: PROVIDERS, { separator, languageModelMiddleware, imageModelMiddleware }?: { separator?: SEPARATOR; languageModelMiddleware?: LanguageModelMiddleware | LanguageModelMiddleware[]; imageModelMiddleware?: ImageModelMiddleware | ImageModelMiddleware[]; }): ProviderRegistryProvider; /** * @deprecated Use `createProviderRegistry` instead. */ declare const experimental_createProviderRegistry: typeof createProviderRegistry; /** * The result of a `rerank` call. * It contains the original documents, the reranked documents, and additional information. */ interface RerankResult { /** * The original documents that were reranked. */ readonly originalDocuments: Array; /** * Reranked documents. * * Sorted by relevance score in descending order. * * Can be less than the original documents if there was a topN limit. */ readonly rerankedDocuments: Array; /** * The ranking is a list of objects with the original index, * relevance score, and the reranked document. * * Sorted by relevance score in descending order. * * Can be less than the original documents if there was a topN limit. */ readonly ranking: Array<{ originalIndex: number; score: number; document: VALUE; }>; /** * Optional provider-specific metadata. */ readonly providerMetadata?: ProviderMetadata; /** * Optional raw response data. */ readonly response: { /** * ID for the generated response if the provider sends one. */ id?: string; /** * Timestamp of the generated response. */ timestamp: Date; /** * The ID of the model that was used to generate the response. */ modelId: string; /** * Response headers. */ headers?: Record; /** * The response body. */ body?: unknown; }; } /** * Rerank documents using a reranking model. The type of the value is defined by the reranking model. * * @param model - The reranking model to use. * @param documents - The documents that should be reranked. * @param query - The query to rerank the documents against. * @param topN - Number of top documents to return. * * @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. * @param providerOptions - Additional provider-specific options. * @param telemetry - Optional telemetry configuration. * * @returns A result object that contains the reranked documents, the reranked indices, and additional information. */ declare function rerank({ model: modelArg, documents, query, topN, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry, telemetry, onStart, experimental_onStart, onEnd, experimental_onEnd, _internal: { generateCallId } }: { /** * The reranking model to use. */ model: RerankingModel; /** * The documents that should be reranked. */ documents: Array; /** * The query to rerank the documents against. */ query: string; /** * Number of top documents to return. */ topN?: number; /** * Maximum number of retries per reranking 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; /** * Optional telemetry configuration. */ telemetry?: TelemetryOptions; /** * Optional telemetry configuration. * * @deprecated Use `telemetry` instead. This alias will be removed in a future major release. */ experimental_telemetry?: TelemetryOptions; /** * Additional provider-specific options. They are passed through * to the provider from the AI SDK and enable provider-specific * functionality that can be fully encapsulated in the provider. */ providerOptions?: ProviderOptions; /** * Callback that is called when the rerank operation begins, * before the reranking model is called. */ onStart?: Callback; /** * Callback that is called when the rerank operation begins, * before the reranking model is called. * * @deprecated Use `onStart` instead. */ experimental_onStart?: Callback; /** * Callback that is called when the rerank operation completes, * after the reranking model returns. */ onEnd?: Callback; /** * Callback that is called when the rerank operation completes, * after the reranking model returns. * * @deprecated Use `onEnd` instead. */ experimental_onEnd?: Callback; /** * Internal. For test use only. May change without notice. */ _internal?: { generateCallId?: () => string; }; }): Promise>; /** * Registers one or more telemetry integrations globally. */ declare function registerTelemetry(...integrations: Telemetry[]): void; /** * Creates a Response object from a text stream. * Each text chunk is encoded as UTF-8 and sent as a separate chunk. * Sets a `Content-Type` header to `text/plain; charset=utf-8`. * * @param options - The options for creating the response. * @param options.status - Optional HTTP status code (default: 200). * @param options.statusText - Optional HTTP status text. * @param options.headers - Optional response headers. * @param options.stream - The text stream to send. * @returns A Response object with the text stream body. */ declare function createTextStreamResponse({ status, statusText, headers, stream }: ResponseInit & { stream: ReadableStream; }): Response; /** * Writes a text stream to a Node.js ServerResponse object. * Each text chunk is encoded as UTF-8 and written as a separate chunk. * Sets a `Content-Type` header to `text/plain; charset=utf-8`. * * @param options - The options for piping the stream. * @param options.response - The Node.js ServerResponse to write to. * @param options.status - Optional HTTP status code. * @param options.statusText - Optional HTTP status text. * @param options.headers - Optional response headers. * @param options.stream - The text stream to pipe. * @returns A promise that resolves when the stream has been written. */ declare function pipeTextStreamToResponse({ response, status, statusText, headers, stream }: { response: ServerResponse; stream: ReadableStream; } & ResponseInit): Promise; /** * Converts a stream of `TextStreamPart` chunks into a stream of text deltas. */ declare function toTextStream({ stream }: { stream: ReadableStream>; }): ReadableStream; /** * The result of a `transcribe` call. * It contains the transcript and additional information. */ interface TranscriptionResult { /** * The complete transcribed text from the audio. */ readonly text: string; /** * Array of transcript segments with timing information. * Each segment represents a portion of the transcribed text with start and end times. */ readonly segments: Array<{ /** * The text content of this segment. */ readonly text: string; /** * The start time of this segment in seconds. */ readonly startSecond: number; /** * The end time of this segment in seconds. */ readonly endSecond: number; }>; /** * The detected language of the audio content, as an ISO-639-1 code (e.g., 'en' for English). * May be undefined if the language couldn't be detected. */ readonly language: string | undefined; /** * The total duration of the audio file in seconds. * May be undefined if the duration couldn't be determined. */ readonly durationInSeconds: number | undefined; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: Array; /** * Response metadata from the provider. There may be multiple responses if we made multiple calls to the model. */ readonly responses: Array; /** * Provider metadata from the provider. */ readonly providerMetadata: Record; } declare function transcribe({ model, audio, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, download: downloadFn }: { /** * The transcription model to use. */ model: TranscriptionModel; /** * The audio data to transcribe. */ audio: DataContent | URL; /** * 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": { * "temperature": 0 * } * } * ``` */ providerOptions?: ProviderOptions; /** * Maximum number of retries per transcript 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; /** * Custom download function for fetching audio from URLs. * Use `createDownload()` from `ai` to create a download function with custom size limits. * * @default createDownload() (2 GiB limit) */ download?: (options: { url: URL; abortSignal?: AbortSignal; }) => Promise<{ data: Uint8Array; mediaType: string | undefined; }>; }): Promise; type TranscriptionStreamPart = { type: 'transcript-delta'; id?: string; delta: string; providerMetadata?: SharedV4ProviderMetadata; } | { type: 'transcript-partial'; id?: string; text: string; startSecond?: number; durationInSeconds?: number; channelIndex?: number; providerMetadata?: SharedV4ProviderMetadata; } | { type: 'transcript-final'; id?: string; text: string; startSecond?: number; endSecond?: number; channelIndex?: number; providerMetadata?: SharedV4ProviderMetadata; } | { type: 'raw'; rawValue: unknown; } | { type: 'error'; error: unknown; }; interface StreamTranscriptionResult { /** * The final transcribed text. */ readonly text: PromiseLike; /** * Final transcript segments with timing information, if available. */ readonly segments: PromiseLike>; /** * The language of the transcript, if available. */ readonly language: PromiseLike; /** * The duration of the transcript in seconds, if available. */ readonly durationInSeconds: PromiseLike; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: PromiseLike>; /** * Response metadata. */ readonly responses: PromiseLike>; /** * Additional provider-specific metadata. */ readonly providerMetadata: PromiseLike>; /** * Full stream of transcription parts. * * This is a single-consumer live stream and can only be accessed once. * Access it before any result promise when both stream parts and final * results are needed; accessing a result promise first consumes the stream * internally and makes `fullStream` unavailable. */ readonly fullStream: AsyncIterableStream; } /** * Streams transcripts using a transcription model. * * @param model - The transcription model to use. * @param audio - Raw audio chunks to transcribe. * @param inputAudioFormat - The input audio format for the raw audio chunks. * @param providerOptions - Additional provider-specific options. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP/WebSocket headers to send when supported by the provider. * * @returns A result object that contains the streaming transcript and final transcript metadata. */ declare function streamTranscribe({ model, audio, inputAudioFormat, providerOptions, abortSignal, headers, includeRawChunks, _internal: { currentDate } }: { /** * The transcription model to use. */ model: TranscriptionModel; /** * Raw audio chunks to transcribe. */ audio: ReadableStream; /** * The input audio format for the raw audio chunks. */ inputAudioFormat: SharedV4AudioFormat; /** * Additional provider-specific options. */ providerOptions?: ProviderOptions; /** * Abort signal. */ abortSignal?: AbortSignal; /** * Additional headers to include in the request, if supported by the provider. */ headers?: Record; /** * When true, providers should include raw provider chunks in the stream. */ includeRawChunks?: boolean; /** * Internal test hooks. */ _internal?: { currentDate?: () => Date; }; }): StreamTranscriptionResult; /** * @deprecated Use `transcribe` instead. */ declare const experimental_transcribe: typeof transcribe; /** * @deprecated Use `TranscriptionResult` instead. */ type Experimental_TranscriptionResult = TranscriptionResult; /** * Speech translation model that is used by the AI SDK. * * Experimental: part of the experimental speech translation modality and may * change in patch releases. */ type SpeechTranslationModel = string | SpeechTranslationModelV4; /** * Stream parts emitted by `experimental_streamTranslate`. * * Speech translation model stream parts are passed through unchanged, except * for `stream-start`, `response-metadata`, and `finish`, which are consumed * internally and surfaced via the result promises. */ type TranslationStreamPart = { /** * Translated audio chunk in the target language. * * `Uint8Array` chunks contain raw audio bytes. `string` chunks contain * base64-encoded raw audio bytes. */ type: 'audio'; id?: string; audio: Uint8Array | string; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Append-only translated text delta. */ type: 'output-text-delta'; id?: string; delta: string; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Final translated text for a provider-defined segment or utterance. */ type: 'output-text-final'; id?: string; text: string; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Append-only source transcript delta. */ type: 'source-transcript-delta'; id?: string; delta: string; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Non-final source transcript text. The text may be revised by later parts. */ type: 'source-transcript-partial'; id?: string; text: string; startSecond?: number; endSecond?: number; channelIndex?: number; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Final source transcript text for a provider-defined segment or utterance. */ type: 'source-transcript-final'; id?: string; text: string; startSecond?: number; endSecond?: number; channelIndex?: number; providerMetadata?: SharedV4ProviderMetadata; } | { /** * Raw provider chunks if enabled via `includeRawChunks`. */ type: 'raw'; rawValue: unknown; } | { /** * Error parts are streamed, allowing for multiple errors. */ type: 'error'; error: unknown; }; interface StreamTranslationResult { /** * The final source-language transcript of the input audio. */ readonly sourceText: PromiseLike; /** * The final translated text in the target language. * * May resolve to an empty string for providers that produce only audio * output. */ readonly translationText: PromiseLike; /** * The duration of the source audio in seconds, if available. */ readonly durationInSeconds: PromiseLike; /** * Usage information for the translation call, if reported by the provider. */ readonly usage: PromiseLike; /** * Warnings for the call, e.g. unsupported settings. */ readonly warnings: PromiseLike>; /** * Response metadata. */ readonly response: PromiseLike; /** * Additional provider-specific metadata. */ readonly providerMetadata: PromiseLike>; /** * Full stream of translation parts. * * This is a single-consumer live stream and can only be accessed once. * Access it before any result promise when both stream parts and final * results are needed; accessing a result promise first consumes the stream * internally and makes `fullStream` unavailable. */ readonly fullStream: AsyncIterableStream; } /** * Streams speech-to-speech translations using a speech translation model. * * @param model - The speech translation model to use. * @param audio - Raw audio chunks to translate. * @param inputAudioFormat - The input audio format for the raw audio chunks. * @param targetLanguage - The language to translate the audio into. * @param sourceLanguage - The language of the source audio. Auto-detected when absent. * @param outputAudioFormat - The desired audio format for translated audio chunks. * @param providerOptions - Additional provider-specific options. * @param abortSignal - An optional abort signal that can be used to cancel the call. * @param headers - Additional HTTP/WebSocket headers to send when supported by the provider. * @param includeRawChunks - When true, providers include raw provider chunks in the stream as `raw` parts. * * @returns A result object that contains the streaming translation and final translation metadata. */ declare function streamTranslate({ model, audio, inputAudioFormat, targetLanguage, sourceLanguage, outputAudioFormat, providerOptions, abortSignal, headers, includeRawChunks, _internal: { currentDate } }: { /** * The speech translation model to use. */ model: SpeechTranslationModel; /** * Raw audio chunks to translate. */ audio: ReadableStream; /** * The input audio format for the raw audio chunks. */ inputAudioFormat: SharedV4AudioFormat; /** * The language to translate the audio into, as a BCP-47-style language * tag (e.g. `en`, `es`, `fr-CA`). Supported values are provider-specific * and validated by the provider. */ targetLanguage: string; /** * The language of the source audio, as a BCP-47-style language tag. * When absent, providers auto-detect the source language. */ sourceLanguage?: string; /** * The desired audio format for translated audio chunks. * When absent, the provider default output format is used. */ outputAudioFormat?: SharedV4AudioFormat; /** * Additional provider-specific options. */ providerOptions?: ProviderOptions; /** * Abort signal. */ abortSignal?: AbortSignal; /** * Additional headers to include in the request, if supported by the provider. */ headers?: Record; /** * When true, providers should include raw provider chunks in the stream. */ includeRawChunks?: boolean; /** * Internal test hooks. */ _internal?: { currentDate?: () => Date; }; }): StreamTranslationResult; interface UploadFileResult { readonly providerReference: ProviderReference; readonly mediaType?: string; readonly filename?: string; readonly providerMetadata?: ProviderMetadata; readonly warnings: Array; } /** * Uploads a file using a files API interface. * * @param api - The Files API interface to use for uploading. * @param data - The file data to upload (tagged `{ type: 'data' | 'text' }`). * @param mediaType - Optional IANA media type. Auto-detected from file bytes * when omitted (falls back to `text/plain` for the `text` variant). * @param filename - Optional filename for the uploaded file. * @param providerOptions - Additional provider-specific options. * * @returns A result object containing the provider reference and optional metadata. */ declare function uploadFile({ api, data: dataArg, mediaType: mediaTypeArg, filename, providerOptions }: { /** * The files API interface to use for uploading. * Can be a `FilesV4` instance or a `ProviderV4` instance with a `files()` method. */ api: FilesV4 | ProviderV4; } & Omit & { /** * The file data. Accepts the tagged `{ type: 'data' | 'text' }` shapes, or * the shorthand `Uint8Array | string` (treated as `{ type: 'data', data }`). */ data: FilesV4UploadFileCallOptions['data'] | Uint8Array | string; /** * Optional IANA media type of the file. Auto-detected from file bytes when * omitted; falls back to `text/plain` for the `text` variant. */ mediaType?: string; }): Promise; type UploadSkillResult = Omit & { readonly providerReference: ProviderReference; readonly warnings: Warning[]; }; type UploadSkillFile = Omit & { /** * The file data. Accepts the tagged `{ type: 'data' | 'text' }` shapes, or * the shorthand `Uint8Array | string` (treated as `{ type: 'data', data }`). */ data: SkillsV4File['data'] | Uint8Array | string; }; declare function uploadSkill({ api, files, displayTitle, providerOptions }: { api: SkillsV4 | ProviderV4; } & Omit & { files: UploadSkillFile[]; }): Promise; //#endregion //#region src/opentelemetry-lib/instrumentation/aisdk/index.d.ts declare const wrapAISDK: (ai: typeof index_d_exports) => typeof index_d_exports; declare function wrapLanguageModel(languageModel: LanguageModelV4): LanguageModelV4; declare function wrapLanguageModel(languageModel: LanguageModelV3): LanguageModelV3; declare function wrapLanguageModel(languageModel: LanguageModelV2): LanguageModelV2; //#endregion //#region src/opentelemetry-lib/instrumentation/aisdk/v7-integration/index.d.ts /** * The AI SDK v7 diagnostics channel name. Every lifecycle event fires * `{ type, event }` through this channel. */ declare const AI_SDK_TELEMETRY_DIAGNOSTIC_CHANNEL = "aisdk:telemetry"; interface LaminarAiSdkTelemetryOptions { /** * When true, record prompt messages and response content on spans. * Defaults to true. */ recordInputs?: boolean; recordOutputs?: boolean; /** * When true, create an `ai.step N` span for each step in a multi-step * generation. Defaults to false. */ createStepSpan?: boolean; /** * Options to pass to {@link Laminar.initialize}. If Laminar is already * initialized, this is ignored. Allows all-in-one setup without a separate * `Laminar.initialize()` call. */ laminarOptions?: LaminarInitializeProps; } /** * Laminar's implementation of the AI SDK v7 `Telemetry` interface. * * Shape matches `ai`'s exported `Telemetry` (v7). Constructing this class * directly depends only on OTel and Laminar internals — we do NOT import the * `Telemetry` interface from `ai` so users can pick up the integration even * when they are on a narrower `ai` version that doesn't export it yet. */ declare class LaminarAiSdkTelemetry { private readonly recordInputs; private readonly recordOutputs; private readonly createStepSpan; private readonly operationByCallId; private readonly stepByKey; private readonly llmByKey; private readonly toolByCallId; private readonly activeStreamStepByCallId; private readonly promptByCallId; private readonly logger; constructor(options?: LaminarAiSdkTelemetryOptions); onStart: (event: any) => void; onStepStart: (event: any) => void; onLanguageModelCallStart: (event: any) => void; onLanguageModelCallEnd: (event: any) => void; onChunk: (event: any) => void; onStepFinish: (event: any) => void; onObjectStepStart: (event: any) => void; onObjectStepFinish: (event: any) => void; onToolExecutionStart: (event: any) => void; onToolExecutionEnd: (event: any) => void; /** * `executeTool` is v7's context-propagation hook. The AI SDK runs the * tool's `execute` function inside whatever we return, so by entering a * context that has the tool span set as the active span, any nested * `generateText`/`streamText` call inside the tool will be reparented * under the TOOL span (sub-agent nesting). */ executeTool: (options: { callId: string; toolCallId: string; execute: () => PromiseLike; }) => PromiseLike; onEmbedStart: (event: any) => void; onEmbedEnd: (event: any) => void; onRerankStart: () => void; onRerankEnd: () => void; onEnd: (event: any) => void; onError: (event: any) => void; onAbort: (event: any) => void; /** End child spans, end the operation span, and clean up both maps. */ private closeOperation; /** Latest (highest-stepNumber) open step for a given callId. */ private findLatestStep; /** * End any still-open child spans owned by `callId` so the parent operation * span always has the latest endTime in its subtree — a degenerate provider * that skipped lang-model-call-end / step-finish / tool-end would otherwise * leave children ending after the operation and break trace hierarchy * semantics. Callers MUST invoke this BEFORE ending the operation span. * * Sweep order is llm + tool (leaves under step) → step. Tool spans are * children of step spans (see `onToolExecutionStart` where * `parentCtx = step?.ctx ?? op.ctx`), so step must end AFTER tool. * * Returns the latest endTime observed across ended children, or undefined * if no child was ended. Callers use this to clamp the operation span's * endTime so it is guaranteed ≥ every child's endTime — the default * `span.end()` reads a fresh hrtime each call, and four rapid synchronous * ends can land within the same sub-microsecond tick where the hrtime * source is not strictly monotonic across consecutive readings, making the * resulting ordering flaky. */ private endOrphanChildSpansForCallId; } /** * Returns a Laminar `Telemetry` integration instance. Pass it to * `experimental_telemetry.integrations` on any AI SDK v7 generate/stream/ * embed/rerank call, or via `registerLaminarTelemetry()` for global opt-in. * * @example * ```ts * import { generateText } from "ai"; * import { laminarTelemetry } from "@lmnr-ai/lmnr"; * * await generateText({ * model: openai("gpt-4o"), * prompt: "hi", * experimental_telemetry: { * isEnabled: true, * integrations: laminarTelemetry(), * }, * }); * ``` */ declare const aiSdkTelemetry: (options?: LaminarAiSdkTelemetryOptions) => LaminarAiSdkTelemetry; /** * Registers a Laminar `Telemetry` integration as a global receiver for every * AI SDK v7 call that has telemetry enabled. * * Mirrors `registerTelemetry(...)` from `ai` (which writes * `globalThis.AI_SDK_TELEMETRY_INTEGRATIONS`), but avoids a runtime import * of `ai` — callers often want to register telemetry before the first * provider call and must not pay the cost of eagerly loading the AI SDK. */ declare const registerAiSdkTelemetry: (options?: LaminarAiSdkTelemetryOptions) => LaminarAiSdkTelemetry; /** * Subscribes a pino-style logger to AI SDK v7's `diagnostics_channel`, which * fires every lifecycle event as `{ type, event }`. Use this for debugging * why a span didn't appear or what attributes are on the wire. * * Returns an unsubscribe function. */ declare const enableAiSdkTelemetryDebug: (log?: (entry: { type: string; event: unknown; }) => void) => (() => void); //#endregion //#region src/opentelemetry-lib/instrumentation/claude-agent-sdk/index.d.ts /** * Create an instrumented version of the claude-agent-sdk query function. * This can be used when importing the query function before Laminar initialization. * * @param originalQuery - The original query function from claude-agent-sdk * @returns The instrumented query function */ declare function instrumentClaudeAgentQuery(originalQuery: any): any; //#endregion //#region src/opentelemetry-lib/instrumentation/mastra/types.d.ts interface MastraSpanErrorInfo { message: string; name?: string; stack?: string; details?: Record; } interface MastraExportedSpan { id: string; traceId: string; parentSpanId?: string; name: string; type: string; startTime: Date; endTime?: Date; attributes?: Record; metadata?: Record; tags?: string[]; input?: unknown; output?: unknown; errorInfo?: MastraSpanErrorInfo; isEvent: boolean; isRootSpan: boolean; } interface MastraTracingEvent { type: "span_started" | "span_updated" | "span_ended"; exportedSpan: MastraExportedSpan; } interface MastraExporterOptions { /** * Flush the underlying span processor after every span end. Useful for * short-lived processes that exit before the batch processor would drain * on its own. */ realtime?: boolean; /** * When true (default), reparent Mastra traces under the caller's active * OpenTelemetry span if one exists. This lets `observe()`-wrapped code that * calls a Mastra agent produce a single unified trace instead of two * disconnected ones (user's OTel trace + Mastra's own trace). * * Mastra does not propagate OTel context into its event bus, so without * this we'd emit under Mastra's self-assigned trace id with no parent. * Set to false to preserve Mastra's original trace id even when nested * inside `observe()`. */ linkToActiveContext?: boolean; } //#endregion //#region src/opentelemetry-lib/instrumentation/mastra/exporter.d.ts /** * Bridges Mastra's ObservabilityExporter contract to Laminar's OTLP ingestion. * * Span-type mapping: * - `model_step` → LLM (atomic LLM call; rendered with message history). * - `tool_call`, `mcp_tool_call` → TOOL. * - `model_chunk` → dropped (per-delta, noise). * - everything else → DEFAULT. * * Tool-call reconstruction: Mastra's `extractStepInput` collapses prior tool * calls/results into empty user messages on MODEL_STEP inputs, so we * reconstruct the full conversation by accumulating (baseMessages → step0's * assistant message → tool-result message(s) → step1's assistant message → * …) using the parent MODEL_GENERATION's input and the children TOOL_CALL * spans paired by arrival order with each step's declared toolCalls. * * For LLM spans we emit `ai.prompt.messages` (stringified AI SDK messages * with tool-call / tool-result content parts) and `ai.response.text` + * `ai.response.toolCalls` so Laminar's backend parser threads them into * the LLM message history view. */ declare class MastraExporter { readonly name = "laminar"; private readonly config; private readonly traceMap; private readonly generationStateById; private readonly generationAttrsById; private readonly generationIdByStepId; private readonly stepIndexBySpanId; private readonly liveOtelSpanByMastraId; private warnedNotInitialized; constructor(options?: MastraExporterOptions); init(_options?: unknown): void; exportTracingEvent(event: MastraTracingEvent): Promise; onTracingEvent(event: MastraTracingEvent): Promise; flush(): Promise; shutdown(): Promise; private handleSpanStarted; private recordSpanPath; private handleSpanEnded; private initGenerationState; private captureReasoningChunk; private updateGenerationStateOnSpanEnd; private getOrCreateTraceState; private startOtelSpan; private warnNotInitializedOnce; private buildParentContext; private applyEndAttributes; private buildLaminarAttributes; private applyLlmAttributes; private applyToolAttributes; } //#endregion //#region src/opentelemetry-lib/instrumentation/temporal/interceptors.d.ts /** * Options for Laminar Temporal interceptors. */ interface LaminarTemporalInterceptorOptions { /** * Whether the activity inbound interceptor should wrap each activity * execution in a Laminar span named after the activity type. * * Defaults to `true`. Set to `false` if you want only context restoration * (letting your own `observe()` calls act as roots inside the activity). */ createActivitySpan?: boolean; /** * Whether to record the activity's arguments as the span input. * * Defaults to `true`. Set to `false` to omit potentially large or sensitive * activity arguments from the span. Ignored when `createActivitySpan` is * `false`. */ recordActivityArgs?: boolean; /** * Whether to record the activity's return value as the span output. * * Defaults to `true`. Set to `false` to omit potentially large or sensitive * activity results from the span. Ignored when `createActivitySpan` is * `false`. */ recordActivityOutput?: boolean; } /** * Temporal client-side workflow interceptor. Injects the active Laminar span context * into every workflow-start / signal / query / update-start call via headers. * * **Explicit usage:** * ```typescript * const client = new Client({ * interceptors: { * workflow: [new LaminarTemporalInterceptors.WorkflowClientInterceptor()], * }, * }); * ``` */ declare class WorkflowClientInterceptor { start(input: T, next: (i: T) => Promise): Promise; startWithDetails(input: T, next: (i: T) => Promise): Promise; startUpdate(input: T, next: (i: T) => Promise): Promise; startUpdateWithStart(input: T, next: (i: T) => Promise): Promise; signal(input: T, next: (i: T) => Promise): Promise; signalWithStart(input: T, next: (i: T) => Promise): Promise; query(input: T, next: (i: T) => Promise): Promise; terminate(input: T, next: (i: T) => Promise): Promise; describe(input: T, next: (i: T) => Promise): Promise; } /** * Temporal client-side schedule interceptor. * * Deliberately a no-op: it does NOT inject Laminar trace headers on schedule * `create`. A Schedule is a long-lived server-side object, and the headers * attached to its workflow-start action are a stored template replayed on every * triggered run — runs that may fire hours or days later. Injecting the active * span at creation time would pin every future scheduled run to that single, * long-dead parent trace instead of letting each run start its own root trace. * Temporal exposes no per-run client-side hook to inject fresh context, so the * correct behavior is to forward unchanged and let each triggered workflow be * its own root. * * Kept as a registered interceptor (rather than omitted) so the wiring stays * explicit and stable, and so future per-run context support has a home. * * **Explicit usage:** * ```typescript * const client = new Client({ * interceptors: { * schedule: [new LaminarTemporalInterceptors.ScheduleClientInterceptor()], * }, * }); * ``` */ declare class ScheduleClientInterceptor { create(input: T, next: (i: T) => Promise): Promise; } /** * Warning: Standalone Activities are experimental in Temporal. If the API changes, * this interceptor may not work as expected. * Temporal client-side activity interceptor. Injects the active Laminar span context * into every activity start / terminate call via headers. * * **Explicit usage:** * ```typescript * const client = new Client({ * interceptors: { * schedule: [new LaminarTemporalInterceptors.ScheduleClientInterceptor()], * }, * }); * ``` */ declare class ActivityClientInterceptor { start(input: T, next: (i: T) => Promise): Promise; getResult(input: T, next: (i: T) => Promise): Promise; describe(input: T, next: (i: T) => Promise): Promise; cancel(input: T, next: (i: T) => Promise): Promise; terminate(input: T, next: (i: T) => Promise): Promise; list(input: T, next: (i: T) => AsyncIterable): AsyncIterable; count(input: T, next: (i: T) => Promise): Promise; } /** * Temporal worker-side interceptor. Reads the Laminar span context from * Temporal headers and restores it as the parent context before each activity * executes. When `createActivitySpan` is `true` (default), also wraps the * activity in a Laminar span named after the activity type. * * **Explicit usage:** * ```typescript * const worker = await Worker.create({ * interceptors: { * activityInbound: [ * () => new LaminarTemporalInterceptors.ActivityInboundInterceptor(), * ], * }, * }); * ``` */ declare class ActivityInboundInterceptor { readonly createActivitySpan: boolean; readonly recordActivityArgs: boolean; readonly recordActivityOutput: boolean; readonly activityType: string | undefined; readonly logger: import("pino").Logger; constructor(options?: LaminarTemporalInterceptorOptions, activityContext?: any); execute: | undefined; args: unknown[]; }, R>(input: T, next: (i: T) => Promise) => Promise; } declare const ActivityInterceptorFactory: (options?: LaminarTemporalInterceptorOptions) => (ctx: any) => { inbound: ActivityInboundInterceptor; }; //#endregion //#region src/opentelemetry-lib/instrumentation/temporal/index.d.ts /** Namespace export: `LaminarTemporalInterceptors.WorkflowClientInterceptor`. */ declare const LaminarTemporalInterceptors: { WorkflowClientInterceptor: typeof WorkflowClientInterceptor; ScheduleClientInterceptor: typeof ScheduleClientInterceptor; ActivityClientInterceptor: typeof ActivityClientInterceptor; ActivityInterceptorFactory: (options?: LaminarTemporalInterceptorOptions) => (ctx: any) => { inbound: { readonly createActivitySpan: boolean; readonly recordActivityArgs: boolean; readonly recordActivityOutput: boolean; readonly activityType: string | undefined; readonly logger: import("pino").Logger; execute: | undefined; args: unknown[]; }, R>(input: T, next: (i: T) => Promise) => Promise; }; }; }; //#endregion //#region src/opentelemetry-lib/instrumentation/temporal/consts.d.ts /** Header key used to carry the serialized Laminar span context through Temporal. */ declare const LAMINAR_SPAN_CONTEXT_HEADER = "x-lmnr-span-context"; /** * W3C traceparent header key — written alongside `x-lmnr-span-context` for * interop with non-Laminar clients/workers that understand W3C trace context. */ declare const TRACEPARENT_HEADER = "traceparent"; //#endregion //#region src/opentelemetry-lib/tracing/index.d.ts /** * Get the tracer provider. Returns Laminar's tracer provider if Laminar is initialized, * otherwise returns the global tracer provider. * @returns The tracer provider. */ declare const getTracerProvider: () => TracerProvider; /** * Get the tracer. * @returns Laminar's tracer if Laminar is initialized, * otherwise returns Laminar's tracer from the global tracer provider * * @example * // instrumentation.ts * import { Laminar } from '@lmnr-ai/lmnr'; * Laminar.initialize() * * // File that calls AI SDK. * import { getTracer } from '@lmnr-ai/lmnr'; * import { openai } from "@ai-sdk/openai"; * import { generateText } from "ai"; * * const response = await generateText({ * model: openai("gpt-4.1-nano"), * prompt: "What is the capital of France?", * experimental_telemetry: { * isEnabled: true, * tracer: getTracer(), * } * }) */ declare const getTracer: () => Tracer; //#endregion //#region src/opentelemetry-lib/tracing/instrumentations.d.ts /** * Initialize and return Laminar instrumentations. * Useful to use with libraries that initialize tracing and can register passed * instrumentations. * * @param options * @param {string} options.baseUrl - Base URL of the Laminar API. * @param {string} options.apiKey - Laminar project API key. If not provided, will use * the LMNR_PROJECT_API_KEY environment variable. * @param {number} options.httpPort - Laminar API http port. If not provided, will use * the port from the baseUrl or defaults to 443. Only required for Playwright/Puppeteer * instrumentations for sending browser sessions. * @param {boolean} options.suppressContentTracing - Whether to suppress content tracing. * @param {InitializeOptions["instrumentModules"]} options.instrumentModules - Record of modules * to instrument. * If not provided, all auto-instrumentable modules will be instrumented, which include * LLM calls (OpenAI, Anthropic, etc), Langchain, VectorDB calls (Pinecone, Qdrant, etc). * Pass an empty object {} to disable any kind of automatic instrumentation. * If you only want to auto-instrument specific modules, then pass them in the object. * * @returns {Instrumentation[]} Array of enabled instrumentations. It is your responsibility * to enable them and register them with the OpenTelemetry SDK. For example, you could use * registerInstrumentations from the opentelemetry-api to register them. */ declare const initializeLaminarInstrumentations: (options?: { baseUrl?: string; apiKey?: string; httpPort?: number; suppressContentTracing?: boolean; instrumentModules?: InitializeOptions["instrumentModules"]; sessionRecordingOptions?: SessionRecordingOptions; }) => Instrumentation[]; //#endregion export { AI_SDK_TELEMETRY_DIAGNOSTIC_CHANNEL, type Datapoint, EvaluationDataset as Dataset, type Dataset as DatasetType, type EvalReporter, type EvaluationDatapoint, type EvaluationDatapointDatasetLink, type EvaluatorFunction, type EvaluatorFunctionReturn, type EveAssertionResult, type EveAssertionSeverity, type EveEval, type EveEvalDerivedFacts, type EveEvalResult, type EveEvalRunSummary, type EveEvalTarget, type EveEvalTaskResult, type EveEvalToolCall, type EveEvalVerdict, type EveRuntimeIdentity, type Event, HumanEvaluator, LAMINAR_SPAN_CONTEXT_HEADER as LAMINAR_TEMPORAL_SPAN_CONTEXT_HEADER, TRACEPARENT_HEADER as LAMINAR_TEMPORAL_TRACEPARENT_HEADER, Laminar, LaminarAiSdkTelemetry, type LaminarAiSdkTelemetryOptions, LaminarAttributes, LaminarClient, LaminarDataset, type LaminarInitializeProps, LaminarReporter, type LaminarReporterOptions, type LaminarSpanContext, LaminarSpanProcessor, ActivityClientInterceptor as LaminarTemporalActivityClientInterceptor, ActivityInterceptorFactory as LaminarTemporalActivityInterceptorFactory, LaminarTemporalInterceptors, ScheduleClientInterceptor as LaminarTemporalScheduleClientInterceptor, WorkflowClientInterceptor as LaminarTemporalWorkflowClientInterceptor, type MaskInputOptions, MastraExporter, type MastraExporterOptions, type PushDatapointsResponse, type SessionRecordingOptions, type Span, TracingLevel, aiSdkTelemetry, enableAiSdkTelemetryDebug, evaluate, getTracer, getTracerProvider, initializeLaminarInstrumentations, instrumentClaudeAgentQuery, observe, observeDecorator, observeExperimentalDecorator, registerAiSdkTelemetry, withTracingLevel, wrapAISDK, wrapLanguageModel }; //# sourceMappingURL=index.d.cts.map