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.
- package/CHANGELOG.md +33 -0
- package/dist/default-stop-condition-wtuJTiTo.js +4213 -0
- package/dist/default-stop-condition-wtuJTiTo.js.map +1 -0
- package/dist/index-CM_8u8gB.d.ts +12107 -0
- package/dist/index-CM_8u8gB.d.ts.map +1 -0
- package/dist/index.d.ts +3 -11788
- package/dist/index.js +680 -4732
- package/dist/index.js.map +1 -1
- package/dist/internal/index.d.ts +4 -3301
- package/dist/internal/index.d.ts.map +1 -1
- package/dist/internal/index.js +2 -3819
- package/dist/simulate-readable-stream-Bi5kQKbv.js +25 -0
- package/dist/simulate-readable-stream-Bi5kQKbv.js.map +1 -0
- package/dist/simulate-readable-stream-BuwR4IbD.d.ts +21 -0
- package/dist/simulate-readable-stream-BuwR4IbD.d.ts.map +1 -0
- package/dist/test/index.d.ts +2 -20
- package/dist/test/index.d.ts.map +1 -1
- package/dist/test/index.js +3 -23
- package/dist/test/index.js.map +1 -1
- package/docs/02-foundations/02-providers-and-models.mdx +1 -0
- package/docs/03-agents/06-policy-tool-approvals.mdx +27 -2
- package/docs/03-agents/06-tool-approvals.mdx +2 -1
- package/docs/03-ai-sdk-core/18-tools.mdx +7 -2
- package/docs/03-ai-sdk-core/33-extractions.mdx +21 -4
- package/docs/03-ai-sdk-core/36-realtime.mdx +3 -1
- package/docs/03-ai-sdk-core/36-transcription.mdx +2 -2
- package/docs/03-ai-sdk-core/37-speech.mdx +1 -0
- package/docs/03-ai-sdk-core/60-telemetry.mdx +52 -4
- package/docs/03-ai-sdk-core/65-lifecycle-callbacks.mdx +124 -2
- package/docs/07-reference/01-ai-sdk-core/14-extract.mdx +13 -4
- package/docs/07-reference/02-ai-sdk-ui/05-use-realtime.mdx +6 -2
- package/docs/07-reference/05-ai-sdk-errors/ai-extraction-refusal-error.mdx +33 -0
- package/docs/07-reference/05-ai-sdk-errors/ai-extraction-unsupported-field-type-error.mdx +36 -0
- package/docs/07-reference/05-ai-sdk-errors/ai-invalid-tool-approval-signature-error.mdx +1 -0
- package/package.json +13 -13
- package/src/agent/tool-loop-agent-settings.ts +2 -1
- package/src/extract/extract-events.ts +135 -0
- package/src/extract/extract.ts +177 -74
- package/src/extract/index.ts +6 -0
- package/src/extract/restricted-telemetry-dispatcher.ts +97 -0
- package/src/generate-text/execute-tools-from-stream.ts +14 -8
- package/src/generate-text/generate-text.ts +26 -10
- package/src/generate-text/stream-language-model-call.ts +3 -0
- package/src/generate-text/stream-text.ts +11 -2
- package/src/realtime/browser-realtime-live-websocket.ts +23 -5
- package/src/realtime/realtime-session.ts +68 -29
- package/src/telemetry/create-telemetry-dispatcher.ts +12 -0
- package/src/telemetry/filter-telemetry-event.ts +2 -0
- package/src/telemetry/redact-telemetry-credentials.ts +13 -1
- package/src/telemetry/telemetry.ts +34 -0
- package/src/telemetry/tracing-channel.ts +2 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/internal/index.js.map +0 -1
|
@@ -0,0 +1,4213 @@
|
|
|
1
|
+
import { GatewayError, gateway } from "@ai-sdk/gateway";
|
|
2
|
+
import { DEFAULT_MAX_DOWNLOAD_SIZE, DownloadError, asArray, asSchema, cancelResponseBody, convertBase64ToUint8Array, convertUint8ArrayToBase64, detectMediaType, experimental_getToolCaller, fetchUntrustedUrl, filterNullable, getRuntimeEnvironmentUserAgent, isArrayBuffer, isBuffer, isExecutableTool, isFullMediaType, isProviderReference, isUint8Array, isUrlSupported, jsonSchema, readResponseWithSizeLimit, redactTelemetryValue, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, tool, validateTypes, withUserAgentSuffix } from "@ai-sdk/provider-utils";
|
|
3
|
+
import { AISDKError, APICallError, InvalidPromptError, NoSuchModelError, getErrorMessage as getErrorMessage$1 } from "@ai-sdk/provider";
|
|
4
|
+
//#region src/error/invalid-argument-error.ts
|
|
5
|
+
const name$11 = "AI_InvalidArgumentError";
|
|
6
|
+
const marker$11 = `vercel.ai.error.${name$11}`;
|
|
7
|
+
const symbol$11 = Symbol.for(marker$11);
|
|
8
|
+
var InvalidArgumentError = class extends AISDKError {
|
|
9
|
+
constructor({ parameter, value, message }) {
|
|
10
|
+
super({
|
|
11
|
+
name: name$11,
|
|
12
|
+
message: `Invalid argument for parameter ${parameter}: ${message}`
|
|
13
|
+
});
|
|
14
|
+
this[symbol$11] = true;
|
|
15
|
+
this.parameter = parameter;
|
|
16
|
+
this.value = value;
|
|
17
|
+
}
|
|
18
|
+
static isInstance(error) {
|
|
19
|
+
return AISDKError.hasMarker(error, marker$11);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/error/invalid-tool-approval-error.ts
|
|
24
|
+
const name$10 = "AI_InvalidToolApprovalError";
|
|
25
|
+
const marker$10 = `vercel.ai.error.${name$10}`;
|
|
26
|
+
const symbol$10 = Symbol.for(marker$10);
|
|
27
|
+
var InvalidToolApprovalError = class extends AISDKError {
|
|
28
|
+
constructor({ approvalId }) {
|
|
29
|
+
super({
|
|
30
|
+
name: name$10,
|
|
31
|
+
message: `Tool approval response references unknown approvalId: "${approvalId}". No matching tool-approval-request found in message history.`
|
|
32
|
+
});
|
|
33
|
+
this[symbol$10] = true;
|
|
34
|
+
this.approvalId = approvalId;
|
|
35
|
+
}
|
|
36
|
+
static isInstance(error) {
|
|
37
|
+
return AISDKError.hasMarker(error, marker$10);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
//#endregion
|
|
41
|
+
//#region src/error/invalid-tool-approval-signature-error.ts
|
|
42
|
+
const name$9 = "AI_InvalidToolApprovalSignatureError";
|
|
43
|
+
const marker$9 = `vercel.ai.error.${name$9}`;
|
|
44
|
+
const symbol$9 = Symbol.for(marker$9);
|
|
45
|
+
var InvalidToolApprovalSignatureError = class extends AISDKError {
|
|
46
|
+
constructor({ approvalId, toolCallId, reason }) {
|
|
47
|
+
super({
|
|
48
|
+
name: name$9,
|
|
49
|
+
message: `Tool approval signature verification failed for approval "${approvalId}" (tool call "${toolCallId}"): ${reason}`
|
|
50
|
+
});
|
|
51
|
+
this[symbol$9] = true;
|
|
52
|
+
this.approvalId = approvalId;
|
|
53
|
+
this.toolCallId = toolCallId;
|
|
54
|
+
}
|
|
55
|
+
static isInstance(error) {
|
|
56
|
+
return AISDKError.hasMarker(error, marker$9);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region src/error/invalid-tool-input-error.ts
|
|
61
|
+
const name$8 = "AI_InvalidToolInputError";
|
|
62
|
+
const marker$8 = `vercel.ai.error.${name$8}`;
|
|
63
|
+
const symbol$8 = Symbol.for(marker$8);
|
|
64
|
+
var InvalidToolInputError = class extends AISDKError {
|
|
65
|
+
constructor({ toolInput, toolName, cause, message = `Invalid input for tool ${toolName}: ${getErrorMessage$1(cause)}` }) {
|
|
66
|
+
super({
|
|
67
|
+
name: name$8,
|
|
68
|
+
message,
|
|
69
|
+
cause
|
|
70
|
+
});
|
|
71
|
+
this[symbol$8] = true;
|
|
72
|
+
this.toolInput = toolInput;
|
|
73
|
+
this.toolName = toolName;
|
|
74
|
+
}
|
|
75
|
+
static isInstance(error) {
|
|
76
|
+
return AISDKError.hasMarker(error, marker$8);
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
//#endregion
|
|
80
|
+
//#region src/error/tool-call-not-found-for-approval-error.ts
|
|
81
|
+
const name$7 = "AI_ToolCallNotFoundForApprovalError";
|
|
82
|
+
const marker$7 = `vercel.ai.error.${name$7}`;
|
|
83
|
+
const symbol$7 = Symbol.for(marker$7);
|
|
84
|
+
var ToolCallNotFoundForApprovalError = class extends AISDKError {
|
|
85
|
+
constructor({ toolCallId, approvalId }) {
|
|
86
|
+
super({
|
|
87
|
+
name: name$7,
|
|
88
|
+
message: `Tool call "${toolCallId}" not found for approval request "${approvalId}".`
|
|
89
|
+
});
|
|
90
|
+
this[symbol$7] = true;
|
|
91
|
+
this.toolCallId = toolCallId;
|
|
92
|
+
this.approvalId = approvalId;
|
|
93
|
+
}
|
|
94
|
+
static isInstance(error) {
|
|
95
|
+
return AISDKError.hasMarker(error, marker$7);
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
//#endregion
|
|
99
|
+
//#region src/error/missing-tool-result-error.ts
|
|
100
|
+
const name$6 = "AI_MissingToolResultsError";
|
|
101
|
+
const marker$6 = `vercel.ai.error.${name$6}`;
|
|
102
|
+
const symbol$6 = Symbol.for(marker$6);
|
|
103
|
+
var MissingToolResultsError = class extends AISDKError {
|
|
104
|
+
constructor({ toolCallIds }) {
|
|
105
|
+
super({
|
|
106
|
+
name: name$6,
|
|
107
|
+
message: `Tool result${toolCallIds.length > 1 ? "s are" : " is"} missing for tool call${toolCallIds.length > 1 ? "s" : ""} ${toolCallIds.join(", ")}.`
|
|
108
|
+
});
|
|
109
|
+
this[symbol$6] = true;
|
|
110
|
+
this.toolCallIds = toolCallIds;
|
|
111
|
+
}
|
|
112
|
+
static isInstance(error) {
|
|
113
|
+
return AISDKError.hasMarker(error, marker$6);
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/error/no-output-generated-error.ts
|
|
118
|
+
const name$5 = "AI_NoOutputGeneratedError";
|
|
119
|
+
const marker$5 = `vercel.ai.error.${name$5}`;
|
|
120
|
+
const symbol$5 = Symbol.for(marker$5);
|
|
121
|
+
/**
|
|
122
|
+
* Thrown when no LLM output was generated, e.g. because of errors.
|
|
123
|
+
*/
|
|
124
|
+
var NoOutputGeneratedError = class extends AISDKError {
|
|
125
|
+
constructor({ message = "No output generated.", cause } = {}) {
|
|
126
|
+
super({
|
|
127
|
+
name: name$5,
|
|
128
|
+
message,
|
|
129
|
+
cause
|
|
130
|
+
});
|
|
131
|
+
this[symbol$5] = true;
|
|
132
|
+
}
|
|
133
|
+
static isInstance(error) {
|
|
134
|
+
return AISDKError.hasMarker(error, marker$5);
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
//#endregion
|
|
138
|
+
//#region src/error/no-such-tool-error.ts
|
|
139
|
+
const name$4 = "AI_NoSuchToolError";
|
|
140
|
+
const marker$4 = `vercel.ai.error.${name$4}`;
|
|
141
|
+
const symbol$4 = Symbol.for(marker$4);
|
|
142
|
+
var NoSuchToolError = class extends AISDKError {
|
|
143
|
+
constructor({ toolName, availableTools = void 0, message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? "No tools are available." : `Available tools: ${availableTools.join(", ")}.`}` }) {
|
|
144
|
+
super({
|
|
145
|
+
name: name$4,
|
|
146
|
+
message
|
|
147
|
+
});
|
|
148
|
+
this[symbol$4] = true;
|
|
149
|
+
this.toolName = toolName;
|
|
150
|
+
this.availableTools = availableTools;
|
|
151
|
+
}
|
|
152
|
+
static isInstance(error) {
|
|
153
|
+
return AISDKError.hasMarker(error, marker$4);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
//#endregion
|
|
157
|
+
//#region src/error/tool-call-repair-error.ts
|
|
158
|
+
const name$3 = "AI_ToolCallRepairError";
|
|
159
|
+
const marker$3 = `vercel.ai.error.${name$3}`;
|
|
160
|
+
const symbol$3 = Symbol.for(marker$3);
|
|
161
|
+
var ToolCallRepairError = class extends AISDKError {
|
|
162
|
+
constructor({ cause, originalError, message = `Error repairing tool call: ${getErrorMessage$1(cause)}` }) {
|
|
163
|
+
super({
|
|
164
|
+
name: name$3,
|
|
165
|
+
message,
|
|
166
|
+
cause
|
|
167
|
+
});
|
|
168
|
+
this[symbol$3] = true;
|
|
169
|
+
this.originalError = originalError;
|
|
170
|
+
}
|
|
171
|
+
static isInstance(error) {
|
|
172
|
+
return AISDKError.hasMarker(error, marker$3);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
//#endregion
|
|
176
|
+
//#region src/error/unsupported-model-version-error.ts
|
|
177
|
+
/**
|
|
178
|
+
* Error that is thrown when a model with an unsupported version is used.
|
|
179
|
+
*/
|
|
180
|
+
var UnsupportedModelVersionError = class extends AISDKError {
|
|
181
|
+
constructor(options) {
|
|
182
|
+
super({
|
|
183
|
+
name: "AI_UnsupportedModelVersionError",
|
|
184
|
+
message: `Unsupported model version ${options.version} for provider "${options.provider}" and model "${options.modelId}". AI SDK 5 only supports models that implement specification version "v2".`
|
|
185
|
+
});
|
|
186
|
+
this.version = options.version;
|
|
187
|
+
this.provider = options.provider;
|
|
188
|
+
this.modelId = options.modelId;
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
//#endregion
|
|
192
|
+
//#region src/prompt/invalid-data-content-error.ts
|
|
193
|
+
const name$2 = "AI_InvalidDataContentError";
|
|
194
|
+
const marker$2 = `vercel.ai.error.${name$2}`;
|
|
195
|
+
const symbol$2 = Symbol.for(marker$2);
|
|
196
|
+
var InvalidDataContentError = class extends AISDKError {
|
|
197
|
+
constructor({ content, cause, message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.` }) {
|
|
198
|
+
super({
|
|
199
|
+
name: name$2,
|
|
200
|
+
message,
|
|
201
|
+
cause
|
|
202
|
+
});
|
|
203
|
+
this[symbol$2] = true;
|
|
204
|
+
this.content = content;
|
|
205
|
+
}
|
|
206
|
+
static isInstance(error) {
|
|
207
|
+
return AISDKError.hasMarker(error, marker$2);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
//#endregion
|
|
211
|
+
//#region src/prompt/invalid-message-role-error.ts
|
|
212
|
+
const name$1 = "AI_InvalidMessageRoleError";
|
|
213
|
+
const marker$1 = `vercel.ai.error.${name$1}`;
|
|
214
|
+
const symbol$1 = Symbol.for(marker$1);
|
|
215
|
+
var InvalidMessageRoleError = class extends AISDKError {
|
|
216
|
+
constructor({ role, message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".` }) {
|
|
217
|
+
super({
|
|
218
|
+
name: name$1,
|
|
219
|
+
message
|
|
220
|
+
});
|
|
221
|
+
this[symbol$1] = true;
|
|
222
|
+
this.role = role;
|
|
223
|
+
}
|
|
224
|
+
static isInstance(error) {
|
|
225
|
+
return AISDKError.hasMarker(error, marker$1);
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
//#endregion
|
|
229
|
+
//#region src/util/retry-error.ts
|
|
230
|
+
const name = "AI_RetryError";
|
|
231
|
+
const marker = `vercel.ai.error.${name}`;
|
|
232
|
+
const symbol = Symbol.for(marker);
|
|
233
|
+
var RetryError = class extends AISDKError {
|
|
234
|
+
constructor({ message, reason, errors }) {
|
|
235
|
+
super({
|
|
236
|
+
name,
|
|
237
|
+
message
|
|
238
|
+
});
|
|
239
|
+
this[symbol] = true;
|
|
240
|
+
this.reason = reason;
|
|
241
|
+
this.errors = errors;
|
|
242
|
+
this.lastError = errors[errors.length - 1];
|
|
243
|
+
}
|
|
244
|
+
static isInstance(error) {
|
|
245
|
+
return AISDKError.hasMarker(error, marker);
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
//#endregion
|
|
249
|
+
//#region src/logger/deprecations.ts
|
|
250
|
+
const deprecationCodes = /* @__PURE__ */ new Map([
|
|
251
|
+
["generateObject", "AISDK_DEP_GENERATE_OBJECT"],
|
|
252
|
+
["streamObject", "AISDK_DEP_STREAM_OBJECT"],
|
|
253
|
+
["experimental_generateSpeech", "AISDK_DEP_EXPERIMENTAL_GENERATE_SPEECH"],
|
|
254
|
+
["experimental_transcribe", "AISDK_DEP_EXPERIMENTAL_TRANSCRIBE"],
|
|
255
|
+
["\"image\" content part", "AISDK_DEP_IMAGE_CONTENT_PART"],
|
|
256
|
+
["\"tool-result\" content of type \"file-data\"", "AISDK_DEP_TOOL_RESULT_FILE_DATA"],
|
|
257
|
+
["\"tool-result\" content of type \"file-url\"", "AISDK_DEP_TOOL_RESULT_FILE_URL"],
|
|
258
|
+
["\"tool-result\" content of type \"file-id\"", "AISDK_DEP_TOOL_RESULT_FILE_ID"],
|
|
259
|
+
["\"tool-result\" content of type \"file-reference\"", "AISDK_DEP_TOOL_RESULT_FILE_REFERENCE"],
|
|
260
|
+
["\"tool-result\" content of type \"image-data\"", "AISDK_DEP_TOOL_RESULT_IMAGE_DATA"],
|
|
261
|
+
["\"tool-result\" content of type \"image-url\"", "AISDK_DEP_TOOL_RESULT_IMAGE_URL"],
|
|
262
|
+
["\"tool-result\" content of type \"image-file-id\"", "AISDK_DEP_TOOL_RESULT_IMAGE_FILE_ID"],
|
|
263
|
+
["\"tool-result\" content of type \"image-file-reference\"", "AISDK_DEP_TOOL_RESULT_IMAGE_FILE_REFERENCE"],
|
|
264
|
+
["rawInput in output-error UI message parts", "AISDK_DEP_UI_MESSAGE_RAW_INPUT"]
|
|
265
|
+
]);
|
|
266
|
+
/**
|
|
267
|
+
* Escape punctuation and UTF-16 code units without losing case or collapsing
|
|
268
|
+
* distinct settings. Underscores are escaped too, so `__` separates code parts.
|
|
269
|
+
*/
|
|
270
|
+
function encodeCodePart(value) {
|
|
271
|
+
return value.replace(/[^a-zA-Z0-9]/g, (character) => `_${character.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}`);
|
|
272
|
+
}
|
|
273
|
+
function getDeprecationCode({ setting, provider }) {
|
|
274
|
+
if (provider == null) return deprecationCodes.get(setting) ?? `AISDK_DEP_SETTING_${encodeCodePart(setting)}`;
|
|
275
|
+
return `AISDK_DEP_PROVIDER_${encodeCodePart(provider)}__${encodeCodePart(setting)}`;
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
//#region src/logger/log-warnings.ts
|
|
279
|
+
/**
|
|
280
|
+
* Formats a warning object into a human-readable string with clear AI SDK branding.
|
|
281
|
+
*
|
|
282
|
+
* @param options - The options for formatting the warning.
|
|
283
|
+
* @param options.warning - The warning to format.
|
|
284
|
+
* @param options.provider - The provider id used for the call, if scoped to a specific provider.
|
|
285
|
+
* @param options.model - The model id used for the call, if scoped to a specific provider.
|
|
286
|
+
* @returns A formatted warning message string.
|
|
287
|
+
*/
|
|
288
|
+
function formatWarning({ warning, provider, model }) {
|
|
289
|
+
const prefix = `AI SDK Warning${provider != null && model != null ? ` (${provider} / ${model})` : ""}:`;
|
|
290
|
+
switch (warning.type) {
|
|
291
|
+
case "unsupported": {
|
|
292
|
+
let message = `${prefix} The feature "${warning.feature}" is not supported.`;
|
|
293
|
+
if (warning.details) message += ` ${warning.details}`;
|
|
294
|
+
return message;
|
|
295
|
+
}
|
|
296
|
+
case "compatibility": {
|
|
297
|
+
let message = `${prefix} The feature "${warning.feature}" is used in a compatibility mode.`;
|
|
298
|
+
if (warning.details) message += ` ${warning.details}`;
|
|
299
|
+
return message;
|
|
300
|
+
}
|
|
301
|
+
case "deprecated": return `${prefix} Deprecated: "${warning.setting}". ${warning.message}`;
|
|
302
|
+
case "other": return `${prefix} ${warning.message}`;
|
|
303
|
+
default: return `${prefix} ${JSON.stringify(warning, null, 2)}`;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const FIRST_WARNING_INFO_MESSAGE = "AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.";
|
|
307
|
+
let hasLoggedBefore = false;
|
|
308
|
+
const emittedDeprecationCodes = /* @__PURE__ */ new Set();
|
|
309
|
+
function emitWarning({ message, type, code }) {
|
|
310
|
+
if (typeof process !== "undefined" && typeof process.emitWarning === "function") process.emitWarning(message, code == null ? { type } : {
|
|
311
|
+
type,
|
|
312
|
+
code
|
|
313
|
+
});
|
|
314
|
+
else console.warn(code == null ? message : `[${code}] ${message}`);
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Logs warnings to the console or uses a custom logger if configured.
|
|
318
|
+
*
|
|
319
|
+
* The behavior can be customized via the `AI_SDK_LOG_WARNINGS` global variable:
|
|
320
|
+
* - If set to `false`, warnings are suppressed.
|
|
321
|
+
* - If set to a function, that function is called with the warnings.
|
|
322
|
+
* - Otherwise, warnings use `process.emitWarning` when available, falling back
|
|
323
|
+
* to `console.warn`. Deprecations have stable codes and are emitted once per
|
|
324
|
+
* code by the default logger. Custom loggers receive every warning.
|
|
325
|
+
*
|
|
326
|
+
* @param options - The options containing warnings and context.
|
|
327
|
+
* @param options.warnings - The warnings to log.
|
|
328
|
+
* @param options.provider - The provider id used for the call, if scoped to a specific provider.
|
|
329
|
+
* @param options.model - The model id used for the call, if scoped to a specific provider.
|
|
330
|
+
*/
|
|
331
|
+
const logWarnings = (options) => {
|
|
332
|
+
if (options.warnings.length === 0) return;
|
|
333
|
+
const logger = globalThis.AI_SDK_LOG_WARNINGS;
|
|
334
|
+
if (logger === false) return;
|
|
335
|
+
if (typeof logger === "function") {
|
|
336
|
+
logger(options);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if (!hasLoggedBefore) {
|
|
340
|
+
hasLoggedBefore = true;
|
|
341
|
+
emitWarning({
|
|
342
|
+
message: FIRST_WARNING_INFO_MESSAGE,
|
|
343
|
+
type: "Warning"
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
for (const warning of options.warnings) {
|
|
347
|
+
const code = warning.type === "deprecated" ? getDeprecationCode({
|
|
348
|
+
setting: warning.setting,
|
|
349
|
+
provider: options.provider
|
|
350
|
+
}) : void 0;
|
|
351
|
+
if (code != null) {
|
|
352
|
+
if (emittedDeprecationCodes.has(code)) continue;
|
|
353
|
+
emittedDeprecationCodes.add(code);
|
|
354
|
+
}
|
|
355
|
+
emitWarning({
|
|
356
|
+
message: formatWarning({
|
|
357
|
+
warning,
|
|
358
|
+
provider: options.provider,
|
|
359
|
+
model: options.model
|
|
360
|
+
}),
|
|
361
|
+
type: warning.type === "deprecated" ? "DeprecationWarning" : "Warning",
|
|
362
|
+
code
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
//#endregion
|
|
367
|
+
//#region src/util/log-v2-compatibility-warning.ts
|
|
368
|
+
function logV2CompatibilityWarning({ provider, modelId }) {
|
|
369
|
+
logWarnings({
|
|
370
|
+
warnings: [{
|
|
371
|
+
type: "compatibility",
|
|
372
|
+
feature: "specificationVersion",
|
|
373
|
+
details: `Using v2 specification compatibility mode. Some features may not be available.`
|
|
374
|
+
}],
|
|
375
|
+
provider,
|
|
376
|
+
model: modelId
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
//#endregion
|
|
380
|
+
//#region src/model/as-embedding-model-v3.ts
|
|
381
|
+
function asEmbeddingModelV3(model) {
|
|
382
|
+
if (model.specificationVersion === "v3") return model;
|
|
383
|
+
logV2CompatibilityWarning({
|
|
384
|
+
provider: model.provider,
|
|
385
|
+
modelId: model.modelId
|
|
386
|
+
});
|
|
387
|
+
return new Proxy(model, { get(target, prop) {
|
|
388
|
+
if (prop === "specificationVersion") return "v3";
|
|
389
|
+
return target[prop];
|
|
390
|
+
} });
|
|
391
|
+
}
|
|
392
|
+
//#endregion
|
|
393
|
+
//#region src/model/as-embedding-model-v4.ts
|
|
394
|
+
function asEmbeddingModelV4(model) {
|
|
395
|
+
if (model.specificationVersion === "v4") return model;
|
|
396
|
+
const v3Model = model.specificationVersion === "v2" ? asEmbeddingModelV3(model) : model;
|
|
397
|
+
return new Proxy(v3Model, { get(target, prop) {
|
|
398
|
+
if (prop === "specificationVersion") return "v4";
|
|
399
|
+
return target[prop];
|
|
400
|
+
} });
|
|
401
|
+
}
|
|
402
|
+
//#endregion
|
|
403
|
+
//#region src/model/as-image-model-v3.ts
|
|
404
|
+
function asImageModelV3(model) {
|
|
405
|
+
if (model.specificationVersion === "v3") return model;
|
|
406
|
+
logV2CompatibilityWarning({
|
|
407
|
+
provider: model.provider,
|
|
408
|
+
modelId: model.modelId
|
|
409
|
+
});
|
|
410
|
+
return new Proxy(model, { get(target, prop) {
|
|
411
|
+
if (prop === "specificationVersion") return "v3";
|
|
412
|
+
return target[prop];
|
|
413
|
+
} });
|
|
414
|
+
}
|
|
415
|
+
//#endregion
|
|
416
|
+
//#region src/model/as-image-model-v4.ts
|
|
417
|
+
function asImageModelV4(model) {
|
|
418
|
+
if (model.specificationVersion === "v4") return model;
|
|
419
|
+
const v3Model = model.specificationVersion === "v2" ? asImageModelV3(model) : model;
|
|
420
|
+
return new Proxy(v3Model, { get(target, prop) {
|
|
421
|
+
if (prop === "specificationVersion") return "v4";
|
|
422
|
+
return target[prop];
|
|
423
|
+
} });
|
|
424
|
+
}
|
|
425
|
+
//#endregion
|
|
426
|
+
//#region src/model/as-language-model-v3.ts
|
|
427
|
+
function asLanguageModelV3(model) {
|
|
428
|
+
if (model.specificationVersion === "v3") return model;
|
|
429
|
+
logV2CompatibilityWarning({
|
|
430
|
+
provider: model.provider,
|
|
431
|
+
modelId: model.modelId
|
|
432
|
+
});
|
|
433
|
+
return new Proxy(model, { get(target, prop) {
|
|
434
|
+
switch (prop) {
|
|
435
|
+
case "specificationVersion": return "v3";
|
|
436
|
+
case "doGenerate": return async (...args) => {
|
|
437
|
+
const result = await target.doGenerate(...args);
|
|
438
|
+
return {
|
|
439
|
+
...result,
|
|
440
|
+
finishReason: convertV2FinishReasonToV3(result.finishReason),
|
|
441
|
+
usage: convertV2UsageToV3(result.usage)
|
|
442
|
+
};
|
|
443
|
+
};
|
|
444
|
+
case "doStream": return async (...args) => {
|
|
445
|
+
const result = await target.doStream(...args);
|
|
446
|
+
return {
|
|
447
|
+
...result,
|
|
448
|
+
stream: convertV2StreamToV3(result.stream)
|
|
449
|
+
};
|
|
450
|
+
};
|
|
451
|
+
default: return target[prop];
|
|
452
|
+
}
|
|
453
|
+
} });
|
|
454
|
+
}
|
|
455
|
+
function convertV2StreamToV3(stream) {
|
|
456
|
+
return stream.pipeThrough(new TransformStream({ transform(chunk, controller) {
|
|
457
|
+
switch (chunk.type) {
|
|
458
|
+
case "finish":
|
|
459
|
+
controller.enqueue({
|
|
460
|
+
...chunk,
|
|
461
|
+
finishReason: convertV2FinishReasonToV3(chunk.finishReason),
|
|
462
|
+
usage: convertV2UsageToV3(chunk.usage)
|
|
463
|
+
});
|
|
464
|
+
break;
|
|
465
|
+
default: controller.enqueue(chunk);
|
|
466
|
+
}
|
|
467
|
+
} }));
|
|
468
|
+
}
|
|
469
|
+
function convertV2FinishReasonToV3(finishReason) {
|
|
470
|
+
return {
|
|
471
|
+
unified: finishReason === "unknown" ? "other" : finishReason,
|
|
472
|
+
raw: void 0
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
function convertV2UsageToV3(usage) {
|
|
476
|
+
return {
|
|
477
|
+
inputTokens: {
|
|
478
|
+
total: usage.inputTokens,
|
|
479
|
+
noCache: void 0,
|
|
480
|
+
cacheRead: usage.cachedInputTokens,
|
|
481
|
+
cacheWrite: void 0
|
|
482
|
+
},
|
|
483
|
+
outputTokens: {
|
|
484
|
+
total: usage.outputTokens,
|
|
485
|
+
text: void 0,
|
|
486
|
+
reasoning: usage.reasoningTokens
|
|
487
|
+
},
|
|
488
|
+
raw: usage.totalTokens == null ? void 0 : { totalTokens: usage.totalTokens }
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
//#endregion
|
|
492
|
+
//#region src/model/as-language-model-v4.ts
|
|
493
|
+
function asLanguageModelV4(model) {
|
|
494
|
+
if (model.specificationVersion === "v4") return model;
|
|
495
|
+
const v3Model = model.specificationVersion === "v2" ? asLanguageModelV3(model) : model;
|
|
496
|
+
return new Proxy(v3Model, { get(target, prop) {
|
|
497
|
+
switch (prop) {
|
|
498
|
+
case "specificationVersion": return "v4";
|
|
499
|
+
case "doGenerate": return async (options) => {
|
|
500
|
+
const result = await target.doGenerate({
|
|
501
|
+
...options,
|
|
502
|
+
prompt: convertV4PromptToV3(options.prompt)
|
|
503
|
+
});
|
|
504
|
+
return {
|
|
505
|
+
...result,
|
|
506
|
+
content: result.content.map(convertV3ContentToV4)
|
|
507
|
+
};
|
|
508
|
+
};
|
|
509
|
+
case "doStream": return async (options) => {
|
|
510
|
+
const result = await target.doStream({
|
|
511
|
+
...options,
|
|
512
|
+
prompt: convertV4PromptToV3(options.prompt)
|
|
513
|
+
});
|
|
514
|
+
return {
|
|
515
|
+
...result,
|
|
516
|
+
stream: convertV3StreamToV4(result.stream)
|
|
517
|
+
};
|
|
518
|
+
};
|
|
519
|
+
default: return target[prop];
|
|
520
|
+
}
|
|
521
|
+
} });
|
|
522
|
+
}
|
|
523
|
+
function convertV4PromptToV3(prompt) {
|
|
524
|
+
return prompt.map((message) => {
|
|
525
|
+
if (message.role === "system") return message;
|
|
526
|
+
return {
|
|
527
|
+
...message,
|
|
528
|
+
content: message.content.map((part) => {
|
|
529
|
+
switch (part.type) {
|
|
530
|
+
case "file": return {
|
|
531
|
+
...part,
|
|
532
|
+
data: convertV4FileDataToV3(part.data)
|
|
533
|
+
};
|
|
534
|
+
case "tool-result": return {
|
|
535
|
+
...part,
|
|
536
|
+
output: convertV4ToolResultOutputToV3(part.output)
|
|
537
|
+
};
|
|
538
|
+
default: return part;
|
|
539
|
+
}
|
|
540
|
+
})
|
|
541
|
+
};
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
function convertV4FileDataToV3(data) {
|
|
545
|
+
switch (data.type) {
|
|
546
|
+
case "data": return data.data;
|
|
547
|
+
case "url": return data.url;
|
|
548
|
+
case "reference":
|
|
549
|
+
case "text": return data;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
function convertV4ToolResultOutputToV3(output) {
|
|
553
|
+
if (output.type !== "content") return output;
|
|
554
|
+
return {
|
|
555
|
+
...output,
|
|
556
|
+
value: output.value.map((part) => {
|
|
557
|
+
if (part.type !== "file") return part;
|
|
558
|
+
switch (part.data.type) {
|
|
559
|
+
case "data": return {
|
|
560
|
+
type: "file-data",
|
|
561
|
+
data: typeof part.data.data === "string" ? part.data.data : convertUint8ArrayToBase64(part.data.data),
|
|
562
|
+
mediaType: part.mediaType,
|
|
563
|
+
filename: part.filename,
|
|
564
|
+
providerOptions: part.providerOptions
|
|
565
|
+
};
|
|
566
|
+
case "url": return {
|
|
567
|
+
type: "file-url",
|
|
568
|
+
url: part.data.url.toString(),
|
|
569
|
+
providerOptions: part.providerOptions
|
|
570
|
+
};
|
|
571
|
+
case "reference": return {
|
|
572
|
+
type: "file-id",
|
|
573
|
+
fileId: part.data.reference,
|
|
574
|
+
providerOptions: part.providerOptions
|
|
575
|
+
};
|
|
576
|
+
case "text": return part;
|
|
577
|
+
}
|
|
578
|
+
})
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
function convertV3ContentToV4(content) {
|
|
582
|
+
return content.type === "file" ? {
|
|
583
|
+
...content,
|
|
584
|
+
data: {
|
|
585
|
+
type: "data",
|
|
586
|
+
data: content.data
|
|
587
|
+
}
|
|
588
|
+
} : content;
|
|
589
|
+
}
|
|
590
|
+
function convertV3StreamToV4(stream) {
|
|
591
|
+
return stream.pipeThrough(new TransformStream({ transform(chunk, controller) {
|
|
592
|
+
controller.enqueue(chunk.type === "file" ? {
|
|
593
|
+
...chunk,
|
|
594
|
+
data: {
|
|
595
|
+
type: "data",
|
|
596
|
+
data: chunk.data
|
|
597
|
+
}
|
|
598
|
+
} : chunk);
|
|
599
|
+
} }));
|
|
600
|
+
}
|
|
601
|
+
//#endregion
|
|
602
|
+
//#region src/model/as-reranking-model-v4.ts
|
|
603
|
+
function asRerankingModelV4(model) {
|
|
604
|
+
if (model.specificationVersion === "v4") return model;
|
|
605
|
+
return new Proxy(model, { get(target, prop) {
|
|
606
|
+
if (prop === "specificationVersion") return "v4";
|
|
607
|
+
return target[prop];
|
|
608
|
+
} });
|
|
609
|
+
}
|
|
610
|
+
//#endregion
|
|
611
|
+
//#region src/model/as-speech-model-v3.ts
|
|
612
|
+
function asSpeechModelV3(model) {
|
|
613
|
+
if (model.specificationVersion === "v3") return model;
|
|
614
|
+
logV2CompatibilityWarning({
|
|
615
|
+
provider: model.provider,
|
|
616
|
+
modelId: model.modelId
|
|
617
|
+
});
|
|
618
|
+
return new Proxy(model, { get(target, prop) {
|
|
619
|
+
if (prop === "specificationVersion") return "v3";
|
|
620
|
+
return target[prop];
|
|
621
|
+
} });
|
|
622
|
+
}
|
|
623
|
+
//#endregion
|
|
624
|
+
//#region src/model/as-speech-model-v4.ts
|
|
625
|
+
function asSpeechModelV4(model) {
|
|
626
|
+
if (model.specificationVersion === "v4") return model;
|
|
627
|
+
const v3Model = model.specificationVersion === "v2" ? asSpeechModelV3(model) : model;
|
|
628
|
+
return new Proxy(v3Model, { get(target, prop) {
|
|
629
|
+
if (prop === "specificationVersion") return "v4";
|
|
630
|
+
return target[prop];
|
|
631
|
+
} });
|
|
632
|
+
}
|
|
633
|
+
//#endregion
|
|
634
|
+
//#region src/model/as-transcription-model-v3.ts
|
|
635
|
+
function asTranscriptionModelV3(model) {
|
|
636
|
+
if (model.specificationVersion === "v3") return model;
|
|
637
|
+
logV2CompatibilityWarning({
|
|
638
|
+
provider: model.provider,
|
|
639
|
+
modelId: model.modelId
|
|
640
|
+
});
|
|
641
|
+
return new Proxy(model, { get(target, prop) {
|
|
642
|
+
if (prop === "specificationVersion") return "v3";
|
|
643
|
+
return target[prop];
|
|
644
|
+
} });
|
|
645
|
+
}
|
|
646
|
+
//#endregion
|
|
647
|
+
//#region src/model/as-transcription-model-v4.ts
|
|
648
|
+
function asTranscriptionModelV4(model) {
|
|
649
|
+
if (model.specificationVersion === "v4") return model;
|
|
650
|
+
const v3Model = model.specificationVersion === "v2" ? asTranscriptionModelV3(model) : model;
|
|
651
|
+
return new Proxy(v3Model, { get(target, prop) {
|
|
652
|
+
if (prop === "specificationVersion") return "v4";
|
|
653
|
+
if (prop === "doGenerate") return async ({ timestampGranularities, ...options }) => {
|
|
654
|
+
const result = await target.doGenerate.call(model, options);
|
|
655
|
+
if (!timestampGranularities?.length) return result;
|
|
656
|
+
return {
|
|
657
|
+
...result,
|
|
658
|
+
warnings: [...result.warnings, {
|
|
659
|
+
type: "unsupported",
|
|
660
|
+
feature: "timestampGranularities",
|
|
661
|
+
details: `Shared timestamp granularities are not supported by ${model.specificationVersion} transcription models.`
|
|
662
|
+
}]
|
|
663
|
+
};
|
|
664
|
+
};
|
|
665
|
+
return target[prop];
|
|
666
|
+
} });
|
|
667
|
+
}
|
|
668
|
+
//#endregion
|
|
669
|
+
//#region src/model/as-video-model-v4.ts
|
|
670
|
+
function asVideoModelV4(model) {
|
|
671
|
+
if (model.specificationVersion === "v4") return model;
|
|
672
|
+
return new Proxy(model, { get(target, prop) {
|
|
673
|
+
if (prop === "specificationVersion") return "v4";
|
|
674
|
+
return target[prop];
|
|
675
|
+
} });
|
|
676
|
+
}
|
|
677
|
+
//#endregion
|
|
678
|
+
//#region src/model/as-provider-v3.ts
|
|
679
|
+
function asProviderV3(provider) {
|
|
680
|
+
if ("specificationVersion" in provider && provider.specificationVersion === "v3") return provider;
|
|
681
|
+
const v2Provider = provider;
|
|
682
|
+
return {
|
|
683
|
+
specificationVersion: "v3",
|
|
684
|
+
languageModel: (modelId) => asLanguageModelV3(v2Provider.languageModel(modelId)),
|
|
685
|
+
embeddingModel: (modelId) => asEmbeddingModelV3(v2Provider.textEmbeddingModel(modelId)),
|
|
686
|
+
imageModel: (modelId) => asImageModelV3(v2Provider.imageModel(modelId)),
|
|
687
|
+
transcriptionModel: v2Provider.transcriptionModel ? (modelId) => asTranscriptionModelV3(v2Provider.transcriptionModel(modelId)) : void 0,
|
|
688
|
+
speechModel: v2Provider.speechModel ? (modelId) => asSpeechModelV3(v2Provider.speechModel(modelId)) : void 0,
|
|
689
|
+
rerankingModel: void 0
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
//#endregion
|
|
693
|
+
//#region src/model/as-provider-v4.ts
|
|
694
|
+
function asProviderV4(provider) {
|
|
695
|
+
if ("specificationVersion" in provider && provider.specificationVersion === "v4") return provider;
|
|
696
|
+
const v3Provider = !("specificationVersion" in provider) || provider.specificationVersion !== "v3" ? asProviderV3(provider) : provider;
|
|
697
|
+
return {
|
|
698
|
+
specificationVersion: "v4",
|
|
699
|
+
languageModel: (modelId) => asLanguageModelV4(v3Provider.languageModel(modelId)),
|
|
700
|
+
embeddingModel: (modelId) => asEmbeddingModelV4(v3Provider.embeddingModel(modelId)),
|
|
701
|
+
imageModel: (modelId) => asImageModelV4(v3Provider.imageModel(modelId)),
|
|
702
|
+
transcriptionModel: v3Provider.transcriptionModel ? (modelId) => asTranscriptionModelV4(v3Provider.transcriptionModel(modelId)) : void 0,
|
|
703
|
+
speechModel: v3Provider.speechModel ? (modelId) => asSpeechModelV4(v3Provider.speechModel(modelId)) : void 0,
|
|
704
|
+
rerankingModel: v3Provider.rerankingModel ? (modelId) => asRerankingModelV4(v3Provider.rerankingModel(modelId)) : void 0
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
//#endregion
|
|
708
|
+
//#region src/model/resolve-model.ts
|
|
709
|
+
function resolveLanguageModel(model) {
|
|
710
|
+
if (typeof model === "string") return getGlobalProvider().languageModel(model);
|
|
711
|
+
if (![
|
|
712
|
+
"v4",
|
|
713
|
+
"v3",
|
|
714
|
+
"v2"
|
|
715
|
+
].includes(model.specificationVersion)) {
|
|
716
|
+
const unsupportedModel = model;
|
|
717
|
+
throw new UnsupportedModelVersionError({
|
|
718
|
+
version: unsupportedModel.specificationVersion,
|
|
719
|
+
provider: unsupportedModel.provider,
|
|
720
|
+
modelId: unsupportedModel.modelId
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
return asLanguageModelV4(model);
|
|
724
|
+
}
|
|
725
|
+
function resolveEmbeddingModel(model) {
|
|
726
|
+
if (typeof model === "string") return getGlobalProvider().embeddingModel(model);
|
|
727
|
+
if (![
|
|
728
|
+
"v4",
|
|
729
|
+
"v3",
|
|
730
|
+
"v2"
|
|
731
|
+
].includes(model.specificationVersion)) {
|
|
732
|
+
const unsupportedModel = model;
|
|
733
|
+
throw new UnsupportedModelVersionError({
|
|
734
|
+
version: unsupportedModel.specificationVersion,
|
|
735
|
+
provider: unsupportedModel.provider,
|
|
736
|
+
modelId: unsupportedModel.modelId
|
|
737
|
+
});
|
|
738
|
+
}
|
|
739
|
+
return asEmbeddingModelV4(model);
|
|
740
|
+
}
|
|
741
|
+
function resolveTranscriptionModel(model) {
|
|
742
|
+
if (typeof model === "string") return getGlobalProvider().transcriptionModel?.(model);
|
|
743
|
+
if (![
|
|
744
|
+
"v4",
|
|
745
|
+
"v3",
|
|
746
|
+
"v2"
|
|
747
|
+
].includes(model.specificationVersion)) {
|
|
748
|
+
const unsupportedModel = model;
|
|
749
|
+
throw new UnsupportedModelVersionError({
|
|
750
|
+
version: unsupportedModel.specificationVersion,
|
|
751
|
+
provider: unsupportedModel.provider,
|
|
752
|
+
modelId: unsupportedModel.modelId
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
return asTranscriptionModelV4(model);
|
|
756
|
+
}
|
|
757
|
+
function resolveSpeechTranslationModel(model) {
|
|
758
|
+
if (typeof model === "string") {
|
|
759
|
+
const speechTranslationModel = (globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway).speechTranslationModel;
|
|
760
|
+
if (!speechTranslationModel) throw new Error("The default provider does not support speech translation models. Please pass a provider model instance that implements the experimental speech translation model specification.");
|
|
761
|
+
return speechTranslationModel(model);
|
|
762
|
+
}
|
|
763
|
+
if (model.specificationVersion !== "v4") {
|
|
764
|
+
const unsupportedModel = model;
|
|
765
|
+
throw new UnsupportedModelVersionError({
|
|
766
|
+
version: unsupportedModel.specificationVersion,
|
|
767
|
+
provider: unsupportedModel.provider,
|
|
768
|
+
modelId: unsupportedModel.modelId
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
return model;
|
|
772
|
+
}
|
|
773
|
+
function resolveSpeechModel(model) {
|
|
774
|
+
if (typeof model === "string") return getGlobalProvider().speechModel?.(model);
|
|
775
|
+
if (![
|
|
776
|
+
"v4",
|
|
777
|
+
"v3",
|
|
778
|
+
"v2"
|
|
779
|
+
].includes(model.specificationVersion)) {
|
|
780
|
+
const unsupportedModel = model;
|
|
781
|
+
throw new UnsupportedModelVersionError({
|
|
782
|
+
version: unsupportedModel.specificationVersion,
|
|
783
|
+
provider: unsupportedModel.provider,
|
|
784
|
+
modelId: unsupportedModel.modelId
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
return asSpeechModelV4(model);
|
|
788
|
+
}
|
|
789
|
+
function resolveImageModel(model) {
|
|
790
|
+
if (typeof model === "string") return getGlobalProvider().imageModel(model);
|
|
791
|
+
if (![
|
|
792
|
+
"v4",
|
|
793
|
+
"v3",
|
|
794
|
+
"v2"
|
|
795
|
+
].includes(model.specificationVersion)) {
|
|
796
|
+
const unsupportedModel = model;
|
|
797
|
+
throw new UnsupportedModelVersionError({
|
|
798
|
+
version: unsupportedModel.specificationVersion,
|
|
799
|
+
provider: unsupportedModel.provider,
|
|
800
|
+
modelId: unsupportedModel.modelId
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
return asImageModelV4(model);
|
|
804
|
+
}
|
|
805
|
+
function resolveVideoModel(model) {
|
|
806
|
+
if (typeof model === "string") {
|
|
807
|
+
const videoModel = (globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway).videoModel;
|
|
808
|
+
if (!videoModel) throw new Error("The default provider does not support video models. Please use a Experimental_VideoModelV4 object from a provider (e.g., vertex.video(\"model-id\")).");
|
|
809
|
+
return videoModel(model);
|
|
810
|
+
}
|
|
811
|
+
if (!["v4", "v3"].includes(model.specificationVersion)) {
|
|
812
|
+
const unsupportedModel = model;
|
|
813
|
+
throw new UnsupportedModelVersionError({
|
|
814
|
+
version: unsupportedModel.specificationVersion,
|
|
815
|
+
provider: unsupportedModel.provider,
|
|
816
|
+
modelId: unsupportedModel.modelId
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
return asVideoModelV4(model);
|
|
820
|
+
}
|
|
821
|
+
function resolveRerankingModel(model) {
|
|
822
|
+
if (typeof model === "string") {
|
|
823
|
+
const rerankingModel = getGlobalProvider().rerankingModel;
|
|
824
|
+
if (!rerankingModel) throw new Error("The default provider does not support reranking models. Please use a RerankingModel object from a provider (e.g., gateway.rerankingModel(\"model-id\")).");
|
|
825
|
+
return rerankingModel(model);
|
|
826
|
+
}
|
|
827
|
+
if (model.specificationVersion !== "v4" && model.specificationVersion !== "v3") {
|
|
828
|
+
const unsupportedModel = model;
|
|
829
|
+
throw new UnsupportedModelVersionError({
|
|
830
|
+
version: unsupportedModel.specificationVersion,
|
|
831
|
+
provider: unsupportedModel.provider,
|
|
832
|
+
modelId: unsupportedModel.modelId
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
return asRerankingModelV4(model);
|
|
836
|
+
}
|
|
837
|
+
function resolveDecisionModel(model) {
|
|
838
|
+
if (typeof model === "string") {
|
|
839
|
+
const provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway;
|
|
840
|
+
const factory = provider.decisionModel ?? provider.evaluationModel;
|
|
841
|
+
if (typeof factory !== "function") throw new NoSuchModelError({
|
|
842
|
+
modelId: model,
|
|
843
|
+
modelType: "decisionModel",
|
|
844
|
+
message: "The default provider does not support decision models. Pass a decision model instance or configure AI_SDK_DEFAULT_PROVIDER with a decisionModel method."
|
|
845
|
+
});
|
|
846
|
+
const resolvedModel = factory.call(provider, model);
|
|
847
|
+
if (resolvedModel == null) throw new NoSuchModelError({
|
|
848
|
+
modelId: model,
|
|
849
|
+
modelType: "decisionModel"
|
|
850
|
+
});
|
|
851
|
+
model = resolvedModel;
|
|
852
|
+
}
|
|
853
|
+
if (model.specificationVersion !== "v4") throw new UnsupportedModelVersionError({
|
|
854
|
+
version: model.specificationVersion,
|
|
855
|
+
provider: model.provider,
|
|
856
|
+
modelId: model.modelId
|
|
857
|
+
});
|
|
858
|
+
if ("doDecide" in model) return model;
|
|
859
|
+
const legacyModel = model;
|
|
860
|
+
return {
|
|
861
|
+
specificationVersion: legacyModel.specificationVersion,
|
|
862
|
+
provider: legacyModel.provider,
|
|
863
|
+
modelId: legacyModel.modelId,
|
|
864
|
+
supportedQuestionTypes: legacyModel.supportedQuestionTypes,
|
|
865
|
+
doDecide: (options) => legacyModel.doEvaluate(options)
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
function resolveExtractionModel(model) {
|
|
869
|
+
if (typeof model === "string") {
|
|
870
|
+
const provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway;
|
|
871
|
+
if (typeof provider.extractionModel !== "function") throw new NoSuchModelError({
|
|
872
|
+
modelId: model,
|
|
873
|
+
modelType: "extractionModel",
|
|
874
|
+
message: "The default provider does not support extraction models. Pass an extraction model instance or configure AI_SDK_DEFAULT_PROVIDER with an extractionModel method."
|
|
875
|
+
});
|
|
876
|
+
const resolvedModel = provider.extractionModel(model);
|
|
877
|
+
if (resolvedModel == null) throw new NoSuchModelError({
|
|
878
|
+
modelId: model,
|
|
879
|
+
modelType: "extractionModel"
|
|
880
|
+
});
|
|
881
|
+
model = resolvedModel;
|
|
882
|
+
}
|
|
883
|
+
const version = model.specificationVersion;
|
|
884
|
+
if (version !== "v4") throw new UnsupportedModelVersionError({
|
|
885
|
+
version,
|
|
886
|
+
provider: model.provider,
|
|
887
|
+
modelId: model.modelId
|
|
888
|
+
});
|
|
889
|
+
return model;
|
|
890
|
+
}
|
|
891
|
+
function getGlobalProvider() {
|
|
892
|
+
return asProviderV4(globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway);
|
|
893
|
+
}
|
|
894
|
+
/** Internal adapter for deprecated provider factories. */
|
|
895
|
+
function asEvaluationModel(model) {
|
|
896
|
+
if ("doEvaluate" in model && typeof model.doEvaluate === "function") return model;
|
|
897
|
+
return {
|
|
898
|
+
specificationVersion: model.specificationVersion,
|
|
899
|
+
provider: model.provider,
|
|
900
|
+
modelId: model.modelId,
|
|
901
|
+
supportedQuestionTypes: model.supportedQuestionTypes,
|
|
902
|
+
doDecide: (options) => model.doDecide(options),
|
|
903
|
+
doEvaluate: (options) => model.doDecide(options)
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
//#endregion
|
|
907
|
+
//#region src/version.ts
|
|
908
|
+
const VERSION = "7.0.179";
|
|
909
|
+
//#endregion
|
|
910
|
+
//#region src/util/download/download.ts
|
|
911
|
+
/**
|
|
912
|
+
* Download a file from a URL.
|
|
913
|
+
*
|
|
914
|
+
* @param url - The URL to download from.
|
|
915
|
+
* @param maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.
|
|
916
|
+
* @param abortSignal - An optional abort signal to cancel the download.
|
|
917
|
+
* @param fetch - An optional fetch transport.
|
|
918
|
+
* @returns The downloaded data and media type.
|
|
919
|
+
*
|
|
920
|
+
* @throws DownloadError if the download fails or exceeds maxBytes.
|
|
921
|
+
*/
|
|
922
|
+
const download = async ({ url, maxBytes, abortSignal, fetch }) => {
|
|
923
|
+
const urlText = url.toString();
|
|
924
|
+
try {
|
|
925
|
+
const headers = withUserAgentSuffix({}, `ai-sdk/${VERSION}`, getRuntimeEnvironmentUserAgent());
|
|
926
|
+
const response = await fetchUntrustedUrl({
|
|
927
|
+
url: urlText,
|
|
928
|
+
headers,
|
|
929
|
+
abortSignal,
|
|
930
|
+
fetch
|
|
931
|
+
});
|
|
932
|
+
if (!response.ok) {
|
|
933
|
+
await cancelResponseBody(response);
|
|
934
|
+
throw new DownloadError({
|
|
935
|
+
url: urlText,
|
|
936
|
+
statusCode: response.status,
|
|
937
|
+
statusText: response.statusText
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
return {
|
|
941
|
+
data: await readResponseWithSizeLimit({
|
|
942
|
+
response,
|
|
943
|
+
url: urlText,
|
|
944
|
+
maxBytes: maxBytes ?? DEFAULT_MAX_DOWNLOAD_SIZE
|
|
945
|
+
}),
|
|
946
|
+
mediaType: response.headers.get("content-type") ?? void 0
|
|
947
|
+
};
|
|
948
|
+
} catch (error) {
|
|
949
|
+
if (DownloadError.isInstance(error)) throw error;
|
|
950
|
+
throw new DownloadError({
|
|
951
|
+
url: urlText,
|
|
952
|
+
cause: error
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
};
|
|
956
|
+
//#endregion
|
|
957
|
+
//#region src/util/download/download-function.ts
|
|
958
|
+
/**
|
|
959
|
+
* Default download function.
|
|
960
|
+
* Downloads the file if it is not supported by the model.
|
|
961
|
+
*/
|
|
962
|
+
const createDefaultDownloadFunction = (download$2 = download, abortSignal) => (requestedDownloads) => Promise.all(requestedDownloads.map(async (requestedDownload) => requestedDownload.isUrlSupportedByModel ? null : await download$2({
|
|
963
|
+
...requestedDownload,
|
|
964
|
+
abortSignal: abortSignal ?? requestedDownload.abortSignal
|
|
965
|
+
})));
|
|
966
|
+
//#endregion
|
|
967
|
+
//#region src/util/merge-objects.ts
|
|
968
|
+
/**
|
|
969
|
+
* Deeply merges two objects together.
|
|
970
|
+
* - Properties from the `overrides` object override those in the `base` object with the same key.
|
|
971
|
+
* - For nested objects, the merge is performed recursively (deep merge).
|
|
972
|
+
* - Arrays are replaced, not merged.
|
|
973
|
+
* - Primitive values are replaced.
|
|
974
|
+
* - If both `base` and `overrides` are undefined, returns undefined.
|
|
975
|
+
* - If one of `base` or `overrides` is undefined, returns the other.
|
|
976
|
+
*
|
|
977
|
+
* @param base The target object to merge into
|
|
978
|
+
* @param overrides The source object to merge from
|
|
979
|
+
* @returns A new object with the merged properties, or undefined if both inputs are undefined
|
|
980
|
+
*/
|
|
981
|
+
function mergeObjects(base, overrides) {
|
|
982
|
+
if (base === void 0 && overrides === void 0) return;
|
|
983
|
+
if (base === void 0) return overrides;
|
|
984
|
+
if (overrides === void 0) return base;
|
|
985
|
+
const result = { ...base };
|
|
986
|
+
for (const key in overrides) {
|
|
987
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
|
|
988
|
+
if (Object.prototype.hasOwnProperty.call(overrides, key)) {
|
|
989
|
+
const overridesValue = overrides[key];
|
|
990
|
+
if (overridesValue === void 0) continue;
|
|
991
|
+
const baseValue = key in base ? base[key] : void 0;
|
|
992
|
+
const isSourceObject = overridesValue !== null && typeof overridesValue === "object" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);
|
|
993
|
+
const isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === "object" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);
|
|
994
|
+
if (isSourceObject && isTargetObject) result[key] = mergeObjects(baseValue, overridesValue);
|
|
995
|
+
else result[key] = overridesValue;
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
return result;
|
|
999
|
+
}
|
|
1000
|
+
//#endregion
|
|
1001
|
+
//#region src/prompt/data-content.ts
|
|
1002
|
+
/**
|
|
1003
|
+
* Converts data content to a base64-encoded string.
|
|
1004
|
+
*
|
|
1005
|
+
* @param content - Data content to convert.
|
|
1006
|
+
* @returns Base64-encoded string.
|
|
1007
|
+
*/
|
|
1008
|
+
function convertDataContentToBase64String(content) {
|
|
1009
|
+
if (typeof content === "string") return content;
|
|
1010
|
+
return convertUint8ArrayToBase64(convertDataContentToUint8Array(content));
|
|
1011
|
+
}
|
|
1012
|
+
/**
|
|
1013
|
+
* Converts data content to a Uint8Array.
|
|
1014
|
+
*
|
|
1015
|
+
* @param content - Data content to convert.
|
|
1016
|
+
* @returns Uint8Array.
|
|
1017
|
+
*/
|
|
1018
|
+
function convertDataContentToUint8Array(content) {
|
|
1019
|
+
if (isUint8Array(content)) {
|
|
1020
|
+
if (content instanceof Uint8Array) return content;
|
|
1021
|
+
const { buffer, byteOffset, byteLength } = content;
|
|
1022
|
+
return new Uint8Array(buffer, byteOffset, byteLength);
|
|
1023
|
+
}
|
|
1024
|
+
if (typeof content === "string") try {
|
|
1025
|
+
return convertBase64ToUint8Array(content);
|
|
1026
|
+
} catch (error) {
|
|
1027
|
+
throw new InvalidDataContentError({
|
|
1028
|
+
message: "Invalid data content. Content string is not a base64-encoded media.",
|
|
1029
|
+
content,
|
|
1030
|
+
cause: error
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
if (isArrayBuffer(content)) return new Uint8Array(content);
|
|
1034
|
+
throw new InvalidDataContentError({ content });
|
|
1035
|
+
}
|
|
1036
|
+
//#endregion
|
|
1037
|
+
//#region src/prompt/split-data-url.ts
|
|
1038
|
+
function splitDataUrl(dataUrl) {
|
|
1039
|
+
try {
|
|
1040
|
+
const [header, base64Content] = dataUrl.split(",");
|
|
1041
|
+
return {
|
|
1042
|
+
mediaType: header.split(";")[0].split(":")[1],
|
|
1043
|
+
base64Content
|
|
1044
|
+
};
|
|
1045
|
+
} catch {
|
|
1046
|
+
return {
|
|
1047
|
+
mediaType: void 0,
|
|
1048
|
+
base64Content: void 0
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
//#endregion
|
|
1053
|
+
//#region src/prompt/file-part-data.ts
|
|
1054
|
+
function isTaggedFileData(value) {
|
|
1055
|
+
if (typeof value !== "object" || value === null) return false;
|
|
1056
|
+
const type = value.type;
|
|
1057
|
+
return type === "data" || type === "url" || type === "reference" || type === "text";
|
|
1058
|
+
}
|
|
1059
|
+
function convertUrlToFilePartData(url, originalUrl) {
|
|
1060
|
+
if (url.protocol === "data:") {
|
|
1061
|
+
const { mediaType, base64Content } = splitDataUrl(url.toString());
|
|
1062
|
+
if (mediaType == null || base64Content == null) throw new InvalidDataContentError({
|
|
1063
|
+
content: url,
|
|
1064
|
+
message: `Invalid data URL format in content ${url.toString()}`
|
|
1065
|
+
});
|
|
1066
|
+
return {
|
|
1067
|
+
data: {
|
|
1068
|
+
type: "data",
|
|
1069
|
+
data: base64Content
|
|
1070
|
+
},
|
|
1071
|
+
mediaType
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
return {
|
|
1075
|
+
data: {
|
|
1076
|
+
type: "url",
|
|
1077
|
+
url,
|
|
1078
|
+
...originalUrl != null ? { originalUrl } : {}
|
|
1079
|
+
},
|
|
1080
|
+
mediaType: void 0
|
|
1081
|
+
};
|
|
1082
|
+
}
|
|
1083
|
+
function convertUrlStringToFilePartData(content) {
|
|
1084
|
+
const result = convertUrlToFilePartData(new URL(content));
|
|
1085
|
+
if (result.data.type === "url" && result.data.url.toString() !== content) result.data.originalUrl = content;
|
|
1086
|
+
return result;
|
|
1087
|
+
}
|
|
1088
|
+
function convertInlineDataToFilePartData(content) {
|
|
1089
|
+
if (isUint8Array(content) || isArrayBuffer(content)) return {
|
|
1090
|
+
data: {
|
|
1091
|
+
type: "data",
|
|
1092
|
+
data: convertDataContentToUint8Array(content)
|
|
1093
|
+
},
|
|
1094
|
+
mediaType: void 0
|
|
1095
|
+
};
|
|
1096
|
+
if (isBuffer(content)) return {
|
|
1097
|
+
data: {
|
|
1098
|
+
type: "data",
|
|
1099
|
+
data: new Uint8Array(content)
|
|
1100
|
+
},
|
|
1101
|
+
mediaType: void 0
|
|
1102
|
+
};
|
|
1103
|
+
return {
|
|
1104
|
+
data: {
|
|
1105
|
+
type: "data",
|
|
1106
|
+
data: content
|
|
1107
|
+
},
|
|
1108
|
+
mediaType: void 0
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
/**
|
|
1112
|
+
* Converts any legacy-or-tagged top-level `FilePart.data` /
|
|
1113
|
+
* `ReasoningFilePart.data` value into the tagged v4 provider prompt shape.
|
|
1114
|
+
*
|
|
1115
|
+
* Returns the tagged `data` together with the resolved mediaType (extracted
|
|
1116
|
+
* from a `data:` URL when applicable).
|
|
1117
|
+
*/
|
|
1118
|
+
function convertToLanguageModelV4FilePart(content) {
|
|
1119
|
+
if (isTaggedFileData(content)) switch (content.type) {
|
|
1120
|
+
case "data":
|
|
1121
|
+
if (typeof content.data === "string" && content.data.startsWith("data:")) throw new InvalidDataContentError({
|
|
1122
|
+
content: content.data,
|
|
1123
|
+
message: "Data URLs are not valid inline data. Pass them as { type: \"url\", url } instead."
|
|
1124
|
+
});
|
|
1125
|
+
return convertInlineDataToFilePartData(content.data);
|
|
1126
|
+
case "url": return convertUrlToFilePartData(content.url, content.originalUrl);
|
|
1127
|
+
case "reference": return {
|
|
1128
|
+
data: {
|
|
1129
|
+
type: "reference",
|
|
1130
|
+
reference: content.reference
|
|
1131
|
+
},
|
|
1132
|
+
mediaType: void 0
|
|
1133
|
+
};
|
|
1134
|
+
case "text": return {
|
|
1135
|
+
data: {
|
|
1136
|
+
type: "text",
|
|
1137
|
+
text: content.text
|
|
1138
|
+
},
|
|
1139
|
+
mediaType: void 0
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
if (content instanceof URL) return convertUrlToFilePartData(content);
|
|
1143
|
+
if (typeof content === "string") try {
|
|
1144
|
+
return convertUrlStringToFilePartData(content);
|
|
1145
|
+
} catch {
|
|
1146
|
+
return convertInlineDataToFilePartData(content);
|
|
1147
|
+
}
|
|
1148
|
+
if (isUint8Array(content) || isArrayBuffer(content)) return convertInlineDataToFilePartData(content);
|
|
1149
|
+
if (isProviderReference(content)) return {
|
|
1150
|
+
data: {
|
|
1151
|
+
type: "reference",
|
|
1152
|
+
reference: content
|
|
1153
|
+
},
|
|
1154
|
+
mediaType: void 0
|
|
1155
|
+
};
|
|
1156
|
+
return convertInlineDataToFilePartData(content);
|
|
1157
|
+
}
|
|
1158
|
+
//#endregion
|
|
1159
|
+
//#region src/prompt/convert-to-language-model-prompt.ts
|
|
1160
|
+
async function convertToLanguageModelPrompt({ prompt, supportedUrls, download, abortSignal, provider }) {
|
|
1161
|
+
const downloadedAssets = await downloadAssets(prompt.messages, download ?? createDefaultDownloadFunction(void 0, abortSignal), supportedUrls, abortSignal);
|
|
1162
|
+
const messages = [...prompt.instructions != null ? typeof prompt.instructions === "string" ? [{
|
|
1163
|
+
role: "system",
|
|
1164
|
+
content: prompt.instructions
|
|
1165
|
+
}] : asArray(prompt.instructions).map((message) => ({
|
|
1166
|
+
role: "system",
|
|
1167
|
+
content: message.content,
|
|
1168
|
+
providerOptions: message.providerOptions
|
|
1169
|
+
})) : [], ...prompt.messages.map((message) => convertToLanguageModelMessage({
|
|
1170
|
+
message,
|
|
1171
|
+
downloadedAssets,
|
|
1172
|
+
provider
|
|
1173
|
+
}))];
|
|
1174
|
+
const combinedMessages = [];
|
|
1175
|
+
for (const message of messages) {
|
|
1176
|
+
if (message.role !== "tool") {
|
|
1177
|
+
combinedMessages.push(message);
|
|
1178
|
+
continue;
|
|
1179
|
+
}
|
|
1180
|
+
const lastCombinedMessage = combinedMessages.at(-1);
|
|
1181
|
+
if (lastCombinedMessage?.role === "tool") {
|
|
1182
|
+
const lastContentPart = lastCombinedMessage.content.at(-1);
|
|
1183
|
+
if (lastContentPart != null && lastCombinedMessage.providerOptions != null) lastContentPart.providerOptions = mergeObjects(lastCombinedMessage.providerOptions, lastContentPart.providerOptions);
|
|
1184
|
+
lastCombinedMessage.content.push(...message.content);
|
|
1185
|
+
lastCombinedMessage.providerOptions = lastContentPart == null ? mergeObjects(lastCombinedMessage.providerOptions, message.providerOptions) : message.providerOptions;
|
|
1186
|
+
} else combinedMessages.push(message);
|
|
1187
|
+
}
|
|
1188
|
+
const toolCallIds = /* @__PURE__ */ new Set();
|
|
1189
|
+
for (const message of combinedMessages) switch (message.role) {
|
|
1190
|
+
case "assistant":
|
|
1191
|
+
for (const content of message.content) if (content.type === "tool-call" && !content.providerExecuted) toolCallIds.add(content.toolCallId);
|
|
1192
|
+
break;
|
|
1193
|
+
case "tool":
|
|
1194
|
+
for (const content of message.content) if (content.type === "tool-result") toolCallIds.delete(content.toolCallId);
|
|
1195
|
+
break;
|
|
1196
|
+
case "user":
|
|
1197
|
+
case "system": if (toolCallIds.size > 0) throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });
|
|
1198
|
+
}
|
|
1199
|
+
if (toolCallIds.size > 0) throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });
|
|
1200
|
+
return combinedMessages.filter((message) => message.role !== "tool" || message.content.length > 0);
|
|
1201
|
+
}
|
|
1202
|
+
/**
|
|
1203
|
+
* Convert a ModelMessage to a LanguageModelV4Message.
|
|
1204
|
+
*
|
|
1205
|
+
* @param message - The ModelMessage to convert.
|
|
1206
|
+
* @param downloadedAssets - A map of URLs to their downloaded data. Only
|
|
1207
|
+
* available if the model does not support URLs, null otherwise.
|
|
1208
|
+
*/
|
|
1209
|
+
function convertToLanguageModelMessage({ message, downloadedAssets, provider }) {
|
|
1210
|
+
const warnings = [];
|
|
1211
|
+
const role = message.role;
|
|
1212
|
+
switch (role) {
|
|
1213
|
+
case "system": return {
|
|
1214
|
+
role: "system",
|
|
1215
|
+
content: message.content,
|
|
1216
|
+
providerOptions: message.providerOptions
|
|
1217
|
+
};
|
|
1218
|
+
case "user": {
|
|
1219
|
+
if (typeof message.content === "string") return {
|
|
1220
|
+
role: "user",
|
|
1221
|
+
content: [{
|
|
1222
|
+
type: "text",
|
|
1223
|
+
text: message.content
|
|
1224
|
+
}],
|
|
1225
|
+
providerOptions: message.providerOptions
|
|
1226
|
+
};
|
|
1227
|
+
const converted = {
|
|
1228
|
+
role: "user",
|
|
1229
|
+
content: message.content.map((part) => {
|
|
1230
|
+
if (part.type === "image") warnings.push({
|
|
1231
|
+
type: "deprecated",
|
|
1232
|
+
setting: "\"image\" content part",
|
|
1233
|
+
message: `The "image" content part type is deprecated. Use a "file" part with mediaType: 'image' (or a more specific image/* subtype) instead.`
|
|
1234
|
+
});
|
|
1235
|
+
return convertImagePartToFilePart(part);
|
|
1236
|
+
}).map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""),
|
|
1237
|
+
providerOptions: message.providerOptions
|
|
1238
|
+
};
|
|
1239
|
+
if (warnings.length > 0) logWarnings({ warnings });
|
|
1240
|
+
return converted;
|
|
1241
|
+
}
|
|
1242
|
+
case "assistant": {
|
|
1243
|
+
if (typeof message.content === "string") return {
|
|
1244
|
+
role: "assistant",
|
|
1245
|
+
content: [{
|
|
1246
|
+
type: "text",
|
|
1247
|
+
text: message.content
|
|
1248
|
+
}],
|
|
1249
|
+
providerOptions: message.providerOptions
|
|
1250
|
+
};
|
|
1251
|
+
const converted = {
|
|
1252
|
+
role: "assistant",
|
|
1253
|
+
content: message.content.filter((part) => part.type !== "text" || part.text !== "" || part.providerOptions != null).filter((part) => part.type !== "tool-approval-request").map((part) => {
|
|
1254
|
+
const providerOptions = part.providerOptions;
|
|
1255
|
+
switch (part.type) {
|
|
1256
|
+
case "custom": return {
|
|
1257
|
+
type: "custom",
|
|
1258
|
+
kind: part.kind,
|
|
1259
|
+
providerOptions
|
|
1260
|
+
};
|
|
1261
|
+
case "file": {
|
|
1262
|
+
const { data, mediaType } = convertToLanguageModelV4FilePart(part.data);
|
|
1263
|
+
return {
|
|
1264
|
+
type: "file",
|
|
1265
|
+
data,
|
|
1266
|
+
filename: part.filename,
|
|
1267
|
+
mediaType: mediaType ?? part.mediaType,
|
|
1268
|
+
providerOptions
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
case "reasoning": return {
|
|
1272
|
+
type: "reasoning",
|
|
1273
|
+
text: part.text,
|
|
1274
|
+
providerOptions
|
|
1275
|
+
};
|
|
1276
|
+
case "reasoning-file": {
|
|
1277
|
+
const { data, mediaType } = convertToLanguageModelV4FilePart(part.data);
|
|
1278
|
+
if (data.type !== "data" && data.type !== "url") throw new Error(`Unsupported reasoning-file data type: ${data.type}`);
|
|
1279
|
+
return {
|
|
1280
|
+
type: "reasoning-file",
|
|
1281
|
+
data,
|
|
1282
|
+
mediaType: mediaType ?? part.mediaType,
|
|
1283
|
+
providerOptions
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
case "text": return {
|
|
1287
|
+
type: "text",
|
|
1288
|
+
text: part.text,
|
|
1289
|
+
providerOptions
|
|
1290
|
+
};
|
|
1291
|
+
case "tool-call": return {
|
|
1292
|
+
type: "tool-call",
|
|
1293
|
+
toolCallId: part.toolCallId,
|
|
1294
|
+
toolName: part.toolName,
|
|
1295
|
+
input: part.input,
|
|
1296
|
+
providerExecuted: part.providerExecuted,
|
|
1297
|
+
providerOptions
|
|
1298
|
+
};
|
|
1299
|
+
case "tool-result": return {
|
|
1300
|
+
type: "tool-result",
|
|
1301
|
+
toolCallId: part.toolCallId,
|
|
1302
|
+
toolName: part.toolName,
|
|
1303
|
+
output: mapToolResultOutput({
|
|
1304
|
+
output: part.output,
|
|
1305
|
+
provider,
|
|
1306
|
+
warnings,
|
|
1307
|
+
downloadedAssets
|
|
1308
|
+
}),
|
|
1309
|
+
providerOptions
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
}),
|
|
1313
|
+
providerOptions: message.providerOptions
|
|
1314
|
+
};
|
|
1315
|
+
if (warnings.length > 0) logWarnings({ warnings });
|
|
1316
|
+
return converted;
|
|
1317
|
+
}
|
|
1318
|
+
case "tool": {
|
|
1319
|
+
const converted = {
|
|
1320
|
+
role: "tool",
|
|
1321
|
+
content: message.content.filter((part) => part.type !== "tool-approval-response" || part.providerExecuted).map((part) => {
|
|
1322
|
+
switch (part.type) {
|
|
1323
|
+
case "tool-result": return {
|
|
1324
|
+
type: "tool-result",
|
|
1325
|
+
toolCallId: part.toolCallId,
|
|
1326
|
+
toolName: part.toolName,
|
|
1327
|
+
output: mapToolResultOutput({
|
|
1328
|
+
output: part.output,
|
|
1329
|
+
provider,
|
|
1330
|
+
warnings,
|
|
1331
|
+
downloadedAssets
|
|
1332
|
+
}),
|
|
1333
|
+
providerOptions: part.providerOptions
|
|
1334
|
+
};
|
|
1335
|
+
case "tool-approval-response": return {
|
|
1336
|
+
type: "tool-approval-response",
|
|
1337
|
+
approvalId: part.approvalId,
|
|
1338
|
+
approved: part.approved,
|
|
1339
|
+
reason: part.reason
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
}),
|
|
1343
|
+
providerOptions: message.providerOptions
|
|
1344
|
+
};
|
|
1345
|
+
if (warnings.length > 0) logWarnings({ warnings });
|
|
1346
|
+
return converted;
|
|
1347
|
+
}
|
|
1348
|
+
default: throw new InvalidMessageRoleError({ role });
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
function convertImagePartToFilePart(part) {
|
|
1352
|
+
if (part.type !== "image") return part;
|
|
1353
|
+
return {
|
|
1354
|
+
type: "file",
|
|
1355
|
+
data: part.image,
|
|
1356
|
+
mediaType: part.mediaType ?? "image",
|
|
1357
|
+
providerOptions: part.providerOptions
|
|
1358
|
+
};
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Downloads files from URLs in the user messages.
|
|
1362
|
+
*/
|
|
1363
|
+
async function downloadAssets(messages, download, supportedUrls, abortSignal) {
|
|
1364
|
+
const downloadableFiles = [];
|
|
1365
|
+
for (const message of messages) {
|
|
1366
|
+
if (message.role === "user" && Array.isArray(message.content)) for (const part of message.content) {
|
|
1367
|
+
const filePart = convertImagePartToFilePart(part);
|
|
1368
|
+
if (filePart.type === "file") downloadableFiles.push(filePart);
|
|
1369
|
+
}
|
|
1370
|
+
if (message.role === "tool") for (const part of message.content) {
|
|
1371
|
+
if (part.type !== "tool-result") continue;
|
|
1372
|
+
if (part.output.type !== "content") continue;
|
|
1373
|
+
for (const contentPart of part.output.value) {
|
|
1374
|
+
const filePart = getDownloadableFilePart(contentPart);
|
|
1375
|
+
if (filePart != null) downloadableFiles.push(filePart);
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
if (message.role === "assistant" && Array.isArray(message.content)) for (const part of message.content) {
|
|
1379
|
+
if (part.type !== "tool-result") continue;
|
|
1380
|
+
if (part.output.type !== "content") continue;
|
|
1381
|
+
for (const contentPart of part.output.value) {
|
|
1382
|
+
const filePart = getDownloadableFilePart(contentPart);
|
|
1383
|
+
if (filePart != null) downloadableFiles.push(filePart);
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
const plannedDownloads = downloadableFiles.map((part) => {
|
|
1388
|
+
const mediaType = part.mediaType;
|
|
1389
|
+
const { data } = convertToLanguageModelV4FilePart(part.data);
|
|
1390
|
+
return {
|
|
1391
|
+
mediaType,
|
|
1392
|
+
data
|
|
1393
|
+
};
|
|
1394
|
+
}).filter((part) => part.data.type === "url").map((part) => ({
|
|
1395
|
+
url: part.data.url,
|
|
1396
|
+
abortSignal,
|
|
1397
|
+
isUrlSupportedByModel: part.mediaType != null && isUrlSupported({
|
|
1398
|
+
url: part.data.url.toString(),
|
|
1399
|
+
mediaType: part.mediaType,
|
|
1400
|
+
supportedUrls
|
|
1401
|
+
})
|
|
1402
|
+
}));
|
|
1403
|
+
const downloadedFiles = await download(plannedDownloads);
|
|
1404
|
+
return Object.fromEntries(downloadedFiles.map((file, index) => file == null ? null : [plannedDownloads[index].url.toString(), {
|
|
1405
|
+
data: file.data,
|
|
1406
|
+
mediaType: file.mediaType
|
|
1407
|
+
}]).filter((file) => file != null));
|
|
1408
|
+
}
|
|
1409
|
+
/**
|
|
1410
|
+
* Resolves the tool result content parts that point at a remote file to the
|
|
1411
|
+
* tagged file shape, including the deprecated `file-url` and `image-url`
|
|
1412
|
+
* types, so that they are downloaded and inlined exactly like their `file`
|
|
1413
|
+
* replacement. Returns `undefined` for content that is already inline or
|
|
1414
|
+
* provider-referenced.
|
|
1415
|
+
*/
|
|
1416
|
+
function getDownloadableFilePart(contentPart) {
|
|
1417
|
+
switch (contentPart.type) {
|
|
1418
|
+
case "file": return contentPart;
|
|
1419
|
+
case "file-url": return {
|
|
1420
|
+
type: "file",
|
|
1421
|
+
data: {
|
|
1422
|
+
type: "url",
|
|
1423
|
+
url: new URL(contentPart.url)
|
|
1424
|
+
},
|
|
1425
|
+
mediaType: contentPart.mediaType ?? getMediaTypeFromUrl(contentPart.url),
|
|
1426
|
+
providerOptions: contentPart.providerOptions
|
|
1427
|
+
};
|
|
1428
|
+
case "image-url": return {
|
|
1429
|
+
type: "file",
|
|
1430
|
+
data: {
|
|
1431
|
+
type: "url",
|
|
1432
|
+
url: new URL(contentPart.url)
|
|
1433
|
+
},
|
|
1434
|
+
mediaType: "image",
|
|
1435
|
+
providerOptions: contentPart.providerOptions
|
|
1436
|
+
};
|
|
1437
|
+
default: return;
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
/**
|
|
1441
|
+
* Resolves file data and media type for a remote tool result content part: the downloaded
|
|
1442
|
+
* bytes when the asset was fetched, otherwise the URL reference. `originalUrl`
|
|
1443
|
+
* is preserved when the URL string does not round-trip through `URL`.
|
|
1444
|
+
*/
|
|
1445
|
+
function resolveDownloadedFile({ url, originalUrl, downloadedAssets, mediaType }) {
|
|
1446
|
+
const convertedPart = convertPartToLanguageModelPart({
|
|
1447
|
+
type: "file",
|
|
1448
|
+
data: {
|
|
1449
|
+
type: "url",
|
|
1450
|
+
url,
|
|
1451
|
+
...url.toString() !== originalUrl ? { originalUrl } : {}
|
|
1452
|
+
},
|
|
1453
|
+
mediaType
|
|
1454
|
+
}, downloadedAssets);
|
|
1455
|
+
return {
|
|
1456
|
+
data: convertedPart.data,
|
|
1457
|
+
mediaType: convertedPart.mediaType
|
|
1458
|
+
};
|
|
1459
|
+
}
|
|
1460
|
+
/**
|
|
1461
|
+
* Convert part of a user message to a LanguageModelV4Part.
|
|
1462
|
+
*
|
|
1463
|
+
* @param part - The part to convert.
|
|
1464
|
+
* @param downloadedAssets - A map of URLs to their downloaded data. Only
|
|
1465
|
+
* available if the model does not support URLs, null otherwise.
|
|
1466
|
+
* @returns The converted part.
|
|
1467
|
+
*/
|
|
1468
|
+
function convertPartToLanguageModelPart(part, downloadedAssets) {
|
|
1469
|
+
if (part.type === "text") return {
|
|
1470
|
+
type: "text",
|
|
1471
|
+
text: part.text,
|
|
1472
|
+
providerOptions: part.providerOptions
|
|
1473
|
+
};
|
|
1474
|
+
const { data: normalizedData, mediaType: dataUrlMediaType } = convertToLanguageModelV4FilePart(part.data);
|
|
1475
|
+
let mediaType = dataUrlMediaType ?? part.mediaType;
|
|
1476
|
+
let data = normalizedData;
|
|
1477
|
+
if (data.type === "url") {
|
|
1478
|
+
const downloadedFile = downloadedAssets[data.url.toString()];
|
|
1479
|
+
if (downloadedFile) {
|
|
1480
|
+
data = {
|
|
1481
|
+
type: "data",
|
|
1482
|
+
data: downloadedFile.data
|
|
1483
|
+
};
|
|
1484
|
+
if (downloadedFile.mediaType != null && (mediaType == null || !isFullMediaType(mediaType))) mediaType = downloadedFile.mediaType;
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
if (data.type === "data" && (data.data instanceof Uint8Array || typeof data.data === "string")) {
|
|
1488
|
+
const imageMediaType = detectMediaType({
|
|
1489
|
+
data: data.data,
|
|
1490
|
+
topLevelType: "image"
|
|
1491
|
+
});
|
|
1492
|
+
if (imageMediaType != null) mediaType = imageMediaType;
|
|
1493
|
+
}
|
|
1494
|
+
if (mediaType == null) throw new Error(`Media type is missing for file part`);
|
|
1495
|
+
return {
|
|
1496
|
+
type: "file",
|
|
1497
|
+
mediaType,
|
|
1498
|
+
filename: part.filename,
|
|
1499
|
+
data,
|
|
1500
|
+
providerOptions: part.providerOptions
|
|
1501
|
+
};
|
|
1502
|
+
}
|
|
1503
|
+
function mapToolResultOutput({ output, provider, warnings = [], downloadedAssets }) {
|
|
1504
|
+
if (output.type !== "content") return output;
|
|
1505
|
+
return {
|
|
1506
|
+
type: "content",
|
|
1507
|
+
value: output.value.map((item) => {
|
|
1508
|
+
switch (item.type) {
|
|
1509
|
+
case "file": {
|
|
1510
|
+
const convertedPart = convertPartToLanguageModelPart(item, downloadedAssets);
|
|
1511
|
+
if (convertedPart.type !== "file") throw new Error("Expected tool result file content to convert to file.");
|
|
1512
|
+
return convertedPart;
|
|
1513
|
+
}
|
|
1514
|
+
case "file-data":
|
|
1515
|
+
warnings.push({
|
|
1516
|
+
type: "deprecated",
|
|
1517
|
+
setting: "\"tool-result\" content of type \"file-data\"",
|
|
1518
|
+
message: `The "file-data" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'data', data } instead.`
|
|
1519
|
+
});
|
|
1520
|
+
return {
|
|
1521
|
+
type: "file",
|
|
1522
|
+
data: {
|
|
1523
|
+
type: "data",
|
|
1524
|
+
data: item.data
|
|
1525
|
+
},
|
|
1526
|
+
filename: item.filename,
|
|
1527
|
+
mediaType: item.mediaType,
|
|
1528
|
+
providerOptions: item.providerOptions
|
|
1529
|
+
};
|
|
1530
|
+
case "file-url": {
|
|
1531
|
+
const mediaType = item.mediaType ?? getMediaTypeFromUrl(item.url);
|
|
1532
|
+
const url = new URL(item.url);
|
|
1533
|
+
let message = `The "file-url" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'url', url } instead.`;
|
|
1534
|
+
if (!item.mediaType) {
|
|
1535
|
+
const inferenceSuffix = mediaType === "application/octet-stream" ? `Unable to infer media type from URL. Defaulting to 'application/octet-stream'.` : `Inferred media type '${mediaType}' from URL.`;
|
|
1536
|
+
message = `The "file-url" tool result content part with URL "${item.url}" is missing a "mediaType". ${inferenceSuffix} ${message}`;
|
|
1537
|
+
}
|
|
1538
|
+
warnings.push({
|
|
1539
|
+
type: "deprecated",
|
|
1540
|
+
setting: "\"tool-result\" content of type \"file-url\"",
|
|
1541
|
+
message
|
|
1542
|
+
});
|
|
1543
|
+
return {
|
|
1544
|
+
type: "file",
|
|
1545
|
+
...resolveDownloadedFile({
|
|
1546
|
+
url,
|
|
1547
|
+
originalUrl: item.url,
|
|
1548
|
+
downloadedAssets,
|
|
1549
|
+
mediaType
|
|
1550
|
+
}),
|
|
1551
|
+
providerOptions: item.providerOptions
|
|
1552
|
+
};
|
|
1553
|
+
}
|
|
1554
|
+
case "file-id":
|
|
1555
|
+
warnings.push({
|
|
1556
|
+
type: "deprecated",
|
|
1557
|
+
setting: "\"tool-result\" content of type \"file-id\"",
|
|
1558
|
+
message: `The "file-id" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'reference', reference } instead.`
|
|
1559
|
+
});
|
|
1560
|
+
return {
|
|
1561
|
+
type: "file",
|
|
1562
|
+
data: {
|
|
1563
|
+
type: "reference",
|
|
1564
|
+
reference: convertFileIdToProviderReference({
|
|
1565
|
+
fileId: item.fileId,
|
|
1566
|
+
provider
|
|
1567
|
+
})
|
|
1568
|
+
},
|
|
1569
|
+
mediaType: "application",
|
|
1570
|
+
providerOptions: item.providerOptions
|
|
1571
|
+
};
|
|
1572
|
+
case "file-reference":
|
|
1573
|
+
warnings.push({
|
|
1574
|
+
type: "deprecated",
|
|
1575
|
+
setting: "\"tool-result\" content of type \"file-reference\"",
|
|
1576
|
+
message: `The "file-reference" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'reference', reference } instead.`
|
|
1577
|
+
});
|
|
1578
|
+
return {
|
|
1579
|
+
type: "file",
|
|
1580
|
+
data: {
|
|
1581
|
+
type: "reference",
|
|
1582
|
+
reference: item.providerReference
|
|
1583
|
+
},
|
|
1584
|
+
mediaType: "application",
|
|
1585
|
+
providerOptions: item.providerOptions
|
|
1586
|
+
};
|
|
1587
|
+
case "image-data":
|
|
1588
|
+
warnings.push({
|
|
1589
|
+
type: "deprecated",
|
|
1590
|
+
setting: "\"tool-result\" content of type \"image-data\"",
|
|
1591
|
+
message: `The "image-data" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'data', data } instead.`
|
|
1592
|
+
});
|
|
1593
|
+
return {
|
|
1594
|
+
type: "file",
|
|
1595
|
+
data: {
|
|
1596
|
+
type: "data",
|
|
1597
|
+
data: item.data
|
|
1598
|
+
},
|
|
1599
|
+
mediaType: item.mediaType,
|
|
1600
|
+
providerOptions: item.providerOptions
|
|
1601
|
+
};
|
|
1602
|
+
case "image-url": {
|
|
1603
|
+
const url = new URL(item.url);
|
|
1604
|
+
warnings.push({
|
|
1605
|
+
type: "deprecated",
|
|
1606
|
+
setting: "\"tool-result\" content of type \"image-url\"",
|
|
1607
|
+
message: `The "image-url" type for tool result content is deprecated. Use the "file" type with mediaType 'image' (or a specific image/* subtype) and { type: 'url', url } instead.`
|
|
1608
|
+
});
|
|
1609
|
+
return {
|
|
1610
|
+
type: "file",
|
|
1611
|
+
...resolveDownloadedFile({
|
|
1612
|
+
url,
|
|
1613
|
+
originalUrl: item.url,
|
|
1614
|
+
downloadedAssets,
|
|
1615
|
+
mediaType: "image"
|
|
1616
|
+
}),
|
|
1617
|
+
providerOptions: item.providerOptions
|
|
1618
|
+
};
|
|
1619
|
+
}
|
|
1620
|
+
case "image-file-id":
|
|
1621
|
+
warnings.push({
|
|
1622
|
+
type: "deprecated",
|
|
1623
|
+
setting: "\"tool-result\" content of type \"image-file-id\"",
|
|
1624
|
+
message: `The "image-file-id" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'reference', reference } instead.`
|
|
1625
|
+
});
|
|
1626
|
+
return {
|
|
1627
|
+
type: "file",
|
|
1628
|
+
data: {
|
|
1629
|
+
type: "reference",
|
|
1630
|
+
reference: convertFileIdToProviderReference({
|
|
1631
|
+
fileId: item.fileId,
|
|
1632
|
+
provider
|
|
1633
|
+
})
|
|
1634
|
+
},
|
|
1635
|
+
mediaType: "image",
|
|
1636
|
+
providerOptions: item.providerOptions
|
|
1637
|
+
};
|
|
1638
|
+
case "image-file-reference":
|
|
1639
|
+
warnings.push({
|
|
1640
|
+
type: "deprecated",
|
|
1641
|
+
setting: "\"tool-result\" content of type \"image-file-reference\"",
|
|
1642
|
+
message: `The "image-file-reference" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'reference', reference } instead.`
|
|
1643
|
+
});
|
|
1644
|
+
return {
|
|
1645
|
+
type: "file",
|
|
1646
|
+
data: {
|
|
1647
|
+
type: "reference",
|
|
1648
|
+
reference: item.providerReference
|
|
1649
|
+
},
|
|
1650
|
+
mediaType: "image",
|
|
1651
|
+
providerOptions: item.providerOptions
|
|
1652
|
+
};
|
|
1653
|
+
default: return item;
|
|
1654
|
+
}
|
|
1655
|
+
})
|
|
1656
|
+
};
|
|
1657
|
+
}
|
|
1658
|
+
function convertFileIdToProviderReference({ fileId, provider }) {
|
|
1659
|
+
if (typeof fileId === "object") return fileId;
|
|
1660
|
+
if (provider == null) throw new Error("Cannot convert string fileId to provider reference without a provider ID. Use a Record<string, string> fileId or switch to the file-reference type.");
|
|
1661
|
+
return { [provider]: fileId };
|
|
1662
|
+
}
|
|
1663
|
+
const URL_EXTENSION_TO_MEDIA_TYPE = {
|
|
1664
|
+
jpg: "image/jpeg",
|
|
1665
|
+
jpeg: "image/jpeg",
|
|
1666
|
+
png: "image/png",
|
|
1667
|
+
gif: "image/gif",
|
|
1668
|
+
webp: "image/webp",
|
|
1669
|
+
svg: "image/svg+xml",
|
|
1670
|
+
avif: "image/avif",
|
|
1671
|
+
heic: "image/heic",
|
|
1672
|
+
bmp: "image/bmp",
|
|
1673
|
+
tiff: "image/tiff",
|
|
1674
|
+
tif: "image/tiff",
|
|
1675
|
+
pdf: "application/pdf",
|
|
1676
|
+
mp4: "video/mp4",
|
|
1677
|
+
webm: "video/webm",
|
|
1678
|
+
mp3: "audio/mpeg",
|
|
1679
|
+
wav: "audio/wav",
|
|
1680
|
+
ogg: "audio/ogg"
|
|
1681
|
+
};
|
|
1682
|
+
function getMediaTypeFromUrl(url, fallbackMediaType = "application/octet-stream") {
|
|
1683
|
+
try {
|
|
1684
|
+
const fileExtension = new URL(url).pathname.split(".").pop()?.toLowerCase();
|
|
1685
|
+
if (fileExtension && Object.hasOwn(URL_EXTENSION_TO_MEDIA_TYPE, fileExtension)) return URL_EXTENSION_TO_MEDIA_TYPE[fileExtension];
|
|
1686
|
+
} catch {}
|
|
1687
|
+
return fallbackMediaType;
|
|
1688
|
+
}
|
|
1689
|
+
//#endregion
|
|
1690
|
+
//#region src/prompt/create-tool-model-output.ts
|
|
1691
|
+
async function createToolModelOutput({ toolCallId, input, output, tool, errorMode }) {
|
|
1692
|
+
if (errorMode === "text") return {
|
|
1693
|
+
type: "error-text",
|
|
1694
|
+
value: getErrorMessage$1(output)
|
|
1695
|
+
};
|
|
1696
|
+
else if (errorMode === "json") return {
|
|
1697
|
+
type: "error-json",
|
|
1698
|
+
value: toJSONValue(output)
|
|
1699
|
+
};
|
|
1700
|
+
if (tool?.toModelOutput) return await tool.toModelOutput({
|
|
1701
|
+
toolCallId,
|
|
1702
|
+
input,
|
|
1703
|
+
output
|
|
1704
|
+
});
|
|
1705
|
+
return typeof output === "string" ? {
|
|
1706
|
+
type: "text",
|
|
1707
|
+
value: output
|
|
1708
|
+
} : {
|
|
1709
|
+
type: "json",
|
|
1710
|
+
value: toJSONValue(output)
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
/**
|
|
1714
|
+
* Normalizes an in-process tool output to a plain JSON value
|
|
1715
|
+
* (applies `toJSON`, converts `Date`, drops `undefined`, etc.)
|
|
1716
|
+
* by round-tripping it through `JSON.stringify`.
|
|
1717
|
+
*
|
|
1718
|
+
* The parsed text is produced by `JSON.stringify` from a value that is
|
|
1719
|
+
* already materialized in this process, so it is not untrusted input.
|
|
1720
|
+
* `JSON.parse` is used deliberately instead of the secure parser from
|
|
1721
|
+
* `@ai-sdk/provider-utils`: the secure parser rejects own `__proto__` and
|
|
1722
|
+
* `constructor.prototype` keys, which are valid data in tool outputs
|
|
1723
|
+
* (e.g. rows from an external API). `JSON.parse` defines `__proto__` as an
|
|
1724
|
+
* own data property and never modifies the prototype chain, so preserving
|
|
1725
|
+
* these keys here is safe. Do not reuse this pattern for text that comes
|
|
1726
|
+
* from outside the process; use `parseJSON` / `safeParseJSON` instead.
|
|
1727
|
+
*/
|
|
1728
|
+
function toJSONValue(value) {
|
|
1729
|
+
if (value === void 0) return null;
|
|
1730
|
+
const serialized = JSON.stringify(value);
|
|
1731
|
+
return serialized === void 0 ? null : JSON.parse(serialized);
|
|
1732
|
+
}
|
|
1733
|
+
//#endregion
|
|
1734
|
+
//#region src/prompt/prepare-language-model-call-options.ts
|
|
1735
|
+
/**
|
|
1736
|
+
* Validates model call options and returns a new object with normalized values.
|
|
1737
|
+
*/
|
|
1738
|
+
function prepareLanguageModelCallOptions({ maxOutputTokens, temperature, topP, topK, presencePenalty, frequencyPenalty, seed, stopSequences, reasoning }) {
|
|
1739
|
+
if (maxOutputTokens != null) {
|
|
1740
|
+
if (!Number.isInteger(maxOutputTokens)) throw new InvalidArgumentError({
|
|
1741
|
+
parameter: "maxOutputTokens",
|
|
1742
|
+
value: maxOutputTokens,
|
|
1743
|
+
message: "maxOutputTokens must be an integer"
|
|
1744
|
+
});
|
|
1745
|
+
if (maxOutputTokens < 1) throw new InvalidArgumentError({
|
|
1746
|
+
parameter: "maxOutputTokens",
|
|
1747
|
+
value: maxOutputTokens,
|
|
1748
|
+
message: "maxOutputTokens must be >= 1"
|
|
1749
|
+
});
|
|
1750
|
+
}
|
|
1751
|
+
if (seed != null) {
|
|
1752
|
+
if (!Number.isInteger(seed)) throw new InvalidArgumentError({
|
|
1753
|
+
parameter: "seed",
|
|
1754
|
+
value: seed,
|
|
1755
|
+
message: "seed must be an integer"
|
|
1756
|
+
});
|
|
1757
|
+
}
|
|
1758
|
+
return {
|
|
1759
|
+
maxOutputTokens,
|
|
1760
|
+
temperature,
|
|
1761
|
+
topP,
|
|
1762
|
+
topK,
|
|
1763
|
+
presencePenalty,
|
|
1764
|
+
frequencyPenalty,
|
|
1765
|
+
stopSequences,
|
|
1766
|
+
seed,
|
|
1767
|
+
reasoning
|
|
1768
|
+
};
|
|
1769
|
+
}
|
|
1770
|
+
//#endregion
|
|
1771
|
+
//#region src/prompt/prepare-tool-choice.ts
|
|
1772
|
+
function prepareToolChoice({ toolChoice }) {
|
|
1773
|
+
return toolChoice == null ? { type: "auto" } : typeof toolChoice === "string" ? { type: toolChoice } : {
|
|
1774
|
+
type: "tool",
|
|
1775
|
+
toolName: toolChoice.toolName
|
|
1776
|
+
};
|
|
1777
|
+
}
|
|
1778
|
+
//#endregion
|
|
1779
|
+
//#region src/util/is-non-empty-object.ts
|
|
1780
|
+
function isNonEmptyObject(object) {
|
|
1781
|
+
return object != null && Object.keys(object).length > 0;
|
|
1782
|
+
}
|
|
1783
|
+
//#endregion
|
|
1784
|
+
//#region src/prompt/prepare-tools.ts
|
|
1785
|
+
async function prepareTools({ tools, toolOrder, toolsContext = {}, experimental_sandbox: sandbox }) {
|
|
1786
|
+
if (!isNonEmptyObject(tools)) return;
|
|
1787
|
+
const languageModelTools = [];
|
|
1788
|
+
for (const [name, tool] of orderToolEntries({
|
|
1789
|
+
tools,
|
|
1790
|
+
toolOrder
|
|
1791
|
+
})) {
|
|
1792
|
+
const toolType = tool.type;
|
|
1793
|
+
switch (toolType) {
|
|
1794
|
+
case void 0:
|
|
1795
|
+
case "dynamic":
|
|
1796
|
+
case "function": {
|
|
1797
|
+
const description = resolveToolDescription({
|
|
1798
|
+
tool,
|
|
1799
|
+
toolName: name,
|
|
1800
|
+
toolsContext,
|
|
1801
|
+
experimental_sandbox: sandbox
|
|
1802
|
+
});
|
|
1803
|
+
const providerOptions = tool.providerOptions;
|
|
1804
|
+
const inputExamples = tool.inputExamples;
|
|
1805
|
+
const strict = tool.strict;
|
|
1806
|
+
languageModelTools.push({
|
|
1807
|
+
type: "function",
|
|
1808
|
+
name,
|
|
1809
|
+
inputSchema: await asSchema(tool.inputSchema).jsonSchema,
|
|
1810
|
+
...description != null ? { description } : {},
|
|
1811
|
+
...inputExamples != null ? { inputExamples } : {},
|
|
1812
|
+
...providerOptions != null ? { providerOptions } : {},
|
|
1813
|
+
...strict != null ? { strict } : {}
|
|
1814
|
+
});
|
|
1815
|
+
break;
|
|
1816
|
+
}
|
|
1817
|
+
case "provider":
|
|
1818
|
+
languageModelTools.push({
|
|
1819
|
+
type: "provider",
|
|
1820
|
+
name,
|
|
1821
|
+
id: tool.id,
|
|
1822
|
+
args: tool.args
|
|
1823
|
+
});
|
|
1824
|
+
break;
|
|
1825
|
+
default: throw new Error(`Unsupported tool type: ${toolType}`);
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
return languageModelTools;
|
|
1829
|
+
}
|
|
1830
|
+
function orderToolEntries({ tools, toolOrder }) {
|
|
1831
|
+
if (toolOrder == null) return Object.entries(tools);
|
|
1832
|
+
const toolEntries = Object.entries(tools);
|
|
1833
|
+
const orderedTools = toolEntries.filter(([name]) => toolOrder.includes(name)).sort(([nameA], [nameB]) => toolOrder.indexOf(nameA) - toolOrder.indexOf(nameB));
|
|
1834
|
+
const unorderedTools = toolEntries.filter(([name]) => !toolOrder.includes(name)).sort(([nameA], [nameB]) => nameA < nameB ? -1 : nameA > nameB ? 1 : 0);
|
|
1835
|
+
return [...orderedTools, ...unorderedTools];
|
|
1836
|
+
}
|
|
1837
|
+
function resolveToolDescription({ tool, toolName, toolsContext, experimental_sandbox: sandbox }) {
|
|
1838
|
+
return tool.description === void 0 ? void 0 : typeof tool.description === "string" ? tool.description : tool.description({
|
|
1839
|
+
context: toolsContext[toolName],
|
|
1840
|
+
experimental_sandbox: sandbox
|
|
1841
|
+
});
|
|
1842
|
+
}
|
|
1843
|
+
//#endregion
|
|
1844
|
+
//#region src/prompt/standardize-prompt.ts
|
|
1845
|
+
/**
|
|
1846
|
+
* Converts a prompt input into a standardized prompt with model messages.
|
|
1847
|
+
*
|
|
1848
|
+
* @param prompt - The prompt definition to standardize.
|
|
1849
|
+
* Set `allowSystemInMessages` to true to allow system messages in the
|
|
1850
|
+
* `prompt` or `messages` fields. System messages in the `instructions`
|
|
1851
|
+
* option are always allowed.
|
|
1852
|
+
* @returns The standardized prompt.
|
|
1853
|
+
* @throws {InvalidPromptError} When the prompt is invalid.
|
|
1854
|
+
*/
|
|
1855
|
+
async function standardizePrompt({ allowSystemInMessages = false, system, instructions = system, prompt, messages }) {
|
|
1856
|
+
messages = prompt == null ? messages : typeof prompt === "string" ? [{
|
|
1857
|
+
role: "user",
|
|
1858
|
+
content: prompt
|
|
1859
|
+
}] : prompt;
|
|
1860
|
+
if (messages.length === 0) throw new InvalidPromptError({
|
|
1861
|
+
prompt,
|
|
1862
|
+
message: "messages must not be empty"
|
|
1863
|
+
});
|
|
1864
|
+
if (!allowSystemInMessages && messages.some((message) => message.role === "system")) throw new InvalidPromptError({
|
|
1865
|
+
prompt,
|
|
1866
|
+
message: "System messages are not allowed in the prompt or messages fields. Use the instructions option instead."
|
|
1867
|
+
});
|
|
1868
|
+
return {
|
|
1869
|
+
messages,
|
|
1870
|
+
instructions
|
|
1871
|
+
};
|
|
1872
|
+
}
|
|
1873
|
+
//#endregion
|
|
1874
|
+
//#region src/types/usage.ts
|
|
1875
|
+
function asLanguageModelUsage(usage) {
|
|
1876
|
+
return {
|
|
1877
|
+
inputTokens: usage.inputTokens.total,
|
|
1878
|
+
inputTokenDetails: {
|
|
1879
|
+
noCacheTokens: usage.inputTokens.noCache,
|
|
1880
|
+
cacheReadTokens: usage.inputTokens.cacheRead,
|
|
1881
|
+
cacheWriteTokens: usage.inputTokens.cacheWrite
|
|
1882
|
+
},
|
|
1883
|
+
outputTokens: usage.outputTokens.total,
|
|
1884
|
+
outputTokenDetails: {
|
|
1885
|
+
textTokens: usage.outputTokens.text,
|
|
1886
|
+
reasoningTokens: usage.outputTokens.reasoning
|
|
1887
|
+
},
|
|
1888
|
+
totalTokens: addTokenCounts(usage.inputTokens.total, usage.outputTokens.total),
|
|
1889
|
+
raw: usage.raw
|
|
1890
|
+
};
|
|
1891
|
+
}
|
|
1892
|
+
function createNullLanguageModelUsage() {
|
|
1893
|
+
return {
|
|
1894
|
+
inputTokens: void 0,
|
|
1895
|
+
inputTokenDetails: {
|
|
1896
|
+
noCacheTokens: void 0,
|
|
1897
|
+
cacheReadTokens: void 0,
|
|
1898
|
+
cacheWriteTokens: void 0
|
|
1899
|
+
},
|
|
1900
|
+
outputTokens: void 0,
|
|
1901
|
+
outputTokenDetails: {
|
|
1902
|
+
textTokens: void 0,
|
|
1903
|
+
reasoningTokens: void 0
|
|
1904
|
+
},
|
|
1905
|
+
totalTokens: void 0,
|
|
1906
|
+
raw: void 0
|
|
1907
|
+
};
|
|
1908
|
+
}
|
|
1909
|
+
function addLanguageModelUsage(usage1, usage2) {
|
|
1910
|
+
const raw = isNullLanguageModelUsage(usage1) ? usage2.raw : isNullLanguageModelUsage(usage2) ? usage1.raw : void 0;
|
|
1911
|
+
return {
|
|
1912
|
+
inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),
|
|
1913
|
+
inputTokenDetails: {
|
|
1914
|
+
noCacheTokens: addTokenCounts(usage1.inputTokenDetails?.noCacheTokens, usage2.inputTokenDetails?.noCacheTokens),
|
|
1915
|
+
cacheReadTokens: addTokenCounts(usage1.inputTokenDetails?.cacheReadTokens, usage2.inputTokenDetails?.cacheReadTokens),
|
|
1916
|
+
cacheWriteTokens: addTokenCounts(usage1.inputTokenDetails?.cacheWriteTokens, usage2.inputTokenDetails?.cacheWriteTokens)
|
|
1917
|
+
},
|
|
1918
|
+
outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),
|
|
1919
|
+
outputTokenDetails: {
|
|
1920
|
+
textTokens: addTokenCounts(usage1.outputTokenDetails?.textTokens, usage2.outputTokenDetails?.textTokens),
|
|
1921
|
+
reasoningTokens: addTokenCounts(usage1.outputTokenDetails?.reasoningTokens, usage2.outputTokenDetails?.reasoningTokens)
|
|
1922
|
+
},
|
|
1923
|
+
totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),
|
|
1924
|
+
...raw == null ? {} : { raw }
|
|
1925
|
+
};
|
|
1926
|
+
}
|
|
1927
|
+
function isNullLanguageModelUsage(usage) {
|
|
1928
|
+
return usage.inputTokens == null && usage.inputTokenDetails?.noCacheTokens == null && usage.inputTokenDetails?.cacheReadTokens == null && usage.inputTokenDetails?.cacheWriteTokens == null && usage.outputTokens == null && usage.outputTokenDetails?.textTokens == null && usage.outputTokenDetails?.reasoningTokens == null && usage.totalTokens == null && usage.raw == null;
|
|
1929
|
+
}
|
|
1930
|
+
function addTokenCounts(tokenCount1, tokenCount2) {
|
|
1931
|
+
return tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 ?? 0) + (tokenCount2 ?? 0);
|
|
1932
|
+
}
|
|
1933
|
+
function addImageModelUsage(usage1, usage2) {
|
|
1934
|
+
return {
|
|
1935
|
+
inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),
|
|
1936
|
+
outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),
|
|
1937
|
+
totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens)
|
|
1938
|
+
};
|
|
1939
|
+
}
|
|
1940
|
+
//#endregion
|
|
1941
|
+
//#region src/util/get-own.ts
|
|
1942
|
+
/**
|
|
1943
|
+
* Reads a property by an untrusted key, ignoring inherited prototype members.
|
|
1944
|
+
*
|
|
1945
|
+
* Tool sets, tool contexts, and similar lookup objects are indexed by names
|
|
1946
|
+
* that can come from model output or client-supplied message history. Plain
|
|
1947
|
+
* bracket access (`obj[name]`) resolves names such as `constructor`,
|
|
1948
|
+
* `toString`, or `__proto__` to values on `Object.prototype`, which would slip
|
|
1949
|
+
* past the `== null` / `!value` guards that treat an unknown name as "not
|
|
1950
|
+
* present". This helper returns `undefined` unless `key` is an own property.
|
|
1951
|
+
*/
|
|
1952
|
+
function getOwn(obj, key) {
|
|
1953
|
+
return obj != null && Object.hasOwn(obj, key) ? obj[key] : void 0;
|
|
1954
|
+
}
|
|
1955
|
+
//#endregion
|
|
1956
|
+
//#region src/util/merge-abort-signals.ts
|
|
1957
|
+
/**
|
|
1958
|
+
* Merges multiple abort sources into a single `AbortSignal`.
|
|
1959
|
+
* The returned signal will abort when any input signal aborts or when any
|
|
1960
|
+
* numeric timeout elapses, using the reason from the first source to abort.
|
|
1961
|
+
*
|
|
1962
|
+
* @param signals - Abort signals or timeout durations in milliseconds.
|
|
1963
|
+
* `null` and `undefined` values are ignored.
|
|
1964
|
+
* @returns An `AbortSignal` that aborts when any valid source aborts,
|
|
1965
|
+
* or `undefined` if no valid sources are provided.
|
|
1966
|
+
*/
|
|
1967
|
+
function mergeAbortSignals(...signals) {
|
|
1968
|
+
const validSignals = filterNullable(...signals).map((signal) => typeof signal === "number" ? AbortSignal.timeout(signal) : signal);
|
|
1969
|
+
return validSignals.length === 0 ? void 0 : validSignals.length === 1 ? validSignals[0] : AbortSignal.any(validSignals);
|
|
1970
|
+
}
|
|
1971
|
+
//#endregion
|
|
1972
|
+
//#region src/util/retry-with-exponential-backoff.ts
|
|
1973
|
+
function getRetryDelayInMs({ error, exponentialBackoffDelay }) {
|
|
1974
|
+
const headers = APICallError.isInstance(error) ? error.responseHeaders : APICallError.isInstance(error.cause) ? error.cause.responseHeaders : void 0;
|
|
1975
|
+
if (!headers) return exponentialBackoffDelay;
|
|
1976
|
+
let ms;
|
|
1977
|
+
const retryAfterMs = headers["retry-after-ms"];
|
|
1978
|
+
if (retryAfterMs) {
|
|
1979
|
+
const timeoutMs = parseFloat(retryAfterMs);
|
|
1980
|
+
if (!Number.isNaN(timeoutMs)) ms = timeoutMs;
|
|
1981
|
+
}
|
|
1982
|
+
const retryAfter = headers["retry-after"];
|
|
1983
|
+
if (retryAfter && ms === void 0) {
|
|
1984
|
+
const timeoutSeconds = parseFloat(retryAfter);
|
|
1985
|
+
if (!Number.isNaN(timeoutSeconds)) ms = timeoutSeconds * 1e3;
|
|
1986
|
+
else ms = Date.parse(retryAfter) - Date.now();
|
|
1987
|
+
}
|
|
1988
|
+
if (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 6e4 || ms < exponentialBackoffDelay)) return ms;
|
|
1989
|
+
return exponentialBackoffDelay;
|
|
1990
|
+
}
|
|
1991
|
+
/**
|
|
1992
|
+
* The `retryWithExponentialBackoffRespectingRetryHeaders` strategy retries a failed API call with an exponential backoff,
|
|
1993
|
+
* while respecting rate limit headers (retry-after-ms and retry-after) if they are provided and reasonable (0-60 seconds).
|
|
1994
|
+
* You can configure the maximum number of retries, the initial delay, and the backoff factor.
|
|
1995
|
+
*/
|
|
1996
|
+
const retryWithExponentialBackoffRespectingRetryHeaders = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal, additionalRetryableError } = {}) => retryWithExponentialBackoff({
|
|
1997
|
+
maxRetries,
|
|
1998
|
+
initialDelayInMs,
|
|
1999
|
+
backoffFactor,
|
|
2000
|
+
abortSignal,
|
|
2001
|
+
shouldRetry: async (error) => error instanceof Error && (APICallError.isInstance(error) && error.isRetryable === true || GatewayError.isInstance(error) && error.isRetryable === true) || additionalRetryableError != null && await additionalRetryableError(error),
|
|
2002
|
+
getDelayInMs: ({ error, exponentialBackoffDelay }) => getRetryDelayInMs({
|
|
2003
|
+
error,
|
|
2004
|
+
exponentialBackoffDelay
|
|
2005
|
+
}),
|
|
2006
|
+
createRetryError: ({ message, reason, errors }) => new RetryError({
|
|
2007
|
+
message,
|
|
2008
|
+
reason,
|
|
2009
|
+
errors
|
|
2010
|
+
})
|
|
2011
|
+
});
|
|
2012
|
+
//#endregion
|
|
2013
|
+
//#region src/util/prepare-retries.ts
|
|
2014
|
+
/**
|
|
2015
|
+
* Validate and prepare retries.
|
|
2016
|
+
*/
|
|
2017
|
+
function prepareRetries({ maxRetries, abortSignal, additionalRetryableError, parameter = "maxRetries", defaultMaxRetries = 2 }) {
|
|
2018
|
+
if (maxRetries != null) {
|
|
2019
|
+
if (!Number.isInteger(maxRetries)) throw new InvalidArgumentError({
|
|
2020
|
+
parameter,
|
|
2021
|
+
value: maxRetries,
|
|
2022
|
+
message: `${parameter} must be an integer`
|
|
2023
|
+
});
|
|
2024
|
+
if (maxRetries < 0) throw new InvalidArgumentError({
|
|
2025
|
+
parameter,
|
|
2026
|
+
value: maxRetries,
|
|
2027
|
+
message: `${parameter} must be >= 0`
|
|
2028
|
+
});
|
|
2029
|
+
}
|
|
2030
|
+
const maxRetriesResult = maxRetries ?? defaultMaxRetries;
|
|
2031
|
+
return {
|
|
2032
|
+
maxRetries: maxRetriesResult,
|
|
2033
|
+
retry: retryWithExponentialBackoffRespectingRetryHeaders({
|
|
2034
|
+
maxRetries: maxRetriesResult,
|
|
2035
|
+
abortSignal,
|
|
2036
|
+
additionalRetryableError
|
|
2037
|
+
})
|
|
2038
|
+
};
|
|
2039
|
+
}
|
|
2040
|
+
//#endregion
|
|
2041
|
+
//#region src/util/set-abort-timeout.ts
|
|
2042
|
+
/**
|
|
2043
|
+
* Schedules a timeout that aborts the given controller with a `TimeoutError`
|
|
2044
|
+
* `DOMException`, matching the reason produced by `AbortSignal.timeout(ms)`.
|
|
2045
|
+
*
|
|
2046
|
+
* @param abortController - The controller to abort when the timeout elapses.
|
|
2047
|
+
* If undefined, no timeout is scheduled.
|
|
2048
|
+
* @param label - Human-readable label included in the error message
|
|
2049
|
+
* (e.g. "Step", "Chunk").
|
|
2050
|
+
* @param timeoutMs - Duration in milliseconds before the controller is aborted.
|
|
2051
|
+
* If undefined, no timeout is scheduled.
|
|
2052
|
+
* @returns The timeout id (suitable for passing to `clearTimeout`), or
|
|
2053
|
+
* `undefined` if no timeout was scheduled.
|
|
2054
|
+
*/
|
|
2055
|
+
function setAbortTimeout({ abortController, label, timeoutMs }) {
|
|
2056
|
+
if (abortController == null || timeoutMs == null) return;
|
|
2057
|
+
return setTimeout(() => abortController.abort(new DOMException(`${label} timeout of ${timeoutMs}ms exceeded`, "TimeoutError")), timeoutMs);
|
|
2058
|
+
}
|
|
2059
|
+
//#endregion
|
|
2060
|
+
//#region src/generate-text/calculate-tokens-per-second.ts
|
|
2061
|
+
/**
|
|
2062
|
+
* Calculates a token rate in tokens per second.
|
|
2063
|
+
*
|
|
2064
|
+
* Returns 0 when the token count is unknown, the duration is unknown or 0, or
|
|
2065
|
+
* the computed rate cannot be represented as a finite JSON-safe number.
|
|
2066
|
+
*/
|
|
2067
|
+
function calculateTokensPerSecond({ tokens, durationMs }) {
|
|
2068
|
+
const tokenRate = 1e3 * (tokens ?? 0) / (durationMs ?? 0);
|
|
2069
|
+
return Number.isFinite(tokenRate) ? tokenRate : 0;
|
|
2070
|
+
}
|
|
2071
|
+
//#endregion
|
|
2072
|
+
//#region src/generate-text/collect-tool-approvals.ts
|
|
2073
|
+
/**
|
|
2074
|
+
* If the last message is a tool message, this function collects all tool approvals
|
|
2075
|
+
* from that message.
|
|
2076
|
+
*/
|
|
2077
|
+
function collectToolApprovals({ messages }) {
|
|
2078
|
+
const lastMessage = messages.at(-1);
|
|
2079
|
+
if (lastMessage?.role != "tool") return {
|
|
2080
|
+
approvedToolApprovals: [],
|
|
2081
|
+
deniedToolApprovals: []
|
|
2082
|
+
};
|
|
2083
|
+
const toolCallsByToolCallId = Object.create(null);
|
|
2084
|
+
const toolCallOrder = Object.create(null);
|
|
2085
|
+
let nextToolCallIndex = 0;
|
|
2086
|
+
for (const message of messages) if (message.role === "assistant" && typeof message.content !== "string") {
|
|
2087
|
+
const content = message.content;
|
|
2088
|
+
for (const part of content) if (part.type === "tool-call") {
|
|
2089
|
+
toolCallsByToolCallId[part.toolCallId] = part;
|
|
2090
|
+
toolCallOrder[part.toolCallId] = nextToolCallIndex++;
|
|
2091
|
+
}
|
|
2092
|
+
}
|
|
2093
|
+
const toolApprovalRequestsByApprovalId = Object.create(null);
|
|
2094
|
+
for (const message of messages) if (message.role === "assistant" && typeof message.content !== "string") {
|
|
2095
|
+
const content = message.content;
|
|
2096
|
+
for (const part of content) if (part.type === "tool-approval-request") toolApprovalRequestsByApprovalId[part.approvalId] = part;
|
|
2097
|
+
}
|
|
2098
|
+
const toolResults = Object.create(null);
|
|
2099
|
+
for (const part of lastMessage.content) if (part.type === "tool-result") toolResults[part.toolCallId] = part;
|
|
2100
|
+
const approvedToolApprovals = [];
|
|
2101
|
+
const deniedToolApprovals = [];
|
|
2102
|
+
const collectedToolCallIds = /* @__PURE__ */ new Set();
|
|
2103
|
+
const approvalResponses = lastMessage.content.filter((part) => part.type === "tool-approval-response");
|
|
2104
|
+
for (const approvalResponse of approvalResponses) {
|
|
2105
|
+
const approvalRequest = toolApprovalRequestsByApprovalId[approvalResponse.approvalId];
|
|
2106
|
+
if (approvalRequest == null) throw new InvalidToolApprovalError({ approvalId: approvalResponse.approvalId });
|
|
2107
|
+
const existingToolResult = toolResults[approvalRequest.toolCallId];
|
|
2108
|
+
if (existingToolResult != null && (approvalResponse.approved || existingToolResult.output.type !== "execution-denied")) continue;
|
|
2109
|
+
const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];
|
|
2110
|
+
if (toolCall == null) throw new ToolCallNotFoundForApprovalError({
|
|
2111
|
+
toolCallId: approvalRequest.toolCallId,
|
|
2112
|
+
approvalId: approvalRequest.approvalId
|
|
2113
|
+
});
|
|
2114
|
+
if (collectedToolCallIds.has(toolCall.toolCallId)) continue;
|
|
2115
|
+
collectedToolCallIds.add(toolCall.toolCallId);
|
|
2116
|
+
const approval = {
|
|
2117
|
+
approvalRequest,
|
|
2118
|
+
approvalResponse,
|
|
2119
|
+
toolCall,
|
|
2120
|
+
...existingToolResult != null ? { existingToolResult } : {}
|
|
2121
|
+
};
|
|
2122
|
+
if (approvalResponse.approved) approvedToolApprovals.push(approval);
|
|
2123
|
+
else deniedToolApprovals.push(approval);
|
|
2124
|
+
}
|
|
2125
|
+
approvedToolApprovals.sort((a, b) => toolCallOrder[a.toolCall.toolCallId] - toolCallOrder[b.toolCall.toolCallId]);
|
|
2126
|
+
return {
|
|
2127
|
+
approvedToolApprovals,
|
|
2128
|
+
deniedToolApprovals
|
|
2129
|
+
};
|
|
2130
|
+
}
|
|
2131
|
+
//#endregion
|
|
2132
|
+
//#region src/generate-text/generated-file.ts
|
|
2133
|
+
var DefaultGeneratedFile = class {
|
|
2134
|
+
constructor({ data, mediaType, providerMetadata }) {
|
|
2135
|
+
this.base64Data = typeof data === "string" ? data : void 0;
|
|
2136
|
+
this.uint8ArrayData = typeof data === "string" ? void 0 : convertDataContentToUint8Array(data);
|
|
2137
|
+
this.mediaType = mediaType;
|
|
2138
|
+
this.providerMetadata = providerMetadata;
|
|
2139
|
+
}
|
|
2140
|
+
get base64() {
|
|
2141
|
+
if (this.base64Data == null) this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData);
|
|
2142
|
+
return this.base64Data;
|
|
2143
|
+
}
|
|
2144
|
+
get uint8Array() {
|
|
2145
|
+
if (this.uint8ArrayData == null) this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data);
|
|
2146
|
+
return this.uint8ArrayData;
|
|
2147
|
+
}
|
|
2148
|
+
};
|
|
2149
|
+
var DefaultGeneratedFileWithType = class extends DefaultGeneratedFile {
|
|
2150
|
+
constructor(..._args) {
|
|
2151
|
+
super(..._args);
|
|
2152
|
+
this.type = "file";
|
|
2153
|
+
}
|
|
2154
|
+
};
|
|
2155
|
+
//#endregion
|
|
2156
|
+
//#region src/generate-text/resolve-generated-file-data.ts
|
|
2157
|
+
async function resolveGeneratedFileData({ data, download: download$1, abortSignal, cache }) {
|
|
2158
|
+
if (data.type === "data") return data.data;
|
|
2159
|
+
const cachedData = cache?.get(data);
|
|
2160
|
+
if (cachedData != null) return cachedData;
|
|
2161
|
+
const downloadedData = download$1 == null ? (await download({
|
|
2162
|
+
url: data.url,
|
|
2163
|
+
abortSignal
|
|
2164
|
+
})).data : await downloadGeneratedFile({
|
|
2165
|
+
url: data.url,
|
|
2166
|
+
download: download$1,
|
|
2167
|
+
abortSignal
|
|
2168
|
+
});
|
|
2169
|
+
cache?.set(data, downloadedData);
|
|
2170
|
+
return downloadedData;
|
|
2171
|
+
}
|
|
2172
|
+
async function downloadGeneratedFile({ url, download, abortSignal }) {
|
|
2173
|
+
const [result] = await download([{
|
|
2174
|
+
url,
|
|
2175
|
+
isUrlSupportedByModel: false,
|
|
2176
|
+
abortSignal
|
|
2177
|
+
}]);
|
|
2178
|
+
if (result == null) throw new DownloadError({
|
|
2179
|
+
url: url.toString(),
|
|
2180
|
+
message: `Generated file URL ${url} must be downloaded, but the download function returned null`
|
|
2181
|
+
});
|
|
2182
|
+
return result.data;
|
|
2183
|
+
}
|
|
2184
|
+
//#endregion
|
|
2185
|
+
//#region src/generate-text/convert-language-model-content.ts
|
|
2186
|
+
async function convertLanguageModelContent({ content, toolCalls, toolOutputs, toolApprovalRequests, toolApprovalResponses, tools, download, abortSignal, generatedFileDataCache }) {
|
|
2187
|
+
const contentParts = [];
|
|
2188
|
+
const toolOutputsWithApprovalResponses = [];
|
|
2189
|
+
const toolOutputsWithoutApprovalResponses = [];
|
|
2190
|
+
const toolCallIdsWithApprovalResponses = new Set(toolApprovalResponses.map((toolApprovalResponse) => toolApprovalResponse.toolCall.toolCallId));
|
|
2191
|
+
for (const part of content) switch (part.type) {
|
|
2192
|
+
case "text":
|
|
2193
|
+
case "reasoning":
|
|
2194
|
+
case "custom":
|
|
2195
|
+
case "source":
|
|
2196
|
+
contentParts.push(part);
|
|
2197
|
+
break;
|
|
2198
|
+
case "file":
|
|
2199
|
+
case "reasoning-file":
|
|
2200
|
+
contentParts.push({
|
|
2201
|
+
type: part.type,
|
|
2202
|
+
file: new DefaultGeneratedFile({
|
|
2203
|
+
data: await resolveGeneratedFileData({
|
|
2204
|
+
data: part.data,
|
|
2205
|
+
download,
|
|
2206
|
+
abortSignal,
|
|
2207
|
+
cache: generatedFileDataCache
|
|
2208
|
+
}),
|
|
2209
|
+
mediaType: part.mediaType
|
|
2210
|
+
}),
|
|
2211
|
+
...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
|
|
2212
|
+
});
|
|
2213
|
+
break;
|
|
2214
|
+
case "tool-call": {
|
|
2215
|
+
const toolCall = toolCalls.find((toolCall) => toolCall.toolCallId === part.toolCallId);
|
|
2216
|
+
if (toolCall == null) throw new Error(`Tool call ${part.toolCallId} not found.`);
|
|
2217
|
+
contentParts.push(toolCall);
|
|
2218
|
+
break;
|
|
2219
|
+
}
|
|
2220
|
+
case "tool-result": {
|
|
2221
|
+
const toolCall = toolCalls.find((toolCall) => toolCall.toolCallId === part.toolCallId);
|
|
2222
|
+
if (toolCall == null) {
|
|
2223
|
+
const tool = getOwn(tools, part.toolName);
|
|
2224
|
+
if (!(tool?.type === "provider" && tool.supportsDeferredResults)) throw new Error(`Tool call ${part.toolCallId} not found.`);
|
|
2225
|
+
if (part.isError) contentParts.push({
|
|
2226
|
+
type: "tool-error",
|
|
2227
|
+
toolCallId: part.toolCallId,
|
|
2228
|
+
toolName: part.toolName,
|
|
2229
|
+
input: void 0,
|
|
2230
|
+
error: part.result,
|
|
2231
|
+
providerExecuted: true,
|
|
2232
|
+
dynamic: part.dynamic,
|
|
2233
|
+
...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},
|
|
2234
|
+
...tool?.metadata != null ? { toolMetadata: tool.metadata } : {}
|
|
2235
|
+
});
|
|
2236
|
+
else contentParts.push({
|
|
2237
|
+
type: "tool-result",
|
|
2238
|
+
toolCallId: part.toolCallId,
|
|
2239
|
+
toolName: part.toolName,
|
|
2240
|
+
input: void 0,
|
|
2241
|
+
output: part.result,
|
|
2242
|
+
providerExecuted: true,
|
|
2243
|
+
dynamic: part.dynamic,
|
|
2244
|
+
...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},
|
|
2245
|
+
...tool?.metadata != null ? { toolMetadata: tool.metadata } : {}
|
|
2246
|
+
});
|
|
2247
|
+
break;
|
|
2248
|
+
}
|
|
2249
|
+
if (part.isError) contentParts.push({
|
|
2250
|
+
type: "tool-error",
|
|
2251
|
+
toolCallId: part.toolCallId,
|
|
2252
|
+
toolName: part.toolName,
|
|
2253
|
+
input: toolCall.input,
|
|
2254
|
+
error: part.result,
|
|
2255
|
+
providerExecuted: true,
|
|
2256
|
+
dynamic: toolCall.dynamic,
|
|
2257
|
+
...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},
|
|
2258
|
+
...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}
|
|
2259
|
+
});
|
|
2260
|
+
else contentParts.push({
|
|
2261
|
+
type: "tool-result",
|
|
2262
|
+
toolCallId: part.toolCallId,
|
|
2263
|
+
toolName: part.toolName,
|
|
2264
|
+
input: toolCall.input,
|
|
2265
|
+
output: part.result,
|
|
2266
|
+
providerExecuted: true,
|
|
2267
|
+
dynamic: toolCall.dynamic,
|
|
2268
|
+
...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},
|
|
2269
|
+
...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}
|
|
2270
|
+
});
|
|
2271
|
+
break;
|
|
2272
|
+
}
|
|
2273
|
+
case "tool-approval-request": {
|
|
2274
|
+
const toolCall = toolCalls.find((toolCall) => toolCall.toolCallId === part.toolCallId);
|
|
2275
|
+
if (toolCall == null) throw new ToolCallNotFoundForApprovalError({
|
|
2276
|
+
toolCallId: part.toolCallId,
|
|
2277
|
+
approvalId: part.approvalId
|
|
2278
|
+
});
|
|
2279
|
+
contentParts.push({
|
|
2280
|
+
type: "tool-approval-request",
|
|
2281
|
+
approvalId: part.approvalId,
|
|
2282
|
+
toolCall
|
|
2283
|
+
});
|
|
2284
|
+
break;
|
|
2285
|
+
}
|
|
2286
|
+
}
|
|
2287
|
+
for (const toolOutput of toolOutputs) if (toolCallIdsWithApprovalResponses.has(toolOutput.toolCallId)) toolOutputsWithApprovalResponses.push(toolOutput);
|
|
2288
|
+
else toolOutputsWithoutApprovalResponses.push(toolOutput);
|
|
2289
|
+
return [
|
|
2290
|
+
...contentParts,
|
|
2291
|
+
...toolOutputsWithoutApprovalResponses,
|
|
2292
|
+
...toolApprovalRequests,
|
|
2293
|
+
...toolApprovalResponses,
|
|
2294
|
+
...toolOutputsWithApprovalResponses
|
|
2295
|
+
];
|
|
2296
|
+
}
|
|
2297
|
+
function resolveToolCallerConfiguration({ tools, toolCallers }) {
|
|
2298
|
+
if (tools == null || toolCallers == null) return;
|
|
2299
|
+
const resolved = {};
|
|
2300
|
+
for (const [toolName, callers] of Object.entries(toolCallers)) {
|
|
2301
|
+
if (!Object.prototype.hasOwnProperty.call(tools, toolName)) throw new InvalidArgumentError({
|
|
2302
|
+
parameter: "experimental_toolCallers",
|
|
2303
|
+
value: toolCallers,
|
|
2304
|
+
message: `unknown tool "${toolName}".`
|
|
2305
|
+
});
|
|
2306
|
+
if (callers != null) resolved[toolName] = callers;
|
|
2307
|
+
}
|
|
2308
|
+
return resolved;
|
|
2309
|
+
}
|
|
2310
|
+
function prepareToolsForToolCallers({ tools, toolCallers }) {
|
|
2311
|
+
if (tools == null || toolCallers == null) return {
|
|
2312
|
+
executionTools: tools,
|
|
2313
|
+
modelTools: tools,
|
|
2314
|
+
toolCallerMessages: []
|
|
2315
|
+
};
|
|
2316
|
+
const executionTools = { ...tools };
|
|
2317
|
+
const modelTools = { ...tools };
|
|
2318
|
+
const localToolsByCaller = /* @__PURE__ */ new Map();
|
|
2319
|
+
const toolCallerMessages = [];
|
|
2320
|
+
for (const [toolName, callerNames] of Object.entries(toolCallers)) {
|
|
2321
|
+
const tool = executionTools[toolName];
|
|
2322
|
+
if (tool == null) continue;
|
|
2323
|
+
let availableDirectly = false;
|
|
2324
|
+
let availableToProvider = false;
|
|
2325
|
+
let preparedTool = tool;
|
|
2326
|
+
for (const callerName of callerNames) {
|
|
2327
|
+
if (callerName === "AI_SDK_DIRECT_TOOL_CALL") {
|
|
2328
|
+
availableDirectly = true;
|
|
2329
|
+
continue;
|
|
2330
|
+
}
|
|
2331
|
+
const caller = experimental_getToolCaller(executionTools[callerName]);
|
|
2332
|
+
if (caller == null) continue;
|
|
2333
|
+
if (caller.type === "provider") {
|
|
2334
|
+
availableToProvider = true;
|
|
2335
|
+
preparedTool = {
|
|
2336
|
+
...preparedTool,
|
|
2337
|
+
providerOptions: caller.prepareProviderOptions(preparedTool.providerOptions)
|
|
2338
|
+
};
|
|
2339
|
+
} else {
|
|
2340
|
+
const localTools = localToolsByCaller.get(callerName) ?? {};
|
|
2341
|
+
localTools[toolName] = preparedTool;
|
|
2342
|
+
localToolsByCaller.set(callerName, localTools);
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
executionTools[toolName] = preparedTool;
|
|
2346
|
+
if (availableDirectly || availableToProvider) modelTools[toolName] = preparedTool;
|
|
2347
|
+
else delete modelTools[toolName];
|
|
2348
|
+
}
|
|
2349
|
+
for (const [callerName, callerTool] of Object.entries(executionTools)) {
|
|
2350
|
+
const caller = experimental_getToolCaller(callerTool);
|
|
2351
|
+
if (caller?.type !== "local") continue;
|
|
2352
|
+
const callerTools = localToolsByCaller.get(callerName) ?? {};
|
|
2353
|
+
const boundCaller = caller.bind(callerTools);
|
|
2354
|
+
executionTools[callerName] = boundCaller;
|
|
2355
|
+
if (Object.prototype.hasOwnProperty.call(modelTools, callerName)) {
|
|
2356
|
+
if (caller.prepareModelMessage == null) modelTools[callerName] = boundCaller;
|
|
2357
|
+
else {
|
|
2358
|
+
const content = caller.prepareModelMessage(callerTools);
|
|
2359
|
+
if (content != null) toolCallerMessages.push({
|
|
2360
|
+
role: "user",
|
|
2361
|
+
content
|
|
2362
|
+
});
|
|
2363
|
+
}
|
|
2364
|
+
}
|
|
2365
|
+
}
|
|
2366
|
+
return {
|
|
2367
|
+
executionTools,
|
|
2368
|
+
modelTools,
|
|
2369
|
+
toolCallerMessages
|
|
2370
|
+
};
|
|
2371
|
+
}
|
|
2372
|
+
function appendToolCallerMessages({ messages, toolCallerMessages }) {
|
|
2373
|
+
if (toolCallerMessages.length === 0) return messages;
|
|
2374
|
+
const latestUserText = messages.findLast((message) => message.role === "user" && typeof message.content === "string")?.content;
|
|
2375
|
+
const existingUserText = new Set(latestUserText == null ? [] : [latestUserText]);
|
|
2376
|
+
const additions = toolCallerMessages.filter((message) => {
|
|
2377
|
+
if (typeof message.content !== "string" || existingUserText.has(message.content)) return false;
|
|
2378
|
+
existingUserText.add(message.content);
|
|
2379
|
+
return true;
|
|
2380
|
+
});
|
|
2381
|
+
return additions.length === 0 ? messages : [...messages, ...additions];
|
|
2382
|
+
}
|
|
2383
|
+
//#endregion
|
|
2384
|
+
//#region src/tool-search/tool-search.ts
|
|
2385
|
+
const toolSearchSymbol = Symbol.for("vercel.ai.toolSearch");
|
|
2386
|
+
const toolSearchFunctionSymbol = Symbol.for("vercel.ai.toolSearch.search");
|
|
2387
|
+
const toolSearchMaxResultsSymbol = Symbol.for("vercel.ai.toolSearch.maxResults");
|
|
2388
|
+
/**
|
|
2389
|
+
* Search deferred tools by name and description. The surrounding generation
|
|
2390
|
+
* binds the search registry and makes matches available on the next step.
|
|
2391
|
+
* Use directly or through code mode with `toolDiscovery: 'conversation'`.
|
|
2392
|
+
*/
|
|
2393
|
+
function toolSearch({ search, maxResults = 5 } = {}) {
|
|
2394
|
+
if (!Number.isSafeInteger(maxResults) || maxResults < 1) throw new InvalidArgumentError({
|
|
2395
|
+
parameter: "maxResults",
|
|
2396
|
+
value: maxResults,
|
|
2397
|
+
message: "maxResults must be a positive safe integer."
|
|
2398
|
+
});
|
|
2399
|
+
return Object.assign(tool({
|
|
2400
|
+
description: `${search == null ? "Search for tools by keywords in their names and descriptions." : "Search for tools matching a query."} Returns up to ${maxResults === 5 ? "five" : maxResults} matching tools. Matches become available on the next model step, after this execution finishes. Wait for their tool definitions before calling the discovered tools. If no tools match, try different keywords.`,
|
|
2401
|
+
inputSchema: jsonSchema({
|
|
2402
|
+
type: "object",
|
|
2403
|
+
properties: { query: {
|
|
2404
|
+
type: "string",
|
|
2405
|
+
minLength: 1
|
|
2406
|
+
} },
|
|
2407
|
+
required: ["query"],
|
|
2408
|
+
additionalProperties: false
|
|
2409
|
+
}),
|
|
2410
|
+
outputSchema: jsonSchema({
|
|
2411
|
+
type: "object",
|
|
2412
|
+
properties: { tools: {
|
|
2413
|
+
type: "array",
|
|
2414
|
+
items: {
|
|
2415
|
+
type: "object",
|
|
2416
|
+
properties: {
|
|
2417
|
+
name: { type: "string" },
|
|
2418
|
+
description: { type: "string" }
|
|
2419
|
+
},
|
|
2420
|
+
required: ["name"],
|
|
2421
|
+
additionalProperties: false
|
|
2422
|
+
}
|
|
2423
|
+
} },
|
|
2424
|
+
required: ["tools"],
|
|
2425
|
+
additionalProperties: false
|
|
2426
|
+
}),
|
|
2427
|
+
execute: () => {
|
|
2428
|
+
throw new Error("toolSearch must be bound by an AI SDK generation.");
|
|
2429
|
+
}
|
|
2430
|
+
}), {
|
|
2431
|
+
type: "function",
|
|
2432
|
+
[toolSearchSymbol]: true,
|
|
2433
|
+
[toolSearchFunctionSymbol]: search,
|
|
2434
|
+
[toolSearchMaxResultsSymbol]: maxResults
|
|
2435
|
+
});
|
|
2436
|
+
}
|
|
2437
|
+
function getToolSearchMaxResults(tool) {
|
|
2438
|
+
return tool[toolSearchMaxResultsSymbol] ?? 5;
|
|
2439
|
+
}
|
|
2440
|
+
function getToolSearchFunction(tool) {
|
|
2441
|
+
return tool[toolSearchFunctionSymbol];
|
|
2442
|
+
}
|
|
2443
|
+
function isToolSearch(tool) {
|
|
2444
|
+
return tool[toolSearchSymbol] === true;
|
|
2445
|
+
}
|
|
2446
|
+
//#endregion
|
|
2447
|
+
//#region src/tool-search/prepare-tool-search.ts
|
|
2448
|
+
/** Create discovery state for one generation, never for a shared tool instance. */
|
|
2449
|
+
function createToolSearchState({ tools, toolCallers }) {
|
|
2450
|
+
const searchTools = Object.entries(tools ?? {}).filter(([, tool]) => tool.deferLoading || isToolSearch(tool));
|
|
2451
|
+
if (searchTools.length === 0) return (activeTools) => activeTools;
|
|
2452
|
+
const discovered = /* @__PURE__ */ new Set();
|
|
2453
|
+
const getCallers = (name) => getOwn(toolCallers, name) ?? ["AI_SDK_DIRECT_TOOL_CALL"];
|
|
2454
|
+
for (const [name, tool] of searchTools) if (getCallers(name).some((name) => {
|
|
2455
|
+
if (name === "AI_SDK_DIRECT_TOOL_CALL") return false;
|
|
2456
|
+
const caller = experimental_getToolCaller(tools?.[name]);
|
|
2457
|
+
return caller?.type !== "local" || caller.prepareModelMessage == null;
|
|
2458
|
+
}) || isToolSearch(tool) && tool.deferLoading) throw new InvalidArgumentError({
|
|
2459
|
+
parameter: "tools",
|
|
2460
|
+
value: name,
|
|
2461
|
+
message: `tool "${name}" must be callable directly or through code mode with toolDiscovery: 'conversation'. The search tool itself must not defer loading.`
|
|
2462
|
+
});
|
|
2463
|
+
return (activeTools, { toolsContext = {}, experimental_sandbox } = {}) => {
|
|
2464
|
+
if (activeTools == null) return;
|
|
2465
|
+
const entries = Object.entries(activeTools);
|
|
2466
|
+
return Object.fromEntries(entries.filter(([name, tool]) => !tool.deferLoading || discovered.has(name)).map(([searchName, tool]) => {
|
|
2467
|
+
if (!isToolSearch(tool)) return [searchName, tool];
|
|
2468
|
+
const callers = getCallers(searchName).filter((name) => name === "AI_SDK_DIRECT_TOOL_CALL" || Object.hasOwn(activeTools, name));
|
|
2469
|
+
const candidates = entries.filter(([name, candidate]) => candidate.deferLoading && !isToolSearch(candidate) && callers.some((caller) => getCallers(name).includes(caller)));
|
|
2470
|
+
return [searchName, {
|
|
2471
|
+
...tool,
|
|
2472
|
+
execute: async ({ query }) => {
|
|
2473
|
+
const availableTools = candidates.map(([name, candidate]) => {
|
|
2474
|
+
const description = resolveToolDescription({
|
|
2475
|
+
tool: candidate,
|
|
2476
|
+
toolName: name,
|
|
2477
|
+
toolsContext,
|
|
2478
|
+
experimental_sandbox
|
|
2479
|
+
});
|
|
2480
|
+
return {
|
|
2481
|
+
name,
|
|
2482
|
+
...description == null ? {} : { description }
|
|
2483
|
+
};
|
|
2484
|
+
});
|
|
2485
|
+
const toolsByName = new Map(availableTools.map((tool) => [tool.name, tool]));
|
|
2486
|
+
const customSearch = getToolSearchFunction(tool);
|
|
2487
|
+
const terms = [...new Set(tokenize(query))];
|
|
2488
|
+
const rankedNames = customSearch ? await customSearch({
|
|
2489
|
+
query,
|
|
2490
|
+
tools: availableTools.map((tool) => ({ ...tool }))
|
|
2491
|
+
}) : availableTools.map(({ name, description }) => {
|
|
2492
|
+
const nameTerms = tokenize(name);
|
|
2493
|
+
const descriptionTerms = tokenize(description ?? "");
|
|
2494
|
+
return {
|
|
2495
|
+
name,
|
|
2496
|
+
score: terms.reduce((score, term) => score + (nameTerms.includes(term) ? 2 : 0) + (descriptionTerms.includes(term) ? 1 : 0), 0)
|
|
2497
|
+
};
|
|
2498
|
+
}).filter((match) => match.score > 0).sort((a, b) => b.score - a.score).map((match) => match.name);
|
|
2499
|
+
const matches = [...new Set(rankedNames)].flatMap((name) => {
|
|
2500
|
+
const match = toolsByName.get(name);
|
|
2501
|
+
return match == null ? [] : [match];
|
|
2502
|
+
}).slice(0, getToolSearchMaxResults(tool));
|
|
2503
|
+
for (const { name } of matches) discovered.add(name);
|
|
2504
|
+
return { tools: matches };
|
|
2505
|
+
}
|
|
2506
|
+
}];
|
|
2507
|
+
}));
|
|
2508
|
+
};
|
|
2509
|
+
}
|
|
2510
|
+
function tokenize(text) {
|
|
2511
|
+
return text.replace(/([a-z\d])([A-Z])/g, "$1 $2").toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
|
|
2512
|
+
}
|
|
2513
|
+
//#endregion
|
|
2514
|
+
//#region src/generate-text/validate-tool-context.ts
|
|
2515
|
+
/**
|
|
2516
|
+
* Validates a tool context value against the tool's optional context schema.
|
|
2517
|
+
*
|
|
2518
|
+
* When no context schema is defined, the original context value is returned as-is.
|
|
2519
|
+
* Otherwise, the context is validated and normalized through the schema before
|
|
2520
|
+
* being passed into tool execution and approval hooks.
|
|
2521
|
+
*
|
|
2522
|
+
* @throws {TypeValidationError} When the provided tool context does not match
|
|
2523
|
+
* the tool's declared `contextSchema`.
|
|
2524
|
+
*/
|
|
2525
|
+
async function validateToolContext({ toolName, context, contextSchema }) {
|
|
2526
|
+
if (contextSchema == null) return context;
|
|
2527
|
+
return await validateTypes({
|
|
2528
|
+
value: context,
|
|
2529
|
+
schema: contextSchema,
|
|
2530
|
+
context: {
|
|
2531
|
+
field: "tool context",
|
|
2532
|
+
entityName: toolName
|
|
2533
|
+
}
|
|
2534
|
+
});
|
|
2535
|
+
}
|
|
2536
|
+
//#endregion
|
|
2537
|
+
//#region src/generate-text/reasoning-output.ts
|
|
2538
|
+
function unwrapReasoningFileData(data) {
|
|
2539
|
+
if (typeof data === "object" && data !== null && "type" in data) return data.type === "data" ? data.data : data.url;
|
|
2540
|
+
return data;
|
|
2541
|
+
}
|
|
2542
|
+
function convertFromReasoningOutputs(parts) {
|
|
2543
|
+
return parts.map((part) => {
|
|
2544
|
+
if (part.type === "reasoning") return {
|
|
2545
|
+
type: "reasoning",
|
|
2546
|
+
text: part.text,
|
|
2547
|
+
...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}
|
|
2548
|
+
};
|
|
2549
|
+
return {
|
|
2550
|
+
type: "reasoning-file",
|
|
2551
|
+
data: part.file.base64,
|
|
2552
|
+
mediaType: part.file.mediaType,
|
|
2553
|
+
...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}
|
|
2554
|
+
};
|
|
2555
|
+
});
|
|
2556
|
+
}
|
|
2557
|
+
function convertToReasoningOutputs(parts) {
|
|
2558
|
+
return parts.map((part) => {
|
|
2559
|
+
if (part.type === "reasoning") return {
|
|
2560
|
+
type: "reasoning",
|
|
2561
|
+
text: part.text,
|
|
2562
|
+
...part.providerOptions != null ? { providerMetadata: part.providerOptions } : {}
|
|
2563
|
+
};
|
|
2564
|
+
const rawData = unwrapReasoningFileData(part.data);
|
|
2565
|
+
return {
|
|
2566
|
+
type: "reasoning-file",
|
|
2567
|
+
file: new DefaultGeneratedFile({
|
|
2568
|
+
data: rawData instanceof ArrayBuffer ? new Uint8Array(rawData) : rawData instanceof URL ? rawData.toString() : rawData,
|
|
2569
|
+
mediaType: part.mediaType
|
|
2570
|
+
}),
|
|
2571
|
+
...part.providerOptions != null ? { providerMetadata: part.providerOptions } : {}
|
|
2572
|
+
};
|
|
2573
|
+
});
|
|
2574
|
+
}
|
|
2575
|
+
//#endregion
|
|
2576
|
+
//#region src/generate-text/default-generate-text-result.ts
|
|
2577
|
+
var DefaultGenerateTextResult = class {
|
|
2578
|
+
constructor(options) {
|
|
2579
|
+
this.initialResponseMessages = options.initialResponseMessages;
|
|
2580
|
+
this.steps = options.steps;
|
|
2581
|
+
this._output = options.output;
|
|
2582
|
+
this.totalUsage = options.totalUsage;
|
|
2583
|
+
}
|
|
2584
|
+
get finalStep() {
|
|
2585
|
+
return this.steps.at(-1);
|
|
2586
|
+
}
|
|
2587
|
+
get content() {
|
|
2588
|
+
return this.steps.flatMap((step) => step.content);
|
|
2589
|
+
}
|
|
2590
|
+
get text() {
|
|
2591
|
+
return this.finalStep.text;
|
|
2592
|
+
}
|
|
2593
|
+
get files() {
|
|
2594
|
+
return this.steps.flatMap((step) => step.files);
|
|
2595
|
+
}
|
|
2596
|
+
get reasoningText() {
|
|
2597
|
+
return this.finalStep.reasoningText;
|
|
2598
|
+
}
|
|
2599
|
+
get reasoning() {
|
|
2600
|
+
return convertToReasoningOutputs(this.finalStep.reasoning);
|
|
2601
|
+
}
|
|
2602
|
+
get toolCalls() {
|
|
2603
|
+
return this.steps.flatMap((step) => step.toolCalls);
|
|
2604
|
+
}
|
|
2605
|
+
get staticToolCalls() {
|
|
2606
|
+
return this.steps.flatMap((step) => step.staticToolCalls);
|
|
2607
|
+
}
|
|
2608
|
+
get dynamicToolCalls() {
|
|
2609
|
+
return this.steps.flatMap((step) => step.dynamicToolCalls);
|
|
2610
|
+
}
|
|
2611
|
+
get toolResults() {
|
|
2612
|
+
return this.steps.flatMap((step) => step.toolResults);
|
|
2613
|
+
}
|
|
2614
|
+
get staticToolResults() {
|
|
2615
|
+
return this.steps.flatMap((step) => step.staticToolResults);
|
|
2616
|
+
}
|
|
2617
|
+
get dynamicToolResults() {
|
|
2618
|
+
return this.steps.flatMap((step) => step.dynamicToolResults);
|
|
2619
|
+
}
|
|
2620
|
+
get sources() {
|
|
2621
|
+
return this.steps.flatMap((step) => step.sources);
|
|
2622
|
+
}
|
|
2623
|
+
get finishReason() {
|
|
2624
|
+
return this.finalStep.finishReason;
|
|
2625
|
+
}
|
|
2626
|
+
get rawFinishReason() {
|
|
2627
|
+
return this.finalStep.rawFinishReason;
|
|
2628
|
+
}
|
|
2629
|
+
get warnings() {
|
|
2630
|
+
return this.steps.flatMap((step) => step.warnings ?? []);
|
|
2631
|
+
}
|
|
2632
|
+
get providerMetadata() {
|
|
2633
|
+
return this.finalStep.providerMetadata;
|
|
2634
|
+
}
|
|
2635
|
+
get response() {
|
|
2636
|
+
return this.finalStep.response;
|
|
2637
|
+
}
|
|
2638
|
+
get responseMessages() {
|
|
2639
|
+
return [...this.initialResponseMessages, ...this.steps.flatMap((step) => step.response.messages)];
|
|
2640
|
+
}
|
|
2641
|
+
get request() {
|
|
2642
|
+
return this.finalStep.request;
|
|
2643
|
+
}
|
|
2644
|
+
get usage() {
|
|
2645
|
+
return this.totalUsage;
|
|
2646
|
+
}
|
|
2647
|
+
get output() {
|
|
2648
|
+
if (this._output == null) throw new NoOutputGeneratedError();
|
|
2649
|
+
return this._output;
|
|
2650
|
+
}
|
|
2651
|
+
};
|
|
2652
|
+
//#endregion
|
|
2653
|
+
//#region src/generate-text/tool-call.ts
|
|
2654
|
+
const inputSchemaInputSymbol = Symbol("ai-sdk-tool-call-input-schema-input");
|
|
2655
|
+
function setToolCallInputSchemaInput(toolCall, inputSchemaInput) {
|
|
2656
|
+
Object.defineProperty(toolCall, inputSchemaInputSymbol, { value: inputSchemaInput });
|
|
2657
|
+
return toolCall;
|
|
2658
|
+
}
|
|
2659
|
+
function getToolCallInputSchemaInput(toolCall) {
|
|
2660
|
+
return inputSchemaInputSymbol in toolCall ? { value: toolCall[inputSchemaInputSymbol] } : void 0;
|
|
2661
|
+
}
|
|
2662
|
+
//#endregion
|
|
2663
|
+
//#region src/generate-text/parse-tool-call.ts
|
|
2664
|
+
async function parseToolCall({ toolCall, tools, repairToolCall, refineToolInput, messages, instructions, abortSignal }) {
|
|
2665
|
+
try {
|
|
2666
|
+
if (tools == null) {
|
|
2667
|
+
if (toolCall.providerExecuted && toolCall.dynamic) return await refineParsedToolCallInput({
|
|
2668
|
+
toolCall: await parseProviderExecutedDynamicToolCall(toolCall),
|
|
2669
|
+
refineToolInput
|
|
2670
|
+
});
|
|
2671
|
+
throw new NoSuchToolError({ toolName: toolCall.toolName });
|
|
2672
|
+
}
|
|
2673
|
+
try {
|
|
2674
|
+
return await refineParsedToolCallInput({
|
|
2675
|
+
toolCall: await doParseToolCall({
|
|
2676
|
+
toolCall,
|
|
2677
|
+
tools
|
|
2678
|
+
}),
|
|
2679
|
+
refineToolInput
|
|
2680
|
+
});
|
|
2681
|
+
} catch (error) {
|
|
2682
|
+
if (repairToolCall == null || !(NoSuchToolError.isInstance(error) || InvalidToolInputError.isInstance(error))) throw error;
|
|
2683
|
+
let repairedToolCall = null;
|
|
2684
|
+
try {
|
|
2685
|
+
abortSignal?.throwIfAborted();
|
|
2686
|
+
repairedToolCall = await waitForPromiseWithAbortSignal({
|
|
2687
|
+
promise: repairToolCall({
|
|
2688
|
+
toolCall,
|
|
2689
|
+
tools,
|
|
2690
|
+
inputSchema: async ({ toolName }) => {
|
|
2691
|
+
const inputSchema = getOwn(tools, toolName)?.inputSchema;
|
|
2692
|
+
return await asSchema(inputSchema).jsonSchema;
|
|
2693
|
+
},
|
|
2694
|
+
instructions,
|
|
2695
|
+
system: instructions,
|
|
2696
|
+
messages,
|
|
2697
|
+
error,
|
|
2698
|
+
abortSignal
|
|
2699
|
+
}),
|
|
2700
|
+
abortSignal
|
|
2701
|
+
});
|
|
2702
|
+
} catch (repairError) {
|
|
2703
|
+
abortSignal?.throwIfAborted();
|
|
2704
|
+
throw new ToolCallRepairError({
|
|
2705
|
+
cause: repairError,
|
|
2706
|
+
originalError: error
|
|
2707
|
+
});
|
|
2708
|
+
}
|
|
2709
|
+
if (repairedToolCall == null) throw error;
|
|
2710
|
+
const parsedRepairedToolCall = await refineParsedToolCallInput({
|
|
2711
|
+
toolCall: await doParseToolCall({
|
|
2712
|
+
toolCall: repairedToolCall,
|
|
2713
|
+
tools
|
|
2714
|
+
}),
|
|
2715
|
+
refineToolInput
|
|
2716
|
+
});
|
|
2717
|
+
abortSignal?.throwIfAborted();
|
|
2718
|
+
return parsedRepairedToolCall;
|
|
2719
|
+
}
|
|
2720
|
+
} catch (error) {
|
|
2721
|
+
abortSignal?.throwIfAborted();
|
|
2722
|
+
const parsedInput = await safeParseJSON({ text: toolCall.input });
|
|
2723
|
+
const input = parsedInput.success ? parsedInput.value : toolCall.input;
|
|
2724
|
+
const tool = getOwn(tools, toolCall.toolName);
|
|
2725
|
+
return {
|
|
2726
|
+
type: "tool-call",
|
|
2727
|
+
toolCallId: toolCall.toolCallId,
|
|
2728
|
+
toolName: toolCall.toolName,
|
|
2729
|
+
input,
|
|
2730
|
+
dynamic: true,
|
|
2731
|
+
invalid: true,
|
|
2732
|
+
error,
|
|
2733
|
+
title: tool?.title,
|
|
2734
|
+
providerExecuted: toolCall.providerExecuted,
|
|
2735
|
+
providerMetadata: toolCall.providerMetadata,
|
|
2736
|
+
...tool?.metadata != null ? { toolMetadata: tool.metadata } : {}
|
|
2737
|
+
};
|
|
2738
|
+
}
|
|
2739
|
+
}
|
|
2740
|
+
async function waitForPromiseWithAbortSignal({ promise, abortSignal }) {
|
|
2741
|
+
if (abortSignal == null) return await promise;
|
|
2742
|
+
return await new Promise((resolve, reject) => {
|
|
2743
|
+
const cleanup = () => {
|
|
2744
|
+
abortSignal.removeEventListener("abort", onAbort);
|
|
2745
|
+
};
|
|
2746
|
+
const onAbort = () => {
|
|
2747
|
+
cleanup();
|
|
2748
|
+
reject(abortSignal.reason);
|
|
2749
|
+
};
|
|
2750
|
+
Promise.resolve(promise).then((value) => {
|
|
2751
|
+
cleanup();
|
|
2752
|
+
resolve(value);
|
|
2753
|
+
}).catch((error) => {
|
|
2754
|
+
cleanup();
|
|
2755
|
+
reject(error);
|
|
2756
|
+
});
|
|
2757
|
+
abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
2758
|
+
if (abortSignal.aborted) onAbort();
|
|
2759
|
+
});
|
|
2760
|
+
}
|
|
2761
|
+
async function refineParsedToolCallInput({ toolCall, refineToolInput }) {
|
|
2762
|
+
const refine = getOwn(refineToolInput, toolCall.toolName);
|
|
2763
|
+
if (refine == null) return toolCall;
|
|
2764
|
+
const refinedToolCall = {
|
|
2765
|
+
...toolCall,
|
|
2766
|
+
input: await refine(toolCall.input)
|
|
2767
|
+
};
|
|
2768
|
+
const inputSchemaInput = getToolCallInputSchemaInput(toolCall);
|
|
2769
|
+
return inputSchemaInput == null ? refinedToolCall : setToolCallInputSchemaInput(refinedToolCall, inputSchemaInput.value);
|
|
2770
|
+
}
|
|
2771
|
+
async function parseProviderExecutedDynamicToolCall(toolCall) {
|
|
2772
|
+
const parseResult = toolCall.input.trim() === "" ? {
|
|
2773
|
+
success: true,
|
|
2774
|
+
value: {}
|
|
2775
|
+
} : await safeParseJSON({ text: toolCall.input });
|
|
2776
|
+
if (parseResult.success === false) throw new InvalidToolInputError({
|
|
2777
|
+
toolName: toolCall.toolName,
|
|
2778
|
+
toolInput: toolCall.input,
|
|
2779
|
+
cause: parseResult.error
|
|
2780
|
+
});
|
|
2781
|
+
return {
|
|
2782
|
+
type: "tool-call",
|
|
2783
|
+
toolCallId: toolCall.toolCallId,
|
|
2784
|
+
toolName: toolCall.toolName,
|
|
2785
|
+
input: parseResult.value,
|
|
2786
|
+
providerExecuted: true,
|
|
2787
|
+
dynamic: true,
|
|
2788
|
+
providerMetadata: toolCall.providerMetadata
|
|
2789
|
+
};
|
|
2790
|
+
}
|
|
2791
|
+
async function doParseToolCall({ toolCall, tools }) {
|
|
2792
|
+
const toolName = toolCall.toolName;
|
|
2793
|
+
const tool = getOwn(tools, toolName);
|
|
2794
|
+
if (tool == null) {
|
|
2795
|
+
if (toolCall.providerExecuted && toolCall.dynamic) return await parseProviderExecutedDynamicToolCall(toolCall);
|
|
2796
|
+
throw new NoSuchToolError({
|
|
2797
|
+
toolName: toolCall.toolName,
|
|
2798
|
+
availableTools: Object.keys(tools)
|
|
2799
|
+
});
|
|
2800
|
+
}
|
|
2801
|
+
const schema = asSchema(tool.inputSchema);
|
|
2802
|
+
const parseResult = toolCall.input.trim() === "" ? await safeValidateTypes({
|
|
2803
|
+
value: {},
|
|
2804
|
+
schema
|
|
2805
|
+
}) : await safeParseJSON({
|
|
2806
|
+
text: toolCall.input,
|
|
2807
|
+
schema
|
|
2808
|
+
});
|
|
2809
|
+
if (parseResult.success === false) throw new InvalidToolInputError({
|
|
2810
|
+
toolName,
|
|
2811
|
+
toolInput: toolCall.input,
|
|
2812
|
+
cause: parseResult.error
|
|
2813
|
+
});
|
|
2814
|
+
return setToolCallInputSchemaInput(tool.type === "dynamic" ? {
|
|
2815
|
+
type: "tool-call",
|
|
2816
|
+
toolCallId: toolCall.toolCallId,
|
|
2817
|
+
toolName: toolCall.toolName,
|
|
2818
|
+
input: parseResult.value,
|
|
2819
|
+
providerExecuted: toolCall.providerExecuted,
|
|
2820
|
+
providerMetadata: toolCall.providerMetadata,
|
|
2821
|
+
...tool.metadata != null ? { toolMetadata: tool.metadata } : {},
|
|
2822
|
+
dynamic: true,
|
|
2823
|
+
title: tool.title
|
|
2824
|
+
} : {
|
|
2825
|
+
type: "tool-call",
|
|
2826
|
+
toolCallId: toolCall.toolCallId,
|
|
2827
|
+
toolName,
|
|
2828
|
+
input: parseResult.value,
|
|
2829
|
+
providerExecuted: toolCall.providerExecuted,
|
|
2830
|
+
providerMetadata: toolCall.providerMetadata,
|
|
2831
|
+
...tool.metadata != null ? { toolMetadata: tool.metadata } : {},
|
|
2832
|
+
title: tool.title
|
|
2833
|
+
}, parseResult.rawValue);
|
|
2834
|
+
}
|
|
2835
|
+
//#endregion
|
|
2836
|
+
//#region src/generate-text/resolve-tool-approval.ts
|
|
2837
|
+
/**
|
|
2838
|
+
* Resolves the approval state for a tool call by checking user-supplied and tool-defined
|
|
2839
|
+
* approval settings, and normalizes the result to the object status shape.
|
|
2840
|
+
* User-defined approval settings take precedence over tool-defined settings.
|
|
2841
|
+
* If no approval settings are provided, the tool call does not require approval.
|
|
2842
|
+
*/
|
|
2843
|
+
async function resolveToolApproval({ tools, toolCall, toolApproval, messages, toolsContext, runtimeContext }) {
|
|
2844
|
+
if (toolApproval != null && typeof toolApproval === "function") return normalizeToolApprovalStatus(await toolApproval({
|
|
2845
|
+
toolCall,
|
|
2846
|
+
tools,
|
|
2847
|
+
toolsContext,
|
|
2848
|
+
messages,
|
|
2849
|
+
runtimeContext
|
|
2850
|
+
}));
|
|
2851
|
+
const toolName = toolCall.toolName;
|
|
2852
|
+
const tool = getOwn(tools, toolName);
|
|
2853
|
+
const input = toolCall.input;
|
|
2854
|
+
const userDefinedToolApprovalStatus = getOwn(toolApproval, toolName);
|
|
2855
|
+
if (userDefinedToolApprovalStatus != null) return normalizeToolApprovalStatus(typeof userDefinedToolApprovalStatus === "function" ? await userDefinedToolApprovalStatus(input, {
|
|
2856
|
+
toolCallId: toolCall.toolCallId,
|
|
2857
|
+
messages,
|
|
2858
|
+
toolContext: await validateToolContext({
|
|
2859
|
+
toolName,
|
|
2860
|
+
context: getOwn(toolsContext, toolName),
|
|
2861
|
+
contextSchema: tool?.contextSchema
|
|
2862
|
+
}),
|
|
2863
|
+
runtimeContext
|
|
2864
|
+
}) : userDefinedToolApprovalStatus);
|
|
2865
|
+
if (tool?.needsApproval == null) return { type: "not-applicable" };
|
|
2866
|
+
return (typeof tool.needsApproval === "function" ? await tool.needsApproval(input, {
|
|
2867
|
+
toolCallId: toolCall.toolCallId,
|
|
2868
|
+
messages,
|
|
2869
|
+
context: await validateToolContext({
|
|
2870
|
+
toolName,
|
|
2871
|
+
context: getOwn(toolsContext, toolName),
|
|
2872
|
+
contextSchema: tool?.contextSchema
|
|
2873
|
+
})
|
|
2874
|
+
}) : tool.needsApproval) ? { type: "user-approval" } : { type: "not-applicable" };
|
|
2875
|
+
}
|
|
2876
|
+
function normalizeToolApprovalStatus(status) {
|
|
2877
|
+
return status === void 0 ? { type: "not-applicable" } : typeof status === "string" ? { type: status } : status;
|
|
2878
|
+
}
|
|
2879
|
+
//#endregion
|
|
2880
|
+
//#region src/telemetry/filter-included-context.ts
|
|
2881
|
+
/**
|
|
2882
|
+
* Returns a shallow copy of the runtime context with only top-level
|
|
2883
|
+
* properties marked for telemetry inclusion.
|
|
2884
|
+
*/
|
|
2885
|
+
function filterIncludedContext({ context, includeContext }) {
|
|
2886
|
+
if (context == null) return {};
|
|
2887
|
+
return Object.fromEntries(Object.entries(context).filter(([key]) => includeContext?.[key] === true));
|
|
2888
|
+
}
|
|
2889
|
+
function filterToolsContext({ toolsContext, includeToolsContext }) {
|
|
2890
|
+
if (includeToolsContext == null) return {};
|
|
2891
|
+
return Object.fromEntries(Object.entries(toolsContext).map(([toolName, toolContext]) => [toolName, filterToolContext({
|
|
2892
|
+
toolName,
|
|
2893
|
+
toolContext,
|
|
2894
|
+
includeToolsContext
|
|
2895
|
+
})]));
|
|
2896
|
+
}
|
|
2897
|
+
function filterToolContext({ toolName, toolContext, includeToolsContext }) {
|
|
2898
|
+
const includeToolContext = includeToolsContext?.[toolName];
|
|
2899
|
+
return filterIncludedContext({
|
|
2900
|
+
context: toolContext,
|
|
2901
|
+
includeContext: includeToolContext
|
|
2902
|
+
});
|
|
2903
|
+
}
|
|
2904
|
+
//#endregion
|
|
2905
|
+
//#region src/util/merge-callbacks.ts
|
|
2906
|
+
/**
|
|
2907
|
+
* Creates an async callback that invokes the provided callbacks in parallel.
|
|
2908
|
+
* Undefined callbacks are skipped, and thrown or rejected callback errors are
|
|
2909
|
+
* ignored.
|
|
2910
|
+
*
|
|
2911
|
+
* @param callbacks The callbacks to invoke for each event.
|
|
2912
|
+
* @returns A callback that forwards each event to all callbacks and waits for
|
|
2913
|
+
* them to settle.
|
|
2914
|
+
*/
|
|
2915
|
+
function mergeCallbacks(...callbacks) {
|
|
2916
|
+
return async (event) => {
|
|
2917
|
+
await Promise.allSettled(callbacks.map(async (callback) => {
|
|
2918
|
+
await callback?.(event);
|
|
2919
|
+
}));
|
|
2920
|
+
};
|
|
2921
|
+
}
|
|
2922
|
+
//#endregion
|
|
2923
|
+
//#region src/telemetry/tracing-channel.ts
|
|
2924
|
+
const AI_SDK_TELEMETRY_TRACING_CHANNEL = "ai:telemetry";
|
|
2925
|
+
//#endregion
|
|
2926
|
+
//#region src/util/is-node-runtime.ts
|
|
2927
|
+
function isNodeRuntime() {
|
|
2928
|
+
return globalThis.process?.release?.name === "node";
|
|
2929
|
+
}
|
|
2930
|
+
//#endregion
|
|
2931
|
+
//#region src/telemetry/redact-telemetry-credentials.ts
|
|
2932
|
+
/**
|
|
2933
|
+
* Apply provider-owned credential redaction on telemetry-only copies. Only visit SDK
|
|
2934
|
+
* metadata containers, never arbitrary prompts, tool outputs, or user context.
|
|
2935
|
+
*/
|
|
2936
|
+
function redactTelemetryCredentials(value) {
|
|
2937
|
+
if (DownloadError.isInstance(value)) return redactDownloadError(value);
|
|
2938
|
+
return replaceProperties(value, {
|
|
2939
|
+
args: redactTelemetryValue,
|
|
2940
|
+
tools: redactTools,
|
|
2941
|
+
stepTools: redactTools,
|
|
2942
|
+
request: redactMetadata,
|
|
2943
|
+
response: redactMetadata,
|
|
2944
|
+
steps: (steps) => mapArray(steps, redactTelemetryCredentials),
|
|
2945
|
+
finalStep: redactTelemetryCredentials,
|
|
2946
|
+
error: redactTelemetryCredentials,
|
|
2947
|
+
cause: redactTelemetryCredentials,
|
|
2948
|
+
errors: (errors) => mapArray(errors, redactTelemetryCredentials),
|
|
2949
|
+
lastError: redactTelemetryCredentials,
|
|
2950
|
+
requestBodyValues: redactBody
|
|
2951
|
+
});
|
|
2952
|
+
}
|
|
2953
|
+
function redactDownloadError(error) {
|
|
2954
|
+
return new DownloadError({
|
|
2955
|
+
url: "[redacted]",
|
|
2956
|
+
statusCode: error.statusCode,
|
|
2957
|
+
statusText: error.statusText,
|
|
2958
|
+
message: "Failed to download a file."
|
|
2959
|
+
});
|
|
2960
|
+
}
|
|
2961
|
+
function redactMetadata(value) {
|
|
2962
|
+
return Array.isArray(value) ? mapArray(value, redactMetadata) : replaceProperties(value, { body: redactBody });
|
|
2963
|
+
}
|
|
2964
|
+
function redactBody(value) {
|
|
2965
|
+
return replaceProperties(redactTelemetryValue(value), { tools: redactTools });
|
|
2966
|
+
}
|
|
2967
|
+
function redactTools(value) {
|
|
2968
|
+
if (Array.isArray(value)) return mapArray(value, redactTelemetryCredentials);
|
|
2969
|
+
if (!isRecord(value)) return value;
|
|
2970
|
+
return replaceProperties(value, Object.fromEntries(Object.keys(value).map((key) => [key, redactTelemetryCredentials])));
|
|
2971
|
+
}
|
|
2972
|
+
function isRecord(value) {
|
|
2973
|
+
return value != null && typeof value === "object" && !Array.isArray(value);
|
|
2974
|
+
}
|
|
2975
|
+
function mapArray(value, redact) {
|
|
2976
|
+
if (!Array.isArray(value)) return value;
|
|
2977
|
+
const copy = value.map(redact);
|
|
2978
|
+
return copy.some((entry, index) => entry !== value[index]) ? copy : value;
|
|
2979
|
+
}
|
|
2980
|
+
/** Preserve result getters and property descriptors without mutation. */
|
|
2981
|
+
function replaceProperties(value, redactors) {
|
|
2982
|
+
if (!isRecord(value)) return value;
|
|
2983
|
+
let descriptors;
|
|
2984
|
+
for (const [key, redact] of Object.entries(redactors)) {
|
|
2985
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
2986
|
+
if (descriptor == null || !("value" in descriptor)) continue;
|
|
2987
|
+
const redacted = redact(descriptor.value);
|
|
2988
|
+
if (redacted !== descriptor.value) {
|
|
2989
|
+
descriptors ??= Object.getOwnPropertyDescriptors(value);
|
|
2990
|
+
descriptors[key] = {
|
|
2991
|
+
...descriptor,
|
|
2992
|
+
value: redacted
|
|
2993
|
+
};
|
|
2994
|
+
}
|
|
2995
|
+
}
|
|
2996
|
+
if (descriptors == null) return value;
|
|
2997
|
+
const streamDescriptor = descriptors.stream;
|
|
2998
|
+
if (streamDescriptor?.writable && streamDescriptor.value instanceof ReadableStream) {
|
|
2999
|
+
const original = value;
|
|
3000
|
+
descriptors.stream = {
|
|
3001
|
+
configurable: streamDescriptor.configurable,
|
|
3002
|
+
enumerable: streamDescriptor.enumerable,
|
|
3003
|
+
get: () => original.stream,
|
|
3004
|
+
set: (stream) => {
|
|
3005
|
+
original.stream = stream;
|
|
3006
|
+
}
|
|
3007
|
+
};
|
|
3008
|
+
}
|
|
3009
|
+
return Object.create(Object.getPrototypeOf(value), descriptors);
|
|
3010
|
+
}
|
|
3011
|
+
//#endregion
|
|
3012
|
+
//#region src/telemetry/tracing-channel-publisher.ts
|
|
3013
|
+
let diagnosticsChannelPromise;
|
|
3014
|
+
/**
|
|
3015
|
+
* Loads Node's diagnostics channel module only when the current runtime supports
|
|
3016
|
+
* it. Unsupported runtimes and failed imports intentionally resolve to
|
|
3017
|
+
* undefined so telemetry tracing never crashes user code.
|
|
3018
|
+
*/
|
|
3019
|
+
async function loadDiagnosticsChannel() {
|
|
3020
|
+
if (!isNodeRuntime()) return;
|
|
3021
|
+
if (diagnosticsChannelPromise == null) diagnosticsChannelPromise = Promise.resolve(loadBuiltinModule("node:diagnostics_channel"));
|
|
3022
|
+
return diagnosticsChannelPromise;
|
|
3023
|
+
}
|
|
3024
|
+
function loadBuiltinModule(id) {
|
|
3025
|
+
const processWithBuiltins = globalThis.process;
|
|
3026
|
+
try {
|
|
3027
|
+
return processWithBuiltins?.getBuiltinModule?.(id);
|
|
3028
|
+
} catch {
|
|
3029
|
+
return;
|
|
3030
|
+
}
|
|
3031
|
+
}
|
|
3032
|
+
/**
|
|
3033
|
+
* Runs an async operation inside the AI SDK telemetry tracing channel when
|
|
3034
|
+
* tracing subscribers may exist. Without Node diagnostics-channel support,
|
|
3035
|
+
* without tracingChannel support, or when the runtime reports no subscribers,
|
|
3036
|
+
* this is a direct pass-through.
|
|
3037
|
+
*
|
|
3038
|
+
* The execution bookkeeping preserves the original model/tool result or error
|
|
3039
|
+
* if tracing itself throws, and prevents falling back by calling `execute` a
|
|
3040
|
+
* second time.
|
|
3041
|
+
*/
|
|
3042
|
+
async function runWithTracingChannelSpan(message, execute, recordResult = true) {
|
|
3043
|
+
const tracingChannel = (await loadDiagnosticsChannel())?.tracingChannel?.(AI_SDK_TELEMETRY_TRACING_CHANNEL);
|
|
3044
|
+
if (tracingChannel == null || tracingChannel.hasSubscribers === false) return await execute();
|
|
3045
|
+
let executePromise;
|
|
3046
|
+
let executionResult;
|
|
3047
|
+
let executionError;
|
|
3048
|
+
let hasExecutionResult = false;
|
|
3049
|
+
let hasExecutionError = false;
|
|
3050
|
+
const tracedExecute = () => {
|
|
3051
|
+
try {
|
|
3052
|
+
executePromise = Promise.resolve(execute());
|
|
3053
|
+
} catch (error) {
|
|
3054
|
+
executePromise = Promise.reject(error);
|
|
3055
|
+
}
|
|
3056
|
+
executePromise = executePromise.then((result) => {
|
|
3057
|
+
executionResult = result;
|
|
3058
|
+
hasExecutionResult = true;
|
|
3059
|
+
return result;
|
|
3060
|
+
}, (error) => {
|
|
3061
|
+
executionError = error;
|
|
3062
|
+
hasExecutionError = true;
|
|
3063
|
+
throw error;
|
|
3064
|
+
});
|
|
3065
|
+
return recordResult ? executePromise.then(redactTelemetryCredentials, (error) => {
|
|
3066
|
+
throw redactTelemetryCredentials(error);
|
|
3067
|
+
}) : executePromise.then(() => void 0, () => {
|
|
3068
|
+
throw new Error("AI SDK operation failed");
|
|
3069
|
+
});
|
|
3070
|
+
};
|
|
3071
|
+
try {
|
|
3072
|
+
await tracingChannel.tracePromise(tracedExecute, message);
|
|
3073
|
+
return executionResult;
|
|
3074
|
+
} catch {
|
|
3075
|
+
if (hasExecutionError) throw executionError;
|
|
3076
|
+
if (hasExecutionResult) return executionResult;
|
|
3077
|
+
if (executePromise != null) return await executePromise;
|
|
3078
|
+
return await execute();
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
3081
|
+
/**
|
|
3082
|
+
* Opens a long-lived tracing-channel span context and returns a runner that can
|
|
3083
|
+
* re-enter that context later without changing stream setup timing.
|
|
3084
|
+
*/
|
|
3085
|
+
function openTelemetryChannelSpanContext({ message, completion, recordResult = true }) {
|
|
3086
|
+
if (!isNodeRuntime()) {
|
|
3087
|
+
Promise.resolve(completion).catch(() => {});
|
|
3088
|
+
return;
|
|
3089
|
+
}
|
|
3090
|
+
const diagnosticsChannel = loadBuiltinModule("node:diagnostics_channel");
|
|
3091
|
+
const asyncHooks = loadBuiltinModule("node:async_hooks");
|
|
3092
|
+
const tracingChannel = diagnosticsChannel?.tracingChannel?.(AI_SDK_TELEMETRY_TRACING_CHANNEL);
|
|
3093
|
+
if (tracingChannel == null || tracingChannel.hasSubscribers === false || asyncHooks == null) {
|
|
3094
|
+
Promise.resolve(completion).catch(() => {});
|
|
3095
|
+
return;
|
|
3096
|
+
}
|
|
3097
|
+
const context = message;
|
|
3098
|
+
let asyncResource;
|
|
3099
|
+
let asyncEndPublished = false;
|
|
3100
|
+
const safePublish = (publish) => {
|
|
3101
|
+
try {
|
|
3102
|
+
publish();
|
|
3103
|
+
} catch {}
|
|
3104
|
+
};
|
|
3105
|
+
const publishAsyncEnd = ({ result, error }) => {
|
|
3106
|
+
if (asyncEndPublished) return;
|
|
3107
|
+
asyncEndPublished = true;
|
|
3108
|
+
if (error !== void 0) {
|
|
3109
|
+
context.error = recordResult ? redactTelemetryCredentials(error) : /* @__PURE__ */ new Error("AI SDK operation failed");
|
|
3110
|
+
safePublish(() => tracingChannel.error.publish(context));
|
|
3111
|
+
}
|
|
3112
|
+
if (recordResult && result !== void 0) context.result = redactTelemetryCredentials(result);
|
|
3113
|
+
safePublish(() => tracingChannel.asyncEnd.publish(context));
|
|
3114
|
+
};
|
|
3115
|
+
safePublish(() => {
|
|
3116
|
+
tracingChannel.start.runStores(context, () => {
|
|
3117
|
+
asyncResource = new asyncHooks.AsyncResource("ai.telemetry");
|
|
3118
|
+
});
|
|
3119
|
+
});
|
|
3120
|
+
safePublish(() => tracingChannel.end.publish(context));
|
|
3121
|
+
Promise.resolve(completion).then((result) => publishAsyncEnd({ result }), (error) => publishAsyncEnd({ error }));
|
|
3122
|
+
return { run: (execute) => asyncResource == null ? execute() : asyncResource.runInAsyncScope(execute) };
|
|
3123
|
+
}
|
|
3124
|
+
//#endregion
|
|
3125
|
+
//#region src/telemetry/telemetry-registry.ts
|
|
3126
|
+
/**
|
|
3127
|
+
* Registers one or more telemetry integrations globally.
|
|
3128
|
+
*/
|
|
3129
|
+
function registerTelemetry(...integrations) {
|
|
3130
|
+
if (!globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [];
|
|
3131
|
+
globalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(...integrations);
|
|
3132
|
+
}
|
|
3133
|
+
function getGlobalTelemetryIntegrations() {
|
|
3134
|
+
return globalThis.AI_SDK_TELEMETRY_INTEGRATIONS ?? [];
|
|
3135
|
+
}
|
|
3136
|
+
//#endregion
|
|
3137
|
+
//#region src/telemetry/filter-telemetry-event.ts
|
|
3138
|
+
/**
|
|
3139
|
+
* Filters SDK-owned content fields on a copy. Only descend into SDK event
|
|
3140
|
+
* containers; user context has its own inclusion policy.
|
|
3141
|
+
*/
|
|
3142
|
+
function filterTelemetryEvent(event, telemetry) {
|
|
3143
|
+
const hideInputs = telemetry.recordInputs === false;
|
|
3144
|
+
const hideOutputs = telemetry.recordOutputs === false;
|
|
3145
|
+
if (!hideInputs && !hideOutputs || event == null || typeof event !== "object") return event;
|
|
3146
|
+
const filtered = Object.assign(Object.create(Object.getPrototypeOf(event)), event);
|
|
3147
|
+
const replace = (fields) => {
|
|
3148
|
+
for (const [key, value] of Object.entries(fields)) if (Object.hasOwn(event, key)) filtered[key] = value;
|
|
3149
|
+
};
|
|
3150
|
+
const isSpeech = filtered.operationId === "ai.generateSpeech";
|
|
3151
|
+
if (hideInputs) {
|
|
3152
|
+
replace({
|
|
3153
|
+
instructions: void 0,
|
|
3154
|
+
system: void 0,
|
|
3155
|
+
prompt: void 0,
|
|
3156
|
+
messages: [],
|
|
3157
|
+
promptMessages: [],
|
|
3158
|
+
experimental_steeringMessages: [],
|
|
3159
|
+
tools: void 0,
|
|
3160
|
+
stepTools: void 0,
|
|
3161
|
+
schema: void 0,
|
|
3162
|
+
schemaName: void 0,
|
|
3163
|
+
schemaDescription: void 0,
|
|
3164
|
+
...typeof filtered.output === "object" ? { output: void 0 } : {},
|
|
3165
|
+
providerOptions: {},
|
|
3166
|
+
value: "",
|
|
3167
|
+
values: [],
|
|
3168
|
+
query: "",
|
|
3169
|
+
documents: [],
|
|
3170
|
+
state: Array.isArray(filtered.state) ? [] : typeof filtered.state === "string" ? "" : {},
|
|
3171
|
+
questions: {},
|
|
3172
|
+
fields: {},
|
|
3173
|
+
referenceDate: void 0,
|
|
3174
|
+
...isSpeech ? { text: "" } : {}
|
|
3175
|
+
});
|
|
3176
|
+
if (filtered.toolCall != null) filtered.toolCall = {
|
|
3177
|
+
...filtered.toolCall,
|
|
3178
|
+
input: void 0
|
|
3179
|
+
};
|
|
3180
|
+
if (filtered.toolOutput != null) filtered.toolOutput = {
|
|
3181
|
+
...filtered.toolOutput,
|
|
3182
|
+
input: void 0
|
|
3183
|
+
};
|
|
3184
|
+
if (Array.isArray(filtered.ranking)) filtered.ranking = filtered.ranking.map((entry) => "document" in entry ? {
|
|
3185
|
+
...entry,
|
|
3186
|
+
document: typeof entry.document === "string" ? "" : {}
|
|
3187
|
+
} : entry);
|
|
3188
|
+
}
|
|
3189
|
+
if (hideOutputs) {
|
|
3190
|
+
replace({
|
|
3191
|
+
content: [],
|
|
3192
|
+
...!isSpeech ? { text: "" } : {},
|
|
3193
|
+
reasoning: Array.isArray(filtered.reasoning) ? [] : void 0,
|
|
3194
|
+
reasoningText: void 0,
|
|
3195
|
+
files: [],
|
|
3196
|
+
sources: [],
|
|
3197
|
+
toolCalls: [],
|
|
3198
|
+
staticToolCalls: [],
|
|
3199
|
+
dynamicToolCalls: [],
|
|
3200
|
+
toolResults: [],
|
|
3201
|
+
staticToolResults: [],
|
|
3202
|
+
dynamicToolResults: [],
|
|
3203
|
+
responseMessages: [],
|
|
3204
|
+
object: void 0,
|
|
3205
|
+
objectText: "",
|
|
3206
|
+
embedding: [],
|
|
3207
|
+
embeddings: [],
|
|
3208
|
+
ranking: [],
|
|
3209
|
+
answers: {},
|
|
3210
|
+
segments: [],
|
|
3211
|
+
words: []
|
|
3212
|
+
});
|
|
3213
|
+
if (filtered.toolOutput != null) filtered.toolOutput = {
|
|
3214
|
+
...filtered.toolOutput,
|
|
3215
|
+
output: void 0,
|
|
3216
|
+
error: void 0
|
|
3217
|
+
};
|
|
3218
|
+
}
|
|
3219
|
+
replace({
|
|
3220
|
+
providerMetadata: void 0,
|
|
3221
|
+
error: filtered.error == null ? filtered.error : /* @__PURE__ */ new Error("AI SDK operation failed")
|
|
3222
|
+
});
|
|
3223
|
+
for (const key of ["toolCall", "toolOutput"]) {
|
|
3224
|
+
const toolEvent = filtered[key];
|
|
3225
|
+
if (toolEvent != null && typeof toolEvent === "object") filtered[key] = {
|
|
3226
|
+
...toolEvent,
|
|
3227
|
+
providerMetadata: void 0,
|
|
3228
|
+
..."error" in toolEvent ? { error: toolEvent.error == null ? toolEvent.error : /* @__PURE__ */ new Error("AI SDK operation failed") } : {}
|
|
3229
|
+
};
|
|
3230
|
+
}
|
|
3231
|
+
for (const key of ["request", "response"]) {
|
|
3232
|
+
const filterMetadata = (metadata) => {
|
|
3233
|
+
if (metadata == null || typeof metadata !== "object") return metadata;
|
|
3234
|
+
const filteredMetadata = { ...metadata };
|
|
3235
|
+
delete filteredMetadata.body;
|
|
3236
|
+
if (key === "request" ? hideInputs : hideOutputs) {
|
|
3237
|
+
if ("messages" in metadata) filteredMetadata.messages = [];
|
|
3238
|
+
if ("instructions" in metadata) filteredMetadata.instructions = void 0;
|
|
3239
|
+
}
|
|
3240
|
+
return filteredMetadata;
|
|
3241
|
+
};
|
|
3242
|
+
const metadata = filtered[key];
|
|
3243
|
+
if (metadata != null) filtered[key] = Array.isArray(metadata) ? metadata.map(filterMetadata) : filterMetadata(metadata);
|
|
3244
|
+
}
|
|
3245
|
+
if (Array.isArray(filtered.steps)) filtered.steps = filtered.steps.map((step) => filterTelemetryEvent(step, telemetry));
|
|
3246
|
+
if (Object.hasOwn(event, "finalStep")) filtered.finalStep = filterTelemetryEvent(filtered.finalStep, telemetry);
|
|
3247
|
+
return filtered;
|
|
3248
|
+
}
|
|
3249
|
+
//#endregion
|
|
3250
|
+
//#region src/telemetry/create-telemetry-dispatcher.ts
|
|
3251
|
+
function augmentEvent(event, telemetry, filterContext = false) {
|
|
3252
|
+
const augmentedEvent = Object.assign(Object.create(Object.getPrototypeOf(event)), event, {
|
|
3253
|
+
recordInputs: telemetry.recordInputs,
|
|
3254
|
+
recordOutputs: telemetry.recordOutputs,
|
|
3255
|
+
functionId: telemetry.functionId,
|
|
3256
|
+
aiVersion: VERSION
|
|
3257
|
+
});
|
|
3258
|
+
if (filterContext && event != null && typeof event === "object" && "runtimeContext" in event) augmentedEvent.runtimeContext = filterIncludedContext({
|
|
3259
|
+
context: event.runtimeContext,
|
|
3260
|
+
includeContext: telemetry.includeRuntimeContext
|
|
3261
|
+
});
|
|
3262
|
+
if (filterContext && event != null && typeof event === "object") {
|
|
3263
|
+
if ("toolsContext" in event) augmentedEvent.toolsContext = filterToolsContext({
|
|
3264
|
+
toolsContext: event.toolsContext,
|
|
3265
|
+
includeToolsContext: telemetry.includeToolsContext
|
|
3266
|
+
});
|
|
3267
|
+
else if ("toolContext" in event && event.toolContext != null && "toolCall" in event && event.toolCall != null && typeof event.toolCall === "object" && "toolName" in event.toolCall) augmentedEvent.toolContext = filterToolContext({
|
|
3268
|
+
toolName: event.toolCall.toolName,
|
|
3269
|
+
toolContext: event.toolContext,
|
|
3270
|
+
includeToolsContext: telemetry.includeToolsContext
|
|
3271
|
+
});
|
|
3272
|
+
}
|
|
3273
|
+
return redactTelemetryCredentials(filterTelemetryEvent(augmentedEvent, telemetry));
|
|
3274
|
+
}
|
|
3275
|
+
/**
|
|
3276
|
+
* Creates a telemetry dispatcher that sends telemetry events
|
|
3277
|
+
* to the resolved set of integrations.
|
|
3278
|
+
*
|
|
3279
|
+
* When per-call integrations are provided, they take precedence over the globally
|
|
3280
|
+
* registered integrations for that call. When no per-call integrations are
|
|
3281
|
+
* provided, the globally registered integrations are used.
|
|
3282
|
+
*
|
|
3283
|
+
* @param args.telemetry - Optional per-call telemetry settings and integrations.
|
|
3284
|
+
*
|
|
3285
|
+
* @returns A telemetry dispatcher that fans out lifecycle events to the
|
|
3286
|
+
* resolved set of integrations.
|
|
3287
|
+
*/
|
|
3288
|
+
function createTelemetryDispatcher({ telemetry }) {
|
|
3289
|
+
if (telemetry?.isEnabled === false) return {};
|
|
3290
|
+
const localIntegrations = telemetry?.integrations;
|
|
3291
|
+
const integrations = localIntegrations != null ? asArray(localIntegrations) : getGlobalTelemetryIntegrations();
|
|
3292
|
+
const telemetryMetadata = {
|
|
3293
|
+
recordInputs: telemetry?.recordInputs,
|
|
3294
|
+
recordOutputs: telemetry?.recordOutputs,
|
|
3295
|
+
functionId: telemetry?.functionId,
|
|
3296
|
+
includeRuntimeContext: telemetry?.includeRuntimeContext,
|
|
3297
|
+
includeToolsContext: telemetry?.includeToolsContext
|
|
3298
|
+
};
|
|
3299
|
+
const recordResult = telemetry?.recordInputs !== false && telemetry?.recordOutputs !== false;
|
|
3300
|
+
const mergeTelemetryCallback = (key, deprecatedKey) => {
|
|
3301
|
+
const integrationCallbacks = integrations.map((integration) => {
|
|
3302
|
+
const callback = integration[key] ?? (deprecatedKey == null ? void 0 : integration[deprecatedKey]);
|
|
3303
|
+
return typeof callback === "function" ? callback.bind(integration) : void 0;
|
|
3304
|
+
}).filter(Boolean).map((callback) => ((event) => callback(augmentEvent(event, telemetryMetadata))));
|
|
3305
|
+
if (integrationCallbacks.length === 0) return;
|
|
3306
|
+
const mergedIntegrationCallback = mergeCallbacks(...integrationCallbacks);
|
|
3307
|
+
return async (event) => {
|
|
3308
|
+
await mergedIntegrationCallback(event);
|
|
3309
|
+
};
|
|
3310
|
+
};
|
|
3311
|
+
const onStepEnd = mergeTelemetryCallback("onStepEnd");
|
|
3312
|
+
const onStepFinish = mergeTelemetryCallback("onStepFinish");
|
|
3313
|
+
const executeLanguageModelCallWrappers = integrations.map((integration) => integration.executeLanguageModelCall?.bind(integration)).filter(Boolean);
|
|
3314
|
+
const executeToolWrappers = integrations.map((integration) => integration.executeTool?.bind(integration)).filter(Boolean);
|
|
3315
|
+
return {
|
|
3316
|
+
runInTracingChannelSpan: async ({ type, event, execute }) => await runWithTracingChannelSpan({
|
|
3317
|
+
type,
|
|
3318
|
+
event: augmentEvent(event, telemetryMetadata, true)
|
|
3319
|
+
}, execute, recordResult),
|
|
3320
|
+
startTracingChannelContext: ({ type, event, completion }) => openTelemetryChannelSpanContext({
|
|
3321
|
+
message: {
|
|
3322
|
+
type,
|
|
3323
|
+
event: augmentEvent(event, telemetryMetadata, true)
|
|
3324
|
+
},
|
|
3325
|
+
completion,
|
|
3326
|
+
recordResult
|
|
3327
|
+
}),
|
|
3328
|
+
onStart: mergeTelemetryCallback("onStart"),
|
|
3329
|
+
onStepStart: mergeTelemetryCallback("onStepStart"),
|
|
3330
|
+
onLanguageModelCallStart: mergeTelemetryCallback("onLanguageModelCallStart"),
|
|
3331
|
+
onLanguageModelCallEnd: mergeTelemetryCallback("onLanguageModelCallEnd"),
|
|
3332
|
+
onToolExecutionStart: mergeTelemetryCallback("onToolExecutionStart"),
|
|
3333
|
+
onToolExecutionEnd: mergeTelemetryCallback("onToolExecutionEnd"),
|
|
3334
|
+
onStepEnd: onStepEnd == null && onStepFinish == null ? void 0 : mergeCallbacks(onStepEnd, onStepFinish),
|
|
3335
|
+
onStepError: mergeTelemetryCallback("onStepError"),
|
|
3336
|
+
onObjectStepStart: mergeTelemetryCallback("onObjectStepStart"),
|
|
3337
|
+
onObjectStepEnd: mergeTelemetryCallback("onObjectStepEnd"),
|
|
3338
|
+
onEmbedStart: mergeTelemetryCallback("onEmbedStart"),
|
|
3339
|
+
onEmbedEnd: mergeTelemetryCallback("onEmbedEnd"),
|
|
3340
|
+
onRerankStart: mergeTelemetryCallback("onRerankStart"),
|
|
3341
|
+
onRerankEnd: mergeTelemetryCallback("onRerankEnd"),
|
|
3342
|
+
experimental_onDecideStart: mergeTelemetryCallback("experimental_onDecideStart", "experimental_onEvaluateStart"),
|
|
3343
|
+
experimental_onDecisionModelCallStart: mergeTelemetryCallback("experimental_onDecisionModelCallStart", "experimental_onEvaluationModelCallStart"),
|
|
3344
|
+
experimental_onDecisionModelCallEnd: mergeTelemetryCallback("experimental_onDecisionModelCallEnd", "experimental_onEvaluationModelCallEnd"),
|
|
3345
|
+
experimental_onDecideEnd: mergeTelemetryCallback("experimental_onDecideEnd", "experimental_onEvaluateEnd"),
|
|
3346
|
+
experimental_onExtractStart: mergeTelemetryCallback("experimental_onExtractStart"),
|
|
3347
|
+
experimental_onExtractionModelCallStart: mergeTelemetryCallback("experimental_onExtractionModelCallStart"),
|
|
3348
|
+
experimental_onExtractionModelCallEnd: mergeTelemetryCallback("experimental_onExtractionModelCallEnd"),
|
|
3349
|
+
experimental_onExtractEnd: mergeTelemetryCallback("experimental_onExtractEnd"),
|
|
3350
|
+
experimental_onStreamTranscriptionStart: mergeTelemetryCallback("experimental_onStreamTranscriptionStart"),
|
|
3351
|
+
experimental_onStreamTranscriptionEnd: mergeTelemetryCallback("experimental_onStreamTranscriptionEnd"),
|
|
3352
|
+
onEnd: mergeTelemetryCallback("onEnd"),
|
|
3353
|
+
onAbort: mergeTelemetryCallback("onAbort"),
|
|
3354
|
+
onError: mergeTelemetryCallback("onError"),
|
|
3355
|
+
/**
|
|
3356
|
+
* Runs provider calls inside integration-specific context so
|
|
3357
|
+
* auto-instrumented provider requests can be associated with model work.
|
|
3358
|
+
*/
|
|
3359
|
+
executeLanguageModelCall: async ({ execute, ...event }) => {
|
|
3360
|
+
const augmentedEvent = augmentEvent(event, telemetryMetadata);
|
|
3361
|
+
let wrappedExecute = execute;
|
|
3362
|
+
for (const executeWrapper of executeLanguageModelCallWrappers) {
|
|
3363
|
+
const innerExecute = wrappedExecute;
|
|
3364
|
+
wrappedExecute = async () => {
|
|
3365
|
+
const originals = /* @__PURE__ */ new Map();
|
|
3366
|
+
const redact = (original) => {
|
|
3367
|
+
const redacted = redactTelemetryCredentials(original);
|
|
3368
|
+
if (redacted !== original) originals.set(redacted, original);
|
|
3369
|
+
return redacted;
|
|
3370
|
+
};
|
|
3371
|
+
const restore = (value) => originals.has(value) ? originals.get(value) : value;
|
|
3372
|
+
try {
|
|
3373
|
+
return restore(await executeWrapper({
|
|
3374
|
+
...augmentedEvent,
|
|
3375
|
+
execute: async () => {
|
|
3376
|
+
try {
|
|
3377
|
+
return redact(await innerExecute());
|
|
3378
|
+
} catch (error) {
|
|
3379
|
+
throw redact(error);
|
|
3380
|
+
}
|
|
3381
|
+
}
|
|
3382
|
+
}));
|
|
3383
|
+
} catch (error) {
|
|
3384
|
+
throw restore(error);
|
|
3385
|
+
}
|
|
3386
|
+
};
|
|
3387
|
+
}
|
|
3388
|
+
return await runWithTracingChannelSpan({
|
|
3389
|
+
type: "languageModelCall",
|
|
3390
|
+
event: augmentedEvent
|
|
3391
|
+
}, wrappedExecute, recordResult);
|
|
3392
|
+
},
|
|
3393
|
+
/**
|
|
3394
|
+
* Composes all `executeTool` wrappers around the original tool execution.
|
|
3395
|
+
* Each wrapper receives an `execute` function that calls the next wrapper in
|
|
3396
|
+
* the chain, so integrations can establish nested telemetry context before
|
|
3397
|
+
* delegating to the underlying tool.
|
|
3398
|
+
*/
|
|
3399
|
+
executeTool: async ({ execute, ...event }) => {
|
|
3400
|
+
const augmentedEvent = augmentEvent(event, telemetryMetadata);
|
|
3401
|
+
let wrappedExecute = execute;
|
|
3402
|
+
for (const executeWrapper of executeToolWrappers) {
|
|
3403
|
+
const innerExecute = wrappedExecute;
|
|
3404
|
+
wrappedExecute = () => executeWrapper({
|
|
3405
|
+
...augmentedEvent,
|
|
3406
|
+
execute: innerExecute
|
|
3407
|
+
});
|
|
3408
|
+
}
|
|
3409
|
+
return await wrappedExecute();
|
|
3410
|
+
}
|
|
3411
|
+
};
|
|
3412
|
+
}
|
|
3413
|
+
//#endregion
|
|
3414
|
+
//#region src/generate-text/reasoning.ts
|
|
3415
|
+
function asReasoningText(reasoningParts) {
|
|
3416
|
+
const reasoningText = reasoningParts.map((part) => "text" in part ? part.text : "").join("");
|
|
3417
|
+
return reasoningText.length > 0 ? reasoningText : void 0;
|
|
3418
|
+
}
|
|
3419
|
+
//#endregion
|
|
3420
|
+
//#region src/generate-text/step-result.ts
|
|
3421
|
+
var DefaultStepResult = class {
|
|
3422
|
+
constructor({ callId, stepNumber, provider, modelId, runtimeContext, toolsContext, content, finishReason, rawFinishReason, usage, performance, warnings, request, response, providerMetadata, steeringMessages }) {
|
|
3423
|
+
this.callId = callId;
|
|
3424
|
+
this.stepNumber = stepNumber;
|
|
3425
|
+
this.model = {
|
|
3426
|
+
provider,
|
|
3427
|
+
modelId
|
|
3428
|
+
};
|
|
3429
|
+
this.runtimeContext = runtimeContext;
|
|
3430
|
+
this.toolsContext = toolsContext;
|
|
3431
|
+
this.content = content;
|
|
3432
|
+
this.finishReason = finishReason;
|
|
3433
|
+
this.rawFinishReason = rawFinishReason;
|
|
3434
|
+
this.usage = usage;
|
|
3435
|
+
this.performance = performance;
|
|
3436
|
+
this.warnings = warnings;
|
|
3437
|
+
this.request = request;
|
|
3438
|
+
this.response = response;
|
|
3439
|
+
this.providerMetadata = providerMetadata;
|
|
3440
|
+
if (steeringMessages != null && steeringMessages.length > 0) this.experimental_steeringMessages = steeringMessages;
|
|
3441
|
+
}
|
|
3442
|
+
get text() {
|
|
3443
|
+
return this.content.filter((part) => part.type === "text").map((part) => part.text).join("");
|
|
3444
|
+
}
|
|
3445
|
+
get reasoning() {
|
|
3446
|
+
return convertFromReasoningOutputs(this.content.filter((part) => part.type === "reasoning" || part.type === "reasoning-file"));
|
|
3447
|
+
}
|
|
3448
|
+
get reasoningText() {
|
|
3449
|
+
return asReasoningText(this.reasoning);
|
|
3450
|
+
}
|
|
3451
|
+
get files() {
|
|
3452
|
+
return this.content.filter((part) => part.type === "file").map((part) => part.file);
|
|
3453
|
+
}
|
|
3454
|
+
get sources() {
|
|
3455
|
+
return this.content.filter((part) => part.type === "source");
|
|
3456
|
+
}
|
|
3457
|
+
get toolCalls() {
|
|
3458
|
+
return this.content.filter((part) => part.type === "tool-call");
|
|
3459
|
+
}
|
|
3460
|
+
get staticToolCalls() {
|
|
3461
|
+
return this.toolCalls.filter((toolCall) => toolCall.dynamic !== true);
|
|
3462
|
+
}
|
|
3463
|
+
get dynamicToolCalls() {
|
|
3464
|
+
return this.toolCalls.filter((toolCall) => toolCall.dynamic === true);
|
|
3465
|
+
}
|
|
3466
|
+
get toolResults() {
|
|
3467
|
+
return this.content.filter((part) => part.type === "tool-result");
|
|
3468
|
+
}
|
|
3469
|
+
get staticToolResults() {
|
|
3470
|
+
return this.toolResults.filter((toolResult) => toolResult.dynamic !== true);
|
|
3471
|
+
}
|
|
3472
|
+
get dynamicToolResults() {
|
|
3473
|
+
return this.toolResults.filter((toolResult) => toolResult.dynamic === true);
|
|
3474
|
+
}
|
|
3475
|
+
};
|
|
3476
|
+
//#endregion
|
|
3477
|
+
//#region src/generate-text/restricted-telemetry-dispatcher.ts
|
|
3478
|
+
/**
|
|
3479
|
+
* Creates a copy of a step result whose runtime context only contains
|
|
3480
|
+
* top-level properties marked for telemetry inclusion.
|
|
3481
|
+
*/
|
|
3482
|
+
function restrictStepResult({ step, includeRuntimeContext, includeToolsContext }) {
|
|
3483
|
+
return new DefaultStepResult({
|
|
3484
|
+
callId: step.callId,
|
|
3485
|
+
stepNumber: step.stepNumber,
|
|
3486
|
+
provider: step.model.provider,
|
|
3487
|
+
modelId: step.model.modelId,
|
|
3488
|
+
runtimeContext: filterIncludedContext({
|
|
3489
|
+
context: step.runtimeContext,
|
|
3490
|
+
includeContext: includeRuntimeContext
|
|
3491
|
+
}),
|
|
3492
|
+
toolsContext: filterToolsContext({
|
|
3493
|
+
toolsContext: step.toolsContext,
|
|
3494
|
+
includeToolsContext
|
|
3495
|
+
}),
|
|
3496
|
+
content: step.content,
|
|
3497
|
+
finishReason: step.finishReason,
|
|
3498
|
+
rawFinishReason: step.rawFinishReason,
|
|
3499
|
+
usage: step.usage,
|
|
3500
|
+
performance: step.performance,
|
|
3501
|
+
warnings: step.warnings,
|
|
3502
|
+
request: step.request,
|
|
3503
|
+
response: step.response,
|
|
3504
|
+
providerMetadata: step.providerMetadata,
|
|
3505
|
+
steeringMessages: step.experimental_steeringMessages
|
|
3506
|
+
});
|
|
3507
|
+
}
|
|
3508
|
+
/**
|
|
3509
|
+
* Creates a telemetry dispatcher that only includes configured runtime context
|
|
3510
|
+
* properties in text-generation lifecycle events before dispatching them.
|
|
3511
|
+
*/
|
|
3512
|
+
function createRestrictedTelemetryDispatcher({ telemetry, includeRuntimeContext, includeToolsContext }) {
|
|
3513
|
+
const telemetryDispatcher = createTelemetryDispatcher({ telemetry });
|
|
3514
|
+
const restrictStepStartEvent = (event) => ({
|
|
3515
|
+
...event,
|
|
3516
|
+
runtimeContext: filterIncludedContext({
|
|
3517
|
+
context: event.runtimeContext,
|
|
3518
|
+
includeContext: includeRuntimeContext
|
|
3519
|
+
}),
|
|
3520
|
+
steps: event.steps.map((step) => restrictStepResult({
|
|
3521
|
+
step,
|
|
3522
|
+
includeRuntimeContext,
|
|
3523
|
+
includeToolsContext
|
|
3524
|
+
})),
|
|
3525
|
+
toolsContext: filterToolsContext({
|
|
3526
|
+
toolsContext: event.toolsContext,
|
|
3527
|
+
includeToolsContext
|
|
3528
|
+
})
|
|
3529
|
+
});
|
|
3530
|
+
return {
|
|
3531
|
+
...telemetryDispatcher,
|
|
3532
|
+
onStart: (event) => telemetryDispatcher.onStart?.({
|
|
3533
|
+
...event,
|
|
3534
|
+
runtimeContext: filterIncludedContext({
|
|
3535
|
+
context: event.runtimeContext,
|
|
3536
|
+
includeContext: includeRuntimeContext
|
|
3537
|
+
}),
|
|
3538
|
+
toolsContext: filterToolsContext({
|
|
3539
|
+
toolsContext: event.toolsContext,
|
|
3540
|
+
includeToolsContext
|
|
3541
|
+
})
|
|
3542
|
+
}),
|
|
3543
|
+
onStepStart: (event) => telemetryDispatcher.onStepStart?.(restrictStepStartEvent(event)),
|
|
3544
|
+
onStepEnd: (event) => telemetryDispatcher.onStepEnd?.(restrictStepResult({
|
|
3545
|
+
step: event,
|
|
3546
|
+
includeRuntimeContext,
|
|
3547
|
+
includeToolsContext
|
|
3548
|
+
})),
|
|
3549
|
+
onStepFinish: (event) => telemetryDispatcher.onStepEnd?.(restrictStepResult({
|
|
3550
|
+
step: event,
|
|
3551
|
+
includeRuntimeContext,
|
|
3552
|
+
includeToolsContext
|
|
3553
|
+
})),
|
|
3554
|
+
onStepError: (event) => telemetryDispatcher.onStepError?.(restrictStepStartEvent(event)),
|
|
3555
|
+
onEnd: (event) => telemetryDispatcher.onEnd?.(((restrictedSteps) => {
|
|
3556
|
+
return {
|
|
3557
|
+
...event,
|
|
3558
|
+
runtimeContext: filterIncludedContext({
|
|
3559
|
+
context: event.runtimeContext,
|
|
3560
|
+
includeContext: includeRuntimeContext
|
|
3561
|
+
}),
|
|
3562
|
+
steps: restrictedSteps,
|
|
3563
|
+
finalStep: restrictedSteps.at(-1),
|
|
3564
|
+
toolsContext: filterToolsContext({
|
|
3565
|
+
toolsContext: event.toolsContext,
|
|
3566
|
+
includeToolsContext
|
|
3567
|
+
})
|
|
3568
|
+
};
|
|
3569
|
+
})(event.steps.map((step) => restrictStepResult({
|
|
3570
|
+
step,
|
|
3571
|
+
includeRuntimeContext,
|
|
3572
|
+
includeToolsContext
|
|
3573
|
+
})))),
|
|
3574
|
+
onAbort: (event) => telemetryDispatcher.onAbort?.({
|
|
3575
|
+
...event,
|
|
3576
|
+
steps: event.steps.map((step) => restrictStepResult({
|
|
3577
|
+
step,
|
|
3578
|
+
includeRuntimeContext,
|
|
3579
|
+
includeToolsContext
|
|
3580
|
+
}))
|
|
3581
|
+
}),
|
|
3582
|
+
onToolExecutionStart: (event) => telemetryDispatcher.onToolExecutionStart?.({
|
|
3583
|
+
...event,
|
|
3584
|
+
toolContext: filterToolContext({
|
|
3585
|
+
toolName: event.toolCall.toolName,
|
|
3586
|
+
toolContext: event.toolContext,
|
|
3587
|
+
includeToolsContext
|
|
3588
|
+
})
|
|
3589
|
+
}),
|
|
3590
|
+
onToolExecutionEnd: (event) => telemetryDispatcher.onToolExecutionEnd?.({
|
|
3591
|
+
...event,
|
|
3592
|
+
toolContext: filterToolContext({
|
|
3593
|
+
toolName: event.toolCall.toolName,
|
|
3594
|
+
toolContext: event.toolContext,
|
|
3595
|
+
includeToolsContext
|
|
3596
|
+
})
|
|
3597
|
+
})
|
|
3598
|
+
};
|
|
3599
|
+
}
|
|
3600
|
+
//#endregion
|
|
3601
|
+
//#region src/util/is-deep-equal-data.ts
|
|
3602
|
+
/**
|
|
3603
|
+
* Performs a deep-equal comparison of two parsed JSON objects.
|
|
3604
|
+
*
|
|
3605
|
+
* @param {any} obj1 - The first object to compare.
|
|
3606
|
+
* @param {any} obj2 - The second object to compare.
|
|
3607
|
+
* @returns {boolean} - Returns true if the two objects are deeply equal, false otherwise.
|
|
3608
|
+
*/
|
|
3609
|
+
function isDeepEqualData(obj1, obj2) {
|
|
3610
|
+
if (obj1 === obj2) return true;
|
|
3611
|
+
if (obj1 == null || obj2 == null) return false;
|
|
3612
|
+
if (typeof obj1 !== "object" && typeof obj2 !== "object") return obj1 === obj2;
|
|
3613
|
+
if (obj1.constructor !== obj2.constructor) return false;
|
|
3614
|
+
if (obj1 instanceof Date && obj2 instanceof Date) return obj1.getTime() === obj2.getTime();
|
|
3615
|
+
if (Array.isArray(obj1)) {
|
|
3616
|
+
if (obj1.length !== obj2.length) return false;
|
|
3617
|
+
for (let i = 0; i < obj1.length; i++) if (!isDeepEqualData(obj1[i], obj2[i])) return false;
|
|
3618
|
+
return true;
|
|
3619
|
+
}
|
|
3620
|
+
const keys1 = Object.keys(obj1);
|
|
3621
|
+
const keys2 = Object.keys(obj2);
|
|
3622
|
+
if (keys1.length !== keys2.length) return false;
|
|
3623
|
+
for (const key of keys1) {
|
|
3624
|
+
if (!keys2.includes(key)) return false;
|
|
3625
|
+
if (!isDeepEqualData(obj1[key], obj2[key])) return false;
|
|
3626
|
+
}
|
|
3627
|
+
return true;
|
|
3628
|
+
}
|
|
3629
|
+
//#endregion
|
|
3630
|
+
//#region src/generate-text/to-response-messages.ts
|
|
3631
|
+
/**
|
|
3632
|
+
* Converts the result of a `generateText` or `streamText` call to a list of response messages.
|
|
3633
|
+
*/
|
|
3634
|
+
async function toResponseMessages({ content: inputContent, tools }) {
|
|
3635
|
+
const responseMessages = [];
|
|
3636
|
+
const toolCallOrder = /* @__PURE__ */ new Map();
|
|
3637
|
+
const content = [];
|
|
3638
|
+
for (const part of inputContent) {
|
|
3639
|
+
if (part.type === "source") continue;
|
|
3640
|
+
if ((part.type === "tool-result" || part.type === "tool-error") && !part.providerExecuted) continue;
|
|
3641
|
+
if (part.type === "text" && part.text.length === 0 && part.providerMetadata == null) continue;
|
|
3642
|
+
switch (part.type) {
|
|
3643
|
+
case "text":
|
|
3644
|
+
content.push({
|
|
3645
|
+
type: "text",
|
|
3646
|
+
text: part.text,
|
|
3647
|
+
providerOptions: part.providerMetadata
|
|
3648
|
+
});
|
|
3649
|
+
break;
|
|
3650
|
+
case "custom":
|
|
3651
|
+
content.push({
|
|
3652
|
+
type: "custom",
|
|
3653
|
+
kind: part.kind,
|
|
3654
|
+
providerOptions: part.providerMetadata
|
|
3655
|
+
});
|
|
3656
|
+
break;
|
|
3657
|
+
case "reasoning":
|
|
3658
|
+
content.push({
|
|
3659
|
+
type: "reasoning",
|
|
3660
|
+
text: part.text,
|
|
3661
|
+
providerOptions: part.providerMetadata
|
|
3662
|
+
});
|
|
3663
|
+
break;
|
|
3664
|
+
case "file":
|
|
3665
|
+
content.push({
|
|
3666
|
+
type: "file",
|
|
3667
|
+
data: part.file.base64,
|
|
3668
|
+
mediaType: part.file.mediaType,
|
|
3669
|
+
providerOptions: part.providerMetadata
|
|
3670
|
+
});
|
|
3671
|
+
break;
|
|
3672
|
+
case "reasoning-file":
|
|
3673
|
+
content.push({
|
|
3674
|
+
type: "reasoning-file",
|
|
3675
|
+
data: part.file.base64,
|
|
3676
|
+
mediaType: part.file.mediaType,
|
|
3677
|
+
providerOptions: part.providerMetadata
|
|
3678
|
+
});
|
|
3679
|
+
break;
|
|
3680
|
+
case "tool-call":
|
|
3681
|
+
if (!toolCallOrder.has(part.toolCallId)) toolCallOrder.set(part.toolCallId, toolCallOrder.size);
|
|
3682
|
+
content.push({
|
|
3683
|
+
type: "tool-call",
|
|
3684
|
+
toolCallId: part.toolCallId,
|
|
3685
|
+
toolName: part.toolName,
|
|
3686
|
+
input: part.invalid && typeof part.input !== "object" ? {} : part.input,
|
|
3687
|
+
providerExecuted: part.providerExecuted,
|
|
3688
|
+
providerOptions: part.providerMetadata
|
|
3689
|
+
});
|
|
3690
|
+
break;
|
|
3691
|
+
case "tool-result": {
|
|
3692
|
+
const output = await createToolModelOutput({
|
|
3693
|
+
toolCallId: part.toolCallId,
|
|
3694
|
+
input: part.input,
|
|
3695
|
+
tool: getOwn(tools, part.toolName),
|
|
3696
|
+
output: part.output,
|
|
3697
|
+
errorMode: "none"
|
|
3698
|
+
});
|
|
3699
|
+
content.push({
|
|
3700
|
+
type: "tool-result",
|
|
3701
|
+
toolCallId: part.toolCallId,
|
|
3702
|
+
toolName: part.toolName,
|
|
3703
|
+
output,
|
|
3704
|
+
providerOptions: part.providerMetadata
|
|
3705
|
+
});
|
|
3706
|
+
break;
|
|
3707
|
+
}
|
|
3708
|
+
case "tool-error": {
|
|
3709
|
+
const output = await createToolModelOutput({
|
|
3710
|
+
toolCallId: part.toolCallId,
|
|
3711
|
+
input: part.input,
|
|
3712
|
+
tool: getOwn(tools, part.toolName),
|
|
3713
|
+
output: part.error,
|
|
3714
|
+
errorMode: "json"
|
|
3715
|
+
});
|
|
3716
|
+
content.push({
|
|
3717
|
+
type: "tool-result",
|
|
3718
|
+
toolCallId: part.toolCallId,
|
|
3719
|
+
toolName: part.toolName,
|
|
3720
|
+
output,
|
|
3721
|
+
providerOptions: part.providerMetadata
|
|
3722
|
+
});
|
|
3723
|
+
break;
|
|
3724
|
+
}
|
|
3725
|
+
case "tool-approval-request":
|
|
3726
|
+
const inputSchemaInput = getToolCallInputSchemaInput(part.toolCall);
|
|
3727
|
+
content.push({
|
|
3728
|
+
type: "tool-approval-request",
|
|
3729
|
+
approvalId: part.approvalId,
|
|
3730
|
+
toolCallId: part.toolCall.toolCallId,
|
|
3731
|
+
...part.reason != null ? { reason: part.reason } : {},
|
|
3732
|
+
isAutomatic: part.isAutomatic,
|
|
3733
|
+
...part.signature != null ? { signature: part.signature } : {},
|
|
3734
|
+
...inputSchemaInput != null && !isDeepEqualData(inputSchemaInput.value, part.toolCall.input) ? { inputSchemaInput: inputSchemaInput.value } : {}
|
|
3735
|
+
});
|
|
3736
|
+
}
|
|
3737
|
+
}
|
|
3738
|
+
if (content.length > 0) responseMessages.push({
|
|
3739
|
+
role: "assistant",
|
|
3740
|
+
content
|
|
3741
|
+
});
|
|
3742
|
+
const toolResultContent = [];
|
|
3743
|
+
for (const part of inputContent) {
|
|
3744
|
+
if (part.type !== "tool-approval-response" && part.type !== "tool-result" && part.type !== "tool-error") continue;
|
|
3745
|
+
if (part.type === "tool-approval-response") {
|
|
3746
|
+
toolResultContent.push({
|
|
3747
|
+
type: "tool-approval-response",
|
|
3748
|
+
approvalId: part.approvalId,
|
|
3749
|
+
approved: part.approved,
|
|
3750
|
+
reason: part.reason,
|
|
3751
|
+
providerExecuted: part.providerExecuted
|
|
3752
|
+
});
|
|
3753
|
+
if (part.approved === false) toolResultContent.push({
|
|
3754
|
+
type: "tool-result",
|
|
3755
|
+
toolCallId: part.toolCall.toolCallId,
|
|
3756
|
+
toolName: part.toolCall.toolName,
|
|
3757
|
+
output: {
|
|
3758
|
+
type: "execution-denied",
|
|
3759
|
+
reason: part.reason
|
|
3760
|
+
}
|
|
3761
|
+
});
|
|
3762
|
+
continue;
|
|
3763
|
+
}
|
|
3764
|
+
if (part.providerExecuted) continue;
|
|
3765
|
+
const output = await createToolModelOutput({
|
|
3766
|
+
toolCallId: part.toolCallId,
|
|
3767
|
+
input: part.input,
|
|
3768
|
+
tool: getOwn(tools, part.toolName),
|
|
3769
|
+
output: part.type === "tool-result" ? part.output : part.error,
|
|
3770
|
+
errorMode: part.type === "tool-error" ? "text" : "none"
|
|
3771
|
+
});
|
|
3772
|
+
toolResultContent.push({
|
|
3773
|
+
type: "tool-result",
|
|
3774
|
+
toolCallId: part.toolCallId,
|
|
3775
|
+
toolName: part.toolName,
|
|
3776
|
+
output,
|
|
3777
|
+
...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}
|
|
3778
|
+
});
|
|
3779
|
+
}
|
|
3780
|
+
if (toolResultContent.length > 0) responseMessages.push({
|
|
3781
|
+
role: "tool",
|
|
3782
|
+
content: sortToolResultContentByToolCallOrder({
|
|
3783
|
+
toolResultContent,
|
|
3784
|
+
toolCallOrder
|
|
3785
|
+
})
|
|
3786
|
+
});
|
|
3787
|
+
return responseMessages;
|
|
3788
|
+
}
|
|
3789
|
+
function sortToolResultContentByToolCallOrder({ toolResultContent, toolCallOrder }) {
|
|
3790
|
+
const sortedToolResults = toolResultContent.filter((part) => part.type === "tool-result").map((part, index) => ({
|
|
3791
|
+
part,
|
|
3792
|
+
index
|
|
3793
|
+
})).sort((a, b) => {
|
|
3794
|
+
const aOrder = toolCallOrder.get(a.part.toolCallId);
|
|
3795
|
+
const bOrder = toolCallOrder.get(b.part.toolCallId);
|
|
3796
|
+
if (aOrder == null && bOrder == null) return a.index - b.index;
|
|
3797
|
+
if (aOrder == null) return 1;
|
|
3798
|
+
if (bOrder == null) return -1;
|
|
3799
|
+
return aOrder - bOrder || a.index - b.index;
|
|
3800
|
+
}).map(({ part }) => part);
|
|
3801
|
+
let toolResultIndex = 0;
|
|
3802
|
+
return toolResultContent.map((part) => part.type === "tool-result" ? sortedToolResults[toolResultIndex++] : part);
|
|
3803
|
+
}
|
|
3804
|
+
//#endregion
|
|
3805
|
+
//#region src/util/canonical-hash.ts
|
|
3806
|
+
const encoder$1 = new TextEncoder();
|
|
3807
|
+
/**
|
|
3808
|
+
* Deterministic JSON serialization: object keys are sorted so that two
|
|
3809
|
+
* structurally-equal values always produce the same string regardless of key
|
|
3810
|
+
* insertion order. Used as the input to content hashing.
|
|
3811
|
+
*/
|
|
3812
|
+
function canonicalJSON(value) {
|
|
3813
|
+
if (value === null || value === void 0) return JSON.stringify(value);
|
|
3814
|
+
if (typeof value !== "object") return JSON.stringify(value);
|
|
3815
|
+
if (Array.isArray(value)) return `[${value.map((element) => element === void 0 ? "null" : canonicalJSON(element)).join(",")}]`;
|
|
3816
|
+
return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJSON(value[k])}`).join(",")}}`;
|
|
3817
|
+
}
|
|
3818
|
+
function toBase64url(bytes) {
|
|
3819
|
+
return convertUint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
3820
|
+
}
|
|
3821
|
+
/**
|
|
3822
|
+
* Canonical SHA-256 digest (base64url) of an arbitrary JSON-serializable value.
|
|
3823
|
+
*/
|
|
3824
|
+
async function hashCanonical(value) {
|
|
3825
|
+
const digest = await crypto.subtle.digest("SHA-256", encoder$1.encode(canonicalJSON(value)));
|
|
3826
|
+
return toBase64url(new Uint8Array(digest));
|
|
3827
|
+
}
|
|
3828
|
+
//#endregion
|
|
3829
|
+
//#region src/generate-text/tool-approval-signature.ts
|
|
3830
|
+
const encoder = new TextEncoder();
|
|
3831
|
+
function fromBase64url(str) {
|
|
3832
|
+
return convertBase64ToUint8Array(str);
|
|
3833
|
+
}
|
|
3834
|
+
async function importKey(secret) {
|
|
3835
|
+
const keyData = typeof secret === "string" ? encoder.encode(secret) : secret;
|
|
3836
|
+
return crypto.subtle.importKey("raw", keyData, {
|
|
3837
|
+
name: "HMAC",
|
|
3838
|
+
hash: "SHA-256"
|
|
3839
|
+
}, false, ["sign", "verify"]);
|
|
3840
|
+
}
|
|
3841
|
+
function buildPayload(approvalId, toolCallId, toolName, inputDigest) {
|
|
3842
|
+
return encoder.encode(JSON.stringify([
|
|
3843
|
+
"ai-sdk-tool-approval-v1",
|
|
3844
|
+
approvalId,
|
|
3845
|
+
toolCallId,
|
|
3846
|
+
toolName,
|
|
3847
|
+
inputDigest
|
|
3848
|
+
]));
|
|
3849
|
+
}
|
|
3850
|
+
function buildLegacyPayload(approvalId, toolCallId, toolName, inputDigest) {
|
|
3851
|
+
return encoder.encode(`${approvalId}\n${toolCallId}\n${toolName}\n${inputDigest}`);
|
|
3852
|
+
}
|
|
3853
|
+
async function signToolApproval({ secret, approvalId, toolCallId, toolName, input }) {
|
|
3854
|
+
const key = await importKey(secret);
|
|
3855
|
+
const payload = buildPayload(approvalId, toolCallId, toolName, await hashCanonical(input));
|
|
3856
|
+
const sig = await crypto.subtle.sign("HMAC", key, payload);
|
|
3857
|
+
return toBase64url(new Uint8Array(sig));
|
|
3858
|
+
}
|
|
3859
|
+
async function verifyToolApprovalSignature({ secret, signature, approvalId, toolCallId, toolName, input }) {
|
|
3860
|
+
const key = await importKey(secret);
|
|
3861
|
+
const inputDigest = await hashCanonical(input);
|
|
3862
|
+
const sigBytes = fromBase64url(signature);
|
|
3863
|
+
const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest);
|
|
3864
|
+
if (await crypto.subtle.verify("HMAC", key, sigBytes, payload)) return true;
|
|
3865
|
+
if (!approvalId.includes("\n") && !toolCallId.includes("\n") && !toolName.includes("\n")) {
|
|
3866
|
+
const legacyPayload = buildLegacyPayload(approvalId, toolCallId, toolName, inputDigest);
|
|
3867
|
+
return crypto.subtle.verify("HMAC", key, sigBytes, legacyPayload);
|
|
3868
|
+
}
|
|
3869
|
+
return false;
|
|
3870
|
+
}
|
|
3871
|
+
async function maybeSignApproval({ secret, approvalId, toolCallId, toolName, input }) {
|
|
3872
|
+
if (secret == null) return void 0;
|
|
3873
|
+
return signToolApproval({
|
|
3874
|
+
secret,
|
|
3875
|
+
approvalId,
|
|
3876
|
+
toolCallId,
|
|
3877
|
+
toolName,
|
|
3878
|
+
input
|
|
3879
|
+
});
|
|
3880
|
+
}
|
|
3881
|
+
//#endregion
|
|
3882
|
+
//#region src/generate-text/validate-tool-approvals.ts
|
|
3883
|
+
/**
|
|
3884
|
+
* Re-validates approved tool approvals reconstructed from client-supplied
|
|
3885
|
+
* message history before they are executed. Checks HMAC signature (when
|
|
3886
|
+
* configured), input schema, and approval policy.
|
|
3887
|
+
*/
|
|
3888
|
+
async function validateApprovedToolApprovals({ approvedToolApprovals, tools, toolApproval, messages, toolsContext, runtimeContext, toolApprovalSecret, refineToolInput }) {
|
|
3889
|
+
const approved = [];
|
|
3890
|
+
const denied = [];
|
|
3891
|
+
const invalid = [];
|
|
3892
|
+
for (const collectedApproval of approvedToolApprovals) {
|
|
3893
|
+
const tool = getOwn(tools, collectedApproval.toolCall.toolName);
|
|
3894
|
+
const { toolMetadata: _toolMetadata, dynamic: _dynamic, ...toolCallFromHistory } = collectedApproval.toolCall;
|
|
3895
|
+
const approval = {
|
|
3896
|
+
...collectedApproval,
|
|
3897
|
+
toolCall: {
|
|
3898
|
+
...toolCallFromHistory,
|
|
3899
|
+
...tool?.metadata != null ? { toolMetadata: tool.metadata } : {},
|
|
3900
|
+
...tool?.type === "dynamic" ? { dynamic: true } : {},
|
|
3901
|
+
title: tool?.title
|
|
3902
|
+
}
|
|
3903
|
+
};
|
|
3904
|
+
const { approvalRequest, toolCall } = approval;
|
|
3905
|
+
if (toolApprovalSecret != null) {
|
|
3906
|
+
if (approvalRequest.signature == null) throw new InvalidToolApprovalSignatureError({
|
|
3907
|
+
approvalId: approvalRequest.approvalId,
|
|
3908
|
+
toolCallId: toolCall.toolCallId,
|
|
3909
|
+
reason: "missing signature"
|
|
3910
|
+
});
|
|
3911
|
+
if (!await verifyToolApprovalSignature({
|
|
3912
|
+
secret: toolApprovalSecret,
|
|
3913
|
+
signature: approvalRequest.signature,
|
|
3914
|
+
approvalId: approvalRequest.approvalId,
|
|
3915
|
+
toolCallId: toolCall.toolCallId,
|
|
3916
|
+
toolName: toolCall.toolName,
|
|
3917
|
+
input: toolCall.input
|
|
3918
|
+
})) throw new InvalidToolApprovalSignatureError({
|
|
3919
|
+
approvalId: approvalRequest.approvalId,
|
|
3920
|
+
toolCallId: toolCall.toolCallId,
|
|
3921
|
+
reason: "invalid signature"
|
|
3922
|
+
});
|
|
3923
|
+
}
|
|
3924
|
+
if (isExecutableTool(tool) && tool.inputSchema != null) {
|
|
3925
|
+
let validationError;
|
|
3926
|
+
try {
|
|
3927
|
+
const approvedInput = structuredClone(toolCall.input);
|
|
3928
|
+
const hasInputSchemaInput = Object.prototype.hasOwnProperty.call(approvalRequest, "inputSchemaInput");
|
|
3929
|
+
const validation = await safeValidateTypes({
|
|
3930
|
+
value: structuredClone(hasInputSchemaInput ? approvalRequest.inputSchemaInput : toolCall.input),
|
|
3931
|
+
schema: asSchema(tool.inputSchema)
|
|
3932
|
+
});
|
|
3933
|
+
if (!validation.success) validationError = validation.error;
|
|
3934
|
+
else {
|
|
3935
|
+
const revalidatedToolCall = await refineParsedToolCallInput({
|
|
3936
|
+
toolCall: {
|
|
3937
|
+
...toolCall,
|
|
3938
|
+
input: validation.value
|
|
3939
|
+
},
|
|
3940
|
+
refineToolInput
|
|
3941
|
+
});
|
|
3942
|
+
if (!isDeepEqualData(structuredClone(revalidatedToolCall.input), approvedInput)) validationError = /* @__PURE__ */ new Error("Approved tool input does not match the validated schema output.");
|
|
3943
|
+
}
|
|
3944
|
+
} catch (error) {
|
|
3945
|
+
validationError = error;
|
|
3946
|
+
}
|
|
3947
|
+
if (validationError != null) {
|
|
3948
|
+
invalid.push({
|
|
3949
|
+
...approval,
|
|
3950
|
+
error: new InvalidToolInputError({
|
|
3951
|
+
toolName: toolCall.toolName,
|
|
3952
|
+
toolInput: JSON.stringify(toolCall.input),
|
|
3953
|
+
cause: validationError
|
|
3954
|
+
})
|
|
3955
|
+
});
|
|
3956
|
+
continue;
|
|
3957
|
+
}
|
|
3958
|
+
}
|
|
3959
|
+
const approvalStatus = await resolveToolApproval({
|
|
3960
|
+
tools,
|
|
3961
|
+
toolApproval,
|
|
3962
|
+
toolCall,
|
|
3963
|
+
messages,
|
|
3964
|
+
toolsContext,
|
|
3965
|
+
runtimeContext
|
|
3966
|
+
});
|
|
3967
|
+
if (approvalStatus.type === "denied") denied.push({
|
|
3968
|
+
...approval,
|
|
3969
|
+
approvalResponse: {
|
|
3970
|
+
...approval.approvalResponse,
|
|
3971
|
+
approved: false,
|
|
3972
|
+
reason: approvalStatus.reason ?? approval.approvalResponse.reason
|
|
3973
|
+
}
|
|
3974
|
+
});
|
|
3975
|
+
else approved.push(approval);
|
|
3976
|
+
}
|
|
3977
|
+
return {
|
|
3978
|
+
approvedToolApprovals: approved,
|
|
3979
|
+
deniedToolApprovals: denied,
|
|
3980
|
+
invalidToolApprovals: invalid
|
|
3981
|
+
};
|
|
3982
|
+
}
|
|
3983
|
+
//#endregion
|
|
3984
|
+
//#region src/generate-text/tool-call-concurrency.ts
|
|
3985
|
+
/**
|
|
3986
|
+
* Validates the maximum number of tool calls that may execute concurrently.
|
|
3987
|
+
*/
|
|
3988
|
+
function prepareToolCallConcurrency(toolCallConcurrency) {
|
|
3989
|
+
if (toolCallConcurrency == null) return;
|
|
3990
|
+
if (!Number.isInteger(toolCallConcurrency)) throw new InvalidArgumentError({
|
|
3991
|
+
parameter: "toolCallConcurrency",
|
|
3992
|
+
value: toolCallConcurrency,
|
|
3993
|
+
message: "toolCallConcurrency must be an integer"
|
|
3994
|
+
});
|
|
3995
|
+
if (toolCallConcurrency < 1) throw new InvalidArgumentError({
|
|
3996
|
+
parameter: "toolCallConcurrency",
|
|
3997
|
+
value: toolCallConcurrency,
|
|
3998
|
+
message: "toolCallConcurrency must be >= 1"
|
|
3999
|
+
});
|
|
4000
|
+
return toolCallConcurrency;
|
|
4001
|
+
}
|
|
4002
|
+
/**
|
|
4003
|
+
* Maps items with an optional concurrency limit while preserving result order.
|
|
4004
|
+
*
|
|
4005
|
+
* Workers claim items in input order. When the signal is aborted or an
|
|
4006
|
+
* execution rejects, no additional queued items are started.
|
|
4007
|
+
*/
|
|
4008
|
+
async function mapWithConcurrency({ items, concurrency, abortSignal, execute }) {
|
|
4009
|
+
if (concurrency == null || concurrency >= items.length) return Promise.all(items.map(execute));
|
|
4010
|
+
const results = new Array(items.length);
|
|
4011
|
+
let nextIndex = 0;
|
|
4012
|
+
let stopped = false;
|
|
4013
|
+
const worker = async () => {
|
|
4014
|
+
while (!stopped) {
|
|
4015
|
+
abortSignal?.throwIfAborted();
|
|
4016
|
+
const index = nextIndex++;
|
|
4017
|
+
if (index >= items.length) return;
|
|
4018
|
+
try {
|
|
4019
|
+
results[index] = await execute(items[index], index);
|
|
4020
|
+
} catch (error) {
|
|
4021
|
+
stopped = true;
|
|
4022
|
+
throw error;
|
|
4023
|
+
}
|
|
4024
|
+
}
|
|
4025
|
+
};
|
|
4026
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
|
|
4027
|
+
return results;
|
|
4028
|
+
}
|
|
4029
|
+
//#endregion
|
|
4030
|
+
//#region src/util/async-iterable-stream.ts
|
|
4031
|
+
/**
|
|
4032
|
+
* Wraps a ReadableStream and returns an object that is both a ReadableStream and an AsyncIterable.
|
|
4033
|
+
* This enables consumption of the stream using for-await-of, with proper resource cleanup on early exit or error.
|
|
4034
|
+
*
|
|
4035
|
+
* @template T The type of the stream's chunks.
|
|
4036
|
+
* @param source The source ReadableStream to wrap.
|
|
4037
|
+
* @returns An AsyncIterableStream that can be used as both a ReadableStream and an AsyncIterable.
|
|
4038
|
+
*/
|
|
4039
|
+
function createAsyncIterableStream(source) {
|
|
4040
|
+
return asAsyncIterableStream(source.pipeThrough(new TransformStream()));
|
|
4041
|
+
}
|
|
4042
|
+
/**
|
|
4043
|
+
* Attaches the async iterator protocol to an existing ReadableStream in place,
|
|
4044
|
+
* turning it into an AsyncIterableStream without piping through an additional
|
|
4045
|
+
* TransformStream.
|
|
4046
|
+
*
|
|
4047
|
+
* Use this when the stream is already known to be fresh and exclusively owned
|
|
4048
|
+
* (e.g. the readable side of a TransformStream created for this consumer).
|
|
4049
|
+
* Adding an extra `pipeThrough` in that situation creates a chain of two
|
|
4050
|
+
* transforms fed by an active upstream pipe, which can surface a spurious
|
|
4051
|
+
* unhandled `undefined` rejection when the consumer cancels early (observed on
|
|
4052
|
+
* Node.js 26). {@link createAsyncIterableStream} wraps this after adding a
|
|
4053
|
+
* fresh transform for callers that may pass shared or locked streams.
|
|
4054
|
+
*
|
|
4055
|
+
* @template T The type of the stream's chunks.
|
|
4056
|
+
* @param stream The ReadableStream to augment. It must be fresh and unlocked.
|
|
4057
|
+
* @returns The same stream, augmented with the async iterator protocol.
|
|
4058
|
+
*/
|
|
4059
|
+
function asAsyncIterableStream(stream) {
|
|
4060
|
+
/**
|
|
4061
|
+
* Implements the async iterator protocol for the stream.
|
|
4062
|
+
* Ensures proper cleanup (cancelling and releasing the reader) on completion, early exit, or error.
|
|
4063
|
+
*/
|
|
4064
|
+
stream[Symbol.asyncIterator] = function() {
|
|
4065
|
+
const reader = this.getReader();
|
|
4066
|
+
let finished = false;
|
|
4067
|
+
/**
|
|
4068
|
+
* Cleans up the reader by cancelling and releasing the lock.
|
|
4069
|
+
*/
|
|
4070
|
+
async function cleanup(cancelStream) {
|
|
4071
|
+
if (finished) return;
|
|
4072
|
+
finished = true;
|
|
4073
|
+
try {
|
|
4074
|
+
if (cancelStream) await reader.cancel?.();
|
|
4075
|
+
} finally {
|
|
4076
|
+
try {
|
|
4077
|
+
reader.releaseLock();
|
|
4078
|
+
} catch {}
|
|
4079
|
+
}
|
|
4080
|
+
}
|
|
4081
|
+
return {
|
|
4082
|
+
/**
|
|
4083
|
+
* Reads the next chunk from the stream.
|
|
4084
|
+
* @returns A promise resolving to the next IteratorResult.
|
|
4085
|
+
*/
|
|
4086
|
+
async next() {
|
|
4087
|
+
if (finished) return {
|
|
4088
|
+
done: true,
|
|
4089
|
+
value: void 0
|
|
4090
|
+
};
|
|
4091
|
+
let result;
|
|
4092
|
+
try {
|
|
4093
|
+
result = await reader.read();
|
|
4094
|
+
} catch (error) {
|
|
4095
|
+
await cleanup(false);
|
|
4096
|
+
throw error;
|
|
4097
|
+
}
|
|
4098
|
+
const { done, value } = result;
|
|
4099
|
+
if (done) {
|
|
4100
|
+
await cleanup(true);
|
|
4101
|
+
return {
|
|
4102
|
+
done: true,
|
|
4103
|
+
value: void 0
|
|
4104
|
+
};
|
|
4105
|
+
}
|
|
4106
|
+
return {
|
|
4107
|
+
done: false,
|
|
4108
|
+
value
|
|
4109
|
+
};
|
|
4110
|
+
},
|
|
4111
|
+
/**
|
|
4112
|
+
* May be called on early exit (e.g., break from for-await) or after completion.
|
|
4113
|
+
* Ensures the stream is cancelled and resources are released.
|
|
4114
|
+
* @returns A promise resolving to a completed IteratorResult.
|
|
4115
|
+
*/
|
|
4116
|
+
async return() {
|
|
4117
|
+
await cleanup(true);
|
|
4118
|
+
return {
|
|
4119
|
+
done: true,
|
|
4120
|
+
value: void 0
|
|
4121
|
+
};
|
|
4122
|
+
},
|
|
4123
|
+
/**
|
|
4124
|
+
* Called on early exit with error.
|
|
4125
|
+
* Ensures the stream is cancelled and resources are released, then rethrows the error.
|
|
4126
|
+
* @param err The error to throw.
|
|
4127
|
+
* @returns A promise that rejects with the provided error.
|
|
4128
|
+
*/
|
|
4129
|
+
async throw(err) {
|
|
4130
|
+
await cleanup(true);
|
|
4131
|
+
throw err;
|
|
4132
|
+
}
|
|
4133
|
+
};
|
|
4134
|
+
};
|
|
4135
|
+
return stream;
|
|
4136
|
+
}
|
|
4137
|
+
//#endregion
|
|
4138
|
+
//#region src/generate-text/is-output-chunk.ts
|
|
4139
|
+
const isOutputChunkType = {
|
|
4140
|
+
file: true,
|
|
4141
|
+
custom: false,
|
|
4142
|
+
source: false,
|
|
4143
|
+
"text-start": false,
|
|
4144
|
+
"text-end": false,
|
|
4145
|
+
"text-delta": true,
|
|
4146
|
+
"reasoning-start": false,
|
|
4147
|
+
"reasoning-end": false,
|
|
4148
|
+
"reasoning-delta": true,
|
|
4149
|
+
"reasoning-file": true,
|
|
4150
|
+
"tool-input-start": false,
|
|
4151
|
+
"tool-input-end": false,
|
|
4152
|
+
"tool-input-delta": true,
|
|
4153
|
+
"tool-approval-request": false,
|
|
4154
|
+
"tool-approval-response": false,
|
|
4155
|
+
"tool-call": true,
|
|
4156
|
+
"tool-result": false,
|
|
4157
|
+
"tool-error": false,
|
|
4158
|
+
"tool-output-denied": false,
|
|
4159
|
+
"tool-execution-end": false,
|
|
4160
|
+
"model-call-start": false,
|
|
4161
|
+
"model-call-response-metadata": false,
|
|
4162
|
+
"model-call-end": false,
|
|
4163
|
+
error: false,
|
|
4164
|
+
ping: false,
|
|
4165
|
+
raw: false
|
|
4166
|
+
};
|
|
4167
|
+
function isOutputChunk(chunk) {
|
|
4168
|
+
if (!isOutputChunkType[chunk.type]) return false;
|
|
4169
|
+
switch (chunk.type) {
|
|
4170
|
+
case "text-delta":
|
|
4171
|
+
case "reasoning-delta": return chunk.text.length > 0;
|
|
4172
|
+
case "tool-input-delta": return chunk.delta.length > 0;
|
|
4173
|
+
case "file":
|
|
4174
|
+
case "reasoning-file":
|
|
4175
|
+
case "tool-call": return true;
|
|
4176
|
+
default: return false;
|
|
4177
|
+
}
|
|
4178
|
+
}
|
|
4179
|
+
//#endregion
|
|
4180
|
+
//#region src/agent/default-stop-condition.ts
|
|
4181
|
+
/**
|
|
4182
|
+
* Logs the warning for the default stopWhen condition.
|
|
4183
|
+
*/
|
|
4184
|
+
function logDefaultStopConditionWarning({ stepCount, provider, modelId }) {
|
|
4185
|
+
logWarnings({
|
|
4186
|
+
provider,
|
|
4187
|
+
model: modelId,
|
|
4188
|
+
warnings: [{
|
|
4189
|
+
type: "other",
|
|
4190
|
+
message: `The tool loop stopped because it reached the default stopWhen condition, isStepCount(${stepCount}). To allow more steps, set stopWhen to isStepCount(...) with a higher limit or provide a custom stop condition. Learn more: https://ai-sdk.dev/docs/agents/loop-control`
|
|
4191
|
+
}]
|
|
4192
|
+
});
|
|
4193
|
+
}
|
|
4194
|
+
/**
|
|
4195
|
+
* Stop conditions are only evaluated when the tool loop can otherwise continue,
|
|
4196
|
+
* so logging here avoids warning when a call finishes naturally at the limit.
|
|
4197
|
+
*/
|
|
4198
|
+
function createDefaultStopCondition(stepCount) {
|
|
4199
|
+
return ({ steps }) => {
|
|
4200
|
+
if (steps.length !== stepCount) return false;
|
|
4201
|
+
const { provider, modelId } = steps[steps.length - 1].model;
|
|
4202
|
+
logDefaultStopConditionWarning({
|
|
4203
|
+
stepCount,
|
|
4204
|
+
provider,
|
|
4205
|
+
modelId
|
|
4206
|
+
});
|
|
4207
|
+
return true;
|
|
4208
|
+
};
|
|
4209
|
+
}
|
|
4210
|
+
//#endregion
|
|
4211
|
+
export { convertToLanguageModelPrompt as $, toolSearch as A, UnsupportedModelVersionError as At, setAbortTimeout as B, resolveToolApproval as C, asLanguageModelV4 as Ct, convertToReasoningOutputs as D, RetryError as Dt, DefaultGenerateTextResult as E, logWarnings as Et, resolveGeneratedFileData as F, ToolCallNotFoundForApprovalError as Ft, addLanguageModelUsage as G, mergeAbortSignals as H, DefaultGeneratedFile as I, InvalidToolInputError as It, standardizePrompt as J, asLanguageModelUsage as K, DefaultGeneratedFileWithType as L, InvalidToolApprovalSignatureError as Lt, prepareToolsForToolCallers as M, NoSuchToolError as Mt, resolveToolCallerConfiguration as N, NoOutputGeneratedError as Nt, validateToolContext as O, InvalidMessageRoleError as Ot, convertLanguageModelContent as P, MissingToolResultsError as Pt, createToolModelOutput as Q, collectToolApprovals as R, InvalidToolApprovalError as Rt, filterIncludedContext as S, asVideoModelV4 as St, getToolCallInputSchemaInput as T, asEmbeddingModelV4 as Tt, getOwn as U, prepareRetries as V, addImageModelUsage as W, prepareToolChoice as X, prepareTools as Y, prepareLanguageModelCallOptions as Z, createTelemetryDispatcher as _, resolveSpeechModel as _t, createAsyncIterableStream as a, convertDataContentToUint8Array as at, AI_SDK_TELEMETRY_TRACING_CHANNEL as b, resolveVideoModel as bt, validateApprovedToolApprovals as c, download as ct, verifyToolApprovalSignature as d, resolveDecisionModel as dt, downloadAssets as et, hashCanonical as f, resolveEmbeddingModel as ft, DefaultStepResult as g, resolveRerankingModel as gt, createRestrictedTelemetryDispatcher as h, resolveLanguageModel as ht, asAsyncIterableStream as i, convertDataContentToBase64String as it, appendToolCallerMessages as j, ToolCallRepairError as jt, createToolSearchState as k, InvalidDataContentError as kt, maybeSignApproval as l, VERSION as lt, isDeepEqualData as m, resolveImageModel as mt, logDefaultStopConditionWarning as n, convertToLanguageModelV4FilePart as nt, mapWithConcurrency as o, mergeObjects as ot, toResponseMessages as p, resolveExtractionModel as pt, createNullLanguageModelUsage as q, isOutputChunk as r, splitDataUrl as rt, prepareToolCallConcurrency as s, createDefaultDownloadFunction as st, createDefaultStopCondition as t, mapToolResultOutput as tt, signToolApproval as u, asEvaluationModel as ut, getGlobalTelemetryIntegrations as v, resolveSpeechTranslationModel as vt, parseToolCall as w, asImageModelV4 as wt, mergeCallbacks as x, asProviderV4 as xt, registerTelemetry as y, resolveTranscriptionModel as yt, calculateTokensPerSecond as z, InvalidArgumentError as zt };
|
|
4212
|
+
|
|
4213
|
+
//# sourceMappingURL=default-stop-condition-wtuJTiTo.js.map
|