### Install Dependencies and Build Project Source: https://github.com/lumalabs/lumaai-node/blob/main/CONTRIBUTING.md Run these commands to install all necessary dependencies and build the project's output files. ```sh $ yarn $ yarn build ``` -------------------------------- ### Install from Git Source: https://github.com/lumalabs/lumaai-node/blob/main/CONTRIBUTING.md Use this command to install the repository directly from a Git URL. ```sh $ npm install git+ssh://git@github.com:lumalabs/lumaai-node.git ``` -------------------------------- ### Add and Run Examples Source: https://github.com/lumalabs/lumaai-node/blob/main/CONTRIBUTING.md Create new TypeScript example files in the `examples/` directory and make them executable. Run them against your API. ```ts // add an example to examples/.ts #!/usr/bin/env -S npm run tsn -T … ``` ```sh $ chmod +x examples/.ts # run the example against your api $ yarn tsn -T examples/.ts ``` -------------------------------- ### Install LumaAI Node Library Source: https://github.com/lumalabs/lumaai-node/blob/main/README.md Install the LumaAI Node.js library using npm. This is the first step to integrate with the LumaAI API. ```sh npm install lumaai ``` -------------------------------- ### Install Runtime Shims Source: https://github.com/lumalabs/lumaai-node/blob/main/src/_shims/README.md Runtime shims are installed by calling `setShims` exported by `lumaai/_shims/registry`. This is typically handled automatically or via manual imports. ```javascript import { setShims } from 'lumaai/_shims/registry'; // Example usage with specific shims (usually done internally or via manual imports) // setShims(nodeRuntimeShims); ``` -------------------------------- ### Customize Fetch Client with Middleware Source: https://github.com/lumalabs/lumaai-node/blob/main/README.md Provide a custom `fetch` function during client instantiation to inspect or alter requests and responses. This example uses `undici`'s fetch for logging. ```typescript import { fetch } from 'undici'; // as one example import LumaAI from 'lumaai'; const client = new LumaAI({ fetch: async (url: RequestInfo, init?: RequestInit): Promise => { console.log('About to make a request', url, init); const response = await fetch(url, init); console.log('Got response', response); return response; }, }); ``` -------------------------------- ### Create Video Generation using Video Resource Source: https://context7.com/lumalabs/lumaai-node/llms.txt An alternative endpoint for video generation using the dedicated video resource, offering the same functionality as `client.generations.create()`. This example demonstrates creating a video with keyframes. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); const generation = await client.generations.video.create({ model: 'ray-2', prompt: 'A serene lake surrounded by mountains at sunset', aspect_ratio: '16:9', duration: '9s', resolution: '720p', loop: true, keyframes: { frame0: { type: 'image', url: 'https://example.com/lake-photo.jpg', }, }, }); console.log('Video generation started:', generation.id); ``` -------------------------------- ### Get Credits Balance Source: https://context7.com/lumalabs/lumaai-node/llms.txt Retrieve the current credits balance for your API account in USD cents. ```APIDOC ## Get Credits Balance ### Description Retrieve the current credits balance for your API account in USD cents. ### Method GET ### Endpoint /credits ### Parameters None ### Request Example ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); const credits = await client.credits.get(); console.log('Credit balance:', credits.credit_balance, 'cents'); console.log('Balance in USD:', (credits.credit_balance / 100).toFixed(2)); // Check before expensive operation if (credits.credit_balance < 100) { console.warn('Low credits! Please top up your account.'); } ``` ### Response #### Success Response (200) - **credit_balance** (integer) - The current credit balance in USD cents. #### Response Example ```json { "credit_balance": 5000 } ``` ``` -------------------------------- ### Get Credits Balance with LumaAI SDK Source: https://context7.com/lumalabs/lumaai-node/llms.txt Retrieve the current API credits balance in USD cents. Includes a check for low credit warnings. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); const credits = await client.credits.get(); console.log('Credit balance:', credits.credit_balance, 'cents'); console.log('Balance in USD:', (credits.credit_balance / 100).toFixed(2)); // Check before expensive operation if (credits.credit_balance < 100) { console.warn('Low credits! Please top up your account.'); } ``` -------------------------------- ### Access Raw Response Data with LumaAI Source: https://github.com/lumalabs/lumaai-node/blob/main/README.md Use `.asResponse()` to get the raw Response object, or `.withResponse()` to get both the parsed data and the raw Response. This is useful for inspecting headers or status messages. ```typescript const client = new LumaAI(); const response = await client.generations .create({ model: 'ray-2', aspect_ratio: '16:9', prompt: 'A teddy bear in sunglasses playing electric guitar, dancing and headbanging in the jungle in front of a large beautiful waterfall', }) .asResponse(); console.log(response.headers.get('X-My-Header')); console.log(response.statusText); // access the underlying Response object const { data: generation, response: raw } = await client.generations .create({ model: 'ray-2', aspect_ratio: '16:9', prompt: 'A teddy bear in sunglasses playing electric guitar, dancing and headbanging in the jungle in front of a large beautiful waterfall', }) .withResponse(); console.log(raw.headers.get('X-My-Header')); console.log(generation.id); ``` -------------------------------- ### Configure Per-Request Timeout for LumaAI Client Source: https://github.com/lumalabs/lumaai-node/blob/main/README.md Override the default timeout for a specific API request by providing the `timeout` option. This example sets the timeout to 5 seconds for a single request. ```ts // Override per-request: await client.generations.create({ model: 'ray-2', aspect_ratio: '16:9', prompt: 'A teddy bear in sunglasses playing electric guitar, dancing and headbanging in the jungle in front of a large beautiful waterfall', }, { timeout: 5 * 1000, }); ``` -------------------------------- ### Configure Default Timeout for LumaAI Client Source: https://github.com/lumalabs/lumaai-node/blob/main/README.md Set a default timeout for all API requests made with the LumaAI client. The default timeout is 1 minute. This example sets it to 20 seconds. ```ts // Configure the default for all requests: const client = new LumaAI({ timeout: 20 * 1000, // 20 seconds (default is 1 minute) }); ``` -------------------------------- ### Delete Generation with LumaAI SDK Source: https://context7.com/lumalabs/lumaai-node/llms.txt Remove a specific generation by its ID. Includes an example with error handling for cases where the generation might not be found. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // Delete a generation await client.generations.delete('gen_abc123'); console.log('Generation deleted successfully'); // Delete with error handling try { await client.generations.delete('gen_xyz789'); } catch (error) { if (error instanceof LumaAI.NotFoundError) { console.log('Generation not found or already deleted'); } else { throw error; } } ``` -------------------------------- ### Get Generation Status and Poll for Completion Source: https://context7.com/lumalabs/lumaai-node/llms.txt Retrieves the status of a generation by its ID and provides a polling function to wait for completion or failure. Useful for tracking asynchronous generation tasks. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // Get generation status const generation = await client.generations.get('gen_abc123'); console.log('ID:', generation.id); console.log('Type:', generation.generation_type); // 'video' or 'image' console.log('Model:', generation.model); console.log('State:', generation.state); console.log('Created:', generation.created_at); if (generation.state === 'completed') { console.log('Video URL:', generation.assets?.video); console.log('Image URL:', generation.assets?.image); } if (generation.state === 'failed') { console.log('Failure reason:', generation.failure_reason); } // Polling pattern for completion async function waitForCompletion(generationId: string): Promise { while (true) { const gen = await client.generations.get(generationId); if (gen.state === 'completed') { return gen; } if (gen.state === 'failed') { throw new Error(`Generation failed: ${gen.failure_reason}`); } // Wait 5 seconds before polling again await new Promise(resolve => setTimeout(resolve, 5000)); } } const completed = await waitForCompletion('gen_abc123'); console.log('Final video:', completed.assets?.video); ``` -------------------------------- ### Use Undocumented Request Parameters Source: https://github.com/lumalabs/lumaai-node/blob/main/README.md Employ `// @ts-expect-error` to include undocumented parameters in requests. Extra values are sent as-is. For GET requests, extra params go to the query; otherwise, they go to the body. ```typescript client.foo.create({ foo: 'my_param', bar: 12, // @ts-expect-error baz is not yet public baz: 'undocumented option', }); ``` -------------------------------- ### Access Raw HTTP Response Source: https://context7.com/lumalabs/lumaai-node/llms.txt Retrieve the raw HTTP response object, including headers and status codes, for advanced debugging or extracting rate limit information. You can get either just the raw response or both the parsed data and the raw response. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // Get raw response object const response = await client.generations.create({ model: 'ray-2', prompt: 'A scenic mountain landscape', }).asResponse(); console.log('Status:', response.status); console.log('Headers:', response.headers); ``` ```typescript // Get both parsed data and raw response const { data: generation, response: raw } = await client.generations.create({ model: 'ray-2', prompt: 'A beautiful forest', }).withResponse(); console.log('Generation ID:', generation.id); console.log('Rate limit remaining:', raw.headers.get('x-ratelimit-remaining')); ``` -------------------------------- ### Run Mock Server Source: https://github.com/lumalabs/lumaai-node/blob/main/CONTRIBUTING.md Execute this script to set up a mock server for running tests against the OpenAPI spec. ```sh $ ./scripts/mock ``` -------------------------------- ### Client Initialization Source: https://context7.com/lumalabs/lumaai-node/llms.txt Initialize the LumaAI client with your API key. The client can automatically read the API key from the `LUMAAI_API_KEY` environment variable or accept it explicitly. ```APIDOC ## Client Initialization Initialize the LumaAI client with your API key to start making requests. The client automatically reads from the `LUMAAI_API_KEY` environment variable if not provided explicitly. ```typescript import LumaAI from 'lumaai'; // Initialize with environment variable (recommended) const client = new LumaAI(); // Or initialize with explicit API key const client = new LumaAI({ authToken: 'your-api-key-here', }); // Full configuration options const client = new LumaAI({ authToken: process.env['LUMAAI_API_KEY'], baseURL: 'https://api.lumalabs.ai/dream-machine/v1', // default timeout: 60000, // 1 minute default maxRetries: 2, // automatic retry on failure }); ``` ``` -------------------------------- ### Run Tests Source: https://github.com/lumalabs/lumaai-node/blob/main/CONTRIBUTING.md Execute the test suite for the repository. ```sh $ yarn run test ``` -------------------------------- ### List Concepts with LumaAI SDK Source: https://context7.com/lumalabs/lumaai-node/llms.txt Retrieve all available concept keywords for use in video generations. Also shows how to apply concepts during generation creation. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // Get available concepts const concepts = await client.generations.concepts.list(); console.log('Available concepts:', concepts); // Returns array of concept key strings // Use concepts in video generation const generation = await client.generations.create({ model: 'ray-2', prompt: 'Walking through a city street', aspect_ratio: '16:9', concepts: [ { key: 'concept_key_1' }, { key: 'concept_key_2' }, ], }); ``` -------------------------------- ### Link Local Repository with PNPM Source: https://github.com/lumalabs/lumaai-node/blob/main/CONTRIBUTING.md Clone the repository, link it globally, and then link it to your local package using PNPM. ```sh # With pnpm $ pnpm link --global $ cd ../my-package $ pnpm link --global lumaai ``` -------------------------------- ### Create a Generation with LumaAI Client Source: https://github.com/lumalabs/lumaai-node/blob/main/README.md Initialize the LumaAI client and create a new generation. Ensure your LUMAAI_API_KEY is set in the environment variables. The default model is 'ray-2' and aspect ratio is '16:9'. ```js import LumaAI from 'lumaai'; const client = new LumaAI({ authToken: process.env['LUMAAI_API_KEY'], // This is the default and can be omitted }); const generation = await client.generations.create({ model: 'ray-2', aspect_ratio: '16:9', prompt: 'A teddy bear in sunglasses playing electric guitar, dancing and headbanging in the jungle in front of a large beautiful waterfall', }); console.log(generation.id); ``` -------------------------------- ### Initialize LumaAI Client Source: https://context7.com/lumalabs/lumaai-node/llms.txt Initialize the LumaAI client with your API key. The client can read the API key from the LUMAAI_API_KEY environment variable or accept it explicitly. Full configuration options include baseURL, timeout, and maxRetries. ```typescript import LumaAI from 'lumaai'; // Initialize with environment variable (recommended) const client = new LumaAI(); ``` ```typescript import LumaAI from 'lumaai'; // Or initialize with explicit API key const client = new LumaAI({ authToken: 'your-api-key-here', }); ``` ```typescript import LumaAI from 'lumaai'; // Full configuration options const client = new LumaAI({ authToken: process.env['LUMAAI_API_KEY'], baseURL: 'https://api.lumalabs.ai/dream-machine/v1', // default timeout: 60000, // 1 minute default maxRetries: 2, // automatic retry on failure }); ``` -------------------------------- ### Configure Web Fetch Shim Source: https://github.com/lumalabs/lumaai-node/blob/main/README.md Import 'lumaai/shims/web' to instruct TypeScript and the package to use the global web fetch instead of node-fetch. This expects polyfills to be provided if needed. ```typescript // Tell TypeScript and the package to use the global web fetch instead of node-fetch. // Note, despite the name, this does not add any polyfills, but expects them to be provided if needed. import 'lumaai/shims/web'; import LumaAI from 'lumaai'; ``` -------------------------------- ### Create Video Generation from Prompt Source: https://context7.com/lumalabs/lumaai-node/llms.txt Generate AI videos using the Ray-2 or Ray-Flash-2 models from text prompts. Supports aspect ratio, resolution, duration, and loop options. Use keyframes for image-to-video workflows. A callback URL can be provided for webhook notifications. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // Basic video generation from prompt const generation = await client.generations.create({ model: 'ray-2', prompt: 'A teddy bear in sunglasses playing electric guitar, dancing and headbanging in the jungle in front of a large beautiful waterfall', aspect_ratio: '16:9', duration: '5s', resolution: '1080p', loop: false, }); console.log('Generation ID:', generation.id); console.log('State:', generation.state); // 'queued', 'dreaming', 'completed', 'failed' ``` ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // Image-to-video with keyframes const imageToVideo = await client.generations.create({ model: 'ray-2', prompt: 'Camera slowly zooms in on the subject', aspect_ratio: '16:9', keyframes: { frame0: { type: 'image', url: 'https://example.com/start-image.jpg', }, frame1: { type: 'image', url: 'https://example.com/end-image.jpg', }, }, }); ``` ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // Use callback URL for webhook notifications const withCallback = await client.generations.create({ model: 'ray-flash-2', // faster model prompt: 'Cinematic drone shot over mountains at sunset', aspect_ratio: '21:9', callback_url: 'https://your-server.com/webhook/luma', }); ``` -------------------------------- ### Publish NPM Package Manually Source: https://github.com/lumalabs/lumaai-node/blob/main/CONTRIBUTING.md Run this script to manually publish the package to npm. Ensure the NPM_TOKEN environment variable is set. ```sh bin/publish-npm ``` -------------------------------- ### Link Local Repository with Yarn Source: https://github.com/lumalabs/lumaai-node/blob/main/CONTRIBUTING.md Clone the repository, link it globally, and then link it to your local package using Yarn. ```sh # Clone $ git clone https://www.github.com/lumalabs/lumaai-node $ cd lumaai-node # With yarn $ yarn link $ cd ../my-package $ yarn link lumaai ``` -------------------------------- ### POST /generations Source: https://context7.com/lumalabs/lumaai-node/llms.txt Generate AI videos from text prompts using the Ray-2 or Ray-Flash-2 models. Supports various aspect ratios, resolutions, durations, and optional keyframe control for image-to-video workflows. ```APIDOC ## POST /generations Generate AI videos from text prompts using the Ray-2 or Ray-Flash-2 models. Supports various aspect ratios, resolutions, durations, and optional keyframe control for image-to-video workflows. ### Method POST ### Endpoint /generations ### Parameters #### Request Body - **model** (string) - Required - The generative model to use (e.g., 'ray-2', 'ray-flash-2'). - **prompt** (string) - Required - The text prompt describing the desired video content. - **aspect_ratio** (string) - Optional - The desired aspect ratio of the video (e.g., '16:9', '21:9'). - **duration** (string) - Optional - The desired duration of the video (e.g., '5s', '9s'). - **resolution** (string) - Optional - The desired resolution of the video (e.g., '1080p', '720p'). - **loop** (boolean) - Optional - Whether the video should loop. - **keyframes** (object) - Optional - Keyframe configuration for image-to-video workflows. - **frame0** (object) - Required if keyframes are used - Configuration for the first frame. - **type** (string) - Required - Type of the keyframe content ('image'). - **url** (string) - Required - URL of the image for the keyframe. - **frame1** (object) - Optional - Configuration for subsequent frames. - **type** (string) - Required - Type of the keyframe content ('image'). - **url** (string) - Required - URL of the image for the keyframe. - **callback_url** (string) - Optional - A URL to receive webhook notifications upon generation completion. ### Request Example ```json { "model": "ray-2", "prompt": "A teddy bear in sunglasses playing electric guitar, dancing and headbanging in the jungle in front of a large beautiful waterfall", "aspect_ratio": "16:9", "duration": "5s", "resolution": "1080p", "loop": false } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the generation. - **state** (string) - The current state of the generation ('queued', 'dreaming', 'completed', 'failed'). #### Response Example ```json { "id": "gen_abc123", "state": "queued" } ``` ``` -------------------------------- ### Lint Code Source: https://github.com/lumalabs/lumaai-node/blob/main/CONTRIBUTING.md Run this command to check the code for linting issues. ```sh $ yarn lint ``` -------------------------------- ### Add Audio to Generation with LumaAI SDK Source: https://context7.com/lumalabs/lumaai-node/llms.txt Add AI-generated audio to an existing video generation using text prompts. Requires a generation ID and audio description. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // Add audio to a completed video const withAudio = await client.generations.audio('gen_video123', { generation_type: 'add_audio', prompt: 'Ambient forest sounds with birds chirping and gentle wind', negative_prompt: 'music, voices, traffic noise', callback_url: 'https://your-server.com/webhook/audio-complete', }); console.log('Audio generation started:', withAudio.id); console.log('State:', withAudio.state); ``` -------------------------------- ### Add Audio to Generation Source: https://context7.com/lumalabs/lumaai-node/llms.txt Add AI-generated audio to an existing video generation using text prompts to describe the desired sound. ```APIDOC ## Add Audio to Generation ### Description Add AI-generated audio to an existing video generation using text prompts to describe the desired sound. ### Method POST ### Endpoint /generations/{generation_id}/audio ### Parameters #### Path Parameters - **generation_id** (string) - Required - The ID of the video generation to add audio to. #### Request Body - **prompt** (string) - Required - Text prompt describing the desired audio. - **negative_prompt** (string) - Optional - Text prompt describing audio elements to exclude. - **callback_url** (string) - Optional - URL to receive webhook notifications when audio generation is complete. ### Request Example ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // Add audio to a completed video const withAudio = await client.generations.audio('gen_video123', { generation_type: 'add_audio', prompt: 'Ambient forest sounds with birds chirping and gentle wind', negative_prompt: 'music, voices, traffic noise', callback_url: 'https://your-server.com/webhook/audio-complete', }); console.log('Audio generation started:', withAudio.id); console.log('State:', withAudio.state); ``` ### Response #### Success Response (200) - **id** (string) - The ID of the new audio generation task. - **state** (string) - The current state of the audio generation (e.g., 'processing', 'completed'). #### Response Example ```json { "id": "gen_audio456", "state": "processing" } ``` ``` -------------------------------- ### List Concepts Source: https://context7.com/lumalabs/lumaai-node/llms.txt Retrieve all available concept keywords that can be used in video generations for consistent character or style references. ```APIDOC ## List Concepts ### Description Retrieve all available concept keywords that can be used in video generations for consistent character or style references. ### Method GET ### Endpoint /generations/concepts ### Parameters None ### Request Example ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // Get available concepts const concepts = await client.generations.concepts.list(); console.log('Available concepts:', concepts); // Returns array of concept key strings // Use concepts in video generation const generation = await client.generations.create({ model: 'ray-2', prompt: 'Walking through a city street', aspect_ratio: '16:9', concepts: [ { key: 'concept_key_1' }, { key: 'concept_key_2' }, ], }); ``` ### Response #### Success Response (200) - **concepts** (array) - An array of strings, where each string is a concept key. #### Response Example ```json [ "concept_key_1", "concept_key_2", "another_concept" ] ``` ``` -------------------------------- ### Configure HTTP Agent for Proxies Source: https://github.com/lumalabs/lumaai-node/blob/main/README.md Pass an httpAgent to the LumaAI client constructor to route all requests through a proxy. Alternatively, override the agent on a per-request basis. ```typescript import http from 'http'; import { HttpsProxyAgent } from 'https-proxy-agent'; // Configure the default for all requests: const client = new LumaAI({ httpAgent: new HttpsProxyAgent(process.env.PROXY_URL), }); // Override per-request: await client.generations.create( { model: 'ray-2', aspect_ratio: '16:9', prompt: 'A teddy bear in sunglasses playing electric guitar, dancing and headbanging in the jungle in front of a large beautiful waterfall', }, { httpAgent: new http.Agent({ keepAlive: false }), }, ); ``` -------------------------------- ### Manually Import Web Shims Source: https://github.com/lumalabs/lumaai-node/blob/main/src/_shims/README.md Manually import web shims if you need to ensure the use of the global fetch API, overriding any Node.js specific shims. ```javascript import 'lumaai/shims/web' ``` -------------------------------- ### POST /generations/video Source: https://context7.com/lumalabs/lumaai-node/llms.txt Alternative endpoint for video generation through the dedicated video resource, providing the same functionality as `client.generations.create()`. ```APIDOC ## POST /generations/video Alternative endpoint for video generation through the dedicated video resource, providing the same functionality as `client.generations.create()`. ### Method POST ### Endpoint /generations/video ### Parameters #### Request Body - **model** (string) - Required - The generative model to use (e.g., 'ray-2'). - **prompt** (string) - Required - The text prompt describing the desired video content. - **aspect_ratio** (string) - Optional - The desired aspect ratio of the video (e.g., '16:9'). - **duration** (string) - Optional - The desired duration of the video (e.g., '9s'). - **resolution** (string) - Optional - The desired resolution of the video (e.g., '720p'). - **loop** (boolean) - Optional - Whether the video should loop. - **keyframes** (object) - Optional - Keyframe configuration for image-to-video workflows. - **frame0** (object) - Required if keyframes are used - Configuration for the first frame. - **type** (string) - Required - Type of the keyframe content ('image'). - **url** (string) - Required - URL of the image for the keyframe. ### Request Example ```json { "model": "ray-2", "prompt": "A serene lake surrounded by mountains at sunset", "aspect_ratio": "16:9", "duration": "9s", "resolution": "720p", "loop": true, "keyframes": { "frame0": { "type": "image", "url": "https://example.com/lake-photo.jpg" } } } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the video generation. #### Response Example ```json { "id": "gen_xyz789" } ``` ``` -------------------------------- ### Upscale Generation with LumaAI SDK Source: https://context7.com/lumalabs/lumaai-node/llms.txt Increase the resolution of an existing video generation. Supports various resolutions like '540p', '720p', '1080p', and '4k'. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // Upscale video to 4K const upscaled = await client.generations.upscale('gen_video123', { generation_type: 'upscale_video', resolution: '4k', // '540p', '720p', '1080p', '4k' callback_url: 'https://your-server.com/webhook/upscale-complete', }); console.log('Upscale started:', upscaled.id); console.log('Target resolution:', upscaled.request); ``` -------------------------------- ### POST /generations/video/modify Source: https://context7.com/lumalabs/lumaai-node/llms.txt Transform existing videos using style transfer and prompt-based editing with different modification modes ranging from subtle adjustments (adhere) to complete reimagination. ```APIDOC ## POST /generations/video/modify Transform existing videos using style transfer and prompt-based editing with different modification modes ranging from subtle adjustments (adhere) to complete reimagination. ### Method POST ### Endpoint /generations/video/modify ### Parameters #### Request Body - **model** (string) - Required - The generative model to use (e.g., 'ray-2', 'ray-flash-2'). - **generation_type** (string) - Required - Must be 'modify_video'. - **media** (object) - Required - The source media for modification. - **url** (string) - Required - URL of the source video. - **mode** (string) - Required - The modification mode (e.g., 'adhere_1', 'flex_2', 'reimagine_3'). - **prompt** (string) - Required - The prompt describing the desired transformation. - **first_frame** (object) - Optional - Specifies a custom first frame for the modified video. - **url** (string) - Required - URL of the custom first frame image. - **callback_url** (string) - Optional - A URL to receive webhook notifications upon completion. ### Request Example ```json { "model": "ray-2", "generation_type": "modify_video", "media": { "url": "https://example.com/source-video.mp4" }, "mode": "adhere_1", "prompt": "Transform into a watercolor painting style" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the video modification. #### Response Example ```json { "id": "mod_def456" } ``` ``` -------------------------------- ### Format and Fix Lint Issues Source: https://github.com/lumalabs/lumaai-node/blob/main/CONTRIBUTING.md Automatically format the code and fix any identified linting issues. ```sh $ yarn fix ``` -------------------------------- ### List Generations with LumaAI SDK Source: https://context7.com/lumalabs/lumaai-node/llms.txt Retrieve a paginated list of generations. Useful for managing generation history. Handles pagination to retrieve all generations. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // List recent generations const response = await client.generations.list(); console.log('Total count:', response.count); console.log('Has more:', response.has_more); console.log('Limit:', response.limit); console.log('Offset:', response.offset); for (const gen of response.generations) { console.log(`${gen.id}: ${gen.state} (${gen.generation_type})`); } // Paginated listing const page1 = await client.generations.list({ limit: 10, offset: 0, }); const page2 = await client.generations.list({ limit: 10, offset: 10, }); // Iterate through all generations async function getAllGenerations(): Promise { const all: LumaAI.Generation[] = []; let offset = 0; const limit = 50; while (true) { const response = await client.generations.list({ limit, offset }); all.push(...response.generations); if (!response.has_more) break; offset += limit; } return all; } ``` -------------------------------- ### Create Image Generation Source: https://context7.com/lumalabs/lumaai-node/llms.txt Generates AI images from text prompts using specified models. Supports various options like aspect ratio, format, synchronous generation, and references for style, composition, and character consistency. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // Basic image generation const image = await client.generations.image.create({ model: 'photon-1', prompt: 'A majestic dragon perched on a mountain peak at dawn, fantasy art style', aspect_ratio: '16:9', format: 'png', }); // Synchronous generation (waits for completion) const syncImage = await client.generations.image.create({ model: 'photon-flash-1', prompt: 'Professional headshot portrait, studio lighting', aspect_ratio: '1:1', format: 'jpg', sync: true, sync_timeout: 30000, // 30 seconds }); // With style reference const styledImage = await client.generations.image.create({ model: 'photon-1', prompt: 'A futuristic city skyline', style_ref: [ { url: 'https://example.com/art-style-reference.jpg', weight: 0.8, }, ], }); // With image reference for composition const composedImage = await client.generations.image.create({ model: 'photon-1', prompt: 'A cozy coffee shop interior', image_ref: [ { url: 'https://example.com/layout-reference.jpg', weight: 0.6, }, ], }); // Character consistency with identity reference const characterImage = await client.generations.image.create({ model: 'photon-1', prompt: 'Portrait in a garden setting', character_ref: { identity0: { images: [ 'https://example.com/person-photo-1.jpg', 'https://example.com/person-photo-2.jpg', ], }, }, }); // Modify existing image const modifiedImage = await client.generations.image.create({ model: 'photon-1', prompt: 'Add dramatic sunset lighting', modify_image_ref: { url: 'https://example.com/original-photo.jpg', weight: 0.7, }, }); console.log('Image generation ID:', image.id); console.log('Assets:', image.assets?.image); // URL when completed ``` -------------------------------- ### Generations API Source: https://github.com/lumalabs/lumaai-node/blob/main/api.md Endpoints for creating, listing, retrieving, and deleting generations, as well as specific operations like adding audio, upscaling, and image/video manipulations. ```APIDOC ## POST /generations/video ### Description Creates a new video generation. ### Method POST ### Endpoint /generations/video ### Request Body - **params** (object) - Required - Parameters for video generation. ### Response #### Success Response (200) - **Generation** (object) - Details of the created generation. ``` ```APIDOC ## GET /generations ### Description Lists existing generations. ### Method GET ### Endpoint /generations ### Request Body - **params** (object) - Required - Parameters for listing generations. ### Response #### Success Response (200) - **GenerationListResponse** (object) - A list of generations. ``` ```APIDOC ## DELETE /generations/{id} ### Description Deletes a specific generation by its ID. ### Method DELETE ### Endpoint /generations/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the generation to delete. ### Response #### Success Response (200) - **void** - Indicates successful deletion. ``` ```APIDOC ## POST /generations/{id}/audio ### Description Adds audio to a specific generation. ### Method POST ### Endpoint /generations/{id}/audio ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the generation to add audio to. ### Request Body - **params** (object) - Required - Parameters for adding audio. ### Response #### Success Response (200) - **Generation** (object) - The updated generation with audio. ``` ```APIDOC ## GET /generations/{id} ### Description Retrieves a specific generation by its ID. ### Method GET ### Endpoint /generations/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the generation to retrieve. ### Response #### Success Response (200) - **Generation** (object) - Details of the requested generation. ``` ```APIDOC ## POST /generations/{id}/upscale ### Description Upscales a specific generation. ### Method POST ### Endpoint /generations/{id}/upscale ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the generation to upscale. ### Request Body - **params** (object) - Required - Parameters for upscaling. ### Response #### Success Response (200) - **Generation** (object) - The upscaled generation. ``` -------------------------------- ### Upscale Generation Source: https://context7.com/lumalabs/lumaai-node/llms.txt Increase the resolution of an existing video generation to higher quality outputs. ```APIDOC ## Upscale Generation ### Description Increase the resolution of an existing video generation to higher quality outputs. ### Method POST ### Endpoint /generations/{generation_id}/upscale ### Parameters #### Path Parameters - **generation_id** (string) - Required - The ID of the video generation to upscale. #### Request Body - **resolution** (string) - Required - The target resolution for the upscaled video. Options: '540p', '720p', '1080p', '4k'. - **callback_url** (string) - Optional - URL to receive webhook notifications when upscaling is complete. ### Request Example ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); // Upscale video to 4K const upscaled = await client.generations.upscale('gen_video123', { generation_type: 'upscale_video', resolution: '4k', // '540p', '720p', '1080p', '4k' callback_url: 'https://your-server.com/webhook/upscale-complete', }); console.log('Upscale started:', upscaled.id); console.log('Target resolution:', upscaled.request); ``` ### Response #### Success Response (200) - **id** (string) - The ID of the upscaling task. - **request** (object) - Details of the upscaling request. - **resolution** (string) - The requested resolution. #### Response Example ```json { "id": "gen_upscale789", "request": { "resolution": "4k" } } ``` ``` -------------------------------- ### Manually Import Node.js Shims Source: https://github.com/lumalabs/lumaai-node/blob/main/src/_shims/README.md Manually import Node.js shims if you encounter issues with automatic selection, especially with older TypeScript module resolution settings. ```javascript import 'lumaai/shims/node' ``` -------------------------------- ### Video Generation API Source: https://github.com/lumalabs/lumaai-node/blob/main/api.md Endpoints for creating, modifying, and reframing video generations. ```APIDOC ## POST /generations/video ### Description Creates a new video generation. ### Method POST ### Endpoint /generations/video ### Request Body - **params** (object) - Required - Parameters for video generation. ### Response #### Success Response (200) - **Generation** (object) - Details of the created generation. ``` ```APIDOC ## POST /generations/video/modify ### Description Modifies an existing video generation. ### Method POST ### Endpoint /generations/video/modify ### Request Body - **params** (object) - Required - Parameters for modifying the video. ### Response #### Success Response (200) - **Generation** (object) - The modified generation. ``` ```APIDOC ## POST /generations/video/reframe ### Description Reframes an existing video generation. ### Method POST ### Endpoint /generations/video/reframe ### Request Body - **params** (object) - Required - Parameters for reframing the video. ### Response #### Success Response (200) - **Generation** (object) - The reframed generation. ``` -------------------------------- ### Use TypeScript Definitions for Generation Source: https://github.com/lumalabs/lumaai-node/blob/main/README.md Utilize TypeScript definitions for request parameters and response fields when creating a generation. This improves type safety and developer experience. ```ts import LumaAI from 'lumaai'; const client = new LumaAI({ authToken: process.env['LUMAAI_API_KEY'], // This is the default and can be omitted }); const params: LumaAI.GenerationCreateParams = { model: 'ray-2', aspect_ratio: '16:9', prompt: 'A teddy bear in sunglasses playing electric guitar, dancing and headbanging in the jungle in front of a large beautiful waterfall', }; const generation: LumaAI.Generation = await client.generations.create(params); ``` -------------------------------- ### Reframe Video Aspect Ratio Source: https://context7.com/lumalabs/lumaai-node/llms.txt Converts a video to a new aspect ratio, intelligently filling new areas with AI generation. Requires a video URL, desired aspect ratio, and optionally a prompt and first frame reference. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); const reframed = await client.generations.video.reframe({ model: 'ray-2', generation_type: 'reframe_video', media: { url: 'https://example.com/horizontal-video.mp4', }, aspect_ratio: '9:16', // convert to vertical prompt: 'Extend the scene naturally', first_frame: { url: 'https://example.com/reference-frame.jpg', }, // Optional crop bounds x_start: 0, x_end: 1920, y_start: 0, y_end: 1080, resized_width: 1080, resized_height: 1920, }); console.log('Reframe generation ID:', reframed.id); ``` -------------------------------- ### Check API Health with LumaAI SDK Source: https://context7.com/lumalabs/lumaai-node/llms.txt Verify API accessibility and status using the ping check. Useful for monitoring and diagnostics. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); const ping = await client.ping.check(); console.log('API Status:', ping.message); // Expected: { message: 'pong' } ``` -------------------------------- ### Make Undocumented POST Requests Source: https://github.com/lumalabs/lumaai-node/blob/main/README.md Use `client.post` to make requests to undocumented endpoints. Options like retries are respected. Specify body, query parameters, and headers as needed. ```typescript await client.post('/some/path', { body: { some_prop: 'foo' }, query: { some_query_arg: 'bar' }, }); ``` -------------------------------- ### Handle API Errors with Specific Error Classes Source: https://context7.com/lumalabs/lumaai-node/llms.txt Catch and handle various API errors using specific error classes provided by the SDK. This includes network issues, authentication failures, and rate limiting. Configure retry behavior by setting maxRetries and timeout options during client initialization. ```typescript import LumaAI from 'lumaai'; const client = new LumaAI(); try { const generation = await client.generations.create({ model: 'ray-2', prompt: 'A beautiful sunset', }); } catch (error) { if (error instanceof LumaAI.BadRequestError) { // 400 - Invalid request parameters console.error('Bad request:', error.message); console.error('Status:', error.status); } else if (error instanceof LumaAI.AuthenticationError) { // 401 - Invalid or missing API key console.error('Authentication failed. Check your API key.'); } else if (error instanceof LumaAI.PermissionDeniedError) { // 403 - Insufficient permissions console.error('Permission denied for this operation.'); } else if (error instanceof LumaAI.NotFoundError) { // 404 - Resource not found console.error('Generation not found.'); } else if (error instanceof LumaAI.RateLimitError) { // 429 - Too many requests console.error('Rate limited. Please slow down requests.'); console.error('Headers:', error.headers); } else if (error instanceof LumaAI.InternalServerError) { // 500+ - Server error console.error('Server error. Please try again later.'); } else if (error instanceof LumaAI.APIConnectionError) { // Network connectivity issues console.error('Connection error:', error.message); } else if (error instanceof LumaAI.APIConnectionTimeoutError) { // Request timed out console.error('Request timed out. Consider increasing timeout.'); } else { throw error; } } ``` ```typescript // Configure retry behavior const clientWithRetries = new LumaAI({ maxRetries: 5, // Retry up to 5 times timeout: 120000, // 2 minute timeout }); ``` -------------------------------- ### Handle API Errors with LumaAI Client Source: https://github.com/lumalabs/lumaai-node/blob/main/README.md Implement error handling for API requests using a try-catch block. Catch specific `APIError` subclasses to handle different error statuses and names. ```ts const generation = await client.generations .create({ model: 'ray-2', aspect_ratio: '16:9', prompt: 'A teddy bear in sunglasses playing electric guitar, dancing and headbanging in the jungle in front of a large beautiful waterfall', }) .catch(async (err) => { if (err instanceof LumaAI.APIError) { console.log(err.status); // 400 console.log(err.name); // BadRequestError console.log(err.headers); // {server: 'nginx', ...} } else { throw err; } }); ``` -------------------------------- ### Credits API Source: https://github.com/lumalabs/lumaai-node/blob/main/api.md Endpoint to retrieve information about user credits. ```APIDOC ## GET /credits ### Description Retrieves the current credit balance for the authenticated user. ### Method GET ### Endpoint /credits ### Response #### Success Response (200) - **CreditGetResponse** (object) - Object containing credit information. ```