ai 7.0.177 → 7.0.179

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/default-stop-condition-wtuJTiTo.js +4213 -0
  3. package/dist/default-stop-condition-wtuJTiTo.js.map +1 -0
  4. package/dist/index-CM_8u8gB.d.ts +12107 -0
  5. package/dist/index-CM_8u8gB.d.ts.map +1 -0
  6. package/dist/index.d.ts +3 -11788
  7. package/dist/index.js +680 -4732
  8. package/dist/index.js.map +1 -1
  9. package/dist/internal/index.d.ts +4 -3301
  10. package/dist/internal/index.d.ts.map +1 -1
  11. package/dist/internal/index.js +2 -3819
  12. package/dist/simulate-readable-stream-Bi5kQKbv.js +25 -0
  13. package/dist/simulate-readable-stream-Bi5kQKbv.js.map +1 -0
  14. package/dist/simulate-readable-stream-BuwR4IbD.d.ts +21 -0
  15. package/dist/simulate-readable-stream-BuwR4IbD.d.ts.map +1 -0
  16. package/dist/test/index.d.ts +2 -20
  17. package/dist/test/index.d.ts.map +1 -1
  18. package/dist/test/index.js +3 -23
  19. package/dist/test/index.js.map +1 -1
  20. package/docs/02-foundations/02-providers-and-models.mdx +1 -0
  21. package/docs/03-agents/06-policy-tool-approvals.mdx +27 -2
  22. package/docs/03-agents/06-tool-approvals.mdx +2 -1
  23. package/docs/03-ai-sdk-core/18-tools.mdx +7 -2
  24. package/docs/03-ai-sdk-core/33-extractions.mdx +21 -4
  25. package/docs/03-ai-sdk-core/36-realtime.mdx +3 -1
  26. package/docs/03-ai-sdk-core/36-transcription.mdx +2 -2
  27. package/docs/03-ai-sdk-core/37-speech.mdx +1 -0
  28. package/docs/03-ai-sdk-core/60-telemetry.mdx +52 -4
  29. package/docs/03-ai-sdk-core/65-lifecycle-callbacks.mdx +124 -2
  30. package/docs/07-reference/01-ai-sdk-core/14-extract.mdx +13 -4
  31. package/docs/07-reference/02-ai-sdk-ui/05-use-realtime.mdx +6 -2
  32. package/docs/07-reference/05-ai-sdk-errors/ai-extraction-refusal-error.mdx +33 -0
  33. package/docs/07-reference/05-ai-sdk-errors/ai-extraction-unsupported-field-type-error.mdx +36 -0
  34. package/docs/07-reference/05-ai-sdk-errors/ai-invalid-tool-approval-signature-error.mdx +1 -0
  35. package/package.json +13 -13
  36. package/src/agent/tool-loop-agent-settings.ts +2 -1
  37. package/src/extract/extract-events.ts +135 -0
  38. package/src/extract/extract.ts +177 -74
  39. package/src/extract/index.ts +6 -0
  40. package/src/extract/restricted-telemetry-dispatcher.ts +97 -0
  41. package/src/generate-text/execute-tools-from-stream.ts +14 -8
  42. package/src/generate-text/generate-text.ts +26 -10
  43. package/src/generate-text/stream-language-model-call.ts +3 -0
  44. package/src/generate-text/stream-text.ts +11 -2
  45. package/src/realtime/browser-realtime-live-websocket.ts +23 -5
  46. package/src/realtime/realtime-session.ts +68 -29
  47. package/src/telemetry/create-telemetry-dispatcher.ts +12 -0
  48. package/src/telemetry/filter-telemetry-event.ts +2 -0
  49. package/src/telemetry/redact-telemetry-credentials.ts +13 -1
  50. package/src/telemetry/telemetry.ts +34 -0
  51. package/src/telemetry/tracing-channel.ts +2 -1
  52. package/dist/index.d.ts.map +0 -1
  53. package/dist/internal/index.js.map +0 -1
