@openrouter/ai-sdk-provider 1.5.4 → 6.0.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +331 -493
- package/dist/index.d.ts +331 -493
- package/dist/index.js +1047 -2782
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1040 -2768
- package/dist/index.mjs.map +1 -1
- package/dist/internal/index.d.mts +315 -361
- package/dist/internal/index.d.ts +315 -361
- package/dist/internal/index.js +372 -2593
- package/dist/internal/index.js.map +1 -1
- package/dist/internal/index.mjs +365 -2582
- package/dist/internal/index.mjs.map +1 -1
- package/package.json +40 -36
package/dist/index.js
CHANGED
|
@@ -1,30 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
2
|
var __defProp = Object.defineProperty;
|
|
4
|
-
var __defProps = Object.defineProperties;
|
|
5
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
-
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
7
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
8
|
-
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
9
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
10
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
11
|
-
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
12
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
13
|
-
var __spreadValues = (a, b) => {
|
|
14
|
-
for (var prop in b || (b = {}))
|
|
15
|
-
if (__hasOwnProp.call(b, prop))
|
|
16
|
-
__defNormalProp(a, prop, b[prop]);
|
|
17
|
-
if (__getOwnPropSymbols)
|
|
18
|
-
for (var prop of __getOwnPropSymbols(b)) {
|
|
19
|
-
if (__propIsEnum.call(b, prop))
|
|
20
|
-
__defNormalProp(a, prop, b[prop]);
|
|
21
|
-
}
|
|
22
|
-
return a;
|
|
23
|
-
};
|
|
24
|
-
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
25
6
|
var __export = (target, all) => {
|
|
26
|
-
for (var
|
|
27
|
-
__defProp(target,
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
28
9
|
};
|
|
29
10
|
var __copyProps = (to, from, except, desc) => {
|
|
30
11
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
@@ -34,2922 +15,1206 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
34
15
|
}
|
|
35
16
|
return to;
|
|
36
17
|
};
|
|
37
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
38
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
39
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
40
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
41
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
42
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
43
|
-
mod
|
|
44
|
-
));
|
|
45
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
46
19
|
|
|
47
20
|
// src/index.ts
|
|
48
21
|
var index_exports = {};
|
|
49
22
|
__export(index_exports, {
|
|
50
|
-
|
|
23
|
+
VERSION: () => VERSION,
|
|
51
24
|
createOpenRouter: () => createOpenRouter,
|
|
52
25
|
openrouter: () => openrouter
|
|
53
26
|
});
|
|
54
27
|
module.exports = __toCommonJS(index_exports);
|
|
55
28
|
|
|
56
|
-
//
|
|
57
|
-
var
|
|
58
|
-
var symbol = Symbol.for(marker);
|
|
59
|
-
var _a;
|
|
60
|
-
var _AISDKError = class _AISDKError2 extends Error {
|
|
61
|
-
/**
|
|
62
|
-
* Creates an AI SDK Error.
|
|
63
|
-
*
|
|
64
|
-
* @param {Object} params - The parameters for creating the error.
|
|
65
|
-
* @param {string} params.name - The name of the error.
|
|
66
|
-
* @param {string} params.message - The error message.
|
|
67
|
-
* @param {unknown} [params.cause] - The underlying cause of the error.
|
|
68
|
-
*/
|
|
69
|
-
constructor({
|
|
70
|
-
name: name14,
|
|
71
|
-
message,
|
|
72
|
-
cause
|
|
73
|
-
}) {
|
|
74
|
-
super(message);
|
|
75
|
-
this[_a] = true;
|
|
76
|
-
this.name = name14;
|
|
77
|
-
this.cause = cause;
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Checks if the given error is an AI SDK Error.
|
|
81
|
-
* @param {unknown} error - The error to check.
|
|
82
|
-
* @returns {boolean} True if the error is an AI SDK Error, false otherwise.
|
|
83
|
-
*/
|
|
84
|
-
static isInstance(error) {
|
|
85
|
-
return _AISDKError2.hasMarker(error, marker);
|
|
86
|
-
}
|
|
87
|
-
static hasMarker(error, marker15) {
|
|
88
|
-
const markerSymbol = Symbol.for(marker15);
|
|
89
|
-
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
|
|
90
|
-
}
|
|
91
|
-
};
|
|
92
|
-
_a = symbol;
|
|
93
|
-
var AISDKError = _AISDKError;
|
|
94
|
-
var name = "AI_APICallError";
|
|
95
|
-
var marker2 = `vercel.ai.error.${name}`;
|
|
96
|
-
var symbol2 = Symbol.for(marker2);
|
|
97
|
-
var _a2;
|
|
98
|
-
var APICallError = class extends AISDKError {
|
|
99
|
-
constructor({
|
|
100
|
-
message,
|
|
101
|
-
url,
|
|
102
|
-
requestBodyValues,
|
|
103
|
-
statusCode,
|
|
104
|
-
responseHeaders,
|
|
105
|
-
responseBody,
|
|
106
|
-
cause,
|
|
107
|
-
isRetryable = statusCode != null && (statusCode === 408 || // request timeout
|
|
108
|
-
statusCode === 409 || // conflict
|
|
109
|
-
statusCode === 429 || // too many requests
|
|
110
|
-
statusCode >= 500),
|
|
111
|
-
// server error
|
|
112
|
-
data
|
|
113
|
-
}) {
|
|
114
|
-
super({ name, message, cause });
|
|
115
|
-
this[_a2] = true;
|
|
116
|
-
this.url = url;
|
|
117
|
-
this.requestBodyValues = requestBodyValues;
|
|
118
|
-
this.statusCode = statusCode;
|
|
119
|
-
this.responseHeaders = responseHeaders;
|
|
120
|
-
this.responseBody = responseBody;
|
|
121
|
-
this.isRetryable = isRetryable;
|
|
122
|
-
this.data = data;
|
|
123
|
-
}
|
|
124
|
-
static isInstance(error) {
|
|
125
|
-
return AISDKError.hasMarker(error, marker2);
|
|
126
|
-
}
|
|
127
|
-
};
|
|
128
|
-
_a2 = symbol2;
|
|
129
|
-
var name2 = "AI_EmptyResponseBodyError";
|
|
130
|
-
var marker3 = `vercel.ai.error.${name2}`;
|
|
131
|
-
var symbol3 = Symbol.for(marker3);
|
|
132
|
-
var _a3;
|
|
133
|
-
var EmptyResponseBodyError = class extends AISDKError {
|
|
134
|
-
// used in isInstance
|
|
135
|
-
constructor({ message = "Empty response body" } = {}) {
|
|
136
|
-
super({ name: name2, message });
|
|
137
|
-
this[_a3] = true;
|
|
138
|
-
}
|
|
139
|
-
static isInstance(error) {
|
|
140
|
-
return AISDKError.hasMarker(error, marker3);
|
|
141
|
-
}
|
|
142
|
-
};
|
|
143
|
-
_a3 = symbol3;
|
|
144
|
-
function getErrorMessage(error) {
|
|
145
|
-
if (error == null) {
|
|
146
|
-
return "unknown error";
|
|
147
|
-
}
|
|
148
|
-
if (typeof error === "string") {
|
|
149
|
-
return error;
|
|
150
|
-
}
|
|
151
|
-
if (error instanceof Error) {
|
|
152
|
-
return error.message;
|
|
153
|
-
}
|
|
154
|
-
return JSON.stringify(error);
|
|
155
|
-
}
|
|
156
|
-
var name3 = "AI_InvalidArgumentError";
|
|
157
|
-
var marker4 = `vercel.ai.error.${name3}`;
|
|
158
|
-
var symbol4 = Symbol.for(marker4);
|
|
159
|
-
var _a4;
|
|
160
|
-
var InvalidArgumentError = class extends AISDKError {
|
|
161
|
-
constructor({
|
|
162
|
-
message,
|
|
163
|
-
cause,
|
|
164
|
-
argument
|
|
165
|
-
}) {
|
|
166
|
-
super({ name: name3, message, cause });
|
|
167
|
-
this[_a4] = true;
|
|
168
|
-
this.argument = argument;
|
|
169
|
-
}
|
|
170
|
-
static isInstance(error) {
|
|
171
|
-
return AISDKError.hasMarker(error, marker4);
|
|
172
|
-
}
|
|
173
|
-
};
|
|
174
|
-
_a4 = symbol4;
|
|
175
|
-
var name4 = "AI_InvalidPromptError";
|
|
176
|
-
var marker5 = `vercel.ai.error.${name4}`;
|
|
177
|
-
var symbol5 = Symbol.for(marker5);
|
|
178
|
-
var _a5;
|
|
179
|
-
var InvalidPromptError = class extends AISDKError {
|
|
180
|
-
constructor({
|
|
181
|
-
prompt,
|
|
182
|
-
message,
|
|
183
|
-
cause
|
|
184
|
-
}) {
|
|
185
|
-
super({ name: name4, message: `Invalid prompt: ${message}`, cause });
|
|
186
|
-
this[_a5] = true;
|
|
187
|
-
this.prompt = prompt;
|
|
188
|
-
}
|
|
189
|
-
static isInstance(error) {
|
|
190
|
-
return AISDKError.hasMarker(error, marker5);
|
|
191
|
-
}
|
|
192
|
-
};
|
|
193
|
-
_a5 = symbol5;
|
|
194
|
-
var name5 = "AI_InvalidResponseDataError";
|
|
195
|
-
var marker6 = `vercel.ai.error.${name5}`;
|
|
196
|
-
var symbol6 = Symbol.for(marker6);
|
|
197
|
-
var _a6;
|
|
198
|
-
var InvalidResponseDataError = class extends AISDKError {
|
|
199
|
-
constructor({
|
|
200
|
-
data,
|
|
201
|
-
message = `Invalid response data: ${JSON.stringify(data)}.`
|
|
202
|
-
}) {
|
|
203
|
-
super({ name: name5, message });
|
|
204
|
-
this[_a6] = true;
|
|
205
|
-
this.data = data;
|
|
206
|
-
}
|
|
207
|
-
static isInstance(error) {
|
|
208
|
-
return AISDKError.hasMarker(error, marker6);
|
|
209
|
-
}
|
|
210
|
-
};
|
|
211
|
-
_a6 = symbol6;
|
|
212
|
-
var name6 = "AI_JSONParseError";
|
|
213
|
-
var marker7 = `vercel.ai.error.${name6}`;
|
|
214
|
-
var symbol7 = Symbol.for(marker7);
|
|
215
|
-
var _a7;
|
|
216
|
-
var JSONParseError = class extends AISDKError {
|
|
217
|
-
constructor({ text, cause }) {
|
|
218
|
-
super({
|
|
219
|
-
name: name6,
|
|
220
|
-
message: `JSON parsing failed: Text: ${text}.
|
|
221
|
-
Error message: ${getErrorMessage(cause)}`,
|
|
222
|
-
cause
|
|
223
|
-
});
|
|
224
|
-
this[_a7] = true;
|
|
225
|
-
this.text = text;
|
|
226
|
-
}
|
|
227
|
-
static isInstance(error) {
|
|
228
|
-
return AISDKError.hasMarker(error, marker7);
|
|
229
|
-
}
|
|
230
|
-
};
|
|
231
|
-
_a7 = symbol7;
|
|
232
|
-
var name7 = "AI_LoadAPIKeyError";
|
|
233
|
-
var marker8 = `vercel.ai.error.${name7}`;
|
|
234
|
-
var symbol8 = Symbol.for(marker8);
|
|
235
|
-
var _a8;
|
|
236
|
-
var LoadAPIKeyError = class extends AISDKError {
|
|
237
|
-
// used in isInstance
|
|
238
|
-
constructor({ message }) {
|
|
239
|
-
super({ name: name7, message });
|
|
240
|
-
this[_a8] = true;
|
|
241
|
-
}
|
|
242
|
-
static isInstance(error) {
|
|
243
|
-
return AISDKError.hasMarker(error, marker8);
|
|
244
|
-
}
|
|
245
|
-
};
|
|
246
|
-
_a8 = symbol8;
|
|
247
|
-
var name8 = "AI_LoadSettingError";
|
|
248
|
-
var marker9 = `vercel.ai.error.${name8}`;
|
|
249
|
-
var symbol9 = Symbol.for(marker9);
|
|
250
|
-
var _a9;
|
|
251
|
-
_a9 = symbol9;
|
|
252
|
-
var name9 = "AI_NoContentGeneratedError";
|
|
253
|
-
var marker10 = `vercel.ai.error.${name9}`;
|
|
254
|
-
var symbol10 = Symbol.for(marker10);
|
|
255
|
-
var _a10;
|
|
256
|
-
var NoContentGeneratedError = class extends AISDKError {
|
|
257
|
-
// used in isInstance
|
|
258
|
-
constructor({
|
|
259
|
-
message = "No content generated."
|
|
260
|
-
} = {}) {
|
|
261
|
-
super({ name: name9, message });
|
|
262
|
-
this[_a10] = true;
|
|
263
|
-
}
|
|
264
|
-
static isInstance(error) {
|
|
265
|
-
return AISDKError.hasMarker(error, marker10);
|
|
266
|
-
}
|
|
267
|
-
};
|
|
268
|
-
_a10 = symbol10;
|
|
269
|
-
var name10 = "AI_NoSuchModelError";
|
|
270
|
-
var marker11 = `vercel.ai.error.${name10}`;
|
|
271
|
-
var symbol11 = Symbol.for(marker11);
|
|
272
|
-
var _a11;
|
|
273
|
-
_a11 = symbol11;
|
|
274
|
-
var name11 = "AI_TooManyEmbeddingValuesForCallError";
|
|
275
|
-
var marker12 = `vercel.ai.error.${name11}`;
|
|
276
|
-
var symbol12 = Symbol.for(marker12);
|
|
277
|
-
var _a12;
|
|
278
|
-
_a12 = symbol12;
|
|
279
|
-
var name12 = "AI_TypeValidationError";
|
|
280
|
-
var marker13 = `vercel.ai.error.${name12}`;
|
|
281
|
-
var symbol13 = Symbol.for(marker13);
|
|
282
|
-
var _a13;
|
|
283
|
-
var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
|
|
284
|
-
constructor({ value, cause }) {
|
|
285
|
-
super({
|
|
286
|
-
name: name12,
|
|
287
|
-
message: `Type validation failed: Value: ${JSON.stringify(value)}.
|
|
288
|
-
Error message: ${getErrorMessage(cause)}`,
|
|
289
|
-
cause
|
|
290
|
-
});
|
|
291
|
-
this[_a13] = true;
|
|
292
|
-
this.value = value;
|
|
293
|
-
}
|
|
294
|
-
static isInstance(error) {
|
|
295
|
-
return AISDKError.hasMarker(error, marker13);
|
|
296
|
-
}
|
|
297
|
-
/**
|
|
298
|
-
* Wraps an error into a TypeValidationError.
|
|
299
|
-
* If the cause is already a TypeValidationError with the same value, it returns the cause.
|
|
300
|
-
* Otherwise, it creates a new TypeValidationError.
|
|
301
|
-
*
|
|
302
|
-
* @param {Object} params - The parameters for wrapping the error.
|
|
303
|
-
* @param {unknown} params.value - The value that failed validation.
|
|
304
|
-
* @param {unknown} params.cause - The original error or cause of the validation failure.
|
|
305
|
-
* @returns {TypeValidationError} A TypeValidationError instance.
|
|
306
|
-
*/
|
|
307
|
-
static wrap({
|
|
308
|
-
value,
|
|
309
|
-
cause
|
|
310
|
-
}) {
|
|
311
|
-
return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
|
|
312
|
-
}
|
|
313
|
-
};
|
|
314
|
-
_a13 = symbol13;
|
|
315
|
-
var TypeValidationError = _TypeValidationError;
|
|
316
|
-
var name13 = "AI_UnsupportedFunctionalityError";
|
|
317
|
-
var marker14 = `vercel.ai.error.${name13}`;
|
|
318
|
-
var symbol14 = Symbol.for(marker14);
|
|
319
|
-
var _a14;
|
|
320
|
-
var UnsupportedFunctionalityError = class extends AISDKError {
|
|
321
|
-
constructor({
|
|
322
|
-
functionality,
|
|
323
|
-
message = `'${functionality}' functionality not supported.`
|
|
324
|
-
}) {
|
|
325
|
-
super({ name: name13, message });
|
|
326
|
-
this[_a14] = true;
|
|
327
|
-
this.functionality = functionality;
|
|
328
|
-
}
|
|
329
|
-
static isInstance(error) {
|
|
330
|
-
return AISDKError.hasMarker(error, marker14);
|
|
331
|
-
}
|
|
332
|
-
};
|
|
333
|
-
_a14 = symbol14;
|
|
29
|
+
// src/openrouter-provider.ts
|
|
30
|
+
var import_provider_utils3 = require("@ai-sdk/provider-utils");
|
|
334
31
|
|
|
335
|
-
//
|
|
336
|
-
var
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
32
|
+
// src/chat/openrouter-chat-language-model.ts
|
|
33
|
+
var import_provider_utils = require("@ai-sdk/provider-utils");
|
|
34
|
+
var import_sdk = require("@openrouter/sdk");
|
|
35
|
+
|
|
36
|
+
// src/utils/build-provider-metadata.ts
|
|
37
|
+
function filterUndefined(obj) {
|
|
38
|
+
return Object.fromEntries(
|
|
39
|
+
Object.entries(obj).filter(([_, v]) => v !== void 0)
|
|
40
|
+
);
|
|
342
41
|
}
|
|
343
|
-
function
|
|
344
|
-
if (
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
const
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
42
|
+
function buildProviderMetadata(response) {
|
|
43
|
+
if (!response) {
|
|
44
|
+
return void 0;
|
|
45
|
+
}
|
|
46
|
+
const usage = response.usage;
|
|
47
|
+
const usageMetadata = usage ? filterUndefined({
|
|
48
|
+
promptTokens: usage.promptTokens,
|
|
49
|
+
completionTokens: usage.completionTokens,
|
|
50
|
+
totalTokens: usage.totalTokens,
|
|
51
|
+
...usage.promptTokensDetails && {
|
|
52
|
+
promptTokensDetails: filterUndefined({
|
|
53
|
+
cachedTokens: usage.promptTokensDetails.cachedTokens ?? void 0,
|
|
54
|
+
cacheWriteTokens: usage.promptTokensDetails.cacheWriteTokens ?? void 0,
|
|
55
|
+
audioTokens: usage.promptTokensDetails.audioTokens ?? void 0,
|
|
56
|
+
videoTokens: usage.promptTokensDetails.videoTokens ?? void 0
|
|
57
|
+
})
|
|
58
|
+
},
|
|
59
|
+
...usage.completionTokensDetails && {
|
|
60
|
+
completionTokensDetails: filterUndefined({
|
|
61
|
+
reasoningTokens: usage.completionTokensDetails.reasoningTokens ?? void 0,
|
|
62
|
+
imageTokens: usage.completionTokensDetails.imageTokens ?? void 0
|
|
63
|
+
})
|
|
64
|
+
},
|
|
65
|
+
cost: usage.cost,
|
|
66
|
+
isByok: usage.isByok,
|
|
67
|
+
costDetails: usage.costDetails
|
|
68
|
+
}) : void 0;
|
|
69
|
+
const metadata = filterUndefined({
|
|
70
|
+
responseId: response.id,
|
|
71
|
+
provider: response.provider,
|
|
72
|
+
usage: usageMetadata
|
|
73
|
+
});
|
|
74
|
+
return {
|
|
75
|
+
openrouter: metadata
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// src/utils/build-usage.ts
|
|
80
|
+
function buildUsage(usage) {
|
|
81
|
+
if (!usage) {
|
|
82
|
+
return {
|
|
83
|
+
inputTokens: {
|
|
84
|
+
total: 0,
|
|
85
|
+
noCache: void 0,
|
|
86
|
+
cacheRead: void 0,
|
|
87
|
+
cacheWrite: void 0
|
|
88
|
+
},
|
|
89
|
+
outputTokens: {
|
|
90
|
+
total: 0,
|
|
91
|
+
text: void 0,
|
|
92
|
+
reasoning: void 0
|
|
93
|
+
},
|
|
94
|
+
raw: void 0
|
|
95
|
+
};
|
|
355
96
|
}
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
97
|
+
const rawUsage = {
|
|
98
|
+
inputTokens: usage.inputTokens ?? null,
|
|
99
|
+
outputTokens: usage.outputTokens ?? null,
|
|
100
|
+
...usage.inputTokensDetails && {
|
|
101
|
+
inputTokensDetails: {
|
|
102
|
+
cachedTokens: usage.inputTokensDetails.cachedTokens ?? null
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
...usage.outputTokensDetails && {
|
|
106
|
+
outputTokensDetails: {
|
|
107
|
+
reasoningTokens: usage.outputTokensDetails.reasoningTokens ?? null
|
|
108
|
+
}
|
|
364
109
|
}
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
110
|
+
};
|
|
111
|
+
return {
|
|
112
|
+
inputTokens: {
|
|
113
|
+
total: usage.inputTokens ?? 0,
|
|
114
|
+
noCache: void 0,
|
|
115
|
+
cacheRead: usage.inputTokensDetails?.cachedTokens,
|
|
116
|
+
cacheWrite: void 0
|
|
117
|
+
},
|
|
118
|
+
outputTokens: {
|
|
119
|
+
total: usage.outputTokens ?? 0,
|
|
120
|
+
text: void 0,
|
|
121
|
+
reasoning: usage.outputTokensDetails?.reasoningTokens
|
|
122
|
+
},
|
|
123
|
+
raw: rawUsage
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// src/chat/convert-to-openrouter-messages.ts
|
|
128
|
+
function convertToOpenRouterMessages(prompt) {
|
|
129
|
+
const result = [];
|
|
130
|
+
for (const message of prompt) {
|
|
131
|
+
const converted = convertMessage(message);
|
|
132
|
+
result.push(...converted);
|
|
133
|
+
}
|
|
134
|
+
return result;
|
|
135
|
+
}
|
|
136
|
+
function convertMessage(message) {
|
|
137
|
+
const messageWithOptions = message;
|
|
138
|
+
const providerOptions = messageWithOptions.providerOptions;
|
|
139
|
+
const providerMetadata = messageWithOptions.providerMetadata;
|
|
140
|
+
switch (message.role) {
|
|
141
|
+
case "system":
|
|
142
|
+
return [{ role: "system", content: message.content }];
|
|
143
|
+
case "user":
|
|
144
|
+
return [convertUserMessage(message.content)];
|
|
145
|
+
case "assistant":
|
|
146
|
+
return convertAssistantMessage(message.content, providerMetadata, providerOptions);
|
|
147
|
+
case "tool":
|
|
148
|
+
return convertToolMessage(message.content);
|
|
149
|
+
default: {
|
|
150
|
+
const _exhaustive = message;
|
|
151
|
+
throw new Error(`Unknown message role: ${_exhaustive.role}`);
|
|
370
152
|
}
|
|
371
|
-
processField(line, "", line);
|
|
372
153
|
}
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
case "
|
|
379
|
-
|
|
380
|
-
`;
|
|
381
|
-
break;
|
|
382
|
-
case "id":
|
|
383
|
-
id = value.includes("\0") ? void 0 : value;
|
|
384
|
-
break;
|
|
385
|
-
case "retry":
|
|
386
|
-
/^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
|
|
387
|
-
new ParseError(`Invalid \`retry\` value: "${value}"`, {
|
|
388
|
-
type: "invalid-retry",
|
|
389
|
-
value,
|
|
390
|
-
line
|
|
391
|
-
})
|
|
392
|
-
);
|
|
154
|
+
}
|
|
155
|
+
function convertUserMessage(content) {
|
|
156
|
+
const convertedContent = [];
|
|
157
|
+
for (const part of content) {
|
|
158
|
+
switch (part.type) {
|
|
159
|
+
case "text": {
|
|
160
|
+
convertedContent.push({ type: "input_text", text: part.text });
|
|
393
161
|
break;
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
|
|
398
|
-
{ type: "unknown-field", field, value, line }
|
|
399
|
-
)
|
|
400
|
-
);
|
|
162
|
+
}
|
|
163
|
+
case "file":
|
|
164
|
+
convertedContent.push(convertFilePart(part));
|
|
401
165
|
break;
|
|
166
|
+
default: {
|
|
167
|
+
const _exhaustive = part;
|
|
168
|
+
throw new Error(`Unknown user content type: ${_exhaustive.type}`);
|
|
169
|
+
}
|
|
402
170
|
}
|
|
403
171
|
}
|
|
404
|
-
|
|
405
|
-
data.length > 0 && onEvent({
|
|
406
|
-
id,
|
|
407
|
-
event: eventType || void 0,
|
|
408
|
-
// If the data buffer's last character is a U+000A LINE FEED (LF) character,
|
|
409
|
-
// then remove the last character from the data buffer.
|
|
410
|
-
data: data.endsWith(`
|
|
411
|
-
`) ? data.slice(0, -1) : data
|
|
412
|
-
}), id = void 0, data = "", eventType = "";
|
|
413
|
-
}
|
|
414
|
-
function reset(options = {}) {
|
|
415
|
-
incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
|
|
416
|
-
}
|
|
417
|
-
return { feed, reset };
|
|
172
|
+
return { role: "user", content: convertedContent };
|
|
418
173
|
}
|
|
419
|
-
function
|
|
420
|
-
const
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
incompleteLine = chunk.slice(searchIndex);
|
|
428
|
-
break;
|
|
429
|
-
} else {
|
|
430
|
-
const line = chunk.slice(searchIndex, lineEnd);
|
|
431
|
-
lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
|
|
432
|
-
` && searchIndex++;
|
|
433
|
-
}
|
|
174
|
+
function convertFilePart(part) {
|
|
175
|
+
const url = convertDataContent(part.data, part.mediaType);
|
|
176
|
+
if (part.mediaType.startsWith("image/")) {
|
|
177
|
+
return {
|
|
178
|
+
type: "input_image",
|
|
179
|
+
imageUrl: url,
|
|
180
|
+
detail: "auto"
|
|
181
|
+
};
|
|
434
182
|
}
|
|
435
|
-
return
|
|
183
|
+
return {
|
|
184
|
+
type: "input_file",
|
|
185
|
+
fileUrl: url
|
|
186
|
+
};
|
|
436
187
|
}
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
constructor({ onError, onRetry, onComment } = {}) {
|
|
441
|
-
let parser;
|
|
442
|
-
super({
|
|
443
|
-
start(controller) {
|
|
444
|
-
parser = createParser({
|
|
445
|
-
onEvent: (event) => {
|
|
446
|
-
controller.enqueue(event);
|
|
447
|
-
},
|
|
448
|
-
onError(error) {
|
|
449
|
-
onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
|
|
450
|
-
},
|
|
451
|
-
onRetry,
|
|
452
|
-
onComment
|
|
453
|
-
});
|
|
454
|
-
},
|
|
455
|
-
transform(chunk) {
|
|
456
|
-
parser.feed(chunk);
|
|
457
|
-
}
|
|
458
|
-
});
|
|
188
|
+
function convertDataContent(data, mediaType) {
|
|
189
|
+
if (data instanceof URL) {
|
|
190
|
+
return data.toString();
|
|
459
191
|
}
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
// node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/selectParser.js
|
|
469
|
-
var import_zod3 = require("zod");
|
|
470
|
-
|
|
471
|
-
// node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
|
|
472
|
-
var import_zod = require("zod");
|
|
473
|
-
|
|
474
|
-
// node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
|
|
475
|
-
var import_zod2 = require("zod");
|
|
476
|
-
|
|
477
|
-
// node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
|
|
478
|
-
var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
|
|
479
|
-
|
|
480
|
-
// node_modules/.pnpm/@ai-sdk+provider-utils@3.0.1_zod@3.25.76/node_modules/@ai-sdk/provider-utils/dist/index.mjs
|
|
481
|
-
function combineHeaders(...headers) {
|
|
482
|
-
return headers.reduce(
|
|
483
|
-
(combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
|
|
484
|
-
{}
|
|
485
|
-
);
|
|
192
|
+
if (data instanceof Uint8Array) {
|
|
193
|
+
const base64 = uint8ArrayToBase64(data);
|
|
194
|
+
return `data:${mediaType};base64,${base64}`;
|
|
195
|
+
}
|
|
196
|
+
if (data.startsWith("http://") || data.startsWith("https://") || data.startsWith("data:")) {
|
|
197
|
+
return data;
|
|
198
|
+
}
|
|
199
|
+
return `data:${mediaType};base64,${data}`;
|
|
486
200
|
}
|
|
487
|
-
function
|
|
488
|
-
|
|
201
|
+
function uint8ArrayToBase64(bytes) {
|
|
202
|
+
let binary = "";
|
|
203
|
+
for (const byte of bytes) {
|
|
204
|
+
binary += String.fromCharCode(byte);
|
|
205
|
+
}
|
|
206
|
+
return btoa(binary);
|
|
489
207
|
}
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
208
|
+
function extractReasoningDetails(content, providerMetadata, providerOptions) {
|
|
209
|
+
const messageLevel = providerOptions?.openrouter?.reasoning_details ?? providerMetadata?.openrouter?.reasoning_details;
|
|
210
|
+
if (messageLevel && Array.isArray(messageLevel) && messageLevel.length > 0) {
|
|
211
|
+
return messageLevel;
|
|
212
|
+
}
|
|
213
|
+
for (const part of content) {
|
|
214
|
+
if (part.type === "reasoning") {
|
|
215
|
+
const partWithMeta = part;
|
|
216
|
+
const partLevel = partWithMeta.providerOptions?.openrouter?.reasoning_details ?? partWithMeta.providerMetadata?.openrouter?.reasoning_details;
|
|
217
|
+
if (partLevel && Array.isArray(partLevel) && partLevel.length > 0) {
|
|
218
|
+
return partLevel;
|
|
219
|
+
}
|
|
501
220
|
}
|
|
502
|
-
return chars.join("");
|
|
503
|
-
};
|
|
504
|
-
if (prefix == null) {
|
|
505
|
-
return generator;
|
|
506
221
|
}
|
|
507
|
-
|
|
508
|
-
throw new InvalidArgumentError({
|
|
509
|
-
argument: "separator",
|
|
510
|
-
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
|
|
511
|
-
});
|
|
512
|
-
}
|
|
513
|
-
return () => `${prefix}${separator}${generator()}`;
|
|
514
|
-
};
|
|
515
|
-
var generateId = createIdGenerator();
|
|
516
|
-
function isAbortError(error) {
|
|
517
|
-
return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
|
|
518
|
-
error.name === "TimeoutError");
|
|
222
|
+
return void 0;
|
|
519
223
|
}
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
224
|
+
function transformReasoningToApiFormat(sdkItems) {
|
|
225
|
+
const apiItems = [];
|
|
226
|
+
for (const rawItem of sdkItems) {
|
|
227
|
+
if (typeof rawItem !== "object" || rawItem === null) {
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
const item = rawItem;
|
|
231
|
+
const baseProps = {
|
|
232
|
+
id: item.id,
|
|
233
|
+
format: item.format ?? null
|
|
234
|
+
};
|
|
235
|
+
let index = item.index ?? 0;
|
|
236
|
+
if (item.type === "reasoning.text" && item.text !== void 0) {
|
|
237
|
+
apiItems.push({
|
|
238
|
+
type: "reasoning.text",
|
|
239
|
+
text: item.text,
|
|
240
|
+
signature: item.signature ?? null,
|
|
241
|
+
index,
|
|
242
|
+
...baseProps
|
|
243
|
+
});
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
if (item.type === "reasoning.summary" && item.summary !== void 0) {
|
|
247
|
+
apiItems.push({
|
|
248
|
+
type: "reasoning.summary",
|
|
249
|
+
summary: typeof item.summary === "string" ? item.summary : "",
|
|
250
|
+
index,
|
|
251
|
+
...baseProps
|
|
539
252
|
});
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
if (item.type === "reasoning.encrypted" && item.data !== void 0) {
|
|
256
|
+
apiItems.push({
|
|
257
|
+
type: "reasoning.encrypted",
|
|
258
|
+
data: item.data,
|
|
259
|
+
index,
|
|
260
|
+
...baseProps
|
|
261
|
+
});
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
if (item.type === "reasoning" || item.content || item.summary || item.encryptedContent) {
|
|
265
|
+
if (item.content && Array.isArray(item.content)) {
|
|
266
|
+
for (const contentItem of item.content) {
|
|
267
|
+
if (contentItem.type === "reasoning_text" && contentItem.text) {
|
|
268
|
+
apiItems.push({
|
|
269
|
+
type: "reasoning.text",
|
|
270
|
+
text: contentItem.text,
|
|
271
|
+
signature: item.signature ?? null,
|
|
272
|
+
index: index++,
|
|
273
|
+
...baseProps
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
if (item.summary && Array.isArray(item.summary)) {
|
|
279
|
+
for (const summaryItem of item.summary) {
|
|
280
|
+
if (summaryItem.type === "summary_text" && summaryItem.text) {
|
|
281
|
+
apiItems.push({
|
|
282
|
+
type: "reasoning.summary",
|
|
283
|
+
summary: summaryItem.text,
|
|
284
|
+
index: index++,
|
|
285
|
+
...baseProps
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
if (item.encryptedContent) {
|
|
291
|
+
apiItems.push({
|
|
292
|
+
type: "reasoning.encrypted",
|
|
293
|
+
data: item.encryptedContent,
|
|
294
|
+
index: index++,
|
|
295
|
+
...baseProps
|
|
296
|
+
});
|
|
297
|
+
}
|
|
540
298
|
}
|
|
541
299
|
}
|
|
542
|
-
return
|
|
543
|
-
}
|
|
544
|
-
function removeUndefinedEntries(record) {
|
|
545
|
-
return Object.fromEntries(
|
|
546
|
-
Object.entries(record).filter(([_key, value]) => value != null)
|
|
547
|
-
);
|
|
300
|
+
return apiItems;
|
|
548
301
|
}
|
|
549
|
-
function
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
apiKeyParameterName = "apiKey",
|
|
553
|
-
description
|
|
554
|
-
}) {
|
|
555
|
-
if (typeof apiKey === "string") {
|
|
556
|
-
return apiKey;
|
|
302
|
+
function buildReasoningFromDetails(items) {
|
|
303
|
+
if (items.length === 0) {
|
|
304
|
+
return void 0;
|
|
557
305
|
}
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
}
|
|
563
|
-
if (typeof process === "undefined") {
|
|
564
|
-
throw new LoadAPIKeyError({
|
|
565
|
-
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
|
|
566
|
-
});
|
|
567
|
-
}
|
|
568
|
-
apiKey = process.env[environmentVariableName];
|
|
569
|
-
if (apiKey == null) {
|
|
570
|
-
throw new LoadAPIKeyError({
|
|
571
|
-
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
|
|
572
|
-
});
|
|
306
|
+
const reasoning = {};
|
|
307
|
+
const textItems = items.filter((i) => i.type === "reasoning.text" && i.text);
|
|
308
|
+
if (textItems.length > 0) {
|
|
309
|
+
reasoning.text = textItems.map((i) => i.text).join("");
|
|
573
310
|
}
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
311
|
+
const summaryItems = items.filter(
|
|
312
|
+
(i) => i.type === "reasoning.summary" && i.summary
|
|
313
|
+
);
|
|
314
|
+
if (summaryItems.length > 0) {
|
|
315
|
+
reasoning.summary = summaryItems.map((i) => i.summary).join("");
|
|
578
316
|
}
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
const obj = JSON.parse(text);
|
|
585
|
-
if (obj === null || typeof obj !== "object") {
|
|
586
|
-
return obj;
|
|
317
|
+
const encryptedItem = items.find(
|
|
318
|
+
(i) => i.type === "reasoning.encrypted" && i.data
|
|
319
|
+
);
|
|
320
|
+
if (encryptedItem?.data) {
|
|
321
|
+
reasoning.encrypted = encryptedItem.data;
|
|
587
322
|
}
|
|
588
|
-
if (
|
|
589
|
-
return
|
|
323
|
+
if (!reasoning.text && !reasoning.summary && !reasoning.encrypted) {
|
|
324
|
+
return void 0;
|
|
590
325
|
}
|
|
591
|
-
return
|
|
326
|
+
return reasoning;
|
|
592
327
|
}
|
|
593
|
-
function
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
328
|
+
function convertAssistantMessage(content, providerMetadata, providerOptions) {
|
|
329
|
+
const result = [];
|
|
330
|
+
let textContent = "";
|
|
331
|
+
const sdkReasoningDetails = extractReasoningDetails(
|
|
332
|
+
content,
|
|
333
|
+
providerMetadata,
|
|
334
|
+
providerOptions
|
|
335
|
+
);
|
|
336
|
+
const reasoningItems = sdkReasoningDetails ? transformReasoningToApiFormat(sdkReasoningDetails) : [];
|
|
337
|
+
const reasoning = buildReasoningFromDetails(reasoningItems);
|
|
338
|
+
for (const part of content) {
|
|
339
|
+
switch (part.type) {
|
|
340
|
+
case "text":
|
|
341
|
+
textContent += part.text;
|
|
342
|
+
break;
|
|
343
|
+
case "reasoning":
|
|
344
|
+
textContent += part.text;
|
|
345
|
+
break;
|
|
346
|
+
case "tool-call":
|
|
347
|
+
result.push({
|
|
348
|
+
type: "function_call",
|
|
349
|
+
callId: part.toolCallId,
|
|
350
|
+
name: part.toolName,
|
|
351
|
+
arguments: typeof part.input === "string" ? part.input : JSON.stringify(part.input)
|
|
352
|
+
});
|
|
353
|
+
break;
|
|
354
|
+
case "file":
|
|
355
|
+
break;
|
|
356
|
+
case "tool-result":
|
|
357
|
+
result.push(convertToolResult(part));
|
|
358
|
+
break;
|
|
359
|
+
default: {
|
|
360
|
+
const _exhaustive = part;
|
|
361
|
+
throw new Error(
|
|
362
|
+
`Unknown assistant content type: ${_exhaustive.type}`
|
|
363
|
+
);
|
|
610
364
|
}
|
|
611
365
|
}
|
|
612
366
|
}
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
Error.stackTraceLimit = 0;
|
|
618
|
-
try {
|
|
619
|
-
return _parse(text);
|
|
620
|
-
} finally {
|
|
621
|
-
Error.stackTraceLimit = stackTraceLimit;
|
|
622
|
-
}
|
|
623
|
-
}
|
|
624
|
-
var validatorSymbol = Symbol.for("vercel.ai.validator");
|
|
625
|
-
function validator(validate) {
|
|
626
|
-
return { [validatorSymbol]: true, validate };
|
|
627
|
-
}
|
|
628
|
-
function isValidator(value) {
|
|
629
|
-
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
|
|
630
|
-
}
|
|
631
|
-
function asValidator(value) {
|
|
632
|
-
return isValidator(value) ? value : standardSchemaValidator(value);
|
|
633
|
-
}
|
|
634
|
-
function standardSchemaValidator(standardSchema) {
|
|
635
|
-
return validator(async (value) => {
|
|
636
|
-
const result = await standardSchema["~standard"].validate(value);
|
|
637
|
-
return result.issues == null ? { success: true, value: result.value } : {
|
|
638
|
-
success: false,
|
|
639
|
-
error: new TypeValidationError({
|
|
640
|
-
value,
|
|
641
|
-
cause: result.issues
|
|
642
|
-
})
|
|
367
|
+
if (textContent) {
|
|
368
|
+
const assistantMessage = {
|
|
369
|
+
role: "assistant",
|
|
370
|
+
content: textContent
|
|
643
371
|
};
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
372
|
+
if (reasoning) {
|
|
373
|
+
assistantMessage.reasoning = reasoning;
|
|
374
|
+
}
|
|
375
|
+
result.unshift(assistantMessage);
|
|
376
|
+
} else if (reasoning) {
|
|
377
|
+
const assistantMessage = {
|
|
378
|
+
role: "assistant",
|
|
379
|
+
content: ""
|
|
380
|
+
};
|
|
381
|
+
assistantMessage.reasoning = reasoning;
|
|
382
|
+
result.unshift(assistantMessage);
|
|
653
383
|
}
|
|
654
|
-
return result
|
|
384
|
+
return result;
|
|
655
385
|
}
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
try {
|
|
662
|
-
if (validator2.validate == null) {
|
|
663
|
-
return { success: true, value, rawValue: value };
|
|
386
|
+
function convertToolMessage(content) {
|
|
387
|
+
const result = [];
|
|
388
|
+
for (const part of content) {
|
|
389
|
+
if (part.type === "tool-result") {
|
|
390
|
+
result.push(convertToolResult(part));
|
|
664
391
|
}
|
|
665
|
-
const result = await validator2.validate(value);
|
|
666
|
-
if (result.success) {
|
|
667
|
-
return { success: true, value: result.value, rawValue: value };
|
|
668
|
-
}
|
|
669
|
-
return {
|
|
670
|
-
success: false,
|
|
671
|
-
error: TypeValidationError.wrap({ value, cause: result.error }),
|
|
672
|
-
rawValue: value
|
|
673
|
-
};
|
|
674
|
-
} catch (error) {
|
|
675
|
-
return {
|
|
676
|
-
success: false,
|
|
677
|
-
error: TypeValidationError.wrap({ value, cause: error }),
|
|
678
|
-
rawValue: value
|
|
679
|
-
};
|
|
680
392
|
}
|
|
393
|
+
return result;
|
|
394
|
+
}
|
|
395
|
+
function convertToolResult(part) {
|
|
396
|
+
const output = convertToolResultOutput(part.output);
|
|
397
|
+
return {
|
|
398
|
+
type: "function_call_output",
|
|
399
|
+
callId: part.toolCallId,
|
|
400
|
+
output: output.value,
|
|
401
|
+
status: output.isError ? "incomplete" : "completed"
|
|
402
|
+
};
|
|
681
403
|
}
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
return
|
|
404
|
+
function convertToolResultOutput(output) {
|
|
405
|
+
switch (output.type) {
|
|
406
|
+
case "text":
|
|
407
|
+
return { value: output.value, isError: false };
|
|
408
|
+
case "json":
|
|
409
|
+
return { value: JSON.stringify(output.value), isError: false };
|
|
410
|
+
case "execution-denied":
|
|
411
|
+
return {
|
|
412
|
+
value: `Execution denied: ${output.reason ?? "No reason provided"}`,
|
|
413
|
+
isError: true
|
|
414
|
+
};
|
|
415
|
+
case "error-text":
|
|
416
|
+
return { value: output.value, isError: true };
|
|
417
|
+
case "error-json":
|
|
418
|
+
return { value: JSON.stringify(output.value), isError: true };
|
|
419
|
+
case "content": {
|
|
420
|
+
const textParts = output.value.filter((item) => item.type === "text").map((item) => item.text);
|
|
421
|
+
return { value: textParts.join("\n"), isError: false };
|
|
690
422
|
}
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
throw error;
|
|
423
|
+
default: {
|
|
424
|
+
const _exhaustive = output;
|
|
425
|
+
throw new Error(`Unknown tool result output type: ${_exhaustive.type}`);
|
|
695
426
|
}
|
|
696
|
-
throw new JSONParseError({ text, cause: error });
|
|
697
427
|
}
|
|
698
428
|
}
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
429
|
+
|
|
430
|
+
// src/chat/extract-reasoning-details.ts
|
|
431
|
+
function extractReasoningDetails2(response) {
|
|
432
|
+
const extractedDetails = [];
|
|
433
|
+
for (const outputItem of response.output) {
|
|
434
|
+
if ("type" in outputItem && outputItem.type === "reasoning") {
|
|
435
|
+
const reasoningItem = outputItem;
|
|
436
|
+
extractedDetails.push({
|
|
437
|
+
type: "reasoning",
|
|
438
|
+
id: reasoningItem.id,
|
|
439
|
+
content: reasoningItem.content,
|
|
440
|
+
summary: reasoningItem.summary,
|
|
441
|
+
encryptedContent: reasoningItem.encryptedContent,
|
|
442
|
+
signature: reasoningItem.signature,
|
|
443
|
+
format: reasoningItem.format
|
|
444
|
+
});
|
|
707
445
|
}
|
|
708
|
-
return await safeValidateTypes({ value, schema });
|
|
709
|
-
} catch (error) {
|
|
710
|
-
return {
|
|
711
|
-
success: false,
|
|
712
|
-
error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
|
|
713
|
-
rawValue: void 0
|
|
714
|
-
};
|
|
715
446
|
}
|
|
447
|
+
return extractedDetails.length > 0 ? extractedDetails : void 0;
|
|
716
448
|
}
|
|
717
|
-
function
|
|
718
|
-
|
|
719
|
-
secureJsonParse(input);
|
|
720
|
-
return true;
|
|
721
|
-
} catch (e) {
|
|
449
|
+
function hasEncryptedReasoning(reasoningDetails) {
|
|
450
|
+
if (!reasoningDetails) {
|
|
722
451
|
return false;
|
|
723
452
|
}
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
}) {
|
|
729
|
-
return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
|
|
730
|
-
new TransformStream({
|
|
731
|
-
async transform({ data }, controller) {
|
|
732
|
-
if (data === "[DONE]") {
|
|
733
|
-
return;
|
|
734
|
-
}
|
|
735
|
-
controller.enqueue(await safeParseJSON({ text: data, schema }));
|
|
736
|
-
}
|
|
737
|
-
})
|
|
738
|
-
);
|
|
739
|
-
}
|
|
740
|
-
var getOriginalFetch2 = () => globalThis.fetch;
|
|
741
|
-
var postJsonToApi = async ({
|
|
742
|
-
url,
|
|
743
|
-
headers,
|
|
744
|
-
body,
|
|
745
|
-
failedResponseHandler,
|
|
746
|
-
successfulResponseHandler,
|
|
747
|
-
abortSignal,
|
|
748
|
-
fetch
|
|
749
|
-
}) => postToApi({
|
|
750
|
-
url,
|
|
751
|
-
headers: __spreadValues({
|
|
752
|
-
"Content-Type": "application/json"
|
|
753
|
-
}, headers),
|
|
754
|
-
body: {
|
|
755
|
-
content: JSON.stringify(body),
|
|
756
|
-
values: body
|
|
757
|
-
},
|
|
758
|
-
failedResponseHandler,
|
|
759
|
-
successfulResponseHandler,
|
|
760
|
-
abortSignal,
|
|
761
|
-
fetch
|
|
762
|
-
});
|
|
763
|
-
var postToApi = async ({
|
|
764
|
-
url,
|
|
765
|
-
headers = {},
|
|
766
|
-
body,
|
|
767
|
-
successfulResponseHandler,
|
|
768
|
-
failedResponseHandler,
|
|
769
|
-
abortSignal,
|
|
770
|
-
fetch = getOriginalFetch2()
|
|
771
|
-
}) => {
|
|
772
|
-
try {
|
|
773
|
-
const response = await fetch(url, {
|
|
774
|
-
method: "POST",
|
|
775
|
-
headers: removeUndefinedEntries(headers),
|
|
776
|
-
body: body.content,
|
|
777
|
-
signal: abortSignal
|
|
778
|
-
});
|
|
779
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
780
|
-
if (!response.ok) {
|
|
781
|
-
let errorInformation;
|
|
782
|
-
try {
|
|
783
|
-
errorInformation = await failedResponseHandler({
|
|
784
|
-
response,
|
|
785
|
-
url,
|
|
786
|
-
requestBodyValues: body.values
|
|
787
|
-
});
|
|
788
|
-
} catch (error) {
|
|
789
|
-
if (isAbortError(error) || APICallError.isInstance(error)) {
|
|
790
|
-
throw error;
|
|
791
|
-
}
|
|
792
|
-
throw new APICallError({
|
|
793
|
-
message: "Failed to process error response",
|
|
794
|
-
cause: error,
|
|
795
|
-
statusCode: response.status,
|
|
796
|
-
url,
|
|
797
|
-
responseHeaders,
|
|
798
|
-
requestBodyValues: body.values
|
|
799
|
-
});
|
|
800
|
-
}
|
|
801
|
-
throw errorInformation.value;
|
|
802
|
-
}
|
|
803
|
-
try {
|
|
804
|
-
return await successfulResponseHandler({
|
|
805
|
-
response,
|
|
806
|
-
url,
|
|
807
|
-
requestBodyValues: body.values
|
|
808
|
-
});
|
|
809
|
-
} catch (error) {
|
|
810
|
-
if (error instanceof Error) {
|
|
811
|
-
if (isAbortError(error) || APICallError.isInstance(error)) {
|
|
812
|
-
throw error;
|
|
813
|
-
}
|
|
814
|
-
}
|
|
815
|
-
throw new APICallError({
|
|
816
|
-
message: "Failed to process successful response",
|
|
817
|
-
cause: error,
|
|
818
|
-
statusCode: response.status,
|
|
819
|
-
url,
|
|
820
|
-
responseHeaders,
|
|
821
|
-
requestBodyValues: body.values
|
|
822
|
-
});
|
|
453
|
+
return reasoningDetails.some((d) => {
|
|
454
|
+
if (typeof d === "object" && d !== null) {
|
|
455
|
+
const obj = d;
|
|
456
|
+
return obj.encryptedContent != null || obj.type === "reasoning.encrypted";
|
|
823
457
|
}
|
|
824
|
-
|
|
825
|
-
throw handleFetchError({ error, url, requestBodyValues: body.values });
|
|
826
|
-
}
|
|
827
|
-
};
|
|
828
|
-
var createJsonErrorResponseHandler = ({
|
|
829
|
-
errorSchema,
|
|
830
|
-
errorToMessage,
|
|
831
|
-
isRetryable
|
|
832
|
-
}) => async ({ response, url, requestBodyValues }) => {
|
|
833
|
-
const responseBody = await response.text();
|
|
834
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
835
|
-
if (responseBody.trim() === "") {
|
|
836
|
-
return {
|
|
837
|
-
responseHeaders,
|
|
838
|
-
value: new APICallError({
|
|
839
|
-
message: response.statusText,
|
|
840
|
-
url,
|
|
841
|
-
requestBodyValues,
|
|
842
|
-
statusCode: response.status,
|
|
843
|
-
responseHeaders,
|
|
844
|
-
responseBody,
|
|
845
|
-
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
|
|
846
|
-
})
|
|
847
|
-
};
|
|
848
|
-
}
|
|
849
|
-
try {
|
|
850
|
-
const parsedError = await parseJSON({
|
|
851
|
-
text: responseBody,
|
|
852
|
-
schema: errorSchema
|
|
853
|
-
});
|
|
854
|
-
return {
|
|
855
|
-
responseHeaders,
|
|
856
|
-
value: new APICallError({
|
|
857
|
-
message: errorToMessage(parsedError),
|
|
858
|
-
url,
|
|
859
|
-
requestBodyValues,
|
|
860
|
-
statusCode: response.status,
|
|
861
|
-
responseHeaders,
|
|
862
|
-
responseBody,
|
|
863
|
-
data: parsedError,
|
|
864
|
-
isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
|
|
865
|
-
})
|
|
866
|
-
};
|
|
867
|
-
} catch (parseError) {
|
|
868
|
-
return {
|
|
869
|
-
responseHeaders,
|
|
870
|
-
value: new APICallError({
|
|
871
|
-
message: response.statusText,
|
|
872
|
-
url,
|
|
873
|
-
requestBodyValues,
|
|
874
|
-
statusCode: response.status,
|
|
875
|
-
responseHeaders,
|
|
876
|
-
responseBody,
|
|
877
|
-
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
|
|
878
|
-
})
|
|
879
|
-
};
|
|
880
|
-
}
|
|
881
|
-
};
|
|
882
|
-
var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
|
|
883
|
-
const responseHeaders = extractResponseHeaders(response);
|
|
884
|
-
if (response.body == null) {
|
|
885
|
-
throw new EmptyResponseBodyError({});
|
|
886
|
-
}
|
|
887
|
-
return {
|
|
888
|
-
responseHeaders,
|
|
889
|
-
value: parseJsonEventStream({
|
|
890
|
-
stream: response.body,
|
|
891
|
-
schema: chunkSchema
|
|
892
|
-
})
|
|
893
|
-
};
|
|
894
|
-
};
|
|
895
|
-
var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
|
|
896
|
-
const responseBody = await response.text();
|
|
897
|
-
const parsedResult = await safeParseJSON({
|
|
898
|
-
text: responseBody,
|
|
899
|
-
schema: responseSchema
|
|
458
|
+
return false;
|
|
900
459
|
});
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
cause: parsedResult.error,
|
|
906
|
-
statusCode: response.status,
|
|
907
|
-
responseHeaders,
|
|
908
|
-
responseBody,
|
|
909
|
-
url,
|
|
910
|
-
requestBodyValues
|
|
911
|
-
});
|
|
460
|
+
}
|
|
461
|
+
function buildReasoningProviderMetadata(reasoningDetails) {
|
|
462
|
+
if (!reasoningDetails || reasoningDetails.length === 0) {
|
|
463
|
+
return void 0;
|
|
912
464
|
}
|
|
913
465
|
return {
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
466
|
+
openrouter: {
|
|
467
|
+
reasoning_details: reasoningDetails
|
|
468
|
+
}
|
|
917
469
|
};
|
|
918
|
-
};
|
|
919
|
-
var schemaSymbol = Symbol.for("vercel.ai.schema");
|
|
920
|
-
var { btoa, atob } = globalThis;
|
|
921
|
-
function convertUint8ArrayToBase64(array) {
|
|
922
|
-
let latin1string = "";
|
|
923
|
-
for (let i = 0; i < array.length; i++) {
|
|
924
|
-
latin1string += String.fromCodePoint(array[i]);
|
|
925
|
-
}
|
|
926
|
-
return btoa(latin1string);
|
|
927
|
-
}
|
|
928
|
-
function withoutTrailingSlash(url) {
|
|
929
|
-
return url == null ? void 0 : url.replace(/\/$/, "");
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
// src/schemas/reasoning-details.ts
|
|
933
|
-
var import_v4 = require("zod/v4");
|
|
934
|
-
|
|
935
|
-
// src/utils/type-guards.ts
|
|
936
|
-
function isDefinedOrNotNull(value) {
|
|
937
|
-
return value !== null && value !== void 0;
|
|
938
470
|
}
|
|
939
471
|
|
|
940
|
-
// src/
|
|
941
|
-
var ReasoningFormat = /* @__PURE__ */ ((ReasoningFormat2) => {
|
|
942
|
-
ReasoningFormat2["Unknown"] = "unknown";
|
|
943
|
-
ReasoningFormat2["OpenAIResponsesV1"] = "openai-responses-v1";
|
|
944
|
-
ReasoningFormat2["XAIResponsesV1"] = "xai-responses-v1";
|
|
945
|
-
ReasoningFormat2["AnthropicClaudeV1"] = "anthropic-claude-v1";
|
|
946
|
-
ReasoningFormat2["GoogleGeminiV1"] = "google-gemini-v1";
|
|
947
|
-
return ReasoningFormat2;
|
|
948
|
-
})(ReasoningFormat || {});
|
|
949
|
-
|
|
950
|
-
// src/schemas/reasoning-details.ts
|
|
951
|
-
var CommonReasoningDetailSchema = import_v4.z.object({
|
|
952
|
-
id: import_v4.z.string().nullish(),
|
|
953
|
-
format: import_v4.z.enum(ReasoningFormat).nullish(),
|
|
954
|
-
index: import_v4.z.number().optional()
|
|
955
|
-
}).loose();
|
|
956
|
-
var ReasoningDetailSummarySchema = import_v4.z.object({
|
|
957
|
-
type: import_v4.z.literal("reasoning.summary" /* Summary */),
|
|
958
|
-
summary: import_v4.z.string()
|
|
959
|
-
}).extend(CommonReasoningDetailSchema.shape);
|
|
960
|
-
var ReasoningDetailEncryptedSchema = import_v4.z.object({
|
|
961
|
-
type: import_v4.z.literal("reasoning.encrypted" /* Encrypted */),
|
|
962
|
-
data: import_v4.z.string()
|
|
963
|
-
}).extend(CommonReasoningDetailSchema.shape);
|
|
964
|
-
var ReasoningDetailTextSchema = import_v4.z.object({
|
|
965
|
-
type: import_v4.z.literal("reasoning.text" /* Text */),
|
|
966
|
-
text: import_v4.z.string().nullish(),
|
|
967
|
-
signature: import_v4.z.string().nullish()
|
|
968
|
-
}).extend(CommonReasoningDetailSchema.shape);
|
|
969
|
-
var ReasoningDetailUnionSchema = import_v4.z.union([
|
|
970
|
-
ReasoningDetailSummarySchema,
|
|
971
|
-
ReasoningDetailEncryptedSchema,
|
|
972
|
-
ReasoningDetailTextSchema
|
|
973
|
-
]);
|
|
974
|
-
var ReasoningDetailsWithUnknownSchema = import_v4.z.union([
|
|
975
|
-
ReasoningDetailUnionSchema,
|
|
976
|
-
import_v4.z.unknown().transform(() => null)
|
|
977
|
-
]);
|
|
978
|
-
var ReasoningDetailArraySchema = import_v4.z.array(ReasoningDetailsWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
|
|
979
|
-
var OutputUnionToReasoningDetailsSchema = import_v4.z.union([
|
|
980
|
-
import_v4.z.object({
|
|
981
|
-
delta: import_v4.z.object({
|
|
982
|
-
reasoning_details: import_v4.z.array(ReasoningDetailsWithUnknownSchema)
|
|
983
|
-
})
|
|
984
|
-
}).transform(
|
|
985
|
-
(data) => data.delta.reasoning_details.filter(isDefinedOrNotNull)
|
|
986
|
-
),
|
|
987
|
-
import_v4.z.object({
|
|
988
|
-
message: import_v4.z.object({
|
|
989
|
-
reasoning_details: import_v4.z.array(ReasoningDetailsWithUnknownSchema)
|
|
990
|
-
})
|
|
991
|
-
}).transform(
|
|
992
|
-
(data) => data.message.reasoning_details.filter(isDefinedOrNotNull)
|
|
993
|
-
),
|
|
994
|
-
import_v4.z.object({
|
|
995
|
-
text: import_v4.z.string(),
|
|
996
|
-
reasoning_details: import_v4.z.array(ReasoningDetailsWithUnknownSchema)
|
|
997
|
-
}).transform((data) => data.reasoning_details.filter(isDefinedOrNotNull))
|
|
998
|
-
]);
|
|
999
|
-
|
|
1000
|
-
// src/schemas/error-response.ts
|
|
1001
|
-
var import_v42 = require("zod/v4");
|
|
1002
|
-
var OpenRouterErrorResponseSchema = import_v42.z.object({
|
|
1003
|
-
error: import_v42.z.object({
|
|
1004
|
-
code: import_v42.z.union([import_v42.z.string(), import_v42.z.number()]).nullable().optional().default(null),
|
|
1005
|
-
message: import_v42.z.string(),
|
|
1006
|
-
type: import_v42.z.string().nullable().optional().default(null),
|
|
1007
|
-
param: import_v42.z.any().nullable().optional().default(null)
|
|
1008
|
-
}).passthrough()
|
|
1009
|
-
}).passthrough();
|
|
1010
|
-
var openrouterFailedResponseHandler = createJsonErrorResponseHandler({
|
|
1011
|
-
errorSchema: OpenRouterErrorResponseSchema,
|
|
1012
|
-
errorToMessage: (data) => data.error.message
|
|
1013
|
-
});
|
|
1014
|
-
|
|
1015
|
-
// src/schemas/provider-metadata.ts
|
|
1016
|
-
var import_v43 = require("zod/v4");
|
|
1017
|
-
var FileAnnotationSchema = import_v43.z.object({
|
|
1018
|
-
type: import_v43.z.literal("file"),
|
|
1019
|
-
file: import_v43.z.object({
|
|
1020
|
-
hash: import_v43.z.string(),
|
|
1021
|
-
name: import_v43.z.string(),
|
|
1022
|
-
content: import_v43.z.array(
|
|
1023
|
-
import_v43.z.object({
|
|
1024
|
-
type: import_v43.z.string(),
|
|
1025
|
-
text: import_v43.z.string().optional()
|
|
1026
|
-
}).catchall(import_v43.z.any())
|
|
1027
|
-
).optional()
|
|
1028
|
-
}).catchall(import_v43.z.any())
|
|
1029
|
-
}).catchall(import_v43.z.any());
|
|
1030
|
-
var OpenRouterProviderMetadataSchema = import_v43.z.object({
|
|
1031
|
-
provider: import_v43.z.string(),
|
|
1032
|
-
reasoning_details: import_v43.z.array(ReasoningDetailUnionSchema).optional(),
|
|
1033
|
-
annotations: import_v43.z.array(FileAnnotationSchema).optional(),
|
|
1034
|
-
usage: import_v43.z.object({
|
|
1035
|
-
promptTokens: import_v43.z.number(),
|
|
1036
|
-
promptTokensDetails: import_v43.z.object({
|
|
1037
|
-
cachedTokens: import_v43.z.number()
|
|
1038
|
-
}).catchall(import_v43.z.any()).optional(),
|
|
1039
|
-
completionTokens: import_v43.z.number(),
|
|
1040
|
-
completionTokensDetails: import_v43.z.object({
|
|
1041
|
-
reasoningTokens: import_v43.z.number()
|
|
1042
|
-
}).catchall(import_v43.z.any()).optional(),
|
|
1043
|
-
totalTokens: import_v43.z.number(),
|
|
1044
|
-
cost: import_v43.z.number().optional(),
|
|
1045
|
-
costDetails: import_v43.z.object({
|
|
1046
|
-
upstreamInferenceCost: import_v43.z.number()
|
|
1047
|
-
}).catchall(import_v43.z.any()).optional()
|
|
1048
|
-
}).catchall(import_v43.z.any())
|
|
1049
|
-
}).catchall(import_v43.z.any());
|
|
1050
|
-
var OpenRouterProviderOptionsSchema = import_v43.z.object({
|
|
1051
|
-
openrouter: import_v43.z.object({
|
|
1052
|
-
reasoning_details: import_v43.z.array(ReasoningDetailUnionSchema).optional(),
|
|
1053
|
-
annotations: import_v43.z.array(FileAnnotationSchema).optional()
|
|
1054
|
-
}).optional()
|
|
1055
|
-
}).optional();
|
|
1056
|
-
|
|
1057
|
-
// src/utils/map-finish-reason.ts
|
|
472
|
+
// src/chat/map-openrouter-finish-reason.ts
|
|
1058
473
|
function mapOpenRouterFinishReason(finishReason) {
|
|
474
|
+
if (finishReason == null) {
|
|
475
|
+
return { unified: "other", raw: void 0 };
|
|
476
|
+
}
|
|
1059
477
|
switch (finishReason) {
|
|
478
|
+
case "end_turn":
|
|
1060
479
|
case "stop":
|
|
1061
|
-
|
|
480
|
+
case "stop_sequence":
|
|
481
|
+
return { unified: "stop", raw: finishReason };
|
|
482
|
+
case "max_tokens":
|
|
1062
483
|
case "length":
|
|
1063
|
-
return "length";
|
|
1064
|
-
case "
|
|
1065
|
-
return "content-filter";
|
|
1066
|
-
case "function_call":
|
|
484
|
+
return { unified: "length", raw: finishReason };
|
|
485
|
+
case "tool_use":
|
|
1067
486
|
case "tool_calls":
|
|
1068
|
-
return "tool-calls";
|
|
487
|
+
return { unified: "tool-calls", raw: finishReason };
|
|
488
|
+
case "content_filter":
|
|
489
|
+
return { unified: "content-filter", raw: finishReason };
|
|
490
|
+
case "error":
|
|
491
|
+
return { unified: "error", raw: finishReason };
|
|
1069
492
|
default:
|
|
1070
|
-
return "
|
|
1071
|
-
}
|
|
1072
|
-
}
|
|
1073
|
-
|
|
1074
|
-
// src/types/openrouter-chat-completions-input.ts
|
|
1075
|
-
var OPENROUTER_AUDIO_FORMATS = [
|
|
1076
|
-
"wav",
|
|
1077
|
-
"mp3",
|
|
1078
|
-
"aiff",
|
|
1079
|
-
"aac",
|
|
1080
|
-
"ogg",
|
|
1081
|
-
"flac",
|
|
1082
|
-
"m4a",
|
|
1083
|
-
"pcm16",
|
|
1084
|
-
"pcm24"
|
|
1085
|
-
];
|
|
1086
|
-
|
|
1087
|
-
// src/chat/is-url.ts
|
|
1088
|
-
function isUrl({
|
|
1089
|
-
url,
|
|
1090
|
-
protocols
|
|
1091
|
-
}) {
|
|
1092
|
-
try {
|
|
1093
|
-
const urlObj = new URL(url);
|
|
1094
|
-
return protocols.has(urlObj.protocol);
|
|
1095
|
-
} catch (_) {
|
|
1096
|
-
return false;
|
|
493
|
+
return { unified: "other", raw: finishReason };
|
|
1097
494
|
}
|
|
1098
495
|
}
|
|
1099
496
|
|
|
1100
|
-
// src/chat/
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
497
|
+
// src/chat/openrouter-chat-language-model.ts
|
|
498
|
+
var OpenRouterChatLanguageModel = class {
|
|
499
|
+
specificationVersion = "v3";
|
|
500
|
+
provider = "openrouter";
|
|
501
|
+
modelId;
|
|
502
|
+
settings;
|
|
503
|
+
/**
|
|
504
|
+
* Supported URL patterns by media type.
|
|
505
|
+
* OpenRouter Chat API only supports image URLs natively.
|
|
506
|
+
* PDF URLs are not supported - use PDF data URIs or the Responses API instead.
|
|
507
|
+
*/
|
|
508
|
+
supportedUrls = {
|
|
509
|
+
"image/*": [/^https?:\/\/.*$/]
|
|
510
|
+
};
|
|
511
|
+
constructor(modelId, settings) {
|
|
512
|
+
this.modelId = modelId;
|
|
513
|
+
this.settings = settings;
|
|
1116
514
|
}
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
"x-m4a": "m4a",
|
|
1145
|
-
mp4: "m4a",
|
|
1146
|
-
// AIFF variants
|
|
1147
|
-
aiff: "aiff",
|
|
1148
|
-
"x-aiff": "aiff",
|
|
1149
|
-
// FLAC
|
|
1150
|
-
flac: "flac",
|
|
1151
|
-
"x-flac": "flac",
|
|
1152
|
-
// PCM variants
|
|
1153
|
-
pcm16: "pcm16",
|
|
1154
|
-
pcm24: "pcm24"
|
|
1155
|
-
};
|
|
1156
|
-
function getInputAudioData(part) {
|
|
1157
|
-
const fileData = getFileUrl({
|
|
1158
|
-
part,
|
|
1159
|
-
defaultMediaType: "audio/mpeg"
|
|
1160
|
-
});
|
|
1161
|
-
if (isUrl({
|
|
1162
|
-
url: fileData,
|
|
1163
|
-
protocols: /* @__PURE__ */ new Set(["http:", "https:"])
|
|
1164
|
-
})) {
|
|
1165
|
-
throw new Error(
|
|
1166
|
-
`Audio files cannot be provided as URLs.
|
|
1167
|
-
|
|
1168
|
-
OpenRouter requires audio to be base64-encoded. Please:
|
|
1169
|
-
1. Download the audio file locally
|
|
1170
|
-
2. Read it as a Buffer or Uint8Array
|
|
1171
|
-
3. Pass it as the data parameter
|
|
1172
|
-
|
|
1173
|
-
The AI SDK will automatically handle base64 encoding.
|
|
1174
|
-
|
|
1175
|
-
Learn more: https://openrouter.ai/docs/features/multimodal/audio`
|
|
1176
|
-
);
|
|
1177
|
-
}
|
|
1178
|
-
const data = getBase64FromDataUrl(fileData);
|
|
1179
|
-
const mediaType = part.mediaType || "audio/mpeg";
|
|
1180
|
-
const rawFormat = mediaType.replace("audio/", "");
|
|
1181
|
-
const format = MIME_TO_FORMAT[rawFormat];
|
|
1182
|
-
if (format === void 0) {
|
|
1183
|
-
const supportedList = OPENROUTER_AUDIO_FORMATS.join(", ");
|
|
1184
|
-
throw new Error(
|
|
1185
|
-
`Unsupported audio format: "${mediaType}"
|
|
1186
|
-
|
|
1187
|
-
OpenRouter supports the following audio formats: ${supportedList}
|
|
1188
|
-
|
|
1189
|
-
Learn more: https://openrouter.ai/docs/features/multimodal/audio`
|
|
515
|
+
async doGenerate(options) {
|
|
516
|
+
const warnings = [];
|
|
517
|
+
const client = new import_sdk.OpenRouter({
|
|
518
|
+
apiKey: this.settings.apiKey,
|
|
519
|
+
serverURL: this.settings.baseURL
|
|
520
|
+
});
|
|
521
|
+
const openRouterInput = convertToOpenRouterMessages(options.prompt);
|
|
522
|
+
const tools = convertToolsToResponsesFormat(options.tools, warnings);
|
|
523
|
+
const toolChoice = convertToolChoiceToResponsesFormat(options.toolChoice);
|
|
524
|
+
const text = convertResponseFormatToText(options.responseFormat);
|
|
525
|
+
const requestParams = {
|
|
526
|
+
model: this.modelId,
|
|
527
|
+
input: openRouterInput,
|
|
528
|
+
stream: false,
|
|
529
|
+
...options.maxOutputTokens !== void 0 && {
|
|
530
|
+
maxOutputTokens: options.maxOutputTokens
|
|
531
|
+
},
|
|
532
|
+
...options.temperature !== void 0 && {
|
|
533
|
+
temperature: options.temperature
|
|
534
|
+
},
|
|
535
|
+
...options.topP !== void 0 && { topP: options.topP },
|
|
536
|
+
...tools.length > 0 && { tools },
|
|
537
|
+
...toolChoice !== void 0 && { toolChoice },
|
|
538
|
+
...text !== void 0 && { text }
|
|
539
|
+
};
|
|
540
|
+
const combinedHeaders = (0, import_provider_utils.normalizeHeaders)(
|
|
541
|
+
(0, import_provider_utils.combineHeaders)(this.settings.headers, options.headers)
|
|
1190
542
|
);
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
// src/chat/convert-to-openrouter-chat-messages.ts
|
|
1196
|
-
function getCacheControl(providerMetadata) {
|
|
1197
|
-
var _a15, _b, _c;
|
|
1198
|
-
const anthropic = providerMetadata == null ? void 0 : providerMetadata.anthropic;
|
|
1199
|
-
const openrouter2 = providerMetadata == null ? void 0 : providerMetadata.openrouter;
|
|
1200
|
-
return (_c = (_b = (_a15 = openrouter2 == null ? void 0 : openrouter2.cacheControl) != null ? _a15 : openrouter2 == null ? void 0 : openrouter2.cache_control) != null ? _b : anthropic == null ? void 0 : anthropic.cacheControl) != null ? _c : anthropic == null ? void 0 : anthropic.cache_control;
|
|
1201
|
-
}
|
|
1202
|
-
function convertToOpenRouterChatMessages(prompt) {
|
|
1203
|
-
var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j;
|
|
1204
|
-
const messages = [];
|
|
1205
|
-
for (const { role, content, providerOptions } of prompt) {
|
|
1206
|
-
switch (role) {
|
|
1207
|
-
case "system": {
|
|
1208
|
-
messages.push({
|
|
1209
|
-
role: "system",
|
|
1210
|
-
content,
|
|
1211
|
-
cache_control: getCacheControl(providerOptions)
|
|
1212
|
-
});
|
|
1213
|
-
break;
|
|
543
|
+
const response = await client.beta.responses.send(requestParams, {
|
|
544
|
+
fetchOptions: {
|
|
545
|
+
signal: options.abortSignal,
|
|
546
|
+
headers: combinedHeaders
|
|
1214
547
|
}
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
548
|
+
});
|
|
549
|
+
const content = [];
|
|
550
|
+
const reasoningDetails = extractReasoningDetails2(response);
|
|
551
|
+
const reasoningMetadata = buildReasoningProviderMetadata(reasoningDetails);
|
|
552
|
+
for (const outputItem of response.output) {
|
|
553
|
+
if (outputItem.type === "reasoning") {
|
|
554
|
+
const reasoningItem = outputItem;
|
|
555
|
+
const reasoningText = reasoningItem.content?.filter((c) => c.type === "reasoning_text").map((c) => c.text).join("") || reasoningItem.summary?.filter((c) => c.type === "summary_text").map((c) => c.text).join("") || "";
|
|
556
|
+
if (reasoningText) {
|
|
557
|
+
content.push({
|
|
558
|
+
type: "reasoning",
|
|
559
|
+
text: reasoningText,
|
|
560
|
+
...reasoningMetadata && { providerMetadata: reasoningMetadata }
|
|
1228
561
|
});
|
|
1229
|
-
break;
|
|
1230
562
|
}
|
|
1231
|
-
|
|
1232
|
-
const
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
type: "text",
|
|
1240
|
-
text: part.text,
|
|
1241
|
-
// For text parts, only use part-specific cache control
|
|
1242
|
-
cache_control: cacheControl
|
|
1243
|
-
};
|
|
1244
|
-
case "file": {
|
|
1245
|
-
if ((_b2 = part.mediaType) == null ? void 0 : _b2.startsWith("image/")) {
|
|
1246
|
-
const url = getFileUrl({
|
|
1247
|
-
part,
|
|
1248
|
-
defaultMediaType: "image/jpeg"
|
|
1249
|
-
});
|
|
1250
|
-
return {
|
|
1251
|
-
type: "image_url",
|
|
1252
|
-
image_url: {
|
|
1253
|
-
url
|
|
1254
|
-
},
|
|
1255
|
-
// For image parts, use part-specific or message-level cache control
|
|
1256
|
-
cache_control: cacheControl
|
|
1257
|
-
};
|
|
1258
|
-
}
|
|
1259
|
-
if ((_c2 = part.mediaType) == null ? void 0 : _c2.startsWith("audio/")) {
|
|
1260
|
-
return {
|
|
1261
|
-
type: "input_audio",
|
|
1262
|
-
input_audio: getInputAudioData(part),
|
|
1263
|
-
cache_control: cacheControl
|
|
1264
|
-
};
|
|
1265
|
-
}
|
|
1266
|
-
const fileName = String(
|
|
1267
|
-
(_g2 = (_f2 = (_e2 = (_d2 = part.providerOptions) == null ? void 0 : _d2.openrouter) == null ? void 0 : _e2.filename) != null ? _f2 : part.filename) != null ? _g2 : ""
|
|
1268
|
-
);
|
|
1269
|
-
const fileData = getFileUrl({
|
|
1270
|
-
part,
|
|
1271
|
-
defaultMediaType: "application/pdf"
|
|
1272
|
-
});
|
|
1273
|
-
if (isUrl({
|
|
1274
|
-
url: fileData,
|
|
1275
|
-
protocols: /* @__PURE__ */ new Set(["http:", "https:"])
|
|
1276
|
-
})) {
|
|
1277
|
-
return {
|
|
1278
|
-
type: "file",
|
|
1279
|
-
file: {
|
|
1280
|
-
filename: fileName,
|
|
1281
|
-
file_data: fileData
|
|
1282
|
-
}
|
|
1283
|
-
};
|
|
1284
|
-
}
|
|
1285
|
-
return {
|
|
1286
|
-
type: "file",
|
|
1287
|
-
file: {
|
|
1288
|
-
filename: fileName,
|
|
1289
|
-
file_data: fileData
|
|
1290
|
-
},
|
|
1291
|
-
cache_control: cacheControl
|
|
1292
|
-
};
|
|
1293
|
-
}
|
|
1294
|
-
default: {
|
|
1295
|
-
return {
|
|
1296
|
-
type: "text",
|
|
1297
|
-
text: "",
|
|
1298
|
-
cache_control: cacheControl
|
|
1299
|
-
};
|
|
1300
|
-
}
|
|
1301
|
-
}
|
|
1302
|
-
}
|
|
1303
|
-
);
|
|
1304
|
-
messages.push({
|
|
1305
|
-
role: "user",
|
|
1306
|
-
content: contentParts
|
|
1307
|
-
});
|
|
1308
|
-
break;
|
|
1309
|
-
}
|
|
1310
|
-
case "assistant": {
|
|
1311
|
-
let text = "";
|
|
1312
|
-
let reasoning = "";
|
|
1313
|
-
const toolCalls = [];
|
|
1314
|
-
const accumulatedReasoningDetails = [];
|
|
1315
|
-
for (const part of content) {
|
|
1316
|
-
switch (part.type) {
|
|
1317
|
-
case "text": {
|
|
1318
|
-
text += part.text;
|
|
1319
|
-
break;
|
|
1320
|
-
}
|
|
1321
|
-
case "tool-call": {
|
|
1322
|
-
const partReasoningDetails = (_c = part.providerOptions) == null ? void 0 : _c.openrouter;
|
|
1323
|
-
if ((partReasoningDetails == null ? void 0 : partReasoningDetails.reasoning_details) && Array.isArray(partReasoningDetails.reasoning_details)) {
|
|
1324
|
-
accumulatedReasoningDetails.push(
|
|
1325
|
-
...partReasoningDetails.reasoning_details
|
|
1326
|
-
);
|
|
1327
|
-
}
|
|
1328
|
-
toolCalls.push({
|
|
1329
|
-
id: part.toolCallId,
|
|
1330
|
-
type: "function",
|
|
1331
|
-
function: {
|
|
1332
|
-
name: part.toolName,
|
|
1333
|
-
arguments: JSON.stringify(part.input)
|
|
1334
|
-
}
|
|
1335
|
-
});
|
|
1336
|
-
break;
|
|
1337
|
-
}
|
|
1338
|
-
case "reasoning": {
|
|
1339
|
-
reasoning += part.text;
|
|
1340
|
-
const parsedPartProviderOptions = OpenRouterProviderOptionsSchema.safeParse(part.providerOptions);
|
|
1341
|
-
if (parsedPartProviderOptions.success && ((_e = (_d = parsedPartProviderOptions.data) == null ? void 0 : _d.openrouter) == null ? void 0 : _e.reasoning_details)) {
|
|
1342
|
-
accumulatedReasoningDetails.push(
|
|
1343
|
-
...parsedPartProviderOptions.data.openrouter.reasoning_details
|
|
1344
|
-
);
|
|
1345
|
-
}
|
|
1346
|
-
break;
|
|
1347
|
-
}
|
|
1348
|
-
case "file":
|
|
1349
|
-
break;
|
|
1350
|
-
default: {
|
|
1351
|
-
break;
|
|
1352
|
-
}
|
|
563
|
+
} else if (outputItem.type === "message") {
|
|
564
|
+
const messageItem = outputItem;
|
|
565
|
+
for (const contentItem of messageItem.content) {
|
|
566
|
+
if (contentItem.type === "output_text" && contentItem.text) {
|
|
567
|
+
content.push({
|
|
568
|
+
type: "text",
|
|
569
|
+
text: contentItem.text
|
|
570
|
+
});
|
|
1353
571
|
}
|
|
1354
572
|
}
|
|
1355
|
-
|
|
1356
|
-
const
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
annotations: messageAnnotations,
|
|
1366
|
-
cache_control: getCacheControl(providerOptions)
|
|
573
|
+
} else if (outputItem.type === "function_call") {
|
|
574
|
+
const functionCallItem = outputItem;
|
|
575
|
+
content.push({
|
|
576
|
+
type: "tool-call",
|
|
577
|
+
toolCallId: functionCallItem.callId,
|
|
578
|
+
toolName: functionCallItem.name,
|
|
579
|
+
// Default to empty object when arguments is undefined/empty
|
|
580
|
+
// (some providers omit arguments for tools with no parameters)
|
|
581
|
+
input: functionCallItem.arguments || "{}",
|
|
582
|
+
...reasoningMetadata && { providerMetadata: reasoningMetadata }
|
|
1367
583
|
});
|
|
1368
|
-
break;
|
|
1369
|
-
}
|
|
1370
|
-
case "tool": {
|
|
1371
|
-
for (const toolResponse of content) {
|
|
1372
|
-
const content2 = getToolResultContent(toolResponse);
|
|
1373
|
-
messages.push({
|
|
1374
|
-
role: "tool",
|
|
1375
|
-
tool_call_id: toolResponse.toolCallId,
|
|
1376
|
-
content: content2,
|
|
1377
|
-
cache_control: (_j = getCacheControl(providerOptions)) != null ? _j : getCacheControl(toolResponse.providerOptions)
|
|
1378
|
-
});
|
|
1379
|
-
}
|
|
1380
|
-
break;
|
|
1381
584
|
}
|
|
1382
|
-
default: {
|
|
1383
|
-
break;
|
|
1384
|
-
}
|
|
1385
|
-
}
|
|
1386
|
-
}
|
|
1387
|
-
return messages;
|
|
1388
|
-
}
|
|
1389
|
-
function getToolResultContent(input) {
|
|
1390
|
-
return input.output.type === "text" ? input.output.value : JSON.stringify(input.output.value);
|
|
1391
|
-
}
|
|
1392
|
-
|
|
1393
|
-
// src/chat/get-tool-choice.ts
|
|
1394
|
-
var import_v44 = require("zod/v4");
|
|
1395
|
-
var ChatCompletionToolChoiceSchema = import_v44.z.union([
|
|
1396
|
-
import_v44.z.literal("auto"),
|
|
1397
|
-
import_v44.z.literal("none"),
|
|
1398
|
-
import_v44.z.literal("required"),
|
|
1399
|
-
import_v44.z.object({
|
|
1400
|
-
type: import_v44.z.literal("function"),
|
|
1401
|
-
function: import_v44.z.object({
|
|
1402
|
-
name: import_v44.z.string()
|
|
1403
|
-
})
|
|
1404
|
-
})
|
|
1405
|
-
]);
|
|
1406
|
-
function getChatCompletionToolChoice(toolChoice) {
|
|
1407
|
-
switch (toolChoice.type) {
|
|
1408
|
-
case "auto":
|
|
1409
|
-
case "none":
|
|
1410
|
-
case "required":
|
|
1411
|
-
return toolChoice.type;
|
|
1412
|
-
case "tool": {
|
|
1413
|
-
return {
|
|
1414
|
-
type: "function",
|
|
1415
|
-
function: { name: toolChoice.toolName }
|
|
1416
|
-
};
|
|
1417
585
|
}
|
|
1418
|
-
|
|
1419
|
-
toolChoice;
|
|
1420
|
-
throw new InvalidArgumentError({
|
|
1421
|
-
argument: "toolChoice",
|
|
1422
|
-
message: `Invalid tool choice type: ${JSON.stringify(toolChoice)}`
|
|
1423
|
-
});
|
|
1424
|
-
}
|
|
1425
|
-
}
|
|
1426
|
-
}
|
|
1427
|
-
|
|
1428
|
-
// src/chat/schemas.ts
|
|
1429
|
-
var import_v46 = require("zod/v4");
|
|
1430
|
-
|
|
1431
|
-
// src/schemas/image.ts
|
|
1432
|
-
var import_v45 = require("zod/v4");
|
|
1433
|
-
var ImageResponseSchema = import_v45.z.object({
|
|
1434
|
-
type: import_v45.z.literal("image_url"),
|
|
1435
|
-
image_url: import_v45.z.object({
|
|
1436
|
-
url: import_v45.z.string()
|
|
1437
|
-
}).passthrough()
|
|
1438
|
-
}).passthrough();
|
|
1439
|
-
var ImageResponseWithUnknownSchema = import_v45.z.union([
|
|
1440
|
-
ImageResponseSchema,
|
|
1441
|
-
import_v45.z.unknown().transform(() => null)
|
|
1442
|
-
]);
|
|
1443
|
-
var ImageResponseArraySchema = import_v45.z.array(ImageResponseWithUnknownSchema).transform((d) => d.filter((d2) => !!d2));
|
|
1444
|
-
|
|
1445
|
-
// src/chat/schemas.ts
|
|
1446
|
-
var OpenRouterChatCompletionBaseResponseSchema = import_v46.z.object({
|
|
1447
|
-
id: import_v46.z.string().optional(),
|
|
1448
|
-
model: import_v46.z.string().optional(),
|
|
1449
|
-
provider: import_v46.z.string().optional(),
|
|
1450
|
-
usage: import_v46.z.object({
|
|
1451
|
-
prompt_tokens: import_v46.z.number(),
|
|
1452
|
-
prompt_tokens_details: import_v46.z.object({
|
|
1453
|
-
cached_tokens: import_v46.z.number()
|
|
1454
|
-
}).passthrough().nullish(),
|
|
1455
|
-
completion_tokens: import_v46.z.number(),
|
|
1456
|
-
completion_tokens_details: import_v46.z.object({
|
|
1457
|
-
reasoning_tokens: import_v46.z.number()
|
|
1458
|
-
}).passthrough().nullish(),
|
|
1459
|
-
total_tokens: import_v46.z.number(),
|
|
1460
|
-
cost: import_v46.z.number().optional(),
|
|
1461
|
-
cost_details: import_v46.z.object({
|
|
1462
|
-
upstream_inference_cost: import_v46.z.number().nullish()
|
|
1463
|
-
}).passthrough().nullish()
|
|
1464
|
-
}).passthrough().nullish()
|
|
1465
|
-
}).passthrough();
|
|
1466
|
-
var OpenRouterNonStreamChatCompletionResponseSchema = import_v46.z.union([
|
|
1467
|
-
// Success response with choices
|
|
1468
|
-
OpenRouterChatCompletionBaseResponseSchema.extend({
|
|
1469
|
-
choices: import_v46.z.array(
|
|
1470
|
-
import_v46.z.object({
|
|
1471
|
-
message: import_v46.z.object({
|
|
1472
|
-
role: import_v46.z.literal("assistant"),
|
|
1473
|
-
content: import_v46.z.string().nullable().optional(),
|
|
1474
|
-
reasoning: import_v46.z.string().nullable().optional(),
|
|
1475
|
-
reasoning_details: ReasoningDetailArraySchema.nullish(),
|
|
1476
|
-
images: ImageResponseArraySchema.nullish(),
|
|
1477
|
-
tool_calls: import_v46.z.array(
|
|
1478
|
-
import_v46.z.object({
|
|
1479
|
-
id: import_v46.z.string().optional().nullable(),
|
|
1480
|
-
type: import_v46.z.literal("function"),
|
|
1481
|
-
function: import_v46.z.object({
|
|
1482
|
-
name: import_v46.z.string(),
|
|
1483
|
-
arguments: import_v46.z.string()
|
|
1484
|
-
}).passthrough()
|
|
1485
|
-
}).passthrough()
|
|
1486
|
-
).optional(),
|
|
1487
|
-
annotations: import_v46.z.array(
|
|
1488
|
-
import_v46.z.union([
|
|
1489
|
-
// URL citation from web search
|
|
1490
|
-
import_v46.z.object({
|
|
1491
|
-
type: import_v46.z.literal("url_citation"),
|
|
1492
|
-
url_citation: import_v46.z.object({
|
|
1493
|
-
end_index: import_v46.z.number(),
|
|
1494
|
-
start_index: import_v46.z.number(),
|
|
1495
|
-
title: import_v46.z.string(),
|
|
1496
|
-
url: import_v46.z.string(),
|
|
1497
|
-
content: import_v46.z.string().optional()
|
|
1498
|
-
}).passthrough()
|
|
1499
|
-
}).passthrough(),
|
|
1500
|
-
// File annotation from FileParserPlugin (old format)
|
|
1501
|
-
import_v46.z.object({
|
|
1502
|
-
type: import_v46.z.literal("file_annotation"),
|
|
1503
|
-
file_annotation: import_v46.z.object({
|
|
1504
|
-
file_id: import_v46.z.string(),
|
|
1505
|
-
quote: import_v46.z.string().optional()
|
|
1506
|
-
}).passthrough()
|
|
1507
|
-
}).passthrough(),
|
|
1508
|
-
// File annotation from FileParserPlugin (new format)
|
|
1509
|
-
import_v46.z.object({
|
|
1510
|
-
type: import_v46.z.literal("file"),
|
|
1511
|
-
file: import_v46.z.object({
|
|
1512
|
-
hash: import_v46.z.string(),
|
|
1513
|
-
name: import_v46.z.string(),
|
|
1514
|
-
content: import_v46.z.array(
|
|
1515
|
-
import_v46.z.object({
|
|
1516
|
-
type: import_v46.z.string(),
|
|
1517
|
-
text: import_v46.z.string().optional()
|
|
1518
|
-
}).passthrough()
|
|
1519
|
-
).optional()
|
|
1520
|
-
}).passthrough()
|
|
1521
|
-
}).passthrough()
|
|
1522
|
-
])
|
|
1523
|
-
).nullish()
|
|
1524
|
-
}).passthrough(),
|
|
1525
|
-
index: import_v46.z.number().nullish(),
|
|
1526
|
-
logprobs: import_v46.z.object({
|
|
1527
|
-
content: import_v46.z.array(
|
|
1528
|
-
import_v46.z.object({
|
|
1529
|
-
token: import_v46.z.string(),
|
|
1530
|
-
logprob: import_v46.z.number(),
|
|
1531
|
-
top_logprobs: import_v46.z.array(
|
|
1532
|
-
import_v46.z.object({
|
|
1533
|
-
token: import_v46.z.string(),
|
|
1534
|
-
logprob: import_v46.z.number()
|
|
1535
|
-
}).passthrough()
|
|
1536
|
-
)
|
|
1537
|
-
}).passthrough()
|
|
1538
|
-
).nullable()
|
|
1539
|
-
}).passthrough().nullable().optional(),
|
|
1540
|
-
finish_reason: import_v46.z.string().optional().nullable()
|
|
1541
|
-
}).passthrough()
|
|
1542
|
-
)
|
|
1543
|
-
}),
|
|
1544
|
-
// Error response (HTTP 200 with error payload)
|
|
1545
|
-
OpenRouterErrorResponseSchema.extend({
|
|
1546
|
-
user_id: import_v46.z.string().optional()
|
|
1547
|
-
})
|
|
1548
|
-
]);
|
|
1549
|
-
var OpenRouterStreamChatCompletionChunkSchema = import_v46.z.union([
|
|
1550
|
-
OpenRouterChatCompletionBaseResponseSchema.extend({
|
|
1551
|
-
choices: import_v46.z.array(
|
|
1552
|
-
import_v46.z.object({
|
|
1553
|
-
delta: import_v46.z.object({
|
|
1554
|
-
role: import_v46.z.enum(["assistant"]).optional(),
|
|
1555
|
-
content: import_v46.z.string().nullish(),
|
|
1556
|
-
reasoning: import_v46.z.string().nullish().optional(),
|
|
1557
|
-
reasoning_details: ReasoningDetailArraySchema.nullish(),
|
|
1558
|
-
images: ImageResponseArraySchema.nullish(),
|
|
1559
|
-
tool_calls: import_v46.z.array(
|
|
1560
|
-
import_v46.z.object({
|
|
1561
|
-
index: import_v46.z.number().nullish(),
|
|
1562
|
-
id: import_v46.z.string().nullish(),
|
|
1563
|
-
type: import_v46.z.literal("function").optional(),
|
|
1564
|
-
function: import_v46.z.object({
|
|
1565
|
-
name: import_v46.z.string().nullish(),
|
|
1566
|
-
arguments: import_v46.z.string().nullish()
|
|
1567
|
-
}).passthrough()
|
|
1568
|
-
}).passthrough()
|
|
1569
|
-
).nullish(),
|
|
1570
|
-
annotations: import_v46.z.array(
|
|
1571
|
-
import_v46.z.union([
|
|
1572
|
-
// URL citation from web search
|
|
1573
|
-
import_v46.z.object({
|
|
1574
|
-
type: import_v46.z.literal("url_citation"),
|
|
1575
|
-
url_citation: import_v46.z.object({
|
|
1576
|
-
end_index: import_v46.z.number(),
|
|
1577
|
-
start_index: import_v46.z.number(),
|
|
1578
|
-
title: import_v46.z.string(),
|
|
1579
|
-
url: import_v46.z.string(),
|
|
1580
|
-
content: import_v46.z.string().optional()
|
|
1581
|
-
}).passthrough()
|
|
1582
|
-
}).passthrough(),
|
|
1583
|
-
// File annotation from FileParserPlugin (old format)
|
|
1584
|
-
import_v46.z.object({
|
|
1585
|
-
type: import_v46.z.literal("file_annotation"),
|
|
1586
|
-
file_annotation: import_v46.z.object({
|
|
1587
|
-
file_id: import_v46.z.string(),
|
|
1588
|
-
quote: import_v46.z.string().optional()
|
|
1589
|
-
}).passthrough()
|
|
1590
|
-
}).passthrough(),
|
|
1591
|
-
// File annotation from FileParserPlugin (new format)
|
|
1592
|
-
import_v46.z.object({
|
|
1593
|
-
type: import_v46.z.literal("file"),
|
|
1594
|
-
file: import_v46.z.object({
|
|
1595
|
-
hash: import_v46.z.string(),
|
|
1596
|
-
name: import_v46.z.string(),
|
|
1597
|
-
content: import_v46.z.array(
|
|
1598
|
-
import_v46.z.object({
|
|
1599
|
-
type: import_v46.z.string(),
|
|
1600
|
-
text: import_v46.z.string().optional()
|
|
1601
|
-
}).passthrough()
|
|
1602
|
-
).optional()
|
|
1603
|
-
}).passthrough()
|
|
1604
|
-
}).passthrough()
|
|
1605
|
-
])
|
|
1606
|
-
).nullish()
|
|
1607
|
-
}).passthrough().nullish(),
|
|
1608
|
-
logprobs: import_v46.z.object({
|
|
1609
|
-
content: import_v46.z.array(
|
|
1610
|
-
import_v46.z.object({
|
|
1611
|
-
token: import_v46.z.string(),
|
|
1612
|
-
logprob: import_v46.z.number(),
|
|
1613
|
-
top_logprobs: import_v46.z.array(
|
|
1614
|
-
import_v46.z.object({
|
|
1615
|
-
token: import_v46.z.string(),
|
|
1616
|
-
logprob: import_v46.z.number()
|
|
1617
|
-
}).passthrough()
|
|
1618
|
-
)
|
|
1619
|
-
}).passthrough()
|
|
1620
|
-
).nullable()
|
|
1621
|
-
}).passthrough().nullish(),
|
|
1622
|
-
finish_reason: import_v46.z.string().nullable().optional(),
|
|
1623
|
-
index: import_v46.z.number().nullish()
|
|
1624
|
-
}).passthrough()
|
|
1625
|
-
)
|
|
1626
|
-
}),
|
|
1627
|
-
OpenRouterErrorResponseSchema
|
|
1628
|
-
]);
|
|
1629
|
-
|
|
1630
|
-
// src/chat/index.ts
|
|
1631
|
-
var OpenRouterChatLanguageModel = class {
|
|
1632
|
-
constructor(modelId, settings, config) {
|
|
1633
|
-
this.specificationVersion = "v2";
|
|
1634
|
-
this.provider = "openrouter";
|
|
1635
|
-
this.defaultObjectGenerationMode = "tool";
|
|
1636
|
-
this.supportsImageUrls = true;
|
|
1637
|
-
this.supportedUrls = {
|
|
1638
|
-
"image/*": [
|
|
1639
|
-
/^data:image\/[a-zA-Z]+;base64,/,
|
|
1640
|
-
/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i
|
|
1641
|
-
],
|
|
1642
|
-
// 'text/*': [/^data:text\//, /^https?:\/\/.+$/],
|
|
1643
|
-
"application/*": [/^data:application\//, /^https?:\/\/.+$/]
|
|
1644
|
-
};
|
|
1645
|
-
this.modelId = modelId;
|
|
1646
|
-
this.settings = settings;
|
|
1647
|
-
this.config = config;
|
|
1648
|
-
}
|
|
1649
|
-
getArgs({
|
|
1650
|
-
prompt,
|
|
1651
|
-
maxOutputTokens,
|
|
1652
|
-
temperature,
|
|
1653
|
-
topP,
|
|
1654
|
-
frequencyPenalty,
|
|
1655
|
-
presencePenalty,
|
|
1656
|
-
seed,
|
|
1657
|
-
stopSequences,
|
|
1658
|
-
responseFormat,
|
|
1659
|
-
topK,
|
|
1660
|
-
tools,
|
|
1661
|
-
toolChoice
|
|
1662
|
-
}) {
|
|
1663
|
-
var _a15;
|
|
1664
|
-
const baseArgs = __spreadValues(__spreadValues({
|
|
1665
|
-
// model id:
|
|
1666
|
-
model: this.modelId,
|
|
1667
|
-
models: this.settings.models,
|
|
1668
|
-
// model specific settings:
|
|
1669
|
-
logit_bias: this.settings.logitBias,
|
|
1670
|
-
logprobs: this.settings.logprobs === true || typeof this.settings.logprobs === "number" ? true : void 0,
|
|
1671
|
-
top_logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
|
|
1672
|
-
user: this.settings.user,
|
|
1673
|
-
parallel_tool_calls: this.settings.parallelToolCalls,
|
|
1674
|
-
// standardized settings:
|
|
1675
|
-
max_tokens: maxOutputTokens,
|
|
1676
|
-
temperature,
|
|
1677
|
-
top_p: topP,
|
|
1678
|
-
frequency_penalty: frequencyPenalty,
|
|
1679
|
-
presence_penalty: presencePenalty,
|
|
1680
|
-
seed,
|
|
1681
|
-
stop: stopSequences,
|
|
1682
|
-
response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
|
|
1683
|
-
type: "json_schema",
|
|
1684
|
-
json_schema: __spreadValues({
|
|
1685
|
-
schema: responseFormat.schema,
|
|
1686
|
-
strict: true,
|
|
1687
|
-
name: (_a15 = responseFormat.name) != null ? _a15 : "response"
|
|
1688
|
-
}, responseFormat.description && {
|
|
1689
|
-
description: responseFormat.description
|
|
1690
|
-
})
|
|
1691
|
-
} : { type: "json_object" } : void 0,
|
|
1692
|
-
top_k: topK,
|
|
1693
|
-
// messages:
|
|
1694
|
-
messages: convertToOpenRouterChatMessages(prompt),
|
|
1695
|
-
// OpenRouter specific settings:
|
|
1696
|
-
include_reasoning: this.settings.includeReasoning,
|
|
1697
|
-
reasoning: this.settings.reasoning,
|
|
1698
|
-
usage: this.settings.usage,
|
|
1699
|
-
// Web search settings:
|
|
1700
|
-
plugins: this.settings.plugins,
|
|
1701
|
-
web_search_options: this.settings.web_search_options,
|
|
1702
|
-
// Provider routing settings:
|
|
1703
|
-
provider: this.settings.provider,
|
|
1704
|
-
// Debug settings:
|
|
1705
|
-
debug: this.settings.debug
|
|
1706
|
-
}, this.config.extraBody), this.settings.extraBody);
|
|
1707
|
-
if (tools && tools.length > 0) {
|
|
1708
|
-
const mappedTools = tools.filter(
|
|
1709
|
-
(tool) => tool.type === "function"
|
|
1710
|
-
).map((tool) => ({
|
|
1711
|
-
type: "function",
|
|
1712
|
-
function: {
|
|
1713
|
-
name: tool.name,
|
|
1714
|
-
description: tool.description,
|
|
1715
|
-
parameters: tool.inputSchema
|
|
1716
|
-
}
|
|
1717
|
-
}));
|
|
1718
|
-
return __spreadProps(__spreadValues({}, baseArgs), {
|
|
1719
|
-
tools: mappedTools,
|
|
1720
|
-
tool_choice: toolChoice ? getChatCompletionToolChoice(toolChoice) : void 0
|
|
1721
|
-
});
|
|
1722
|
-
}
|
|
1723
|
-
return baseArgs;
|
|
1724
|
-
}
|
|
1725
|
-
async doGenerate(options) {
|
|
1726
|
-
var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w;
|
|
1727
|
-
const providerOptions = options.providerOptions || {};
|
|
1728
|
-
const openrouterOptions = providerOptions.openrouter || {};
|
|
1729
|
-
const args = __spreadValues(__spreadValues({}, this.getArgs(options)), openrouterOptions);
|
|
1730
|
-
const { value: responseValue, responseHeaders } = await postJsonToApi({
|
|
1731
|
-
url: this.config.url({
|
|
1732
|
-
path: "/chat/completions",
|
|
1733
|
-
modelId: this.modelId
|
|
1734
|
-
}),
|
|
1735
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
1736
|
-
body: args,
|
|
1737
|
-
failedResponseHandler: openrouterFailedResponseHandler,
|
|
1738
|
-
successfulResponseHandler: createJsonResponseHandler(
|
|
1739
|
-
OpenRouterNonStreamChatCompletionResponseSchema
|
|
1740
|
-
),
|
|
1741
|
-
abortSignal: options.abortSignal,
|
|
1742
|
-
fetch: this.config.fetch
|
|
1743
|
-
});
|
|
1744
|
-
if ("error" in responseValue) {
|
|
1745
|
-
const errorData = responseValue.error;
|
|
1746
|
-
throw new APICallError({
|
|
1747
|
-
message: errorData.message,
|
|
1748
|
-
url: this.config.url({
|
|
1749
|
-
path: "/chat/completions",
|
|
1750
|
-
modelId: this.modelId
|
|
1751
|
-
}),
|
|
1752
|
-
requestBodyValues: args,
|
|
1753
|
-
statusCode: 200,
|
|
1754
|
-
responseHeaders,
|
|
1755
|
-
data: errorData
|
|
1756
|
-
});
|
|
1757
|
-
}
|
|
1758
|
-
const response = responseValue;
|
|
1759
|
-
const choice = response.choices[0];
|
|
1760
|
-
if (!choice) {
|
|
1761
|
-
throw new NoContentGeneratedError({
|
|
1762
|
-
message: "No choice in response"
|
|
1763
|
-
});
|
|
1764
|
-
}
|
|
1765
|
-
const usageInfo = response.usage ? {
|
|
1766
|
-
inputTokens: (_a15 = response.usage.prompt_tokens) != null ? _a15 : 0,
|
|
1767
|
-
outputTokens: (_b = response.usage.completion_tokens) != null ? _b : 0,
|
|
1768
|
-
totalTokens: ((_c = response.usage.prompt_tokens) != null ? _c : 0) + ((_d = response.usage.completion_tokens) != null ? _d : 0),
|
|
1769
|
-
reasoningTokens: (_f = (_e = response.usage.completion_tokens_details) == null ? void 0 : _e.reasoning_tokens) != null ? _f : 0,
|
|
1770
|
-
cachedInputTokens: (_h = (_g = response.usage.prompt_tokens_details) == null ? void 0 : _g.cached_tokens) != null ? _h : 0
|
|
1771
|
-
} : {
|
|
1772
|
-
inputTokens: 0,
|
|
1773
|
-
outputTokens: 0,
|
|
1774
|
-
totalTokens: 0,
|
|
1775
|
-
reasoningTokens: 0,
|
|
1776
|
-
cachedInputTokens: 0
|
|
1777
|
-
};
|
|
1778
|
-
const reasoningDetails = (_i = choice.message.reasoning_details) != null ? _i : [];
|
|
1779
|
-
const reasoning = reasoningDetails.length > 0 ? reasoningDetails.map((detail) => {
|
|
1780
|
-
switch (detail.type) {
|
|
1781
|
-
case "reasoning.text" /* Text */: {
|
|
1782
|
-
if (detail.text) {
|
|
1783
|
-
return {
|
|
1784
|
-
type: "reasoning",
|
|
1785
|
-
text: detail.text,
|
|
1786
|
-
providerMetadata: {
|
|
1787
|
-
openrouter: {
|
|
1788
|
-
reasoning_details: [detail]
|
|
1789
|
-
}
|
|
1790
|
-
}
|
|
1791
|
-
};
|
|
1792
|
-
}
|
|
1793
|
-
break;
|
|
1794
|
-
}
|
|
1795
|
-
case "reasoning.summary" /* Summary */: {
|
|
1796
|
-
if (detail.summary) {
|
|
1797
|
-
return {
|
|
1798
|
-
type: "reasoning",
|
|
1799
|
-
text: detail.summary,
|
|
1800
|
-
providerMetadata: {
|
|
1801
|
-
openrouter: {
|
|
1802
|
-
reasoning_details: [detail]
|
|
1803
|
-
}
|
|
1804
|
-
}
|
|
1805
|
-
};
|
|
1806
|
-
}
|
|
1807
|
-
break;
|
|
1808
|
-
}
|
|
1809
|
-
case "reasoning.encrypted" /* Encrypted */: {
|
|
1810
|
-
if (detail.data) {
|
|
1811
|
-
return {
|
|
1812
|
-
type: "reasoning",
|
|
1813
|
-
text: "[REDACTED]",
|
|
1814
|
-
providerMetadata: {
|
|
1815
|
-
openrouter: {
|
|
1816
|
-
reasoning_details: [detail]
|
|
1817
|
-
}
|
|
1818
|
-
}
|
|
1819
|
-
};
|
|
1820
|
-
}
|
|
1821
|
-
break;
|
|
1822
|
-
}
|
|
1823
|
-
default: {
|
|
1824
|
-
detail;
|
|
1825
|
-
}
|
|
1826
|
-
}
|
|
1827
|
-
return null;
|
|
1828
|
-
}).filter((p) => p !== null) : choice.message.reasoning ? [
|
|
1829
|
-
{
|
|
1830
|
-
type: "reasoning",
|
|
1831
|
-
text: choice.message.reasoning
|
|
1832
|
-
}
|
|
1833
|
-
] : [];
|
|
1834
|
-
const content = [];
|
|
1835
|
-
content.push(...reasoning);
|
|
1836
|
-
if (choice.message.content) {
|
|
586
|
+
if (response.outputText && !content.some((c) => c.type === "text")) {
|
|
1837
587
|
content.push({
|
|
1838
588
|
type: "text",
|
|
1839
|
-
text:
|
|
589
|
+
text: response.outputText
|
|
1840
590
|
});
|
|
1841
591
|
}
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
content.push({
|
|
1845
|
-
type: "tool-call",
|
|
1846
|
-
toolCallId: (_j = toolCall.id) != null ? _j : generateId(),
|
|
1847
|
-
toolName: toolCall.function.name,
|
|
1848
|
-
input: toolCall.function.arguments,
|
|
1849
|
-
providerMetadata: {
|
|
1850
|
-
openrouter: {
|
|
1851
|
-
reasoning_details: reasoningDetails
|
|
1852
|
-
}
|
|
1853
|
-
}
|
|
1854
|
-
});
|
|
1855
|
-
}
|
|
1856
|
-
}
|
|
1857
|
-
if (choice.message.images) {
|
|
1858
|
-
for (const image of choice.message.images) {
|
|
1859
|
-
content.push({
|
|
1860
|
-
type: "file",
|
|
1861
|
-
mediaType: getMediaType(image.image_url.url, "image/jpeg"),
|
|
1862
|
-
data: getBase64FromDataUrl(image.image_url.url)
|
|
1863
|
-
});
|
|
1864
|
-
}
|
|
1865
|
-
}
|
|
1866
|
-
if (choice.message.annotations) {
|
|
1867
|
-
for (const annotation of choice.message.annotations) {
|
|
1868
|
-
if (annotation.type === "url_citation") {
|
|
1869
|
-
content.push({
|
|
1870
|
-
type: "source",
|
|
1871
|
-
sourceType: "url",
|
|
1872
|
-
id: annotation.url_citation.url,
|
|
1873
|
-
url: annotation.url_citation.url,
|
|
1874
|
-
title: annotation.url_citation.title,
|
|
1875
|
-
providerMetadata: {
|
|
1876
|
-
openrouter: {
|
|
1877
|
-
content: annotation.url_citation.content || ""
|
|
1878
|
-
}
|
|
1879
|
-
}
|
|
1880
|
-
});
|
|
1881
|
-
}
|
|
1882
|
-
}
|
|
1883
|
-
}
|
|
1884
|
-
const fileAnnotations = (_k = choice.message.annotations) == null ? void 0 : _k.filter(
|
|
1885
|
-
(a) => a.type === "file"
|
|
592
|
+
let finishReason = mapOpenRouterFinishReason(
|
|
593
|
+
response.status === "completed" ? "stop" : response.status ?? "stop"
|
|
1886
594
|
);
|
|
1887
|
-
const hasToolCalls =
|
|
1888
|
-
|
|
1889
|
-
|
|
595
|
+
const hasToolCalls = content.some((c) => c.type === "tool-call");
|
|
596
|
+
if (hasToolCalls && hasEncryptedReasoning(reasoningDetails) && finishReason.unified === "stop") {
|
|
597
|
+
finishReason = { unified: "tool-calls", raw: finishReason.raw };
|
|
598
|
+
}
|
|
599
|
+
const usage = buildUsage(
|
|
600
|
+
response.usage ? {
|
|
601
|
+
inputTokens: response.usage.inputTokens,
|
|
602
|
+
outputTokens: response.usage.outputTokens
|
|
603
|
+
} : void 0
|
|
1890
604
|
);
|
|
1891
|
-
const
|
|
1892
|
-
|
|
605
|
+
const providerMetadata = buildProviderMetadata({
|
|
606
|
+
id: response.id,
|
|
607
|
+
provider: void 0,
|
|
608
|
+
// Responses API doesn't expose provider in response
|
|
609
|
+
usage: response.usage ? {
|
|
610
|
+
promptTokens: response.usage.inputTokens,
|
|
611
|
+
completionTokens: response.usage.outputTokens,
|
|
612
|
+
totalTokens: response.usage.totalTokens,
|
|
613
|
+
cost: response.usage.cost ?? void 0,
|
|
614
|
+
// Map inputTokensDetails -> promptTokensDetails
|
|
615
|
+
promptTokensDetails: response.usage.inputTokensDetails ? {
|
|
616
|
+
cachedTokens: response.usage.inputTokensDetails.cachedTokens
|
|
617
|
+
} : void 0,
|
|
618
|
+
// Map outputTokensDetails -> completionTokensDetails
|
|
619
|
+
completionTokensDetails: response.usage.outputTokensDetails ? {
|
|
620
|
+
reasoningTokens: response.usage.outputTokensDetails.reasoningTokens
|
|
621
|
+
} : void 0
|
|
622
|
+
} : void 0
|
|
623
|
+
});
|
|
1893
624
|
return {
|
|
1894
625
|
content,
|
|
1895
|
-
finishReason
|
|
1896
|
-
usage
|
|
1897
|
-
warnings
|
|
1898
|
-
providerMetadata
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
reasoning_details: (_m = choice.message.reasoning_details) != null ? _m : [],
|
|
1902
|
-
annotations: fileAnnotations && fileAnnotations.length > 0 ? fileAnnotations : void 0,
|
|
1903
|
-
usage: __spreadValues(__spreadValues(__spreadValues({
|
|
1904
|
-
promptTokens: (_n = usageInfo.inputTokens) != null ? _n : 0,
|
|
1905
|
-
completionTokens: (_o = usageInfo.outputTokens) != null ? _o : 0,
|
|
1906
|
-
totalTokens: (_p = usageInfo.totalTokens) != null ? _p : 0,
|
|
1907
|
-
cost: (_q = response.usage) == null ? void 0 : _q.cost
|
|
1908
|
-
}, ((_s = (_r = response.usage) == null ? void 0 : _r.prompt_tokens_details) == null ? void 0 : _s.cached_tokens) != null ? {
|
|
1909
|
-
promptTokensDetails: {
|
|
1910
|
-
cachedTokens: response.usage.prompt_tokens_details.cached_tokens
|
|
1911
|
-
}
|
|
1912
|
-
} : {}), ((_u = (_t = response.usage) == null ? void 0 : _t.completion_tokens_details) == null ? void 0 : _u.reasoning_tokens) != null ? {
|
|
1913
|
-
completionTokensDetails: {
|
|
1914
|
-
reasoningTokens: response.usage.completion_tokens_details.reasoning_tokens
|
|
1915
|
-
}
|
|
1916
|
-
} : {}), ((_w = (_v = response.usage) == null ? void 0 : _v.cost_details) == null ? void 0 : _w.upstream_inference_cost) != null ? {
|
|
1917
|
-
costDetails: {
|
|
1918
|
-
upstreamInferenceCost: response.usage.cost_details.upstream_inference_cost
|
|
1919
|
-
}
|
|
1920
|
-
} : {})
|
|
1921
|
-
})
|
|
626
|
+
finishReason,
|
|
627
|
+
usage,
|
|
628
|
+
warnings,
|
|
629
|
+
providerMetadata,
|
|
630
|
+
request: {
|
|
631
|
+
body: requestParams
|
|
1922
632
|
},
|
|
1923
|
-
request: { body: args },
|
|
1924
633
|
response: {
|
|
1925
634
|
id: response.id,
|
|
1926
|
-
|
|
1927
|
-
|
|
635
|
+
timestamp: new Date(response.createdAt * 1e3),
|
|
636
|
+
modelId: response.model
|
|
1928
637
|
}
|
|
1929
638
|
};
|
|
1930
639
|
}
|
|
1931
640
|
async doStream(options) {
|
|
1932
|
-
|
|
1933
|
-
const
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
const { value: response, responseHeaders } = await postJsonToApi({
|
|
1937
|
-
url: this.config.url({
|
|
1938
|
-
path: "/chat/completions",
|
|
1939
|
-
modelId: this.modelId
|
|
1940
|
-
}),
|
|
1941
|
-
headers: combineHeaders(this.config.headers(), options.headers),
|
|
1942
|
-
body: __spreadProps(__spreadValues({}, args), {
|
|
1943
|
-
stream: true,
|
|
1944
|
-
// only include stream_options when in strict compatibility mode:
|
|
1945
|
-
stream_options: this.config.compatibility === "strict" ? __spreadValues({
|
|
1946
|
-
include_usage: true
|
|
1947
|
-
}, ((_a15 = this.settings.usage) == null ? void 0 : _a15.include) ? { include_usage: true } : {}) : void 0
|
|
1948
|
-
}),
|
|
1949
|
-
failedResponseHandler: openrouterFailedResponseHandler,
|
|
1950
|
-
successfulResponseHandler: createEventSourceResponseHandler(
|
|
1951
|
-
OpenRouterStreamChatCompletionChunkSchema
|
|
1952
|
-
),
|
|
1953
|
-
abortSignal: options.abortSignal,
|
|
1954
|
-
fetch: this.config.fetch
|
|
641
|
+
const warnings = [];
|
|
642
|
+
const client = new import_sdk.OpenRouter({
|
|
643
|
+
apiKey: this.settings.apiKey,
|
|
644
|
+
serverURL: this.settings.baseURL
|
|
1955
645
|
});
|
|
1956
|
-
const
|
|
1957
|
-
|
|
1958
|
-
const
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
646
|
+
const openRouterInput = convertToOpenRouterMessages(options.prompt);
|
|
647
|
+
const tools = convertToolsToResponsesFormat(options.tools, warnings);
|
|
648
|
+
const toolChoice = convertToolChoiceToResponsesFormat(options.toolChoice);
|
|
649
|
+
const text = convertResponseFormatToText(options.responseFormat);
|
|
650
|
+
const requestParams = {
|
|
651
|
+
model: this.modelId,
|
|
652
|
+
input: openRouterInput,
|
|
653
|
+
stream: true,
|
|
654
|
+
...options.maxOutputTokens !== void 0 && {
|
|
655
|
+
maxOutputTokens: options.maxOutputTokens
|
|
656
|
+
},
|
|
657
|
+
...options.temperature !== void 0 && {
|
|
658
|
+
temperature: options.temperature
|
|
659
|
+
},
|
|
660
|
+
...options.topP !== void 0 && { topP: options.topP },
|
|
661
|
+
...tools.length > 0 && { tools },
|
|
662
|
+
...toolChoice !== void 0 && { toolChoice },
|
|
663
|
+
...text !== void 0 && { text }
|
|
1964
664
|
};
|
|
1965
|
-
const
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
const
|
|
1985
|
-
|
|
1986
|
-
finishReason = "error";
|
|
1987
|
-
controller.enqueue({ type: "error", error: value.error });
|
|
1988
|
-
return;
|
|
1989
|
-
}
|
|
1990
|
-
if (value.provider) {
|
|
1991
|
-
provider = value.provider;
|
|
1992
|
-
}
|
|
1993
|
-
if (value.id) {
|
|
1994
|
-
openrouterResponseId = value.id;
|
|
1995
|
-
controller.enqueue({
|
|
1996
|
-
type: "response-metadata",
|
|
1997
|
-
id: value.id
|
|
1998
|
-
});
|
|
1999
|
-
}
|
|
2000
|
-
if (value.model) {
|
|
2001
|
-
controller.enqueue({
|
|
2002
|
-
type: "response-metadata",
|
|
2003
|
-
modelId: value.model
|
|
2004
|
-
});
|
|
2005
|
-
}
|
|
2006
|
-
if (value.usage != null) {
|
|
2007
|
-
usage.inputTokens = value.usage.prompt_tokens;
|
|
2008
|
-
usage.outputTokens = value.usage.completion_tokens;
|
|
2009
|
-
usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
|
|
2010
|
-
openrouterUsage.promptTokens = value.usage.prompt_tokens;
|
|
2011
|
-
if (value.usage.prompt_tokens_details) {
|
|
2012
|
-
const cachedInputTokens = (_a16 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a16 : 0;
|
|
2013
|
-
usage.cachedInputTokens = cachedInputTokens;
|
|
2014
|
-
openrouterUsage.promptTokensDetails = {
|
|
2015
|
-
cachedTokens: cachedInputTokens
|
|
2016
|
-
};
|
|
2017
|
-
}
|
|
2018
|
-
openrouterUsage.completionTokens = value.usage.completion_tokens;
|
|
2019
|
-
if (value.usage.completion_tokens_details) {
|
|
2020
|
-
const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
|
|
2021
|
-
usage.reasoningTokens = reasoningTokens;
|
|
2022
|
-
openrouterUsage.completionTokensDetails = {
|
|
2023
|
-
reasoningTokens
|
|
2024
|
-
};
|
|
2025
|
-
}
|
|
2026
|
-
openrouterUsage.cost = value.usage.cost;
|
|
2027
|
-
openrouterUsage.totalTokens = value.usage.total_tokens;
|
|
2028
|
-
const upstreamInferenceCost = (_c = value.usage.cost_details) == null ? void 0 : _c.upstream_inference_cost;
|
|
2029
|
-
if (upstreamInferenceCost != null) {
|
|
2030
|
-
openrouterUsage.costDetails = {
|
|
2031
|
-
upstreamInferenceCost
|
|
2032
|
-
};
|
|
2033
|
-
}
|
|
2034
|
-
}
|
|
2035
|
-
const choice = value.choices[0];
|
|
2036
|
-
if ((choice == null ? void 0 : choice.finish_reason) != null) {
|
|
2037
|
-
finishReason = mapOpenRouterFinishReason(choice.finish_reason);
|
|
2038
|
-
}
|
|
2039
|
-
if ((choice == null ? void 0 : choice.delta) == null) {
|
|
2040
|
-
return;
|
|
2041
|
-
}
|
|
2042
|
-
const delta = choice.delta;
|
|
2043
|
-
const emitReasoningChunk = (chunkText, providerMetadata) => {
|
|
2044
|
-
if (!reasoningStarted) {
|
|
2045
|
-
reasoningId = openrouterResponseId || generateId();
|
|
2046
|
-
controller.enqueue({
|
|
2047
|
-
providerMetadata,
|
|
2048
|
-
type: "reasoning-start",
|
|
2049
|
-
id: reasoningId
|
|
2050
|
-
});
|
|
2051
|
-
reasoningStarted = true;
|
|
2052
|
-
}
|
|
2053
|
-
controller.enqueue({
|
|
2054
|
-
providerMetadata,
|
|
2055
|
-
type: "reasoning-delta",
|
|
2056
|
-
delta: chunkText,
|
|
2057
|
-
id: reasoningId || generateId()
|
|
2058
|
-
});
|
|
2059
|
-
};
|
|
2060
|
-
if (delta.reasoning_details && delta.reasoning_details.length > 0) {
|
|
2061
|
-
for (const detail of delta.reasoning_details) {
|
|
2062
|
-
if (detail.type === "reasoning.text" /* Text */) {
|
|
2063
|
-
const lastDetail = accumulatedReasoningDetails[accumulatedReasoningDetails.length - 1];
|
|
2064
|
-
if ((lastDetail == null ? void 0 : lastDetail.type) === "reasoning.text" /* Text */) {
|
|
2065
|
-
lastDetail.text = (lastDetail.text || "") + (detail.text || "");
|
|
2066
|
-
lastDetail.signature = lastDetail.signature || detail.signature;
|
|
2067
|
-
lastDetail.format = lastDetail.format || detail.format;
|
|
2068
|
-
} else {
|
|
2069
|
-
accumulatedReasoningDetails.push(__spreadValues({}, detail));
|
|
2070
|
-
}
|
|
2071
|
-
} else {
|
|
2072
|
-
accumulatedReasoningDetails.push(detail);
|
|
2073
|
-
}
|
|
2074
|
-
}
|
|
2075
|
-
const reasoningMetadata = {
|
|
2076
|
-
openrouter: {
|
|
2077
|
-
reasoning_details: delta.reasoning_details
|
|
2078
|
-
}
|
|
2079
|
-
};
|
|
2080
|
-
for (const detail of delta.reasoning_details) {
|
|
2081
|
-
switch (detail.type) {
|
|
2082
|
-
case "reasoning.text" /* Text */: {
|
|
2083
|
-
if (detail.text) {
|
|
2084
|
-
emitReasoningChunk(detail.text, reasoningMetadata);
|
|
2085
|
-
}
|
|
2086
|
-
break;
|
|
2087
|
-
}
|
|
2088
|
-
case "reasoning.encrypted" /* Encrypted */: {
|
|
2089
|
-
if (detail.data) {
|
|
2090
|
-
emitReasoningChunk("[REDACTED]", reasoningMetadata);
|
|
2091
|
-
}
|
|
2092
|
-
break;
|
|
2093
|
-
}
|
|
2094
|
-
case "reasoning.summary" /* Summary */: {
|
|
2095
|
-
if (detail.summary) {
|
|
2096
|
-
emitReasoningChunk(detail.summary, reasoningMetadata);
|
|
2097
|
-
}
|
|
2098
|
-
break;
|
|
2099
|
-
}
|
|
2100
|
-
default: {
|
|
2101
|
-
detail;
|
|
2102
|
-
break;
|
|
2103
|
-
}
|
|
2104
|
-
}
|
|
2105
|
-
}
|
|
2106
|
-
} else if (delta.reasoning) {
|
|
2107
|
-
emitReasoningChunk(delta.reasoning);
|
|
2108
|
-
}
|
|
2109
|
-
if (delta.content) {
|
|
2110
|
-
if (reasoningStarted && !textStarted) {
|
|
2111
|
-
controller.enqueue({
|
|
2112
|
-
type: "reasoning-end",
|
|
2113
|
-
id: reasoningId || generateId()
|
|
2114
|
-
});
|
|
2115
|
-
reasoningStarted = false;
|
|
2116
|
-
}
|
|
2117
|
-
if (!textStarted) {
|
|
2118
|
-
textId = openrouterResponseId || generateId();
|
|
2119
|
-
controller.enqueue({
|
|
2120
|
-
type: "text-start",
|
|
2121
|
-
id: textId
|
|
2122
|
-
});
|
|
2123
|
-
textStarted = true;
|
|
2124
|
-
}
|
|
2125
|
-
controller.enqueue({
|
|
2126
|
-
type: "text-delta",
|
|
2127
|
-
delta: delta.content,
|
|
2128
|
-
id: textId || generateId()
|
|
2129
|
-
});
|
|
2130
|
-
}
|
|
2131
|
-
if (delta.annotations) {
|
|
2132
|
-
for (const annotation of delta.annotations) {
|
|
2133
|
-
if (annotation.type === "url_citation") {
|
|
2134
|
-
controller.enqueue({
|
|
2135
|
-
type: "source",
|
|
2136
|
-
sourceType: "url",
|
|
2137
|
-
id: annotation.url_citation.url,
|
|
2138
|
-
url: annotation.url_citation.url,
|
|
2139
|
-
title: annotation.url_citation.title,
|
|
2140
|
-
providerMetadata: {
|
|
2141
|
-
openrouter: {
|
|
2142
|
-
content: annotation.url_citation.content || ""
|
|
2143
|
-
}
|
|
2144
|
-
}
|
|
2145
|
-
});
|
|
2146
|
-
} else if (annotation.type === "file") {
|
|
2147
|
-
const file = annotation.file;
|
|
2148
|
-
if (file && typeof file === "object" && "hash" in file && "name" in file) {
|
|
2149
|
-
accumulatedFileAnnotations.push(
|
|
2150
|
-
annotation
|
|
2151
|
-
);
|
|
2152
|
-
}
|
|
2153
|
-
}
|
|
2154
|
-
}
|
|
2155
|
-
}
|
|
2156
|
-
if (delta.tool_calls != null) {
|
|
2157
|
-
for (const toolCallDelta of delta.tool_calls) {
|
|
2158
|
-
const index = (_d = toolCallDelta.index) != null ? _d : toolCalls.length - 1;
|
|
2159
|
-
if (toolCalls[index] == null) {
|
|
2160
|
-
if (toolCallDelta.type !== "function") {
|
|
2161
|
-
throw new InvalidResponseDataError({
|
|
2162
|
-
data: toolCallDelta,
|
|
2163
|
-
message: `Expected 'function' type.`
|
|
2164
|
-
});
|
|
2165
|
-
}
|
|
2166
|
-
if (toolCallDelta.id == null) {
|
|
2167
|
-
throw new InvalidResponseDataError({
|
|
2168
|
-
data: toolCallDelta,
|
|
2169
|
-
message: `Expected 'id' to be a string.`
|
|
2170
|
-
});
|
|
2171
|
-
}
|
|
2172
|
-
if (((_e = toolCallDelta.function) == null ? void 0 : _e.name) == null) {
|
|
2173
|
-
throw new InvalidResponseDataError({
|
|
2174
|
-
data: toolCallDelta,
|
|
2175
|
-
message: `Expected 'function.name' to be a string.`
|
|
2176
|
-
});
|
|
2177
|
-
}
|
|
2178
|
-
toolCalls[index] = {
|
|
2179
|
-
id: toolCallDelta.id,
|
|
2180
|
-
type: "function",
|
|
2181
|
-
function: {
|
|
2182
|
-
name: toolCallDelta.function.name,
|
|
2183
|
-
arguments: (_f = toolCallDelta.function.arguments) != null ? _f : ""
|
|
2184
|
-
},
|
|
2185
|
-
inputStarted: false,
|
|
2186
|
-
sent: false
|
|
2187
|
-
};
|
|
2188
|
-
const toolCall2 = toolCalls[index];
|
|
2189
|
-
if (toolCall2 == null) {
|
|
2190
|
-
throw new InvalidResponseDataError({
|
|
2191
|
-
data: { index, toolCallsLength: toolCalls.length },
|
|
2192
|
-
message: `Tool call at index ${index} is missing after creation.`
|
|
2193
|
-
});
|
|
2194
|
-
}
|
|
2195
|
-
if (((_g = toolCall2.function) == null ? void 0 : _g.name) != null && ((_h = toolCall2.function) == null ? void 0 : _h.arguments) != null && isParsableJson(toolCall2.function.arguments)) {
|
|
2196
|
-
toolCall2.inputStarted = true;
|
|
2197
|
-
controller.enqueue({
|
|
2198
|
-
type: "tool-input-start",
|
|
2199
|
-
id: toolCall2.id,
|
|
2200
|
-
toolName: toolCall2.function.name
|
|
2201
|
-
});
|
|
2202
|
-
controller.enqueue({
|
|
2203
|
-
type: "tool-input-delta",
|
|
2204
|
-
id: toolCall2.id,
|
|
2205
|
-
delta: toolCall2.function.arguments
|
|
2206
|
-
});
|
|
2207
|
-
controller.enqueue({
|
|
2208
|
-
type: "tool-input-end",
|
|
2209
|
-
id: toolCall2.id
|
|
2210
|
-
});
|
|
2211
|
-
controller.enqueue({
|
|
2212
|
-
type: "tool-call",
|
|
2213
|
-
toolCallId: toolCall2.id,
|
|
2214
|
-
toolName: toolCall2.function.name,
|
|
2215
|
-
input: toolCall2.function.arguments,
|
|
2216
|
-
providerMetadata: {
|
|
2217
|
-
openrouter: {
|
|
2218
|
-
reasoning_details: accumulatedReasoningDetails
|
|
2219
|
-
}
|
|
2220
|
-
}
|
|
2221
|
-
});
|
|
2222
|
-
toolCall2.sent = true;
|
|
2223
|
-
}
|
|
2224
|
-
continue;
|
|
2225
|
-
}
|
|
2226
|
-
const toolCall = toolCalls[index];
|
|
2227
|
-
if (toolCall == null) {
|
|
2228
|
-
throw new InvalidResponseDataError({
|
|
2229
|
-
data: {
|
|
2230
|
-
index,
|
|
2231
|
-
toolCallsLength: toolCalls.length,
|
|
2232
|
-
toolCallDelta
|
|
2233
|
-
},
|
|
2234
|
-
message: `Tool call at index ${index} is missing during merge.`
|
|
2235
|
-
});
|
|
2236
|
-
}
|
|
2237
|
-
if (!toolCall.inputStarted) {
|
|
2238
|
-
toolCall.inputStarted = true;
|
|
2239
|
-
controller.enqueue({
|
|
2240
|
-
type: "tool-input-start",
|
|
2241
|
-
id: toolCall.id,
|
|
2242
|
-
toolName: toolCall.function.name
|
|
2243
|
-
});
|
|
2244
|
-
}
|
|
2245
|
-
if (((_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null) {
|
|
2246
|
-
toolCall.function.arguments += (_k = (_j = toolCallDelta.function) == null ? void 0 : _j.arguments) != null ? _k : "";
|
|
2247
|
-
}
|
|
2248
|
-
controller.enqueue({
|
|
2249
|
-
type: "tool-input-delta",
|
|
2250
|
-
id: toolCall.id,
|
|
2251
|
-
delta: (_l = toolCallDelta.function.arguments) != null ? _l : ""
|
|
2252
|
-
});
|
|
2253
|
-
if (((_m = toolCall.function) == null ? void 0 : _m.name) != null && ((_n = toolCall.function) == null ? void 0 : _n.arguments) != null && isParsableJson(toolCall.function.arguments)) {
|
|
2254
|
-
controller.enqueue({
|
|
2255
|
-
type: "tool-call",
|
|
2256
|
-
toolCallId: (_o = toolCall.id) != null ? _o : generateId(),
|
|
2257
|
-
toolName: toolCall.function.name,
|
|
2258
|
-
input: toolCall.function.arguments,
|
|
2259
|
-
providerMetadata: {
|
|
2260
|
-
openrouter: {
|
|
2261
|
-
reasoning_details: accumulatedReasoningDetails
|
|
2262
|
-
}
|
|
2263
|
-
}
|
|
2264
|
-
});
|
|
2265
|
-
toolCall.sent = true;
|
|
2266
|
-
}
|
|
2267
|
-
}
|
|
2268
|
-
}
|
|
2269
|
-
if (delta.images != null) {
|
|
2270
|
-
for (const image of delta.images) {
|
|
2271
|
-
controller.enqueue({
|
|
2272
|
-
type: "file",
|
|
2273
|
-
mediaType: getMediaType(image.image_url.url, "image/jpeg"),
|
|
2274
|
-
data: getBase64FromDataUrl(image.image_url.url)
|
|
2275
|
-
});
|
|
2276
|
-
}
|
|
2277
|
-
}
|
|
2278
|
-
},
|
|
2279
|
-
flush(controller) {
|
|
2280
|
-
var _a16;
|
|
2281
|
-
const hasToolCalls = toolCalls.length > 0;
|
|
2282
|
-
const hasEncryptedReasoning = accumulatedReasoningDetails.some(
|
|
2283
|
-
(d) => d.type === "reasoning.encrypted" /* Encrypted */ && d.data
|
|
2284
|
-
);
|
|
2285
|
-
if (hasToolCalls && hasEncryptedReasoning && finishReason === "stop") {
|
|
2286
|
-
finishReason = "tool-calls";
|
|
2287
|
-
}
|
|
2288
|
-
if (finishReason === "tool-calls") {
|
|
2289
|
-
for (const toolCall of toolCalls) {
|
|
2290
|
-
if (toolCall && !toolCall.sent) {
|
|
2291
|
-
controller.enqueue({
|
|
2292
|
-
type: "tool-call",
|
|
2293
|
-
toolCallId: (_a16 = toolCall.id) != null ? _a16 : generateId(),
|
|
2294
|
-
toolName: toolCall.function.name,
|
|
2295
|
-
// Coerce invalid arguments to an empty JSON object
|
|
2296
|
-
input: isParsableJson(toolCall.function.arguments) ? toolCall.function.arguments : "{}",
|
|
2297
|
-
providerMetadata: {
|
|
2298
|
-
openrouter: {
|
|
2299
|
-
reasoning_details: accumulatedReasoningDetails
|
|
2300
|
-
}
|
|
2301
|
-
}
|
|
2302
|
-
});
|
|
2303
|
-
toolCall.sent = true;
|
|
2304
|
-
}
|
|
2305
|
-
}
|
|
2306
|
-
}
|
|
2307
|
-
if (reasoningStarted) {
|
|
2308
|
-
controller.enqueue({
|
|
2309
|
-
type: "reasoning-end",
|
|
2310
|
-
id: reasoningId || generateId()
|
|
2311
|
-
});
|
|
2312
|
-
}
|
|
2313
|
-
if (textStarted) {
|
|
2314
|
-
controller.enqueue({
|
|
2315
|
-
type: "text-end",
|
|
2316
|
-
id: textId || generateId()
|
|
2317
|
-
});
|
|
2318
|
-
}
|
|
2319
|
-
const openrouterMetadata = {
|
|
2320
|
-
usage: openrouterUsage
|
|
2321
|
-
};
|
|
2322
|
-
if (provider !== void 0) {
|
|
2323
|
-
openrouterMetadata.provider = provider;
|
|
2324
|
-
}
|
|
2325
|
-
if (accumulatedReasoningDetails.length > 0) {
|
|
2326
|
-
openrouterMetadata.reasoning_details = accumulatedReasoningDetails;
|
|
2327
|
-
}
|
|
2328
|
-
if (accumulatedFileAnnotations.length > 0) {
|
|
2329
|
-
openrouterMetadata.annotations = accumulatedFileAnnotations;
|
|
665
|
+
const combinedHeaders = (0, import_provider_utils.normalizeHeaders)(
|
|
666
|
+
(0, import_provider_utils.combineHeaders)(this.settings.headers, options.headers)
|
|
667
|
+
);
|
|
668
|
+
const eventStream = await client.beta.responses.send(requestParams, {
|
|
669
|
+
fetchOptions: {
|
|
670
|
+
signal: options.abortSignal,
|
|
671
|
+
headers: combinedHeaders
|
|
672
|
+
}
|
|
673
|
+
});
|
|
674
|
+
const state = createStreamState();
|
|
675
|
+
const transformedStream = new ReadableStream({
|
|
676
|
+
async start(controller) {
|
|
677
|
+
controller.enqueue({
|
|
678
|
+
type: "stream-start",
|
|
679
|
+
warnings
|
|
680
|
+
});
|
|
681
|
+
try {
|
|
682
|
+
for await (const event of eventStream) {
|
|
683
|
+
const parts = transformResponsesEvent(event, state);
|
|
684
|
+
for (const part of parts) {
|
|
685
|
+
controller.enqueue(part);
|
|
2330
686
|
}
|
|
2331
|
-
controller.enqueue({
|
|
2332
|
-
type: "finish",
|
|
2333
|
-
finishReason,
|
|
2334
|
-
usage,
|
|
2335
|
-
providerMetadata: {
|
|
2336
|
-
openrouter: openrouterMetadata
|
|
2337
|
-
}
|
|
2338
|
-
});
|
|
2339
687
|
}
|
|
2340
|
-
})
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
688
|
+
} catch (error) {
|
|
689
|
+
controller.enqueue({
|
|
690
|
+
type: "error",
|
|
691
|
+
error
|
|
692
|
+
});
|
|
693
|
+
} finally {
|
|
694
|
+
controller.close();
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
});
|
|
698
|
+
return {
|
|
699
|
+
stream: transformedStream,
|
|
700
|
+
request: {
|
|
701
|
+
body: requestParams
|
|
702
|
+
}
|
|
2345
703
|
};
|
|
2346
704
|
}
|
|
2347
705
|
};
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
706
|
+
function createStreamState() {
|
|
707
|
+
return {
|
|
708
|
+
responseId: void 0,
|
|
709
|
+
responseModel: void 0,
|
|
710
|
+
responseCreated: void 0,
|
|
711
|
+
textStarted: false,
|
|
712
|
+
textId: "text-0",
|
|
713
|
+
reasoningStarted: false,
|
|
714
|
+
reasoningId: "reasoning-0",
|
|
715
|
+
textEnded: false,
|
|
716
|
+
reasoningEnded: false,
|
|
717
|
+
sourceIds: [],
|
|
718
|
+
toolCalls: /* @__PURE__ */ new Map()
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
function transformResponsesEvent(event, state) {
|
|
722
|
+
const parts = [];
|
|
723
|
+
switch (event.type) {
|
|
724
|
+
// Response lifecycle events
|
|
725
|
+
case "response.created":
|
|
726
|
+
case "response.in_progress": {
|
|
727
|
+
if (event.response) {
|
|
728
|
+
state.responseId = event.response.id;
|
|
729
|
+
state.responseModel = event.response.model;
|
|
730
|
+
state.responseCreated = event.response.createdAt;
|
|
731
|
+
}
|
|
732
|
+
break;
|
|
733
|
+
}
|
|
734
|
+
// Text streaming
|
|
735
|
+
case "response.output_text.delta": {
|
|
736
|
+
if (!state.textStarted) {
|
|
737
|
+
state.textStarted = true;
|
|
738
|
+
parts.push({
|
|
739
|
+
type: "text-start",
|
|
740
|
+
id: state.textId
|
|
2372
741
|
});
|
|
2373
742
|
}
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
case "file": {
|
|
2381
|
-
throw new UnsupportedFunctionalityError({
|
|
2382
|
-
functionality: "file attachments"
|
|
2383
|
-
});
|
|
2384
|
-
}
|
|
2385
|
-
default: {
|
|
2386
|
-
return "";
|
|
2387
|
-
}
|
|
2388
|
-
}
|
|
2389
|
-
}).join("");
|
|
2390
|
-
text += `${user}:
|
|
2391
|
-
${userMessage}
|
|
2392
|
-
|
|
2393
|
-
`;
|
|
2394
|
-
break;
|
|
743
|
+
if (event.delta && event.delta.length > 0) {
|
|
744
|
+
parts.push({
|
|
745
|
+
type: "text-delta",
|
|
746
|
+
id: state.textId,
|
|
747
|
+
delta: event.delta
|
|
748
|
+
});
|
|
2395
749
|
}
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
functionality: "tool-call messages"
|
|
2406
|
-
});
|
|
2407
|
-
}
|
|
2408
|
-
case "tool-result": {
|
|
2409
|
-
throw new UnsupportedFunctionalityError({
|
|
2410
|
-
functionality: "tool-result messages"
|
|
2411
|
-
});
|
|
2412
|
-
}
|
|
2413
|
-
case "reasoning": {
|
|
2414
|
-
throw new UnsupportedFunctionalityError({
|
|
2415
|
-
functionality: "reasoning messages"
|
|
2416
|
-
});
|
|
2417
|
-
}
|
|
2418
|
-
case "file": {
|
|
2419
|
-
throw new UnsupportedFunctionalityError({
|
|
2420
|
-
functionality: "file attachments"
|
|
2421
|
-
});
|
|
2422
|
-
}
|
|
2423
|
-
default: {
|
|
2424
|
-
return "";
|
|
2425
|
-
}
|
|
2426
|
-
}
|
|
2427
|
-
}
|
|
2428
|
-
).join("");
|
|
2429
|
-
text += `${assistant}:
|
|
2430
|
-
${assistantMessage}
|
|
2431
|
-
|
|
2432
|
-
`;
|
|
2433
|
-
break;
|
|
750
|
+
break;
|
|
751
|
+
}
|
|
752
|
+
case "response.output_text.done": {
|
|
753
|
+
if (state.textStarted && !state.textEnded) {
|
|
754
|
+
state.textEnded = true;
|
|
755
|
+
parts.push({
|
|
756
|
+
type: "text-end",
|
|
757
|
+
id: state.textId
|
|
758
|
+
});
|
|
2434
759
|
}
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
760
|
+
break;
|
|
761
|
+
}
|
|
762
|
+
// Reasoning streaming
|
|
763
|
+
case "response.reasoning_text.delta": {
|
|
764
|
+
if (!state.reasoningStarted) {
|
|
765
|
+
state.reasoningStarted = true;
|
|
766
|
+
parts.push({
|
|
767
|
+
type: "reasoning-start",
|
|
768
|
+
id: state.reasoningId
|
|
2438
769
|
});
|
|
2439
770
|
}
|
|
2440
|
-
|
|
2441
|
-
|
|
771
|
+
if (event.delta && event.delta.length > 0) {
|
|
772
|
+
parts.push({
|
|
773
|
+
type: "reasoning-delta",
|
|
774
|
+
id: state.reasoningId,
|
|
775
|
+
delta: event.delta
|
|
776
|
+
});
|
|
2442
777
|
}
|
|
778
|
+
break;
|
|
2443
779
|
}
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
}
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
]);
|
|
2490
|
-
|
|
2491
|
-
// src/completion/index.ts
|
|
2492
|
-
var OpenRouterCompletionLanguageModel = class {
|
|
2493
|
-
constructor(modelId, settings, config) {
|
|
2494
|
-
this.specificationVersion = "v2";
|
|
2495
|
-
this.provider = "openrouter";
|
|
2496
|
-
this.supportsImageUrls = true;
|
|
2497
|
-
this.supportedUrls = {
|
|
2498
|
-
"image/*": [
|
|
2499
|
-
/^data:image\/[a-zA-Z]+;base64,/,
|
|
2500
|
-
/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i
|
|
2501
|
-
],
|
|
2502
|
-
"text/*": [/^data:text\//, /^https?:\/\/.+$/],
|
|
2503
|
-
"application/*": [/^data:application\//, /^https?:\/\/.+$/]
|
|
2504
|
-
};
|
|
2505
|
-
this.defaultObjectGenerationMode = void 0;
|
|
2506
|
-
this.modelId = modelId;
|
|
2507
|
-
this.settings = settings;
|
|
2508
|
-
this.config = config;
|
|
2509
|
-
}
|
|
2510
|
-
getArgs({
|
|
2511
|
-
prompt,
|
|
2512
|
-
maxOutputTokens,
|
|
2513
|
-
temperature,
|
|
2514
|
-
topP,
|
|
2515
|
-
frequencyPenalty,
|
|
2516
|
-
presencePenalty,
|
|
2517
|
-
seed,
|
|
2518
|
-
responseFormat,
|
|
2519
|
-
topK,
|
|
2520
|
-
stopSequences,
|
|
2521
|
-
tools,
|
|
2522
|
-
toolChoice
|
|
2523
|
-
}) {
|
|
2524
|
-
const { prompt: completionPrompt } = convertToOpenRouterCompletionPrompt({
|
|
2525
|
-
prompt,
|
|
2526
|
-
inputFormat: "prompt"
|
|
2527
|
-
});
|
|
2528
|
-
if (tools == null ? void 0 : tools.length) {
|
|
2529
|
-
throw new UnsupportedFunctionalityError({
|
|
2530
|
-
functionality: "tools"
|
|
780
|
+
// Function call arguments streaming
|
|
781
|
+
case "response.function_call_arguments.delta": {
|
|
782
|
+
const toolCallId = event.itemId;
|
|
783
|
+
let toolState = state.toolCalls.get(toolCallId);
|
|
784
|
+
if (!toolState) {
|
|
785
|
+
toolState = { argumentsStarted: false };
|
|
786
|
+
state.toolCalls.set(toolCallId, toolState);
|
|
787
|
+
}
|
|
788
|
+
if (!toolState.argumentsStarted) {
|
|
789
|
+
toolState.argumentsStarted = true;
|
|
790
|
+
parts.push({
|
|
791
|
+
type: "tool-input-start",
|
|
792
|
+
id: toolCallId,
|
|
793
|
+
toolName: toolState.name ?? ""
|
|
794
|
+
// Will be filled in by output_item.added
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
if (event.delta && event.delta.length > 0) {
|
|
798
|
+
parts.push({
|
|
799
|
+
type: "tool-input-delta",
|
|
800
|
+
id: toolCallId,
|
|
801
|
+
delta: event.delta
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
break;
|
|
805
|
+
}
|
|
806
|
+
case "response.function_call_arguments.done": {
|
|
807
|
+
const toolCallId = event.itemId;
|
|
808
|
+
const toolState = state.toolCalls.get(toolCallId);
|
|
809
|
+
if (!toolState?.argumentsStarted) {
|
|
810
|
+
parts.push({
|
|
811
|
+
type: "tool-input-start",
|
|
812
|
+
id: toolCallId,
|
|
813
|
+
toolName: event.name
|
|
814
|
+
});
|
|
815
|
+
const args = event.arguments || "{}";
|
|
816
|
+
parts.push({
|
|
817
|
+
type: "tool-input-delta",
|
|
818
|
+
id: toolCallId,
|
|
819
|
+
delta: args
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
parts.push({
|
|
823
|
+
type: "tool-input-end",
|
|
824
|
+
id: toolCallId
|
|
2531
825
|
});
|
|
826
|
+
parts.push({
|
|
827
|
+
type: "tool-call",
|
|
828
|
+
toolCallId,
|
|
829
|
+
toolName: event.name,
|
|
830
|
+
input: event.arguments || "{}"
|
|
831
|
+
});
|
|
832
|
+
break;
|
|
833
|
+
}
|
|
834
|
+
// Output item events (for function call metadata)
|
|
835
|
+
case "response.output_item.added": {
|
|
836
|
+
if (event.item.type === "function_call") {
|
|
837
|
+
const funcItem = event.item;
|
|
838
|
+
const toolCallId = funcItem.callId ?? `tool-${event.outputIndex}`;
|
|
839
|
+
const toolState = state.toolCalls.get(toolCallId) ?? {
|
|
840
|
+
argumentsStarted: false
|
|
841
|
+
};
|
|
842
|
+
toolState.name = funcItem.name;
|
|
843
|
+
state.toolCalls.set(toolCallId, toolState);
|
|
844
|
+
}
|
|
845
|
+
break;
|
|
2532
846
|
}
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
847
|
+
// Annotation events (web search sources)
|
|
848
|
+
case "response.output_text.annotation.added": {
|
|
849
|
+
const annotation = event.annotation;
|
|
850
|
+
if (annotation.type === "url_citation") {
|
|
851
|
+
const urlAnnotation = annotation;
|
|
852
|
+
const sourceId = `source-${state.sourceIds.length}`;
|
|
853
|
+
state.sourceIds.push(sourceId);
|
|
854
|
+
parts.push({
|
|
855
|
+
type: "source",
|
|
856
|
+
sourceType: "url",
|
|
857
|
+
id: sourceId,
|
|
858
|
+
url: urlAnnotation.url,
|
|
859
|
+
title: urlAnnotation.title
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
break;
|
|
863
|
+
}
|
|
864
|
+
// Response completed - extract final usage data
|
|
865
|
+
case "response.completed": {
|
|
866
|
+
if (state.textStarted && !state.textEnded) {
|
|
867
|
+
state.textEnded = true;
|
|
868
|
+
parts.push({
|
|
869
|
+
type: "text-end",
|
|
870
|
+
id: state.textId
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
if (state.reasoningStarted && !state.reasoningEnded) {
|
|
874
|
+
state.reasoningEnded = true;
|
|
875
|
+
parts.push({
|
|
876
|
+
type: "reasoning-end",
|
|
877
|
+
id: state.reasoningId
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
const response = event.response;
|
|
881
|
+
parts.push({
|
|
882
|
+
type: "response-metadata",
|
|
883
|
+
id: response.id,
|
|
884
|
+
timestamp: response.createdAt ? new Date(response.createdAt * 1e3) : void 0,
|
|
885
|
+
modelId: response.model
|
|
2536
886
|
});
|
|
887
|
+
const finishReason = mapOpenRouterFinishReason(
|
|
888
|
+
response.status === "completed" ? "stop" : response.status ?? "stop"
|
|
889
|
+
);
|
|
890
|
+
const usage = buildUsage(
|
|
891
|
+
response.usage ? {
|
|
892
|
+
inputTokens: response.usage.inputTokens,
|
|
893
|
+
outputTokens: response.usage.outputTokens
|
|
894
|
+
} : void 0
|
|
895
|
+
);
|
|
896
|
+
const providerMetadata = buildProviderMetadata({
|
|
897
|
+
id: response.id,
|
|
898
|
+
provider: void 0,
|
|
899
|
+
// Responses API doesn't expose provider
|
|
900
|
+
usage: response.usage ? {
|
|
901
|
+
promptTokens: response.usage.inputTokens,
|
|
902
|
+
completionTokens: response.usage.outputTokens,
|
|
903
|
+
totalTokens: response.usage.totalTokens,
|
|
904
|
+
cost: response.usage.cost ?? void 0,
|
|
905
|
+
// Map inputTokensDetails -> promptTokensDetails
|
|
906
|
+
promptTokensDetails: response.usage.inputTokensDetails ? {
|
|
907
|
+
cachedTokens: response.usage.inputTokensDetails.cachedTokens
|
|
908
|
+
} : void 0,
|
|
909
|
+
// Map outputTokensDetails -> completionTokensDetails
|
|
910
|
+
completionTokensDetails: response.usage.outputTokensDetails ? {
|
|
911
|
+
reasoningTokens: response.usage.outputTokensDetails.reasoningTokens
|
|
912
|
+
} : void 0
|
|
913
|
+
} : void 0
|
|
914
|
+
});
|
|
915
|
+
parts.push({
|
|
916
|
+
type: "finish",
|
|
917
|
+
finishReason,
|
|
918
|
+
usage,
|
|
919
|
+
providerMetadata
|
|
920
|
+
});
|
|
921
|
+
break;
|
|
2537
922
|
}
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
statusCode: 200,
|
|
2593
|
-
responseHeaders,
|
|
2594
|
-
data: errorData
|
|
923
|
+
// Response incomplete or failed
|
|
924
|
+
case "response.incomplete":
|
|
925
|
+
case "response.failed": {
|
|
926
|
+
if (state.textStarted && !state.textEnded) {
|
|
927
|
+
state.textEnded = true;
|
|
928
|
+
parts.push({
|
|
929
|
+
type: "text-end",
|
|
930
|
+
id: state.textId
|
|
931
|
+
});
|
|
932
|
+
}
|
|
933
|
+
if (state.reasoningStarted && !state.reasoningEnded) {
|
|
934
|
+
state.reasoningEnded = true;
|
|
935
|
+
parts.push({
|
|
936
|
+
type: "reasoning-end",
|
|
937
|
+
id: state.reasoningId
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
const response = event.response;
|
|
941
|
+
parts.push({
|
|
942
|
+
type: "response-metadata",
|
|
943
|
+
id: response.id,
|
|
944
|
+
timestamp: response.createdAt ? new Date(response.createdAt * 1e3) : void 0,
|
|
945
|
+
modelId: response.model
|
|
946
|
+
});
|
|
947
|
+
const finishReason = event.type === "response.failed" ? mapOpenRouterFinishReason("error") : mapOpenRouterFinishReason(response.status ?? "incomplete");
|
|
948
|
+
const usage = buildUsage(
|
|
949
|
+
response.usage ? {
|
|
950
|
+
inputTokens: response.usage.inputTokens,
|
|
951
|
+
outputTokens: response.usage.outputTokens
|
|
952
|
+
} : void 0
|
|
953
|
+
);
|
|
954
|
+
const providerMetadata = buildProviderMetadata({
|
|
955
|
+
id: response.id,
|
|
956
|
+
provider: void 0,
|
|
957
|
+
usage: response.usage ? {
|
|
958
|
+
promptTokens: response.usage.inputTokens,
|
|
959
|
+
completionTokens: response.usage.outputTokens,
|
|
960
|
+
totalTokens: response.usage.totalTokens,
|
|
961
|
+
cost: response.usage.cost ?? void 0,
|
|
962
|
+
// Map inputTokensDetails -> promptTokensDetails
|
|
963
|
+
promptTokensDetails: response.usage.inputTokensDetails ? {
|
|
964
|
+
cachedTokens: response.usage.inputTokensDetails.cachedTokens
|
|
965
|
+
} : void 0,
|
|
966
|
+
// Map outputTokensDetails -> completionTokensDetails
|
|
967
|
+
completionTokensDetails: response.usage.outputTokensDetails ? {
|
|
968
|
+
reasoningTokens: response.usage.outputTokensDetails.reasoningTokens
|
|
969
|
+
} : void 0
|
|
970
|
+
} : void 0
|
|
971
|
+
});
|
|
972
|
+
parts.push({
|
|
973
|
+
type: "finish",
|
|
974
|
+
finishReason,
|
|
975
|
+
usage,
|
|
976
|
+
providerMetadata
|
|
2595
977
|
});
|
|
978
|
+
break;
|
|
2596
979
|
}
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
980
|
+
// Error event
|
|
981
|
+
case "error": {
|
|
982
|
+
const errorEvent = event;
|
|
983
|
+
parts.push({
|
|
984
|
+
type: "error",
|
|
985
|
+
error: new Error(
|
|
986
|
+
errorEvent.error?.message ?? "Unknown streaming error"
|
|
987
|
+
)
|
|
2601
988
|
});
|
|
989
|
+
break;
|
|
2602
990
|
}
|
|
991
|
+
// Ignored events (handled implicitly or not needed)
|
|
992
|
+
case "response.output_item.done":
|
|
993
|
+
case "response.content_part.added":
|
|
994
|
+
case "response.content_part.done":
|
|
995
|
+
case "response.refusal.delta":
|
|
996
|
+
case "response.refusal.done":
|
|
997
|
+
case "response.reasoning_text.done":
|
|
998
|
+
case "response.reasoning_summary_part.added":
|
|
999
|
+
case "response.reasoning_summary_part.done":
|
|
1000
|
+
case "response.reasoning_summary_text.delta":
|
|
1001
|
+
case "response.reasoning_summary_text.done":
|
|
1002
|
+
case "response.image_generation_call.in_progress":
|
|
1003
|
+
case "response.image_generation_call.generating":
|
|
1004
|
+
case "response.image_generation_call.partial_image":
|
|
1005
|
+
case "response.image_generation_call.completed":
|
|
1006
|
+
break;
|
|
1007
|
+
}
|
|
1008
|
+
return parts;
|
|
1009
|
+
}
|
|
1010
|
+
function convertToolsToResponsesFormat(tools, warnings) {
|
|
1011
|
+
if (!tools || tools.length === 0) {
|
|
1012
|
+
return [];
|
|
1013
|
+
}
|
|
1014
|
+
return tools.map((tool) => {
|
|
1015
|
+
if (tool.type !== "function") {
|
|
1016
|
+
warnings.push({
|
|
1017
|
+
type: "unsupported",
|
|
1018
|
+
feature: `tool type '${tool.type}'`,
|
|
1019
|
+
details: `Only 'function' type tools are supported. Tool '${tool.name ?? "unknown"}' has type '${tool.type}'.`
|
|
1020
|
+
});
|
|
1021
|
+
return null;
|
|
1022
|
+
}
|
|
1023
|
+
const functionTool = tool;
|
|
2603
1024
|
return {
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
}
|
|
2609
|
-
],
|
|
2610
|
-
finishReason: mapOpenRouterFinishReason(choice.finish_reason),
|
|
2611
|
-
usage: {
|
|
2612
|
-
inputTokens: (_c = (_b = response.usage) == null ? void 0 : _b.prompt_tokens) != null ? _c : 0,
|
|
2613
|
-
outputTokens: (_e = (_d = response.usage) == null ? void 0 : _d.completion_tokens) != null ? _e : 0,
|
|
2614
|
-
totalTokens: ((_g = (_f = response.usage) == null ? void 0 : _f.prompt_tokens) != null ? _g : 0) + ((_i = (_h = response.usage) == null ? void 0 : _h.completion_tokens) != null ? _i : 0),
|
|
2615
|
-
reasoningTokens: (_l = (_k = (_j = response.usage) == null ? void 0 : _j.completion_tokens_details) == null ? void 0 : _k.reasoning_tokens) != null ? _l : 0,
|
|
2616
|
-
cachedInputTokens: (_o = (_n = (_m = response.usage) == null ? void 0 : _m.prompt_tokens_details) == null ? void 0 : _n.cached_tokens) != null ? _o : 0
|
|
2617
|
-
},
|
|
2618
|
-
warnings: [],
|
|
2619
|
-
response: {
|
|
2620
|
-
headers: responseHeaders
|
|
2621
|
-
}
|
|
1025
|
+
type: "function",
|
|
1026
|
+
name: functionTool.name,
|
|
1027
|
+
description: functionTool.description ?? null,
|
|
1028
|
+
parameters: functionTool.inputSchema
|
|
2622
1029
|
};
|
|
1030
|
+
}).filter((tool) => tool !== null);
|
|
1031
|
+
}
|
|
1032
|
+
function convertToolChoiceToResponsesFormat(toolChoice) {
|
|
1033
|
+
if (!toolChoice) {
|
|
1034
|
+
return void 0;
|
|
2623
1035
|
}
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
const usage = {
|
|
2648
|
-
inputTokens: Number.NaN,
|
|
2649
|
-
outputTokens: Number.NaN,
|
|
2650
|
-
totalTokens: Number.NaN,
|
|
2651
|
-
reasoningTokens: Number.NaN,
|
|
2652
|
-
cachedInputTokens: Number.NaN
|
|
1036
|
+
switch (toolChoice.type) {
|
|
1037
|
+
case "auto":
|
|
1038
|
+
return "auto";
|
|
1039
|
+
case "none":
|
|
1040
|
+
return "none";
|
|
1041
|
+
case "required":
|
|
1042
|
+
return "required";
|
|
1043
|
+
case "tool":
|
|
1044
|
+
return {
|
|
1045
|
+
type: "function",
|
|
1046
|
+
name: toolChoice.toolName
|
|
1047
|
+
};
|
|
1048
|
+
default:
|
|
1049
|
+
return void 0;
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
function convertResponseFormatToText(responseFormat) {
|
|
1053
|
+
if (!responseFormat) {
|
|
1054
|
+
return void 0;
|
|
1055
|
+
}
|
|
1056
|
+
if (responseFormat.type === "text") {
|
|
1057
|
+
return {
|
|
1058
|
+
format: { type: "text" }
|
|
2653
1059
|
};
|
|
2654
|
-
|
|
1060
|
+
}
|
|
1061
|
+
if (responseFormat.type === "json") {
|
|
1062
|
+
if (responseFormat.schema) {
|
|
1063
|
+
return {
|
|
1064
|
+
format: {
|
|
1065
|
+
type: "json_schema",
|
|
1066
|
+
name: responseFormat.name ?? "response",
|
|
1067
|
+
description: responseFormat.description,
|
|
1068
|
+
schema: responseFormat.schema
|
|
1069
|
+
}
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
2655
1072
|
return {
|
|
2656
|
-
|
|
2657
|
-
new TransformStream({
|
|
2658
|
-
transform(chunk, controller) {
|
|
2659
|
-
var _a15, _b, _c;
|
|
2660
|
-
if (!chunk.success) {
|
|
2661
|
-
finishReason = "error";
|
|
2662
|
-
controller.enqueue({ type: "error", error: chunk.error });
|
|
2663
|
-
return;
|
|
2664
|
-
}
|
|
2665
|
-
const value = chunk.value;
|
|
2666
|
-
if ("error" in value) {
|
|
2667
|
-
finishReason = "error";
|
|
2668
|
-
controller.enqueue({ type: "error", error: value.error });
|
|
2669
|
-
return;
|
|
2670
|
-
}
|
|
2671
|
-
if (value.usage != null) {
|
|
2672
|
-
usage.inputTokens = value.usage.prompt_tokens;
|
|
2673
|
-
usage.outputTokens = value.usage.completion_tokens;
|
|
2674
|
-
usage.totalTokens = value.usage.prompt_tokens + value.usage.completion_tokens;
|
|
2675
|
-
openrouterUsage.promptTokens = value.usage.prompt_tokens;
|
|
2676
|
-
if (value.usage.prompt_tokens_details) {
|
|
2677
|
-
const cachedInputTokens = (_a15 = value.usage.prompt_tokens_details.cached_tokens) != null ? _a15 : 0;
|
|
2678
|
-
usage.cachedInputTokens = cachedInputTokens;
|
|
2679
|
-
openrouterUsage.promptTokensDetails = {
|
|
2680
|
-
cachedTokens: cachedInputTokens
|
|
2681
|
-
};
|
|
2682
|
-
}
|
|
2683
|
-
openrouterUsage.completionTokens = value.usage.completion_tokens;
|
|
2684
|
-
if (value.usage.completion_tokens_details) {
|
|
2685
|
-
const reasoningTokens = (_b = value.usage.completion_tokens_details.reasoning_tokens) != null ? _b : 0;
|
|
2686
|
-
usage.reasoningTokens = reasoningTokens;
|
|
2687
|
-
openrouterUsage.completionTokensDetails = {
|
|
2688
|
-
reasoningTokens
|
|
2689
|
-
};
|
|
2690
|
-
}
|
|
2691
|
-
openrouterUsage.cost = value.usage.cost;
|
|
2692
|
-
openrouterUsage.totalTokens = value.usage.total_tokens;
|
|
2693
|
-
const upstreamInferenceCost = (_c = value.usage.cost_details) == null ? void 0 : _c.upstream_inference_cost;
|
|
2694
|
-
if (upstreamInferenceCost != null) {
|
|
2695
|
-
openrouterUsage.costDetails = {
|
|
2696
|
-
upstreamInferenceCost
|
|
2697
|
-
};
|
|
2698
|
-
}
|
|
2699
|
-
}
|
|
2700
|
-
const choice = value.choices[0];
|
|
2701
|
-
if ((choice == null ? void 0 : choice.finish_reason) != null) {
|
|
2702
|
-
finishReason = mapOpenRouterFinishReason(choice.finish_reason);
|
|
2703
|
-
}
|
|
2704
|
-
if ((choice == null ? void 0 : choice.text) != null) {
|
|
2705
|
-
controller.enqueue({
|
|
2706
|
-
type: "text-delta",
|
|
2707
|
-
delta: choice.text,
|
|
2708
|
-
id: generateId()
|
|
2709
|
-
});
|
|
2710
|
-
}
|
|
2711
|
-
},
|
|
2712
|
-
flush(controller) {
|
|
2713
|
-
controller.enqueue({
|
|
2714
|
-
type: "finish",
|
|
2715
|
-
finishReason,
|
|
2716
|
-
usage,
|
|
2717
|
-
providerMetadata: {
|
|
2718
|
-
openrouter: {
|
|
2719
|
-
usage: openrouterUsage
|
|
2720
|
-
}
|
|
2721
|
-
}
|
|
2722
|
-
});
|
|
2723
|
-
}
|
|
2724
|
-
})
|
|
2725
|
-
),
|
|
2726
|
-
response: {
|
|
2727
|
-
headers: responseHeaders
|
|
2728
|
-
}
|
|
1073
|
+
format: { type: "json_object" }
|
|
2729
1074
|
};
|
|
2730
1075
|
}
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
// src/embedding/schemas.ts
|
|
2734
|
-
var import_v48 = require("zod/v4");
|
|
2735
|
-
var openrouterEmbeddingUsageSchema = import_v48.z.object({
|
|
2736
|
-
prompt_tokens: import_v48.z.number(),
|
|
2737
|
-
total_tokens: import_v48.z.number(),
|
|
2738
|
-
cost: import_v48.z.number().optional()
|
|
2739
|
-
});
|
|
2740
|
-
var openrouterEmbeddingDataSchema = import_v48.z.object({
|
|
2741
|
-
object: import_v48.z.literal("embedding"),
|
|
2742
|
-
embedding: import_v48.z.array(import_v48.z.number()),
|
|
2743
|
-
index: import_v48.z.number().optional()
|
|
2744
|
-
});
|
|
2745
|
-
var OpenRouterEmbeddingResponseSchema = import_v48.z.object({
|
|
2746
|
-
id: import_v48.z.string().optional(),
|
|
2747
|
-
object: import_v48.z.literal("list"),
|
|
2748
|
-
data: import_v48.z.array(openrouterEmbeddingDataSchema),
|
|
2749
|
-
model: import_v48.z.string(),
|
|
2750
|
-
usage: openrouterEmbeddingUsageSchema.optional()
|
|
2751
|
-
});
|
|
1076
|
+
return void 0;
|
|
1077
|
+
}
|
|
2752
1078
|
|
|
2753
|
-
// src/embedding/
|
|
1079
|
+
// src/embedding/openrouter-embedding-model.ts
|
|
1080
|
+
var import_provider_utils2 = require("@ai-sdk/provider-utils");
|
|
1081
|
+
var import_sdk2 = require("@openrouter/sdk");
|
|
2754
1082
|
var OpenRouterEmbeddingModel = class {
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
1083
|
+
specificationVersion = "v3";
|
|
1084
|
+
provider = "openrouter";
|
|
1085
|
+
modelId;
|
|
1086
|
+
settings;
|
|
1087
|
+
/**
|
|
1088
|
+
* Maximum number of embeddings that can be generated in a single API call.
|
|
1089
|
+
* Set to 2048 as a reasonable default for most embedding models.
|
|
1090
|
+
*/
|
|
1091
|
+
maxEmbeddingsPerCall = 2048;
|
|
1092
|
+
/**
|
|
1093
|
+
* Whether the model supports parallel calls.
|
|
1094
|
+
*/
|
|
1095
|
+
supportsParallelCalls = true;
|
|
1096
|
+
constructor(modelId, settings) {
|
|
2760
1097
|
this.modelId = modelId;
|
|
2761
1098
|
this.settings = settings;
|
|
2762
|
-
this.config = config;
|
|
2763
1099
|
}
|
|
2764
1100
|
async doEmbed(options) {
|
|
2765
|
-
|
|
2766
|
-
const
|
|
2767
|
-
|
|
1101
|
+
const warnings = [];
|
|
1102
|
+
const client = new import_sdk2.OpenRouter({
|
|
1103
|
+
apiKey: this.settings.apiKey,
|
|
1104
|
+
serverURL: this.settings.baseURL
|
|
1105
|
+
});
|
|
1106
|
+
const requestParams = {
|
|
2768
1107
|
model: this.modelId,
|
|
2769
|
-
input: values
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
1108
|
+
input: options.values
|
|
1109
|
+
};
|
|
1110
|
+
const modelOptions = this.settings.modelOptions;
|
|
1111
|
+
if (modelOptions?.user) {
|
|
1112
|
+
requestParams.user = modelOptions.user;
|
|
1113
|
+
}
|
|
1114
|
+
if (modelOptions?.provider) {
|
|
1115
|
+
requestParams.provider = modelOptions.provider;
|
|
1116
|
+
}
|
|
1117
|
+
const combinedHeaders = (0, import_provider_utils2.normalizeHeaders)(
|
|
1118
|
+
(0, import_provider_utils2.combineHeaders)(this.settings.headers, options.headers)
|
|
1119
|
+
);
|
|
1120
|
+
const response = await client.embeddings.generate(requestParams, {
|
|
1121
|
+
fetchOptions: {
|
|
1122
|
+
signal: options.abortSignal,
|
|
1123
|
+
headers: combinedHeaders
|
|
1124
|
+
}
|
|
2786
1125
|
});
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
}
|
|
2796
|
-
} : void 0,
|
|
2797
|
-
response: {
|
|
2798
|
-
headers: responseHeaders,
|
|
2799
|
-
body: responseValue
|
|
1126
|
+
if (typeof response === "string") {
|
|
1127
|
+
throw new Error(`Unexpected string response from embeddings API: ${response}`);
|
|
1128
|
+
}
|
|
1129
|
+
const responseBody = response;
|
|
1130
|
+
const sortedData = [...responseBody.data].sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
|
|
1131
|
+
const embeddings = sortedData.map((item) => {
|
|
1132
|
+
if (typeof item.embedding === "string") {
|
|
1133
|
+
throw new Error("Base64 encoded embeddings are not supported");
|
|
2800
1134
|
}
|
|
1135
|
+
return item.embedding;
|
|
1136
|
+
});
|
|
1137
|
+
return {
|
|
1138
|
+
embeddings,
|
|
1139
|
+
usage: responseBody.usage ? { tokens: responseBody.usage.promptTokens } : void 0,
|
|
1140
|
+
warnings
|
|
2801
1141
|
};
|
|
2802
1142
|
}
|
|
2803
1143
|
};
|
|
2804
1144
|
|
|
2805
|
-
// src/
|
|
2806
|
-
var
|
|
1145
|
+
// src/image/openrouter-image-model.ts
|
|
1146
|
+
var OpenRouterImageModel = class {
|
|
1147
|
+
specificationVersion = "v3";
|
|
1148
|
+
provider = "openrouter";
|
|
1149
|
+
modelId;
|
|
2807
1150
|
/**
|
|
2808
|
-
*
|
|
1151
|
+
* Maximum number of images that can be generated in a single API call.
|
|
2809
1152
|
*/
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
this.
|
|
2813
|
-
this.apiKey = options.apiKey;
|
|
2814
|
-
this.headers = options.headers;
|
|
2815
|
-
this.api_keys = options.api_keys;
|
|
2816
|
-
}
|
|
2817
|
-
get baseConfig() {
|
|
2818
|
-
return {
|
|
2819
|
-
baseURL: this.baseURL,
|
|
2820
|
-
headers: () => __spreadValues(__spreadValues({
|
|
2821
|
-
Authorization: `Bearer ${loadApiKey({
|
|
2822
|
-
apiKey: this.apiKey,
|
|
2823
|
-
environmentVariableName: "OPENROUTER_API_KEY",
|
|
2824
|
-
description: "OpenRouter"
|
|
2825
|
-
})}`
|
|
2826
|
-
}, this.headers), this.api_keys && Object.keys(this.api_keys).length > 0 && {
|
|
2827
|
-
"X-Provider-API-Keys": JSON.stringify(this.api_keys)
|
|
2828
|
-
})
|
|
2829
|
-
};
|
|
2830
|
-
}
|
|
2831
|
-
chat(modelId, settings = {}) {
|
|
2832
|
-
return new OpenRouterChatLanguageModel(modelId, settings, __spreadProps(__spreadValues({
|
|
2833
|
-
provider: "openrouter.chat"
|
|
2834
|
-
}, this.baseConfig), {
|
|
2835
|
-
compatibility: "strict",
|
|
2836
|
-
url: ({ path }) => `${this.baseURL}${path}`
|
|
2837
|
-
}));
|
|
2838
|
-
}
|
|
2839
|
-
completion(modelId, settings = {}) {
|
|
2840
|
-
return new OpenRouterCompletionLanguageModel(modelId, settings, __spreadProps(__spreadValues({
|
|
2841
|
-
provider: "openrouter.completion"
|
|
2842
|
-
}, this.baseConfig), {
|
|
2843
|
-
compatibility: "strict",
|
|
2844
|
-
url: ({ path }) => `${this.baseURL}${path}`
|
|
2845
|
-
}));
|
|
2846
|
-
}
|
|
2847
|
-
textEmbeddingModel(modelId, settings = {}) {
|
|
2848
|
-
return new OpenRouterEmbeddingModel(modelId, settings, __spreadProps(__spreadValues({
|
|
2849
|
-
provider: "openrouter.embedding"
|
|
2850
|
-
}, this.baseConfig), {
|
|
2851
|
-
url: ({ path }) => `${this.baseURL}${path}`
|
|
2852
|
-
}));
|
|
1153
|
+
maxImagesPerCall = 1;
|
|
1154
|
+
constructor(modelId, _settings) {
|
|
1155
|
+
this.modelId = modelId;
|
|
2853
1156
|
}
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
return this.textEmbeddingModel(modelId, settings);
|
|
1157
|
+
async doGenerate(_options) {
|
|
1158
|
+
throw new Error(
|
|
1159
|
+
"Image generation not yet supported. See: https://github.com/OpenRouterTeam/ai-sdk-provider/issues/new?title=Image+generation+support"
|
|
1160
|
+
);
|
|
2859
1161
|
}
|
|
2860
1162
|
};
|
|
2861
1163
|
|
|
2862
|
-
// src/
|
|
2863
|
-
function
|
|
2864
|
-
|
|
2865
|
-
|
|
1164
|
+
// src/openrouter-provider.ts
|
|
1165
|
+
function createOpenRouter(options = {}) {
|
|
1166
|
+
const baseURL = (0, import_provider_utils3.withoutTrailingSlash)(
|
|
1167
|
+
options.baseURL ?? options.baseUrl ?? "https://openrouter.ai/api/v1"
|
|
2866
1168
|
);
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
1169
|
+
const getModelSettings = (modelOptions) => {
|
|
1170
|
+
const apiKey = (0, import_provider_utils3.loadApiKey)({
|
|
1171
|
+
apiKey: options.apiKey,
|
|
1172
|
+
environmentVariableName: "OPENROUTER_API_KEY",
|
|
1173
|
+
description: "OpenRouter"
|
|
1174
|
+
});
|
|
1175
|
+
return {
|
|
1176
|
+
apiKey,
|
|
1177
|
+
baseURL,
|
|
1178
|
+
headers: options.headers,
|
|
1179
|
+
fetch: options.fetch,
|
|
1180
|
+
extraBody: options.extraBody,
|
|
1181
|
+
modelOptions
|
|
1182
|
+
};
|
|
1183
|
+
};
|
|
1184
|
+
const languageModel = (modelId, modelOptions) => {
|
|
1185
|
+
return new OpenRouterChatLanguageModel(modelId, getModelSettings(modelOptions));
|
|
1186
|
+
};
|
|
1187
|
+
const embeddingModel = (modelId, modelOptions) => {
|
|
1188
|
+
return new OpenRouterEmbeddingModel(modelId, getModelSettings(modelOptions));
|
|
1189
|
+
};
|
|
1190
|
+
const imageModel = (modelId, modelOptions) => {
|
|
1191
|
+
return new OpenRouterImageModel(modelId, getModelSettings(modelOptions));
|
|
1192
|
+
};
|
|
1193
|
+
const provider = Object.assign(
|
|
1194
|
+
// Make provider callable - calling it directly creates a language model
|
|
1195
|
+
(modelId, modelOptions) => languageModel(modelId, modelOptions),
|
|
1196
|
+
{
|
|
1197
|
+
specificationVersion: "v3",
|
|
1198
|
+
languageModel,
|
|
1199
|
+
chat: languageModel,
|
|
1200
|
+
embeddingModel,
|
|
1201
|
+
textEmbeddingModel: embeddingModel,
|
|
1202
|
+
imageModel,
|
|
1203
|
+
image: imageModel,
|
|
1204
|
+
embedding: embeddingModel
|
|
1205
|
+
}
|
|
2873
1206
|
);
|
|
2874
|
-
|
|
2875
|
-
const newUserAgent = [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ");
|
|
2876
|
-
return __spreadProps(__spreadValues({}, cleanedHeaders), {
|
|
2877
|
-
"user-agent": newUserAgent
|
|
2878
|
-
});
|
|
1207
|
+
return provider;
|
|
2879
1208
|
}
|
|
2880
1209
|
|
|
2881
1210
|
// src/version.ts
|
|
2882
|
-
var VERSION =
|
|
1211
|
+
var VERSION = "6.0.0-alpha.0";
|
|
2883
1212
|
|
|
2884
|
-
// src/
|
|
2885
|
-
|
|
2886
|
-
var _a15, _b, _c;
|
|
2887
|
-
const baseURL = (_b = withoutTrailingSlash((_a15 = options.baseURL) != null ? _a15 : options.baseUrl)) != null ? _b : "https://openrouter.ai/api/v1";
|
|
2888
|
-
const compatibility = (_c = options.compatibility) != null ? _c : "compatible";
|
|
2889
|
-
const getHeaders = () => withUserAgentSuffix(
|
|
2890
|
-
__spreadValues(__spreadValues({
|
|
2891
|
-
Authorization: `Bearer ${loadApiKey({
|
|
2892
|
-
apiKey: options.apiKey,
|
|
2893
|
-
environmentVariableName: "OPENROUTER_API_KEY",
|
|
2894
|
-
description: "OpenRouter"
|
|
2895
|
-
})}`
|
|
2896
|
-
}, options.headers), options.api_keys && Object.keys(options.api_keys).length > 0 && {
|
|
2897
|
-
"X-Provider-API-Keys": JSON.stringify(options.api_keys)
|
|
2898
|
-
}),
|
|
2899
|
-
`ai-sdk/openrouter/${VERSION}`
|
|
2900
|
-
);
|
|
2901
|
-
const createChatModel = (modelId, settings = {}) => new OpenRouterChatLanguageModel(modelId, settings, {
|
|
2902
|
-
provider: "openrouter.chat",
|
|
2903
|
-
url: ({ path }) => `${baseURL}${path}`,
|
|
2904
|
-
headers: getHeaders,
|
|
2905
|
-
compatibility,
|
|
2906
|
-
fetch: options.fetch,
|
|
2907
|
-
extraBody: options.extraBody
|
|
2908
|
-
});
|
|
2909
|
-
const createCompletionModel = (modelId, settings = {}) => new OpenRouterCompletionLanguageModel(modelId, settings, {
|
|
2910
|
-
provider: "openrouter.completion",
|
|
2911
|
-
url: ({ path }) => `${baseURL}${path}`,
|
|
2912
|
-
headers: getHeaders,
|
|
2913
|
-
compatibility,
|
|
2914
|
-
fetch: options.fetch,
|
|
2915
|
-
extraBody: options.extraBody
|
|
2916
|
-
});
|
|
2917
|
-
const createEmbeddingModel = (modelId, settings = {}) => new OpenRouterEmbeddingModel(modelId, settings, {
|
|
2918
|
-
provider: "openrouter.embedding",
|
|
2919
|
-
url: ({ path }) => `${baseURL}${path}`,
|
|
2920
|
-
headers: getHeaders,
|
|
2921
|
-
fetch: options.fetch,
|
|
2922
|
-
extraBody: options.extraBody
|
|
2923
|
-
});
|
|
2924
|
-
const createLanguageModel = (modelId, settings) => {
|
|
2925
|
-
if (new.target) {
|
|
2926
|
-
throw new Error(
|
|
2927
|
-
"The OpenRouter model function cannot be called with the new keyword."
|
|
2928
|
-
);
|
|
2929
|
-
}
|
|
2930
|
-
if (modelId === "openai/gpt-3.5-turbo-instruct") {
|
|
2931
|
-
return createCompletionModel(
|
|
2932
|
-
modelId,
|
|
2933
|
-
settings
|
|
2934
|
-
);
|
|
2935
|
-
}
|
|
2936
|
-
return createChatModel(modelId, settings);
|
|
2937
|
-
};
|
|
2938
|
-
const provider = (modelId, settings) => createLanguageModel(modelId, settings);
|
|
2939
|
-
provider.languageModel = createLanguageModel;
|
|
2940
|
-
provider.chat = createChatModel;
|
|
2941
|
-
provider.completion = createCompletionModel;
|
|
2942
|
-
provider.textEmbeddingModel = createEmbeddingModel;
|
|
2943
|
-
provider.embedding = createEmbeddingModel;
|
|
2944
|
-
return provider;
|
|
2945
|
-
}
|
|
2946
|
-
var openrouter = createOpenRouter({
|
|
2947
|
-
compatibility: "strict"
|
|
2948
|
-
// strict for OpenRouter API
|
|
2949
|
-
});
|
|
1213
|
+
// src/index.ts
|
|
1214
|
+
var openrouter = createOpenRouter();
|
|
2950
1215
|
// Annotate the CommonJS export names for ESM import in node:
|
|
2951
1216
|
0 && (module.exports = {
|
|
2952
|
-
|
|
1217
|
+
VERSION,
|
|
2953
1218
|
createOpenRouter,
|
|
2954
1219
|
openrouter
|
|
2955
1220
|
});
|