@ai-sdk/replicate 3.0.51 → 3.0.53

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 CHANGED
@@ -1,652 +1,502 @@
1
- // src/replicate-provider.ts
2
- import {
3
- NoSuchModelError
4
- } from "@ai-sdk/provider";
5
- import {
6
- loadApiKey,
7
- validateBaseURL,
8
- withoutTrailingSlash,
9
- withUserAgentSuffix
10
- } from "@ai-sdk/provider-utils";
11
-
12
- // src/replicate-image-model.ts
13
- import {
14
- InvalidResponseDataError
15
- } from "@ai-sdk/provider";
16
- import {
17
- combineHeaders,
18
- convertImageModelFileToDataUri,
19
- createBinaryResponseHandler,
20
- createJsonResponseHandler,
21
- delay,
22
- getFromApi,
23
- parseProviderOptions,
24
- postJsonToApi,
25
- resolve,
26
- serializeModelOptions,
27
- WORKFLOW_SERIALIZE,
28
- WORKFLOW_DESERIALIZE
29
- } from "@ai-sdk/provider-utils";
30
- import { z as z3 } from "zod/v4";
31
-
32
- // src/replicate-error.ts
33
- import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
1
+ import { AISDKError, InvalidResponseDataError, NoSuchModelError } from "@ai-sdk/provider";
2
+ import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, combineHeaders, convertImageModelFileToDataUri, createBinaryResponseHandler, createJsonErrorResponseHandler, createJsonResponseHandler, delay, getFromApi, lazySchema, loadApiKey, parseProviderOptions, postJsonToApi, resolve, serializeModelOptions, validateBaseURL, withUserAgentSuffix, withoutTrailingSlash, zodSchema } from "@ai-sdk/provider-utils";
34
3
  import { z } from "zod/v4";