@@ -1,3136 +1,6 @@
1
- import { Arrayable, AssistantModelMessage, AssistantModelMessage as AssistantModelMessage$1, Context, Experimental_SandboxSession, FetchFunction, FilePart, FlexibleSchema, HasRequiredKey, InferToolContext, InferToolInput, InferToolOutput, InferToolSetContext, MaybePromiseLike, ModelMessage, ModelMessage as ModelMessage$1, ProviderOptions, ReasoningFilePart, ReasoningPart, RetryFunction, ShouldRetryFunction, SystemModelMessage, TextPart, Tool, ToolApprovalRequest, ToolApprovalResponse, ToolExecutionOptions, ToolModelMessage, ToolModelMessage as ToolModelMessage$1, ToolResultOutput, ToolResultPart, ToolSet, UserModelMessage, convertAsyncIteratorToReadableStream } from "@ai-sdk/provider-utils";
2
- import { AISDKError, EmbeddingModelV4Embedding, Experimental_DecisionModelV4CallOptions, Experimental_DecisionModelV4Question, Experimental_DecisionModelV4Result, JSONObject, JSONSchema7, JSONValue, LanguageModelV2, LanguageModelV3, LanguageModelV4, LanguageModelV4CallOptions, LanguageModelV4Citation, LanguageModelV4Content, LanguageModelV4FunctionTool, LanguageModelV4Prompt, LanguageModelV4ProviderTool, LanguageModelV4Source, LanguageModelV4ToolCall, LanguageModelV4ToolChoice, LanguageModelV4ToolResultOutput, LanguageModelV4Usage, ProviderV2, ProviderV3, ProviderV4, SharedV4AudioFormat, SharedV4ProviderMetadata, SharedV4Warning, TranscriptionModelV4TimestampGranularity } from "@ai-sdk/provider";
3
- import { GatewayModelId } from "@ai-sdk/gateway";
4
- import "zod/v4/core";
5
- import "zod/v4/mini";
6
- import "zod/v4";
7
- //#region src/types/provider-metadata.d.ts
8
- /**
9
- * Additional provider-specific metadata that is returned from the provider.
10
- *
11
- * This is needed to enable provider-specific functionality that can be
12
- * fully encapsulated in the provider.
13
- */
14
- type ProviderMetadata = SharedV4ProviderMetadata;
15
- //#endregion
16
- //#region src/types/citation.d.ts
17
- /** A reference supporting a generated text part. */
18
- type Citation = LanguageModelV4Citation;
19
- //#endregion
20
- //#region src/types/embedding-model.d.ts
21
- /**
22
- * Embedding.
23
- */
24
- type Embedding = EmbeddingModelV4Embedding;
25
- //#endregion
26
- //#region src/types/language-model.d.ts
27
- declare global {
28
- /**
29
- * Global interface that can be augmented by third-party packages to register custom model IDs.
30
- *
31
- * You can register model IDs in two ways:
32
- *
33
- * 1. Register based on Model IDs from a provider package:
34
- * @example
35
- * ```typescript
36
- * import { openai } from '@ai-sdk/openai';
37
- * type OpenAIResponsesModelId = Parameters<typeof openai>[0];
38
- *
39
- * declare global {
40
- * interface RegisteredProviderModels {
41
- * openai: OpenAIResponsesModelId;
42
- * }
43
- * }
44
- * ```
45
- *
46
- * 2. Register individual model IDs directly as keys:
47
- * @example
48
- * ```typescript
49
- * declare global {
50
- * interface RegisteredProviderModels {
51
- * 'my-provider:my-model': any;
52
- * 'my-provider:another-model': any;
53
- * }
54
- * }
55
- * ```
56
- */
57
- interface RegisteredProviderModels {}
58
- }
59
- /**
60
- * Global provider model ID type that defaults to GatewayModelId but can be augmented
61
- * by third-party packages via declaration merging.
62
- */
63
- type GlobalProviderModelId = [keyof RegisteredProviderModels] extends [never] ? GatewayModelId : keyof RegisteredProviderModels | RegisteredProviderModels[keyof RegisteredProviderModels];
64
- /**
65
- * Language model that is used by the AI SDK.
66
- */
67
- type LanguageModel = GlobalProviderModelId | LanguageModelV4 | LanguageModelV3 | LanguageModelV2;
68
- /**
69
- * Reason why a language model finished generating a response.
70
- *
71
- * Can be one of the following:
72
- * - `stop`: model generated stop sequence
73
- * - `length`: model generated maximum number of tokens
74
- * - `content-filter`: content filter violation stopped the model
75
- * - `tool-calls`: model triggered tool calls
76
- * - `error`: model stopped because of an error
77
- * - `interrupted`: provider stream ended without a completion signal; output may be incomplete
78
- * - `other`: model stopped for other reasons
79
- */
80
- type FinishReason = 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'interrupted' | 'other';
81
- /**
82
- * Registry for call warning variants. Packages that expose additional warning
83
- * protocols can augment this interface.
84
- */
85
- interface CallWarningRegistry {
86
- sharedV4: SharedV4Warning;
87
- }
88
- /**
89
- * Warning from the model provider for this call. The call will proceed, but e.g.
90
- * some settings might not be supported, which can lead to suboptimal results.
91
- */
92
- type CallWarning = CallWarningRegistry[keyof CallWarningRegistry];
93
- /**
94
- * A source that has been used as input to generate the response.
95
- */
96
- type Source = LanguageModelV4Source;
97
- /**
98
- * Tool choice for the generation. It supports the following settings:
99
- *
100
- * - `auto` (default): the model can choose whether and which tools to call.
101
- * - `required`: the model must call a tool. It can choose which tool to call.
102
- * - `none`: the model must not call tools
103
- * - `{ type: 'tool', toolName: string (typed) }`: the model must call the specified tool
104
- */
105
- type ToolChoice<TOOLS extends Record<string, unknown>> = 'auto' | 'none' | 'required' | {
106
- type: 'tool';
107
- toolName: Extract<keyof TOOLS, string>;
108
- };
109
- //#endregion
110
- //#region src/types/language-model-request-metadata.d.ts
111
- /**
112
- * Metadata for a language model request.
113
- */
114
- type LanguageModelRequestMetadata = {
115
- /** HTTP origin used for this request, without URL credentials, paths, queries or fragments. */
116
- readonly url?: string;
117
- /**
118
- * The input messages that were sent to the model for this step.
119
- */
120
- readonly messages?: Array<ModelMessage>;
121
- /**
122
- * Request HTTP body that was sent to the provider API.
123
- */
124
- readonly body?: unknown;
125
- };
126
- //#endregion
127
- //#region src/generate-text/response-message.d.ts
128
- /**
129
- * A message that was generated during the generation process.
130
- * It can be either an assistant message or a tool message.
131
- */
132
- type ResponseMessage = AssistantModelMessage | ToolModelMessage;
133
- //#endregion
134
- //#region src/types/language-model-response-metadata.d.ts
135
- /**
136
- * Metadata for a language model response.
137
- */
138
- type LanguageModelResponseMetadata = {
139
- /**
140
- * The response messages that were generated during the call.
141
- * Response messages can be either assistant messages or tool messages.
142
- * They contain a generated id.
143
- */
144
- readonly messages: Array<ResponseMessage>;
145
- /**
146
- * ID for the generated response.
147
- */
148
- readonly id: string;
149
- /**
150
- * Timestamp for the start of the generated response.
151
- */
152
- readonly timestamp: Date;
153
- /**
154
- * The ID of the response model that was used to generate the response.
155
- */
156
- readonly modelId: string;
157
- /**
158
- * Response headers (available only for providers that use HTTP requests).
159
- */
160
- readonly headers?: Record<string, string>;
161
- /**
162
- * Response body (available only for providers that use HTTP requests).
163
- */
164
- readonly body?: unknown;
165
- };
166
- //#endregion
167
- //#region src/types/speech-model-response-metadata.d.ts
168
- type SpeechModelResponseMetadata = {
169
- /**
170
- * Timestamp for the start of the generated response.
171
- */
172
- timestamp: Date;
173
- /**
174
- * The ID of the response model that was used to generate the response.
175
- */
176
- modelId: string;
177
- /**
178
- * Response headers.
179
- */
180
- headers?: Record<string, string>;
181
- /**
182
- * Response body.
183
- */
184
- body?: unknown;
185
- };
186
- //#endregion
187
- //#region src/types/transcription-model-response-metadata.d.ts
188
- type TranscriptionModelResponseMetadata = {
189
- /**
190
- * Timestamp for the start of the generated response.
191
- */
192
- timestamp: Date;
193
- /**
194
- * The ID of the response model that was used to generate the response.
195
- */
196
- modelId: string;
197
- /**
198
- * Response headers.
199
- */
200
- headers?: Record<string, string>;
201
- };
202
- //#endregion
203
- //#region src/types/usage.d.ts
204
- /**
205
- * Represents the number of tokens used in a prompt and completion.
206
- */
207
- type LanguageModelUsage = {
208
- /**
209
- * The total number of input (prompt) tokens used.
210
- */
211
- inputTokens: number | undefined;
212
- /**
213
- * Detailed information about the input tokens.
214
- */
215
- inputTokenDetails: {
216
- /**
217
- * The number of non-cached input (prompt) tokens used.
218
- */
219
- noCacheTokens: number | undefined;
220
- /**
221
- * The number of cached input (prompt) tokens read.
222
- */
223
- cacheReadTokens: number | undefined;
224
- /**
225
- * The number of cached input (prompt) tokens written.
226
- */
227
- cacheWriteTokens: number | undefined;
228
- };
229
- /**
230
- * The number of total output (completion) tokens used.
231
- */
232
- outputTokens: number | undefined;
233
- /**
234
- * Detailed information about the output tokens.
235
- */
236
- outputTokenDetails: {
237
- /**
238
- * The number of text tokens used.
239
- */
240
- textTokens: number | undefined;
241
- /**
242
- * The number of reasoning tokens used.
243
- */
244
- reasoningTokens: number | undefined;
245
- };
246
- /**
247
- * The total number of tokens used.
248
- */
249
- totalTokens: number | undefined;
250
- /**
251
- * Raw usage information from the provider.
252
- *
253
- * This is the usage information in the shape that the provider returns.
254
- * It can include additional information that is not part of the standard usage information.
255
- */
256
- raw?: JSONObject;
257
- };
258
- /**
259
- * Represents the number of tokens used in an embedding.
260
- */
261
- type EmbeddingModelUsage = {
262
- /**
263
- * The number of tokens used in the embedding.
264
- */
265
- tokens: number;
266
- };
267
- export declare function asLanguageModelUsage(usage: LanguageModelV4Usage): LanguageModelUsage;
268
- export declare function createNullLanguageModelUsage(): LanguageModelUsage;
269
- export declare function addLanguageModelUsage(usage1: LanguageModelUsage, usage2: LanguageModelUsage): LanguageModelUsage;
270
- //#endregion
271
- //#region src/types/warning.d.ts
272
- /**
273
- * Warning from the model provider for this call. The call will proceed, but e.g.
274
- * some settings might not be supported, which can lead to suboptimal results.
275
- */
276
- type Warning = SharedV4Warning;
277
- //#endregion
278
- //#region src/logger/log-warnings.d.ts
279
- /**
280
- * A function for logging warnings.
281
- *
282
- * You can assign it to the `AI_SDK_LOG_WARNINGS` global variable to use it as the default warning logger.
283
- *
284
- * @example
285
- * ```ts
286
- * globalThis.AI_SDK_LOG_WARNINGS = (options) => {
287
- * console.log('WARNINGS:', options.warnings, options.provider, options.model);
288
- * };
289
- * ```
290
- */
291
- type LogWarningsFunction = (options: {
292
- /**
293
- * The warnings returned by the model provider.
294
- */
295
- warnings: Warning[];
296
- /**
297
- * The provider id used for the call, if scoped to a specific provider.
298
- */
299
- provider?: string;
300
- /**
301
- * The model id used for the call, if scoped to a specific provider.
302
- */
303
- model?: string;
304
- }) => void;
305
- /**
306
- * Logs warnings to the console or uses a custom logger if configured.
307
- *
308
- * The behavior can be customized via the `AI_SDK_LOG_WARNINGS` global variable:
309
- * - If set to `false`, warnings are suppressed.
310
- * - If set to a function, that function is called with the warnings.
311
- * - Otherwise, warnings use `process.emitWarning` when available, falling back
312
- * to `console.warn`. Deprecations have stable codes and are emitted once per
313
- * code by the default logger. Custom loggers receive every warning.
314
- *
315
- * @param options - The options containing warnings and context.
316
- * @param options.warnings - The warnings to log.
317
- * @param options.provider - The provider id used for the call, if scoped to a specific provider.
318
- * @param options.model - The model id used for the call, if scoped to a specific provider.
319
- */
320
- export declare const logWarnings: LogWarningsFunction;
321
- //#endregion
322
- //#region src/embed/embed-events.d.ts
323
- /**
324
- * Event passed to the `onStart` callback for embed and embedMany operations.
325
- *
326
- * Called when the operation begins, before the embedding model is called.
327
- */
328
- type EmbedStartEvent<RUNTIME_CONTEXT extends Context = Context> = {
329
- /** User-defined runtime context. */
330
- readonly runtimeContext: RUNTIME_CONTEXT;
331
- /** Unique identifier for this embed call, used to correlate events. */
332
- readonly callId: string;
333
- /** Identifies the operation type (e.g. 'ai.embed' or 'ai.embedMany'). */
334
- readonly operationId: string;
335
- /** The provider identifier (e.g., 'openai', 'anthropic'). */
336
- readonly provider: string;
337
- /** The specific model identifier (e.g., 'text-embedding-3-small'). */
338
- readonly modelId: string;
339
- /** The value(s) being embedded. A string for embed, an array for embedMany. */
340
- readonly value: string | Array<string>;
341
- /** Requested output dimensions, when specified. */
342
- readonly dimensions?: number;
343
- /** Maximum number of retries for failed requests. */
344
- readonly maxRetries: number;
345
- /** Additional HTTP headers sent with the request. */
346
- readonly headers: Record<string, string | undefined> | undefined;
347
- /** Additional provider-specific options. */
348
- readonly providerOptions: ProviderOptions | undefined;
349
- };
350
- /**
351
- * Event passed to the `onEnd` callback for embed and embedMany operations.
352
- *
353
- * Called when the operation completes, after the embedding model returns.
354
- */
355
- type EmbedEndEvent<RUNTIME_CONTEXT extends Context = Context> = {
356
- /** User-defined runtime context. */
357
- readonly runtimeContext: RUNTIME_CONTEXT;
358
- /** Unique identifier for this embed call, used to correlate events. */
359
- readonly callId: string;
360
- /** Identifies the operation type (e.g. 'ai.embed' or 'ai.embedMany'). */
361
- readonly operationId: string;
362
- /** The provider identifier (e.g., 'openai', 'anthropic'). */
363
- readonly provider: string;
364
- /** The specific model identifier (e.g., 'text-embedding-3-small'). */
365
- readonly modelId: string;
366
- /** The value(s) that were embedded. A string for embed, an array for embedMany. */
367
- readonly value: string | Array<string>;
368
- /** The resulting embedding(s). A single vector for embed, an array for embedMany. */
369
- readonly embedding: Embedding | Array<Embedding>;
370
- /** Token usage for the embedding operation. */
371
- readonly usage: EmbeddingModelUsage;
372
- /** Warnings from the embedding model, e.g. unsupported settings. */
373
- readonly warnings: Array<Warning>;
374
- /** Optional provider-specific metadata. */
375
- readonly providerMetadata: ProviderMetadata | undefined;
376
- /** Response data including headers and body. A single response for embed, an array for embedMany. */
377
- readonly response: {
378
- headers?: Record<string, string>;
379
- body?: unknown;
380
- } | Array<{
381
- headers?: Record<string, string>;
382
- body?: unknown;
383
- } | undefined> | undefined;
384
- };
385
- /**
386
- * Event fired when an individual embedding model call (inner operation doEmbed) begins.
387
- *
388
- * For `embed`, there is one call. For `embedMany`, there may be multiple
389
- * calls when values are chunked.
390
- */
391
- type EmbeddingModelCallStartEvent = {
392
- /** Unique identifier for this embed call, used to correlate events. */
393
- readonly callId: string;
394
- /** Unique identifier for this individual doEmbed invocation, used to correlate start/finish within parallel chunks. */
395
- readonly embedCallId: string;
396
- /** Identifies the inner operation (e.g. 'ai.embed.doEmbed' or 'ai.embedMany.doEmbed'). */
397
- readonly operationId: string;
398
- /** The provider identifier. */
399
- readonly provider: string;
400
- /** The specific model identifier. */
401
- readonly modelId: string;
402
- /** The values being embedded in this particular model call. */
403
- readonly values: Array<string>;
404
- /** Requested output dimensions, when specified. */
405
- readonly dimensions?: number;
406
- };
407
- /**
408
- * Event fired when an individual embedding model call (doEmbed) completes.
409
- *
410
- * Contains the embeddings, usage, and any warnings from the model response.
411
- */
412
- type EmbeddingModelCallEndEvent = {
413
- /** Unique identifier for this embed call, used to correlate events. */
414
- readonly callId: string;
415
- /** Unique identifier for this individual doEmbed invocation, used to correlate start/finish within parallel chunks. */
416
- readonly embedCallId: string;
417
- /** Identifies the inner operation (e.g. 'ai.embed.doEmbed' or 'ai.embedMany.doEmbed'). */
418
- readonly operationId: string;
419
- /** The provider identifier. */
420
- readonly provider: string;
421
- /** The specific model identifier. */
422
- readonly modelId: string;
423
- /** The values that were embedded in this particular model call. */
424
- readonly values: Array<string>;
425
- /** The resulting embeddings from the model call. */
426
- readonly embeddings: Array<Embedding>;
427
- /** Token usage for this model call. */
428
- readonly usage: EmbeddingModelUsage;
429
- };
430
- //#endregion
431
- //#region src/util/download/download.d.ts
432
- /**
433
- * Download a file from a URL.
434
- *
435
- * @param url - The URL to download from.
436
- * @param maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.
437
- * @param abortSignal - An optional abort signal to cancel the download.
438
- * @param fetch - An optional fetch transport.
439
- * @returns The downloaded data and media type.
440
- *
441
- * @throws DownloadError if the download fails or exceeds maxBytes.
442
- */
443
- declare const download$1: ({ url, maxBytes, abortSignal, fetch }: {
444
- url: URL;
445
- maxBytes?: number;
446
- abortSignal?: AbortSignal;
447
- fetch?: FetchFunction;
448
- }) => Promise<{
449
- data: Uint8Array<ArrayBufferLike>;
450
- mediaType: string | undefined;
451
- }>;
452
- //#endregion
453
- //#region src/util/download/download-function.d.ts
454
- /**
455
- * Experimental. Can change in patch versions without warning.
456
- *
457
- * Download function. Called with the array of URLs and a boolean indicating
458
- * whether the URL is supported by the model.
459
- *
460
- * The download function can decide for each URL:
461
- * - to return null (which means that the URL should be passed to the model)
462
- * - to download the asset and return the data (incl. retries, authentication, etc.)
463
- *
464
- * Should throw DownloadError if the download fails.
465
- *
466
- * Should return an array of objects sorted by the order of the requested downloads.
467
- * For each object, the data should be a Uint8Array if the URL was downloaded.
468
- * For each object, the mediaType should be the media type of the downloaded asset.
469
- * For each object, the data should be null if the URL should be passed through as is.
470
- */
471
- type DownloadFunction = (options: Array<{
472
- url: URL;
473
- isUrlSupportedByModel: boolean;
474
- /** Signal for cancellation and timeouts of the enclosing call. */
475
- abortSignal?: AbortSignal;
476
- }>) => PromiseLike<Array<{
477
- data: Uint8Array;
478
- mediaType: string | undefined;
479
- } | null>>;
480
- /**
481
- * Default download function.
482
- * Downloads the file if it is not supported by the model.
483
- */
484
- export declare const createDefaultDownloadFunction: (download?: typeof download$1, abortSignal?: AbortSignal) => DownloadFunction;
485
- //#endregion
486
- //#region src/decide/decision-state.d.ts
487
- /** Shared text, JSON data, or ordered multimodal parts for a decision. */
488
- type DecisionState = string | Readonly<JSONObject> | readonly DecisionStatePart[];
489
- type DecisionStatePart = TextPart | FilePart | {
490
- type: 'json';
491
- value: JSONValue;
492
- };
493
- //#endregion
494
- //#region src/decide/decision-result.d.ts
495
- type DecisionAnswer<QUESTION extends Experimental_DecisionModelV4Question> = QUESTION extends {
496
- type: 'choice';
497
- criteria: infer CRITERIA;
498
- } ? {
499
- type: 'choice';
500
- choice: Extract<keyof CRITERIA, string>;
501
- probabilities?: Record<Extract<keyof CRITERIA, string>, number>;
502
- } : QUESTION extends {
503
- type: 'score';
504
- } ? {
505
- type: 'score';
506
- score: number;
507
- probabilities?: Record<string, number>;
508
- } : QUESTION extends {
509
- type: 'box';
510
- } ? {
511
- type: 'box';
512
- box: {
513
- top: number;
514
- bottom: number;
515
- left: number;
516
- right: number;
517
- };
518
- } : {
519
- type: 'boolean';
520
- probability: number;
521
- };
522
- type DecisionResult<QUESTIONS extends Record<string, Experimental_DecisionModelV4Question>> = {
523
- readonly answers: { [ID in keyof QUESTIONS]: DecisionAnswer<QUESTIONS[ID]>; };
524
- readonly usage: {
525
- inputTokens: number | undefined;
526
- outputTokens: number | undefined;
527
- totalTokens: number | undefined;
528
- };
529
- readonly warnings: Experimental_DecisionModelV4Result['warnings'];
530
- readonly rounding: Experimental_DecisionModelV4Result['rounding'];
531
- readonly providerMetadata: Experimental_DecisionModelV4Result['providerMetadata'];
532
- readonly response: NonNullable<Experimental_DecisionModelV4Result['response']> & {
533
- timestamp: Date;
534
- modelId: string;
535
- };
536
- };
537
- //#endregion
538
- //#region src/decide/decide-events.d.ts
539
- /**
540
- * Event passed to the `onStart` callback for decision operations.
541
- *
542
- * Called when the operation begins, before the decision model is called.
543
- */
544
- type DecideStartEvent<RUNTIME_CONTEXT extends Context = Context> = {
545
- /** User-defined runtime context. */
546
- readonly runtimeContext: RUNTIME_CONTEXT;
547
- /** Unique identifier for this decision call, used to correlate events. */
548
- readonly callId: string;
549
- /** Identifies the operation type (`ai.decide`). */
550
- readonly operationId: 'ai.decide';
551
- /** The provider identifier. */
552
- readonly provider: string;
553
- /** The decision model identifier. */
554
- readonly modelId: string;
555
- /** The shared state used to make decisions. */
556
- readonly state: DecisionState;
557
- /** The questions to decide against the shared state. */
558
- readonly questions: Readonly<Record<string, Experimental_DecisionModelV4Question>>;
559
- /** Maximum output tokens requested for the decision. */
560
- readonly maxOutputTokens?: number;
561
- /** Reasoning effort requested for the decision. */
562
- readonly reasoning?: Experimental_DecisionModelV4CallOptions['reasoning'];
563
- /** Maximum number of retries for the decision model call. */
564
- readonly maxRetries: number;
565
- /** Additional HTTP headers sent with the request. */
566
- readonly headers: Record<string, string> | undefined;
567
- /** Additional provider-specific options. */
568
- readonly providerOptions: ProviderOptions;
569
- };
570
- /**
571
- * Event passed to the `onEnd` callback for decision operations.
572
- *
573
- * Called when the operation completes successfully.
574
- */
575
- type DecideEndEvent<RUNTIME_CONTEXT extends Context = Context> = DecideStartEvent<RUNTIME_CONTEXT> & {
576
- /** Exactly one typed answer per question ID. */
577
- readonly answers: DecisionResult<Record<string, Experimental_DecisionModelV4Question>>['answers'];
578
- /** Token usage for the decision operation. */
579
- readonly usage: DecisionResult<Record<string, Experimental_DecisionModelV4Question>>['usage'];
580
- /** Warnings from the decision model. */
581
- readonly warnings: DecisionResult<Record<string, Experimental_DecisionModelV4Question>>['warnings'];
582
- /** Provider-declared decimal precision for probabilities and scores. */
583
- readonly rounding: DecisionResult<Record<string, Experimental_DecisionModelV4Question>>['rounding'];
584
- /** Optional provider-specific metadata. */
585
- readonly providerMetadata: DecisionResult<Record<string, Experimental_DecisionModelV4Question>>['providerMetadata'];
586
- /** Response metadata, including the resolved model ID and timestamp. */
587
- readonly response: DecisionResult<Record<string, Experimental_DecisionModelV4Question>>['response'];
588
- };
589
- /**
590
- * Event fired when the decision model call begins.
591
- *
592
- * The logical model call includes any provider retries.
593
- */
594
- type DecisionModelCallStartEvent = {
595
- /** Unique identifier for the outer decision call. */
596
- readonly callId: string;
597
- /** Identifies the inner operation (`ai.decide.doDecide`). */
598
- readonly operationId: 'ai.decide.doDecide';
599
- /** The provider identifier. */
600
- readonly provider: string;
601
- /** The decision model identifier. */
602
- readonly modelId: string;
603
- /** The shared state used to make decisions. */
604
- readonly state: Experimental_DecisionModelV4CallOptions['state'];
605
- /** The questions to decide against the shared state. */
606
- readonly questions: Experimental_DecisionModelV4CallOptions['questions'];
607
- };
608
- /**
609
- * Event fired after the decision model response has been validated.
610
- *
611
- * Contains the result of the logical model call, including any retries.
612
- */
613
- type DecisionModelCallEndEvent = DecisionModelCallStartEvent & {
614
- /** Exactly one answer per question ID. */
615
- readonly answers: Experimental_DecisionModelV4Result['answers'];
616
- /** Token usage reported by the decision model. */
617
- readonly usage?: Experimental_DecisionModelV4Result['usage'];
618
- /** Warnings from the decision model. */
619
- readonly warnings: Experimental_DecisionModelV4Result['warnings'];
620
- /** Provider-declared decimal precision for probabilities and scores. */
621
- readonly rounding?: Experimental_DecisionModelV4Result['rounding'];
622
- /** Optional provider-specific metadata. */
623
- readonly providerMetadata?: Experimental_DecisionModelV4Result['providerMetadata'];
624
- /** Optional raw response metadata from the provider. */
625
- readonly response?: Experimental_DecisionModelV4Result['response'];
626
- };
627
- //#endregion
628
- //#region src/prompt/language-model-call-options.d.ts
629
- /**
630
- * Model-facing generation controls. These settings influence how the model
631
- * generates its response (token limits, sampling, penalties, stop sequences,
632
- * seed, reasoning).
633
- */
634
- type LanguageModelCallOptions = {
635
- /**
636
- * Maximum number of tokens to generate.
637
- */
638
- maxOutputTokens?: number;
639
- /**
640
- * Temperature setting. The range depends on the provider and model.
641
- *
642
- * It is recommended to set either `temperature` or `topP`, but not both.
643
- */
644
- temperature?: number;
645
- /**
646
- * Nucleus sampling. This is a number between 0 and 1.
647
- *
648
- * E.g. 0.1 would mean that only tokens with the top 10% probability mass
649
- * are considered.
650
- *
651
- * It is recommended to set either `temperature` or `topP`, but not both.
652
- */
653
- topP?: number;
654
- /**
655
- * Only sample from the top K options for each subsequent token.
656
- *
657
- * Used to remove "long tail" low probability responses.
658
- * Recommended for advanced use cases only. You usually only need to use temperature.
659
- */
660
- topK?: number;
661
- /**
662
- * Presence penalty setting. It affects the likelihood of the model to
663
- * repeat information that is already in the prompt.
664
- *
665
- * The presence penalty is a number between -1 (increase repetition)
666
- * and 1 (maximum penalty, decrease repetition). 0 means no penalty.
667
- */
668
- presencePenalty?: number;
669
- /**
670
- * Frequency penalty setting. It affects the likelihood of the model
671
- * to repeatedly use the same words or phrases.
672
- *
673
- * The frequency penalty is a number between -1 (increase repetition)
674
- * and 1 (maximum penalty, decrease repetition). 0 means no penalty.
675
- */
676
- frequencyPenalty?: number;
677
- /**
678
- * Stop sequences.
679
- * If set, the model will stop generating text when one of the stop sequences is generated.
680
- * Providers may have limits on the number of stop sequences.
681
- */
682
- stopSequences?: string[];
683
- /**
684
- * The seed (integer) to use for random sampling. If set and supported
685
- * by the model, calls will generate deterministic results.
686
- */
687
- seed?: number;
688
- /**
689
- * Reasoning effort level for the model. Controls how much reasoning
690
- * the model performs before generating a response.
691
- *
692
- * Use `'provider-default'` to use the provider's default reasoning level.
693
- * Use `'none'` to disable reasoning (if supported by the provider).
694
- */
695
- reasoning?: LanguageModelV4CallOptions['reasoning'];
696
- };
697
- //#endregion
698
- //#region src/prompt/request-options.d.ts
699
- /**
700
- * Timeout configuration for API calls. Can be specified as:
701
- * - A number representing milliseconds
702
- * - An object with `totalMs` property for the total timeout in milliseconds
703
- * - An object with `stepMs` property for the timeout of each complete step, including model generation, retries, and local tool execution, in milliseconds
704
- * - An object with `firstChunkMs` property for the timeout until the first content chunk of each step (streaming only)
705
- * - An object with `chunkMs` property for the timeout between meaningful model output chunks, starting with the first output and ending when the model response ends (streaming only)
706
- * - An object with `toolMs` property for the default timeout for all tool executions
707
- * - An object with `tools` property for per-tool timeout overrides using `{toolName}Ms` keys
708
- */
709
- type TimeoutConfiguration<TOOLS extends ToolSet> = number | {
710
- totalMs?: number;
711
- stepMs?: number;
712
- firstChunkMs?: number;
713
- chunkMs?: number;
714
- toolMs?: number;
715
- tools?: Partial<Record<`${keyof TOOLS & string}Ms`, number>>;
716
- };
717
- //#endregion
718
- //#region src/prompt/prompt.d.ts
719
- /**
720
- * Instructions to include in the prompt. Can be used with `prompt` or `messages`.
721
- */
722
- type Instructions = string | SystemModelMessage | Array<SystemModelMessage>;
723
- /**
724
- * Prompt part of the AI function options.
725
- * It contains instructions, a simple text prompt, or a list of messages.
726
- */
727
- type Prompt = {
728
- /**
729
- * Instructions to include in the prompt. Can be used with `prompt` or `messages`.
730
- */
731
- instructions?: Instructions;
732
- /**
733
- * Instructions to include in the prompt. Can be used with `prompt` or `messages`.
734
- *
735
- * @deprecated Use `instructions` instead.
736
- */
737
- system?: Instructions;
738
- /**
739
- * Whether system messages are allowed in the `prompt` or `messages` fields.
740
- *
741
- * When disabled, system messages must be provided through the `instructions`
742
- * option.
743
- *
744
- * @default false
745
- */
746
- allowSystemInMessages?: boolean;
747
- } & ({
748
- /**
749
- * A prompt. It can be either a text prompt or a list of messages.
750
- *
751
- * You can either use `prompt` or `messages` but not both.
752
- */
753
- prompt: string | Array<ModelMessage>;
754
- /**
755
- * A list of messages.
756
- *
757
- * You can either use `prompt` or `messages` but not both.
758
- */
759
- messages?: never;
760
- } | {
761
- /**
762
- * A list of messages.
763
- *
764
- * You can either use `prompt` or `messages` but not both.
765
- */
766
- messages: Array<ModelMessage>;
767
- /**
768
- * A prompt. It can be either a text prompt or a list of messages.
769
- *
770
- * You can either use `prompt` or `messages` but not both.
771
- */
772
- prompt?: never;
773
- });
774
- //#endregion
775
- //#region src/generate-object/structured-output-events.d.ts
776
- /**
777
- * Event passed to the `onStart` callback of
778
- * `generateObject` and `streamObject`.
779
- *
780
- * Called when the operation begins, before any LLM call.
781
- *
782
- * @deprecated
783
- */
784
- interface GenerateObjectStartEvent {
785
- /** Unique identifier for this generation call, used to correlate events. */
786
- readonly callId: string;
787
- /** Identifies the operation type (e.g. `'ai.generateObject'` or `'ai.streamObject'`). */
788
- readonly operationId: string;
789
- /** The provider identifier (e.g., 'openai', 'anthropic'). */
790
- readonly provider: string;
791
- /** The specific model identifier (e.g., 'gpt-4o'). */
792
- readonly modelId: string;
793
- /** The system message(s) provided to the model. */
794
- readonly system: Instructions | undefined;
795
- /** The prompt string or array of messages if using the prompt option. */
796
- readonly prompt: string | Array<ModelMessage> | undefined;
797
- /** The messages array if using the messages option. */
798
- readonly messages: Array<ModelMessage> | undefined;
799
- /** Maximum number of tokens to generate. */
800
- readonly maxOutputTokens: number | undefined;
801
- /** Sampling temperature for generation. */
802
- readonly temperature: number | undefined;
803
- /** Top-p (nucleus) sampling parameter. */
804
- readonly topP: number | undefined;
805
- /** Top-k sampling parameter. */
806
- readonly topK: number | undefined;
807
- /** Presence penalty for generation. */
808
- readonly presencePenalty: number | undefined;
809
- /** Frequency penalty for generation. */
810
- readonly frequencyPenalty: number | undefined;
811
- /** Random seed for reproducible generation. */
812
- readonly seed: number | undefined;
813
- /** Maximum number of retries for failed requests. */
814
- readonly maxRetries: number;
815
- /** Additional HTTP headers sent with the request. */
816
- readonly headers: Record<string, string | undefined> | undefined;
817
- /** Additional provider-specific options. */
818
- readonly providerOptions: ProviderOptions | undefined;
819
- /** The output strategy type. */
820
- readonly output: 'object' | 'array' | 'enum' | 'no-schema';
821
- /** The JSON Schema used for object generation, if any. */
822
- readonly schema: Record<string, unknown> | undefined;
823
- /** Optional name of the schema. */
824
- readonly schemaName: string | undefined;
825
- /** Optional description of the schema. */
826
- readonly schemaDescription: string | undefined;
827
- }
828
- /**
829
- * Event passed to the `onStepStart` callback of
830
- * `generateObject` and `streamObject`.
831
- *
832
- * Called when the model call (step) begins, before the provider is called.
833
- * For object generation, there is always exactly one step (step 0).
834
- *
835
- * @deprecated
836
- */
837
- interface GenerateObjectStepStartEvent {
838
- /** Unique identifier for this generation call, used to correlate events. */
839
- readonly callId: string;
840
- /** Zero-based index of the current step. Always `0` for object generation. */
841
- readonly stepNumber: 0;
842
- /** The provider identifier (e.g., 'openai', 'anthropic'). */
843
- readonly provider: string;
844
- /** The specific model identifier (e.g., 'gpt-4o'). */
845
- readonly modelId: string;
846
- /** Additional provider-specific options. */
847
- readonly providerOptions: ProviderOptions | undefined;
848
- /** Additional HTTP headers sent with the request. */
849
- readonly headers: Record<string, string | undefined> | undefined;
850
- /** The prompt messages in provider format (for telemetry). */
851
- readonly promptMessages?: LanguageModelV4Prompt;
852
- }
853
- /**
854
- * Event passed to the `onStepEnd` callback of
855
- * `generateObject` and `streamObject`.
856
- *
857
- * Called when the model call (step) completes, with the raw result
858
- * before JSON parsing and schema validation.
859
- *
860
- * @deprecated
861
- */
862
- interface GenerateObjectStepEndEvent {
863
- /** Unique identifier for this generation call, used to correlate events. */
864
- readonly callId: string;
865
- /** Zero-based index of the current step. Always `0` for object generation. */
866
- readonly stepNumber: 0;
867
- /** The provider identifier (e.g., 'openai', 'anthropic'). */
868
- readonly provider: string;
869
- /** The specific model identifier (e.g., 'gpt-4o'). */
870
- readonly modelId: string;
871
- /** The unified reason why the generation finished. */
872
- readonly finishReason: FinishReason;
873
- /** The token usage of the generated response. */
874
- readonly usage: LanguageModelUsage;
875
- /** The raw text output from the model (before JSON parsing). */
876
- readonly objectText: string;
877
- /** The reasoning generated by the model, if any. */
878
- readonly reasoning: string | undefined;
879
- /** Warnings from the model provider (e.g. unsupported settings). */
880
- readonly warnings: CallWarning[] | undefined;
881
- /** Additional request information. */
882
- readonly request: Omit<LanguageModelRequestMetadata, 'messages'>;
883
- /** Additional response information. */
884
- readonly response: Omit<LanguageModelResponseMetadata, 'messages'>;
885
- /** Additional provider-specific metadata. */
886
- readonly providerMetadata: ProviderMetadata | undefined;
887
- /** Milliseconds from the start of the stream to the first chunk (streaming only). */
888
- readonly msToFirstChunk: number | undefined;
889
- }
890
- /**
891
- * Event passed to the `onFinish` callback of
892
- * `generateObject` and `streamObject`.
893
- *
894
- * Called when the entire operation completes, including JSON parsing
895
- * and schema validation. For `streamObject`, the object may be undefined
896
- * if validation failed (the error is provided in that case).
897
- *
898
- * @deprecated
899
- */
900
- interface GenerateObjectEndEvent<RESULT> {
901
- /** Unique identifier for this generation call, used to correlate events. */
902
- readonly callId: string;
903
- /**
904
- * The generated object (typed according to the schema).
905
- * Always defined for `generateObject`. May be `undefined` for `streamObject`
906
- * when parsing or validation fails.
907
- */
908
- readonly object: RESULT | undefined;
909
- /**
910
- * Error from parsing or schema validation, if any.
911
- * Always `undefined` for `generateObject` (which throws instead).
912
- */
913
- readonly error: unknown | undefined;
914
- /** The reasoning generated by the model, if any. */
915
- readonly reasoning: string | undefined;
916
- /** The unified reason why the generation finished. */
917
- readonly finishReason: FinishReason;
918
- /** The token usage of the generated response. */
919
- readonly usage: LanguageModelUsage;
920
- /** Warnings from the model provider (e.g. unsupported settings). */
921
- readonly warnings: CallWarning[] | undefined;
922
- /** Additional request information. */
923
- readonly request: Omit<LanguageModelRequestMetadata, 'messages'>;
924
- /** Additional response information. */
925
- readonly response: Omit<LanguageModelResponseMetadata, 'messages'>;
926
- /** Additional provider-specific metadata. */
927
- readonly providerMetadata: ProviderMetadata | undefined;
928
- }
929
- //#endregion
930
- //#region src/prompt/standardize-prompt.d.ts
931
- type StandardizedPrompt = {
932
- /**
933
- * Instructions.
934
- */
935
- instructions: Instructions | undefined;
936
- /**
937
- * Messages.
938
- */
939
- messages: ModelMessage[];
940
- };
941
- /**
942
- * Converts a prompt input into a standardized prompt with model messages.
943
- *
944
- * @param prompt - The prompt definition to standardize.
945
- * Set `allowSystemInMessages` to true to allow system messages in the
946
- * `prompt` or `messages` fields. System messages in the `instructions`
947
- * option are always allowed.
948
- * @returns The standardized prompt.
949
- * @throws {InvalidPromptError} When the prompt is invalid.
950
- */
951
- export declare function standardizePrompt({ allowSystemInMessages, system, instructions, prompt, messages }: Prompt): Promise<StandardizedPrompt>;
952
- //#endregion
953
- //#region src/util/callback.d.ts
954
- /**
955
- * A callback function that can be used with `notify`.
956
- */
957
- type Callback<EVENT> = (event: EVENT) => PromiseLike<void> | void;
958
- //#endregion
959
- //#region src/generate-text/active-tools.d.ts
960
- /**
961
- * Tool names that are enabled for a generation step.
962
- *
963
- * `undefined` means no tool restriction is applied. Tool names are object keys
964
- * at runtime, so the type is restricted to the string keys of the configured
965
- * tool set.
966
- */
967
- type ActiveTools<TOOLS extends ToolSet> = ReadonlyArray<keyof TOOLS & string> | undefined;
968
- //#endregion
969
- //#region src/telemetry/telemetry-options.d.ts
970
- type IncludedContext<CONTEXT extends Context | unknown | never> = { [KEY in keyof NoInfer<CONTEXT>]?: boolean; } | undefined;
971
- type IncludedToolsContext<TOOLS extends ToolSet> = { [TOOL_NAME in keyof NoInfer<InferToolSetContext<TOOLS>>]?: IncludedContext<NoInfer<InferToolSetContext<TOOLS>[TOOL_NAME]>>; } | undefined;
972
- /**
973
- * Telemetry configuration.
974
- */
975
- type TelemetryOptions<RUNTIME_CONTEXT extends Context = Context, TOOLS extends ToolSet = ToolSet> = {
976
- /**
977
- * Enable or disable telemetry. Enabled by default when a telemetry
978
- * integration is registered. Set to `false` to opt out.
979
- */
980
- isEnabled?: boolean;
981
- /**
982
- * Enable or disable input recording. Enabled by default.
983
- *
984
- * You might want to disable input recording to avoid recording sensitive
985
- * information, to reduce data transfers, or to increase performance.
986
- */
987
- recordInputs?: boolean;
988
- /**
989
- * Enable or disable output recording. Enabled by default.
990
- *
991
- * You might want to disable output recording to avoid recording sensitive
992
- * information, to reduce data transfers, or to increase performance.
993
- */
994
- recordOutputs?: boolean;
995
- /**
996
- * Identifier for this function. Used to group telemetry data by function.
997
- */
998
- functionId?: string;
999
- /**
1000
- * Top-level runtime context properties that should be included in telemetry.
1001
- * Runtime context properties are excluded unless they are explicitly set to `true`.
1002
- */
1003
- includeRuntimeContext?: IncludedContext<RUNTIME_CONTEXT>;
1004
- /**
1005
- * Top-level tool context properties that should be included in telemetry,
1006
- * configured per tool.
1007
- *
1008
- * Tool context properties are excluded unless they are explicitly set to `true`.
1009
- */
1010
- includeToolsContext?: IncludedToolsContext<TOOLS>;
1011
- /**
1012
- * Per-call telemetry integrations that receive lifecycle events during generation.
1013
- *
1014
- * When provided, these integrations will take precedence over the globally registered
1015
- * integrations for this call.
1016
- */
1017
- integrations?: Arrayable<Telemetry>;
1018
- };
1019
- //#endregion
1020
- //#region src/generate-text/generated-file.d.ts
1021
- /**
1022
- * A generated file.
1023
- */
1024
- interface GeneratedFile {
1025
- /**
1026
- * File as a base64 encoded string.
1027
- */
1028
- readonly base64: string;
1029
- /**
1030
- * File as a Uint8Array.
1031
- */
1032
- readonly uint8Array: Uint8Array;
1033
- /**
1034
- * The IANA media type of the file.
1035
- *
1036
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
1037
- */
1038
- readonly mediaType: string;
1039
- /**
1040
- * Provider-specific metadata for this file.
1041
- */
1042
- readonly providerMetadata?: Record<string, JSONObject>;
1043
- }
1044
- //#endregion
1045
- //#region src/generate-text/reasoning-output.d.ts
1046
- /**
1047
- * Reasoning output of a text generation. It contains a reasoning.
1048
- */
1049
- interface ReasoningOutput {
1050
- type: 'reasoning';
1051
- /**
1052
- * The reasoning text.
1053
- */
1054
- text: string;
1055
- /**
1056
- * Additional provider-specific metadata. They are passed through
1057
- * to the provider from the AI SDK and enable provider-specific
1058
- * functionality that can be fully encapsulated in the provider.
1059
- */
1060
- providerMetadata?: ProviderMetadata;
1061
- }
1062
- /**
1063
- * Reasoning file output of a text generation.
1064
- * It contains a file generated as part of reasoning.
1065
- */
1066
- interface ReasoningFileOutput {
1067
- type: 'reasoning-file';
1068
- /**
1069
- * The generated file.
1070
- */
1071
- file: GeneratedFile;
1072
- /**
1073
- * Additional provider-specific metadata. They are passed through
1074
- * to the provider from the AI SDK and enable provider-specific
1075
- * functionality that can be fully encapsulated in the provider.
1076
- */
1077
- providerMetadata?: ProviderMetadata;
1078
- }
1079
- //#endregion
1080
- //#region src/util/value-of.d.ts
1081
- /**
1082
- * Create a union of the given object's values, and optionally specify which keys to get the values from.
1083
- *
1084
- * Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31438) if you want to have this type as a built-in in TypeScript.
1085
- *
1086
- * @example
1087
- * ```
1088
- * // data.json
1089
- * {
1090
- * 'foo': 1,
1091
- * 'bar': 2,
1092
- * 'biz': 3
1093
- * }
1094
- *
1095
- * // main.ts
1096
- * import type {ValueOf} from 'type-fest';
1097
- * import data = require('./data.json');
1098
- *
1099
- * export function getData(name: string): ValueOf<typeof data> {
1100
- * return data[name];
1101
- * }
1102
- *
1103
- * export function onlyBar(name: string): ValueOf<typeof data, 'bar'> {
1104
- * return data[name];
1105
- * }
1106
- *
1107
- * // file.ts
1108
- * import {getData, onlyBar} from './main';
1109
- *
1110
- * getData('foo');
1111
- * //=> 1
1112
- *
1113
- * onlyBar('foo');
1114
- * //=> TypeError ...
1115
- *
1116
- * onlyBar('bar');
1117
- * //=> 2
1118
- * ```
1119
- * @see https://github.com/sindresorhus/type-fest/blob/main/source/value-of.d.ts
1120
- */
1121
- type ValueOf<ObjectType, ValueType extends keyof ObjectType = keyof ObjectType> = ObjectType[ValueType];
1122
- //#endregion
1123
- //#region src/generate-text/tool-call.d.ts
1124
- type BaseToolCall = {
1125
- type: 'tool-call';
1126
- toolCallId: string;
1127
- providerExecuted?: boolean;
1128
- providerMetadata?: ProviderMetadata;
1129
- toolMetadata?: JSONObject;
1130
- };
1131
- /**
1132
- * A tool call whose `toolName` maps to a tool in the declared tool set,
1133
- * with an `input` type inferred from that tool's input schema.
1134
- */
1135
- type StaticToolCall<TOOLS extends ToolSet> = ValueOf<{ [NAME in keyof TOOLS]-?: BaseToolCall & {
1136
- toolName: NAME & string;
1137
- input: InferToolInput<TOOLS[NAME]>;
1138
- dynamic?: false | undefined;
1139
- invalid?: false | undefined;
1140
- error?: never;
1141
- title?: string;
1142
- }; }>;
1143
- /**
1144
- * A tool call whose `toolName` is only known at runtime, such as an invalid
1145
- * or otherwise untyped call that cannot be matched to the declared tool set.
1146
- */
1147
- type DynamicToolCall = BaseToolCall & {
1148
- toolName: string;
1149
- input: unknown;
1150
- dynamic: true;
1151
- title?: string;
1152
- /**
1153
- * True if this is caused by an unparsable tool call or
1154
- * a tool that does not exist.
1155
- */
1156
- invalid?: boolean;
1157
- /**
1158
- * The error that caused the tool call to be invalid.
1159
- */
1160
- error?: unknown;
1161
- };
1162
- /**
1163
- * A tool call returned by text generation, either statically typed from the
1164
- * declared tool set or dynamically typed when the tool cannot be inferred.
1165
- */
1166
- type TypedToolCall<TOOLS extends ToolSet> = StaticToolCall<TOOLS> | DynamicToolCall;
1167
- //#endregion
1168
- //#region src/generate-text/tool-approval-request-output.d.ts
1169
- /**
1170
- * Output part that indicates that a tool approval request has been made.
1171
- *
1172
- * The tool approval request can be approved or denied in the next tool message.
1173
- */
1174
- type ToolApprovalRequestOutput<TOOLS extends ToolSet> = {
1175
- type: 'tool-approval-request';
1176
- /**
1177
- * ID of the tool approval request.
1178
- */
1179
- approvalId: string;
1180
- /**
1181
- * Tool call that the approval request is for.
1182
- */
1183
- toolCall: TypedToolCall<TOOLS>;
1184
- /**
1185
- * Reason why the tool call requires approval.
1186
- */
1187
- reason?: string;
1188
- /**
1189
- * Flag indicating whether the tool was automatically approved or denied.
1190
- *
1191
- * @default false
1192
- */
1193
- isAutomatic?: boolean;
1194
- /**
1195
- * HMAC-SHA256 signature binding this approval request to its tool call.
1196
- */
1197
- signature?: string;
1198
- };
1199
- //#endregion
1200
- //#region src/generate-text/tool-approval-response-output.d.ts
1201
- /**
1202
- * Output part that indicates that a tool approval response is available.
1203
- */
1204
- type ToolApprovalResponseOutput<TOOLS extends ToolSet> = {
1205
- type: 'tool-approval-response';
1206
- /**
1207
- * ID of the tool approval.
1208
- */
1209
- approvalId: string;
1210
- /**
1211
- * Tool call that the approval response is for.
1212
- */
1213
- toolCall: TypedToolCall<TOOLS>;
1214
- /**
1215
- * Flag indicating whether the approval was granted or denied.
1216
- */
1217
- approved: boolean;
1218
- /**
1219
- * Optional reason for the approval or denial.
1220
- */
1221
- reason?: string;
1222
- /**
1223
- * Flag indicating whether the tool call is provider-executed.
1224
- * Only provider-executed tool approval responses should be sent to the model.
1225
- */
1226
- providerExecuted?: boolean;
1227
- };
1228
- //#endregion
1229
- //#region src/generate-text/tool-error.d.ts
1230
- type StaticToolError<TOOLS extends ToolSet> = ValueOf<{ [NAME in keyof TOOLS]-?: {
1231
- type: 'tool-error';
1232
- toolCallId: string;
1233
- toolName: NAME & string;
1234
- input: InferToolInput<TOOLS[NAME]>;
1235
- error: unknown;
1236
- providerExecuted?: boolean;
1237
- providerMetadata?: ProviderMetadata;
1238
- toolMetadata?: JSONObject;
1239
- dynamic?: false | undefined;
1240
- title?: string;
1241
- }; }>;
1242
- type DynamicToolError = {
1243
- type: 'tool-error';
1244
- toolCallId: string;
1245
- toolName: string;
1246
- input: unknown;
1247
- error: unknown;
1248
- providerExecuted?: boolean;
1249
- providerMetadata?: ProviderMetadata;
1250
- toolMetadata?: JSONObject;
1251
- dynamic: true;
1252
- title?: string;
1253
- };
1254
- type TypedToolError<TOOLS extends ToolSet> = StaticToolError<TOOLS> | DynamicToolError;
1255
- //#endregion
1256
- //#region src/generate-text/tool-result.d.ts
1257
- type StaticToolResult<TOOLS extends ToolSet> = ValueOf<{ [NAME in keyof TOOLS]-?: {
1258
- type: 'tool-result';
1259
- toolCallId: string;
1260
- toolName: NAME & string;
1261
- input: InferToolInput<TOOLS[NAME]>;
1262
- output: InferToolOutput<TOOLS[NAME]>;
1263
- providerExecuted?: boolean;
1264
- providerMetadata?: ProviderMetadata;
1265
- toolMetadata?: JSONObject;
1266
- dynamic?: false | undefined;
1267
- preliminary?: boolean;
1268
- title?: string;
1269
- }; }>;
1270
- type DynamicToolResult = {
1271
- type: 'tool-result';
1272
- toolCallId: string;
1273
- toolName: string;
1274
- input: unknown;
1275
- output: unknown;
1276
- providerExecuted?: boolean;
1277
- providerMetadata?: ProviderMetadata;
1278
- toolMetadata?: JSONObject;
1279
- dynamic: true;
1280
- preliminary?: boolean;
1281
- title?: string;
1282
- };
1283
- type TypedToolResult<TOOLS extends ToolSet> = StaticToolResult<TOOLS> | DynamicToolResult;
1284
- //#endregion
1285
- //#region src/generate-text/content-part.d.ts
1286
- type ContentPart<TOOLS extends ToolSet> = {
1287
- type: 'text';
1288
- text: string;
1289
- citations?: Array<Citation>;
1290
- providerMetadata?: ProviderMetadata;
1291
- } | {
1292
- type: 'custom';
1293
- kind: `${string}.${string}`;
1294
- providerMetadata?: ProviderMetadata;
1295
- } | ReasoningOutput | ReasoningFileOutput | ({
1296
- type: 'source';
1297
- } & Source) | {
1298
- type: 'file';
1299
- file: GeneratedFile;
1300
- providerMetadata?: ProviderMetadata;
1301
- } | ({
1302
- type: 'tool-call';
1303
- } & TypedToolCall<TOOLS> & {
1304
- providerMetadata?: ProviderMetadata;
1305
- }) | ({
1306
- type: 'tool-result';
1307
- } & TypedToolResult<TOOLS> & {
1308
- providerMetadata?: ProviderMetadata;
1309
- }) | ({
1310
- type: 'tool-error';
1311
- } & TypedToolError<TOOLS> & {
1312
- providerMetadata?: ProviderMetadata;
1313
- }) | ToolApprovalRequestOutput<TOOLS> | ToolApprovalResponseOutput<TOOLS>;
1314
- //#endregion
1315
- //#region src/generate-text/step-result.d.ts
1316
- /**
1317
- * Timing statistics for the gaps between generated output chunks.
1318
- */
1319
- type OutputChunkTimingStats = {
1320
- /** Shortest observed time between output chunks in milliseconds. */
1321
- readonly min: number;
1322
- /** 10th percentile time between output chunks in milliseconds. */
1323
- readonly p10: number;
1324
- /** Median time between output chunks in milliseconds. */
1325
- readonly median: number;
1326
- /** Average time between output chunks in milliseconds. */
1327
- readonly avg: number;
1328
- /** 90th percentile time between output chunks in milliseconds. */
1329
- readonly p90: number;
1330
- /** Longest observed time between output chunks in milliseconds. */
1331
- readonly max: number;
1332
- };
1333
- /**
1334
- * Performance metrics for a single step in the generation process.
1335
- */
1336
- type StepResultPerformance = {
1337
- /**
1338
- * Effective number of output tokens per second over the full language model
1339
- * response.
1340
- *
1341
- * Calculated as `outputTokens / requestSeconds`.
1342
- */
1343
- readonly effectiveOutputTokensPerSecond: number;
1344
- /**
1345
- * Number of output tokens per second after the first generated output chunk
1346
- * was received.
1347
- *
1348
- * Only available for streaming steps.
1349
- *
1350
- * Calculated as `outputTokens / outputStreamSeconds`.
1351
- */
1352
- readonly outputTokensPerSecond: number | undefined;
1353
- /**
1354
- * Number of input tokens processed per second before the first generated
1355
- * output chunk was received.
1356
- *
1357
- * Only available for streaming steps.
1358
- *
1359
- * Calculated as `inputTokens / ttftSeconds`.
1360
- */
1361
- readonly inputTokensPerSecond: number | undefined;
1362
- /**
1363
- * Effective number of input and output tokens per second over the full
1364
- * language model response.
1365
- *
1366
- * Calculated as `(inputTokens + outputTokens) / requestSeconds`.
1367
- */
1368
- readonly effectiveTotalTokensPerSecond: number;
1369
- /**
1370
- * Total time spent on the step in milliseconds.
1371
- */
1372
- readonly stepTimeMs: number;
1373
- /**
1374
- * Time spent waiting for the language model response in milliseconds.
1375
- */
1376
- readonly responseTimeMs: number;
1377
- /**
1378
- * Time spent executing each client-side tool call in milliseconds, keyed by
1379
- * tool call ID.
1380
- */
1381
- readonly toolExecutionMs: Readonly<Record<string, number>>;
1382
- /**
1383
- * Time until the first generated output chunk was received in milliseconds.
1384
- *
1385
- * This includes text deltas, reasoning deltas, generated files, reasoning
1386
- * files, tool input deltas, and tool calls.
1387
- *
1388
- * Only available for streaming steps.
1389
- */
1390
- readonly timeToFirstOutputMs: number | undefined;
1391
- /**
1392
- * Timing statistics for the gaps between generated output chunks in
1393
- * milliseconds.
1394
- *
1395
- * Only available for streaming steps with at least two generated output
1396
- * chunks.
1397
- */
1398
- readonly timeBetweenOutputChunksMs?: OutputChunkTimingStats;
1399
- };
1400
- /**
1401
- * The result of a single step in the generation process.
1402
- */
1403
- type StepResult<TOOLS extends ToolSet, RUNTIME_CONTEXT extends Context = Context> = {
1404
- /**
1405
- * Unique identifier for the generation call this step belongs to.
1406
- */
1407
- readonly callId: string;
1408
- /**
1409
- * Zero-based index of this step.
1410
- */
1411
- readonly stepNumber: number;
1412
- /**
1413
- * Information about the model that produced this step.
1414
- */
1415
- readonly model: {
1416
- /** The provider of the model. */
1417
- readonly provider: string;
1418
- /** The ID of the model. */
1419
- readonly modelId: string;
1420
- };
1421
- /**
1422
- * Tool context.
1423
- */
1424
- readonly toolsContext: InferToolSetContext<TOOLS>;
1425
- /**
1426
- * The runtime context that was used as input for the step.
1427
- */
1428
- readonly runtimeContext: RUNTIME_CONTEXT;
1429
- /**
1430
- * The content that was generated in the last step.
1431
- */
1432
- readonly content: Array<ContentPart<TOOLS>>;
1433
- /**
1434
- * The concatenation of all text parts generated in this step.
1435
- * It is an empty string if the step contains no text parts.
1436
- */
1437
- readonly text: string;
1438
- /**
1439
- * The reasoning that was generated during the generation.
1440
- */
1441
- readonly reasoning: Array<ReasoningPart | ReasoningFilePart>;
1442
- /**
1443
- * The reasoning text that was generated during the generation.
1444
- *
1445
- * It is a concatenation of all reasoning parts (but excluding reasoning file parts).
1446
- * Can be undefined if the model has only generated text.
1447
- */
1448
- readonly reasoningText: string | undefined;
1449
- /**
1450
- * The files that were generated during the generation.
1451
- */
1452
- readonly files: Array<GeneratedFile>;
1453
- /**
1454
- * The sources that were used to generate the text.
1455
- */
1456
- readonly sources: Array<Source>;
1457
- /**
1458
- * The tool calls that were made during the generation.
1459
- */
1460
- readonly toolCalls: Array<TypedToolCall<TOOLS>>;
1461
- /**
1462
- * The static tool calls that were made in the last step.
1463
- */
1464
- readonly staticToolCalls: Array<StaticToolCall<TOOLS>>;
1465
- /**
1466
- * The dynamic tool calls that were made in the last step.
1467
- */
1468
- readonly dynamicToolCalls: Array<DynamicToolCall>;
1469
- /**
1470
- * The results of the tool calls.
1471
- */
1472
- readonly toolResults: Array<TypedToolResult<TOOLS>>;
1473
- /**
1474
- * The static tool results that were made in the last step.
1475
- */
1476
- readonly staticToolResults: Array<StaticToolResult<TOOLS>>;
1477
- /**
1478
- * The dynamic tool results that were made in the last step.
1479
- */
1480
- readonly dynamicToolResults: Array<DynamicToolResult>;
1481
- /**
1482
- * The unified reason why the generation finished.
1483
- */
1484
- readonly finishReason: FinishReason;
1485
- /**
1486
- * The raw reason why the generation finished (from the provider).
1487
- */
1488
- readonly rawFinishReason: string | undefined;
1489
- /**
1490
- * The token usage of the generated text.
1491
- */
1492
- readonly usage: LanguageModelUsage;
1493
- /**
1494
- * Performance metrics for the step.
1495
- */
1496
- readonly performance: StepResultPerformance;
1497
- /**
1498
- * Warnings from the model provider (e.g. unsupported settings).
1499
- */
1500
- readonly warnings: CallWarning[] | undefined;
1501
- /**
1502
- * Additional request information.
1503
- */
1504
- readonly request: LanguageModelRequestMetadata;
1505
- /**
1506
- * Additional response information.
1507
- */
1508
- readonly response: LanguageModelResponseMetadata;
1509
- /**
1510
- * Additional provider-specific metadata. They are passed through
1511
- * from the provider to the AI SDK and enable provider-specific
1512
- * results that can be fully encapsulated in the provider.
1513
- */
1514
- readonly providerMetadata: ProviderMetadata | undefined;
1515
- /**
1516
- * The user messages that were sent with `experimental_steering` and added
1517
- * to the input of this step. Undefined when the step received no steering
1518
- * messages.
1519
- */
1520
- readonly experimental_steeringMessages?: Array<UserModelMessage>;
1521
- };
1522
- export declare class DefaultStepResult<TOOLS extends ToolSet, RUNTIME_CONTEXT extends Context = Context> implements StepResult<TOOLS, RUNTIME_CONTEXT> {
1523
- readonly callId: StepResult<TOOLS, RUNTIME_CONTEXT>['callId'];
1524
- readonly stepNumber: StepResult<TOOLS, RUNTIME_CONTEXT>['stepNumber'];
1525
- readonly model: StepResult<TOOLS, RUNTIME_CONTEXT>['model'];
1526
- readonly toolsContext: StepResult<TOOLS, RUNTIME_CONTEXT>['toolsContext'];
1527
- readonly runtimeContext: StepResult<TOOLS, RUNTIME_CONTEXT>['runtimeContext'];
1528
- readonly content: StepResult<TOOLS, RUNTIME_CONTEXT>['content'];
1529
- readonly finishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['finishReason'];
1530
- readonly rawFinishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['rawFinishReason'];
1531
- readonly usage: StepResult<TOOLS, RUNTIME_CONTEXT>['usage'];
1532
- readonly performance: StepResult<TOOLS, RUNTIME_CONTEXT>['performance'];
1533
- readonly warnings: StepResult<TOOLS, RUNTIME_CONTEXT>['warnings'];
1534
- readonly request: StepResult<TOOLS, RUNTIME_CONTEXT>['request'];
1535
- readonly response: StepResult<TOOLS, RUNTIME_CONTEXT>['response'];
1536
- readonly providerMetadata: StepResult<TOOLS, RUNTIME_CONTEXT>['providerMetadata'];
1537
- readonly experimental_steeringMessages?: StepResult<TOOLS, RUNTIME_CONTEXT>['experimental_steeringMessages'];
1538
- constructor({ callId, stepNumber, provider, modelId, runtimeContext, toolsContext, content, finishReason, rawFinishReason, usage, performance, warnings, request, response, providerMetadata, steeringMessages }: {
1539
- callId: StepResult<TOOLS, RUNTIME_CONTEXT>['callId'];
1540
- stepNumber: StepResult<TOOLS, RUNTIME_CONTEXT>['stepNumber'];
1541
- provider: StepResult<TOOLS, RUNTIME_CONTEXT>['model']['provider'];
1542
- modelId: StepResult<TOOLS, RUNTIME_CONTEXT>['model']['modelId'];
1543
- runtimeContext: StepResult<TOOLS, RUNTIME_CONTEXT>['runtimeContext'];
1544
- toolsContext: StepResult<TOOLS, RUNTIME_CONTEXT>['toolsContext'];
1545
- content: StepResult<TOOLS, RUNTIME_CONTEXT>['content'];
1546
- finishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['finishReason'];
1547
- rawFinishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['rawFinishReason'];
1548
- usage: StepResult<TOOLS, RUNTIME_CONTEXT>['usage'];
1549
- performance: StepResult<TOOLS, RUNTIME_CONTEXT>['performance'];
1550
- warnings: StepResult<TOOLS, RUNTIME_CONTEXT>['warnings'];
1551
- request: StepResult<TOOLS, RUNTIME_CONTEXT>['request'];
1552
- response: StepResult<TOOLS, RUNTIME_CONTEXT>['response'];
1553
- providerMetadata: StepResult<TOOLS, RUNTIME_CONTEXT>['providerMetadata'];
1554
- steeringMessages?: Array<UserModelMessage>;
1555
- });
1556
- get text(): string;
1557
- get reasoning(): Array<ReasoningPart | ReasoningFilePart>;
1558
- get reasoningText(): string | undefined;
1559
- get files(): GeneratedFile[];
1560
- get sources(): (({
1561
- type: "source";
1562
- } & {
1563
- type: "source";
1564
- sourceType: "url";
1565
- id: string;
1566
- url: string;
1567
- title?: string;
1568
- providerMetadata?: import("@ai-sdk/provider").SharedV4ProviderMetadata;
1569
- }) | ({
1570
- type: "source";
1571
- } & {
1572
- type: "source";
1573
- sourceType: "document";
1574
- id: string;
1575
- mediaType: string;
1576
- title: string;
1577
- filename?: string;
1578
- providerMetadata?: import("@ai-sdk/provider").SharedV4ProviderMetadata;
1579
- }))[];
1580
- get toolCalls(): (({
1581
- type: "tool-call";
1582
- } & {
1583
- type: "tool-call";
1584
- toolCallId: string;
1585
- providerExecuted?: boolean;
1586
- providerMetadata?: ProviderMetadata;
1587
- toolMetadata?: import("@ai-sdk/provider").JSONObject;
1588
- } & {
1589
- toolName: string;
1590
- input: unknown;
1591
- dynamic: true;
1592
- title?: string;
1593
- invalid?: boolean;
1594
- error?: unknown;
1595
- } & {
1596
- providerMetadata?: ProviderMetadata;
1597
- }) | ({
1598
- type: "tool-call";
1599
- } & StaticToolCall<TOOLS> & {
1600
- providerMetadata?: ProviderMetadata;
1601
- }))[];
1602
- get staticToolCalls(): StaticToolCall<TOOLS>[];
1603
- get dynamicToolCalls(): DynamicToolCall[];
1604
- get toolResults(): (({
1605
- type: "tool-result";
1606
- } & DynamicToolResult & {
1607
- providerMetadata?: ProviderMetadata;
1608
- }) | ({
1609
- type: "tool-result";
1610
- } & StaticToolResult<TOOLS> & {
1611
- providerMetadata?: ProviderMetadata;
1612
- }))[];
1613
- get staticToolResults(): StaticToolResult<TOOLS>[];
1614
- get dynamicToolResults(): DynamicToolResult[];
1615
- }
1616
- //#endregion
1617
- //#region src/generate-text/language-model-events.d.ts
1618
- /**
1619
- * Common model information used across callback events.
1620
- */
1621
- type ModelInfo = {
1622
- /** The provider identifier (e.g., 'openai', 'anthropic'). */
1623
- readonly provider: string;
1624
- /** The specific model identifier (e.g., 'gpt-4o'). */
1625
- readonly modelId: string;
1626
- };
1627
- /**
1628
- * Event passed to the `onLanguageModelCallStart` callback.
1629
- *
1630
- * Called immediately before the provider model call begins.
1631
- * Unlike `onStepStart`, this only represents model invocation work.
1632
- */
1633
- type LanguageModelCallStartEvent = ModelInfo & {
1634
- /** Unique identifier for this generation call, used to correlate events. */
1635
- readonly callId: string;
1636
- /** Prepared tool definitions for the model call, if any. */
1637
- readonly tools: ReadonlyArray<Record<string, unknown>> | undefined;
1638
- } & StandardizedPrompt & LanguageModelCallOptions;
1639
- /**
1640
- * Event passed to the `onLanguageModelCallEnd` callback.
1641
- *
1642
- * Called after the model response has been normalized and parsed, but before
1643
- * any client-side tool execution begins.
1644
- */
1645
- type LanguageModelCallEndEvent<TOOLS extends ToolSet = ToolSet> = ModelInfo & {
1646
- /** Unique identifier for this generation call, used to correlate events. */
1647
- readonly callId: string;
1648
- /** The unified reason why the model call finished. */
1649
- readonly finishReason: FinishReason;
1650
- /** The token usage reported by the model call. */
1651
- readonly usage: LanguageModelUsage;
1652
- /** The content parts produced by the model call. */
1653
- readonly content: ReadonlyArray<ContentPart<TOOLS>>;
1654
- /** The provider-returned response id for this model call. */
1655
- readonly responseId: string;
1656
- /** Optional provider-specific metadata for this model call. */
1657
- readonly providerMetadata?: ProviderMetadata;
1658
- /** HTTP origin reported by the provider, excluding URL credentials and path. */
1659
- readonly request?: {
1660
- readonly url?: string;
1661
- };
1662
- /** Performance metrics for the model call. */
1663
- readonly performance: {
1664
- /** Time spent waiting for the language model response in milliseconds. */
1665
- readonly responseTimeMs: number;
1666
- /**
1667
- * Effective number of output tokens per second over the full language
1668
- * model response.
1669
- */
1670
- readonly effectiveOutputTokensPerSecond: number;
1671
- /**
1672
- * Number of output tokens per second after the first generated output
1673
- * chunk was received.
1674
- *
1675
- * Only available for streaming calls.
1676
- */
1677
- readonly outputTokensPerSecond: number | undefined;
1678
- /**
1679
- * Number of input tokens processed per second before the first generated
1680
- * output chunk was received.
1681
- *
1682
- * Only available for streaming calls.
1683
- */
1684
- readonly inputTokensPerSecond: number | undefined;
1685
- /**
1686
- * Effective number of input and output tokens per second over the full
1687
- * language model response.
1688
- */
1689
- readonly effectiveTotalTokensPerSecond: number;
1690
- /**
1691
- * Time until the first generated output chunk was received in
1692
- * milliseconds.
1693
- */
1694
- readonly timeToFirstOutputMs: number | undefined;
1695
- /**
1696
- * Timing statistics for the gaps between generated output chunks in
1697
- * milliseconds.
1698
- *
1699
- * Only available for streaming calls with at least two output chunks.
1700
- */
1701
- readonly timeBetweenOutputChunksMs?: OutputChunkTimingStats;
1702
- };
1703
- };
1704
- /**
1705
- * Callback that is set using the `onLanguageModelCallStart` option.
1706
- *
1707
- * Called immediately before the provider model call begins.
1708
- * Unlike step-start callbacks, this is scoped to model work only and
1709
- * excludes any later client-side tool execution.
1710
- *
1711
- * @param event - The event object containing model-call-specific inputs.
1712
- */
1713
- type OnLanguageModelCallStartCallback = Callback<LanguageModelCallStartEvent>;
1714
- /**
1715
- * Callback that is set using the `onLanguageModelCallEnd` option.
1716
- *
1717
- * Called after the model response has been normalized and parsed, but before
1718
- * any client-side tool execution begins.
1719
- *
1720
- * @param event - The event object containing model-call-specific outputs.
1721
- */
1722
- type OnLanguageModelCallEndCallback<TOOLS extends ToolSet = ToolSet> = Callback<LanguageModelCallEndEvent<TOOLS>>;
1723
- //#endregion
1724
- //#region src/util/async-iterable-stream.d.ts
1725
- /**
1726
- * A type that combines AsyncIterable and ReadableStream.
1727
- * This allows a ReadableStream to be consumed using for-await-of syntax.
1728
- */
1729
- type AsyncIterableStream<T> = AsyncIterable<T> & ReadableStream<T>;
1730
- /**
1731
- * Wraps a ReadableStream and returns an object that is both a ReadableStream and an AsyncIterable.
1732
- * This enables consumption of the stream using for-await-of, with proper resource cleanup on early exit or error.
1733
- *
1734
- * @template T The type of the stream's chunks.
1735
- * @param source The source ReadableStream to wrap.
1736
- * @returns An AsyncIterableStream that can be used as both a ReadableStream and an AsyncIterable.
1737
- */
1738
- export declare function createAsyncIterableStream<T>(source: ReadableStream<T>): AsyncIterableStream<T>;
1739
- //#endregion
1740
- //#region src/generate-text/output-utils.d.ts
1741
- /**
1742
- * Infers the complete output type from the output specification.
1743
- */
1744
- type InferCompleteOutput<OUTPUT extends Output> = OUTPUT extends Output<infer COMPLETE_OUTPUT, any, any> ? COMPLETE_OUTPUT : never;
1745
- //#endregion
1746
- //#region src/generate-text/tool-output-denied.d.ts
1747
- /**
1748
- * Tool output when the tool execution has been denied (for static tools).
1749
- */
1750
- type StaticToolOutputDenied<TOOLS extends ToolSet> = ValueOf<{ [NAME in keyof TOOLS]-?: {
1751
- type: 'tool-output-denied';
1752
- toolCallId: string;
1753
- toolName: NAME & string;
1754
- providerExecuted?: boolean;
1755
- dynamic?: false | undefined;
1756
- }; }>;
1757
- //#endregion
1758
- //#region src/generate-text/stream-text-result.d.ts
1759
- type TextStreamTextDeltaPart = {
1760
- type: 'text-delta';
1761
- id: string;
1762
- providerMetadata?: ProviderMetadata;
1763
- text: string;
1764
- };
1765
- type TextStreamTextStartPart = {
1766
- type: 'text-start';
1767
- id: string;
1768
- providerMetadata?: ProviderMetadata;
1769
- };
1770
- type TextStreamTextEndPart = {
1771
- type: 'text-end';
1772
- citations?: Array<Citation>;
1773
- id: string;
1774
- providerMetadata?: ProviderMetadata;
1775
- };
1776
- type TextStreamReasoningStartPart = {
1777
- type: 'reasoning-start';
1778
- id: string;
1779
- providerMetadata?: ProviderMetadata;
1780
- };
1781
- type TextStreamReasoningEndPart = {
1782
- type: 'reasoning-end';
1783
- id: string;
1784
- providerMetadata?: ProviderMetadata;
1785
- };
1786
- type TextStreamReasoningDeltaPart = {
1787
- type: 'reasoning-delta';
1788
- providerMetadata?: ProviderMetadata;
1789
- id: string;
1790
- text: string;
1791
- };
1792
- type TextStreamCustomPart = {
1793
- type: 'custom';
1794
- kind: `${string}.${string}`;
1795
- providerMetadata?: ProviderMetadata;
1796
- };
1797
- type TextStreamToolInputStartPart = {
1798
- type: 'tool-input-start';
1799
- id: string;
1800
- toolName: string;
1801
- /** Encoding of the input deltas. Defaults to JSON when omitted. */
1802
- inputEncoding?: 'json' | 'text';
1803
- providerMetadata?: ProviderMetadata;
1804
- toolMetadata?: JSONObject;
1805
- providerExecuted?: boolean;
1806
- dynamic?: boolean;
1807
- title?: string;
1808
- };
1809
- type TextStreamToolInputEndPart = {
1810
- type: 'tool-input-end';
1811
- id: string;
1812
- providerMetadata?: ProviderMetadata;
1813
- };
1814
- type TextStreamToolInputDeltaPart = {
1815
- type: 'tool-input-delta';
1816
- id: string;
1817
- delta: string;
1818
- providerMetadata?: ProviderMetadata;
1819
- };
1820
- type TextStreamSourcePart = {
1821
- type: 'source';
1822
- } & Source;
1823
- type TextStreamFilePart = {
1824
- type: 'file';
1825
- file: GeneratedFile;
1826
- providerMetadata?: ProviderMetadata;
1827
- };
1828
- type TextStreamReasoningFilePart = {
1829
- type: 'reasoning-file';
1830
- file: GeneratedFile;
1831
- providerMetadata?: ProviderMetadata;
1832
- };
1833
- type TextStreamToolCallPart<TOOLS extends ToolSet> = {
1834
- type: 'tool-call';
1835
- } & TypedToolCall<TOOLS>;
1836
- type TextStreamToolResultPart<TOOLS extends ToolSet> = {
1837
- type: 'tool-result';
1838
- } & TypedToolResult<TOOLS>;
1839
- type TextStreamToolErrorPart<TOOLS extends ToolSet> = {
1840
- type: 'tool-error';
1841
- } & TypedToolError<TOOLS>;
1842
- type TextStreamToolOutputDeniedPart<TOOLS extends ToolSet> = {
1843
- type: 'tool-output-denied';
1844
- } & StaticToolOutputDenied<TOOLS>;
1845
- type TextStreamToolApprovalRequestPart<TOOLS extends ToolSet> = ToolApprovalRequestOutput<TOOLS>;
1846
- type TextStreamToolApprovalResponsePart<TOOLS extends ToolSet> = ToolApprovalResponseOutput<TOOLS>;
1847
- /**
1848
- * Experimental. A steering message that was added to the run before the step
1849
- * with the given number. Streamed before the output of that step.
1850
- */
1851
- type TextStreamSteeringMessagePart = {
1852
- type: 'steering-message';
1853
- /** The id of the steering message. */
1854
- id: string;
1855
- /** The user message that was added to the run. */
1856
- message: UserModelMessage;
1857
- /** The number of the step whose model call received the message. */
1858
- stepNumber: number;
1859
- };
1860
- type TextStreamStartStepPart = {
1861
- type: 'start-step';
1862
- request: LanguageModelRequestMetadata;
1863
- warnings: CallWarning[];
1864
- };
1865
- type TextStreamFinishStepPart = {
1866
- type: 'finish-step';
1867
- response: Omit<LanguageModelResponseMetadata, 'messages' | 'body'>;
1868
- usage: LanguageModelUsage;
1869
- performance: StepResultPerformance;
1870
- finishReason: FinishReason;
1871
- rawFinishReason: string | undefined;
1872
- providerMetadata: ProviderMetadata | undefined;
1873
- };
1874
- type TextStreamStartPart = {
1875
- type: 'start';
1876
- };
1877
- type TextStreamFinishPart = {
1878
- type: 'finish';
1879
- finishReason: FinishReason;
1880
- rawFinishReason: string | undefined;
1881
- totalUsage: LanguageModelUsage;
1882
- };
1883
- type TextStreamAbortPart = {
1884
- type: 'abort';
1885
- reason?: string;
1886
- };
1887
- type TextStreamErrorPart = {
1888
- type: 'error';
1889
- error: unknown;
1890
- };
1891
- type TextStreamRawPart = {
1892
- type: 'raw';
1893
- rawValue: unknown;
1894
- };
1895
- type TextStreamPingPart = {
1896
- type: 'ping';
1897
- };
1898
- type TextStreamPart<TOOLS extends ToolSet> = TextStreamTextStartPart | TextStreamTextEndPart | TextStreamTextDeltaPart | TextStreamReasoningStartPart | TextStreamReasoningEndPart | TextStreamReasoningDeltaPart | TextStreamCustomPart | TextStreamToolInputStartPart | TextStreamToolInputEndPart | TextStreamToolInputDeltaPart | TextStreamSourcePart | TextStreamFilePart | TextStreamReasoningFilePart | TextStreamToolCallPart<TOOLS> | TextStreamToolResultPart<TOOLS> | TextStreamToolErrorPart<TOOLS> | TextStreamToolOutputDeniedPart<TOOLS> | TextStreamToolApprovalRequestPart<TOOLS> | TextStreamToolApprovalResponsePart<TOOLS> | TextStreamSteeringMessagePart | TextStreamStartStepPart | TextStreamFinishStepPart | TextStreamStartPart | TextStreamFinishPart | TextStreamAbortPart | TextStreamErrorPart | TextStreamPingPart | TextStreamRawPart;
1899
- //#endregion
1900
- //#region src/generate-text/tool-order.d.ts
1901
- /**
1902
- * Tool names that define the order in which tools are sent to the provider.
1903
- *
1904
- * Tool names are object keys at runtime, so the type is restricted to the
1905
- * string keys of the configured tool set. The list can be partial; tools not
1906
- * listed in `toolOrder` are sent after the listed tools, sorted alphabetically.
1907
- */
1908
- type ToolOrder<TOOLS extends ToolSet> = ReadonlyArray<keyof TOOLS & string> | undefined;
1909
- //#endregion
1910
- //#region src/generate-text/tool-approval-configuration.d.ts
1911
- /**
1912
- * The approval status of a tool configuration. This can be one of the following:
1913
- *
1914
- * - 'not-applicable': The tool does not require approval.
1915
- * - 'approved': The tool is automatically approved.
1916
- * - 'denied': The tool is automatically denied.
1917
- * - 'user-approval': The tool requires user approval.
1918
- *
1919
- * In addition to the string statuses, you can also use object statuses with a reason property.
1920
- * For approved and denied statuses, the reason is emitted on the approval response.
1921
- * For user-approval statuses, the reason is emitted on the approval request so it can be shown to the approver.
1922
- *
1923
- * `undefined` is treated as the `not-applicable` status.
1924
- */
1925
- type ToolApprovalStatus = undefined | 'not-applicable' | 'approved' | 'denied' | 'user-approval' | {
1926
- type: 'not-applicable';
1927
- reason?: never;
1928
- } | {
1929
- type: 'approved';
1930
- reason?: string;
1931
- } | {
1932
- type: 'denied';
1933
- reason?: string;
1934
- } | {
1935
- type: 'user-approval';
1936
- reason?: string;
1937
- };
1938
- /**
1939
- * Function that is called to determine if the tool needs approval before it can be executed.
1940
- *
1941
- * Return `undefined` for the same effect as the `not-applicable` status.
1942
- */
1943
- type SingleToolApprovalFunction<INPUT, TOOL_CONTEXT extends Context | unknown | never, RUNTIME_CONTEXT extends Context | unknown | never> = (input: INPUT, options: Omit<ToolExecutionOptions<TOOL_CONTEXT>, 'abortSignal' | 'context'> & {
1944
- toolContext: TOOL_CONTEXT;
1945
- runtimeContext: RUNTIME_CONTEXT;
1946
- }) => MaybePromiseLike<ToolApprovalStatus>;
1947
- /**
1948
- * Function that is called to determine if a tool call needs approval before it can be executed.
1949
- *
1950
- * Return `undefined` for the same effect as the `not-applicable` status.
1951
- */
1952
- type GenericToolApprovalFunction<TOOLS extends ToolSet, TOOLS_CONTEXT extends InferToolSetContext<TOOLS>, RUNTIME_CONTEXT extends Context | unknown | never> = (options: {
1953
- /**
1954
- * The tool call that needs approval.
1955
- */
1956
- toolCall: TypedToolCall<TOOLS>;
1957
- /**
1958
- * All tools that are available for the model to call.
1959
- */
1960
- tools: TOOLS | undefined;
1961
- /**
1962
- * Tool context for all tools that are available for the model to call.
1963
- */
1964
- toolsContext: TOOLS_CONTEXT;
1965
- /**
1966
- * Runtime context.
1967
- */
1968
- runtimeContext: RUNTIME_CONTEXT;
1969
- /**
1970
- * Messages that were sent to the language model to initiate the response that contained the tool call.
1971
- * The messages **do not** include the system prompt nor the assistant response that contained the tool call.
1972
- */
1973
- messages: ModelMessage[];
1974
- }) => MaybePromiseLike<ToolApprovalStatus>;
1975
- /**
1976
- * Configure whether individual tools require approval before they can run.
1977
- *
1978
- * You can either use a generic function that is called for all tool calls,
1979
- * or you can use a per-tool function.
1980
- *
1981
- * For the per-tool functions, each tool can be assigned either an approval status
1982
- * or a function that produces an approval status at runtime.
1983
- *
1984
- * The approval status can be one of the following:
1985
- * - 'not-applicable': The tool does not require approval.
1986
- * - 'approved': The tool is automatically approved.
1987
- * - 'denied': The tool is automatically denied.
1988
- * - 'user-approval': The tool requires user approval.
1989
- *
1990
- * In addition to the string statuses, you can also use object statuses with a reason property.
1991
- * For approved and denied statuses, the reason is emitted on the approval response.
1992
- * For user-approval statuses, the reason is emitted on the approval request so it can be shown to the approver.
1993
- */
1994
- type ToolApprovalConfiguration<TOOLS extends ToolSet, RUNTIME_CONTEXT extends Context | unknown | never> = GenericToolApprovalFunction<TOOLS, InferToolSetContext<TOOLS>, RUNTIME_CONTEXT> | { [key in keyof TOOLS]?: ToolApprovalStatus | SingleToolApprovalFunction<InferToolInput<TOOLS[key]>, InferToolContext<TOOLS[key]>, RUNTIME_CONTEXT>; };
1995
- //#endregion
1996
- //#region src/generate-text/tool-caller-configuration.d.ts
1997
- type ResolvedToolCallers = Record<string, ReadonlyArray<string>>;
1998
- //#endregion
1999
- //#region src/error/invalid-tool-input-error.d.ts
2000
- declare const symbol$1: unique symbol;
2001
- declare class InvalidToolInputError extends AISDKError {
2002
- private readonly [symbol$1];
2003
- readonly toolName: string;
2004
- readonly toolInput: string;
2005
- constructor({ toolInput, toolName, cause, message }: {
2006
- message?: string;
2007
- toolInput: string;
2008
- toolName: string;
2009
- cause: unknown;
2010
- });
2011
- static isInstance(error: unknown): error is InvalidToolInputError;
2012
- }
2013
- //#endregion
2014
- //#region src/error/no-such-tool-error.d.ts
2015
- declare const symbol: unique symbol;
2016
- declare class NoSuchToolError extends AISDKError {
2017
- private readonly [symbol];
2018
- readonly toolName: string;
2019
- readonly availableTools: string[] | undefined;
2020
- constructor({ toolName, availableTools, message }: {
2021
- toolName: string;
2022
- availableTools?: string[] | undefined;
2023
- message?: string;
2024
- });
2025
- static isInstance(error: unknown): error is NoSuchToolError;
2026
- }
2027
- //#endregion
2028
- //#region src/generate-text/tool-call-repair-function.d.ts
2029
- /**
2030
- * A function that attempts to repair a tool call that failed to parse.
2031
- *
2032
- * It receives the error and the context as arguments and returns the repair
2033
- * tool call JSON as text.
2034
- *
2035
- * @param options.instructions - The instructions provided to the model.
2036
- * @param options.system - The instructions provided to the model.
2037
- * @param options.messages - The messages in the current generation step.
2038
- * @param options.toolCall - The tool call that failed to parse.
2039
- * @param options.tools - The tools that are available.
2040
- * @param options.inputSchema - A function that returns the JSON Schema for a tool.
2041
- * @param options.error - The error that occurred while parsing the tool call.
2042
- * @param options.abortSignal - An optional signal for cancelling the repair.
2043
- */
2044
- type ToolCallRepairFunction<TOOLS extends ToolSet> = (options: {
2045
- instructions: Instructions | undefined;
2046
- /**
2047
- * @deprecated Use `instructions` instead.
2048
- */
2049
- system: Instructions | undefined;
2050
- messages: ModelMessage$1[];
2051
- toolCall: LanguageModelV4ToolCall;
2052
- tools: TOOLS;
2053
- inputSchema: (options: {
2054
- toolName: string;
2055
- }) => PromiseLike<JSONSchema7>;
2056
- error: NoSuchToolError | InvalidToolInputError;
2057
- abortSignal?: AbortSignal;
2058
- }) => Promise<LanguageModelV4ToolCall | null>;
2059
- //#endregion
2060
- //#region src/generate-text/tool-output.d.ts
2061
- type ToolOutput<TOOLS extends ToolSet> = TypedToolResult<TOOLS> | TypedToolError<TOOLS>;
2062
- //#endregion
2063
- //#region src/generate-text/tool-execution-events.d.ts
2064
- /**
2065
- * Resolves a single tool's context type, falling back to `undefined` when the
2066
- * tool does not declare a `contextSchema`.
2067
- */
2068
- type ToolContextFor<TOOL extends ToolSet[keyof ToolSet]> = [InferToolContext<TOOL>] extends [never] ? undefined : InferToolContext<TOOL>;
2069
- type BaseToolExecutionStartFields = {
2070
- /** Unique identifier for this generation call, used to correlate events. */
2071
- readonly callId: string;
2072
- /**
2073
- * Messages that were sent to the language model to initiate the response that contained the tool call.
2074
- * The messages **do not** include the system prompt nor the assistant response that contained the tool call.
2075
- */
2076
- readonly messages: ModelMessage[];
2077
- };
2078
- /**
2079
- * Precise start event union for statically known tools.
2080
- *
2081
- * Each union member ties a specific `toolCall.toolName` to that tool's
2082
- * validated `toolContext` type.
2083
- */
2084
- type StaticToolExecutionStartEvent<TOOLS extends ToolSet> = ValueOf<{ [NAME in keyof TOOLS]-?: BaseToolExecutionStartFields & {
2085
- readonly toolCall: Extract<StaticToolCall<TOOLS>, {
2086
- toolName: NAME;
2087
- }>;
2088
- readonly toolContext: ToolContextFor<TOOLS[NAME]>;
2089
- }; }>;
2090
- /**
2091
- * Start event shape for dynamic or untyped tool calls.
2092
- */
2093
- type DynamicToolExecutionStartEvent = BaseToolExecutionStartFields & {
2094
- readonly toolCall: DynamicToolCall;
2095
- readonly toolContext: unknown;
2096
- };
2097
- /**
2098
- * Broad start event shape used for the default `ToolSet` specialization.
2099
- *
2100
- * This keeps generic collectors ergonomic when the caller is not working with
2101
- * a concrete tool set and therefore cannot benefit from per-tool narrowing.
2102
- */
2103
- type WidenedToolExecutionStartEvent = BaseToolExecutionStartFields & {
2104
- readonly toolCall: StaticToolCall<ToolSet> | DynamicToolCall;
2105
- readonly toolContext: unknown;
2106
- };
2107
- /**
2108
- * Event passed to the `onToolExecutionStart` callback.
2109
- *
2110
- * Called when a tool execution begins, before the tool's `execute` function is invoked.
2111
- */
2112
- type ToolExecutionStartEvent<TOOLS extends ToolSet = ToolSet> = [ToolSet] extends [TOOLS] ? WidenedToolExecutionStartEvent : StaticToolExecutionStartEvent<TOOLS> | DynamicToolExecutionStartEvent;
2113
- type BaseToolExecutionEndFields = {
2114
- /** Unique identifier for this generation call, used to correlate events. */
2115
- readonly callId: string;
2116
- /** Execution time of the tool call in milliseconds. */
2117
- readonly toolExecutionMs: number;
2118
- /**
2119
- * Messages that were sent to the language model to initiate the response that contained the tool call.
2120
- * The messages **do not** include the system prompt nor the assistant response that contained the tool call.
2121
- */
2122
- readonly messages: ModelMessage[];
2123
- };
2124
- /**
2125
- * Precise end event union for statically known tools.
2126
- *
2127
- * Each union member preserves the link between `toolCall.toolName`, the
2128
- * corresponding validated `toolContext`, and the tool execution result.
2129
- */
2130
- type StaticToolExecutionEndEvent<TOOLS extends ToolSet> = ValueOf<{ [NAME in keyof TOOLS]-?: BaseToolExecutionEndFields & {
2131
- readonly toolCall: Extract<StaticToolCall<TOOLS>, {
2132
- toolName: NAME;
2133
- }>;
2134
- readonly toolContext: ToolContextFor<TOOLS[NAME]>;
2135
- readonly toolOutput: ToolOutput<TOOLS>;
2136
- }; }>;
2137
- /**
2138
- * End event shape for dynamic or untyped tool calls.
2139
- */
2140
- type DynamicToolExecutionEndEvent<TOOLS extends ToolSet> = BaseToolExecutionEndFields & {
2141
- readonly toolCall: DynamicToolCall;
2142
- readonly toolContext: unknown;
2143
- readonly toolOutput: ToolOutput<TOOLS>;
2144
- };
2145
- /**
2146
- * Broad end event shape used for the default `ToolSet` specialization.
2147
- *
2148
- * This provides an assignable catch-all event type for generic consumers while
2149
- * the concrete-tool specialization retains full per-tool narrowing.
2150
- */
2151
- type WidenedToolExecutionEndEvent = BaseToolExecutionEndFields & {
2152
- readonly toolCall: StaticToolCall<ToolSet> | DynamicToolCall;
2153
- readonly toolContext: unknown;
2154
- readonly toolOutput: ToolOutput<ToolSet>;
2155
- };
2156
- /**
2157
- * Event passed to the `onToolExecutionEnd` callback.
2158
- *
2159
- * Called when a tool execution completes, either successfully or with an error.
2160
- * Uses the `toolOutput.type` discriminator to distinguish success and error.
2161
- */
2162
- type ToolExecutionEndEvent<TOOLS extends ToolSet = ToolSet> = [ToolSet] extends [TOOLS] ? WidenedToolExecutionEndEvent : StaticToolExecutionEndEvent<TOOLS> | DynamicToolExecutionEndEvent<TOOLS>;
2163
- /**
2164
- * Callback that is set using the `onToolExecutionStart` option.
2165
- *
2166
- * Called when a tool execution begins, before the tool's `execute` function is invoked.
2167
- * Use this for logging tool invocations, tracking tool usage, or pre-execution validation.
2168
- *
2169
- * @param event - The event object containing tool call information.
2170
- */
2171
- type OnToolExecutionStartCallback<TOOLS extends ToolSet = ToolSet> = Callback<ToolExecutionStartEvent<TOOLS>>;
2172
- /**
2173
- * Callback that is set using the `onToolExecutionEnd` option.
2174
- *
2175
- * Called when a tool execution completes, either successfully or with an error.
2176
- * Use this for logging tool results, tracking execution time, or error handling.
2177
- *
2178
- * The event uses a discriminated union on `toolOutput.type`:
2179
- * - When `toolOutput.type === 'tool-result'`: `toolOutput.output` contains the tool result.
2180
- * - When `toolOutput.type === 'tool-error'`: `toolOutput.error` contains the error.
2181
- *
2182
- * @param event - The event object containing tool call result information.
2183
- */
2184
- type OnToolExecutionEndCallback<TOOLS extends ToolSet = ToolSet> = Callback<ToolExecutionEndEvent<TOOLS>>;
2185
- //#endregion
2186
- //#region src/generate-text/tool-input-refinement.d.ts
2187
- /**
2188
- * Mapping of tool names to functions that refine parsed tool inputs.
2189
- *
2190
- * Each refinement function receives the typed input for its tool and must return
2191
- * an input with the same type shape. Refined inputs are used for tool execution,
2192
- * output parts, lifecycle callbacks, and telemetry.
2193
- */
2194
- type ToolInputRefinement<TOOLS extends ToolSet> = { [NAME in keyof TOOLS]?: (input: InferToolInput<TOOLS[NAME]>) => MaybePromiseLike<InferToolInput<TOOLS[NAME]>>; };
2195
- //#endregion
2196
- //#region src/generate-text/tools-context-parameter.d.ts
2197
- /**
2198
- * Checks whether a tool context map contains any contextual tool entries.
2199
- */
2200
- type IsEmptyObject<OBJECT> = keyof OBJECT extends never ? true : false;
2201
- /**
2202
- * Makes the toolsContext setting optional, required, or unavailable based on
2203
- * the tool set.
2204
- */
2205
- type ToolsContextSettings<TOOLS extends ToolSet> = IsEmptyObject<InferToolSetContext<TOOLS>> extends true ? {
2206
- toolsContext?: never;
2207
- } : HasRequiredKey<InferToolSetContext<TOOLS>> extends true ? {
2208
- toolsContext: InferToolSetContext<TOOLS>;
2209
- } : {
2210
- toolsContext?: InferToolSetContext<TOOLS>;
2211
- };
2212
- //#endregion
2213
- //#region src/generate-text/stream-text.d.ts
2214
- type EnrichedStreamPart<TOOLS extends ToolSet, PARTIAL_OUTPUT> = {
2215
- part: TextStreamPart<TOOLS>;
2216
- partialOutput: PARTIAL_OUTPUT | undefined;
2217
- };
2218
- //#endregion
2219
- //#region src/generate-text/output.d.ts
2220
- interface Output<OUTPUT = any, PARTIAL = any, ELEMENT = any> {
2221
- /**
2222
- * The name of the output mode.
2223
- */
2224
- name: string;
2225
- /**
2226
- * The response format to use for the model.
2227
- */
2228
- responseFormat: PromiseLike<LanguageModelV4CallOptions['responseFormat']>;
2229
- /**
2230
- * Parses the complete output of the model.
2231
- */
2232
- parseCompleteOutput(options: {
2233
- text: string;
2234
- }, context: {
2235
- response: Omit<LanguageModelResponseMetadata, 'messages' | 'body'>;
2236
- usage: LanguageModelUsage;
2237
- finishReason: FinishReason;
2238
- }): Promise<OUTPUT>;
2239
- /**
2240
- * Parses the partial output of the model.
2241
- */
2242
- parsePartialOutput(options: {
2243
- text: string;
2244
- }): Promise<{
2245
- partial: PARTIAL;
2246
- } | undefined>;
2247
- /**
2248
- * Creates a stream transform that emits individual elements as they complete.
2249
- */
2250
- createElementStreamTransform(): TransformStream<EnrichedStreamPart<any, PARTIAL>, ELEMENT> | undefined;
2251
- }
2252
- //#endregion
2253
- //#region src/generate-text/generate-text-events.d.ts
2254
- /**
2255
- * Event passed to the `onStart` callback.
2256
- *
2257
- * Called when the generation operation begins, before any LLM calls.
2258
- */
2259
- type GenerateTextStartEvent<TOOLS extends ToolSet = ToolSet, RUNTIME_CONTEXT extends Context = Context, OUTPUT extends Output = Output> = {
2260
- /** Unique identifier for this generation call, used to correlate events. */
2261
- readonly callId: string;
2262
- /** Identifies the operation type (e.g. 'ai.generateText' or 'ai.streamText'). */
2263
- readonly operationId: string;
2264
- /** The provider identifier (e.g., 'openai', 'anthropic'). */
2265
- readonly provider: string;
2266
- /** The specific model identifier (e.g., 'gpt-4o'). */
2267
- readonly modelId: string;
2268
- /** The tools available for this generation. */
2269
- readonly tools: TOOLS | undefined;
2270
- /** The tool choice strategy for this generation. */
2271
- readonly toolChoice: ToolChoice<NoInfer<TOOLS>> | undefined;
2272
- /** Limits which tools are available for the model to call. */
2273
- readonly activeTools: ActiveTools<TOOLS>;
2274
- /** Controls the order in which tools are sent to the provider. */
2275
- readonly toolOrder: ToolOrder<TOOLS>;
2276
- /** Maximum number of retries for failed requests. */
2277
- readonly maxRetries: number;
2278
- /**
2279
- * Timeout configuration for the generation.
2280
- * Can be a number (milliseconds) or an object with totalMs, stepMs,
2281
- * firstChunkMs (streaming only), chunkMs, toolMs, and per-tool overrides via tools.
2282
- */
2283
- readonly timeout: TimeoutConfiguration<TOOLS> | undefined;
2284
- /** Additional HTTP headers sent with the request. */
2285
- readonly headers: Record<string, string | undefined> | undefined;
2286
- /** Additional provider-specific options. */
2287
- readonly providerOptions: ProviderOptions | undefined;
2288
- /** The output specification for structured outputs, if configured. */
2289
- readonly output: OUTPUT | undefined;
2290
- /**
2291
- * Tool context.
2292
- */
2293
- readonly toolsContext: InferToolSetContext<TOOLS>;
2294
- /**
2295
- * User-defined runtime context.
2296
- */
2297
- readonly runtimeContext: RUNTIME_CONTEXT;
2298
- } & LanguageModelCallOptions & StandardizedPrompt;
2299
- /**
2300
- * Event passed to the `onStepStart` callback.
2301
- *
2302
- * Called when a step (LLM call) begins, before the provider is called.
2303
- * Each step represents a single LLM invocation.
2304
- */
2305
- type GenerateTextStepStartEvent<TOOLS extends ToolSet = ToolSet, RUNTIME_CONTEXT extends Context = Context, OUTPUT extends Output = Output> = {
2306
- /** Unique identifier for this generation call, used to correlate events. */
2307
- readonly callId: string;
2308
- /** The provider identifier (e.g., 'openai', 'anthropic'). */
2309
- readonly provider: string;
2310
- /** The specific model identifier (e.g., 'gpt-4o'). */
2311
- readonly modelId: string;
2312
- /** Zero-based index of the current step. */
2313
- readonly stepNumber: number;
2314
- /** The tools available for this generation. */
2315
- readonly tools: TOOLS | undefined;
2316
- /** The tool choice configuration for this step. */
2317
- readonly toolChoice: ToolChoice<NoInfer<TOOLS>> | undefined;
2318
- /** Limits which tools are available for this step. */
2319
- readonly activeTools: ActiveTools<TOOLS>;
2320
- /** Controls the order in which tools are sent to the provider for this step. */
2321
- readonly toolOrder: ToolOrder<TOOLS>;
2322
- /** Array of results from previous steps (empty for first step). */
2323
- readonly steps: ReadonlyArray<StepResult<TOOLS, RUNTIME_CONTEXT>>;
2324
- /** Additional provider-specific options for this step. */
2325
- readonly providerOptions: ProviderOptions | undefined;
2326
- /** The output specification for structured outputs, if configured. */
2327
- readonly output: OUTPUT | undefined;
2328
- /**
2329
- * Runtime context. May be updated from `prepareStep` between steps.
2330
- */
2331
- readonly runtimeContext: RUNTIME_CONTEXT;
2332
- /**
2333
- * Tool context. May be updated from `prepareStep` between steps.
2334
- */
2335
- readonly toolsContext: InferToolSetContext<TOOLS>;
2336
- } & StandardizedPrompt;
2337
- /**
2338
- * Event passed to the `onStepEnd` callback.
2339
- *
2340
- * Called when a step (LLM call) completes.
2341
- * Includes the StepResult for that step along with the call identifier.
2342
- */
2343
- type GenerateTextStepEndEvent<TOOLS extends ToolSet = ToolSet, RUNTIME_CONTEXT extends Context = Context> = StepResult<TOOLS, RUNTIME_CONTEXT>;
2344
- /**
2345
- * Event passed to the `onEnd` callback.
2346
- *
2347
- * Called when the entire generation completes (all steps finished).
2348
- * Includes the final step's result along with aggregated data from all steps.
2349
- */
2350
- type GenerateTextEndEvent<TOOLS extends ToolSet = ToolSet, RUNTIME_CONTEXT extends Context = Context> = {
2351
- /** Unique identifier for this generation call, used to correlate events. */
2352
- readonly callId: string;
2353
- /** Zero-based index of the final step. */
2354
- readonly stepNumber: number;
2355
- /** Information about the model that produced the final step. */
2356
- readonly model: StepResult<TOOLS, RUNTIME_CONTEXT>['model'];
2357
- /**
2358
- * Tool context from the final step.
2359
- *
2360
- * @deprecated Use `finalStep.toolsContext` instead.
2361
- */
2362
- readonly toolsContext: InferToolSetContext<TOOLS>;
2363
- /**
2364
- * Runtime context from the final step.
2365
- *
2366
- * @deprecated Use `finalStep.runtimeContext` instead.
2367
- */
2368
- readonly runtimeContext: RUNTIME_CONTEXT;
2369
- /** The content that was generated in all steps. */
2370
- readonly content: StepResult<TOOLS, RUNTIME_CONTEXT>['content'];
2371
- /** The text that was generated in the final step. */
2372
- readonly text: StepResult<TOOLS, RUNTIME_CONTEXT>['text'];
2373
- /**
2374
- * The reasoning that was generated in the final step.
2375
- *
2376
- * @deprecated Use `finalStep.reasoning` instead.
2377
- */
2378
- readonly reasoning: StepResult<TOOLS, RUNTIME_CONTEXT>['reasoning'];
2379
- /**
2380
- * The reasoning text that was generated in the final step.
2381
- *
2382
- * @deprecated Use `finalStep.reasoningText` instead.
2383
- */
2384
- readonly reasoningText: StepResult<TOOLS, RUNTIME_CONTEXT>['reasoningText'];
2385
- /** Files that were generated in all steps. */
2386
- readonly files: StepResult<TOOLS, RUNTIME_CONTEXT>['files'];
2387
- /** Sources that were used as references in all steps. */
2388
- readonly sources: StepResult<TOOLS, RUNTIME_CONTEXT>['sources'];
2389
- /** Tool calls that were made in all steps. */
2390
- readonly toolCalls: StepResult<TOOLS, RUNTIME_CONTEXT>['toolCalls'];
2391
- /** Static tool calls that were made in all steps. */
2392
- readonly staticToolCalls: StepResult<TOOLS, RUNTIME_CONTEXT>['staticToolCalls'];
2393
- /** Dynamic tool calls that were made in all steps. */
2394
- readonly dynamicToolCalls: StepResult<TOOLS, RUNTIME_CONTEXT>['dynamicToolCalls'];
2395
- /** Tool results that were generated in all steps. */
2396
- readonly toolResults: StepResult<TOOLS, RUNTIME_CONTEXT>['toolResults'];
2397
- /** Static tool results that were generated in all steps. */
2398
- readonly staticToolResults: StepResult<TOOLS, RUNTIME_CONTEXT>['staticToolResults'];
2399
- /** Dynamic tool results that were generated in all steps. */
2400
- readonly dynamicToolResults: StepResult<TOOLS, RUNTIME_CONTEXT>['dynamicToolResults'];
2401
- /** The unified reason why the generation finished. Taken from the final step. */
2402
- readonly finishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['finishReason'];
2403
- /** The raw reason why the generation finished. Taken from the final step. */
2404
- readonly rawFinishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['rawFinishReason'];
2405
- /** Aggregated token usage across all steps. */
2406
- readonly usage: LanguageModelUsage;
2407
- /**
2408
- * Aggregated token usage across all steps.
2409
- *
2410
- * @deprecated Use `usage` instead.
2411
- */
2412
- readonly totalUsage: LanguageModelUsage;
2413
- /** Warnings from the model provider in all steps. */
2414
- readonly warnings: StepResult<TOOLS, RUNTIME_CONTEXT>['warnings'];
2415
- /**
2416
- * Additional request information from the final step.
2417
- *
2418
- * @deprecated Use `finalStep.request` instead.
2419
- */
2420
- readonly request: StepResult<TOOLS, RUNTIME_CONTEXT>['request'];
2421
- /**
2422
- * Additional response information from the final step.
2423
- *
2424
- * @deprecated Use `finalStep.response` instead.
2425
- */
2426
- readonly response: StepResult<TOOLS, RUNTIME_CONTEXT>['response'];
2427
- /**
2428
- * Additional provider-specific metadata from the final step.
2429
- *
2430
- * @deprecated Use `finalStep.providerMetadata` instead.
2431
- */
2432
- readonly providerMetadata: StepResult<TOOLS, RUNTIME_CONTEXT>['providerMetadata'];
2433
- /** The response messages that were generated during the call. */
2434
- readonly responseMessages: ResponseMessage[];
2435
- /** Array containing results from all steps in the generation. */
2436
- readonly steps: StepResult<TOOLS, RUNTIME_CONTEXT>[];
2437
- /** The final step. This is a shortcut for `steps.at(-1)`. */
2438
- readonly finalStep: StepResult<TOOLS, RUNTIME_CONTEXT>;
2439
- };
2440
- /**
2441
- * Event passed to an `onAbort` callback for text generation.
2442
- *
2443
- * Called when a streaming text generation operation is aborted before it
2444
- * completes.
2445
- */
2446
- type GenerateTextAbortEvent<TOOLS extends ToolSet = ToolSet, RUNTIME_CONTEXT extends Context = Context> = {
2447
- /** Unique identifier for this generation call, used to correlate events. */
2448
- readonly callId: string;
2449
- /** Details for all previously finished steps. */
2450
- readonly steps: StepResult<TOOLS, RUNTIME_CONTEXT>[];
2451
- /** The abort reason from the AbortSignal, when one is available. */
2452
- readonly reason?: unknown;
2453
- };
2454
- /**
2455
- * Callback that is set using the `onStart` option.
2456
- *
2457
- * Called when the generateText operation begins, before any LLM calls.
2458
- * Use this callback for logging, analytics, or initializing state at the
2459
- * start of a generation.
2460
- *
2461
- * @param event - The event object containing generation configuration.
2462
- */
2463
- type GenerateTextOnStartCallback<TOOLS extends ToolSet = ToolSet, RUNTIME_CONTEXT extends Context = Context, OUTPUT extends Output = Output> = Callback<GenerateTextStartEvent<TOOLS, RUNTIME_CONTEXT, OUTPUT>>;
2464
- /**
2465
- * Callback that is set using the `onStepStart` option.
2466
- *
2467
- * Called when a step (LLM call) begins, before the provider is called.
2468
- * Each step represents a single LLM invocation. Multiple steps occur when
2469
- * using tool calls (the model may be called multiple times in a loop).
2470
- *
2471
- * @param event - The event object containing step configuration.
2472
- */
2473
- type GenerateTextOnStepStartCallback<TOOLS extends ToolSet = ToolSet, RUNTIME_CONTEXT extends Context = Context, OUTPUT extends Output = Output> = Callback<GenerateTextStepStartEvent<TOOLS, RUNTIME_CONTEXT, OUTPUT>>;
2474
- /**
2475
- * Callback that is set using the `onStepEnd` option.
2476
- *
2477
- * Called when a step (LLM call) completes. The event includes all step result
2478
- * properties (text, tool calls, usage, etc.) along with additional metadata.
2479
- *
2480
- * @param stepResult - The result of the step.
2481
- */
2482
- type GenerateTextOnStepEndCallback<TOOLS extends ToolSet = ToolSet, RUNTIME_CONTEXT extends Context = Context> = Callback<GenerateTextStepEndEvent<TOOLS, RUNTIME_CONTEXT>>;
2483
- /**
2484
- * Callback that is set using the `onStepFinish` option.
2485
- *
2486
- * @deprecated Use `GenerateTextOnStepEndCallback` instead.
2487
- */
2488
- type GenerateTextOnStepFinishCallback<TOOLS extends ToolSet = ToolSet, RUNTIME_CONTEXT extends Context = Context> = GenerateTextOnStepEndCallback<TOOLS, RUNTIME_CONTEXT>;
2489
- /**
2490
- * Event passed to the `onStepError` callback.
2491
- *
2492
- * Contains the step start event of the step that failed before it produced
2493
- * a step result, along with the error.
2494
- */
2495
- type GenerateTextStepErrorEvent<TOOLS extends ToolSet = ToolSet, RUNTIME_CONTEXT extends Context = Context, OUTPUT extends Output = Output> = GenerateTextStepStartEvent<TOOLS, RUNTIME_CONTEXT, OUTPUT> & {
2496
- /** The error that ended the step. */
2497
- readonly error: unknown;
2498
- };
2499
- /**
2500
- * Callback that is set using the `onStepError` option.
2501
- *
2502
- * Called when a step that started fails before it produces a step result:
2503
- * when the provider call throws or rejects, or when the model stream ends
2504
- * without output. `onStepEnd` is not called for such a step. A provider
2505
- * `error` chunk does not fail the step, it still ends with `onStepEnd` and
2506
- * `finishReason: 'error'`.
2507
- *
2508
- * In `generateText`, an abort or timeout also ends the step here. The error
2509
- * is the abort or timeout error, or a provider error that has it as its
2510
- * `cause`. In `streamText`, an abort or timeout ends the step
2511
- * with `onAbort` instead.
2512
- *
2513
- * @param event - The step that failed and the error.
2514
- */
2515
- type GenerateTextOnStepErrorCallback<TOOLS extends ToolSet = ToolSet, RUNTIME_CONTEXT extends Context = Context, OUTPUT extends Output = Output> = Callback<GenerateTextStepErrorEvent<TOOLS, RUNTIME_CONTEXT, OUTPUT>>;
2516
- /**
2517
- * Callback that is set using the `onEnd` option.
2518
- *
2519
- * Called when the entire generation completes (all steps finished).
2520
- * The event includes the final step's result properties along with
2521
- * aggregated data from all steps.
2522
- *
2523
- * @param event - The final result along with aggregated step data.
2524
- */
2525
- type GenerateTextOnEndCallback<TOOLS extends ToolSet = ToolSet, RUNTIME_CONTEXT extends Context = Context> = Callback<GenerateTextEndEvent<TOOLS, RUNTIME_CONTEXT>>;
2526
- /**
2527
- * Callback that is set using the telemetry `onAbort` option.
2528
- *
2529
- * Called when a streaming text generation operation is aborted before it
2530
- * completes.
2531
- *
2532
- * @param event - The abort event, including finished steps and abort reason.
2533
- */
2534
- type GenerateTextOnAbortCallback<TOOLS extends ToolSet = ToolSet, RUNTIME_CONTEXT extends Context = Context> = Callback<GenerateTextAbortEvent<TOOLS, RUNTIME_CONTEXT>>;
2535
- //#endregion
2536
- //#region src/rerank/rerank-events.d.ts
2537
- /**
2538
- * Event passed to the `onStart` callback for rerank operations.
2539
- *
2540
- * Called when the operation begins, before the reranking model is called.
2541
- */
2542
- type RerankStartEvent<RUNTIME_CONTEXT extends Context = Context> = {
2543
- /** User-defined runtime context. */
2544
- readonly runtimeContext: RUNTIME_CONTEXT;
2545
- /** Unique identifier for this rerank call, used to correlate events. */
2546
- readonly callId: string;
2547
- /** Identifies the operation type ('ai.rerank'). */
2548
- readonly operationId: string;
2549
- readonly provider: string;
2550
- /** The specific model identifier (e.g., 'gpt-4o'). */
2551
- readonly modelId: string;
2552
- /** The documents being reranked. */
2553
- readonly documents: Array<JSONObject | string>;
2554
- /** The query to rerank the documents against. */
2555
- readonly query: string;
2556
- /** Number of top documents to return. */
2557
- readonly topN: number | undefined;
2558
- /** Maximum number of retries for failed requests. */
2559
- readonly maxRetries: number;
2560
- /** Additional HTTP headers sent with the request. */
2561
- readonly headers: Record<string, string | undefined> | undefined;
2562
- /** Additional provider-specific options. */
2563
- readonly providerOptions: ProviderOptions | undefined;
2564
- };
2565
- /**
2566
- * Event passed to the `onEnd` callback for rerank operations.
2567
- *
2568
- * Called when the operation completes, after the reranking model returns.
2569
- */
2570
- type RerankEndEvent<RUNTIME_CONTEXT extends Context = Context> = {
2571
- /** User-defined runtime context. */
2572
- readonly runtimeContext: RUNTIME_CONTEXT;
2573
- /** Unique identifier for this rerank call, used to correlate events. */
2574
- readonly callId: string;
2575
- /** Identifies the operation type ('ai.rerank'). */
2576
- readonly operationId: string;
2577
- readonly provider: string;
2578
- /** The specific model identifier (e.g., 'gpt-4o'). */
2579
- readonly modelId: string;
2580
- /** The documents that were reranked. */
2581
- readonly documents: Array<JSONObject | string>;
2582
- /** The query that documents were reranked against. */
2583
- readonly query: string;
2584
- /** The reranked results sorted by relevance score in descending order. */
2585
- readonly ranking: Array<{
2586
- originalIndex: number;
2587
- score: number;
2588
- document: JSONObject | string;
2589
- }>;
2590
- /** Warnings from the reranking model. */
2591
- readonly warnings: Array<Warning>;
2592
- /** Optional provider-specific metadata. */
2593
- readonly providerMetadata: ProviderMetadata | undefined;
2594
- /** Response data including headers and body. */
2595
- readonly response: {
2596
- id?: string;
2597
- timestamp: Date;
2598
- modelId: string;
2599
- headers?: Record<string, string>;
2600
- body?: unknown;
2601
- };
2602
- };
2603
- /**
2604
- * Event fired when an individual reranking model call (inner doRerank) begins.
2605
- */
2606
- type RerankingModelCallStartEvent = {
2607
- /** Unique identifier for this rerank call, used to correlate events. */
2608
- readonly callId: string;
2609
- /** Identifies the inner operation ('ai.rerank.doRerank'). */
2610
- readonly operationId: string;
2611
- /** The provider identifier. */
2612
- readonly provider: string;
2613
- /** The specific model identifier. */
2614
- readonly modelId: string;
2615
- /** The documents being reranked. */
2616
- readonly documents: Array<JSONObject | string>;
2617
- /** The type of documents ('text' or 'object'). */
2618
- readonly documentsType: string;
2619
- /** The query to rerank against. */
2620
- readonly query: string;
2621
- /** Number of top documents to return. */
2622
- readonly topN: number | undefined;
2623
- };
2624
- /**
2625
- * Event fired when an individual reranking model call (doRerank) completes.
2626
- *
2627
- * Contains the ranking results from the model response.
2628
- */
2629
- type RerankingModelCallEndEvent = {
2630
- /** Unique identifier for this rerank call, used to correlate events. */
2631
- readonly callId: string;
2632
- /** Identifies the inner operation ('ai.rerank.doRerank'). */
2633
- readonly operationId: string;
2634
- /** The provider identifier. */
2635
- readonly provider: string;
2636
- /** The specific model identifier. */
2637
- readonly modelId: string;
2638
- /** The type of documents ('text' or 'object'). */
2639
- readonly documentsType: string;
2640
- /** The ranking results from the model. */
2641
- readonly ranking: Array<{
2642
- index: number;
2643
- relevanceScore: number;
2644
- }>;
2645
- };
2646
- //#endregion
2647
- //#region src/generate-speech/speech-events.d.ts
2648
- /**
2649
- * Event passed to telemetry integrations when speech generation begins.
2650
- */
2651
- type GenerateSpeechStartEvent = {
2652
- /** Unique identifier for this speech generation call. */
2653
- readonly callId: string;
2654
- /** Identifies the operation type (`ai.generateSpeech`). */
2655
- readonly operationId: 'ai.generateSpeech';
2656
- /** The provider identifier. */
2657
- readonly provider: string;
2658
- /** The specific model identifier. */
2659
- readonly modelId: string;
2660
- /** The text to convert to speech. */
2661
- readonly text: string;
2662
- /** The requested voice. */
2663
- readonly voice: string | undefined;
2664
- /** The requested output format. */
2665
- readonly outputFormat: string | undefined;
2666
- /** Additional speech instructions. */
2667
- readonly instructions: string | undefined;
2668
- /** The requested speech speed. */
2669
- readonly speed: number | undefined;
2670
- /** The requested language. */
2671
- readonly language: string | undefined;
2672
- /** Maximum number of retries for failed requests. */
2673
- readonly maxRetries: number;
2674
- /** Additional HTTP headers sent with the request. */
2675
- readonly headers: Record<string, string> | undefined;
2676
- /** Additional provider-specific options. */
2677
- readonly providerOptions: ProviderOptions;
2678
- };
2679
- /**
2680
- * Event passed to telemetry integrations when speech generation completes.
2681
- *
2682
- * Raw audio is intentionally not included. Integrations receive only its size,
2683
- * media type, and format.
2684
- */
2685
- type GenerateSpeechEndEvent = {
2686
- /** Unique identifier for this speech generation call. */
2687
- readonly callId: string;
2688
- /** Identifies the operation type (`ai.generateSpeech`). */
2689
- readonly operationId: 'ai.generateSpeech';
2690
- /** The provider identifier. */
2691
- readonly provider: string;
2692
- /** The specific model identifier. */
2693
- readonly modelId: string;
2694
- /** The text that was converted to speech. */
2695
- readonly text: string;
2696
- /** Metadata about the generated audio. */
2697
- readonly audio: {
2698
- readonly byteLength: number;
2699
- readonly mediaType: string;
2700
- readonly format: string;
2701
- };
2702
- /** Usage reported by the provider, when available. */
2703
- readonly usage: JSONObject | undefined;
2704
- /** Warnings from the speech model. */
2705
- readonly warnings: Array<Warning>;
2706
- /** Optional provider-specific metadata. */
2707
- readonly providerMetadata: ProviderMetadata | undefined;
2708
- /** Response metadata from the provider. */
2709
- readonly response: SpeechModelResponseMetadata;
2710
- };
2711
- //#endregion
2712
- //#region src/transcribe/transcription-events.d.ts
2713
- /**
2714
- * Event passed to telemetry integrations when transcription begins.
2715
- */
2716
- type TranscriptionStartEventFor<OPERATION_ID extends string> = {
2717
- /** Unique identifier for this transcription call. */
2718
- readonly callId: string;
2719
- /** Identifies the operation type (`ai.transcribe` or `ai.streamTranscribe`). */
2720
- readonly operationId: OPERATION_ID;
2721
- /** The provider identifier. */
2722
- readonly provider: string;
2723
- /** The specific model identifier. */
2724
- readonly modelId: string;
2725
- /**
2726
- * Metadata about the input audio. Native URL transcription does not inspect
2727
- * the audio, so its byte length and media type are unknown. Streaming byte
2728
- * length is reported on the end event after consuming the stream.
2729
- */
2730
- readonly audio: {
2731
- readonly byteLength: number | undefined;
2732
- /**
2733
- * The media type, when it is known before input preparation completes.
2734
- * URL downloads and invalid inline inputs can begin without this metadata.
2735
- */
2736
- readonly mediaType: string | undefined;
2737
- };
2738
- /** The raw input format for streaming transcription. */
2739
- readonly inputAudioFormat: SharedV4AudioFormat | undefined;
2740
- /** Maximum number of retries for non-streaming transcription. */
2741
- readonly maxRetries: number | undefined;
2742
- /** Additional HTTP or WebSocket headers sent with the request. */
2743
- readonly headers: Record<string, string> | undefined;
2744
- /** Additional provider-specific options. */
2745
- readonly providerOptions: ProviderOptions;
2746
- };
2747
- type TranscriptionStartEvent = TranscriptionStartEventFor<'ai.transcribe'> & {
2748
- /** Requested shared timing granularities, when specified. */
2749
- readonly timestampGranularities?: Array<TranscriptionModelV4TimestampGranularity>;
2750
- };
2751
- type StreamTranscriptionStartEvent = TranscriptionStartEventFor<'ai.streamTranscribe'>;
2752
- /**
2753
- * Event passed to telemetry integrations when transcription completes.
2754
- *
2755
- * Raw audio is intentionally not included.
2756
- */
2757
- type TranscriptionEndEventFor<OPERATION_ID extends string> = {
2758
- /** Unique identifier for this transcription call. */
2759
- readonly callId: string;
2760
- /** Identifies the operation type (`ai.transcribe` or `ai.streamTranscribe`). */
2761
- readonly operationId: OPERATION_ID;
2762
- /** The provider identifier. */
2763
- readonly provider: string;
2764
- /** The specific model identifier. */
2765
- readonly modelId: string;
2766
- /** Metadata about the input audio. */
2767
- readonly audio: {
2768
- readonly byteLength: OPERATION_ID extends 'ai.transcribe' ? number | undefined : number;
2769
- readonly mediaType: OPERATION_ID extends 'ai.transcribe' ? string | undefined : string;
2770
- };
2771
- /** The complete transcript. */
2772
- readonly text: string;
2773
- /** Transcript segments with timing information, retaining provider behavior. */
2774
- readonly segments: Array<{
2775
- readonly text: string;
2776
- readonly startSecond: number;
2777
- readonly endSecond: number;
2778
- }>;
2779
- /** The detected language. */
2780
- readonly language: string | undefined;
2781
- /** The duration of the input audio, when available. */
2782
- readonly durationInSeconds: number | undefined;
2783
- /** Usage reported by the provider, when available. */
2784
- readonly usage: JSONObject | undefined;
2785
- /** Warnings from the transcription model. */
2786
- readonly warnings: Array<Warning>;
2787
- /** Optional provider-specific metadata. */
2788
- readonly providerMetadata: ProviderMetadata | undefined;
2789
- /** Response metadata from the provider. */
2790
- readonly response: TranscriptionModelResponseMetadata;
2791
- };
2792
- type TranscriptionEndEvent = TranscriptionEndEventFor<'ai.transcribe'> & {
2793
- /** Word timings returned by the provider, whether requested or returned by default. */
2794
- readonly words?: Array<{
2795
- readonly text: string;
2796
- readonly startSecond: number;
2797
- readonly endSecond: number;
2798
- }>;
2799
- };
2800
- type StreamTranscriptionEndEvent = TranscriptionEndEventFor<'ai.streamTranscribe'>;
2801
- //#endregion
2802
- //#region src/telemetry/tracing-channel.d.ts
2803
- type TelemetryTracingEventType = 'generateText' | 'streamText' | 'step' | 'languageModelCall' | 'executeTool' | 'embed' | 'embedMany' | 'rerank' | 'generateSpeech' | 'transcribe' | 'streamTranscribe' | 'experimental_decide';
2804
- //#endregion
2805
- //#region src/telemetry/tracing-channel-publisher.d.ts
2806
- type TracingChannelContext = {
2807
- run<T>(execute: () => T): T;
2808
- };
2809
- //#endregion
2810
- //#region src/telemetry/telemetry.d.ts
2811
- /** Serializable tracing identity shared by the processes of a durable run. */
2812
- type DurableTelemetryContext = {
2813
- traceId: string;
2814
- rootSpanId: string;
2815
- /** The integration's root-span data, reused when the run is reported. */
2816
- rootSpanName?: string;
2817
- rootAttributes?: Record<string, string | number | boolean | Array<string | null | undefined> | Array<number | null | undefined> | Array<boolean | null | undefined> | undefined>;
2818
- traceFlags: number;
2819
- traceState?: string;
2820
- samplingDecision: 0 | 1 | 2;
2821
- parentSpanContext?: {
2822
- traceId: string;
2823
- spanId: string;
2824
- traceFlags: number;
2825
- traceState?: string;
2826
- };
2827
- };
2828
- /** Identifies live model events and the run events reported after completion. */
2829
- type DurableTelemetryEventContext = {
2830
- run: DurableTelemetryContext;
2831
- stepNumber?: number;
2832
- phase: 'live' | 'replay';
2833
- /** Context has already been filtered before crossing the step boundary. */
2834
- runtimeContext?: Record<string, unknown>;
2835
- headers?: Record<string, string | undefined>;
2836
- };
2837
- type InferTelemetryEvent<EVENT> = EVENT & Omit<TelemetryOptions, 'integrations' | 'isEnabled' | 'includeRuntimeContext'> & {
2838
- /**
2839
- * The version of the `ai` package that emitted this event.
2840
- * Absent in older releases.
2841
- */
2842
- readonly aiVersion?: string;
2843
- /**
2844
- * Time at which the event occurred, in milliseconds since the Unix epoch.
2845
- *
2846
- * Set when events are reported after they happened, for example when a
2847
- * durable workflow reports a run that spanned several processes.
2848
- * Integrations should use it instead of the current time when present.
2849
- */
2850
- readonly timestamp?: number;
2851
- readonly durableContext?: DurableTelemetryEventContext;
2852
- };
2853
- type BivariantCallback<EVENT> = {
2854
- bivarianceHack(event: EVENT): PromiseLike<void> | void;
2855
- }['bivarianceHack'];
2856
- type OperationStartEvent = GenerateTextStartEvent | GenerateObjectStartEvent | EmbedStartEvent | RerankStartEvent | GenerateSpeechStartEvent | TranscriptionStartEvent;
2857
- type OperationEndEvent = GenerateTextEndEvent<ToolSet> | GenerateObjectEndEvent<unknown> | EmbedEndEvent | RerankEndEvent | GenerateSpeechEndEvent | TranscriptionEndEvent;
2858
- interface TelemetryDispatcher {
2859
- /**
2860
- * Runs awaited work inside a diagnostics-channel tracing span.
2861
- */
2862
- runInTracingChannelSpan?: <T>(options: {
2863
- type: TelemetryTracingEventType;
2864
- event: unknown;
2865
- execute: () => PromiseLike<T>;
2866
- }) => Promise<T>;
2867
- /**
2868
- * Opens a tracing span context whose completion is observed separately.
2869
- * This is used by streamed operations that must preserve stream timing while
2870
- * still creating child spans with the correct parent.
2871
- */
2872
- startTracingChannelContext?: (options: {
2873
- type: TelemetryTracingEventType;
2874
- event: unknown;
2875
- completion: PromiseLike<unknown>;
2876
- }) => TracingChannelContext | undefined;
2877
- onStart?: Callback<OperationStartEvent>;
2878
- onStepStart?: Callback<GenerateTextStepStartEvent>;
2879
- onLanguageModelCallStart?: OnLanguageModelCallStartCallback;
2880
- onLanguageModelCallEnd?: OnLanguageModelCallEndCallback;
2881
- onToolExecutionStart?: Callback<ToolExecutionStartEvent>;
2882
- onToolExecutionEnd?: Callback<ToolExecutionEndEvent>;
2883
- onStepEnd?: Callback<GenerateTextStepEndEvent>;
2884
- /** @deprecated Use `onStepEnd` instead. */
2885
- onStepFinish?: Callback<GenerateTextStepEndEvent>;
2886
- onStepError?: Callback<GenerateTextStepErrorEvent>;
2887
- onObjectStepStart?: Callback<GenerateObjectStepStartEvent>;
2888
- onObjectStepEnd?: Callback<GenerateObjectStepEndEvent>;
2889
- onEmbedStart?: Callback<EmbeddingModelCallStartEvent>;
2890
- onEmbedEnd?: Callback<EmbeddingModelCallEndEvent>;
2891
- onRerankStart?: Callback<RerankingModelCallStartEvent>;
2892
- onRerankEnd?: Callback<RerankingModelCallEndEvent>;
2893
- experimental_onDecideStart?: Callback<DecideStartEvent>;
2894
- experimental_onDecisionModelCallStart?: Callback<DecisionModelCallStartEvent>;
2895
- experimental_onDecisionModelCallEnd?: Callback<DecisionModelCallEndEvent>;
2896
- experimental_onDecideEnd?: Callback<DecideEndEvent>;
2897
- experimental_onStreamTranscriptionStart?: Callback<StreamTranscriptionStartEvent>;
2898
- experimental_onStreamTranscriptionEnd?: Callback<StreamTranscriptionEndEvent>;
2899
- onEnd?: Callback<OperationEndEvent>;
2900
- onAbort?: Callback<GenerateTextAbortEvent<ToolSet>>;
2901
- onError?: Callback<unknown>;
2902
- executeLanguageModelCall?: Telemetry['executeLanguageModelCall'];
2903
- executeTool?: Telemetry['executeTool'];
2904
- }
2905
- /**
2906
- * Implement this interface to create custom telemetry integrations.
2907
- * Methods can be sync or return a PromiseLike.
2908
- */
2909
- interface Telemetry {
2910
- /**
2911
- * Capture a serializable tracing identity before a durable run's model calls.
2912
- * Return undefined to preserve live per-model operations when the integration
2913
- * cannot reconstruct a run span across processes. Integrations without this
2914
- * hook receive the recorded lifecycle after completion.
2915
- */
2916
- experimental_durable?: {
2917
- captureContext: (event: InferTelemetryEvent<GenerateTextStartEvent>) => DurableTelemetryContext | undefined | PromiseLike<DurableTelemetryContext | undefined>;
2918
- };
2919
- /**
2920
- * Called when an operation begins. Fired for text generation
2921
- * (generateText/streamText), object generation (generateObject/streamObject),
2922
- * embedding (embed/embedMany), reranking, speech generation, and
2923
- * non-streaming transcription operations.
2924
- *
2925
- * Use the `operationId` field to distinguish between operation types.
2926
- */
2927
- onStart?: BivariantCallback<InferTelemetryEvent<OperationStartEvent>>;
2928
- /**
2929
- * Called when an individual step (single LLM invocation) begins.
2930
- * A generation may consist of multiple steps (e.g. when tool calls trigger
2931
- * follow-up LLM calls). Use this to create per-step spans or record
2932
- * step-level inputs.
2933
- *
2934
- * The event includes the step number, accumulated previous step results,
2935
- * and the messages that will be sent to the model.
2936
- */
2937
- onStepStart?: Callback<InferTelemetryEvent<GenerateTextStepStartEvent>>;
2938
- /**
2939
- * Called immediately before the provider model call begins.
2940
- * Unlike `onStepStart`, this callback is scoped to model work only and
2941
- * excludes any later client-side tool execution.
2942
- */
2943
- onLanguageModelCallStart?: Callback<InferTelemetryEvent<LanguageModelCallStartEvent>>;
2944
- /**
2945
- * Called after the model response has been normalized and parsed, but before
2946
- * any client-side tool execution begins.
2947
- */
2948
- onLanguageModelCallEnd?: Callback<InferTelemetryEvent<LanguageModelCallEndEvent>>;
2949
- /**
2950
- * Called when a tool execution begins, before the tool's `execute` function
2951
- * is invoked. Use this to create tool-level spans or log tool invocations.
2952
- */
2953
- onToolExecutionStart?: Callback<InferTelemetryEvent<ToolExecutionStartEvent>>;
2954
- /**
2955
- * Called when a tool execution completes, either successfully or with an error.
2956
- * The event uses a discriminated union on the `success` field — check
2957
- * `event.success` to determine whether `output` or `error` is available.
2958
- *
2959
- * The event includes execution time (`toolExecutionMs`) for performance tracking.
2960
- */
2961
- onToolExecutionEnd?: Callback<InferTelemetryEvent<ToolExecutionEndEvent>>;
2962
- /**
2963
- * Called when an individual step (single LLM invocation) completes.
2964
- * The event is a `StepResult` containing the model's response, tool calls
2965
- * and results, usage statistics, finish reason, and optional request/response
2966
- * bodies.
2967
- */
2968
- onStepEnd?: Callback<InferTelemetryEvent<GenerateTextStepEndEvent>>;
2969
- /**
2970
- * Called when an individual step (single LLM invocation) completes.
2971
- *
2972
- * @deprecated Use `onStepEnd` instead.
2973
- */
2974
- onStepFinish?: Callback<InferTelemetryEvent<GenerateTextStepEndEvent>>;
2975
- /**
2976
- * Called when a step that started fails before it produces a step result.
2977
- * Use it to close step-level spans. The call then ends with `onError`.
2978
- */
2979
- onStepError?: Callback<InferTelemetryEvent<GenerateTextStepErrorEvent>>;
2980
- /**
2981
- * Called when an object generation step (single LLM invocation) begins.
2982
- * For generateObject/streamObject there is always exactly one step.
2983
- *
2984
- * @deprecated
2985
- */
2986
- onObjectStepStart?: Callback<InferTelemetryEvent<GenerateObjectStepStartEvent>>;
2987
- /**
2988
- * Called when an object generation step (single LLM invocation) completes,
2989
- * with the raw result before JSON parsing and schema validation.
2990
- *
2991
- * @deprecated
2992
- */
2993
- onObjectStepEnd?: Callback<InferTelemetryEvent<GenerateObjectStepEndEvent>>;
2994
- /**
2995
- * Called when an individual embedding model call (doEmbed) begins.
2996
- * For `embed`, there is one call. For `embedMany`, there may be multiple
2997
- * calls when values are chunked.
2998
- */
2999
- onEmbedStart?: Callback<InferTelemetryEvent<EmbeddingModelCallStartEvent>>;
3000
- /**
3001
- * Called when an individual embedding model call (doEmbed) completes.
3002
- * Contains the embeddings, usage, and any warnings from the model response.
3003
- */
3004
- onEmbedEnd?: Callback<InferTelemetryEvent<EmbeddingModelCallEndEvent>>;
3005
- /**
3006
- * Called when an individual reranking model call (doRerank) begins.
3007
- * There is one call per `rerank` invocation.
3008
- */
3009
- onRerankStart?: Callback<InferTelemetryEvent<RerankingModelCallStartEvent>>;
3010
- /**
3011
- * Called when an individual reranking model call (doRerank) completes.
3012
- * Contains the ranking results from the model response.
3013
- */
3014
- onRerankEnd?: Callback<InferTelemetryEvent<RerankingModelCallEndEvent>>;
3015
- /** @deprecated Use `experimental_onDecideStart` instead. */
3016
- experimental_onEvaluateStart?: Callback<InferTelemetryEvent<DecideStartEvent>>;
3017
- /** @deprecated Use `experimental_onDecisionModelCallStart` instead. */
3018
- experimental_onEvaluationModelCallStart?: Callback<InferTelemetryEvent<DecisionModelCallStartEvent>>;
3019
- /** @deprecated Use `experimental_onDecisionModelCallEnd` instead. */
3020
- experimental_onEvaluationModelCallEnd?: Callback<InferTelemetryEvent<DecisionModelCallEndEvent>>;
3021
- /** @deprecated Use `experimental_onDecideEnd` instead. */
3022
- experimental_onEvaluateEnd?: Callback<InferTelemetryEvent<DecideEndEvent>>;
3023
- /** Called when an experimental decision operation begins. */
3024
- experimental_onDecideStart?: Callback<InferTelemetryEvent<DecideStartEvent>>;
3025
- /**
3026
- * Called immediately before an experimental decision model call begins.
3027
- * The logical model call includes any provider retries.
3028
- */
3029
- experimental_onDecisionModelCallStart?: Callback<InferTelemetryEvent<DecisionModelCallStartEvent>>;
3030
- /**
3031
- * Called after an experimental decision model response has been validated.
3032
- * The logical model call includes any provider retries.
3033
- */
3034
- experimental_onDecisionModelCallEnd?: Callback<InferTelemetryEvent<DecisionModelCallEndEvent>>;
3035
- /** Called when an experimental decision operation completes. */
3036
- experimental_onDecideEnd?: Callback<InferTelemetryEvent<DecideEndEvent>>;
3037
- /** Called when an experimental streaming transcription operation begins. */
3038
- experimental_onStreamTranscriptionStart?: Callback<InferTelemetryEvent<StreamTranscriptionStartEvent>>;
3039
- /** Called when an experimental streaming transcription operation completes. */
3040
- experimental_onStreamTranscriptionEnd?: Callback<InferTelemetryEvent<StreamTranscriptionEndEvent>>;
3041
- /**
3042
- * Called when an operation completes. Fired for text generation
3043
- * (generateText/streamText), object generation (generateObject/streamObject),
3044
- * embedding (embed/embedMany), reranking, speech generation, and
3045
- * non-streaming transcription operations.
3046
- *
3047
- * Use the event shape or `operationId` to distinguish between operation types.
3048
- */
3049
- onEnd?: BivariantCallback<InferTelemetryEvent<OperationEndEvent>>;
3050
- /**
3051
- * Called when a streaming text generation operation is aborted before it
3052
- * completes.
3053
- */
3054
- onAbort?: Callback<InferTelemetryEvent<GenerateTextAbortEvent<ToolSet>>>;
3055
- /**
3056
- * Called when an unrecoverable error occurs during the generation lifecycle.
3057
- * The error value is untyped — it may be an `Error` instance, an `AISDKError`,
3058
- * or any thrown value.
3059
- *
3060
- * Use this to record error details on telemetry spans and set error status.
3061
- */
3062
- onError?: Callback<unknown>;
3063
- /**
3064
- * Optionally runs the language model call in a telemetry-integration-specific context. This enables
3065
- * auto-instrumented model provider requests to become children of the current
3066
- * model-call span.
3067
- *
3068
- * The options carry the model-call start-event content as context (the event
3069
- * fields are optional), alongside the always-present `callId` and the
3070
- * `execute` function that performs the model call.
3071
- */
3072
- executeLanguageModelCall?: <T>(options: Partial<InferTelemetryEvent<LanguageModelCallStartEvent>> & {
3073
- callId: string;
3074
- execute: () => PromiseLike<T>;
3075
- }) => PromiseLike<T>;
3076
- /**
3077
- * Optionally runs the tool execute function in a telemetry-integration-specific context. This enables
3078
- * nested traces — e.g. when a tool's `execute` function calls `generateText`,
3079
- * the inner call's spans become children of the tool span.
3080
- *
3081
- * The options carry the tool-execution start-event content as context (the
3082
- * event fields are optional), alongside the always-present `callId`,
3083
- * `toolCallId`, and the `execute` function to run.
3084
- */
3085
- executeTool?: <T>(options: Partial<InferTelemetryEvent<ToolExecutionStartEvent>> & {
3086
- callId: string;
3087
- toolCallId: string;
3088
- execute: () => PromiseLike<T>;
3089
- }) => PromiseLike<T>;
3090
- }
3091
- //#endregion
3092
- //#region src/global.d.ts
3093
- declare const aiSdkGlobalsKey: unique symbol;
3094
- declare global {
3095
- interface AISDKGlobalTypes {
3096
- [aiSdkGlobalsKey]: {
3097
- provider: ProviderV4 | ProviderV3 | ProviderV2;
3098
- logWarnings: LogWarningsFunction;
3099
- telemetry: Telemetry;
3100
- };
3101
- }
3102
- /**
3103
- * The default provider to use for the AI SDK.
3104
- * String model ids are resolved to the default provider and model id.
3105
- *
3106
- * If not set, the default provider is the Vercel AI gateway provider.
3107
- * An explicitly configured provider must support decision models to use experimental_decide.
3108
- * An explicitly configured provider must support extraction models to use experimental_extract.
3109
- *
3110
- * @see https://ai-sdk.dev/docs/ai-sdk-core/provider-management#global-provider-configuration
3111
- */
3112
- var AI_SDK_DEFAULT_PROVIDER: AISDKGlobalTypes[keyof AISDKGlobalTypes]['provider'] | undefined;
3113
- /**
3114
- * The warning logger to use for the AI SDK.
3115
- *
3116
- * If not set, warnings use process.emitWarning when available, otherwise
3117
- * console.warn. Deprecations are emitted once per code by the default logger.
3118
- *
3119
- * If set to false, no warnings are logged.
3120
- */
3121
- var AI_SDK_LOG_WARNINGS: AISDKGlobalTypes[keyof AISDKGlobalTypes]['logWarnings'] | undefined | false;
3122
- /**
3123
- * Globally registered telemetry integrations for the AI SDK.
3124
- *
3125
- * Integrations registered here receive lifecycle events (onStart, onStepStart,
3126
- * etc.) from every `generateText`, `streamText`, and similar call.
3127
- *
3128
- * Prefer using `registerTelemetry()` from `'ai'` instead of
3129
- * assigning this directly.
3130
- */
3131
- var AI_SDK_TELEMETRY_INTEGRATIONS: Array<AISDKGlobalTypes[keyof AISDKGlobalTypes]['telemetry']> | undefined;
3132
- }
3133
- //#endregion
1
+ import { $c as LanguageModelCallOptions, Al as addLanguageModelUsage, Ao as ToolApprovalStatus, Ba as GenerateTextOnEndCallback, Bl as LanguageModelResponseMetadata, Ca as TelemetryDispatcher, El as Warning, Eo as ResolvedToolCallers, Ga as GenerateTextOnStepFinishCallback, Go as StaticToolOutputDenied, Ha as GenerateTextOnStartCallback, Hl as LanguageModelRequestMetadata, Jl as ToolChoice, Js as ContentPart, Ka as GenerateTextOnStepStartCallback, Kl as FinishReason, Ks as StepResult, Ml as createNullLanguageModelUsage, Pc as ToolModelMessage$1, So as ToolCallRepairFunction, Ua as GenerateTextOnStepEndCallback, Vl as ResponseMessage, Vo as ToolOrder, Wa as GenerateTextOnStepErrorCallback, Ws as DefaultStepResult, Xs as StaticToolResult, Ys as DynamicToolResult, Zo as createAsyncIterableStream, Zs as TypedToolResult, _a as LanguageModelStreamPart, _c as StandardizedPrompt, _l as DownloadFunction, _o as OnToolExecutionEndCallback, ac as TypedToolCall, dc as IncludedContext, fc as IncludedToolsContext, ga as GenerateTextResult, gc as Callback, ic as StaticToolCall, jl as asLanguageModelUsage, kl as LanguageModelUsage, ko as ToolApprovalConfiguration, mo as ToolInputRefinement, nc as ToolApprovalRequestOutput, oc as ReasoningFileOutput, pc as TelemetryOptions, po as ToolsContextSettings, ql as LanguageModel, qo as InferCompleteOutput, rc as DynamicToolCall, sc as ReasoningOutput, tc as ToolApprovalResponseOutput, to as Output, uc as GeneratedFile, vc as standardizePrompt, vl as createDefaultDownloadFunction, vo as OnToolExecutionStartCallback, wc as AssistantModelMessage$1, wl as logWarnings, wo as InvalidToolInputError, xo as ToolOutput, za as GenerateTextOnAbortCallback, zc as Instructions } from "../index-CM_8u8gB.js";
2
+ import { Arrayable, Context, Experimental_SandboxSession, FlexibleSchema, IdGenerator, InferToolSetContext, ModelMessage, RetryFunction, ShouldRetryFunction, Tool, ToolApprovalRequest, ToolApprovalResponse, ToolResultOutput, ToolResultPart, ToolSet, convertAsyncIteratorToReadableStream } from "@ai-sdk/provider-utils";
3
+ import { EmbeddingModelV4, Experimental_DecisionModelV4, Experimental_ExtractionModelV4, Experimental_SpeechTranslationModelV4, Experimental_VideoModelV4, ImageModelV4, LanguageModelV4, LanguageModelV4Content, LanguageModelV4FunctionTool, LanguageModelV4Prompt, LanguageModelV4ProviderTool, LanguageModelV4ToolCall, LanguageModelV4ToolChoice, LanguageModelV4ToolResultOutput, RerankingModelV4, SharedV4Warning, SpeechModelV4, TranscriptionModelV4 } from "@ai-sdk/provider";
3134
4
  //#region src/prompt/convert-to-language-model-prompt.d.ts
