### Install SDK Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/README.md Install the SDK using pip. For async support with aiohttp, install with the `aiohttp` extra. ```bash pip install runwayml # For async with aiohttp support pip install runwayml[aiohttp] ``` -------------------------------- ### Install SDK from Git Source: https://github.com/runwayml/sdk-python/blob/main/CONTRIBUTING.md Install the SDK directly from the GitHub repository using pip. ```sh pip install git+ssh://git@github.com/runwayml/sdk-python.git ``` -------------------------------- ### Code Examples Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt The documentation includes over 60 runnable code examples covering synchronous and asynchronous patterns, error handling, and advanced usage scenarios. Source file references are provided for all examples. ```APIDOC ## Code Examples - **Sync examples**: 30+ - **Async examples**: 20+ - **Error handling**: 15+ - **Advanced patterns**: 15+ ``` -------------------------------- ### Build and Install Wheel File Source: https://github.com/runwayml/sdk-python/blob/main/CONTRIBUTING.md Build a distributable wheel file for the library and then install it using pip. This is an alternative to installing directly from git. ```sh rye build # or $ python -m build ``` ```sh pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Add and Run Example Script Source: https://github.com/runwayml/sdk-python/blob/main/CONTRIBUTING.md Add new example scripts to the `examples/` directory and make them executable. These files are not modified by the generator. ```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 aiohttp for Async Client Source: https://github.com/runwayml/sdk-python/blob/main/README.md Install the `aiohttp` library to use it as the HTTP backend for the asynchronous client. This can improve concurrency performance. ```sh # install from PyPI pip install runwayml[aiohttp] ``` -------------------------------- ### Minimal Example - Sync Client Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/README.md A basic example demonstrating how to use the synchronous client to create an image generation task and wait for its output. The client automatically uses the RUNWAYML_API_SECRET environment variable. ```python from runwayml import RunwayML client = RunwayML() # Uses RUNWAYML_API_SECRET environment variable # Create a task (async operation) task = client.text_to_image.create( model="gen4_image", prompt_text="A cat sleeping on a sunny windowsill", ratio="1024:1024", ) # Wait for completion result = task.wait_for_task_output() # Download output for url in result.output: print(f"Image: {url}") ``` -------------------------------- ### SDK Structure and Navigation Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt The SDK documentation is structured hierarchically, starting with an index and overview, followed by core and advanced documentation sections. Users can navigate through API references, configuration guides, type definitions, and error details. ```APIDOC ## Documentation Structure 1. INDEX.md - Start here for navigation 2. README.md - Overview and quick start 3. Core Documentation: - configuration.md - api-reference/* (organized by feature) - types.md - errors.md 4. Advanced Documentation: - advanced-patterns.md Each file is self-contained but cross-referenced to related documentation. ``` -------------------------------- ### Install RunwayML Python SDK Source: https://github.com/runwayml/sdk-python/blob/main/README.md Install the library using pip. Ensure you are using Python 3.9+. ```sh pip install runwayml ``` -------------------------------- ### Async Example - Async Client Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/README.md An example demonstrating the usage of the asynchronous client for creating an image generation task and awaiting its output. Ensure you are running this within an asyncio event loop. ```python import asyncio from runwayml import AsyncRunwayML async def main(): async with AsyncRunwayML() as client: task = await client.text_to_image.create( model="gen4_image", prompt_text="A cat sleeping on a sunny windowsill", ratio="1024:1024", ) result = await task.wait_for_task_output() for url in result.output: print(f"Image: {url}") asyncio.run(main()) ``` -------------------------------- ### Async Client Configuration with aiohttp Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/configuration.md Configure the asynchronous client using `AsyncRunwayML` and `DefaultAioHttpClient`. This example demonstrates initializing the client and performing an async operation. ```python import asyncio from runwayml import AsyncRunwayML, DefaultAioHttpClient async def main(): async with AsyncRunwayML( api_key="your-api-key", http_client=DefaultAioHttpClient(), ) as client: task = await client.text_to_image.create( model="gen4_image", prompt_text="A cat", ratio="1024:1024", ) asyncio.run(main()) ``` -------------------------------- ### Install Development Dependencies with Pip Source: https://github.com/runwayml/sdk-python/blob/main/CONTRIBUTING.md If not using Rye, install development dependencies using pip and the locked requirements file. ```sh pip install -r requirements-dev.lock ``` -------------------------------- ### Create Image to Video Task (Async) Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/client.md Example of creating an image-to-video task using the asynchronous client. Ensure the RUNWAYML_API_SECRET environment variable is set. ```python import asyncio import os from runwayml import AsyncRunwayML async def main(): async with AsyncRunwayML( api_key=os.environ.get("RUNWAYML_API_SECRET") ) as client: task = await client.image_to_video.create( model="gen4_turbo", prompt_image="https://example.com/image.jpg", ratio="1280:720", prompt_text="A description of the video" ) print(f"Task created: {task.id}") asyncio.run(main()) ``` -------------------------------- ### Get Installed SDK Version Information Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/configuration.md Retrieve the installed SDK version and title using the imported runwayml package. This is useful for debugging and ensuring compatibility. ```python import runwayml print(runwayml.__version__) # e.g., "5.3.0" print(runwayml.__title__) # "runwayml" ``` -------------------------------- ### Python Example for Text-to-Image Generation Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/generation-resources.md Demonstrates how to use the client to create an image with a text prompt, specifying the model, ratio, and an optional reference image. It then waits for the task to complete and prints the resulting image URL. ```python task = client.text_to_image.create( model="gen4_image_turbo", prompt_text="A futuristic city skyline at night, neon lights, cyberpunk style", ratio="1920:1080", reference_images=[ {"url": "https://example.com/reference.jpg", "weight": 0.7} ], ) result = task.wait_for_task_output() print(f"Image URL: {result.output[0]}") ``` -------------------------------- ### Async Image to Video Creation Source: https://github.com/runwayml/sdk-python/blob/main/README.md Example of creating an image-to-video generation task using the asynchronous client with the default httpx HTTP client. ```APIDOC ## Async Image to Video Creation This example demonstrates how to use the `AsyncRunwayML` client to create an image-to-video generation task asynchronously. ### Method ```python await client.image_to_video.create( model="gen4_turbo", prompt_image="https://example.com/assets/bunny.jpg", ratio="1280:720", prompt_text="The bunny is eating a carrot", ) ``` ### Parameters #### Model - **model** (string) - Required - The model to use for generation (e.g., "gen4_turbo"). - **prompt_image** (string) - Required - The URL of the prompt image. - **ratio** (string) - Required - The desired aspect ratio for the output video (e.g., "1280:720"). - **prompt_text** (string) - Required - A text description to guide the video generation. ### Request Example ```python import os import asyncio from runwayml import AsyncRunwayML client = AsyncRunwayML( api_key=os.environ.get("RUNWAYML_API_SECRET"), ) async def main() -> None: image_to_video = await client.image_to_video.create( model="gen4_turbo", prompt_image="https://example.com/assets/bunny.jpg", ratio="1280:720", prompt_text="The bunny is eating a carrot", ) print(image_to_video.id) asyncio.run(main()) ``` ### Response #### Success Response Returns an object containing the ID of the created generation task. - **id** (string) - The unique identifier for the generation task. ``` -------------------------------- ### Async Client Usage with aiohttp Source: https://github.com/runwayml/sdk-python/blob/main/README.md Instantiate the `AsyncRunwayML` client with `http_client=DefaultAioHttpClient()` to use `aiohttp` as the backend. This requires `aiohttp` to be installed. ```python import os import asyncio from runwayml import DefaultAioHttpClient from runwayml import AsyncRunwayML async def main() -> None: async with AsyncRunwayML( api_key=os.environ.get("RUNWAYML_API_SECRET"), # This is the default and can be omitted http_client=DefaultAioHttpClient(), ) as client: image_to_video = await client.image_to_video.create( model="gen4_turbo", prompt_image="https://example.com/assets/bunny.jpg", ratio="1280:720", prompt_text="The bunny is eating a carrot", ) print(image_to_video.id) asyncio.run(main()) ``` -------------------------------- ### Async Image to Video Creation with aiohttp Source: https://github.com/runwayml/sdk-python/blob/main/README.md Example of creating an image-to-video generation task using the asynchronous client with aiohttp as the HTTP client backend. ```APIDOC ## Async Image to Video Creation with aiohttp This example demonstrates how to use the `AsyncRunwayML` client with `aiohttp` for improved concurrency performance. ### Method ```python async with AsyncRunwayML( api_key=os.environ.get("RUNWAYML_API_SECRET"), http_client=DefaultAioHttpClient(), ) as client: image_to_video = await client.image_to_video.create( model="gen4_turbo", prompt_image="https://example.com/assets/bunny.jpg", ratio="1280:720", prompt_text="The bunny is eating a carrot", ) print(image_to_video.id) ``` ### Parameters #### Model - **model** (string) - Required - The model to use for generation (e.g., "gen4_turbo"). - **prompt_image** (string) - Required - The URL of the prompt image. - **ratio** (string) - Required - The desired aspect ratio for the output video (e.g., "1280:720"). - **prompt_text** (string) - Required - A text description to guide the video generation. ### Request Example ```python import os import asyncio from runwayml import DefaultAioHttpClient from runwayml import AsyncRunwayML async def main() -> None: async with AsyncRunwayML( api_key=os.environ.get("RUNWAYML_API_SECRET"), http_client=DefaultAioHttpClient(), ) as client: image_to_video = await client.image_to_video.create( model="gen4_turbo", prompt_image="https://example.com/assets/bunny.jpg", ratio="1280:720", prompt_text="The bunny is eating a carrot", ) print(image_to_video.id) asyncio.run(main()) ``` ### Response #### Success Response Returns an object containing the ID of the created generation task. - **id** (string) - The unique identifier for the generation task. ``` -------------------------------- ### List All Workflows Source: https://github.com/runwayml/sdk-python/blob/main/api.md Use this method to get a list of all available workflows. ```python client.workflows.list() -> WorkflowListResponse ``` -------------------------------- ### Custom Response Handling with SDK Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/README.md Demonstrates how to get the raw response including headers and status code, or stream the response body for large data. ```python # Get raw response with headers and status code response = client.image_to_video.with_raw_response.create(...) print(response.status_code) image_data = response.parse() ``` ```python # Stream response body instead of loading it all at once with client.image_to_video.with_streaming_response.create(...) as response: for line in response.iter_lines(): print(line) ``` -------------------------------- ### Sync Dependencies with Rye Source: https://github.com/runwayml/sdk-python/blob/main/CONTRIBUTING.md After installing Rye manually, use this command to synchronize all project dependencies, including features. ```sh rye sync --all-features ``` -------------------------------- ### Create Video Transformation Task Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/generation-resources.md Use this method to create a video transformation task. Specify the model and a prompt to guide the transformation. The returned task object can be used to wait for the output. ```python def create( *, model: str, # Required prompt_text: str | None = None, prompt_image: str | Iterable | None = None, ratio: str | None = None, content_moderation: dict | None = None, seed: int | None = None, extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> NewTaskCreatedResponse ``` ```python task = client.video_to_video.create( model="gen4_turbo", prompt_text="Apply a vaporwave art style to the video", ) result = task.wait_for_task_output() print(f"Transformed video: {result.output[0]}") ``` -------------------------------- ### AvatarConversationManager Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/advanced-patterns.md Manages multi-turn avatar conversations. Provides methods to start, get details, and list conversations. ```APIDOC ## AvatarConversationManager Manages multi-turn avatar conversations. ### Methods - **start_conversation()** - Description: Start a new conversation with the avatar. - Returns: The ID of the newly started conversation. - **get_conversation_details()** - Description: Get current conversation details. - Raises: ValueError if the conversation has not been started. - Returns: Details of the current conversation. - **list_conversations()** - Description: List all conversations for this avatar. - Returns: A list of all conversations associated with the avatar. ``` -------------------------------- ### Set Up Mock Server Source: https://github.com/runwayml/sdk-python/blob/main/CONTRIBUTING.md Run this script to set up a mock server against the OpenAPI spec, which is often required for running tests. ```sh ./scripts/mock ``` -------------------------------- ### Manage Avatar Conversations with Python Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/advanced-patterns.md Use this class to manage multi-turn avatar conversations. It requires an AsyncRunwayML client and an avatar ID. Ensure a conversation is started before attempting to get details or list conversations. ```python import asyncio from typing import Optional from runwayml import AsyncRunwayML class AvatarConversationManager: def __init__(self, client: AsyncRunwayML, avatar_id: str): self.client = client self.avatar_id = avatar_id self.conversation_id: Optional[str] = None async def start_conversation(self) -> str: """Start a new conversation with the avatar.""" conversation = await self.client.avatar_conversations.create( avatar_id=self.avatar_id ) self.conversation_id = conversation.id return conversation.id async def get_conversation_details(self): """Get current conversation details.""" if not self.conversation_id: raise ValueError("Conversation not started") return await self.client.avatar_conversations.retrieve( avatar_id=self.avatar_id, id=self.conversation_id, ) async def list_conversations(self) -> list: """List all conversations for this avatar.""" page = await self.client.avatar_conversations.list( avatar_id=self.avatar_id, ) return page.data # Usage async def main(): async with AsyncRunwayML() as client: manager = AvatarConversationManager(client, "avatar_123") # Start conversation conv_id = await manager.start_conversation() print(f"Started conversation: {conv_id}") # Get conversation details details = await manager.get_conversation_details() print(f"Conversation: {details}") # List all conversations all_convs = await manager.list_conversations() print(f"Total conversations: {len(all_convs)}") asyncio.run(main()) ``` -------------------------------- ### Initialize and Use RunwayML Client Source: https://github.com/runwayml/sdk-python/blob/main/README.md Initialize the client with your API key, preferably from environment variables. Then, use the client to create an image-to-video generation task. ```python import os from runwayml import RunwayML client = RunwayML( api_key=os.environ.get("RUNWAYML_API_SECRET"), # This is the default and can be omitted ) image_to_video = client.image_to_video.create( model="gen4_turbo", prompt_image="https://example.com/assets/bunny.jpg", ratio="1280:720", prompt_text="The bunny is eating a carrot", ) print(image_to_video.id) ``` -------------------------------- ### Client Initialization Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Documentation for initializing the synchronous and asynchronous RunwayML clients, including constructor parameters and configuration options. ```APIDOC ## Client Initialization ### Description This section details how to initialize the synchronous `RunwayML` client and the asynchronous `AsyncRunwayML` client. It covers the various constructor parameters available for configuring the client, such as API keys, base URLs, and timeout settings. ### Constructor Parameters - **api_key** (str) - Optional - Your RunwayML API key. If not provided, the SDK will attempt to load it from the `RUNWAYML_API_KEY` environment variable. - **api_base_url** (str) - Optional - The base URL for the RunwayML API. Defaults to the production API endpoint. - **timeout** (float) - Optional - The request timeout in seconds. Defaults to 30.0 seconds. - **max_retries** (int) - Optional - The maximum number of retries for failed requests. Defaults to 3. ### Example Usage (Synchronous) ```python from runwayml import RunwayML client = RunwayML(api_key="YOUR_API_KEY", timeout=60.0) ``` ### Example Usage (Asynchronous) ```python from runwayml import AsyncRunwayML async_client = AsyncRunwayML(api_key="YOUR_API_KEY", timeout=60.0) ``` ``` -------------------------------- ### Print Installed RunwayML SDK Version Source: https://github.com/runwayml/sdk-python/blob/main/README.md Determine the currently installed version of the runwayml SDK in your Python environment. This is useful for debugging or verifying upgrades. ```python import runwayml print(runwayml.__version__) ``` -------------------------------- ### Configure Client with Options Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/client.md Use `with_options` to create a new client instance with overridden settings like timeout or max retries for specific requests. ```python response = client.with_options(timeout=120.0).image_to_video.create( model="gen4_turbo", prompt_image="https://example.com/image.jpg", ratio="1280:720", prompt_text="A description" ) ``` ```python client_no_retry = client.with_options(max_retries=0) ``` -------------------------------- ### Basic Image Generation with RunwayML Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/INDEX.md Demonstrates how to create a basic text-to-image task using the synchronous RunwayML client. Ensure the client is initialized before use. ```python from runwayml import RunwayML client = RunwayML() task = client.text_to_image.create( model="gen4_image", prompt_text="A cat", ratio="1024:1024", ) result = task.wait_for_task_output() ``` -------------------------------- ### UploadsResource.retrieve() Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/utility-resources.md Get details of an uploaded file using its ID. ```APIDOC ## UploadsResource.retrieve() ### Description Get details of an uploaded file. ### Method GET ### Endpoint /uploads/{id} ### Parameters #### Path Parameters - **id** (str) - Required - The ID of the upload to retrieve #### Query Parameters - **extra_headers** (Headers) - Optional - Additional HTTP headers - **extra_query** (Query) - Optional - Additional query parameters - **extra_body** (Body) - Optional - Additional request body fields - **timeout** (float | httpx.Timeout) - Optional - Request timeout override ### Response #### Success Response (200) - **id** (str) - Upload ID - **url** (str) - HTTPS URL of the uploaded file - **created_at** (datetime) - Upload timestamp ``` -------------------------------- ### Configuration Options Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Users can configure the SDK through various parameters, including constructor arguments, environment variables, per-request overrides, and timeout options. Detailed documentation is available in `configuration.md`. ```APIDOC ## Configuration Options - **Constructor parameters**: 8 - **Environment variables**: 4 - **Per-request overrides**: 5 - **Timeout options**: 3 ``` -------------------------------- ### DocumentsResource.retrieve() Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/utility-resources.md Get document details by providing the document's ID. ```APIDOC ## GET /documents/{id} ### Description Get document details. ### Method GET ### Endpoint /documents/{id} ### Parameters #### Path Parameters - **id** (str) - Required - The ID of the document to retrieve ### Response #### Success Response (200) - **id** (str) - Document ID - **name** (str) - Document name - **metadata** (object) - Document metadata ``` -------------------------------- ### Bootstrap Development Environment with Rye Source: https://github.com/runwayml/sdk-python/blob/main/CONTRIBUTING.md Run this script to set up the development environment using Rye, which automatically provisions the correct Python version. ```sh ./scripts/bootstrap ``` -------------------------------- ### client.avatars.retrieve Source: https://github.com/runwayml/sdk-python/blob/main/api.md Retrieves a specific avatar by its ID. This method corresponds to the GET /v1/avatars/{id} API endpoint. ```APIDOC ## GET /v1/avatars/{id} ### Description Retrieves a specific avatar by its ID. ### Method GET ### Endpoint /v1/avatars/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the avatar. ### Response #### Success Response (200) - **avatar** (AvatarRetrieveResponse) - Details of the retrieved avatar. ``` -------------------------------- ### Basic Image Generation with Python SDK Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/00_START_HERE.md Use this pattern to generate an image from a text prompt. Ensure the client is initialized before use. ```python task = client.text_to_image.create( model="gen4_image", prompt_text="description", ratio="1024:1024", ) result = task.wait_for_task_output() ``` -------------------------------- ### client.organization.retrieve Source: https://github.com/runwayml/sdk-python/blob/main/api.md Retrieves information about the organization associated with the client. This method corresponds to the GET /v1/organization API endpoint. ```APIDOC ## GET /v1/organization ### Description Retrieves information about the organization. ### Method GET ### Endpoint /v1/organization ### Response #### Success Response (200) - **organization** (OrganizationRetrieveResponse) - Details of the organization. ``` -------------------------------- ### Configuration with Custom HTTP Client (Proxy) Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/configuration.md Integrate a custom `httpx.Client` to configure proxy settings for the SDK's HTTP requests. ```python import httpx from runwayml import RunwayML, DefaultHttpxClient # With proxy client = RunwayML( api_key="your-api-key", http_client=DefaultHttpxClient( proxy="http://proxy.example.com:8080", ), ) ``` -------------------------------- ### Retrieve an uploaded file using client.uploads.retrieve() Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/utility-resources.md Get details of a previously uploaded file by providing its ID. ```python upload = client.uploads.retrieve(id="your_upload_id") ``` -------------------------------- ### Task Creation and Polling with SDK Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/README.md Shows how to create a task and then wait for its completion using automatic polling or manual status checks. ```python # Create task task = client.text_to_image.create( model="gen4_image", prompt_text="description", ratio="1024:1024", ) ``` ```python # Option 1: Wait with automatic polling result = task.wait_for_task_output(timeout=600) # 10 minute timeout ``` ```python # Option 2: Manual polling import time while True: status = client.tasks.retrieve(task.id) if status.status == "SUCCEEDED": print(f"Done: {status.output}") break elif status.status == "FAILED": print(f"Failed: {status.failure}") break time.sleep(5) ``` -------------------------------- ### Initialize Synchronous RunwayML Client Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/client.md Demonstrates various ways to initialize the synchronous RunwayML client, including using environment variables, explicit API keys, custom timeouts, and advanced httpx configurations. The client can also be used as a context manager for proper HTTP resource cleanup. ```python import os from runwayml import RunwayML # Basic initialization with environment variable client = RunwayML(api_key=os.environ.get("RUNWAYML_API_SECRET")) # With explicit API key client = RunwayML(api_key="your-api-key") # With custom timeout and retries client = RunwayML( api_key="your-api-key", timeout=20.0, max_retries=5, ) ``` ```python import httpx from runwayml import DefaultHttpxClient client = RunwayML( api_key="your-api-key", http_client=DefaultHttpxClient( proxy="http://proxy.example.com:8080", ), ) ``` ```python from runwayml import RunwayML # As context manager to ensure HTTP cleanup with RunwayML(api_key="your-api-key") as client: task = client.image_to_video.create( model="gen4_turbo", prompt_image="https://example.com/image.jpg", ratio="1280:720", prompt_text="A description of the video" ) ``` -------------------------------- ### client.avatars.get_usage Source: https://github.com/runwayml/sdk-python/blob/main/api.md Retrieves usage statistics for avatars. This method corresponds to the GET /v1/avatar_usage API endpoint and accepts optional parameters. ```APIDOC ## GET /v1/avatar_usage ### Description Retrieves usage statistics for avatars. ### Method GET ### Endpoint /v1/avatar_usage ### Parameters #### Query Parameters - **params** (AvatarGetUsageParams) - Optional - Parameters for retrieving avatar usage statistics. ### Response #### Success Response (200) - **usage** (AvatarGetUsageResponse) - The usage statistics for avatars. ``` -------------------------------- ### Get Avatar Usage Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/avatar-voice-resources.md Retrieves usage statistics for a specific avatar, identified by its ID. This helps in monitoring resource consumption. ```python usage = client.avatars.get_usage("avatar_123") ``` -------------------------------- ### Retrieve Organization Details Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/utility-resources.md Use this method to get information about the current organization. It returns details such as ID, name, and creation timestamp. ```python org = client.organization.retrieve() print(f"Organization: {org.name}") ``` -------------------------------- ### list() Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/avatar-voice-resources.md List all available voice configurations, with options for pagination. ```APIDOC ## list() ### Description List all voices. ### Method GET ### Endpoint /voices ### Parameters #### Path Parameters None #### Query Parameters - **limit** (int) - Optional - Maximum number of voices to return - **cursor** (str) - Optional - Cursor for pagination #### Request Body None ### Response #### Success Response (200) - **voices** (array) - A list of voice configurations. - **next_cursor** (str) - Cursor for the next page of results. #### Response Example ```json { "voices": [ { "id": "voice_abc123", "language": "en", "name": "Friendly Assistant", "accent": "american" } ], "next_cursor": "cursor_xyz789" } ``` ``` -------------------------------- ### client.avatars.list Source: https://github.com/runwayml/sdk-python/blob/main/api.md Retrieves a list of avatars, supporting pagination. This method corresponds to the GET /v1/avatars API endpoint and accepts optional parameters. ```APIDOC ## GET /v1/avatars ### Description Retrieves a list of avatars. ### Method GET ### Endpoint /v1/avatars ### Parameters #### Query Parameters - **params** (AvatarListParams) - Optional - Parameters for listing avatars. ### Response #### Success Response (200) - **avatars** (SyncCursorPage[AvatarListResponse]) - A paginated list of avatars. ``` -------------------------------- ### Run Tests Source: https://github.com/runwayml/sdk-python/blob/main/CONTRIBUTING.md Execute the project's test suite. Ensure the mock server is running if tests require it. ```sh ./scripts/test ``` -------------------------------- ### AvatarConversationsResource.create Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/avatar-voice-resources.md Starts a new conversation session with a specified avatar. It returns an AvatarConversationCreateResponse object containing the conversation ID and session details. ```APIDOC ## AvatarConversationsResource.create ### Description Start a new conversation session with an avatar. This method initiates a new session and returns details about the created conversation. ### Method `create` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **avatar_id** (str) - Required - ID of the avatar to converse with - **extra_headers** (Headers) - Optional - Additional HTTP headers - **extra_query** (Query) - Optional - Additional query parameters - **extra_body** (Body) - Optional - Additional request body fields - **timeout** (float | httpx.Timeout) - Optional - Request timeout override ### Request Example ```python conversation = client.avatar_conversations.create(avatar_id="avatar_123") print(f"Conversation started: {conversation.id}") ``` ### Response #### Success Response `AvatarConversationCreateResponse` - Contains conversation ID and session details. #### Response Example ```json { "id": "conv_xyz", "session_details": { ... } } ``` ``` -------------------------------- ### preview() Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/avatar-voice-resources.md Generate a preview audio sample for a specific voice. ```APIDOC ## preview() ### Description Generate a preview audio sample for a voice. ### Method GET ### Endpoint /voices/{id}/preview ### Parameters #### Path Parameters - **id** (str) - Required - The ID of the voice configuration for which to generate a preview #### Query Parameters - **text** (str) - Optional - The text to be spoken in the audio preview #### Request Body None ### Response #### Success Response (200) - **audio_data** (bytes) - Raw audio bytes of the voice preview. ### Response Example ``` (binary audio data) ``` ``` -------------------------------- ### Retrieve Document using Python Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/utility-resources.md Get details for a specific document using its ID. This is useful for fetching metadata or checking the status of a document. ```python def retrieve( id: str, # Required *, extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> DocumentRetrieveResponse: pass ``` -------------------------------- ### Core Client & Configuration Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/README.md Details on the main client classes, initialization, resource access, and configuration options including environment variables, timeouts, and retry behavior. ```APIDOC ## Core Client & Configuration ### Client Classes - `RunwayML`: Synchronous client for interacting with RunwayML services. - `AsyncRunwayML`: Asynchronous client for interacting with RunwayML services. ### Initialization - Details on how to initialize the client, including authentication and base URL configuration. ### Resource Access - How to access different resource managers (e.g., generation, avatar, voice) through the client instance. ### HTTP Method Proxies - Direct proxies for common HTTP methods (GET, POST, PUT, DELETE) for making raw API calls. ### Configuration - **Environment Variables**: Supported environment variables for SDK configuration. - **Timeout Settings**: How to configure request timeouts. - **Retry Behavior**: Configuration for automatic request retries. - **HTTP Client Customization**: Options for customizing the underlying HTTP client. ``` -------------------------------- ### Create Document using Python Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/utility-resources.md Create a knowledge document from either text content or a file. The `name` parameter is required. Use this when you need to add new knowledge bases for avatars or conversations. ```python def create( *, file: BinaryIO | None = None, name: str | None = None, content: str | None = None, extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> DocumentCreateResponse: pass ``` ```python # Create from text content doc = client.documents.create( name="Company Policies", content="Our company policies include...", ) # Create from file with open("manual.pdf", "rb") as f: doc = client.documents.create( name="User Manual", file=f, ) # Use with avatar avatar = client.avatars.create( name="SupportBot", personality="You are a support representative.", reference_image="https://example.com/bot.jpg", voice={"preset": "default_male"}, document_ids=[doc.id], ) ``` -------------------------------- ### Async Client Constructor Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/client.md Initializes the asynchronous client. Supports all parameters of the synchronous client, plus an httpx.AsyncClient for the http_client parameter. ```python AsyncRunwayML( *, api_key: str | None = None, runway_version: str | None = "2024-11-06", base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, max_retries: int = 2, default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, http_client: httpx.AsyncClient | None = None, _strict_response_validation: bool = False, ) -> None ``` -------------------------------- ### AsyncTextToVideoResource.create() Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/generation-resources.md Generates a video from a text prompt using asynchronous calls. It requires specifying the model, prompt text, and desired aspect ratio, with optional parameters for duration, content moderation, seed, and request customization. ```APIDOC ## AsyncTextToVideoResource.create() ### Description Generates a video from a text prompt using asynchronous calls. It requires specifying the model, prompt text, and desired aspect ratio, with optional parameters for duration, content moderation, seed, and request customization. ### Method POST ### Endpoint /v1/text-to-video ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **model** (str) - Required - Model version: `"gen4"`, `"gen4_turbo"`, or `"veo3.1"` - **prompt_text** (str) - Required - Detailed text description of the video (up to 1000 UTF-16 code units) - **ratio** (str) - Required - Output resolution. Common values: `"1280:720"`, `"720:1280"`, `"960:960"`, `"1920:1080"`, `"1080:1920"` - **duration** (int) - Optional - Video duration in seconds - **content_moderation** (dict) - Optional - Content moderation settings - **seed** (int) - Optional - Random seed for reproducibility - **extra_headers** (Headers) - Optional - Additional HTTP headers - **extra_query** (Query) - Optional - Additional query parameters - **extra_body** (Body) - Optional - Additional request body fields - **timeout** (float | httpx.Timeout) - Optional - Request timeout override ### Request Example ```python async_task = await client.async_text_to_video.create( model="gen4_turbo", prompt_text="A surfer riding a wave in Hawaii at sunset, cinematic lighting", ratio="1920:1080", duration=8, ) # Poll for completion result = await async_task.wait_for_task_output() for url in result.output: print(f"Video available at: {url}") ``` ### Response #### Success Response (200) - **AsyncNewTaskCreatedResponse** - Contains task ID and `wait_for_task_output()` method #### Response Example ```python # Example of AsyncNewTaskCreatedResponse structure (actual response may vary) async_task = AsyncNewTaskCreatedResponse(task_id='some_task_id', ...) result = await async_task.wait_for_task_output() for url in result.output: print(f"Video available at: {url}") ``` ``` -------------------------------- ### Start Avatar Conversation Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/avatar-voice-resources.md Initiates a new conversational session with a specified avatar. Requires the avatar ID. Returns conversation ID and session details. ```python conversation = client.avatar_conversations.create(avatar_id="avatar_123") print(f"Conversation started: {conversation.id}") ``` -------------------------------- ### create() Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/avatar-voice-resources.md Create a custom voice configuration with specified language, name, and optional accent. ```APIDOC ## create() ### Description Create a custom voice configuration. ### Method POST ### Endpoint /voices ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **language** (str) - Required - Language code (e.g., "en", "es", "fr") - **name** (str) - Required - Name for the voice configuration - **accent** (str) - Optional - Optional accent specification ### Request Example ```json { "language": "en", "name": "Friendly Assistant", "accent": "american" } ``` ### Response #### Success Response (200) - **voice_id** (str) - The ID of the created voice configuration. - **details** (object) - Details about the created voice configuration. #### Response Example ```json { "voice_id": "voice_abc123", "details": { "language": "en", "name": "Friendly Assistant", "accent": "american" } } ``` ``` -------------------------------- ### Update Avatar Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/avatar-voice-resources.md Modify an existing avatar's properties such as personality, start script, voice, or attached documents. Requires the avatar's ID. ```python updated = client.avatars.update( "avatar_123", personality="Updated personality", voice={"preset": "different_voice"}, ) ``` -------------------------------- ### Retrieve Task Status Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/task-workflow-resources.md Get the current status and details of a task using its ID. Handles different task statuses like SUCCEEDED, RUNNING, and FAILED. ```python task_details = client.tasks.retrieve("task_abc123") if task_details.status == "SUCCEEDED": for url in task_details.output: print(f"Output: {url}") elif task_details.status == "RUNNING": print(f"Progress: {task_details.progress * 100:.1f}%") elif task_details.status == "FAILED": print(f"Failure: {task_details.failure}") if task_details.failure_code: print(f"Error code: {task_details.failure_code}") ``` -------------------------------- ### Minimal Configuration with Environment Variable Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/configuration.md Instantiate the `RunwayML` client without any arguments. It will automatically use the `RUNWAYML_API_SECRET` environment variable if set. ```python from runwayml import RunwayML # Uses RUNWAYML_API_SECRET environment variable client = RunwayML() ``` -------------------------------- ### Create a New Recipe Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/utility-resources.md Use the `create` method to define and create a new recipe. Requires a `name` and `nodes` parameter specifying the workflow node configuration. Supports optional extra headers, query parameters, and body content. ```python def create( *, name: str, # Required nodes: dict, # Required - Workflow node configuration extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> RecipeCreateResponse ``` -------------------------------- ### Manual Task Polling Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/task-workflow-resources.md Implement manual polling for tasks when `wait_for_task_output()` is insufficient. This example demonstrates checking task status periodically and handling success, failure, cancellation, and timeouts. ```python import time import runwayml task = client.text_to_image.create(...) start_time = time.time() timeout = 600 # 10 minutes while True: task_details = client.tasks.retrieve(task.id) if task_details.status == "SUCCEEDED": print(f"Task completed: {task_details.output}") break if task_details.status == "FAILED": raise runwayml.TaskFailedError(task_details) if task_details.status == "CANCELLED": raise runwayml.TaskFailedError(task_details) if time.time() - start_time > timeout: raise runwayml.TaskTimeoutError(task_details) # Wait before next poll time.sleep(5) print(f"Task status: {task_details.status}") ``` -------------------------------- ### Get Raw HTTP Response Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/client.md Use `.with_raw_response` to access the raw HTTP response object, including headers and status code. The response can then be parsed into the desired task object. ```python response = client.image_to_video.with_raw_response.create( model="gen4_turbo", prompt_image="https://example.com/image.jpg", ratio="1280:720", prompt_text="A description" ) print(response.status_code) print(response.headers.get("X-Request-ID")) task = response.parse() ``` -------------------------------- ### Handle API Errors with RunwayML SDK Source: https://github.com/runwayml/sdk-python/blob/main/README.md This example demonstrates how to catch and handle different types of API errors, including connection errors, rate limiting, and general status errors. ```python import runwayml from runwayml import RunwayML client = RunwayML() try: client.image_to_video.create( model="gen4_turbo", prompt_image="https://example.com/assets/bunny.jpg", ratio="1280:720", prompt_text="The bunny is eating a carrot", ) except runwayml.APIConnectionError as e: print("The server could not be reached") print(e.__cause__) # an underlying Exception, likely raised within httpx. except runwayml.RateLimitError as e: print("A 429 status code was received; we should back off a bit.") except runwayml.APIStatusError as e: print("Another non-200-range status code was received") print(e.status_code) print(e.response) ``` -------------------------------- ### TextToVideoResource.create() Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/generation-resources.md Generates a video from a text prompt using synchronous calls. It requires specifying the model, prompt text, and desired aspect ratio, with optional parameters for duration, content moderation, seed, and request customization. ```APIDOC ## TextToVideoResource.create() ### Description Generates a video from a text prompt using synchronous calls. It requires specifying the model, prompt text, and desired aspect ratio, with optional parameters for duration, content moderation, seed, and request customization. ### Method POST ### Endpoint /v1/text-to-video ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **model** (str) - Required - Model version: `"gen4"`, `"gen4_turbo"`, or `"veo3.1"` - **prompt_text** (str) - Required - Detailed text description of the video (up to 1000 UTF-16 code units) - **ratio** (str) - Required - Output resolution. Common values: `"1280:720"`, `"720:1280"`, `"960:960"`, `"1920:1080"`, `"1080:1920"` - **duration** (int) - Optional - Video duration in seconds - **content_moderation** (dict) - Optional - Content moderation settings - **seed** (int) - Optional - Random seed for reproducibility - **extra_headers** (Headers) - Optional - Additional HTTP headers - **extra_query** (Query) - Optional - Additional query parameters - **extra_body** (Body) - Optional - Additional request body fields - **timeout** (float | httpx.Timeout) - Optional - Request timeout override ### Request Example ```python client.text_to_video.create( model="gen4_turbo", prompt_text="A surfer riding a wave in Hawaii at sunset, cinematic lighting", ratio="1920:1080", duration=8, ) ``` ### Response #### Success Response (200) - **NewTaskCreatedResponse** - Contains task ID and `wait_for_task_output()` method #### Response Example ```python # Example of NewTaskCreatedResponse structure (actual response may vary) task = NewTaskCreatedResponse(task_id='some_task_id', ...) result = task.wait_for_task_output() for url in result.output: print(f"Video available at: {url}") ``` ``` -------------------------------- ### Retrieve Workflow Invocation Status Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/task-workflow-resources.md Get the status of a workflow invocation using the `retrieve()` method. This method returns a response object with the current status, and potentially output or failure details. ```python invocation = client.workflow_invocations.retrieve("invocation_123") if invocation.status == "SUCCEEDED": print(f"Workflow completed with output: {invocation.output}") elif invocation.status == "FAILED": print(f"Workflow failed: {invocation.failure}") ``` -------------------------------- ### Client Configuration Methods Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/client.md Methods for configuring the client instance, such as overriding options or closing connections. ```APIDOC ## with_options() ### Description Returns a new client instance with overridden options. ### Method Signature ```python def with_options( *, api_key: str | None = None, runway_version: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, max_retries: int | None = None, default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, http_client: httpx.Client | httpx.AsyncClient | None = None, ) -> RunwayML | AsyncRunwayML ``` ### Example ```python # Create a client with custom timeout for a specific request response = client.with_options(timeout=120.0).image_to_video.create( model="gen4_turbo", prompt_image="https://example.com/image.jpg", ratio="1280:720", prompt_text="A description" ) # Override max retries for a specific call client_no_retry = client.with_options(max_retries=0) ``` ## close() ### Description Manually close HTTP connections. Connections are otherwise closed on garbage collection. ### Method Signature ```python def close() -> None ``` ### Example ```python client = RunwayML(api_key="your-api-key") try: task = client.image_to_video.create(...) finally: client.close() ``` ``` -------------------------------- ### Create a Document Source: https://github.com/runwayml/sdk-python/blob/main/api.md Use this method to create a new document with specified parameters. ```python client.documents.create(**params) ``` -------------------------------- ### Retrieve a Recipe Definition Source: https://github.com/runwayml/sdk-python/blob/main/_autodocs/api-reference/utility-resources.md Use the `retrieve` method to get a specific recipe definition by its ID. This method supports optional extra headers, query parameters, and body content for advanced customization. ```python def retrieve( id: str, # Required *, extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> RecipeRetrieveResponse ```