35
- var replicateErrorSchema = z.object({
36
- detail: z.string().optional(),
37
- error: z.string().optional()
4
+ //#region src/replicate-error.ts
5
+ const replicateErrorSchema = z.object({
6
+ detail: z.string().optional(),
7
+ error: z.string().optional()
38
8
  });
39
- var replicateFailedResponseHandler = createJsonErrorResponseHandler({
40
- errorSchema: replicateErrorSchema,
41
- errorToMessage: (error) => error.detail ?? error.error ?? "Unknown Replicate error"
9
+ const replicateFailedResponseHandler = createJsonErrorResponseHandler({
10
+ errorSchema: replicateErrorSchema,
11
+ errorToMessage: (error) => error.detail ?? error.error ?? "Unknown Replicate error"
42
12
  });
43
-
44
- // src/replicate-image-model-options.ts
45
- import {
46
- lazySchema,
47
- zodSchema
48
- } from "@ai-sdk/provider-utils";
49
- import { z as z2 } from "zod/v4";
50
- var replicateImageModelOptionsSchema = lazySchema(
51
- () => zodSchema(
52
- z2.looseObject({
53
- /**
54
- * Maximum time in seconds to wait for the prediction to complete in sync mode.
55
- * By default, Replicate uses sync mode with a 60-second timeout.
56
- *
57
- * - When not specified: Uses default 60-second sync wait (`prefer: wait`)
58
- * - When set to a positive number: Uses that duration (`prefer: wait=N`)
59
- */
60
- maxWaitTimeInSeconds: z2.number().positive().nullish(),
61
- /**
62
- * Interval in milliseconds between polling attempts when the prediction
63
- * does not complete within the synchronous wait duration.
64
- * Defaults to 500 milliseconds.
65
- */
66
- pollIntervalMillis: z2.number().int().positive().nullish(),
67
- /**
68
- * Maximum number of polling attempts before giving up.
69
- * Defaults to 240 attempts.
70
- */
71
- maxPollAttempts: z2.number().int().positive().nullish(),
72
- /**
73
- * Guidance scale for classifier-free guidance.
74
- * Higher values make the output more closely match the prompt.
75
- */
76
- guidance_scale: z2.number().nullish(),
77
- /**
78
- * Number of denoising steps. More steps = higher quality but slower.
79
- */
80
- num_inference_steps: z2.number().nullish(),
81
- /**
82
- * Negative prompt to guide what to avoid in the generation.
83
- */
84
- negative_prompt: z2.string().nullish(),
85
- /**
86
- * Output image format.
87
- */
88
- output_format: z2.enum(["png", "jpg", "webp"]).nullish(),
89
- /**
90
- * Output image quality (1-100). Only applies to jpg and webp.
91
- */
92
- output_quality: z2.number().min(1).max(100).nullish(),
93
- /**
94
- * Strength of the transformation for img2img (0-1).
95
- * Lower values keep more of the original image.
96
- */
97
- strength: z2.number().min(0).max(1).nullish()
98
- })
99
- )
100
- );
101
-
102
- // src/replicate-image-model.ts
103
- var DEFAULT_POLL_INTERVAL_MILLIS = 500;
104
- var DEFAULT_MAX_POLL_ATTEMPTS = 240;
105
- var FLUX_2_MODEL_PATTERN = /^black-forest-labs\/flux-2-/;
106
- var MAX_FLUX_2_INPUT_IMAGES = 8;
107
- var ReplicateImageModel = class _ReplicateImageModel {
108
- constructor(modelId, config) {
109
- this.modelId = modelId;
110
- this.config = config;
111
- this.specificationVersion = "v4";
112
- }
113
- get maxImagesPerCall() {
114
- return this.isFlux2Model ? MAX_FLUX_2_INPUT_IMAGES : 1;
115
- }
116
- get supportsFileInputs() {
117
- if (this.modelId === "black-forest-labs/flux-2-pro" || this.modelId === "black-forest-labs/flux-2-dev" || this.modelId === "black-forest-labs/flux-fill-pro" || this.modelId === "black-forest-labs/flux-fill-dev") {
118
- return true;
119
- }
120
- return void 0;
121
- }
122
- get supportsMaskInputs() {
123
- if (this.modelId === "black-forest-labs/flux-fill-pro" || this.modelId === "black-forest-labs/flux-fill-dev") {
124
- return true;
125
- }
126
- return this.supportsFileInputs === true ? false : void 0;
127
- }
128
- get provider() {
129
- return this.config.provider;
130
- }
131
- get isFlux2Model() {
132
- return FLUX_2_MODEL_PATTERN.test(this.modelId);
133
- }
134
- static [WORKFLOW_SERIALIZE](model) {
135
- return serializeModelOptions({
136
- modelId: model.modelId,
137
- config: model.config
138
- });
139
- }
140
- static [WORKFLOW_DESERIALIZE](options) {
141
- return new _ReplicateImageModel(options.modelId, options.config);
142
- }
143
- async doGenerate({
144
- prompt,
145
- n,
146
- aspectRatio,
147
- size,
148
- seed,
149
- providerOptions,
150
- headers,
151
- abortSignal,
152
- files,
153
- mask
154
- }) {
155
- const warnings = [];
156
- const [modelId, version] = this.modelId.split(":");
157
- const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
158
- const replicateOptions = await parseProviderOptions({
159
- provider: "replicate",
160
- providerOptions,
161
- schema: replicateImageModelOptionsSchema
162
- });
163
- let imageInputs = {};
164
- if (files != null && files.length > 0) {
165
- if (this.isFlux2Model) {
166
- for (let i = 0; i < Math.min(files.length, MAX_FLUX_2_INPUT_IMAGES); i++) {
167
- const key = i === 0 ? "input_image" : `input_image_${i + 1}`;
168
- imageInputs[key] = convertImageModelFileToDataUri(files[i]);
169
- }
170
- if (files.length > MAX_FLUX_2_INPUT_IMAGES) {
171
- warnings.push({
172
- type: "other",
173
- message: `Flux-2 models support up to ${MAX_FLUX_2_INPUT_IMAGES} input images. Additional images are ignored.`
174
- });
175
- }
176
- } else {
177
- imageInputs = { image: convertImageModelFileToDataUri(files[0]) };
178
- if (files.length > 1) {
179
- warnings.push({
180
- type: "other",
181
- message: "This Replicate model only supports a single input image. Additional images are ignored."
182
- });
183
- }
184
- }
185
- }
186
- let maskInput;
187
- if (mask != null) {
188
- if (this.isFlux2Model) {
189
- warnings.push({
190
- type: "other",
191
- message: "Flux-2 models do not support mask input. The mask will be ignored."
192
- });
193
- } else {
194
- maskInput = convertImageModelFileToDataUri(mask);
195
- }
196
- }
197
- const {
198
- maxWaitTimeInSeconds,
199
- pollIntervalMillis = DEFAULT_POLL_INTERVAL_MILLIS,
200
- maxPollAttempts = DEFAULT_MAX_POLL_ATTEMPTS,
201
- ...inputOptions
202
- } = replicateOptions ?? {};
203
- const preferHeader = maxWaitTimeInSeconds != null ? { prefer: `wait=${maxWaitTimeInSeconds}` } : { prefer: "wait" };
204
- const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
205
- const { value: initialPrediction, responseHeaders } = await postJsonToApi({
206
- url: (
207
- // different endpoints for versioned vs unversioned models:
208
- version != null ? `${this.config.baseURL}/predictions` : `${this.config.baseURL}/models/${modelId}/predictions`
209
- ),
210
- headers: combineHeaders(resolvedHeaders, headers, preferHeader),
211
- body: {
212
- input: {
213
- prompt,
214
- aspect_ratio: aspectRatio,
215
- size,
216
- seed,
217
- num_outputs: n,
218
- ...imageInputs,
219
- ...maskInput != null ? { mask: maskInput } : {},
220
- ...inputOptions
221
- },
222
- // for versioned models, include the version in the body:
223
- ...version != null ? { version } : {}
224
- },
225
- successfulResponseHandler: createJsonResponseHandler(
226
- replicateImageResponseSchema
227
- ),
228
- failedResponseHandler: replicateFailedResponseHandler,
229
- abortSignal,
230
- fetch: this.config.fetch
231
- });
232
- const prediction = await this.pollPrediction({
233
- prediction: initialPrediction,
234
- headers: combineHeaders(resolvedHeaders, headers),
235
- pollIntervalMillis: pollIntervalMillis ?? DEFAULT_POLL_INTERVAL_MILLIS,
236
- maxPollAttempts: maxPollAttempts ?? DEFAULT_MAX_POLL_ATTEMPTS,
237
- abortSignal
238
- });
239
- if (prediction.output == null) {
240
- throw new InvalidResponseDataError({
241
- data: prediction,
242
- message: "Replicate image generation completed without output."
243
- });
244
- }
245
- const outputArray = Array.isArray(prediction.output) ? prediction.output : [prediction.output];
246
- const images = await Promise.all(
247
- outputArray.map(async (url) => {
248
- const { value: image } = await getFromApi({
249
- url,
250
- // url is an output image URL from the provider response; validate it.
251
- validateUrl: true,
252
- trustedOrigin: this.config.baseURL,
253
- successfulResponseHandler: createBinaryResponseHandler(),
254
- failedResponseHandler: replicateFailedResponseHandler,
255
- abortSignal,
256
- fetch: this.config.fetch
257
- });
258
- return image;
259
- })
260
- );
261
- return {
262
- images,
263
- warnings,
264
- response: {
265
- timestamp: currentDate,
266
- modelId: this.modelId,
267
- headers: responseHeaders
268
- }
269
- };
270
- }
271
- async pollPrediction({
272
- prediction,
273
- headers,
274
- pollIntervalMillis,
275
- maxPollAttempts,
276
- abortSignal
277
- }) {
278
- let currentPrediction = prediction;
279
- for (let i = 0; i < maxPollAttempts; i++) {
280
- const completedPrediction2 = this.getCompletedPrediction(currentPrediction);
281
- if (completedPrediction2 != null) {
282
- return completedPrediction2;
283
- }
284
- const { value } = await getFromApi({
285
- url: currentPrediction.urls.get,
286
- validateUrl: true,
287
- credentialedOrigin: this.config.baseURL,
288
- trustedOrigin: this.config.baseURL,
289
- headers,
290
- successfulResponseHandler: createJsonResponseHandler(
291
- replicateImageResponseSchema
292
- ),
293
- failedResponseHandler: replicateFailedResponseHandler,
294
- abortSignal,
295
- fetch: this.config.fetch
296
- });
297
- currentPrediction = value;
298
- if (i < maxPollAttempts - 1) {
299
- await delay(pollIntervalMillis, { abortSignal });
300
- }
301
- }
302
- const completedPrediction = this.getCompletedPrediction(currentPrediction);
303
- if (completedPrediction != null) {
304
- return completedPrediction;
305
- }
306
- throw new Error(
307
- `Replicate image generation did not complete after ${maxPollAttempts} polling attempts.`
308
- );
309
- }
310
- getCompletedPrediction(prediction) {
311
- if (prediction.status === "failed" || prediction.status === "canceled") {
312
- throw new InvalidResponseDataError({
313
- data: prediction,
314
- message: `Replicate image generation ${prediction.status}: ${prediction.error ?? "Unknown error"}`
315
- });
316
- }
317
- if (prediction.output != null || prediction.status === "succeeded") {
318
- return prediction;
319
- }
320
- }
13
+ //#endregion
14
+ //#region src/replicate-image-model-options.ts
15
+ /**
16
+ * Provider options schema for Replicate image generation.
17
+ *
18
+ * Note: Different Replicate models support different parameters.
19
+ * This schema includes common parameters, but you can pass any
20
+ * model-specific parameters through the passthrough.
21
+ */
22
+ const replicateImageModelOptionsSchema = lazySchema(() => zodSchema(z.looseObject({
23
+ /**
24
+ * Maximum time in seconds to wait for the prediction to complete in sync mode.
25
+ * By default, Replicate uses sync mode with a 60-second timeout.
26
+ *
27
+ * - When not specified: Uses default 60-second sync wait (`prefer: wait`)
28
+ * - When set to a positive number: Uses that duration (`prefer: wait=N`)
29
+ */
30
+ maxWaitTimeInSeconds: z.number().positive().nullish(),
31
+ /**
32
+ * Interval in milliseconds between polling attempts when the prediction
33
+ * does not complete within the synchronous wait duration.
34
+ * Defaults to 500 milliseconds.
35
+ */
36
+ pollIntervalMillis: z.number().int().positive().nullish(),
37
+ /**
38
+ * Maximum number of polling attempts before giving up.
39
+ * Defaults to 240 attempts.
40
+ */
41
+ maxPollAttempts: z.number().int().positive().nullish(),
42
+ /**
43
+ * Guidance scale for classifier-free guidance.
44
+ * Higher values make the output more closely match the prompt.
45
+ */
46
+ guidance_scale: z.number().nullish(),
47
+ /**
48
+ * Number of denoising steps. More steps = higher quality but slower.
49
+ */
50
+ num_inference_steps: z.number().nullish(),
51
+ /**
52
+ * Negative prompt to guide what to avoid in the generation.
53
+ */
54
+ negative_prompt: z.string().nullish(),
55
+ /**
56
+ * Output image format.
57
+ */
58
+ output_format: z.enum([
59
+ "png",
60
+ "jpg",
61
+ "webp"
62
+ ]).nullish(),
63
+ /**
64
+ * Output image quality (1-100). Only applies to jpg and webp.
65
+ */
66
+ output_quality: z.number().min(1).max(100).nullish(),
67
+ /**
68
+ * Strength of the transformation for img2img (0-1).
69
+ * Lower values keep more of the original image.
70
+ */
71
+ strength: z.number().min(0).max(1).nullish()
72
+ })));
73
+ //#endregion
74
+ //#region src/replicate-image-model.ts
75
+ const DEFAULT_POLL_INTERVAL_MILLIS = 500;
76
+ const DEFAULT_MAX_POLL_ATTEMPTS = 240;
77
+ const FLUX_2_MODEL_PATTERN = /^black-forest-labs\/flux-2-/;
78
+ const MAX_FLUX_2_INPUT_IMAGES = 8;
79
+ var ReplicateImageModel = class ReplicateImageModel {
80
+ get maxImagesPerCall() {
81
+ return this.isFlux2Model ? MAX_FLUX_2_INPUT_IMAGES : 1;
82
+ }
83
+ get supportsFileInputs() {
84
+ if (this.modelId === "black-forest-labs/flux-2-pro" || this.modelId === "black-forest-labs/flux-2-dev" || this.modelId === "black-forest-labs/flux-fill-pro" || this.modelId === "black-forest-labs/flux-fill-dev") return true;
85
+ }
86
+ get supportsMaskInputs() {
87
+ if (this.modelId === "black-forest-labs/flux-fill-pro" || this.modelId === "black-forest-labs/flux-fill-dev") return true;
88
+ return this.supportsFileInputs === true ? false : void 0;
89
+ }
90
+ get provider() {
91
+ return this.config.provider;
92
+ }
93
+ get isFlux2Model() {
94
+ return FLUX_2_MODEL_PATTERN.test(this.modelId);
95
+ }
96
+ static [WORKFLOW_SERIALIZE](model) {
97
+ return serializeModelOptions({
98
+ modelId: model.modelId,
99
+ config: model.config
100
+ });
101
+ }
102
+ static [WORKFLOW_DESERIALIZE](options) {
103
+ return new ReplicateImageModel(options.modelId, options.config);
104
+ }
105
+ constructor(modelId, config) {
106
+ this.modelId = modelId;
107
+ this.config = config;
108
+ this.specificationVersion = "v4";
109
+ }
110
+ async doGenerate({ prompt, n, aspectRatio, size, seed, providerOptions, headers, abortSignal, files, mask }) {
111
+ const warnings = [];
112
+ const [modelId, version] = this.modelId.split(":");
113
+ const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
114
+ const replicateOptions = await parseProviderOptions({
115
+ provider: "replicate",
116
+ providerOptions,
117
+ schema: replicateImageModelOptionsSchema
118
+ });
119
+ let imageInputs = {};
120
+ if (files != null && files.length > 0) {
121
+ if (this.isFlux2Model) {
122
+ for (let i = 0; i < Math.min(files.length, MAX_FLUX_2_INPUT_IMAGES); i++) {
123
+ const key = i === 0 ? "input_image" : `input_image_${i + 1}`;
124
+ imageInputs[key] = convertImageModelFileToDataUri(files[i]);
125
+ }
126
+ if (files.length > MAX_FLUX_2_INPUT_IMAGES) warnings.push({
127
+ type: "other",
128
+ message: `Flux-2 models support up to ${MAX_FLUX_2_INPUT_IMAGES} input images. Additional images are ignored.`
129
+ });
130
+ } else {
131
+ imageInputs = { image: convertImageModelFileToDataUri(files[0]) };
132
+ if (files.length > 1) warnings.push({
133
+ type: "other",
134
+ message: "This Replicate model only supports a single input image. Additional images are ignored."
135
+ });
136
+ }
137
+ }
138
+ let maskInput;
139
+ if (mask != null) {
140
+ if (this.isFlux2Model) warnings.push({
141
+ type: "other",
142
+ message: "Flux-2 models do not support mask input. The mask will be ignored."
143
+ });
144
+ else maskInput = convertImageModelFileToDataUri(mask);
145
+ }
146
+ const { maxWaitTimeInSeconds, pollIntervalMillis = DEFAULT_POLL_INTERVAL_MILLIS, maxPollAttempts = DEFAULT_MAX_POLL_ATTEMPTS, ...inputOptions } = replicateOptions ?? {};
147
+ const preferHeader = maxWaitTimeInSeconds != null ? { prefer: `wait=${maxWaitTimeInSeconds}` } : { prefer: "wait" };
148
+ const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
149
+ const { value: initialPrediction, responseHeaders } = await postJsonToApi({
150
+ url: version != null ? `${this.config.baseURL}/predictions` : `${this.config.baseURL}/models/${modelId}/predictions`,
151
+ headers: combineHeaders(resolvedHeaders, headers, preferHeader),
152
+ body: {
153
+ input: {
154
+ prompt,
155
+ aspect_ratio: aspectRatio,
156
+ size,
157
+ seed,
158
+ num_outputs: n,
159
+ ...imageInputs,
160
+ ...maskInput != null ? { mask: maskInput } : {},
161
+ ...inputOptions
162
+ },
163
+ ...version != null ? { version } : {}
164
+ },
165
+ successfulResponseHandler: createJsonResponseHandler(replicateImageResponseSchema),
166
+ failedResponseHandler: replicateFailedResponseHandler,
167
+ abortSignal,
168
+ fetch: this.config.fetch
169
+ });
170
+ const prediction = await this.pollPrediction({
171
+ prediction: initialPrediction,
172
+ headers: combineHeaders(resolvedHeaders, headers),
173
+ pollIntervalMillis: pollIntervalMillis ?? DEFAULT_POLL_INTERVAL_MILLIS,
174
+ maxPollAttempts: maxPollAttempts ?? DEFAULT_MAX_POLL_ATTEMPTS,
175
+ abortSignal
176
+ });
177
+ if (prediction.output == null) throw new InvalidResponseDataError({
178
+ data: prediction,
179
+ message: "Replicate image generation completed without output."
180
+ });
181
+ const outputArray = Array.isArray(prediction.output) ? prediction.output : [prediction.output];
182
+ return {
183
+ images: await Promise.all(outputArray.map(async (url) => {
184
+ const { value: image } = await getFromApi({
185
+ url,
186
+ validateUrl: true,
187
+ trustedOrigin: this.config.baseURL,
188
+ successfulResponseHandler: createBinaryResponseHandler(),
189
+ failedResponseHandler: replicateFailedResponseHandler,
190
+ abortSignal,
191
+ fetch: this.config.fetch
192
+ });
193
+ return image;
194
+ })),
195
+ warnings,
196
+ response: {
197
+ timestamp: currentDate,
198
+ modelId: this.modelId,
199
+ headers: responseHeaders
200
+ }
201
+ };
202
+ }
203
+ async pollPrediction({ prediction, headers, pollIntervalMillis, maxPollAttempts, abortSignal }) {
204
+ let currentPrediction = prediction;
205
+ for (let i = 0; i < maxPollAttempts; i++) {
206
+ const completedPrediction = this.getCompletedPrediction(currentPrediction);
207
+ if (completedPrediction != null) return completedPrediction;
208
+ const { value } = await getFromApi({
209
+ url: currentPrediction.urls.get,
210
+ validateUrl: true,
211
+ credentialedOrigin: this.config.baseURL,
212
+ trustedOrigin: this.config.baseURL,
213
+ headers,
214
+ successfulResponseHandler: createJsonResponseHandler(replicateImageResponseSchema),
215
+ failedResponseHandler: replicateFailedResponseHandler,
216
+ abortSignal,
217
+ fetch: this.config.fetch
218
+ });
219
+ currentPrediction = value;
220
+ if (i < maxPollAttempts - 1) await delay(pollIntervalMillis, { abortSignal });
221
+ }
222
+ const completedPrediction = this.getCompletedPrediction(currentPrediction);
223
+ if (completedPrediction != null) return completedPrediction;
224
+ throw new Error(`Replicate image generation did not complete after ${maxPollAttempts} polling attempts.`);
225
+ }
226
+ getCompletedPrediction(prediction) {
227
+ if (prediction.status === "failed" || prediction.status === "canceled") throw new InvalidResponseDataError({
228
+ data: prediction,
229
+ message: `Replicate image generation ${prediction.status}: ${prediction.error ?? "Unknown error"}`
230
+ });
231
+ if (prediction.output != null || prediction.status === "succeeded") return prediction;
232
+ }
321
233
  };
322
- var replicateImageResponseSchema = z3.object({
323
- status: z3.enum(["starting", "processing", "succeeded", "failed", "canceled"]),
324
- output: z3.union([z3.array(z3.string()), z3.string()]).nullish(),
325
- error: z3.string().nullish(),
326
- urls: z3.object({
327
- get: z3.string()
328
- })
234
+ const replicateImageResponseSchema = z.object({
235
+ status: z.enum([
236
+ "starting",
237
+ "processing",
238
+ "succeeded",
239
+ "failed",
240
+ "canceled"
241
+ ]),
242
+ output: z.union([z.array(z.string()), z.string()]).nullish(),
243
+ error: z.string().nullish(),
244
+ urls: z.object({ get: z.string() })
329
245
  });
330
-
331
- // src/replicate-video-model.ts
332
- import {
333
- AISDKError
334
- } from "@ai-sdk/provider";
335
- import {
336
- combineHeaders as combineHeaders2,
337
- convertImageModelFileToDataUri as convertImageModelFileToDataUri2,
338
- createJsonResponseHandler as createJsonResponseHandler2,
339
- getFromApi as getFromApi2,
340
- parseProviderOptions as parseProviderOptions2,
341
- postJsonToApi as postJsonToApi2,
342
- resolve as resolve2
343
- } from "@ai-sdk/provider-utils";
344
- import { z as z5 } from "zod/v4";
345
-
346
- // src/replicate-video-model-options.ts
347
- import { lazySchema as lazySchema2, zodSchema as zodSchema2 } from "@ai-sdk/provider-utils";
348
- import { z as z4 } from "zod/v4";
349
- var replicateVideoModelOptionsSchema = lazySchema2(
350
- () => zodSchema2(
351
- z4.object({
352
- pollIntervalMs: z4.number().positive().nullish(),
353
- pollTimeoutMs: z4.number().positive().nullish(),
354
- maxWaitTimeInSeconds: z4.number().positive().nullish(),
355
- guidance_scale: z4.number().nullish(),
356
- num_inference_steps: z4.number().nullish(),
357
- motion_bucket_id: z4.number().nullish(),
358
- cond_aug: z4.number().nullish(),
359
- decoding_t: z4.number().nullish(),
360
- video_length: z4.string().nullish(),
361
- sizing_strategy: z4.string().nullish(),
362
- frames_per_second: z4.number().nullish(),
363
- prompt_optimizer: z4.boolean().nullish()
364
- }).loose()
365
- )
366
- );
367
-
368
- // src/replicate-video-model.ts
246
+ //#endregion
247
+ //#region src/replicate-video-model-options.ts
248
+ const replicateVideoModelOptionsSchema = lazySchema(() => zodSchema(z.object({
249
+ pollIntervalMs: z.number().positive().nullish(),
250
+ pollTimeoutMs: z.number().positive().nullish(),
251
+ maxWaitTimeInSeconds: z.number().positive().nullish(),
252
+ guidance_scale: z.number().nullish(),
253
+ num_inference_steps: z.number().nullish(),
254
+ motion_bucket_id: z.number().nullish(),
255
+ cond_aug: z.number().nullish(),
256
+ decoding_t: z.number().nullish(),
257
+ video_length: z.string().nullish(),
258
+ sizing_strategy: z.string().nullish(),
259
+ frames_per_second: z.number().nullish(),
260
+ prompt_optimizer: z.boolean().nullish()
261
+ }).loose()));
262
+ //#endregion
263
+ //#region src/replicate-video-model.ts
369
264
  var ReplicateVideoModel = class {
370
- constructor(modelId, config) {
371
- this.modelId = modelId;
372
- this.config = config;
373
- this.specificationVersion = "v4";
374
- this.maxVideosPerCall = 1;
375
- }
376
- // Replicate video models support 1 video at a time
377
- get provider() {
378
- return this.config.provider;
379
- }
380
- async buildInput(options) {
381
- const warnings = [];
382
- const replicateOptions = await parseProviderOptions2({
383
- provider: "replicate",
384
- providerOptions: options.providerOptions,
385
- schema: replicateVideoModelOptionsSchema
386
- });
387
- const input = {};
388
- if (options.prompt != null) {
389
- input.prompt = options.prompt;
390
- }
391
- if (options.image != null) {
392
- if (options.image.type === "url") {
393
- input.image = options.image.url;
394
- } else {
395
- input.image = convertImageModelFileToDataUri2(options.image);
396
- }
397
- }
398
- if (options.aspectRatio) {
399
- input.aspect_ratio = options.aspectRatio;
400
- }
401
- if (options.resolution) {
402
- input.size = options.resolution;
403
- }
404
- if (options.duration) {
405
- input.duration = options.duration;
406
- }
407
- if (options.fps) {
408
- input.fps = options.fps;
409
- }
410
- if (options.seed) {
411
- input.seed = options.seed;
412
- }
413
- if (replicateOptions != null) {
414
- const opts = replicateOptions;
415
- if (opts.guidance_scale !== void 0 && opts.guidance_scale !== null) {
416
- input.guidance_scale = opts.guidance_scale;
417
- }
418
- if (opts.num_inference_steps !== void 0 && opts.num_inference_steps !== null) {
419
- input.num_inference_steps = opts.num_inference_steps;
420
- }
421
- if (opts.motion_bucket_id !== void 0 && opts.motion_bucket_id !== null) {
422
- input.motion_bucket_id = opts.motion_bucket_id;
423
- }
424
- if (opts.cond_aug !== void 0 && opts.cond_aug !== null) {
425
- input.cond_aug = opts.cond_aug;
426
- }
427
- if (opts.decoding_t !== void 0 && opts.decoding_t !== null) {
428
- input.decoding_t = opts.decoding_t;
429
- }
430
- if (opts.video_length !== void 0 && opts.video_length !== null) {
431
- input.video_length = opts.video_length;
432
- }
433
- if (opts.sizing_strategy !== void 0 && opts.sizing_strategy !== null) {
434
- input.sizing_strategy = opts.sizing_strategy;
435
- }
436
- if (opts.frames_per_second !== void 0 && opts.frames_per_second !== null) {
437
- input.frames_per_second = opts.frames_per_second;
438
- }
439
- if (opts.prompt_optimizer !== void 0 && opts.prompt_optimizer !== null) {
440
- input.prompt_optimizer = opts.prompt_optimizer;
441
- }
442
- for (const [key, value] of Object.entries(opts)) {
443
- if (![
444
- "pollIntervalMs",
445
- "pollTimeoutMs",
446
- "maxWaitTimeInSeconds",
447
- "guidance_scale",
448
- "num_inference_steps",
449
- "motion_bucket_id",
450
- "cond_aug",
451
- "decoding_t",
452
- "video_length",
453
- "sizing_strategy",
454
- "frames_per_second",
455
- "prompt_optimizer"
456
- ].includes(key)) {
457
- input[key] = value;
458
- }
459
- }
460
- }
461
- return { input, warnings, replicateOptions };
462
- }
463
- async handleWebhookOption(options) {
464
- const { url, received } = await options.webhook();
465
- return { webhookUrl: url, received };
466
- }
467
- async doStart(options) {
468
- const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
469
- const { input, warnings } = await this.buildInput(options);
470
- const [modelId, version] = this.modelId.split(":");
471
- const predictionUrl = version != null ? `${this.config.baseURL}/predictions` : `${this.config.baseURL}/models/${modelId}/predictions`;
472
- const { value: prediction, responseHeaders } = await postJsonToApi2({
473
- url: predictionUrl,
474
- headers: combineHeaders2(
475
- await resolve2(this.config.headers),
476
- options.headers
477
- ),
478
- body: {
479
- input,
480
- ...version != null ? { version } : {},
481
- ...options.webhookUrl != null ? {
482
- webhook: options.webhookUrl,
483
- webhook_events_filter: ["completed"]
484
- } : {}
485
- },
486
- successfulResponseHandler: createJsonResponseHandler2(
487
- replicatePredictionSchema
488
- ),
489
- failedResponseHandler: replicateFailedResponseHandler,
490
- abortSignal: options.abortSignal,
491
- fetch: this.config.fetch
492
- });
493
- return {
494
- operation: { getUrl: prediction.urls.get },
495
- warnings,
496
- response: {
497
- timestamp: currentDate,
498
- modelId: this.modelId,
499
- headers: responseHeaders
500
- }
501
- };
502
- }
503
- async doStatus(options) {
504
- const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
505
- const { getUrl } = options.operation;
506
- const { value: prediction, responseHeaders } = await getFromApi2({
507
- url: getUrl,
508
- // getUrl comes from the provider response body.
509
- validateUrl: true,
510
- credentialedOrigin: this.config.baseURL,
511
- trustedOrigin: this.config.baseURL,
512
- headers: combineHeaders2(
513
- await resolve2(this.config.headers),
514
- options.headers
515
- ),
516
- successfulResponseHandler: createJsonResponseHandler2(
517
- replicatePredictionSchema
518
- ),
519
- failedResponseHandler: replicateFailedResponseHandler,
520
- abortSignal: options.abortSignal,
521
- fetch: this.config.fetch
522
- });
523
- if (prediction.status === "failed") {
524
- return {
525
- status: "error",
526
- error: `Video generation failed: ${prediction.error ?? "Unknown error"}`,
527
- response: {
528
- timestamp: currentDate,
529
- modelId: this.modelId,
530
- headers: responseHeaders
531
- }
532
- };
533
- }
534
- if (prediction.status === "canceled") {
535
- return {
536
- status: "error",
537
- error: "Video generation was canceled",
538
- response: {
539
- timestamp: currentDate,
540
- modelId: this.modelId,
541
- headers: responseHeaders
542
- }
543
- };
544
- }
545
- if (prediction.status === "succeeded") {
546
- if (!prediction.output) {
547
- throw new AISDKError({
548
- name: "REPLICATE_VIDEO_GENERATION_ERROR",
549
- message: "No video URL in response"
550
- });
551
- }
552
- return {
553
- status: "completed",
554
- videos: [
555
- { type: "url", url: prediction.output, mediaType: "video/mp4" }
556
- ],
557
- warnings: [],
558
- response: {
559
- timestamp: currentDate,
560
- modelId: this.modelId,
561
- headers: responseHeaders
562
- },
563
- providerMetadata: {
564
- replicate: {
565
- videos: [{ url: prediction.output }],
566
- predictionId: prediction.id,
567
- metrics: prediction.metrics
568
- }
569
- }
570
- };
571
- }
572
- return {
573
- status: "pending",
574
- response: {
575
- timestamp: currentDate,
576
- modelId: this.modelId,
577
- headers: responseHeaders
578
- }
579
- };
580
- }
265
+ get provider() {
266
+ return this.config.provider;
267
+ }
268
+ constructor(modelId, config) {
269
+ this.modelId = modelId;
270
+ this.config = config;
271
+ this.specificationVersion = "v4";
272
+ this.maxVideosPerCall = 1;
273
+ }
274
+ async buildInput(options) {
275
+ const warnings = [];
276
+ const replicateOptions = await parseProviderOptions({
277
+ provider: "replicate",
278
+ providerOptions: options.providerOptions,
279
+ schema: replicateVideoModelOptionsSchema
280
+ });
281
+ const input = {};
282
+ if (options.prompt != null) input.prompt = options.prompt;
283
+ if (options.image != null) {
284
+ if (options.image.type === "url") input.image = options.image.url;
285
+ else input.image = convertImageModelFileToDataUri(options.image);
286
+ }
287
+ if (options.aspectRatio) input.aspect_ratio = options.aspectRatio;
288
+ if (options.resolution) input.size = options.resolution;
289
+ if (options.duration) input.duration = options.duration;
290
+ if (options.fps) input.fps = options.fps;
291
+ if (options.seed) input.seed = options.seed;
292
+ if (replicateOptions != null) {
293
+ const opts = replicateOptions;
294
+ if (opts.guidance_scale !== void 0 && opts.guidance_scale !== null) input.guidance_scale = opts.guidance_scale;
295
+ if (opts.num_inference_steps !== void 0 && opts.num_inference_steps !== null) input.num_inference_steps = opts.num_inference_steps;
296
+ if (opts.motion_bucket_id !== void 0 && opts.motion_bucket_id !== null) input.motion_bucket_id = opts.motion_bucket_id;
297
+ if (opts.cond_aug !== void 0 && opts.cond_aug !== null) input.cond_aug = opts.cond_aug;
298
+ if (opts.decoding_t !== void 0 && opts.decoding_t !== null) input.decoding_t = opts.decoding_t;
299
+ if (opts.video_length !== void 0 && opts.video_length !== null) input.video_length = opts.video_length;
300
+ if (opts.sizing_strategy !== void 0 && opts.sizing_strategy !== null) input.sizing_strategy = opts.sizing_strategy;
301
+ if (opts.frames_per_second !== void 0 && opts.frames_per_second !== null) input.frames_per_second = opts.frames_per_second;
302
+ if (opts.prompt_optimizer !== void 0 && opts.prompt_optimizer !== null) input.prompt_optimizer = opts.prompt_optimizer;
303
+ for (const [key, value] of Object.entries(opts)) if (![
304
+ "pollIntervalMs",
305
+ "pollTimeoutMs",
306
+ "maxWaitTimeInSeconds",
307
+ "guidance_scale",
308
+ "num_inference_steps",
309
+ "motion_bucket_id",
310
+ "cond_aug",
311
+ "decoding_t",
312
+ "video_length",
313
+ "sizing_strategy",
314
+ "frames_per_second",
315
+ "prompt_optimizer"
316
+ ].includes(key)) input[key] = value;
317
+ }
318
+ return {
319
+ input,
320
+ warnings,
321
+ replicateOptions
322
+ };
323
+ }
324
+ async handleWebhookOption(options) {
325
+ const { url, received } = await options.webhook();
326
+ return {
327
+ webhookUrl: url,
328
+ received
329
+ };
330
+ }
331
+ async doStart(options) {
332
+ const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
333
+ const { input, warnings } = await this.buildInput(options);
334
+ const [modelId, version] = this.modelId.split(":");
335
+ const predictionUrl = version != null ? `${this.config.baseURL}/predictions` : `${this.config.baseURL}/models/${modelId}/predictions`;
336
+ const { value: prediction, responseHeaders } = await postJsonToApi({
337
+ url: predictionUrl,
338
+ headers: combineHeaders(await resolve(this.config.headers), options.headers),
339
+ body: {
340
+ input,
341
+ ...version != null ? { version } : {},
342
+ ...options.webhookUrl != null ? {
343
+ webhook: options.webhookUrl,
344
+ webhook_events_filter: ["completed"]
345
+ } : {}
346
+ },
347
+ successfulResponseHandler: createJsonResponseHandler(replicatePredictionSchema),
348
+ failedResponseHandler: replicateFailedResponseHandler,
349
+ abortSignal: options.abortSignal,
350
+ fetch: this.config.fetch
351
+ });
352
+ return {
353
+ operation: { getUrl: prediction.urls.get },
354
+ warnings,
355
+ response: {
356
+ timestamp: currentDate,
357
+ modelId: this.modelId,
358
+ headers: responseHeaders
359
+ }
360
+ };
361
+ }
362
+ async doStatus(options) {
363
+ const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
364
+ const { getUrl } = options.operation;
365
+ const { value: prediction, responseHeaders } = await getFromApi({
366
+ url: getUrl,
367
+ validateUrl: true,
368
+ credentialedOrigin: this.config.baseURL,
369
+ trustedOrigin: this.config.baseURL,
370
+ headers: combineHeaders(await resolve(this.config.headers), options.headers),
371
+ successfulResponseHandler: createJsonResponseHandler(replicatePredictionSchema),
372
+ failedResponseHandler: replicateFailedResponseHandler,
373
+ abortSignal: options.abortSignal,
374
+ fetch: this.config.fetch
375
+ });
376
+ if (prediction.status === "failed") return {
377
+ status: "error",
378
+ error: `Video generation failed: ${prediction.error ?? "Unknown error"}`,
379
+ response: {
380
+ timestamp: currentDate,
381
+ modelId: this.modelId,
382
+ headers: responseHeaders
383
+ }
384
+ };
385
+ if (prediction.status === "canceled") return {
386
+ status: "error",
387
+ error: "Video generation was canceled",
388
+ response: {
389
+ timestamp: currentDate,
390
+ modelId: this.modelId,
391
+ headers: responseHeaders
392
+ }
393
+ };
394
+ if (prediction.status === "succeeded") {
395
+ if (!prediction.output) throw new AISDKError({
396
+ name: "REPLICATE_VIDEO_GENERATION_ERROR",
397
+ message: "No video URL in response"
398
+ });
399
+ return {
400
+ status: "completed",
401
+ videos: [{
402
+ type: "url",
403
+ url: prediction.output,
404
+ mediaType: "video/mp4"
405
+ }],
406
+ warnings: [],
407
+ response: {
408
+ timestamp: currentDate,
409
+ modelId: this.modelId,
410
+ headers: responseHeaders
411
+ },
412
+ providerMetadata: { replicate: {
413
+ videos: [{ url: prediction.output }],
414
+ predictionId: prediction.id,
415
+ metrics: prediction.metrics
416
+ } }
417
+ };
418
+ }
419
+ return {
420
+ status: "pending",
421
+ response: {
422
+ timestamp: currentDate,
423
+ modelId: this.modelId,
424
+ headers: responseHeaders
425
+ }
426
+ };
427
+ }
581
428
  };
582
- var replicatePredictionSchema = z5.object({
583
- id: z5.string(),
584
- status: z5.enum(["starting", "processing", "succeeded", "failed", "canceled"]),
585
- output: z5.string().nullish(),
586
- error: z5.string().nullish(),
587
- urls: z5.object({
588
- get: z5.string()
589
- }),
590
- metrics: z5.object({
591
- predict_time: z5.number().nullish()
592
- }).nullish()
429
+ const replicatePredictionSchema = z.object({
430
+ id: z.string(),
431
+ status: z.enum([
432
+ "starting",
433
+ "processing",
434
+ "succeeded",
435
+ "failed",
436
+ "canceled"
437
+ ]),
438
+ output: z.string().nullish(),
439
+ error: z.string().nullish(),
440
+ urls: z.object({ get: z.string() }),
441
+ metrics: z.object({ predict_time: z.number().nullish() }).nullish()
593
442
  });
594
-
595
- // src/version.ts
596
- var VERSION = true ? "3.0.51" : "0.0.0-test";
597
-
598
- // src/replicate-provider.ts
443
+ //#endregion
444
+ //#region src/version.ts
445
+ const VERSION = "3.0.53";
446
+ //#endregion
447
+ //#region src/replicate-provider.ts
448
+ /**
449
+ * Create a Replicate provider instance.
450
+ */
599
451
  function createReplicate(options = {}) {
600
- const baseURL = withoutTrailingSlash(validateBaseURL(options.baseURL)) ?? "https://api.replicate.com/v1";
601
- const getHeaders = () => withUserAgentSuffix(
602
- {
603
- Authorization: `Bearer ${loadApiKey({
604
- apiKey: options.apiToken,
605
- environmentVariableName: "REPLICATE_API_TOKEN",
606
- description: "Replicate"
607
- })}`,
608
- ...options.headers
609
- },
610
- `ai-sdk/replicate/${VERSION}`
611
- );
612
- const createImageModel = (modelId) => new ReplicateImageModel(modelId, {
613
- provider: "replicate",
614
- baseURL,
615
- headers: getHeaders(),
616
- fetch: options.fetch
617
- });
618
- const createVideoModel = (modelId) => new ReplicateVideoModel(modelId, {
619
- provider: "replicate.video",
620
- baseURL,
621
- headers: getHeaders,
622
- fetch: options.fetch
623
- });
624
- const embeddingModel = (modelId) => {
625
- throw new NoSuchModelError({
626
- modelId,
627
- modelType: "embeddingModel"
628
- });
629
- };
630
- return {
631
- specificationVersion: "v4",
632
- image: createImageModel,
633
- imageModel: createImageModel,
634
- languageModel: (modelId) => {
635
- throw new NoSuchModelError({
636
- modelId,
637
- modelType: "languageModel"
638
- });
639
- },
640
- embeddingModel,
641
- textEmbeddingModel: embeddingModel,
642
- video: createVideoModel,
643
- videoModel: createVideoModel
644
- };
452
+ const baseURL = withoutTrailingSlash(validateBaseURL(options.baseURL)) ?? "https://api.replicate.com/v1";
453
+ const getHeaders = () => withUserAgentSuffix({
454
+ Authorization: `Bearer ${loadApiKey({
455
+ apiKey: options.apiToken,
456
+ environmentVariableName: "REPLICATE_API_TOKEN",
457
+ description: "Replicate"
458
+ })}`,
459
+ ...options.headers
460
+ }, `ai-sdk-replicate/${VERSION}`);
461
+ const createImageModel = (modelId) => new ReplicateImageModel(modelId, {
462
+ provider: "replicate",
463
+ baseURL,
464
+ headers: getHeaders(),
465
+ fetch: options.fetch
466
+ });
467
+ const createVideoModel = (modelId) => new ReplicateVideoModel(modelId, {
468
+ provider: "replicate.video",
469
+ baseURL,
470
+ headers: getHeaders,
471
+ fetch: options.fetch
472
+ });
473
+ const embeddingModel = (modelId) => {
474
+ throw new NoSuchModelError({
475
+ modelId,
476
+ modelType: "embeddingModel"
477
+ });
478
+ };
479
+ return {
480
+ specificationVersion: "v4",
481
+ image: createImageModel,
482
+ imageModel: createImageModel,
483
+ languageModel: (modelId) => {
484
+ throw new NoSuchModelError({
485
+ modelId,
486
+ modelType: "languageModel"
487
+ });
488
+ },
489
+ embeddingModel,
490
+ textEmbeddingModel: embeddingModel,
491
+ video: createVideoModel,
492
+ videoModel: createVideoModel
493
+ };
645
494
  }
646
- var replicate = createReplicate();
647
- export {
648
- VERSION,
649
- createReplicate,
650
- replicate
651
- };
495
+ /**
496
+ * Default Replicate provider instance.
497
+ */
498
+ const replicate = createReplicate();
499
+ //#endregion
500
+ export { VERSION, createReplicate, replicate };
501
+
652
502
  //# sourceMappingURL=index.js.map