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