@ai-sdk/luma 3.0.0-beta.20 → 3.0.0-beta.22
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/CHANGELOG.md +24 -0
- package/dist/index.js +17 -5
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/src/luma-image-model.ts +19 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
# @ai-sdk/luma
|
|
2
2
|
|
|
3
|
+
## 3.0.0-beta.22
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [add1126]
|
|
8
|
+
- @ai-sdk/provider-utils@5.0.0-beta.21
|
|
9
|
+
|
|
10
|
+
## 3.0.0-beta.21
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- b3976a2: Add workflow serialization support to all provider models.
|
|
15
|
+
|
|
16
|
+
**`@ai-sdk/provider-utils`:** New `serializeModel()` helper that extracts only serializable properties from a model instance, filtering out functions and objects containing functions. Third-party provider authors can use this to add workflow support to their own models.
|
|
17
|
+
|
|
18
|
+
**All providers:** `headers` is now optional in provider config types. This is non-breaking — existing code that passes `headers` continues to work. Custom provider implementations that construct model configs manually can now omit `headers`, which is useful when models are deserialized from a workflow step boundary where auth is provided separately.
|
|
19
|
+
|
|
20
|
+
All provider model classes now include `WORKFLOW_SERIALIZE` and `WORKFLOW_DESERIALIZE` static methods, enabling them to cross workflow step boundaries without serialization errors.
|
|
21
|
+
|
|
22
|
+
- Updated dependencies [b3976a2]
|
|
23
|
+
- Updated dependencies [ff5eba1]
|
|
24
|
+
- @ai-sdk/provider-utils@5.0.0-beta.20
|
|
25
|
+
- @ai-sdk/provider@4.0.0-beta.12
|
|
26
|
+
|
|
3
27
|
## 3.0.0-beta.20
|
|
4
28
|
|
|
5
29
|
### Major Changes
|
package/dist/index.js
CHANGED
|
@@ -21,12 +21,15 @@ import {
|
|
|
21
21
|
postJsonToApi,
|
|
22
22
|
lazySchema,
|
|
23
23
|
parseProviderOptions,
|
|
24
|
-
zodSchema
|
|
24
|
+
zodSchema,
|
|
25
|
+
serializeModelOptions,
|
|
26
|
+
WORKFLOW_SERIALIZE,
|
|
27
|
+
WORKFLOW_DESERIALIZE
|
|
25
28
|
} from "@ai-sdk/provider-utils";
|
|
26
29
|
import { z } from "zod/v4";
|
|
27
30
|
var DEFAULT_POLL_INTERVAL_MILLIS = 500;
|
|
28
31
|
var DEFAULT_MAX_POLL_ATTEMPTS = 6e4 / DEFAULT_POLL_INTERVAL_MILLIS;
|
|
29
|
-
var LumaImageModel = class {
|
|
32
|
+
var LumaImageModel = class _LumaImageModel {
|
|
30
33
|
constructor(modelId, config) {
|
|
31
34
|
this.modelId = modelId;
|
|
32
35
|
this.config = config;
|
|
@@ -38,6 +41,15 @@ var LumaImageModel = class {
|
|
|
38
41
|
get provider() {
|
|
39
42
|
return this.config.provider;
|
|
40
43
|
}
|
|
44
|
+
static [WORKFLOW_SERIALIZE](model) {
|
|
45
|
+
return serializeModelOptions({
|
|
46
|
+
modelId: model.modelId,
|
|
47
|
+
config: model.config
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
static [WORKFLOW_DESERIALIZE](options) {
|
|
51
|
+
return new _LumaImageModel(options.modelId, options.config);
|
|
52
|
+
}
|
|
41
53
|
async doGenerate({
|
|
42
54
|
prompt,
|
|
43
55
|
size,
|
|
@@ -49,7 +61,7 @@ var LumaImageModel = class {
|
|
|
49
61
|
files,
|
|
50
62
|
mask
|
|
51
63
|
}) {
|
|
52
|
-
var _a, _b, _c;
|
|
64
|
+
var _a, _b, _c, _d, _e;
|
|
53
65
|
const warnings = [];
|
|
54
66
|
if (seed != null) {
|
|
55
67
|
warnings.push({
|
|
@@ -84,7 +96,7 @@ var LumaImageModel = class {
|
|
|
84
96
|
imageConfigs != null ? imageConfigs : []
|
|
85
97
|
);
|
|
86
98
|
const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
|
|
87
|
-
const fullHeaders = combineHeaders(this.config.headers(), headers);
|
|
99
|
+
const fullHeaders = combineHeaders((_e = (_d = this.config).headers) == null ? void 0 : _e.call(_d), headers);
|
|
88
100
|
const { value: generationResponse, responseHeaders } = await postJsonToApi({
|
|
89
101
|
url: this.getLumaGenerationsUrl(),
|
|
90
102
|
headers: fullHeaders,
|
|
@@ -345,7 +357,7 @@ var lumaImageModelOptionsSchema = lazySchema(
|
|
|
345
357
|
);
|
|
346
358
|
|
|
347
359
|
// src/version.ts
|
|
348
|
-
var VERSION = true ? "3.0.0-beta.
|
|
360
|
+
var VERSION = true ? "3.0.0-beta.22" : "0.0.0-test";
|
|
349
361
|
|
|
350
362
|
// src/luma-provider.ts
|
|
351
363
|
var defaultBaseURL = "https://api.lumalabs.ai";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/luma-provider.ts","../src/luma-image-model.ts","../src/version.ts"],"sourcesContent":["import { ImageModelV4, NoSuchModelError, ProviderV4 } from '@ai-sdk/provider';\nimport {\n FetchFunction,\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix,\n} from '@ai-sdk/provider-utils';\nimport { LumaImageModel } from './luma-image-model';\nimport { LumaImageModelId } from './luma-image-settings';\nimport { VERSION } from './version';\n\nexport interface LumaProviderSettings {\n /**\n * Luma API key. Default value is taken from the `LUMA_API_KEY` environment\n * variable.\n */\n apiKey?: string;\n /**\n * Base URL for the API calls.\n */\n baseURL?: string;\n /**\n * Custom headers to include in the requests.\n */\n headers?: Record<string, string>;\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n}\n\nexport interface LumaProvider extends ProviderV4 {\n /**\n * Creates a model for image generation.\n */\n image(modelId: LumaImageModelId): ImageModelV4;\n\n /**\n * Creates a model for image generation.\n */\n imageModel(modelId: LumaImageModelId): ImageModelV4;\n\n /**\n * @deprecated Use `embeddingModel` instead.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nconst defaultBaseURL = 'https://api.lumalabs.ai';\n\nexport function createLuma(options: LumaProviderSettings = {}): LumaProvider {\n const baseURL = withoutTrailingSlash(options.baseURL ?? defaultBaseURL);\n const getHeaders = () =>\n withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: 'LUMA_API_KEY',\n description: 'Luma',\n })}`,\n ...options.headers,\n },\n `ai-sdk/luma/${VERSION}`,\n );\n\n const createImageModel = (modelId: LumaImageModelId) =>\n new LumaImageModel(modelId, {\n provider: 'luma.image',\n baseURL: baseURL ?? defaultBaseURL,\n headers: getHeaders,\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: 'v4' 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\nexport const luma = createLuma();\n","import {\n ImageModelV4,\n ImageModelV4File,\n SharedV4Warning,\n InvalidResponseDataError,\n} from '@ai-sdk/provider';\nimport {\n FetchFunction,\n combineHeaders,\n createBinaryResponseHandler,\n createJsonResponseHandler,\n createJsonErrorResponseHandler,\n createStatusCodeErrorResponseHandler,\n delay,\n getFromApi,\n postJsonToApi,\n InferSchema,\n lazySchema,\n parseProviderOptions,\n zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { LumaReferenceType } from './luma-image-settings';\nimport { z } from 'zod/v4';\n\nconst DEFAULT_POLL_INTERVAL_MILLIS = 500;\nconst DEFAULT_MAX_POLL_ATTEMPTS = 60000 / DEFAULT_POLL_INTERVAL_MILLIS;\n\ninterface LumaImageModelConfig {\n provider: string;\n baseURL: string;\n headers: () => Record<string, string>;\n fetch?: FetchFunction;\n _internal?: {\n currentDate?: () => Date;\n };\n}\n\nexport class LumaImageModel implements ImageModelV4 {\n readonly specificationVersion = 'v4';\n readonly maxImagesPerCall = 1;\n readonly pollIntervalMillis = DEFAULT_POLL_INTERVAL_MILLIS;\n readonly maxPollAttempts = DEFAULT_MAX_POLL_ATTEMPTS;\n\n get provider(): string {\n return this.config.provider;\n }\n\n constructor(\n readonly modelId: string,\n private readonly config: LumaImageModelConfig,\n ) {}\n\n async doGenerate({\n prompt,\n size,\n aspectRatio,\n seed,\n providerOptions,\n headers,\n abortSignal,\n files,\n mask,\n }: Parameters<ImageModelV4['doGenerate']>[0]): Promise<\n Awaited<ReturnType<ImageModelV4['doGenerate']>>\n > {\n const warnings: Array<SharedV4Warning> = [];\n\n if (seed != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'seed',\n details: 'This model does not support the `seed` option.',\n });\n }\n\n if (size != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'size',\n details:\n 'This model does not support the `size` option. Use `aspectRatio` instead.',\n });\n }\n\n // Parse and validate provider options\n const lumaOptions = await parseProviderOptions({\n provider: 'luma',\n providerOptions,\n schema: lumaImageModelOptionsSchema,\n });\n\n // Extract non-request options\n const {\n pollIntervalMillis,\n maxPollAttempts,\n referenceType,\n images: imageConfigs,\n ...providerRequestOptions\n } = lumaOptions ?? {};\n\n // Handle image editing via files with reference type support\n const editingOptions = this.getEditingOptions(\n files,\n mask,\n referenceType ?? undefined,\n imageConfigs ?? [],\n );\n\n const currentDate = this.config._internal?.currentDate?.() ?? new Date();\n const fullHeaders = combineHeaders(this.config.headers(), headers);\n const { value: generationResponse, responseHeaders } = await postJsonToApi({\n url: this.getLumaGenerationsUrl(),\n headers: fullHeaders,\n body: {\n prompt,\n ...(aspectRatio ? { aspect_ratio: aspectRatio } : {}),\n model: this.modelId,\n ...editingOptions,\n ...providerRequestOptions,\n },\n abortSignal,\n fetch: this.config.fetch,\n failedResponseHandler: this.createLumaErrorHandler(),\n successfulResponseHandler: createJsonResponseHandler(\n lumaGenerationResponseSchema,\n ),\n });\n\n const imageUrl = await this.pollForImageUrl(\n generationResponse.id,\n fullHeaders,\n abortSignal,\n {\n pollIntervalMillis: pollIntervalMillis ?? undefined,\n maxPollAttempts: maxPollAttempts ?? undefined,\n },\n );\n\n const downloadedImage = await this.downloadImage(imageUrl, abortSignal);\n\n return {\n images: [downloadedImage],\n warnings,\n response: {\n modelId: this.modelId,\n timestamp: currentDate,\n headers: responseHeaders,\n },\n };\n }\n\n private async pollForImageUrl(\n generationId: string,\n headers: Record<string, string | undefined>,\n abortSignal: AbortSignal | undefined,\n pollSettings?: { pollIntervalMillis?: number; maxPollAttempts?: number },\n ): Promise<string> {\n const url = this.getLumaGenerationsUrl(generationId);\n const maxPollAttempts =\n pollSettings?.maxPollAttempts ?? this.maxPollAttempts;\n const pollIntervalMillis =\n pollSettings?.pollIntervalMillis ?? this.pollIntervalMillis;\n\n for (let i = 0; i < maxPollAttempts; i++) {\n const { value: statusResponse } = await getFromApi({\n url,\n headers,\n abortSignal,\n fetch: this.config.fetch,\n failedResponseHandler: this.createLumaErrorHandler(),\n successfulResponseHandler: createJsonResponseHandler(\n lumaGenerationResponseSchema,\n ),\n });\n\n switch (statusResponse.state) {\n case 'completed':\n if (!statusResponse.assets?.image) {\n throw new InvalidResponseDataError({\n data: statusResponse,\n message: `Image generation completed but no image was found.`,\n });\n }\n return statusResponse.assets.image;\n case 'failed':\n throw new InvalidResponseDataError({\n data: statusResponse,\n message: `Image generation failed.`,\n });\n }\n await delay(pollIntervalMillis);\n }\n\n throw new Error(\n `Image generation timed out after ${this.maxPollAttempts} attempts.`,\n );\n }\n\n private createLumaErrorHandler() {\n return createJsonErrorResponseHandler({\n errorSchema: lumaErrorSchema,\n errorToMessage: (error: LumaErrorData) =>\n error.detail[0].msg ?? 'Unknown error',\n });\n }\n\n private getEditingOptions(\n files: ImageModelV4File[] | undefined,\n mask: ImageModelV4File | undefined,\n referenceType: LumaReferenceType = 'image',\n imageConfigs: Array<{ weight?: number | null; id?: string | null }> = [],\n ): Record<string, unknown> {\n const options: Record<string, unknown> = {};\n\n // Luma does not support mask-based inpainting\n if (mask != null) {\n throw new Error(\n 'Luma AI does not support mask-based image editing. ' +\n 'Use the prompt to describe the changes you want to make, along with ' +\n '`prompt.images` containing the source image URL.',\n );\n }\n\n if (files == null || files.length === 0) {\n return options;\n }\n\n // Validate all files are URL-based\n for (const file of files) {\n if (file.type !== 'url') {\n throw new Error(\n 'Luma AI only supports URL-based images. ' +\n 'Please provide image URLs using `prompt.images` with publicly accessible URLs. ' +\n 'Base64 and Uint8Array data are not supported.',\n );\n }\n }\n\n // Default weights per reference type\n const defaultWeights: Record<LumaReferenceType, number> = {\n image: 0.85,\n style: 0.8,\n character: 1.0, // Not used, but defined for completeness\n modify_image: 1.0,\n };\n\n switch (referenceType) {\n case 'image': {\n // Supports up to 4 images\n if (files.length > 4) {\n throw new Error(\n 'Luma AI image supports up to 4 reference images. ' +\n `You provided ${files.length} images.`,\n );\n }\n options.image = files.map((file, index) => ({\n url: (file as { type: 'url'; url: string }).url,\n weight: imageConfigs[index]?.weight ?? defaultWeights.image,\n }));\n break;\n }\n\n case 'style': {\n // Style ref accepts an array but typically uses one style image\n options.style = files.map((file, index) => ({\n url: (file as { type: 'url'; url: string }).url,\n weight: imageConfigs[index]?.weight ?? defaultWeights.style,\n }));\n break;\n }\n\n case 'character': {\n // Group images by identity id\n const identities: Record<string, string[]> = {};\n for (let i = 0; i < files.length; i++) {\n const file = files[i] as { type: 'url'; url: string };\n const identityId = imageConfigs[i]?.id ?? 'identity0';\n if (!identities[identityId]) {\n identities[identityId] = [];\n }\n identities[identityId].push(file.url);\n }\n\n // Validate each identity has at most 4 images\n for (const [identityId, images] of Object.entries(identities)) {\n if (images.length > 4) {\n throw new Error(\n `Luma AI character supports up to 4 images per identity. ` +\n `Identity '${identityId}' has ${images.length} images.`,\n );\n }\n }\n\n options.character = Object.fromEntries(\n Object.entries(identities).map(([id, images]) => [id, { images }]),\n );\n break;\n }\n\n case 'modify_image': {\n // Only supports a single image\n if (files.length > 1) {\n throw new Error(\n 'Luma AI modify_image only supports a single input image. ' +\n `You provided ${files.length} images.`,\n );\n }\n options.modify_image = {\n url: (files[0] as { type: 'url'; url: string }).url,\n weight: imageConfigs[0]?.weight ?? defaultWeights.modify_image,\n };\n break;\n }\n }\n\n return options;\n }\n\n private getLumaGenerationsUrl(generationId?: string) {\n return `${this.config.baseURL}/dream-machine/v1/generations/${\n generationId ?? 'image'\n }`;\n }\n\n private async downloadImage(\n url: string,\n abortSignal: AbortSignal | undefined,\n ): Promise<Uint8Array> {\n const { value: response } = await getFromApi({\n url,\n // No specific headers should be needed for this request as it's a\n // generated image provided by Luma.\n abortSignal,\n failedResponseHandler: createStatusCodeErrorResponseHandler(),\n successfulResponseHandler: createBinaryResponseHandler(),\n fetch: this.config.fetch,\n });\n return response;\n }\n}\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nconst lumaGenerationResponseSchema = lazySchema(() =>\n zodSchema(\n z.object({\n id: z.string(),\n state: z.enum(['queued', 'dreaming', 'completed', 'failed']),\n failure_reason: z.string().nullish(),\n assets: z\n .object({\n image: z.string(), // URL of the generated image\n })\n .nullish(),\n }),\n ),\n);\n\nconst lumaErrorSchema = z.object({\n detail: z.array(\n z.object({\n type: z.string(),\n loc: z.array(z.string()),\n msg: z.string(),\n input: z.string(),\n ctx: z\n .object({\n expected: z.string(),\n })\n .nullish(),\n }),\n ),\n});\n\nexport type LumaErrorData = z.infer<typeof lumaErrorSchema>;\n\n/**\n * Provider options schema for Luma image generation.\n *\n * @see https://docs.lumalabs.ai/docs/image-generation\n */\nexport const lumaImageModelOptionsSchema = lazySchema(() =>\n zodSchema(\n z\n .object({\n /**\n * The type of image reference to use when providing input images.\n * - `image`: Guide generation using reference images (up to 4). Default.\n * - `style`: Apply a specific style from reference image(s).\n * - `character`: Create consistent characters from reference images (up to 4).\n * - `modify_image`: Transform a single input image with prompt guidance.\n */\n referenceType: z\n .enum(['image', 'style', 'character', 'modify_image'])\n .nullish(),\n\n /**\n * Per-image configuration array. Each entry corresponds to an image in `prompt.images`.\n * Allows setting individual weights for each reference image.\n */\n images: z\n .array(\n z.object({\n /**\n * The weight of this image's influence on the generation.\n * - For `image`: Higher weight = closer to reference (default: 0.85)\n * - For `style`: Higher weight = stronger style influence (default: 0.8)\n * - For `modify_image`: Higher weight = closer to input, lower = more creative (default: 1.0)\n */\n weight: z.number().min(0).max(1).nullish(),\n\n /**\n * The identity name for character references.\n * Used with `character` to specify which identity group the image belongs to.\n * Luma supports multiple identities (e.g., 'identity0', 'identity1') for generating\n * images with multiple consistent characters.\n * Default: 'identity0'\n */\n id: z.string().nullish(),\n }),\n )\n .nullish(),\n\n /**\n * Override the polling interval in milliseconds (default 500).\n */\n pollIntervalMillis: z.number().nullish(),\n\n /**\n * Override the maximum number of polling attempts (default 120).\n */\n maxPollAttempts: z.number().nullish(),\n })\n .passthrough(),\n ),\n);\n\nexport type LumaImageModelOptions = InferSchema<\n typeof lumaImageModelOptionsSchema\n>;\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n"],"mappings":";AAAA,SAAuB,wBAAoC;AAC3D;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACNP;AAAA,EAIE;AAAA,OACK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,SAAS;AAElB,IAAM,+BAA+B;AACrC,IAAM,4BAA4B,MAAQ;AAYnC,IAAM,iBAAN,MAA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AsB;AAAA,IACtB,OAAO;AAAA,IACP,YAAY;AAAA,IACZ,eAAe,CAAC,YAAoB;AAClC,YAAM,IAAI,iBAAiB;AAAA,QACzB;AAAA,QACA,WAAW;AAAA,MACb,CAAC;AAAA,IACH;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,EACtB;AACF;AAEO,IAAM,OAAO,WAAW;","names":["_a","_b"]}
|
|
1
|
+
{"version":3,"sources":["../src/luma-provider.ts","../src/luma-image-model.ts","../src/version.ts"],"sourcesContent":["import { ImageModelV4, NoSuchModelError, ProviderV4 } from '@ai-sdk/provider';\nimport {\n FetchFunction,\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix,\n} from '@ai-sdk/provider-utils';\nimport { LumaImageModel } from './luma-image-model';\nimport { LumaImageModelId } from './luma-image-settings';\nimport { VERSION } from './version';\n\nexport interface LumaProviderSettings {\n /**\n * Luma API key. Default value is taken from the `LUMA_API_KEY` environment\n * variable.\n */\n apiKey?: string;\n /**\n * Base URL for the API calls.\n */\n baseURL?: string;\n /**\n * Custom headers to include in the requests.\n */\n headers?: Record<string, string>;\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n}\n\nexport interface LumaProvider extends ProviderV4 {\n /**\n * Creates a model for image generation.\n */\n image(modelId: LumaImageModelId): ImageModelV4;\n\n /**\n * Creates a model for image generation.\n */\n imageModel(modelId: LumaImageModelId): ImageModelV4;\n\n /**\n * @deprecated Use `embeddingModel` instead.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nconst defaultBaseURL = 'https://api.lumalabs.ai';\n\nexport function createLuma(options: LumaProviderSettings = {}): LumaProvider {\n const baseURL = withoutTrailingSlash(options.baseURL ?? defaultBaseURL);\n const getHeaders = () =>\n withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: 'LUMA_API_KEY',\n description: 'Luma',\n })}`,\n ...options.headers,\n },\n `ai-sdk/luma/${VERSION}`,\n );\n\n const createImageModel = (modelId: LumaImageModelId) =>\n new LumaImageModel(modelId, {\n provider: 'luma.image',\n baseURL: baseURL ?? defaultBaseURL,\n headers: getHeaders,\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: 'v4' 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\nexport const luma = createLuma();\n","import {\n ImageModelV4,\n ImageModelV4File,\n SharedV4Warning,\n InvalidResponseDataError,\n} from '@ai-sdk/provider';\nimport {\n FetchFunction,\n combineHeaders,\n createBinaryResponseHandler,\n createJsonResponseHandler,\n createJsonErrorResponseHandler,\n createStatusCodeErrorResponseHandler,\n delay,\n getFromApi,\n postJsonToApi,\n InferSchema,\n lazySchema,\n parseProviderOptions,\n zodSchema,\n serializeModelOptions,\n WORKFLOW_SERIALIZE,\n WORKFLOW_DESERIALIZE,\n} from '@ai-sdk/provider-utils';\nimport { LumaReferenceType } from './luma-image-settings';\nimport { z } from 'zod/v4';\n\nconst DEFAULT_POLL_INTERVAL_MILLIS = 500;\nconst DEFAULT_MAX_POLL_ATTEMPTS = 60000 / DEFAULT_POLL_INTERVAL_MILLIS;\n\ninterface LumaImageModelConfig {\n provider: string;\n baseURL: string;\n headers?: () => Record<string, string>;\n fetch?: FetchFunction;\n _internal?: {\n currentDate?: () => Date;\n };\n}\n\nexport class LumaImageModel implements ImageModelV4 {\n readonly specificationVersion = 'v4';\n readonly maxImagesPerCall = 1;\n readonly pollIntervalMillis = DEFAULT_POLL_INTERVAL_MILLIS;\n readonly maxPollAttempts = DEFAULT_MAX_POLL_ATTEMPTS;\n\n get provider(): string {\n return this.config.provider;\n }\n\n static [WORKFLOW_SERIALIZE](model: LumaImageModel) {\n return serializeModelOptions({\n modelId: model.modelId,\n config: model.config,\n });\n }\n\n static [WORKFLOW_DESERIALIZE](options: {\n modelId: string;\n config: LumaImageModelConfig;\n }) {\n return new LumaImageModel(options.modelId, options.config);\n }\n\n constructor(\n readonly modelId: string,\n private readonly config: LumaImageModelConfig,\n ) {}\n\n async doGenerate({\n prompt,\n size,\n aspectRatio,\n seed,\n providerOptions,\n headers,\n abortSignal,\n files,\n mask,\n }: Parameters<ImageModelV4['doGenerate']>[0]): Promise<\n Awaited<ReturnType<ImageModelV4['doGenerate']>>\n > {\n const warnings: Array<SharedV4Warning> = [];\n\n if (seed != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'seed',\n details: 'This model does not support the `seed` option.',\n });\n }\n\n if (size != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'size',\n details:\n 'This model does not support the `size` option. Use `aspectRatio` instead.',\n });\n }\n\n // Parse and validate provider options\n const lumaOptions = await parseProviderOptions({\n provider: 'luma',\n providerOptions,\n schema: lumaImageModelOptionsSchema,\n });\n\n // Extract non-request options\n const {\n pollIntervalMillis,\n maxPollAttempts,\n referenceType,\n images: imageConfigs,\n ...providerRequestOptions\n } = lumaOptions ?? {};\n\n // Handle image editing via files with reference type support\n const editingOptions = this.getEditingOptions(\n files,\n mask,\n referenceType ?? undefined,\n imageConfigs ?? [],\n );\n\n const currentDate = this.config._internal?.currentDate?.() ?? new Date();\n const fullHeaders = combineHeaders(this.config.headers?.(), headers);\n const { value: generationResponse, responseHeaders } = await postJsonToApi({\n url: this.getLumaGenerationsUrl(),\n headers: fullHeaders,\n body: {\n prompt,\n ...(aspectRatio ? { aspect_ratio: aspectRatio } : {}),\n model: this.modelId,\n ...editingOptions,\n ...providerRequestOptions,\n },\n abortSignal,\n fetch: this.config.fetch,\n failedResponseHandler: this.createLumaErrorHandler(),\n successfulResponseHandler: createJsonResponseHandler(\n lumaGenerationResponseSchema,\n ),\n });\n\n const imageUrl = await this.pollForImageUrl(\n generationResponse.id,\n fullHeaders,\n abortSignal,\n {\n pollIntervalMillis: pollIntervalMillis ?? undefined,\n maxPollAttempts: maxPollAttempts ?? undefined,\n },\n );\n\n const downloadedImage = await this.downloadImage(imageUrl, abortSignal);\n\n return {\n images: [downloadedImage],\n warnings,\n response: {\n modelId: this.modelId,\n timestamp: currentDate,\n headers: responseHeaders,\n },\n };\n }\n\n private async pollForImageUrl(\n generationId: string,\n headers: Record<string, string | undefined>,\n abortSignal: AbortSignal | undefined,\n pollSettings?: { pollIntervalMillis?: number; maxPollAttempts?: number },\n ): Promise<string> {\n const url = this.getLumaGenerationsUrl(generationId);\n const maxPollAttempts =\n pollSettings?.maxPollAttempts ?? this.maxPollAttempts;\n const pollIntervalMillis =\n pollSettings?.pollIntervalMillis ?? this.pollIntervalMillis;\n\n for (let i = 0; i < maxPollAttempts; i++) {\n const { value: statusResponse } = await getFromApi({\n url,\n headers,\n abortSignal,\n fetch: this.config.fetch,\n failedResponseHandler: this.createLumaErrorHandler(),\n successfulResponseHandler: createJsonResponseHandler(\n lumaGenerationResponseSchema,\n ),\n });\n\n switch (statusResponse.state) {\n case 'completed':\n if (!statusResponse.assets?.image) {\n throw new InvalidResponseDataError({\n data: statusResponse,\n message: `Image generation completed but no image was found.`,\n });\n }\n return statusResponse.assets.image;\n case 'failed':\n throw new InvalidResponseDataError({\n data: statusResponse,\n message: `Image generation failed.`,\n });\n }\n await delay(pollIntervalMillis);\n }\n\n throw new Error(\n `Image generation timed out after ${this.maxPollAttempts} attempts.`,\n );\n }\n\n private createLumaErrorHandler() {\n return createJsonErrorResponseHandler({\n errorSchema: lumaErrorSchema,\n errorToMessage: (error: LumaErrorData) =>\n error.detail[0].msg ?? 'Unknown error',\n });\n }\n\n private getEditingOptions(\n files: ImageModelV4File[] | undefined,\n mask: ImageModelV4File | undefined,\n referenceType: LumaReferenceType = 'image',\n imageConfigs: Array<{ weight?: number | null; id?: string | null }> = [],\n ): Record<string, unknown> {\n const options: Record<string, unknown> = {};\n\n // Luma does not support mask-based inpainting\n if (mask != null) {\n throw new Error(\n 'Luma AI does not support mask-based image editing. ' +\n 'Use the prompt to describe the changes you want to make, along with ' +\n '`prompt.images` containing the source image URL.',\n );\n }\n\n if (files == null || files.length === 0) {\n return options;\n }\n\n // Validate all files are URL-based\n for (const file of files) {\n if (file.type !== 'url') {\n throw new Error(\n 'Luma AI only supports URL-based images. ' +\n 'Please provide image URLs using `prompt.images` with publicly accessible URLs. ' +\n 'Base64 and Uint8Array data are not supported.',\n );\n }\n }\n\n // Default weights per reference type\n const defaultWeights: Record<LumaReferenceType, number> = {\n image: 0.85,\n style: 0.8,\n character: 1.0, // Not used, but defined for completeness\n modify_image: 1.0,\n };\n\n switch (referenceType) {\n case 'image': {\n // Supports up to 4 images\n if (files.length > 4) {\n throw new Error(\n 'Luma AI image supports up to 4 reference images. ' +\n `You provided ${files.length} images.`,\n );\n }\n options.image = files.map((file, index) => ({\n url: (file as { type: 'url'; url: string }).url,\n weight: imageConfigs[index]?.weight ?? defaultWeights.image,\n }));\n break;\n }\n\n case 'style': {\n // Style ref accepts an array but typically uses one style image\n options.style = files.map((file, index) => ({\n url: (file as { type: 'url'; url: string }).url,\n weight: imageConfigs[index]?.weight ?? defaultWeights.style,\n }));\n break;\n }\n\n case 'character': {\n // Group images by identity id\n const identities: Record<string, string[]> = {};\n for (let i = 0; i < files.length; i++) {\n const file = files[i] as { type: 'url'; url: string };\n const identityId = imageConfigs[i]?.id ?? 'identity0';\n if (!identities[identityId]) {\n identities[identityId] = [];\n }\n identities[identityId].push(file.url);\n }\n\n // Validate each identity has at most 4 images\n for (const [identityId, images] of Object.entries(identities)) {\n if (images.length > 4) {\n throw new Error(\n `Luma AI character supports up to 4 images per identity. ` +\n `Identity '${identityId}' has ${images.length} images.`,\n );\n }\n }\n\n options.character = Object.fromEntries(\n Object.entries(identities).map(([id, images]) => [id, { images }]),\n );\n break;\n }\n\n case 'modify_image': {\n // Only supports a single image\n if (files.length > 1) {\n throw new Error(\n 'Luma AI modify_image only supports a single input image. ' +\n `You provided ${files.length} images.`,\n );\n }\n options.modify_image = {\n url: (files[0] as { type: 'url'; url: string }).url,\n weight: imageConfigs[0]?.weight ?? defaultWeights.modify_image,\n };\n break;\n }\n }\n\n return options;\n }\n\n private getLumaGenerationsUrl(generationId?: string) {\n return `${this.config.baseURL}/dream-machine/v1/generations/${\n generationId ?? 'image'\n }`;\n }\n\n private async downloadImage(\n url: string,\n abortSignal: AbortSignal | undefined,\n ): Promise<Uint8Array> {\n const { value: response } = await getFromApi({\n url,\n // No specific headers should be needed for this request as it's a\n // generated image provided by Luma.\n abortSignal,\n failedResponseHandler: createStatusCodeErrorResponseHandler(),\n successfulResponseHandler: createBinaryResponseHandler(),\n fetch: this.config.fetch,\n });\n return response;\n }\n}\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nconst lumaGenerationResponseSchema = lazySchema(() =>\n zodSchema(\n z.object({\n id: z.string(),\n state: z.enum(['queued', 'dreaming', 'completed', 'failed']),\n failure_reason: z.string().nullish(),\n assets: z\n .object({\n image: z.string(), // URL of the generated image\n })\n .nullish(),\n }),\n ),\n);\n\nconst lumaErrorSchema = z.object({\n detail: z.array(\n z.object({\n type: z.string(),\n loc: z.array(z.string()),\n msg: z.string(),\n input: z.string(),\n ctx: z\n .object({\n expected: z.string(),\n })\n .nullish(),\n }),\n ),\n});\n\nexport type LumaErrorData = z.infer<typeof lumaErrorSchema>;\n\n/**\n * Provider options schema for Luma image generation.\n *\n * @see https://docs.lumalabs.ai/docs/image-generation\n */\nexport const lumaImageModelOptionsSchema = lazySchema(() =>\n zodSchema(\n z\n .object({\n /**\n * The type of image reference to use when providing input images.\n * - `image`: Guide generation using reference images (up to 4). Default.\n * - `style`: Apply a specific style from reference image(s).\n * - `character`: Create consistent characters from reference images (up to 4).\n * - `modify_image`: Transform a single input image with prompt guidance.\n */\n referenceType: z\n .enum(['image', 'style', 'character', 'modify_image'])\n .nullish(),\n\n /**\n * Per-image configuration array. Each entry corresponds to an image in `prompt.images`.\n * Allows setting individual weights for each reference image.\n */\n images: z\n .array(\n z.object({\n /**\n * The weight of this image's influence on the generation.\n * - For `image`: Higher weight = closer to reference (default: 0.85)\n * - For `style`: Higher weight = stronger style influence (default: 0.8)\n * - For `modify_image`: Higher weight = closer to input, lower = more creative (default: 1.0)\n */\n weight: z.number().min(0).max(1).nullish(),\n\n /**\n * The identity name for character references.\n * Used with `character` to specify which identity group the image belongs to.\n * Luma supports multiple identities (e.g., 'identity0', 'identity1') for generating\n * images with multiple consistent characters.\n * Default: 'identity0'\n */\n id: z.string().nullish(),\n }),\n )\n .nullish(),\n\n /**\n * Override the polling interval in milliseconds (default 500).\n */\n pollIntervalMillis: z.number().nullish(),\n\n /**\n * Override the maximum number of polling attempts (default 120).\n */\n maxPollAttempts: z.number().nullish(),\n })\n .passthrough(),\n ),\n);\n\nexport type LumaImageModelOptions = InferSchema<\n typeof lumaImageModelOptionsSchema\n>;\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n"],"mappings":";AAAA,SAAuB,wBAAoC;AAC3D;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACNP;AAAA,EAIE;AAAA,OACK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,SAAS;AAElB,IAAM,+BAA+B;AACrC,IAAM,4BAA4B,MAAQ;AAYnC,IAAM,iBAAN,MAAM,gBAAuC;AAAA,EAwBlD,YACW,SACQ,QACjB;AAFS;AACQ;AAzBnB,SAAS,uBAAuB;AAChC,SAAS,mBAAmB;AAC5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EACjB,CAAC;AAEH,QAAM,iBAAiB,CAAC,YAAoB;AAC1C,UAAM,IAAI,iBAAiB;AAAA,MACzB;AAAA,MACA,WAAW;AAAA,IACb,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL,sBAAsB;AAAA,IACtB,OAAO;AAAA,IACP,YAAY;AAAA,IACZ,eAAe,CAAC,YAAoB;AAClC,YAAM,IAAI,iBAAiB;AAAA,QACzB;AAAA,QACA,WAAW;AAAA,MACb,CAAC;AAAA,IACH;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,EACtB;AACF;AAEO,IAAM,OAAO,WAAW;","names":["_a","_b"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-sdk/luma",
|
|
3
|
-
"version": "3.0.0-beta.
|
|
3
|
+
"version": "3.0.0-beta.22",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -29,8 +29,8 @@
|
|
|
29
29
|
}
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@ai-sdk/provider": "4.0.0-beta.
|
|
33
|
-
"@ai-sdk/provider-utils": "5.0.0-beta.
|
|
32
|
+
"@ai-sdk/provider": "4.0.0-beta.12",
|
|
33
|
+
"@ai-sdk/provider-utils": "5.0.0-beta.21"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@types/node": "20.17.24",
|
package/src/luma-image-model.ts
CHANGED
|
@@ -18,6 +18,9 @@ import {
|
|
|
18
18
|
lazySchema,
|
|
19
19
|
parseProviderOptions,
|
|
20
20
|
zodSchema,
|
|
21
|
+
serializeModelOptions,
|
|
22
|
+
WORKFLOW_SERIALIZE,
|
|
23
|
+
WORKFLOW_DESERIALIZE,
|
|
21
24
|
} from '@ai-sdk/provider-utils';
|
|
22
25
|
import { LumaReferenceType } from './luma-image-settings';
|
|
23
26
|
import { z } from 'zod/v4';
|
|
@@ -28,7 +31,7 @@ const DEFAULT_MAX_POLL_ATTEMPTS = 60000 / DEFAULT_POLL_INTERVAL_MILLIS;
|
|
|
28
31
|
interface LumaImageModelConfig {
|
|
29
32
|
provider: string;
|
|
30
33
|
baseURL: string;
|
|
31
|
-
headers
|
|
34
|
+
headers?: () => Record<string, string>;
|
|
32
35
|
fetch?: FetchFunction;
|
|
33
36
|
_internal?: {
|
|
34
37
|
currentDate?: () => Date;
|
|
@@ -45,6 +48,20 @@ export class LumaImageModel implements ImageModelV4 {
|
|
|
45
48
|
return this.config.provider;
|
|
46
49
|
}
|
|
47
50
|
|
|
51
|
+
static [WORKFLOW_SERIALIZE](model: LumaImageModel) {
|
|
52
|
+
return serializeModelOptions({
|
|
53
|
+
modelId: model.modelId,
|
|
54
|
+
config: model.config,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
static [WORKFLOW_DESERIALIZE](options: {
|
|
59
|
+
modelId: string;
|
|
60
|
+
config: LumaImageModelConfig;
|
|
61
|
+
}) {
|
|
62
|
+
return new LumaImageModel(options.modelId, options.config);
|
|
63
|
+
}
|
|
64
|
+
|
|
48
65
|
constructor(
|
|
49
66
|
readonly modelId: string,
|
|
50
67
|
private readonly config: LumaImageModelConfig,
|
|
@@ -107,7 +124,7 @@ export class LumaImageModel implements ImageModelV4 {
|
|
|
107
124
|
);
|
|
108
125
|
|
|
109
126
|
const currentDate = this.config._internal?.currentDate?.() ?? new Date();
|
|
110
|
-
const fullHeaders = combineHeaders(this.config.headers(), headers);
|
|
127
|
+
const fullHeaders = combineHeaders(this.config.headers?.(), headers);
|
|
111
128
|
const { value: generationResponse, responseHeaders } = await postJsonToApi({
|
|
112
129
|
url: this.getLumaGenerationsUrl(),
|
|
113
130
|
headers: fullHeaders,
|