### Install from Local Wheel File Source: https://github.com/lumalabs/luma-agents-python/blob/main/CONTRIBUTING.md Install the package using a locally built wheel file after running the build command. ```sh pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Install Luma Python Library Source: https://github.com/lumalabs/luma-agents-python/blob/main/README.md Install the library using pip. This command installs the base package. ```sh pip install luma-agents ``` -------------------------------- ### Install from Git Source: https://github.com/lumalabs/luma-agents-python/blob/main/CONTRIBUTING.md Install the luma-agents-python package directly from its Git repository using pip. ```sh pip install git+ssh://git@github.com/lumalabs/luma-agents-python.git ``` -------------------------------- ### Add and Execute Example Script Source: https://github.com/lumalabs/luma-agents-python/blob/main/CONTRIBUTING.md Add new example scripts to the 'examples/' directory and make them executable. These scripts are not modified by the generator and can be freely edited. ```python # add an example to examples/.py #!/usr/bin/env -S rye run python … ``` ```sh chmod +x examples/.py # run the example against your api ./examples/.py ``` -------------------------------- ### Install Luma Python Library with aiohttp Source: https://github.com/lumalabs/luma-agents-python/blob/main/README.md Install the library with the aiohttp extra for improved concurrency performance in the asynchronous client. ```sh pip install luma-agents[aiohttp] ``` -------------------------------- ### Asynchronous File Operations Example Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/files.md This example demonstrates common asynchronous file operations using `AsyncLuma`. It covers creating a file, listing files, and retrieving file details. All methods require `await`. ```python import asyncio from luma_agents import AsyncLuma async def main(): client = AsyncLuma() # Create file response = await client.files.create( mime_type="image/jpeg", size_bytes=12345, filename="test.jpg", purpose="input", ) # List files files = await client.files.list(limit=10) print(f"Files: {len(files.data)}") # Get file details file = await client.files.get(response.file.id) print(f"State: {file.state}") asyncio.run(main()) ``` -------------------------------- ### Example Endpoint Path Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/endpoints.md An example of how a relative endpoint path resolves to a full URL using the default base URL. ```text https://agents.lumalabs.ai/v1/generations ``` -------------------------------- ### Start Mock Server Source: https://github.com/lumalabs/luma-agents-python/blob/main/CONTRIBUTING.md Set up a mock server against the OpenAPI spec to run tests. This is a prerequisite for most of the project's tests. ```sh ./scripts/mock ``` -------------------------------- ### Install Dependencies with Pip Source: https://github.com/lumalabs/luma-agents-python/blob/main/CONTRIBUTING.md If not using Rye, install development dependencies using pip by referencing the locked requirements file. ```sh pip install -r requirements-dev.lock ``` -------------------------------- ### Install Luma Agents Python Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/README.md Install the library using pip. This is the first step to using Luma Agents in your Python projects. ```bash pip install luma-agents ``` -------------------------------- ### Configure Async HTTP Client with aiohttp Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/configuration.md Use `DefaultAioHttpClient` for improved async concurrency with `aiohttp`. Ensure `luma-agents[aiohttp]` is installed. ```bash pip install luma-agents[aiohttp] ``` ```python from luma_agents import DefaultAioHttpClient, AsyncLuma async def main(): async with AsyncLuma( http_client=DefaultAioHttpClient(), ) as client: generation = await client.generations.create( prompt="A cat", model="uni-1", ) import asyncio asyncio.run(main()) ``` -------------------------------- ### Generate Video from Image Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/examples.md Create a video by providing a starting image and a text prompt describing the desired motion or scene. ```python from luma_agents import Luma client = Luma() generation = client.generations.create( prompt="The camera pans slowly to the left", type="video", model="ray-3.2", video={ "duration": "5s", "resolution": "1080p", "start_frame": { "url": "https://example.com/image.jpg", }, }, ) ``` -------------------------------- ### GET /files Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/endpoints.md List files in your namespace, newest first. Supports keyset pagination. ```APIDOC ## GET /files ### Description List files in your namespace, newest first. Keyset-paginated. ### Method GET ### Endpoint /files ### Parameters #### Query Parameters - **cursor** (string) - Optional - Opaque pagination cursor from prior response's next_cursor. - **limit** (integer) - Optional - Max files to return (1–100). Defaults to 25. - **purpose** (string) - Optional - Filter by purpose: `input` or `reference`. - **state** (string) - Optional - Filter by state: `pending`, `ready`, `failed`, or `deleted`. ### Response #### Success Response (200) - **data** (array of File) - Files in this page. - **has_more** (boolean) - Whether more files exist. - **next_cursor** (string) - Cursor for next page (if has_more is true). ### Request Example ```python from luma_agents import Luma client = Luma() # First page page = client.files.list(limit=10) print(f"Files: {len(page.data)}") print(f"Has more: {page.has_more}") # Next page if page.has_more: next_page = client.files.list(cursor=page.next_cursor, limit=10) ``` ``` -------------------------------- ### Nested Parameters Example Source: https://github.com/lumalabs/luma-agents-python/blob/main/README.md Demonstrates creating a generation with an empty nested 'source' parameter, which is typed using TypedDict. ```python from luma_agents import Luma client = Luma() generation = client.generations.create( prompt="A glass of iced coffee on a marble countertop, morning light streaming through a window", source={}, ) print(generation.source) ``` -------------------------------- ### Sync Dependencies with Rye Source: https://github.com/lumalabs/luma-agents-python/blob/main/CONTRIBUTING.md Manually install Rye and then use this command to synchronize all project dependencies, including development features. ```sh rye sync --all-features ``` -------------------------------- ### List Files with Pagination Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/examples.md Explains how to retrieve a list of files, including how to paginate through results to get all available files. ```APIDOC ## List Files with Pagination ### Description Retrieves a list of files with support for pagination to handle large numbers of files. ### Method `client.files.list` ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of files to return per page. - **cursor** (string) - Optional - A cursor for fetching the next page of results. ### Request Example ```python from luma_agents import Luma client = Luma() # Get first page page = client.files.list(limit=20) print(f"Page 1: {len(page.data)} files") # Get all pages cursor = page.next_cursor while page.has_more: page = client.files.list(cursor=cursor, limit=20) print(f"Page: {len(page.data)} files") cursor = page.next_cursor ``` ### Response #### Success Response Returns a page object containing a list of files (`data`) and information about pagination (`next_cursor`, `has_more`). ``` -------------------------------- ### Manage Client Lifecycle with Context Manager (Synchronous) Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/configuration.md Use the `with` statement to automatically manage the Luma client's lifecycle, ensuring proper setup and cleanup for synchronous operations. ```python from luma_agents import Luma # Synchronous with Luma() as client: generation = client.generations.create(prompt="A cat", model="uni-1") ``` -------------------------------- ### Build Distribution Wheel Source: https://github.com/lumalabs/luma-agents-python/blob/main/CONTRIBUTING.md Build distributable versions of the library, including a source tarball and a wheel file, which can be used for efficient installation. ```sh rye build ``` ```sh python -m build ``` -------------------------------- ### Basic Image Generation Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/00-START-HERE.md Generate an image using the Luma client. Specify a prompt and the desired model. The 'uni-1' model is used here as an example. ```python generation = client.generations.create(prompt="...", model="uni-1") ``` -------------------------------- ### Check File Status Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/examples.md Provides an example of how to retrieve the status of a specific file and wait until it reaches a 'ready' or 'failed' state. ```APIDOC ## Check File Status ### Description Retrieves the status of a specific file and polls until it is ready or has failed. ### Method `client.files.create` and `client.files.get` ### Parameters #### `client.files.create` Parameters - **mime_type** (string) - Required - The MIME type of the file. - **size_bytes** (integer) - Required - The size of the file in bytes. - **purpose** (string) - Required - The purpose of the file (e.g., "input"). #### `client.files.get` Parameters - **file_id** (string) - Required - The ID of the file to retrieve status for. ### Request Example ```python from luma_agents import Luma import time client = Luma() # Upload file response = client.files.create( mime_type="image/jpeg", size_bytes=100000, purpose="input", ) file_id = response.file.id # Wait for file to be ready while True: file = client.files.get(file_id) print(f"State: {file.state}") if file.state == "ready": print("File ready to use") break elif file.state == "failed": print(f"File failed: {file.failure_reason}") break time.sleep(1) ``` ### Response #### Success Response `client.files.create` returns a file object. `client.files.get` returns the file object with its current state and potential failure reason. ``` -------------------------------- ### Manage Client Lifecycle with Context Manager (Asynchronous) Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/configuration.md Use `async with` to manage the AsyncLuma client's lifecycle, ensuring proper setup and cleanup for asynchronous operations. ```python import asyncio from luma_agents import AsyncLuma async def main(): async with AsyncLuma() as client: generation = await client.generations.create( prompt="A cat", model="uni-1", ) asyncio.run(main()) ``` -------------------------------- ### Create Image Generation Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/00-START-HERE.md Initiates an image generation job with a given prompt and model. The job starts in a 'queued' or 'processing' state. ```APIDOC ## POST /generations ### Description Creates a new image generation job. ### Method POST ### Endpoint /generations ### Parameters #### Request Body - **prompt** (string) - Required - The text prompt to guide image generation. - **model** (string) - Required - The model to use for generation (e.g., "uni-1"). ### Request Example ```json { "prompt": "A cat wearing a hat", "model": "uni-1" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the generation job. - **state** (string) - The current state of the job (e.g., "queued", "processing", "completed", "failed"). #### Response Example ```json { "id": "gen_abc123", "state": "queued" } ``` ``` -------------------------------- ### Edit Image with Luma Agents Python SDK Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/00-START-HERE.md This example shows how to edit an existing image. Provide an editing prompt and a URL to the source image. The 'type' parameter must be set to 'image_edit'. ```python gen = client.generations.create( prompt="Make it brighter", type="image_edit", source={"url": "https://..."}, model="uni-1", ) ``` -------------------------------- ### Create an asynchronous generation Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/generations.md Use this method to asynchronously create a new generation. Ensure you have initialized the AsyncLuma client. This example shows a basic generation request. ```python import asyncio from luma_agents import AsyncLuma async def main(): client = AsyncLuma() generation = await client.generations.create( prompt="A cat", model="uni-1", ) print(f"Generation ID: {generation.id}") asyncio.run(main()) ``` -------------------------------- ### VideoOptionsParam for Video Generation Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/types.md Configures advanced options for video generation, editing, and reframing. Supports settings for duration, HDR export, looping, resolution, and frame references (start, end, keyframes). Use keyframes for image-to-video, or start_frame/end_frame for video extension. ```python class VideoOptionsParam(TypedDict, total=False): duration: Optional[VideoDuration] edit: Optional[VideoEditOptionsParam] end_frame: Optional[ImageRefParam] exr_export: Optional[bool] hdr: Optional[bool] keyframe_indexes: Optional[Iterable[int]] keyframes: Optional[Iterable[ImageRefParam]] loop: Optional[bool] resolution: Optional[VideoResolution] source_position: Optional[SourcePositionParam] start_frame: Optional[ImageRefParam] ``` -------------------------------- ### Get an asynchronous generation and poll for completion Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/generations.md This method retrieves an existing generation asynchronously. The example demonstrates polling the generation's status until it is completed, requiring the generation ID. ```python import asyncio from luma_agents import AsyncLuma async def main(): client = AsyncLuma() generation = await client.generations.create( prompt="A cat", model="uni-1", ) # Poll for completion while generation.state in ["queued", "processing"]: await asyncio.sleep(2) generation = await client.generations.get(generation.id) if generation.state == "completed": print("Done!") asyncio.run(main()) ``` -------------------------------- ### Instantiate Luma Clients and Use APIs Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/00-START-HERE.md Demonstrates how to create synchronous and asynchronous Luma clients and interact with the Generations and Files APIs. Ensure you provide a valid authentication token. ```python from luma_agents import Luma, AsyncLuma # Synchronous client client = Luma(auth_token="...") # Generations API generation = client.generations.create(prompt="...", model="uni-1") status = client.generations.get(generation_id) # Files API response = client.files.create(mime_type="image/jpeg", size_bytes=...) files = client.files.list(limit=10) file = client.files.get(file_id) client.files.delete(file_id) file = client.files.complete(file_id) # Asynchronous client async_client = AsyncLuma() generation = await async_client.generations.create(...) ``` -------------------------------- ### Configure Luma Client with Constructor Options Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/00-START-HERE.md Illustrates how to initialize the Luma client with various configuration options, including authentication token, base URL, timeouts, retries, default headers, and a custom HTTP client. ```python from luma_agents import Luma client = Luma( auth_token="sk_...", # API token base_url="https://...", # Endpoint URL timeout=60.0, # Request timeout max_retries=2, # Automatic retries default_headers={...}, # Global headers http_client=custom_httpx_client, # Custom HTTP client ) ``` -------------------------------- ### Configuration via Constructor Options Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/00-START-HERE.md Illustrates how to configure the Luma client directly within the constructor using various parameters. ```APIDOC ## Configuration via Constructor Options ### Description Customize the `Luma` client during initialization with specific parameters. ### Parameters - `auth_token` (str): Your API token. - `base_url` (str): The API endpoint URL. - `timeout` (float): Request timeout in seconds. - `max_retries` (int): Number of automatic retries for failed requests. - `default_headers` (dict): A dictionary of default headers to send with every request. - `http_client`: An optional custom HTTP client instance. ### Example Usage ```python from luma_agents import Luma client = Luma( auth_token="sk_...", base_url="https://api.example.com", timeout=60.0, max_retries=2, default_headers={"X-Custom-Header": "value"}, ) ``` ``` -------------------------------- ### Initialize Luma Clients (Sync and Async) Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/INDEX.md Instantiate the synchronous `Luma` client with an authentication token or the asynchronous `AsyncLuma` client. Use the synchronous client for standard operations and the asynchronous client for I/O-bound workloads requiring better concurrency. ```python from luma_agents import Luma, AsyncLuma # Synchronous client = Luma(auth_token="sk_...") generation = client.generations.create(prompt="...", model="uni-1") files = client.files.list() # Asynchronous async_client = AsyncLuma() generation = await async_client.generations.create(...) ``` -------------------------------- ### Determine Installed Luma Agents Version Source: https://github.com/lumalabs/luma-agents-python/blob/main/README.md Check the installed version of the `luma-agents` package at runtime by importing the library and accessing the `__version__` attribute. ```python import luma_agents print(luma_agents.__version__) ``` -------------------------------- ### Get File Source: https://github.com/lumalabs/luma-agents-python/blob/main/api.md Retrieves a specific file by its ID. Returns the File object. ```python client.files.get(file_id) ``` -------------------------------- ### Bootstrap Environment with Rye Source: https://github.com/lumalabs/luma-agents-python/blob/main/CONTRIBUTING.md Run this script to automatically set up the project environment using Rye, including provisioning the correct Python version and dependencies. ```sh ./scripts/bootstrap ``` -------------------------------- ### Get Generation Source: https://github.com/lumalabs/luma-agents-python/blob/main/api.md Retrieve a specific generation by its ID. This method returns the Generation object. ```python client.generations.get(generation_id) ``` -------------------------------- ### Basic Async Generation with Luma Agents Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/examples.md Demonstrates how to perform a basic asynchronous generation request. Ensure `AsyncLuma` client is initialized. ```python import asyncio from luma_agents import AsyncLuma async def main(): client = AsyncLuma() generation = await client.generations.create( prompt="A cat wearing a hat", model="uni-1", ) print(f"Generation ID: {generation.id}") print(f"Status: {generation.state}") asyncio.run(main()) ``` -------------------------------- ### Handle PermissionDeniedError Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/errors.md Example of how to catch and handle a PermissionDeniedError when a feature is not enabled for the account or token lacks permissions. ```python import luma_agents from luma_agents import Luma client = Luma() try: generation = client.generations.create( prompt="A cat", model="uni-1-max", # If not enabled for account ) except luma_agents.PermissionDeniedError: print("Feature not available for this account") ``` -------------------------------- ### Initialize Luma Client Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/client.md Initialize the Luma client using an API key from the environment, an explicit token, or with custom configuration for base URL and timeout. ```python import os from luma_agents import Luma # From environment variable client = Luma() # Explicit token client = Luma(auth_token="your-api-key") # With custom options client = Luma( auth_token=os.environ.get("LUMA_AGENTS_API_KEY"), base_url="https://custom.api.endpoint/v1", timeout=30.0, max_retries=3, ) ``` -------------------------------- ### Get Generation Status Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/README.md Retrieves the current status and details of a previously created generation using its ID. ```APIDOC ## GET /generations/{generation_id} ### Description Retrieves the status and details of a specific image generation request. ### Method GET ### Endpoint /generations/{generation_id} ### Parameters #### Path Parameters - **generation_id** (string) - Required - The unique identifier of the generation to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the generation. - **state** (string) - The current state of the generation. - **output** (array) - A list of generated image outputs if the generation is completed. #### Response Example ```json { "id": "gen_abc123", "state": "processing", "output": [] } ``` ``` -------------------------------- ### Initialize AsyncLuma Client Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/client.md Instantiate the AsyncLuma client with an authentication token. Ensure to close the client when done to release resources. ```python import asyncio from luma_agents import AsyncLuma async def main(): client = AsyncLuma(auth_token="your-api-key") generation = await client.generations.create( prompt="A cat", model="uni-1", ) print(generation.id) await client.close() asyncio.run(main()) ``` -------------------------------- ### Minimal Image Generation with Luma Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/INDEX.md Demonstrates the basic usage of the Luma client to create an image generation request with a simple prompt. ```python from luma_agents import Luma client = Luma() gen = client.generations.create(prompt="A cat", model="uni-1") print(f"ID: {gen.id}") ``` -------------------------------- ### Create Luma Client Instance Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/00-START-HERE.md Instantiate the Luma client to interact with the API. This client will use the API key set in the environment. ```python client = Luma() ``` -------------------------------- ### Get Generation Status Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/00-START-HERE.md Retrieves the current status and details of a specific image generation job using its ID. ```APIDOC ## GET /generations/{generation_id} ### Description Retrieves the status and details of a specific generation job. ### Method GET ### Endpoint /generations/{generation_id} ### Parameters #### Path Parameters - **generation_id** (string) - Required - The ID of the generation job to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the generation job. - **state** (string) - The current state of the job. - **output** (array) - A list of output URLs if the job is completed. - **url** (string) - The URL of the generated image. #### Response Example ```json { "id": "gen_abc123", "state": "completed", "output": [ { "url": "https://example.com/image.png" } ] } ``` ``` -------------------------------- ### Custom httpx.Client Configuration Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/configuration.md Configure a custom httpx.Client with specific proxy settings, SSL verification options, and client certificates before initializing the Luma client. ```python import httpx from luma_agents import Luma http_client = httpx.Client( proxy="http://proxy.example.com:8080", verify=False, # Disable SSL verification (not recommended for production) cert=("client.cert", "client.key"), # Client certificate ) client = Luma(http_client=http_client) ``` -------------------------------- ### GET /files/{file_id} Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/endpoints.md Retrieves metadata for a specific file using its ID. Requires a Bearer token for authentication. ```APIDOC ## GET /files/{file_id} ### Description Retrieve metadata for a single file. ### Method GET ### Endpoint /files/{file_id} ### Parameters #### Path Parameters - **file_id** (string) - Required - File ID. ### Response #### Success Response (200) - **id** (string) - File ID. - **created_at** (datetime) - Creation timestamp. - **mime_type** (string) - MIME type of stored bytes. - **purpose** (string) - File purpose (input, reference). - **size_bytes** (integer) - Size in bytes. - **state** (string) - File state (pending, ready, failed, deleted). - **filename** (string) - Original filename. - **user_id** (string) - Opaque end-user identifier. - **expires_at** (datetime) - TTL expiry time. - **failure_reason** (string) - Failure reason if state is failed. - **deleted_at** (datetime) - Soft-delete timestamp. #### Response Example { "id": "file_id_123", "created_at": "2023-10-27T10:00:00Z", "mime_type": "image/jpeg", "purpose": "input", "size_bytes": 1000000, "state": "pending", "filename": "image.jpg", "user_id": "user_abc", "expires_at": "2023-11-27T10:00:00Z", "failure_reason": null, "deleted_at": null } ### Status Codes - **200** - Success. File metadata returned. - **401** - AuthenticationError - Invalid or missing authentication token. - **404** - NotFoundError - File ID not found. - **500+** - InternalServerError - Server error. Automatically retried. ``` -------------------------------- ### Video Generation with Custom Options Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/INDEX.md Demonstrates creating a video generation request with specific options for duration and resolution. ```python from luma_agents import Luma client = Luma() gen = client.generations.create( prompt="A cat running", type="video", model="ray-3.2", video={"duration": "10s", "resolution": "1080p"}, ) ``` -------------------------------- ### Create Luma Client Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/00-START-HERE.md Initialize the Luma client. It automatically reads the API key from the LUMA_AGENTS_API_API_KEY environment variable. ```python from luma_agents import Luma client = Luma() # Reads from LUMA_AGENTS_API_KEY ``` -------------------------------- ### Create Luma Client with Options (Alias) Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/client.md An alias for the `copy()` method, providing a more concise syntax for creating a new client instance with modified options. Use this for quick configuration changes. ```python result = client.with_options(timeout=30.0).generations.create( prompt="Quick generation", model="uni-1", ) ``` -------------------------------- ### Run Project Tests Source: https://github.com/lumalabs/luma-agents-python/blob/main/CONTRIBUTING.md Execute the project's test suite. Ensure the mock server is running if required by the tests. ```sh ./scripts/test ``` -------------------------------- ### Configure Async HTTP Client with Proxy Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/configuration.md Configure the asynchronous HTTP client using `DefaultAsyncHttpxClient`. Specify a proxy server for API requests. ```python from luma_agents import DefaultAsyncHttpxClient, AsyncLuma client = AsyncLuma( http_client=DefaultAsyncHttpxClient( proxy="http://proxy.example.com:8080", ) ) ``` -------------------------------- ### Resource Management with Context Managers Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/configuration.md Ensure proper resource cleanup by using the Luma client as a context manager with the 'with' statement. ```python with Luma() as client: generation = client.generations.create(prompt="A cat", model="uni-1") ``` -------------------------------- ### Handle ConflictError Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/errors.md Example of catching a ConflictError when a resource state conflict occurs during an operation. Note that this error is automatically retried by default. ```python import luma_agents from luma_agents import Luma client = Luma() try: # Conflict in resource state result = client.files.complete("file_id") except luma_agents.ConflictError: print("Resource conflict - check current state and retry") ``` -------------------------------- ### Enable Logging in Code Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/configuration.md Enable logging within your Python application by calling `setup_logging()` and configuring the `logging` module. ```python import logging from luma_agents._utils._logs import setup_logging setup_logging() logging.basicConfig(level=logging.DEBUG) ``` -------------------------------- ### GET /generations/{generation_id} Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/endpoints.md Poll for generation status and output. On completion, response includes presigned URLs to download generated images/videos. ```APIDOC ## GET /generations/{generation_id} ### Description Poll for generation status and output. On completion, response includes presigned URLs to download generated images/videos. ### Method GET ### Endpoint /generations/{generation_id} ### Parameters #### Path Parameters - **generation_id** (string) - Required - Generation job ID from POST /generations. ### Response #### Success Response (200) - **id** (string) - Generation job ID (UUID). - **created_at** (string) - ISO 8601 creation timestamp. - **model** (string) - Model used (uni-1, uni-1-max, ray-3.2). - **state** (string) - Job state (queued, processing, completed, failed). - **type** (string) - Generation type. - **failure_code** (string) - Failure code if state is failed. - **failure_reason** (string) - Human-readable failure reason. - **output** (array of GenerationOutput) - Generated outputs when completed. ### Status Codes - 200: Success. Current job status returned. - 401: AuthenticationError - Invalid or missing authentication token. - 404: NotFoundError - Generation ID not found. - 500+: InternalServerError - Server error. Automatically retried. ### Request Example ```python from luma_agents import Luma import time client = Luma() # Create generation generation = client.generations.create( prompt="A cat", model="uni-1", ) print(f"Job ID: {generation.id}") # Poll for completion while generation.state in ["queued", "processing"]: print(f"Status: {generation.state}") time.sleep(2) generation = client.generations.get(generation.id) # Check result if generation.state == "completed": for output in generation.output or []: print(f"Output URL: {output.url}") elif generation.state == "failed": print(f"Failed: {generation.failure_reason}") ``` ``` -------------------------------- ### AsyncLuma Client with Context Manager Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/client.md Utilize the `async with` statement for automatic client initialization and cleanup. This ensures the underlying HTTP client is properly closed. ```python async with AsyncLuma() as client: generation = await client.generations.create( prompt="A cat", model="uni-1", ) ``` -------------------------------- ### Handle InternalServerError Exception Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/errors.md Example of catching an InternalServerError exception when creating a generation. This error indicates a server-side issue and is automatically retried by default. ```python import luma_agents from luma_agents import Luma client = Luma() try: generation = client.generations.create(prompt="A cat", model="uni-1") except luma_agents.InternalServerError: print("Server error - the service is experiencing issues") ``` -------------------------------- ### Configure Luma Agents via Environment Variables Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/00-START-HERE.md Shows how to set up the Luma Agents Python library using environment variables for API keys, custom endpoints, headers, and logging. ```bash LUMA_AGENTS_API_KEY=sk_live_... # API token (recommended) LUMA_BASE_URL=https://... # Custom endpoint LUMA_CUSTOM_HEADERS=X-Header: value # Extra headers LUMA_LOG=debug # Logging level ``` -------------------------------- ### ImageRefParam Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/types.md Defines a media reference for guided generation, allowing specification via URL, inline data, generation ID, or file ID. ```APIDOC ## ImageRefParam ### Description Media reference for guided generation. Provide exactly one of url, inline base64 data, generation_id, or file_id. ### Type `TypedDict` ### Fields - **data** (`Optional[str]`) - Base64-encoded image or video data. Provide exactly one of data, file_id, generation_id, or url. - **file_id** (`Optional[str]`) - UUID of a file previously uploaded via POST /files. File must be owned by same client and in state=ready. - **generation_id** (`Optional[str]`) - UUID of a prior generation owned by the same caller. Used on source for image_edit/video_edit/video_reframe chaining. - **media_type** (`Optional[str]`) - MIME type (e.g., "image/jpeg", "video/mp4"). Required with data. Required with source.url on video_edit/video_reframe. Optional for image URLs. - **url** (`Optional[str]`) - Publicly accessible image URL, or video URL for video_edit/video_reframe with media_type=video/*. ``` -------------------------------- ### Handle AuthenticationError Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/errors.md Example of catching an AuthenticationError when initializing the Luma client with an invalid token. This demonstrates how to handle authentication failures by verifying the token and retrying. ```python import luma_agents from luma_agents import Luma try: client = Luma(auth_token="invalid_token") generation = client.generations.create(prompt="A cat", model="uni-1") except luma_agents.AuthenticationError: print("Invalid authentication token") ``` -------------------------------- ### Copy Luma Client with Options Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/client.md Create a new client instance with modified options such as timeout or headers. Useful for making specific requests with different configurations without affecting the original client. ```python def copy( self, *, auth_token: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, http_client: httpx.Client | None = None, max_retries: int | NotGiven = not_given, default_headers: Mapping[str, str] | None = None, set_default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, set_default_query: Mapping[str, object] | None = None, _extra_kwargs: Mapping[str, Any] = {}, ) -> Self ``` ```python # Create a client with longer timeout for specific request result = client.copy(timeout=120.0).generations.create( prompt="Complex generation", model="uni-1", ) # Create a client with additional headers custom_client = client.copy( default_headers={"X-Custom-Header": "value"} ) ``` -------------------------------- ### Handle BadRequestError Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/errors.md Example of catching a BadRequestError when creating a generation with an empty prompt. This demonstrates how to handle client-side request errors by checking parameters and retrying. ```python import luma_agents from luma_agents import Luma client = Luma() try: generation = client.generations.create( prompt="", # Empty prompt model="uni-1", ) except luma_agents.BadRequestError as e: print(f"Invalid request: {e.message}") print(f"Response: {e.response.text()}") ``` -------------------------------- ### Set Global Default Headers and Query Parameters Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/configuration.md Initialize the Luma client with default headers and query parameters that will be applied to all requests unless overridden. ```python from luma_agents import Luma client = Luma( default_headers={ "X-Custom-Header": "value", "X-Request-ID": "123", }, default_query={ "api_version": "v1", }, ) ``` -------------------------------- ### Catch APIError Exception Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/errors.md Example of catching `APIError` to access details about the HTTP request and response body. This is useful for debugging communication or API-related issues. ```python from luma_agents import Luma client = Luma() try: generation = client.generations.create(prompt="A cat", model="uni-1") except luma_agents.APIError as e: print(f"Request URL: {e.request.url}") print(f"Request method: {e.request.method}") print(f"Response body: {e.body}") ``` -------------------------------- ### Catch LumaError Exception Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/errors.md Example of catching the base `LumaError` to handle any exception originating from the Luma library. Use more specific exception types when possible. ```python import luma_agents from luma_agents import Luma client = Luma() try: generation = client.generations.create(prompt="A cat", model="uni-1") except luma_agents.LumaError as e: print(f"Luma error: {e}") ``` -------------------------------- ### Use Luma Client as Context Manager Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/examples.md Use the Luma client as a context manager to ensure automatic cleanup after use. This is the recommended way to manage client instances. ```python from luma_agents import Luma # Automatic cleanup with Luma() as client: generation = client.generations.create( prompt="A cat", model="uni-1", ) print(f"Generated: {generation.id}") # Client is now closed ``` -------------------------------- ### Generations API Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/00-START-HERE.md Methods for creating and retrieving generations. The `create` method initiates a new generation, while the `get` method retrieves the status of an existing one. ```APIDOC ## Generations API ### Description Methods for creating and retrieving generations. ### Methods - `create(prompt: str, model: str)`: Initiates a new generation. - `get(generation_id: str)`: Retrieves the status of an existing generation. ### Example Usage ```python from luma_agents import Luma client = Luma(auth_token="...") # Create a generation generation = client.generations.create(prompt="A futuristic cityscape", model="uni-1") # Get generation status status = client.generations.get(generation.id) ``` ``` -------------------------------- ### client.files.create Source: https://github.com/lumalabs/luma-agents-python/blob/main/api.md Creates a new file with the specified parameters. ```APIDOC ## POST /files ### Description Creates a new file. ### Method POST ### Endpoint /files ### Parameters #### Request Body - **params** (dict) - Required - Parameters for file creation. See `luma_agents.types.file_create_params` for details. ### Response #### Success Response (200) - **CreateFileResponse** (object) - Details of the created file, including upload information. ``` -------------------------------- ### Get File Metadata Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/files.md Retrieve metadata for a single file using its unique ID. This includes details like its state, MIME type, and size. ```APIDOC ## GET /files/{file_id} ### Description Retrieve metadata for a single file in your namespace. ### Method GET ### Endpoint /files/{file_id} ### Parameters #### Path Parameters - **file_id** (str) - Required - File ID. #### Query Parameters - **extra_headers** (Headers | None) - Optional - Additional HTTP headers for this request. - **extra_query** (Query | None) - Optional - Additional query parameters for this request. - **extra_body** (Body | None) - Optional - Additional JSON fields to include in the request body. - **timeout** (float | httpx.Timeout | None | NotGiven) - Optional - Override client timeout for this request. ### Response #### Success Response (200) - **File** (object) - file metadata ### Response Example { "example": "{\"id\": \"file_id_123\", \"state\": \"completed\", \"mime_type\": \"image/jpeg\", \"size_bytes\": 12345, \"created_at\": \"2023-01-01T12:00:00Z\", \"failure_reason\": null}" } ### Error Handling - `NotFoundError` — if file_id does not exist - `APIStatusError` — for other API errors ``` -------------------------------- ### Configure Sync HTTP Client with Proxy and Local Address Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/configuration.md Configure the synchronous HTTP client using `DefaultHttpxClient`. Specify a proxy server and a local address for the transport. ```python from luma_agents import DefaultHttpxClient, Luma client = Luma( http_client=DefaultHttpxClient( proxy="http://proxy.example.com:8080", transport=httpx.HTTPTransport( local_address="0.0.0.0", ), ) ) ``` -------------------------------- ### POST /generations Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/endpoints.md Submit an image or video generation job. Returns immediately with an opaque job ID to poll via GET /generations/{id}. ```APIDOC ## POST /generations ### Description Submit an image or video generation job. Returns immediately with an opaque job ID to poll via GET /generations/{id}. ### Method POST ### Endpoint /generations ### Parameters #### Request Body - **prompt** (string) - Required - Text prompt describing the generation. - **aspect_ratio** (string) - Optional - Output aspect ratio (3:1, 2:1, 21:9, 16:9, 4:3, 3:2, 1:1, 3:4, 2:3, 9:16, 1:2, 1:3). Valid values depend on model and type. - **image_ref** (array of ImageRefParam) - Optional - Reference images for style/content guidance. Up to 9 for type 'image', up to 8 for type 'image_edit'. - **model** (string) - Optional - Model: `uni-1` (default), `uni-1-max` (higher quality), or `ray-3.2` (video). - **output_format** (string) - Optional - Output format: `png` or `jpeg`. - **source** (ImageRefParam) - Optional - Media reference for guided generation. Required for image_edit, video_edit, video_reframe. - **style** (string) - Optional - Style preset: `auto` or `manga`. - **type** (string) - Optional - Generation type: `image`, `image_edit`, `video`, `video_edit`, or `video_reframe`. - **user_id** (string) - Optional - Opaque end-user identifier for trust & safety attribution. - **video** (VideoOptionsParam) - Optional - Video generation options for ray-3.2 model. - **web_search** (boolean) - Optional - Enable web search grounding. ### Response #### Success Response (200) - **id** (string) - Generation job ID (UUID). - **created_at** (string) - ISO 8601 creation timestamp. - **model** (string) - Model used (uni-1, uni-1-max, ray-3.2). - **state** (string) - Job state (queued, processing, completed, failed). - **type** (string) - Generation type. - **failure_code** (string) - Failure code if state is failed. - **failure_reason** (string) - Human-readable failure reason. - **output** (array of GenerationOutput) - Generated outputs when completed. ### Status Codes - 200: Success. Generation job created. - 400: BadRequestError - Invalid request parameters. - 401: AuthenticationError - Invalid or missing authentication token. - 403: PermissionDeniedError - Token lacks required permissions or feature not enabled. - 429: RateLimitError - Rate limit exceeded. - 500+: InternalServerError - Server error. Automatically retried. ### Request Example ```python from luma_agents import Luma client = Luma() response = client.generations.create( prompt="A glass of iced coffee on a marble countertop, morning light streaming through a window", aspect_ratio="16:9", model="uni-1", type="image", ) ``` ``` -------------------------------- ### Generate Video from Text Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/examples.md Use this to generate a video from a text prompt. It includes polling for completion, as video generation can take time. ```python from luma_agents import Luma import time client = Luma() generation = client.generations.create( prompt="A cat running through a field of tall grass", type="video", model="ray-3.2", video={ "duration": "5s", "resolution": "1080p", }, ) # Poll for completion (videos take longer) while generation.state in ["queued", "processing"]: print(f"Status: {generation.state}") time.sleep(5) generation = client.generations.get(generation.id) if generation.state == "completed": for output in generation.output or []: print(f"Video: {output.url}") ``` -------------------------------- ### Async Get File Metadata Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/files.md Asynchronously retrieve metadata for a single file using its unique ID. This operation is part of the asynchronous file resource interface. ```APIDOC ## GET /files/{file_id} (async) ### Description Asynchronously retrieve metadata for a single file in your namespace. ### Method GET ### Endpoint /files/{file_id} ### Parameters #### Path Parameters - **file_id** (str) - Required - File ID. #### Query Parameters - **extra_headers** (Headers | None) - Optional - Additional HTTP headers for this request. - **extra_query** (Query | None) - Optional - Additional query parameters for this request. - **extra_body** (Body | None) - Optional - Additional JSON fields to include in the request body. - **timeout** (float | httpx.Timeout | None | NotGiven) - Optional - Override client timeout for this request. ### Response #### Success Response (200) - **File** (object) - file metadata ### Response Example { "example": "{\"id\": \"file_id_123\", \"state\": \"completed\", \"mime_type\": \"image/jpeg\", \"size_bytes\": 12345, \"created_at\": \"2023-01-01T12:00:00Z\", \"failure_reason\": null}" } ### Error Handling - `NotFoundError` — if file_id does not exist - `APIStatusError` — for other API errors ``` -------------------------------- ### Luma Client Constructor Source: https://github.com/lumalabs/luma-agents-python/blob/main/_autodocs/client.md Initializes the Luma client. You can configure authentication, base URL, timeouts, and other request-related settings. It can be initialized with an API key directly or by relying on environment variables. ```APIDOC ## Constructor ### Description Initializes the Luma client with optional configuration parameters. ### Parameters - **auth_token** (`str | None`) - Optional - API authentication token. Inferred from `LUMA_AGENTS_API_KEY` environment variable if not provided. Required if env var not set. - **base_url** (`str | httpx.URL | None`) - Optional - Base URL for API requests. Defaults to `https://agents.lumalabs.ai/v1`. Can be overridden with `LUMA_BASE_URL` environment variable. - **timeout** (`float | Timeout | None | NotGiven`) - Optional - Request timeout in seconds or an httpx.Timeout object. Defaults to 60 seconds. - **max_retries** (`int`) - Optional - Maximum number of automatic retries for failed requests. Applicable to connection errors, 408, 409, 429, and 5xx errors. Defaults to 2. - **default_headers** (`Mapping[str, str] | None`) - Optional - Custom headers to include in all requests. Merged with any headers from `LUMA_CUSTOM_HEADERS` environment variable. - **default_query** (`Mapping[str, object] | None`) - Optional - Default query parameters for all requests. - **http_client** (`httpx.Client | None`) - Optional - Custom httpx.Client instance. If not provided, a default client with standard limits and timeout is used. - **_strict_response_validation** (`bool`) - Optional - Enable strict validation of API responses. When enabled, raises APIResponseValidationError if response data doesn't match expected schema. Defaults to False. ### Returns - `Luma` - The initialized Luma client instance. ### Raises - `LumaError` - if `auth_token` is not provided and `LUMA_AGENTS_API_KEY` environment variable is not set. ### Example ```python import os from luma_agents import Luma # From environment variable client = Luma() # Explicit token client = Luma(auth_token="your-api-key") # With custom options client = Luma( auth_token=os.environ.get("LUMA_AGENTS_API_KEY"), base_url="https://custom.api.endpoint/v1", timeout=30.0, max_retries=3, ) ``` ```