@ai-sdk/replicate 0.0.0-64aae7dd-20260114144918

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/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2023 Vercel, Inc.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # AI SDK - Replicate Provider
2
+
3
+ The **[Replicate provider](https://ai-sdk.dev/providers/ai-sdk-providers/replicate)** for the [AI SDK](https://ai-sdk.dev/docs) contains image model support for the Replicate API.
4
+
5
+ ## Setup
6
+
7
+ The Replicate provider is available in the `@ai-sdk/replicate` module. You can install it with
8
+
9
+ ```bash
10
+ npm i @ai-sdk/replicate
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { replicate } from '@ai-sdk/replicate';
17
+ import { generateImage } from 'ai';
18
+
19
+ const { image } = await generateImage({
20
+ model: replicate.image('black-forest-labs/flux-schnell'),
21
+ prompt: 'The Loch Ness Monster getting a manicure',
22
+ });
23
+
24
+ const filename = `image-${Date.now()}.png`;
25
+ fs.writeFileSync(filename, image.uint8Array);
26
+ console.log(`Image saved to ${filename}`);
27
+ ```
28
+
29
+ If you want to pass additional inputs to the model besides the prompt, use the `providerOptions.replicate` property:
30
+
31
+ ```ts
32
+ const { image } = await generateImage({
33
+ model: replicate.image('recraft-ai/recraft-v3'),
34
+ prompt: 'The Loch Ness Monster getting a manicure',
35
+ size: '1365x1024',
36
+ providerOptions: {
37
+ replicate: {
38
+ style: 'realistic_image',
39
+ },
40
+ },
41
+ });
42
+ ```
43
+
44
+ ## Documentation
45
+
46
+ Please check out the **[Replicate provider](https://ai-sdk.dev/providers/ai-sdk-providers/replicate)** for more information.
@@ -0,0 +1,91 @@
1
+ import { ImageModelV3, ProviderV3 } from '@ai-sdk/provider';
2
+ import * as _ai_sdk_provider_utils from '@ai-sdk/provider-utils';
3
+ import { Resolvable, FetchFunction, InferSchema } from '@ai-sdk/provider-utils';
4
+
5
+ type ReplicateImageModelId = 'black-forest-labs/flux-1.1-pro' | 'black-forest-labs/flux-1.1-pro-ultra' | 'black-forest-labs/flux-dev' | 'black-forest-labs/flux-pro' | 'black-forest-labs/flux-schnell' | 'bytedance/sdxl-lightning-4step' | 'fofr/aura-flow' | 'fofr/latent-consistency-model' | 'fofr/realvisxl-v3-multi-controlnet-lora' | 'fofr/sdxl-emoji' | 'fofr/sdxl-multi-controlnet-lora' | 'ideogram-ai/ideogram-v2' | 'ideogram-ai/ideogram-v2-turbo' | 'lucataco/dreamshaper-xl-turbo' | 'lucataco/open-dalle-v1.1' | 'lucataco/realvisxl-v2.0' | 'lucataco/realvisxl2-lcm' | 'luma/photon' | 'luma/photon-flash' | 'nvidia/sana' | 'playgroundai/playground-v2.5-1024px-aesthetic' | 'recraft-ai/recraft-v3' | 'recraft-ai/recraft-v3-svg' | 'stability-ai/stable-diffusion-3.5-large' | 'stability-ai/stable-diffusion-3.5-large-turbo' | 'stability-ai/stable-diffusion-3.5-medium' | 'tstramer/material-diffusion' | 'black-forest-labs/flux-fill-pro' | 'black-forest-labs/flux-fill-dev' | 'black-forest-labs/flux-2-pro' | 'black-forest-labs/flux-2-dev' | (string & {});
6
+
7
+ interface ReplicateImageModelConfig {
8
+ provider: string;
9
+ baseURL: string;
10
+ headers?: Resolvable<Record<string, string | undefined>>;
11
+ fetch?: FetchFunction;
12
+ _internal?: {
13
+ currentDate?: () => Date;
14
+ };
15
+ }
16
+ declare class ReplicateImageModel implements ImageModelV3 {
17
+ readonly modelId: ReplicateImageModelId;
18
+ private readonly config;
19
+ readonly specificationVersion = "v3";
20
+ get maxImagesPerCall(): number;
21
+ get provider(): string;
22
+ private get isFlux2Model();
23
+ constructor(modelId: ReplicateImageModelId, config: ReplicateImageModelConfig);
24
+ doGenerate({ prompt, n, aspectRatio, size, seed, providerOptions, headers, abortSignal, files, mask, }: Parameters<ImageModelV3['doGenerate']>[0]): Promise<Awaited<ReturnType<ImageModelV3['doGenerate']>>>;
25
+ }
26
+ /**
27
+ * Provider options schema for Replicate image generation.
28
+ *
29
+ * Note: Different Replicate models support different parameters.
30
+ * This schema includes common parameters, but you can pass any
31
+ * model-specific parameters through the passthrough.
32
+ */
33
+ declare const replicateImageProviderOptionsSchema: _ai_sdk_provider_utils.LazySchema<{
34
+ [x: string]: unknown;
35
+ maxWaitTimeInSeconds?: number | null | undefined;
36
+ guidance_scale?: number | null | undefined;
37
+ num_inference_steps?: number | null | undefined;
38
+ negative_prompt?: string | null | undefined;
39
+ output_format?: "png" | "jpg" | "webp" | null | undefined;
40
+ output_quality?: number | null | undefined;
41
+ strength?: number | null | undefined;
42
+ }>;
43
+ type ReplicateImageProviderOptions = InferSchema<typeof replicateImageProviderOptionsSchema>;
44
+
45
+ interface ReplicateProviderSettings {
46
+ /**
47
+ API token that is being send using the `Authorization` header.
48
+ It defaults to the `REPLICATE_API_TOKEN` environment variable.
49
+ */
50
+ apiToken?: string;
51
+ /**
52
+ Use a different URL prefix for API calls, e.g. to use proxy servers.
53
+ The default prefix is `https://api.replicate.com/v1`.
54
+ */
55
+ baseURL?: string;
56
+ /**
57
+ Custom headers to include in the requests.
58
+ */
59
+ headers?: Record<string, string>;
60
+ /**
61
+ Custom fetch implementation. You can use it as a middleware to intercept requests,
62
+ or to provide a custom fetch implementation for e.g. testing.
63
+ */
64
+ fetch?: FetchFunction;
65
+ }
66
+ interface ReplicateProvider extends ProviderV3 {
67
+ /**
68
+ * Creates a Replicate image generation model.
69
+ */
70
+ image(modelId: ReplicateImageModelId): ReplicateImageModel;
71
+ /**
72
+ * Creates a Replicate image generation model.
73
+ */
74
+ imageModel(modelId: ReplicateImageModelId): ReplicateImageModel;
75
+ /**
76
+ * @deprecated Use `embeddingModel` instead.
77
+ */
78
+ textEmbeddingModel(modelId: string): never;
79
+ }
80
+ /**
81
+ * Create a Replicate provider instance.
82
+ */
83
+ declare function createReplicate(options?: ReplicateProviderSettings): ReplicateProvider;
84
+ /**
85
+ * Default Replicate provider instance.
86
+ */
87
+ declare const replicate: ReplicateProvider;
88
+
89
+ declare const VERSION: string;
90
+
91
+ export { type ReplicateImageProviderOptions, type ReplicateProvider, type ReplicateProviderSettings, VERSION, createReplicate, replicate };
@@ -0,0 +1,91 @@
1
+ import { ImageModelV3, ProviderV3 } from '@ai-sdk/provider';
2
+ import * as _ai_sdk_provider_utils from '@ai-sdk/provider-utils';
3
+ import { Resolvable, FetchFunction, InferSchema } from '@ai-sdk/provider-utils';
4
+
5
+ type ReplicateImageModelId = 'black-forest-labs/flux-1.1-pro' | 'black-forest-labs/flux-1.1-pro-ultra' | 'black-forest-labs/flux-dev' | 'black-forest-labs/flux-pro' | 'black-forest-labs/flux-schnell' | 'bytedance/sdxl-lightning-4step' | 'fofr/aura-flow' | 'fofr/latent-consistency-model' | 'fofr/realvisxl-v3-multi-controlnet-lora' | 'fofr/sdxl-emoji' | 'fofr/sdxl-multi-controlnet-lora' | 'ideogram-ai/ideogram-v2' | 'ideogram-ai/ideogram-v2-turbo' | 'lucataco/dreamshaper-xl-turbo' | 'lucataco/open-dalle-v1.1' | 'lucataco/realvisxl-v2.0' | 'lucataco/realvisxl2-lcm' | 'luma/photon' | 'luma/photon-flash' | 'nvidia/sana' | 'playgroundai/playground-v2.5-1024px-aesthetic' | 'recraft-ai/recraft-v3' | 'recraft-ai/recraft-v3-svg' | 'stability-ai/stable-diffusion-3.5-large' | 'stability-ai/stable-diffusion-3.5-large-turbo' | 'stability-ai/stable-diffusion-3.5-medium' | 'tstramer/material-diffusion' | 'black-forest-labs/flux-fill-pro' | 'black-forest-labs/flux-fill-dev' | 'black-forest-labs/flux-2-pro' | 'black-forest-labs/flux-2-dev' | (string & {});
6
+
7
+ interface ReplicateImageModelConfig {
8
+ provider: string;
9
+ baseURL: string;
10
+ headers?: Resolvable<Record<string, string | undefined>>;
11
+ fetch?: FetchFunction;
12
+ _internal?: {
13
+ currentDate?: () => Date;
14
+ };
15
+ }
16
+ declare class ReplicateImageModel implements ImageModelV3 {
17
+ readonly modelId: ReplicateImageModelId;
18
+ private readonly config;
19
+ readonly specificationVersion = "v3";
20
+ get maxImagesPerCall(): number;
21
+ get provider(): string;
22
+ private get isFlux2Model();
23
+ constructor(modelId: ReplicateImageModelId, config: ReplicateImageModelConfig);
24
+ doGenerate({ prompt, n, aspectRatio, size, seed, providerOptions, headers, abortSignal, files, mask, }: Parameters<ImageModelV3['doGenerate']>[0]): Promise<Awaited<ReturnType<ImageModelV3['doGenerate']>>>;
25
+ }
26
+ /**
27
+ * Provider options schema for Replicate image generation.
28
+ *
29
+ * Note: Different Replicate models support different parameters.
30
+ * This schema includes common parameters, but you can pass any
31
+ * model-specific parameters through the passthrough.
32
+ */
33
+ declare const replicateImageProviderOptionsSchema: _ai_sdk_provider_utils.LazySchema<{
34
+ [x: string]: unknown;
35
+ maxWaitTimeInSeconds?: number | null | undefined;
36
+ guidance_scale?: number | null | undefined;
37
+ num_inference_steps?: number | null | undefined;
38
+ negative_prompt?: string | null | undefined;
39
+ output_format?: "png" | "jpg" | "webp" | null | undefined;
40
+ output_quality?: number | null | undefined;
41
+ strength?: number | null | undefined;
42
+ }>;
43
+ type ReplicateImageProviderOptions = InferSchema<typeof replicateImageProviderOptionsSchema>;
44
+
45
+ interface ReplicateProviderSettings {
46
+ /**
47
+ API token that is being send using the `Authorization` header.
48
+ It defaults to the `REPLICATE_API_TOKEN` environment variable.
49
+ */
50
+ apiToken?: string;
51
+ /**
52
+ Use a different URL prefix for API calls, e.g. to use proxy servers.
53
+ The default prefix is `https://api.replicate.com/v1`.
54
+ */
55
+ baseURL?: string;
56
+ /**
57
+ Custom headers to include in the requests.
58
+ */
59
+ headers?: Record<string, string>;
60
+ /**
61
+ Custom fetch implementation. You can use it as a middleware to intercept requests,
62
+ or to provide a custom fetch implementation for e.g. testing.
63
+ */
64
+ fetch?: FetchFunction;
65
+ }
66
+ interface ReplicateProvider extends ProviderV3 {
67
+ /**
68
+ * Creates a Replicate image generation model.
69
+ */
70
+ image(modelId: ReplicateImageModelId): ReplicateImageModel;
71
+ /**
72
+ * Creates a Replicate image generation model.
73
+ */
74
+ imageModel(modelId: ReplicateImageModelId): ReplicateImageModel;
75
+ /**
76
+ * @deprecated Use `embeddingModel` instead.
77
+ */
78
+ textEmbeddingModel(modelId: string): never;
79
+ }
80
+ /**
81
+ * Create a Replicate provider instance.
82
+ */
83
+ declare function createReplicate(options?: ReplicateProviderSettings): ReplicateProvider;
84
+ /**
85
+ * Default Replicate provider instance.
86
+ */
87
+ declare const replicate: ReplicateProvider;
88
+
89
+ declare const VERSION: string;
90
+
91
+ export { type ReplicateImageProviderOptions, type ReplicateProvider, type ReplicateProviderSettings, VERSION, createReplicate, replicate };
package/dist/index.js ADDED
@@ -0,0 +1,280 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ VERSION: () => VERSION,
24
+ createReplicate: () => createReplicate,
25
+ replicate: () => replicate
26
+ });
27
+ module.exports = __toCommonJS(src_exports);
28
+
29
+ // src/replicate-provider.ts
30
+ var import_provider = require("@ai-sdk/provider");
31
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
32
+
33
+ // src/replicate-image-model.ts
34
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
35
+ var import_v42 = require("zod/v4");
36
+
37
+ // src/replicate-error.ts
38
+ var import_provider_utils = require("@ai-sdk/provider-utils");
39
+ var import_v4 = require("zod/v4");
40
+ var replicateErrorSchema = import_v4.z.object({
41
+ detail: import_v4.z.string().optional(),
42
+ error: import_v4.z.string().optional()
43
+ });
44
+ var replicateFailedResponseHandler = (0, import_provider_utils.createJsonErrorResponseHandler)({
45
+ errorSchema: replicateErrorSchema,
46
+ errorToMessage: (error) => {
47
+ var _a, _b;
48
+ return (_b = (_a = error.detail) != null ? _a : error.error) != null ? _b : "Unknown Replicate error";
49
+ }
50
+ });
51
+
52
+ // src/replicate-image-model.ts
53
+ var FLUX_2_MODEL_PATTERN = /^black-forest-labs\/flux-2-/;
54
+ var MAX_FLUX_2_INPUT_IMAGES = 8;
55
+ var ReplicateImageModel = class {
56
+ constructor(modelId, config) {
57
+ this.modelId = modelId;
58
+ this.config = config;
59
+ this.specificationVersion = "v3";
60
+ }
61
+ get maxImagesPerCall() {
62
+ return this.isFlux2Model ? MAX_FLUX_2_INPUT_IMAGES : 1;
63
+ }
64
+ get provider() {
65
+ return this.config.provider;
66
+ }
67
+ get isFlux2Model() {
68
+ return FLUX_2_MODEL_PATTERN.test(this.modelId);
69
+ }
70
+ async doGenerate({
71
+ prompt,
72
+ n,
73
+ aspectRatio,
74
+ size,
75
+ seed,
76
+ providerOptions,
77
+ headers,
78
+ abortSignal,
79
+ files,
80
+ mask
81
+ }) {
82
+ var _a, _b, _c;
83
+ const warnings = [];
84
+ const [modelId, version] = this.modelId.split(":");
85
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
86
+ const replicateOptions = await (0, import_provider_utils2.parseProviderOptions)({
87
+ provider: "replicate",
88
+ providerOptions,
89
+ schema: replicateImageProviderOptionsSchema
90
+ });
91
+ let imageInputs = {};
92
+ if (files != null && files.length > 0) {
93
+ if (this.isFlux2Model) {
94
+ for (let i = 0; i < Math.min(files.length, MAX_FLUX_2_INPUT_IMAGES); i++) {
95
+ const key = i === 0 ? "input_image" : `input_image_${i + 1}`;
96
+ imageInputs[key] = (0, import_provider_utils2.convertImageModelFileToDataUri)(files[i]);
97
+ }
98
+ if (files.length > MAX_FLUX_2_INPUT_IMAGES) {
99
+ warnings.push({
100
+ type: "other",
101
+ message: `Flux-2 models support up to ${MAX_FLUX_2_INPUT_IMAGES} input images. Additional images are ignored.`
102
+ });
103
+ }
104
+ } else {
105
+ imageInputs = { image: (0, import_provider_utils2.convertImageModelFileToDataUri)(files[0]) };
106
+ if (files.length > 1) {
107
+ warnings.push({
108
+ type: "other",
109
+ message: "This Replicate model only supports a single input image. Additional images are ignored."
110
+ });
111
+ }
112
+ }
113
+ }
114
+ let maskInput;
115
+ if (mask != null) {
116
+ if (this.isFlux2Model) {
117
+ warnings.push({
118
+ type: "other",
119
+ message: "Flux-2 models do not support mask input. The mask will be ignored."
120
+ });
121
+ } else {
122
+ maskInput = (0, import_provider_utils2.convertImageModelFileToDataUri)(mask);
123
+ }
124
+ }
125
+ const { maxWaitTimeInSeconds, ...inputOptions } = replicateOptions != null ? replicateOptions : {};
126
+ const preferHeader = maxWaitTimeInSeconds != null ? { prefer: `wait=${maxWaitTimeInSeconds}` } : { prefer: "wait" };
127
+ const {
128
+ value: { output },
129
+ responseHeaders
130
+ } = await (0, import_provider_utils2.postJsonToApi)({
131
+ url: (
132
+ // different endpoints for versioned vs unversioned models:
133
+ version != null ? `${this.config.baseURL}/predictions` : `${this.config.baseURL}/models/${modelId}/predictions`
134
+ ),
135
+ headers: (0, import_provider_utils2.combineHeaders)(
136
+ await (0, import_provider_utils2.resolve)(this.config.headers),
137
+ headers,
138
+ preferHeader
139
+ ),
140
+ body: {
141
+ input: {
142
+ prompt,
143
+ aspect_ratio: aspectRatio,
144
+ size,
145
+ seed,
146
+ num_outputs: n,
147
+ ...imageInputs,
148
+ ...maskInput != null ? { mask: maskInput } : {},
149
+ ...inputOptions
150
+ },
151
+ // for versioned models, include the version in the body:
152
+ ...version != null ? { version } : {}
153
+ },
154
+ successfulResponseHandler: (0, import_provider_utils2.createJsonResponseHandler)(
155
+ replicateImageResponseSchema
156
+ ),
157
+ failedResponseHandler: replicateFailedResponseHandler,
158
+ abortSignal,
159
+ fetch: this.config.fetch
160
+ });
161
+ const outputArray = Array.isArray(output) ? output : [output];
162
+ const images = await Promise.all(
163
+ outputArray.map(async (url) => {
164
+ const { value: image } = await (0, import_provider_utils2.getFromApi)({
165
+ url,
166
+ successfulResponseHandler: (0, import_provider_utils2.createBinaryResponseHandler)(),
167
+ failedResponseHandler: replicateFailedResponseHandler,
168
+ abortSignal,
169
+ fetch: this.config.fetch
170
+ });
171
+ return image;
172
+ })
173
+ );
174
+ return {
175
+ images,
176
+ warnings,
177
+ response: {
178
+ timestamp: currentDate,
179
+ modelId: this.modelId,
180
+ headers: responseHeaders
181
+ }
182
+ };
183
+ }
184
+ };
185
+ var replicateImageResponseSchema = import_v42.z.object({
186
+ output: import_v42.z.union([import_v42.z.array(import_v42.z.string()), import_v42.z.string()])
187
+ });
188
+ var replicateImageProviderOptionsSchema = (0, import_provider_utils2.lazySchema)(
189
+ () => (0, import_provider_utils2.zodSchema)(
190
+ import_v42.z.object({
191
+ /**
192
+ * Maximum time in seconds to wait for the prediction to complete in sync mode.
193
+ * By default, Replicate uses sync mode with a 60-second timeout.
194
+ *
195
+ * - When not specified: Uses default 60-second sync wait (`prefer: wait`)
196
+ * - When set to a positive number: Uses that duration (`prefer: wait=N`)
197
+ */
198
+ maxWaitTimeInSeconds: import_v42.z.number().positive().nullish(),
199
+ /**
200
+ * Guidance scale for classifier-free guidance.
201
+ * Higher values make the output more closely match the prompt.
202
+ */
203
+ guidance_scale: import_v42.z.number().nullish(),
204
+ /**
205
+ * Number of denoising steps. More steps = higher quality but slower.
206
+ */
207
+ num_inference_steps: import_v42.z.number().nullish(),
208
+ /**
209
+ * Negative prompt to guide what to avoid in the generation.
210
+ */
211
+ negative_prompt: import_v42.z.string().nullish(),
212
+ /**
213
+ * Output image format.
214
+ */
215
+ output_format: import_v42.z.enum(["png", "jpg", "webp"]).nullish(),
216
+ /**
217
+ * Output image quality (1-100). Only applies to jpg and webp.
218
+ */
219
+ output_quality: import_v42.z.number().min(1).max(100).nullish(),
220
+ /**
221
+ * Strength of the transformation for img2img (0-1).
222
+ * Lower values keep more of the original image.
223
+ */
224
+ strength: import_v42.z.number().min(0).max(1).nullish()
225
+ }).passthrough()
226
+ )
227
+ );
228
+
229
+ // src/version.ts
230
+ var VERSION = true ? "0.0.0-64aae7dd-20260114144918" : "0.0.0-test";
231
+
232
+ // src/replicate-provider.ts
233
+ function createReplicate(options = {}) {
234
+ const createImageModel = (modelId) => {
235
+ var _a;
236
+ return new ReplicateImageModel(modelId, {
237
+ provider: "replicate",
238
+ baseURL: (_a = options.baseURL) != null ? _a : "https://api.replicate.com/v1",
239
+ headers: (0, import_provider_utils3.withUserAgentSuffix)(
240
+ {
241
+ Authorization: `Bearer ${(0, import_provider_utils3.loadApiKey)({
242
+ apiKey: options.apiToken,
243
+ environmentVariableName: "REPLICATE_API_TOKEN",
244
+ description: "Replicate"
245
+ })}`,
246
+ ...options.headers
247
+ },
248
+ `ai-sdk/replicate/${VERSION}`
249
+ ),
250
+ fetch: options.fetch
251
+ });
252
+ };
253
+ const embeddingModel = (modelId) => {
254
+ throw new import_provider.NoSuchModelError({
255
+ modelId,
256
+ modelType: "embeddingModel"
257
+ });
258
+ };
259
+ return {
260
+ specificationVersion: "v3",
261
+ image: createImageModel,
262
+ imageModel: createImageModel,
263
+ languageModel: (modelId) => {
264
+ throw new import_provider.NoSuchModelError({
265
+ modelId,
266
+ modelType: "languageModel"
267
+ });
268
+ },
269
+ embeddingModel,
270
+ textEmbeddingModel: embeddingModel
271
+ };
272
+ }
273
+ var replicate = createReplicate();
274
+ // Annotate the CommonJS export names for ESM import in node:
275
+ 0 && (module.exports = {
276
+ VERSION,
277
+ createReplicate,
278
+ replicate
279
+ });
280
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/replicate-provider.ts","../src/replicate-image-model.ts","../src/replicate-error.ts","../src/version.ts"],"sourcesContent":["export { createReplicate, replicate } from './replicate-provider';\nexport type {\n ReplicateProvider,\n ReplicateProviderSettings,\n} from './replicate-provider';\nexport type { ReplicateImageProviderOptions } from './replicate-image-model';\nexport { VERSION } from './version';\n","import { NoSuchModelError, ProviderV3 } from '@ai-sdk/provider';\nimport type { FetchFunction } from '@ai-sdk/provider-utils';\nimport { loadApiKey, withUserAgentSuffix } from '@ai-sdk/provider-utils';\nimport { ReplicateImageModel } from './replicate-image-model';\nimport { ReplicateImageModelId } from './replicate-image-settings';\nimport { VERSION } from './version';\n\nexport interface ReplicateProviderSettings {\n /**\nAPI token that is being send using the `Authorization` header.\nIt defaults to the `REPLICATE_API_TOKEN` environment variable.\n */\n apiToken?: string;\n\n /**\nUse a different URL prefix for API calls, e.g. to use proxy servers.\nThe default prefix is `https://api.replicate.com/v1`.\n */\n baseURL?: string;\n\n /**\nCustom headers to include in the requests.\n */\n headers?: Record<string, string>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n}\n\nexport interface ReplicateProvider extends ProviderV3 {\n /**\n * Creates a Replicate image generation model.\n */\n image(modelId: ReplicateImageModelId): ReplicateImageModel;\n\n /**\n * Creates a Replicate image generation model.\n */\n imageModel(modelId: ReplicateImageModelId): ReplicateImageModel;\n\n /**\n * @deprecated Use `embeddingModel` instead.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\n/**\n * Create a Replicate provider instance.\n */\nexport function createReplicate(\n options: ReplicateProviderSettings = {},\n): ReplicateProvider {\n const createImageModel = (modelId: ReplicateImageModelId) =>\n new ReplicateImageModel(modelId, {\n provider: 'replicate',\n baseURL: options.baseURL ?? 'https://api.replicate.com/v1',\n headers: withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiToken,\n environmentVariableName: 'REPLICATE_API_TOKEN',\n description: 'Replicate',\n })}`,\n ...options.headers,\n },\n `ai-sdk/replicate/${VERSION}`,\n ),\n fetch: options.fetch,\n });\n\n const embeddingModel = (modelId: string) => {\n throw new NoSuchModelError({\n modelId,\n modelType: 'embeddingModel',\n });\n };\n\n return {\n specificationVersion: 'v3' as const,\n image: createImageModel,\n imageModel: createImageModel,\n languageModel: (modelId: string) => {\n throw new NoSuchModelError({\n modelId,\n modelType: 'languageModel',\n });\n },\n embeddingModel,\n textEmbeddingModel: embeddingModel,\n };\n}\n\n/**\n * Default Replicate provider instance.\n */\nexport const replicate = createReplicate();\n","import type { ImageModelV3, SharedV3Warning } from '@ai-sdk/provider';\nimport type { Resolvable } from '@ai-sdk/provider-utils';\nimport {\n combineHeaders,\n convertImageModelFileToDataUri,\n createBinaryResponseHandler,\n createJsonResponseHandler,\n FetchFunction,\n getFromApi,\n InferSchema,\n lazySchema,\n parseProviderOptions,\n postJsonToApi,\n resolve,\n zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { replicateFailedResponseHandler } from './replicate-error';\nimport { ReplicateImageModelId } from './replicate-image-settings';\n\ninterface ReplicateImageModelConfig {\n provider: string;\n baseURL: string;\n headers?: Resolvable<Record<string, string | undefined>>;\n fetch?: FetchFunction;\n _internal?: {\n currentDate?: () => Date;\n };\n}\n\n// Flux-2 models support up to 8 input images with input_image, input_image_2, etc.\nconst FLUX_2_MODEL_PATTERN = /^black-forest-labs\\/flux-2-/;\nconst MAX_FLUX_2_INPUT_IMAGES = 8;\n\nexport class ReplicateImageModel implements ImageModelV3 {\n readonly specificationVersion = 'v3';\n\n get maxImagesPerCall(): number {\n // Flux-2 models support up to 8 input images\n return this.isFlux2Model ? MAX_FLUX_2_INPUT_IMAGES : 1;\n }\n\n get provider(): string {\n return this.config.provider;\n }\n\n private get isFlux2Model(): boolean {\n return FLUX_2_MODEL_PATTERN.test(this.modelId);\n }\n\n constructor(\n readonly modelId: ReplicateImageModelId,\n private readonly config: ReplicateImageModelConfig,\n ) {}\n\n async doGenerate({\n prompt,\n n,\n aspectRatio,\n size,\n seed,\n providerOptions,\n headers,\n abortSignal,\n files,\n mask,\n }: Parameters<ImageModelV3['doGenerate']>[0]): Promise<\n Awaited<ReturnType<ImageModelV3['doGenerate']>>\n > {\n const warnings: Array<SharedV3Warning> = [];\n\n const [modelId, version] = this.modelId.split(':');\n\n const currentDate = this.config._internal?.currentDate?.() ?? new Date();\n\n // Parse provider options\n const replicateOptions = await parseProviderOptions({\n provider: 'replicate',\n providerOptions,\n schema: replicateImageProviderOptionsSchema,\n });\n\n // Handle image input from files\n let imageInputs: Record<string, string> = {};\n if (files != null && files.length > 0) {\n if (this.isFlux2Model) {\n // Flux-2 models use input_image, input_image_2, input_image_3, etc.\n for (\n let i = 0;\n i < Math.min(files.length, MAX_FLUX_2_INPUT_IMAGES);\n i++\n ) {\n const key = i === 0 ? 'input_image' : `input_image_${i + 1}`;\n imageInputs[key] = convertImageModelFileToDataUri(files[i]);\n }\n if (files.length > MAX_FLUX_2_INPUT_IMAGES) {\n warnings.push({\n type: 'other',\n message: `Flux-2 models support up to ${MAX_FLUX_2_INPUT_IMAGES} input images. Additional images are ignored.`,\n });\n }\n } else {\n // Other models use single 'image' parameter\n imageInputs = { image: convertImageModelFileToDataUri(files[0]) };\n if (files.length > 1) {\n warnings.push({\n type: 'other',\n message:\n 'This Replicate model only supports a single input image. Additional images are ignored.',\n });\n }\n }\n }\n\n // Handle mask input (not supported by Flux-2 models)\n let maskInput: string | undefined;\n if (mask != null) {\n if (this.isFlux2Model) {\n warnings.push({\n type: 'other',\n message:\n 'Flux-2 models do not support mask input. The mask will be ignored.',\n });\n } else {\n maskInput = convertImageModelFileToDataUri(mask);\n }\n }\n\n // Extract maxWaitTimeInSeconds from provider options and prepare the rest for the request body\n const { maxWaitTimeInSeconds, ...inputOptions } = replicateOptions ?? {};\n\n // Build the prefer header based on maxWaitTimeInSeconds:\n // - undefined/null: use default sync wait (prefer: wait)\n // - positive number: use custom wait duration (prefer: wait=N)\n const preferHeader: Record<string, string> =\n maxWaitTimeInSeconds != null\n ? { prefer: `wait=${maxWaitTimeInSeconds}` }\n : { prefer: 'wait' };\n\n const {\n value: { output },\n responseHeaders,\n } = await postJsonToApi({\n url:\n // different endpoints for versioned vs unversioned models:\n version != null\n ? `${this.config.baseURL}/predictions`\n : `${this.config.baseURL}/models/${modelId}/predictions`,\n\n headers: combineHeaders(\n await resolve(this.config.headers),\n headers,\n preferHeader,\n ),\n\n body: {\n input: {\n prompt,\n aspect_ratio: aspectRatio,\n size,\n seed,\n num_outputs: n,\n ...imageInputs,\n ...(maskInput != null ? { mask: maskInput } : {}),\n ...inputOptions,\n },\n // for versioned models, include the version in the body:\n ...(version != null ? { version } : {}),\n },\n\n successfulResponseHandler: createJsonResponseHandler(\n replicateImageResponseSchema,\n ),\n failedResponseHandler: replicateFailedResponseHandler,\n abortSignal,\n fetch: this.config.fetch,\n });\n\n // download the images:\n const outputArray = Array.isArray(output) ? output : [output];\n const images = await Promise.all(\n outputArray.map(async url => {\n const { value: image } = await getFromApi({\n url,\n successfulResponseHandler: createBinaryResponseHandler(),\n failedResponseHandler: replicateFailedResponseHandler,\n abortSignal,\n fetch: this.config.fetch,\n });\n return image;\n }),\n );\n\n return {\n images,\n warnings,\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders,\n },\n };\n }\n}\n\nconst replicateImageResponseSchema = z.object({\n output: z.union([z.array(z.string()), z.string()]),\n});\n\n/**\n * Provider options schema for Replicate image generation.\n *\n * Note: Different Replicate models support different parameters.\n * This schema includes common parameters, but you can pass any\n * model-specific parameters through the passthrough.\n */\nexport const replicateImageProviderOptionsSchema = lazySchema(() =>\n zodSchema(\n z\n .object({\n /**\n * Maximum time in seconds to wait for the prediction to complete in sync mode.\n * By default, Replicate uses sync mode with a 60-second timeout.\n *\n * - When not specified: Uses default 60-second sync wait (`prefer: wait`)\n * - When set to a positive number: Uses that duration (`prefer: wait=N`)\n */\n maxWaitTimeInSeconds: z.number().positive().nullish(),\n\n /**\n * Guidance scale for classifier-free guidance.\n * Higher values make the output more closely match the prompt.\n */\n guidance_scale: z.number().nullish(),\n\n /**\n * Number of denoising steps. More steps = higher quality but slower.\n */\n num_inference_steps: z.number().nullish(),\n\n /**\n * Negative prompt to guide what to avoid in the generation.\n */\n negative_prompt: z.string().nullish(),\n\n /**\n * Output image format.\n */\n output_format: z.enum(['png', 'jpg', 'webp']).nullish(),\n\n /**\n * Output image quality (1-100). Only applies to jpg and webp.\n */\n output_quality: z.number().min(1).max(100).nullish(),\n\n /**\n * Strength of the transformation for img2img (0-1).\n * Lower values keep more of the original image.\n */\n strength: z.number().min(0).max(1).nullish(),\n })\n .passthrough(),\n ),\n);\n\nexport type ReplicateImageProviderOptions = InferSchema<\n typeof replicateImageProviderOptionsSchema\n>;\n","import { createJsonErrorResponseHandler } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nconst replicateErrorSchema = z.object({\n detail: z.string().optional(),\n error: z.string().optional(),\n});\n\nexport const replicateFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: replicateErrorSchema,\n errorToMessage: error =>\n error.detail ?? error.error ?? 'Unknown Replicate error',\n});\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKA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