3135
5
  export declare function convertToLanguageModelPrompt({ prompt, supportedUrls, download, abortSignal, provider }: {
3136
6
  prompt: StandardizedPrompt;
@@ -3329,43 +199,6 @@ export declare function parseToolCall<TOOLS extends ToolSet>({ toolCall, tools,
3329
199
  abortSignal?: AbortSignal;
3330
200
  }): Promise<TypedToolCall<TOOLS>>;
3331
201
  //#endregion
3332
- //#region src/generate-text/stream-language-model-call.d.ts
3333
- type LanguageModelStreamPart<TOOLS extends ToolSet = ToolSet> = Exclude<TextStreamPart<TOOLS>, {
3334
- type: 'finish' | 'stream-start' | 'tool-output-denied' | 'start-step' | 'finish-step' | 'steering-message' | 'start' | 'abort';
3335
- }> | TextStreamTextDeltaPart | TextStreamReasoningDeltaPart | TextStreamFilePart | TextStreamReasoningFilePart | TextStreamToolApprovalRequestPart<TOOLS> | TextStreamToolApprovalResponsePart<TOOLS> | TextStreamToolCallPart<TOOLS> | TextStreamToolResultPart<TOOLS> | TextStreamToolErrorPart<TOOLS> | {
3336
- type: 'model-call-end';
3337
- finishReason: FinishReason;
3338
- rawFinishReason: string | undefined;
3339
- usage: LanguageModelUsage;
3340
- providerMetadata?: ProviderMetadata;
3341
- performance: {
3342
- responseTimeMs: number;
3343
- effectiveOutputTokensPerSecond: number;
3344
- outputTokensPerSecond: number | undefined;
3345
- inputTokensPerSecond: number | undefined;
3346
- effectiveTotalTokensPerSecond: number;
3347
- timeToFirstOutputMs: number | undefined;
3348
- timeBetweenOutputChunksMs?: OutputChunkTimingStats;
3349
- };
3350
- } | {
3351
- type: 'model-call-start';
3352
- warnings: Array<CallWarning>;
3353
- } | {
3354
- type: 'model-call-response-metadata';
3355
- /**
3356
- * ID for the generated response, if the provider sends one.
3357
- */
3358
- id?: string;
3359
- /**
3360
- * Timestamp for the start of the generated response, if the provider sends one.
3361
- */
3362
- timestamp?: Date;
3363
- /**
3364
- * The ID of the response model that was used to generate the response, if the provider sends one.
3365
- */
3366
- modelId?: string;
3367
- };
3368
- //#endregion
3369
202
  //#region src/generate-text/stream-retry-attempt-boundary.d.ts
3370
203
  declare const streamRetryAttemptBoundarySymbol: unique symbol;
3371
204
  type StreamRetryAttemptBoundaryPart = {
@@ -3524,136 +357,6 @@ export declare function toResponseMessages<TOOLS extends ToolSet>({ content: inp
3524
357
  tools: TOOLS | undefined;
3525
358
  }): Promise<Array<AssistantModelMessage$1 | ToolModelMessage$1>>;
3526
359
  //#endregion
3527
- //#region src/generate-text/generate-text-result.d.ts
3528
- /**
3529
- * The result of a `generateText` call.
3530
- * It contains the generated text, the tool calls that were made during the generation, and the results of the tool calls.
3531
- */
3532
- interface GenerateTextResult<TOOLS extends ToolSet, RUNTIME_CONTEXT extends Context, OUTPUT extends Output> {
3533
- /**
3534
- * The content that was generated in all steps.
3535
- */
3536
- readonly content: Array<ContentPart<TOOLS>>;
3537
- /**
3538
- * The concatenation of all text parts generated in the final step.
3539
- * It is an empty string if the final step contains no text parts.
3540
- * Inspect `finalStep.content` to distinguish that case.
3541
- */
3542
- readonly text: string;
3543
- /**
3544
- * The full reasoning that the model has generated in the last step.
3545
- *
3546
- * @deprecated Use `finalStep.reasoning` instead.
3547
- */
3548
- readonly reasoning: Array<ReasoningOutput | ReasoningFileOutput>;
3549
- /**
3550
- * The reasoning text that the model has generated in the last step. Can be undefined if the model
3551
- * has only generated text.
3552
- *
3553
- * @deprecated Use `finalStep.reasoningText` instead.
3554
- */
3555
- readonly reasoningText: string | undefined;
3556
- /**
3557
- * The files that were generated in all steps.
3558
- * Empty array if no files were generated.
3559
- */
3560
- readonly files: Array<GeneratedFile>;
3561
- /**
3562
- * Sources that have been used as references in all steps.
3563
- */
3564
- readonly sources: Array<Source>;
3565
- /**
3566
- * The tool calls that were made in all steps.
3567
- */
3568
- readonly toolCalls: Array<TypedToolCall<TOOLS>>;
3569
- /**
3570
- * The static tool calls that were made in all steps.
3571
- */
3572
- readonly staticToolCalls: Array<StaticToolCall<TOOLS>>;
3573
- /**
3574
- * The dynamic tool calls that were made in all steps.
3575
- */
3576
- readonly dynamicToolCalls: Array<DynamicToolCall>;
3577
- /**
3578
- * The results of the tool calls from all steps.
3579
- */
3580
- readonly toolResults: Array<TypedToolResult<TOOLS>>;
3581
- /**
3582
- * The static tool results that were made in all steps.
3583
- */
3584
- readonly staticToolResults: Array<StaticToolResult<TOOLS>>;
3585
- /**
3586
- * The dynamic tool results that were made in all steps.
3587
- */
3588
- readonly dynamicToolResults: Array<DynamicToolResult>;
3589
- /**
3590
- * The unified reason why the generation finished.
3591
- */
3592
- readonly finishReason: FinishReason;
3593
- /**
3594
- * The raw reason why the generation finished (from the provider).
3595
- */
3596
- readonly rawFinishReason: string | undefined;
3597
- /**
3598
- * The total token usage of all steps.
3599
- * When there are multiple steps, the usage is the sum of all step usages.
3600
- */
3601
- readonly usage: LanguageModelUsage;
3602
- /**
3603
- * The total token usage of all steps.
3604
- * When there are multiple steps, the usage is the sum of all step usages.
3605
- *
3606
- * @deprecated Use `usage` instead.
3607
- */
3608
- readonly totalUsage: LanguageModelUsage;
3609
- /**
3610
- * Warnings from the model provider (e.g. unsupported settings) in all steps.
3611
- */
3612
- readonly warnings: CallWarning[] | undefined;
3613
- /**
3614
- * Additional request information from the last step.
3615
- *
3616
- * @deprecated Use `finalStep.request` instead.
3617
- */
3618
- readonly request: StepResult<TOOLS, RUNTIME_CONTEXT>['request'];
3619
- /**
3620
- * Additional response information from the last step.
3621
- *
3622
- * @deprecated Use `finalStep.response` instead.
3623
- */
3624
- readonly response: LanguageModelResponseMetadata;
3625
- /**
3626
- * The accumulated response messages of all steps that were generated during the call.
3627
- */
3628
- readonly responseMessages: Array<ResponseMessage>;
3629
- /**
3630
- * Additional provider-specific metadata from the final step. They are passed
3631
- * through from the provider to the AI SDK and enable provider-specific
3632
- * results that can be fully encapsulated in the provider.
3633
- *
3634
- * @deprecated Use `finalStep.providerMetadata` instead.
3635
- */
3636
- readonly providerMetadata: ProviderMetadata | undefined;
3637
- /**
3638
- * Details for all steps.
3639
- * You can use this to get information about intermediate steps,
3640
- * such as the tool calls or the response headers.
3641
- */
3642
- readonly steps: Array<StepResult<TOOLS, RUNTIME_CONTEXT>>;
3643
- /**
3644
- * The final step. This is a shortcut for `steps.at(-1)`.
3645
- */
3646
- readonly finalStep: StepResult<TOOLS, RUNTIME_CONTEXT>;
3647
- /**
3648
- * The generated output according to the `output` specification.
3649
- *
3650
- * @throws {NoOutputGeneratedError} When no output is available, for example
3651
- * when the final step finishes with a `tool-calls` reason, or when it
3652
- * contains no text and does not finish with a `stop` reason.
3653
- */
3654
- readonly output: InferCompleteOutput<OUTPUT>;
3655
- }
3656
- //#endregion
3657
360
  //#region src/generate-text/default-generate-text-result.d.ts
3658
361
  export declare class DefaultGenerateTextResult<TOOLS extends ToolSet, RUNTIME_CONTEXT extends Context, OUTPUT extends Output> implements GenerateTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT> {
3659
362
  readonly steps: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['steps'];
@@ -3739,5 +442,5 @@ export declare function mapWithConcurrency<INPUT, OUTPUT>({ items, concurrency,
3739
442
  execute: (item: INPUT, index: number) => Promise<OUTPUT>;
3740
443
  }): Promise<Array<OUTPUT>>;
3741
444
  //#endregion
3742
- export { type CollectedToolApprovals, type DownloadFunction, type ToolsContextSettings, convertAsyncIteratorToReadableStream, prepareLanguageModelCallOptions as prepareCallSettings };
445
+ export { type CollectedToolApprovals, DefaultStepResult, type DownloadFunction, type ToolsContextSettings, addLanguageModelUsage, asLanguageModelUsage, convertAsyncIteratorToReadableStream, createAsyncIterableStream, createDefaultDownloadFunction, createNullLanguageModelUsage, logWarnings, prepareLanguageModelCallOptions as prepareCallSettings, standardizePrompt };
3743
446
  //# sourceMappingURL=index.d.ts.map