@alpic80/rivet-ai-sdk-provider 2.0.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.js ADDED
@@ -0,0 +1,1876 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ 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
+ var __export = (target, all) => {
26
+ for (var name14 in all)
27
+ __defProp(target, name14, { get: all[name14], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
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
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+
47
+ // src/index.ts
48
+ var index_exports = {};
49
+ __export(index_exports, {
50
+ VERSION: () => VERSION,
51
+ createRivet: () => createRivet,
52
+ rivet: () => rivet
53
+ });
54
+ module.exports = __toCommonJS(index_exports);
55
+
56
+ // node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/dist/index.mjs
57
+ var marker = "vercel.ai.error";
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
+ _a5 = symbol5;
180
+ var name5 = "AI_InvalidResponseDataError";
181
+ var marker6 = `vercel.ai.error.${name5}`;
182
+ var symbol6 = Symbol.for(marker6);
183
+ var _a6;
184
+ _a6 = symbol6;
185
+ var name6 = "AI_JSONParseError";
186
+ var marker7 = `vercel.ai.error.${name6}`;
187
+ var symbol7 = Symbol.for(marker7);
188
+ var _a7;
189
+ var JSONParseError = class extends AISDKError {
190
+ constructor({ text, cause }) {
191
+ super({
192
+ name: name6,
193
+ message: `JSON parsing failed: Text: ${text}.
194
+ Error message: ${getErrorMessage(cause)}`,
195
+ cause
196
+ });
197
+ this[_a7] = true;
198
+ this.text = text;
199
+ }
200
+ static isInstance(error) {
201
+ return AISDKError.hasMarker(error, marker7);
202
+ }
203
+ };
204
+ _a7 = symbol7;
205
+ var name7 = "AI_LoadAPIKeyError";
206
+ var marker8 = `vercel.ai.error.${name7}`;
207
+ var symbol8 = Symbol.for(marker8);
208
+ var _a8;
209
+ var LoadAPIKeyError = class extends AISDKError {
210
+ // used in isInstance
211
+ constructor({ message }) {
212
+ super({ name: name7, message });
213
+ this[_a8] = true;
214
+ }
215
+ static isInstance(error) {
216
+ return AISDKError.hasMarker(error, marker8);
217
+ }
218
+ };
219
+ _a8 = symbol8;
220
+ var name8 = "AI_LoadSettingError";
221
+ var marker9 = `vercel.ai.error.${name8}`;
222
+ var symbol9 = Symbol.for(marker9);
223
+ var _a9;
224
+ _a9 = symbol9;
225
+ var name9 = "AI_NoContentGeneratedError";
226
+ var marker10 = `vercel.ai.error.${name9}`;
227
+ var symbol10 = Symbol.for(marker10);
228
+ var _a10;
229
+ _a10 = symbol10;
230
+ var name10 = "AI_NoSuchModelError";
231
+ var marker11 = `vercel.ai.error.${name10}`;
232
+ var symbol11 = Symbol.for(marker11);
233
+ var _a11;
234
+ var NoSuchModelError = class extends AISDKError {
235
+ constructor({
236
+ errorName = name10,
237
+ modelId,
238
+ modelType,
239
+ message = `No such ${modelType}: ${modelId}`
240
+ }) {
241
+ super({ name: errorName, message });
242
+ this[_a11] = true;
243
+ this.modelId = modelId;
244
+ this.modelType = modelType;
245
+ }
246
+ static isInstance(error) {
247
+ return AISDKError.hasMarker(error, marker11);
248
+ }
249
+ };
250
+ _a11 = symbol11;
251
+ var name11 = "AI_TooManyEmbeddingValuesForCallError";
252
+ var marker12 = `vercel.ai.error.${name11}`;
253
+ var symbol12 = Symbol.for(marker12);
254
+ var _a12;
255
+ _a12 = symbol12;
256
+ var name12 = "AI_TypeValidationError";
257
+ var marker13 = `vercel.ai.error.${name12}`;
258
+ var symbol13 = Symbol.for(marker13);
259
+ var _a13;
260
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
261
+ constructor({ value, cause }) {
262
+ super({
263
+ name: name12,
264
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
265
+ Error message: ${getErrorMessage(cause)}`,
266
+ cause
267
+ });
268
+ this[_a13] = true;
269
+ this.value = value;
270
+ }
271
+ static isInstance(error) {
272
+ return AISDKError.hasMarker(error, marker13);
273
+ }
274
+ /**
275
+ * Wraps an error into a TypeValidationError.
276
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
277
+ * Otherwise, it creates a new TypeValidationError.
278
+ *
279
+ * @param {Object} params - The parameters for wrapping the error.
280
+ * @param {unknown} params.value - The value that failed validation.
281
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
282
+ * @returns {TypeValidationError} A TypeValidationError instance.
283
+ */
284
+ static wrap({
285
+ value,
286
+ cause
287
+ }) {
288
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
289
+ }
290
+ };
291
+ _a13 = symbol13;
292
+ var TypeValidationError = _TypeValidationError;
293
+ var name13 = "AI_UnsupportedFunctionalityError";
294
+ var marker14 = `vercel.ai.error.${name13}`;
295
+ var symbol14 = Symbol.for(marker14);
296
+ var _a14;
297
+ var UnsupportedFunctionalityError = class extends AISDKError {
298
+ constructor({
299
+ functionality,
300
+ message = `'${functionality}' functionality not supported.`
301
+ }) {
302
+ super({ name: name13, message });
303
+ this[_a14] = true;
304
+ this.functionality = functionality;
305
+ }
306
+ static isInstance(error) {
307
+ return AISDKError.hasMarker(error, marker14);
308
+ }
309
+ };
310
+ _a14 = symbol14;
311
+
312
+ // node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js
313
+ var ParseError = class extends Error {
314
+ constructor(message, options) {
315
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
316
+ }
317
+ };
318
+ function noop(_arg) {
319
+ }
320
+ function createParser(callbacks) {
321
+ if (typeof callbacks == "function")
322
+ throw new TypeError(
323
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
324
+ );
325
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
326
+ let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
327
+ function feed(newChunk) {
328
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
329
+ for (const line of complete)
330
+ parseLine(line);
331
+ incompleteLine = incomplete, isFirstChunk = false;
332
+ }
333
+ function parseLine(line) {
334
+ if (line === "") {
335
+ dispatchEvent();
336
+ return;
337
+ }
338
+ if (line.startsWith(":")) {
339
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
340
+ return;
341
+ }
342
+ const fieldSeparatorIndex = line.indexOf(":");
343
+ if (fieldSeparatorIndex !== -1) {
344
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
345
+ processField(field, value, line);
346
+ return;
347
+ }
348
+ processField(line, "", line);
349
+ }
350
+ function processField(field, value, line) {
351
+ switch (field) {
352
+ case "event":
353
+ eventType = value;
354
+ break;
355
+ case "data":
356
+ data = `${data}${value}
357
+ `;
358
+ break;
359
+ case "id":
360
+ id = value.includes("\0") ? void 0 : value;
361
+ break;
362
+ case "retry":
363
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
364
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
365
+ type: "invalid-retry",
366
+ value,
367
+ line
368
+ })
369
+ );
370
+ break;
371
+ default:
372
+ onError(
373
+ new ParseError(
374
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
375
+ { type: "unknown-field", field, value, line }
376
+ )
377
+ );
378
+ break;
379
+ }
380
+ }
381
+ function dispatchEvent() {
382
+ data.length > 0 && onEvent({
383
+ id,
384
+ event: eventType || void 0,
385
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
386
+ // then remove the last character from the data buffer.
387
+ data: data.endsWith(`
388
+ `) ? data.slice(0, -1) : data
389
+ }), id = void 0, data = "", eventType = "";
390
+ }
391
+ function reset(options = {}) {
392
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
393
+ }
394
+ return { feed, reset };
395
+ }
396
+ function splitLines(chunk) {
397
+ const lines = [];
398
+ let incompleteLine = "", searchIndex = 0;
399
+ for (; searchIndex < chunk.length; ) {
400
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
401
+ `, searchIndex);
402
+ let lineEnd = -1;
403
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
404
+ incompleteLine = chunk.slice(searchIndex);
405
+ break;
406
+ } else {
407
+ const line = chunk.slice(searchIndex, lineEnd);
408
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
409
+ ` && searchIndex++;
410
+ }
411
+ }
412
+ return [lines, incompleteLine];
413
+ }
414
+
415
+ // node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js
416
+ var EventSourceParserStream = class extends TransformStream {
417
+ constructor({ onError, onRetry, onComment } = {}) {
418
+ let parser;
419
+ super({
420
+ start(controller) {
421
+ parser = createParser({
422
+ onEvent: (event) => {
423
+ controller.enqueue(event);
424
+ },
425
+ onError(error) {
426
+ onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
427
+ },
428
+ onRetry,
429
+ onComment
430
+ });
431
+ },
432
+ transform(chunk) {
433
+ parser.feed(chunk);
434
+ }
435
+ });
436
+ }
437
+ };
438
+
439
+ // node_modules/.pnpm/@ai-sdk+provider-utils@3.0.12_zod@3.25.76/node_modules/@ai-sdk/provider-utils/dist/index.mjs
440
+ var z4 = __toESM(require("zod/v4"), 1);
441
+ var import_v3 = require("zod/v3");
442
+ var import_v32 = require("zod/v3");
443
+ var import_v33 = require("zod/v3");
444
+ function combineHeaders(...headers) {
445
+ return headers.reduce(
446
+ (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}),
447
+ {}
448
+ );
449
+ }
450
+ function extractResponseHeaders(response) {
451
+ return Object.fromEntries([...response.headers]);
452
+ }
453
+ var createIdGenerator = ({
454
+ prefix,
455
+ size = 16,
456
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
457
+ separator = "-"
458
+ } = {}) => {
459
+ const generator = () => {
460
+ const alphabetLength = alphabet.length;
461
+ const chars = new Array(size);
462
+ for (let i = 0; i < size; i++) {
463
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
464
+ }
465
+ return chars.join("");
466
+ };
467
+ if (prefix == null) {
468
+ return generator;
469
+ }
470
+ if (alphabet.includes(separator)) {
471
+ throw new InvalidArgumentError({
472
+ argument: "separator",
473
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
474
+ });
475
+ }
476
+ return () => `${prefix}${separator}${generator()}`;
477
+ };
478
+ var generateId = createIdGenerator();
479
+ function isAbortError(error) {
480
+ return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js
481
+ error.name === "TimeoutError");
482
+ }
483
+ function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
484
+ var _a15, _b, _c;
485
+ if (globalThisAny.window) {
486
+ return `runtime/browser`;
487
+ }
488
+ if ((_a15 = globalThisAny.navigator) == null ? void 0 : _a15.userAgent) {
489
+ return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
490
+ }
491
+ if ((_c = (_b = globalThisAny.process) == null ? void 0 : _b.versions) == null ? void 0 : _c.node) {
492
+ return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
493
+ }
494
+ if (globalThisAny.EdgeRuntime) {
495
+ return `runtime/vercel-edge`;
496
+ }
497
+ return "runtime/unknown";
498
+ }
499
+ function removeUndefinedEntries(record) {
500
+ return Object.fromEntries(
501
+ Object.entries(record).filter(([_key, value]) => value != null)
502
+ );
503
+ }
504
+ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
505
+ const cleanedHeaders = removeUndefinedEntries(
506
+ headers != null ? headers : {}
507
+ );
508
+ const normalizedHeaders = new Headers(cleanedHeaders);
509
+ const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
510
+ normalizedHeaders.set(
511
+ "user-agent",
512
+ [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")
513
+ );
514
+ return Object.fromEntries(normalizedHeaders);
515
+ }
516
+ function loadApiKey({
517
+ apiKey,
518
+ environmentVariableName,
519
+ apiKeyParameterName = "apiKey",
520
+ description
521
+ }) {
522
+ if (typeof apiKey === "string") {
523
+ return apiKey;
524
+ }
525
+ if (apiKey != null) {
526
+ throw new LoadAPIKeyError({
527
+ message: `${description} API key must be a string.`
528
+ });
529
+ }
530
+ if (typeof process === "undefined") {
531
+ throw new LoadAPIKeyError({
532
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
533
+ });
534
+ }
535
+ apiKey = process.env[environmentVariableName];
536
+ if (apiKey == null) {
537
+ throw new LoadAPIKeyError({
538
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
539
+ });
540
+ }
541
+ if (typeof apiKey !== "string") {
542
+ throw new LoadAPIKeyError({
543
+ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
544
+ });
545
+ }
546
+ return apiKey;
547
+ }
548
+ var suspectProtoRx = /"__proto__"\s*:/;
549
+ var suspectConstructorRx = /"constructor"\s*:/;
550
+ function _parse(text) {
551
+ const obj = JSON.parse(text);
552
+ if (obj === null || typeof obj !== "object") {
553
+ return obj;
554
+ }
555
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
556
+ return obj;
557
+ }
558
+ return filter(obj);
559
+ }
560
+ function filter(obj) {
561
+ let next = [obj];
562
+ while (next.length) {
563
+ const nodes = next;
564
+ next = [];
565
+ for (const node of nodes) {
566
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
567
+ throw new SyntaxError("Object contains forbidden prototype property");
568
+ }
569
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
570
+ throw new SyntaxError("Object contains forbidden prototype property");
571
+ }
572
+ for (const key in node) {
573
+ const value = node[key];
574
+ if (value && typeof value === "object") {
575
+ next.push(value);
576
+ }
577
+ }
578
+ }
579
+ }
580
+ return obj;
581
+ }
582
+ function secureJsonParse(text) {
583
+ const { stackTraceLimit } = Error;
584
+ Error.stackTraceLimit = 0;
585
+ try {
586
+ return _parse(text);
587
+ } finally {
588
+ Error.stackTraceLimit = stackTraceLimit;
589
+ }
590
+ }
591
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
592
+ function validator(validate) {
593
+ return { [validatorSymbol]: true, validate };
594
+ }
595
+ function isValidator(value) {
596
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
597
+ }
598
+ function asValidator(value) {
599
+ return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
600
+ }
601
+ function standardSchemaValidator(standardSchema) {
602
+ return validator(async (value) => {
603
+ const result = await standardSchema["~standard"].validate(value);
604
+ return result.issues == null ? { success: true, value: result.value } : {
605
+ success: false,
606
+ error: new TypeValidationError({
607
+ value,
608
+ cause: result.issues
609
+ })
610
+ };
611
+ });
612
+ }
613
+ async function validateTypes({
614
+ value,
615
+ schema
616
+ }) {
617
+ const result = await safeValidateTypes({ value, schema });
618
+ if (!result.success) {
619
+ throw TypeValidationError.wrap({ value, cause: result.error });
620
+ }
621
+ return result.value;
622
+ }
623
+ async function safeValidateTypes({
624
+ value,
625
+ schema
626
+ }) {
627
+ const validator2 = asValidator(schema);
628
+ try {
629
+ if (validator2.validate == null) {
630
+ return { success: true, value, rawValue: value };
631
+ }
632
+ const result = await validator2.validate(value);
633
+ if (result.success) {
634
+ return { success: true, value: result.value, rawValue: value };
635
+ }
636
+ return {
637
+ success: false,
638
+ error: TypeValidationError.wrap({ value, cause: result.error }),
639
+ rawValue: value
640
+ };
641
+ } catch (error) {
642
+ return {
643
+ success: false,
644
+ error: TypeValidationError.wrap({ value, cause: error }),
645
+ rawValue: value
646
+ };
647
+ }
648
+ }
649
+ async function parseJSON({
650
+ text,
651
+ schema
652
+ }) {
653
+ try {
654
+ const value = secureJsonParse(text);
655
+ if (schema == null) {
656
+ return value;
657
+ }
658
+ return validateTypes({ value, schema });
659
+ } catch (error) {
660
+ if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
661
+ throw error;
662
+ }
663
+ throw new JSONParseError({ text, cause: error });
664
+ }
665
+ }
666
+ async function safeParseJSON({
667
+ text,
668
+ schema
669
+ }) {
670
+ try {
671
+ const value = secureJsonParse(text);
672
+ if (schema == null) {
673
+ return { success: true, value, rawValue: value };
674
+ }
675
+ return await safeValidateTypes({ value, schema });
676
+ } catch (error) {
677
+ return {
678
+ success: false,
679
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }),
680
+ rawValue: void 0
681
+ };
682
+ }
683
+ }
684
+ async function parseProviderOptions({
685
+ provider,
686
+ providerOptions,
687
+ schema
688
+ }) {
689
+ if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
690
+ return void 0;
691
+ }
692
+ const parsedProviderOptions = await safeValidateTypes({
693
+ value: providerOptions[provider],
694
+ schema
695
+ });
696
+ if (!parsedProviderOptions.success) {
697
+ throw new InvalidArgumentError({
698
+ argument: "providerOptions",
699
+ message: `invalid ${provider} provider options`,
700
+ cause: parsedProviderOptions.error
701
+ });
702
+ }
703
+ return parsedProviderOptions.value;
704
+ }
705
+ var createJsonErrorResponseHandler = ({
706
+ errorSchema,
707
+ errorToMessage,
708
+ isRetryable
709
+ }) => async ({ response, url, requestBodyValues }) => {
710
+ const responseBody = await response.text();
711
+ const responseHeaders = extractResponseHeaders(response);
712
+ if (responseBody.trim() === "") {
713
+ return {
714
+ responseHeaders,
715
+ value: new APICallError({
716
+ message: response.statusText,
717
+ url,
718
+ requestBodyValues,
719
+ statusCode: response.status,
720
+ responseHeaders,
721
+ responseBody,
722
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
723
+ })
724
+ };
725
+ }
726
+ try {
727
+ const parsedError = await parseJSON({
728
+ text: responseBody,
729
+ schema: errorSchema
730
+ });
731
+ return {
732
+ responseHeaders,
733
+ value: new APICallError({
734
+ message: errorToMessage(parsedError),
735
+ url,
736
+ requestBodyValues,
737
+ statusCode: response.status,
738
+ responseHeaders,
739
+ responseBody,
740
+ data: parsedError,
741
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
742
+ })
743
+ };
744
+ } catch (parseError) {
745
+ return {
746
+ responseHeaders,
747
+ value: new APICallError({
748
+ message: response.statusText,
749
+ url,
750
+ requestBodyValues,
751
+ statusCode: response.status,
752
+ responseHeaders,
753
+ responseBody,
754
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
755
+ })
756
+ };
757
+ }
758
+ };
759
+ var ignoreOverride = Symbol(
760
+ "Let zodToJsonSchema decide on which parser to use"
761
+ );
762
+ var ALPHA_NUMERIC = new Set(
763
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
764
+ );
765
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
766
+ var { btoa, atob } = globalThis;
767
+ function convertUint8ArrayToBase64(array) {
768
+ let latin1string = "";
769
+ for (let i = 0; i < array.length; i++) {
770
+ latin1string += String.fromCodePoint(array[i]);
771
+ }
772
+ return btoa(latin1string);
773
+ }
774
+ function convertToBase64(value) {
775
+ return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;
776
+ }
777
+ function withoutTrailingSlash(url) {
778
+ return url == null ? void 0 : url.replace(/\/$/, "");
779
+ }
780
+
781
+ // src/rivet-chat-language-model.ts
782
+ var import_v43 = require("zod/v4");
783
+
784
+ // src/rivet-chat-prompt.ts
785
+ var SUPPORTED_IMAGE_MEDIA_TYPES = [
786
+ "image/jpeg",
787
+ "image/png",
788
+ "image/gif"
789
+ ];
790
+ var isSupportedImageMediaType = (mediaType) => SUPPORTED_IMAGE_MEDIA_TYPES.includes(mediaType);
791
+
792
+ // src/convert-to-rivet-chat-messages.ts
793
+ function convertToRivetChatMessages(prompt) {
794
+ const messages = [];
795
+ for (let i = 0; i < prompt.length; i++) {
796
+ const pr = prompt[i];
797
+ if (!pr) continue;
798
+ const { role, content } = pr;
799
+ switch (role) {
800
+ case "system": {
801
+ messages.push({ type: "system", message: content });
802
+ break;
803
+ }
804
+ case "user": {
805
+ messages.push({
806
+ type: "user",
807
+ message: content.map((part) => {
808
+ switch (part.type) {
809
+ case "text": {
810
+ return part.text;
811
+ }
812
+ case "file": {
813
+ if (part.mediaType.startsWith("image/")) {
814
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
815
+ if (isSupportedImageMediaType(mediaType)) {
816
+ return {
817
+ type: "url",
818
+ mediaType,
819
+ url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}`
820
+ };
821
+ } else {
822
+ throw new UnsupportedFunctionalityError({
823
+ functionality: "Invalid images mediaType"
824
+ });
825
+ }
826
+ } else {
827
+ throw new UnsupportedFunctionalityError({
828
+ functionality: "Only images and PDF file parts are supported"
829
+ });
830
+ }
831
+ }
832
+ }
833
+ })
834
+ });
835
+ break;
836
+ }
837
+ case "assistant": {
838
+ let text = "";
839
+ const toolCalls = [];
840
+ for (const part of content) {
841
+ switch (part.type) {
842
+ case "text": {
843
+ text += part.text;
844
+ break;
845
+ }
846
+ case "tool-call": {
847
+ toolCalls.push({
848
+ id: part.toolCallId,
849
+ name: part.toolName,
850
+ arguments: JSON.stringify(part.input)
851
+ });
852
+ break;
853
+ }
854
+ case "reasoning": {
855
+ text += part.text;
856
+ break;
857
+ }
858
+ default: {
859
+ throw new Error(
860
+ `Unsupported content type in assistant message: ${part.type}`
861
+ );
862
+ }
863
+ }
864
+ }
865
+ messages.push({
866
+ type: "assistant",
867
+ message: text,
868
+ function_calls: toolCalls.length > 0 ? toolCalls : void 0
869
+ });
870
+ break;
871
+ }
872
+ case "tool": {
873
+ for (const toolResponse of content) {
874
+ const output = toolResponse.output;
875
+ let contentValue;
876
+ switch (output.type) {
877
+ case "text":
878
+ case "error-text":
879
+ contentValue = output.value;
880
+ break;
881
+ case "content":
882
+ case "json":
883
+ case "error-json":
884
+ contentValue = JSON.stringify(output.value);
885
+ break;
886
+ }
887
+ messages.push({
888
+ type: "function",
889
+ message: contentValue,
890
+ name: toolResponse.toolCallId
891
+ });
892
+ }
893
+ break;
894
+ }
895
+ default: {
896
+ const _exhaustiveCheck = role;
897
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
898
+ }
899
+ }
900
+ }
901
+ return messages;
902
+ }
903
+
904
+ // src/get-response-metadata.ts
905
+ function getResponseMetadata({
906
+ id,
907
+ model,
908
+ created
909
+ }) {
910
+ return {
911
+ id: id != null ? id : void 0,
912
+ modelId: model != null ? model : void 0,
913
+ timestamp: created != null ? new Date(created * 1e3) : void 0
914
+ };
915
+ }
916
+
917
+ // src/map-rivet-finish-reason.ts
918
+ function mapRivetFinishReason(finishReason) {
919
+ switch (finishReason) {
920
+ case "stop":
921
+ return "stop";
922
+ case "length":
923
+ case "model_length":
924
+ return "length";
925
+ case "tool_calls":
926
+ return "tool-calls";
927
+ default:
928
+ return "unknown";
929
+ }
930
+ }
931
+
932
+ // src/rivet-chat-options.ts
933
+ var import_v4 = require("zod/v4");
934
+ var rivetRunParamsSchema = import_v4.z.object({
935
+ openaiApiKey: import_v4.z.string().optional(),
936
+ openaiEndpoint: import_v4.z.string().optional(),
937
+ openaiOrganization: import_v4.z.string().optional(),
938
+ exposeCost: import_v4.z.boolean().optional(),
939
+ exposeUsage: import_v4.z.boolean().optional(),
940
+ logTrace: import_v4.z.boolean().optional(),
941
+ stream: import_v4.z.string().optional(),
942
+ streamNode: import_v4.z.string().optional(),
943
+ events: import_v4.z.string().optional()
944
+ });
945
+ var standardChatConfigSchema = import_v4.z.object({
946
+ temperature: import_v4.z.number().optional(),
947
+ top_p: import_v4.z.number().optional(),
948
+ top_k: import_v4.z.number().optional(),
949
+ maxTokens: import_v4.z.number().optional(),
950
+ stop_sequences: import_v4.z.array(import_v4.z.string()).optional(),
951
+ presencePenalty: import_v4.z.number().optional(),
952
+ frequencyPenalty: import_v4.z.number().optional(),
953
+ seed: import_v4.z.number().optional(),
954
+ toolChoice: import_v4.z.enum(["none", "auto", "required", "function"]).optional(),
955
+ toolChoiceFunction: import_v4.z.string().optional(),
956
+ responseFormat: import_v4.z.enum(["", "text", "json", "json_schema"]).optional(),
957
+ responseSchemaName: import_v4.z.string().optional()
958
+ });
959
+ var rivetCustomChatConfigSchema = import_v4.z.object({
960
+ useTopP: import_v4.z.boolean().optional(),
961
+ stop: import_v4.z.string().optional(),
962
+ enableFunctionUse: import_v4.z.boolean().optional(),
963
+ user: import_v4.z.string().optional(),
964
+ numberOfChoices: import_v4.z.number().optional(),
965
+ endpoint: import_v4.z.string().optional(),
966
+ overrideModel: import_v4.z.string().optional(),
967
+ overrideMaxTokens: import_v4.z.number().optional(),
968
+ headers: import_v4.z.array(
969
+ import_v4.z.object({
970
+ key: import_v4.z.string(),
971
+ value: import_v4.z.string()
972
+ })
973
+ ).optional(),
974
+ parallelFunctionCalling: import_v4.z.boolean().optional(),
975
+ additionalParameters: import_v4.z.array(
976
+ import_v4.z.object({
977
+ key: import_v4.z.string(),
978
+ value: import_v4.z.string()
979
+ })
980
+ ).optional(),
981
+ useServerTokenCalculation: import_v4.z.boolean().optional(),
982
+ outputUsage: import_v4.z.boolean().optional(),
983
+ usePredictedOutput: import_v4.z.boolean().optional(),
984
+ reasoningEffort: import_v4.z.enum(["", "low", "medium", "high"]).optional(),
985
+ modalitiesIncludeText: import_v4.z.boolean().optional(),
986
+ modalitiesIncludeAudio: import_v4.z.boolean().optional(),
987
+ audioVoice: import_v4.z.string().optional(),
988
+ audioFormat: import_v4.z.enum(["wav", "mp3", "flac", "opus", "pcm16"]).optional()
989
+ });
990
+ var rivetLanguageModelOptions = import_v4.z.object({
991
+ runParams: rivetRunParamsSchema,
992
+ chatConfig: rivetCustomChatConfigSchema
993
+ });
994
+ var rivetChatConfigSchema = standardChatConfigSchema.merge(rivetCustomChatConfigSchema);
995
+ var rivetToolOptions = import_v4.z.record(
996
+ import_v4.z.string(),
997
+ import_v4.z.object({
998
+ //See RivetTool
999
+ name: import_v4.z.string(),
1000
+ namespace: import_v4.z.string().optional(),
1001
+ description: import_v4.z.string(),
1002
+ parameters: import_v4.z.object({}).passthrough(),
1003
+ strict: import_v4.z.boolean().optional()
1004
+ })
1005
+ );
1006
+
1007
+ // src/rivet-error.ts
1008
+ var import_v42 = require("zod/v4");
1009
+ var rivetErrorDataSchema = import_v42.z.object({
1010
+ object: import_v42.z.literal("error"),
1011
+ message: import_v42.z.string(),
1012
+ type: import_v42.z.string(),
1013
+ param: import_v42.z.string().nullable(),
1014
+ code: import_v42.z.string().nullable()
1015
+ });
1016
+ var rivetFailedResponseHandler = createJsonErrorResponseHandler({
1017
+ errorSchema: rivetErrorDataSchema,
1018
+ errorToMessage: (data) => data.message
1019
+ });
1020
+
1021
+ // src/utils.ts
1022
+ function printObject(obj) {
1023
+ const seen = /* @__PURE__ */ new WeakSet();
1024
+ return JSON.stringify(
1025
+ obj,
1026
+ (_, value) => {
1027
+ if (typeof value === "function") {
1028
+ return `[Function: ${value.name || "anonymous"}]`;
1029
+ }
1030
+ if (typeof value === "object" && value !== null) {
1031
+ if (seen.has(value)) {
1032
+ return "[Circular]";
1033
+ }
1034
+ seen.add(value);
1035
+ }
1036
+ return value;
1037
+ },
1038
+ 2
1039
+ // Indentation level for pretty-printing
1040
+ );
1041
+ }
1042
+
1043
+ // src/rivet-prepare-tools.ts
1044
+ async function prepareTools({
1045
+ tools,
1046
+ toolChoice
1047
+ }) {
1048
+ var _a15;
1049
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
1050
+ const toolWarnings = [];
1051
+ if (tools == null) {
1052
+ return { tools: void 0, toolSchemas: void 0, toolChoice: void 0, toolWarnings };
1053
+ }
1054
+ console.log(`
1055
+
1056
+ prepare tools input:${printObject(tools)}`);
1057
+ const rivetTools = [];
1058
+ const rivetSchemas = [];
1059
+ for (const tool of tools) {
1060
+ if (tool.type === "provider-defined") {
1061
+ toolWarnings.push({ type: "unsupported-tool", tool });
1062
+ } else {
1063
+ const options = (_a15 = await parseProviderOptions({
1064
+ provider: "rivet",
1065
+ providerOptions: tool.providerOptions,
1066
+ schema: rivetToolOptions
1067
+ })) != null ? _a15 : {};
1068
+ rivetTools.push({
1069
+ name: tool.name,
1070
+ description: tool.description || "",
1071
+ parameters: tool.inputSchema,
1072
+ strict: false
1073
+ });
1074
+ for (const [_, value] of Object.entries(options)) {
1075
+ rivetSchemas.push({
1076
+ name: value.name,
1077
+ description: value.description || "",
1078
+ parameters: value.parameters,
1079
+ strict: false
1080
+ });
1081
+ }
1082
+ }
1083
+ }
1084
+ console.log(`rivetSchemas:${printObject(rivetSchemas)}`);
1085
+ if (toolChoice == null) {
1086
+ return { tools: rivetTools, toolSchemas: rivetSchemas, toolChoice: void 0, toolWarnings };
1087
+ }
1088
+ const type = toolChoice.type;
1089
+ switch (type) {
1090
+ case "auto":
1091
+ case "none":
1092
+ case "required":
1093
+ return { tools: rivetTools, toolSchemas: rivetSchemas, toolChoice: { toolChoice: type }, toolWarnings };
1094
+ // Rivet toolChoice for 'tool' is called 'function',
1095
+ case "tool":
1096
+ return {
1097
+ tools: rivetTools,
1098
+ toolSchemas: rivetSchemas,
1099
+ toolChoice: { toolChoice: "function", toolChoiceFunction: toolChoice.toolName },
1100
+ toolWarnings
1101
+ };
1102
+ default: {
1103
+ const _exhaustiveCheck = type;
1104
+ throw new UnsupportedFunctionalityError({
1105
+ functionality: `tool choice type: ${_exhaustiveCheck}`
1106
+ });
1107
+ }
1108
+ }
1109
+ }
1110
+
1111
+ // src/version.ts
1112
+ var VERSION = true ? "2.0.0" : "0.0.0-test";
1113
+
1114
+ // src/post-to-api.ts
1115
+ var getOriginalFetch = () => globalThis.fetch;
1116
+ var postJsonToApi = async ({
1117
+ url,
1118
+ headers,
1119
+ body,
1120
+ failedResponseHandler,
1121
+ successfulResponseHandler,
1122
+ abortSignal,
1123
+ fetch
1124
+ }) => postToApi({
1125
+ url,
1126
+ headers: __spreadValues({
1127
+ "Content-Type": "application/json"
1128
+ }, headers),
1129
+ body: {
1130
+ content: JSON.stringify(body),
1131
+ values: body
1132
+ },
1133
+ failedResponseHandler,
1134
+ successfulResponseHandler,
1135
+ abortSignal,
1136
+ fetch
1137
+ });
1138
+ var postToApi = async ({
1139
+ url,
1140
+ headers = {},
1141
+ body,
1142
+ successfulResponseHandler,
1143
+ failedResponseHandler,
1144
+ abortSignal,
1145
+ fetch = getOriginalFetch()
1146
+ }) => {
1147
+ try {
1148
+ let bodyContent;
1149
+ if (typeof body.content === "string" || body.content instanceof FormData) {
1150
+ bodyContent = body.content;
1151
+ } else if (body.content instanceof Uint8Array) {
1152
+ bodyContent = body.content.buffer;
1153
+ } else if (body.content instanceof ArrayBuffer) {
1154
+ bodyContent = body.content;
1155
+ } else {
1156
+ throw new TypeError("Unsupported body content type");
1157
+ }
1158
+ const response = await fetch(url, {
1159
+ method: "POST",
1160
+ headers: withUserAgentSuffix(
1161
+ headers,
1162
+ `ai-sdk/provider-utils/${VERSION}`,
1163
+ getRuntimeEnvironmentUserAgent()
1164
+ ),
1165
+ body: bodyContent,
1166
+ signal: abortSignal
1167
+ });
1168
+ const responseHeaders = extractResponseHeaders(response);
1169
+ if (!response.ok) {
1170
+ let errorInformation;
1171
+ try {
1172
+ errorInformation = await failedResponseHandler({
1173
+ response,
1174
+ url,
1175
+ requestBodyValues: body.values
1176
+ });
1177
+ } catch (error) {
1178
+ if (isAbortError(error) || APICallError.isInstance(error)) {
1179
+ throw error;
1180
+ }
1181
+ throw new APICallError({
1182
+ message: "Failed to process error response",
1183
+ cause: error,
1184
+ statusCode: response.status,
1185
+ url,
1186
+ responseHeaders,
1187
+ requestBodyValues: body.values
1188
+ });
1189
+ }
1190
+ throw errorInformation.value;
1191
+ }
1192
+ try {
1193
+ return await successfulResponseHandler({
1194
+ response,
1195
+ url,
1196
+ requestBodyValues: body.values
1197
+ });
1198
+ } catch (error) {
1199
+ if (error instanceof Error) {
1200
+ if (isAbortError(error) || APICallError.isInstance(error)) {
1201
+ throw error;
1202
+ }
1203
+ }
1204
+ throw new APICallError({
1205
+ message: "Failed to process successful response",
1206
+ cause: error,
1207
+ statusCode: response.status,
1208
+ url,
1209
+ responseHeaders,
1210
+ requestBodyValues: body.values
1211
+ });
1212
+ }
1213
+ } catch (error) {
1214
+ throw handleFetchError({ error, url, requestBodyValues: body.values });
1215
+ }
1216
+ };
1217
+ var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
1218
+ function handleFetchError({
1219
+ error,
1220
+ url,
1221
+ requestBodyValues
1222
+ }) {
1223
+ if (isAbortError(error)) {
1224
+ return error;
1225
+ }
1226
+ if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
1227
+ const cause = error.cause;
1228
+ if (cause != null) {
1229
+ return new APICallError({
1230
+ message: `Cannot connect to API: ${cause.message}`,
1231
+ cause,
1232
+ url,
1233
+ requestBodyValues,
1234
+ isRetryable: true
1235
+ // retry when network error
1236
+ });
1237
+ }
1238
+ }
1239
+ return error;
1240
+ }
1241
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
1242
+ const responseHeaders = extractResponseHeaders(response);
1243
+ if (response.body == null) {
1244
+ throw new EmptyResponseBodyError({});
1245
+ }
1246
+ return {
1247
+ responseHeaders,
1248
+ value: parseJsonEventStream({
1249
+ stream: response.body,
1250
+ schema: chunkSchema
1251
+ })
1252
+ };
1253
+ };
1254
+ function parseJsonEventStream({
1255
+ stream,
1256
+ schema
1257
+ }) {
1258
+ return stream.pipeThrough(new TransformStream({
1259
+ transform(chunk, controller) {
1260
+ const decoded = new TextDecoder().decode(chunk);
1261
+ console.log(`Decoded:${printObject(decoded)}`);
1262
+ controller.enqueue(decoded);
1263
+ }
1264
+ })).pipeThrough(new EventSourceParserStream()).pipeThrough(
1265
+ new TransformStream({
1266
+ async transform({ data }, controller) {
1267
+ if (data === "[DONE]") {
1268
+ return;
1269
+ }
1270
+ console.log(`Data to schema:${printObject(data)}`);
1271
+ controller.enqueue(await safeParseJSON({ text: data, schema }));
1272
+ }
1273
+ })
1274
+ );
1275
+ }
1276
+
1277
+ // src/rivet-chat-language-model.ts
1278
+ var RivetChatLanguageModel = class {
1279
+ constructor(modelId, config) {
1280
+ this.specificationVersion = "v2";
1281
+ this.supportedUrls = {
1282
+ "application/pdf": [/^https:\/\/.*$/]
1283
+ };
1284
+ var _a15;
1285
+ this.modelId = modelId;
1286
+ this.config = config;
1287
+ this.generateId = (_a15 = config.generateId) != null ? _a15 : generateId;
1288
+ }
1289
+ get provider() {
1290
+ return this.config.provider;
1291
+ }
1292
+ // Response Schema name and content to be passed in earlier if needed
1293
+ async getArgs({
1294
+ prompt,
1295
+ //in Rivet separate
1296
+ maxOutputTokens,
1297
+ //in Rivet chat config
1298
+ temperature,
1299
+ //in Rivet chat config
1300
+ topP,
1301
+ //in Rivet chat config
1302
+ topK,
1303
+ //in Rivet chat config (some models like Anthropic and Google)
1304
+ frequencyPenalty,
1305
+ //in Rivet chat config
1306
+ presencePenalty,
1307
+ //in Rivet chat config
1308
+ stopSequences,
1309
+ //in Rivet chat config
1310
+ responseFormat,
1311
+ //in Rivet chat config
1312
+ seed,
1313
+ //in Rivet chat config
1314
+ providerOptions,
1315
+ tools,
1316
+ //in Rivet separate
1317
+ toolChoice
1318
+ //in Rivet tool section
1319
+ }) {
1320
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
1321
+ const warnings = [];
1322
+ const emptyOptions = {
1323
+ runParams: {},
1324
+ chatConfig: {}
1325
+ };
1326
+ console.log(`providerOptions:${printObject(providerOptions)}`);
1327
+ const options = (_a15 = await parseProviderOptions({
1328
+ provider: "rivet",
1329
+ providerOptions,
1330
+ schema: rivetLanguageModelOptions
1331
+ })) != null ? _a15 : emptyOptions;
1332
+ console.log(`options:${printObject(options)}`);
1333
+ const {
1334
+ tools: rivetTools,
1335
+ toolSchemas: rivetSchemas,
1336
+ toolChoice: rivetToolChoice,
1337
+ toolWarnings
1338
+ } = await prepareTools({ tools, toolChoice });
1339
+ options.runParams = (_b = options.runParams) != null ? _b : {};
1340
+ options.chatConfig = (_c = options.chatConfig) != null ? _c : {};
1341
+ const chatConfig = __spreadValues({}, options.chatConfig);
1342
+ chatConfig.maxTokens = (_d = chatConfig.maxTokens) != null ? _d : maxOutputTokens;
1343
+ chatConfig.temperature = (_e = chatConfig.temperature) != null ? _e : temperature;
1344
+ chatConfig.top_p = (_f = chatConfig.top_p) != null ? _f : topP;
1345
+ chatConfig.top_k = (_g = chatConfig.top_k) != null ? _g : topK;
1346
+ chatConfig.stop_sequences = (_h = chatConfig.stop_sequences) != null ? _h : stopSequences;
1347
+ chatConfig.frequencyPenalty = (_i = chatConfig.frequencyPenalty) != null ? _i : frequencyPenalty;
1348
+ chatConfig.presencePenalty = (_j = chatConfig.presencePenalty) != null ? _j : presencePenalty;
1349
+ chatConfig.seed = (_k = chatConfig.seed) != null ? _k : seed;
1350
+ if (responseFormat) {
1351
+ const isJson = (responseFormat == null ? void 0 : responseFormat.type) === "json";
1352
+ const hasSchema = isJson && !!(responseFormat == null ? void 0 : responseFormat.schema);
1353
+ chatConfig.responseFormat = isJson ? hasSchema ? "json_schema" : "json" : responseFormat == null ? void 0 : responseFormat.type;
1354
+ chatConfig.responseSchemaName = isJson && hasSchema ? responseFormat.schema : void 0;
1355
+ }
1356
+ if (rivetToolChoice) {
1357
+ chatConfig.toolChoice = rivetToolChoice.toolChoice;
1358
+ chatConfig.toolChoiceFunction = rivetToolChoice.toolChoiceFunction;
1359
+ }
1360
+ const messages = convertToRivetChatMessages(prompt);
1361
+ return {
1362
+ args: {
1363
+ chatConfig: {
1364
+ type: "object",
1365
+ value: chatConfig
1366
+ },
1367
+ input: {
1368
+ //assign chat messages to the input node
1369
+ type: "chat-message[]",
1370
+ value: messages
1371
+ },
1372
+ tools: {
1373
+ type: "gpt-function[]",
1374
+ value: rivetTools
1375
+ },
1376
+ toolSchemas: {
1377
+ type: "gpt-function[]",
1378
+ value: rivetSchemas
1379
+ },
1380
+ runParams: __spreadValues({}, options.runParams)
1381
+ },
1382
+ warnings: [...warnings, ...toolWarnings]
1383
+ };
1384
+ }
1385
+ async doGenerate(options) {
1386
+ const { args: body, warnings } = await this.getArgs(options);
1387
+ const headers = combineHeaders(this.config.headers(), options.headers);
1388
+ let responseId = headers["X-Completion-Id"];
1389
+ responseId = responseId != null ? responseId : this.generateId();
1390
+ const {
1391
+ responseHeaders,
1392
+ value: response,
1393
+ rawValue: rawResponse
1394
+ } = await postJsonToApi({
1395
+ url: `${this.config.baseURL}/${this.modelId}`,
1396
+ headers,
1397
+ body,
1398
+ failedResponseHandler: rivetFailedResponseHandler,
1399
+ successfulResponseHandler: rivetChatResponseHandler(`rivetcmpl-${responseId}`, this.modelId),
1400
+ abortSignal: options.abortSignal,
1401
+ fetch: this.config.fetch
1402
+ });
1403
+ const choice = response.choices[0];
1404
+ if (!choice) {
1405
+ throw new Error("No choices found");
1406
+ }
1407
+ const content = [];
1408
+ if (choice.message.content != null && Array.isArray(choice.message.content)) {
1409
+ for (const part of choice.message.content) {
1410
+ if (part.type === "thinking") {
1411
+ const reasoningText = extractReasoningContent(part.thinking);
1412
+ if (reasoningText.length > 0) {
1413
+ content.push({ type: "reasoning", text: reasoningText });
1414
+ }
1415
+ } else if (part.type === "text") {
1416
+ if (part.text.length > 0) {
1417
+ content.push({ type: "text", text: part.text });
1418
+ }
1419
+ }
1420
+ }
1421
+ } else {
1422
+ const text = extractTextContent(choice.message.content);
1423
+ if (text != null && text.length > 0) {
1424
+ content.push({ type: "text", text });
1425
+ }
1426
+ }
1427
+ if (choice.message.tool_calls != null) {
1428
+ for (const toolCall of choice.message.tool_calls) {
1429
+ content.push({
1430
+ type: "tool-call",
1431
+ toolCallId: toolCall.id,
1432
+ toolName: toolCall.function.name,
1433
+ input: toolCall.function.arguments
1434
+ });
1435
+ }
1436
+ }
1437
+ return {
1438
+ content,
1439
+ finishReason: mapRivetFinishReason(choice.finish_reason),
1440
+ usage: {
1441
+ inputTokens: response.usage.prompt_tokens,
1442
+ outputTokens: response.usage.completion_tokens,
1443
+ totalTokens: response.usage.total_tokens
1444
+ },
1445
+ request: { body },
1446
+ response: __spreadProps(__spreadValues({}, getResponseMetadata(response)), {
1447
+ headers: responseHeaders,
1448
+ body: rawResponse
1449
+ }),
1450
+ warnings
1451
+ };
1452
+ }
1453
+ async doStream(options) {
1454
+ var _a15;
1455
+ const { args, warnings } = await this.getArgs(options);
1456
+ const body = args;
1457
+ console.log(`body:${printObject(body)}`);
1458
+ const headers = combineHeaders(this.config.headers(), options.headers);
1459
+ let responseId = (_a15 = headers["X-Completion-Id"]) != null ? _a15 : this.generateId();
1460
+ const model = this.modelId;
1461
+ const { responseHeaders, value: response } = await postJsonToApi({
1462
+ url: `${this.config.baseURL}/${this.modelId}`,
1463
+ headers,
1464
+ body,
1465
+ failedResponseHandler: rivetFailedResponseHandler,
1466
+ successfulResponseHandler: createRivetEventSourceResponseHandler(`rivetcmpl-${responseId}`, model),
1467
+ abortSignal: options.abortSignal,
1468
+ fetch: this.config.fetch
1469
+ });
1470
+ let finishReason = "unknown";
1471
+ const usage = {
1472
+ inputTokens: void 0,
1473
+ outputTokens: void 0,
1474
+ totalTokens: void 0
1475
+ };
1476
+ let isFirstChunk = true;
1477
+ let activeText = false;
1478
+ let activeReasoningId = null;
1479
+ const generateId2 = this.generateId;
1480
+ return {
1481
+ stream: response.pipeThrough(
1482
+ new TransformStream({
1483
+ start(controller) {
1484
+ controller.enqueue({ type: "stream-start", warnings });
1485
+ },
1486
+ transform(chunk, controller) {
1487
+ if (options.includeRawChunks) {
1488
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1489
+ }
1490
+ if (!chunk.success) {
1491
+ controller.enqueue({ type: "error", error: chunk.error });
1492
+ return;
1493
+ }
1494
+ const value = chunk.value;
1495
+ if (isFirstChunk) {
1496
+ isFirstChunk = false;
1497
+ controller.enqueue(__spreadValues({
1498
+ type: "response-metadata"
1499
+ }, getResponseMetadata(value)));
1500
+ }
1501
+ if (value.usage != null) {
1502
+ usage.inputTokens = value.usage.prompt_tokens;
1503
+ usage.outputTokens = value.usage.completion_tokens;
1504
+ usage.totalTokens = value.usage.total_tokens;
1505
+ }
1506
+ const choice = value.choices[0];
1507
+ if (!choice) {
1508
+ throw new Error("No choices found");
1509
+ }
1510
+ const delta = choice.delta;
1511
+ const textContent = extractTextContent(delta.content);
1512
+ if (delta.content != null && Array.isArray(delta.content)) {
1513
+ for (const part of delta.content) {
1514
+ if (part.type === "thinking") {
1515
+ const reasoningDelta = extractReasoningContent(part.thinking);
1516
+ if (reasoningDelta.length > 0) {
1517
+ if (activeReasoningId == null) {
1518
+ if (activeText) {
1519
+ controller.enqueue({ type: "text-end", id: "0" });
1520
+ activeText = false;
1521
+ }
1522
+ activeReasoningId = generateId2();
1523
+ controller.enqueue({
1524
+ type: "reasoning-start",
1525
+ id: activeReasoningId
1526
+ });
1527
+ }
1528
+ controller.enqueue({
1529
+ type: "reasoning-delta",
1530
+ id: activeReasoningId,
1531
+ delta: reasoningDelta
1532
+ });
1533
+ }
1534
+ }
1535
+ }
1536
+ }
1537
+ if (textContent != null && textContent.length > 0) {
1538
+ if (!activeText) {
1539
+ if (activeReasoningId != null) {
1540
+ controller.enqueue({
1541
+ type: "reasoning-end",
1542
+ id: activeReasoningId
1543
+ });
1544
+ activeReasoningId = null;
1545
+ }
1546
+ controller.enqueue({ type: "text-start", id: "0" });
1547
+ activeText = true;
1548
+ }
1549
+ controller.enqueue({
1550
+ type: "text-delta",
1551
+ id: "0",
1552
+ delta: textContent
1553
+ });
1554
+ }
1555
+ if ((delta == null ? void 0 : delta.tool_calls) != null) {
1556
+ for (const toolCall of delta.tool_calls) {
1557
+ const toolCallId = toolCall.id;
1558
+ const toolName = toolCall.function.name;
1559
+ const input = toolCall.function.arguments;
1560
+ controller.enqueue({
1561
+ type: "tool-input-start",
1562
+ id: toolCallId,
1563
+ toolName
1564
+ });
1565
+ controller.enqueue({
1566
+ type: "tool-input-delta",
1567
+ id: toolCallId,
1568
+ delta: input
1569
+ });
1570
+ controller.enqueue({
1571
+ type: "tool-input-end",
1572
+ id: toolCallId
1573
+ });
1574
+ controller.enqueue({
1575
+ type: "tool-call",
1576
+ toolCallId,
1577
+ toolName,
1578
+ input
1579
+ });
1580
+ }
1581
+ }
1582
+ if (choice.finish_reason != null) {
1583
+ finishReason = mapRivetFinishReason(choice.finish_reason);
1584
+ }
1585
+ },
1586
+ flush(controller) {
1587
+ if (activeReasoningId != null) {
1588
+ controller.enqueue({
1589
+ type: "reasoning-end",
1590
+ id: activeReasoningId
1591
+ });
1592
+ }
1593
+ if (activeText) {
1594
+ controller.enqueue({ type: "text-end", id: "0" });
1595
+ }
1596
+ controller.enqueue({
1597
+ type: "finish",
1598
+ finishReason,
1599
+ usage
1600
+ });
1601
+ }
1602
+ })
1603
+ ),
1604
+ request: { body },
1605
+ response: { headers: responseHeaders }
1606
+ };
1607
+ }
1608
+ };
1609
+ function extractReasoningContent(thinking) {
1610
+ return thinking.filter((chunk) => chunk.type === "text").map((chunk) => chunk.text).join("");
1611
+ }
1612
+ function extractTextContent(content) {
1613
+ if (typeof content === "string") {
1614
+ return content;
1615
+ }
1616
+ if (content == null) {
1617
+ return void 0;
1618
+ }
1619
+ const textContent = [];
1620
+ for (const chunk of content) {
1621
+ const { type } = chunk;
1622
+ switch (type) {
1623
+ case "text":
1624
+ textContent.push(chunk.text);
1625
+ break;
1626
+ case "thinking":
1627
+ case "image_url":
1628
+ case "reference":
1629
+ break;
1630
+ default: {
1631
+ const _exhaustiveCheck = type;
1632
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
1633
+ }
1634
+ }
1635
+ }
1636
+ return textContent.length ? textContent.join("") : void 0;
1637
+ }
1638
+ var rivetContentSchema = import_v43.z.union([
1639
+ import_v43.z.string(),
1640
+ import_v43.z.array(
1641
+ import_v43.z.discriminatedUnion("type", [
1642
+ import_v43.z.object({
1643
+ type: import_v43.z.literal("text"),
1644
+ text: import_v43.z.string()
1645
+ }),
1646
+ import_v43.z.object({
1647
+ type: import_v43.z.literal("image_url"),
1648
+ image_url: import_v43.z.union([
1649
+ import_v43.z.string(),
1650
+ import_v43.z.object({
1651
+ url: import_v43.z.string(),
1652
+ detail: import_v43.z.string().nullable()
1653
+ })
1654
+ ])
1655
+ }),
1656
+ import_v43.z.object({
1657
+ type: import_v43.z.literal("reference"),
1658
+ reference_ids: import_v43.z.array(import_v43.z.number())
1659
+ }),
1660
+ import_v43.z.object({
1661
+ type: import_v43.z.literal("thinking"),
1662
+ thinking: import_v43.z.array(
1663
+ import_v43.z.object({
1664
+ type: import_v43.z.literal("text"),
1665
+ text: import_v43.z.string()
1666
+ })
1667
+ )
1668
+ })
1669
+ ])
1670
+ )
1671
+ ]).nullish();
1672
+ var rivetUsageSchema = import_v43.z.object({
1673
+ prompt_tokens: import_v43.z.number(),
1674
+ completion_tokens: import_v43.z.number(),
1675
+ total_tokens: import_v43.z.number()
1676
+ });
1677
+ var rivetChatResponseSchema = import_v43.z.object({
1678
+ id: import_v43.z.string().nullish(),
1679
+ created: import_v43.z.number().nullish(),
1680
+ model: import_v43.z.string().nullish(),
1681
+ choices: import_v43.z.array(
1682
+ import_v43.z.object({
1683
+ message: import_v43.z.object({
1684
+ role: import_v43.z.literal("assistant"),
1685
+ content: rivetContentSchema,
1686
+ tool_calls: import_v43.z.array(
1687
+ import_v43.z.object({
1688
+ id: import_v43.z.string(),
1689
+ function: import_v43.z.object({ name: import_v43.z.string(), arguments: import_v43.z.string() })
1690
+ })
1691
+ ).nullish()
1692
+ }),
1693
+ index: import_v43.z.number(),
1694
+ finish_reason: import_v43.z.string().nullish()
1695
+ })
1696
+ ),
1697
+ object: import_v43.z.literal("chat.completion"),
1698
+ usage: rivetUsageSchema
1699
+ });
1700
+ var rivetChatResponseHandler = (id, model) => async ({
1701
+ url,
1702
+ requestBodyValues,
1703
+ response
1704
+ }) => {
1705
+ const raw = await response.json();
1706
+ const mapped = mapGraphOutputsToSDK(raw, id, model);
1707
+ return {
1708
+ value: rivetChatResponseSchema.parse(mapped)
1709
+ };
1710
+ };
1711
+ function mapGraphOutputsToSDK(outputs, id, model) {
1712
+ var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j;
1713
+ return {
1714
+ id,
1715
+ created: Date.now(),
1716
+ model,
1717
+ object: "chat.completion",
1718
+ choices: [
1719
+ {
1720
+ message: {
1721
+ role: "assistant",
1722
+ content: (_b = (_a15 = outputs.output) == null ? void 0 : _a15.value) != null ? _b : ""
1723
+ },
1724
+ index: 0,
1725
+ finish_reason: "stop"
1726
+ }
1727
+ ],
1728
+ usage: {
1729
+ prompt_tokens: (_d = (_c = outputs.requestTokens) == null ? void 0 : _c.value) != null ? _d : 0,
1730
+ completion_tokens: (_f = (_e = outputs.responseTokens) == null ? void 0 : _e.value) != null ? _f : 0,
1731
+ total_tokens: ((_h = (_g = outputs.requestTokens) == null ? void 0 : _g.value) != null ? _h : 0) + ((_j = (_i = outputs.responseTokens) == null ? void 0 : _i.value) != null ? _j : 0)
1732
+ }
1733
+ };
1734
+ }
1735
+ var rivetChatChunkSchema = import_v43.z.object({
1736
+ id: import_v43.z.string().nullish(),
1737
+ created: import_v43.z.number().nullish(),
1738
+ model: import_v43.z.string().nullish(),
1739
+ choices: import_v43.z.array(
1740
+ import_v43.z.object({
1741
+ delta: import_v43.z.object({
1742
+ role: import_v43.z.enum(["assistant"]).optional(),
1743
+ content: rivetContentSchema,
1744
+ tool_calls: import_v43.z.array(
1745
+ import_v43.z.object({
1746
+ id: import_v43.z.string(),
1747
+ function: import_v43.z.object({ name: import_v43.z.string(), arguments: import_v43.z.string() })
1748
+ })
1749
+ ).nullish()
1750
+ }),
1751
+ finish_reason: import_v43.z.string().nullish(),
1752
+ index: import_v43.z.number()
1753
+ })
1754
+ ),
1755
+ usage: rivetUsageSchema.nullish()
1756
+ });
1757
+ function createRivetEventSourceResponseHandler(id, model) {
1758
+ return createEventSourceResponseHandler(import_v43.z.any().transform((data) => {
1759
+ console.log(`SSE event received:${printObject(data)}`);
1760
+ return mapRivetEventToOpenAIChunk(data, id, model);
1761
+ }));
1762
+ }
1763
+ function mapRivetEventToOpenAIChunk(eventData, id, model) {
1764
+ var _a15, _b, _c, _d, _e, _f, _g;
1765
+ const eventType = eventData.type;
1766
+ switch (eventType) {
1767
+ case "partialOutput":
1768
+ return {
1769
+ id,
1770
+ created: Math.floor(Date.now() / 1e3),
1771
+ model,
1772
+ choices: [
1773
+ {
1774
+ delta: {
1775
+ role: "assistant",
1776
+ content: (_a15 = eventData.delta) != null ? _a15 : "",
1777
+ tool_calls: void 0
1778
+ },
1779
+ finish_reason: null,
1780
+ index: 0
1781
+ }
1782
+ ],
1783
+ usage: void 0
1784
+ };
1785
+ case "done":
1786
+ return {
1787
+ id,
1788
+ created: Math.floor(Date.now() / 1e3),
1789
+ model,
1790
+ choices: [
1791
+ {
1792
+ delta: {
1793
+ role: "assistant",
1794
+ content: (_d = (_c = (_b = eventData.graphOutput) == null ? void 0 : _b.response) == null ? void 0 : _c.value) != null ? _d : "",
1795
+ tool_calls: void 0
1796
+ },
1797
+ finish_reason: "stop",
1798
+ index: 0
1799
+ }
1800
+ ],
1801
+ usage: toOpenAIUsage((_g = (_f = (_e = eventData.graphOutput.usages) == null ? void 0 : _e.value) == null ? void 0 : _f[0]) == null ? void 0 : _g.value)
1802
+ };
1803
+ default:
1804
+ return {
1805
+ id,
1806
+ created: Math.floor(Date.now() / 1e3),
1807
+ model,
1808
+ choices: [
1809
+ {
1810
+ delta: {
1811
+ role: "assistant",
1812
+ content: "",
1813
+ tool_calls: void 0
1814
+ },
1815
+ finish_reason: null,
1816
+ index: 0
1817
+ }
1818
+ ],
1819
+ usage: void 0
1820
+ };
1821
+ }
1822
+ }
1823
+ var toOpenAIUsage = (usage) => {
1824
+ console.log(`Usage to convert:${printObject(usage)}`);
1825
+ return usage ? {
1826
+ prompt_tokens: usage.prompt_tokens,
1827
+ completion_tokens: usage.completion_tokens,
1828
+ total_tokens: usage.total_tokens
1829
+ } : void 0;
1830
+ };
1831
+
1832
+ // src/rivet-provider.ts
1833
+ function createRivet(options = {}) {
1834
+ var _a15;
1835
+ const baseURL = (_a15 = withoutTrailingSlash(options.baseURL)) != null ? _a15 : "https://api.rivet.ai/v1";
1836
+ const getHeaders = () => withUserAgentSuffix(
1837
+ __spreadValues({
1838
+ Authorization: `Bearer ${loadApiKey({
1839
+ apiKey: options.apiKey,
1840
+ environmentVariableName: "RIVET_API_KEY",
1841
+ description: "Rivet"
1842
+ })}`
1843
+ }, options.headers),
1844
+ `ai-sdk/rivet/${VERSION}`
1845
+ );
1846
+ const createChatModel = (modelId) => new RivetChatLanguageModel(modelId, {
1847
+ provider: "rivet.chat",
1848
+ baseURL,
1849
+ headers: getHeaders,
1850
+ fetch: options.fetch,
1851
+ generateId: options.generateId
1852
+ });
1853
+ const provider = function(modelId) {
1854
+ if (new.target) {
1855
+ throw new Error("The Rivet model function cannot be called with the new keyword.");
1856
+ }
1857
+ return createChatModel(modelId);
1858
+ };
1859
+ provider.languageModel = createChatModel;
1860
+ provider.chat = createChatModel;
1861
+ provider.textEmbeddingModel = (modelId) => {
1862
+ throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
1863
+ };
1864
+ provider.imageModel = (modelId) => {
1865
+ throw new NoSuchModelError({ modelId, modelType: "imageModel" });
1866
+ };
1867
+ return provider;
1868
+ }
1869
+ var rivet = createRivet();
1870
+ // Annotate the CommonJS export names for ESM import in node:
1871
+ 0 && (module.exports = {
1872
+ VERSION,
1873
+ createRivet,
1874
+ rivet
1875
+ });
1876
+ //# sourceMappingURL=index.js.map