Python SDK integration guide

更新时间:
复制 MD 格式

The SpeedPix Python software development kit (SDK) provides simple and easy-to-use interfaces for AI image generation and editing workflows.

View API reference

Authorization

Obtain API credentials

  1. Create an application

  2. Create an application to obtain an app_key and app_secret.

Call OpenAPI

Prepare the Python environment

# Make sure you have Python 3.8 or later.
python --version

# Create a virtual environment (optional).
python -m venv venv
source venv/bin/activate  # macOS/Linux

Configure environment variables

# Set API credentials (recommended).
export SPEEDPIX_APP_KEY="your-app-key"
export SPEEDPIX_APP_SECRET="your-app-secret"

export SPEEDPIX_ENDPOINT="https://your-endpoint.com"  # Optional

Install dependencies

# Install using pip.
pip install speedpix

# Or use uv (recommended).
uv add speedpix

Prepare a published workflow

In the Intelligent Creation Workshop console:

For more information, see Workflow management
  1. Create or select an AI workflow. You can drag the following example workflow into the workflow editor.

    1. This workflow converts a product image to an image with a white background. You can use the sample workflow file: SDK test case.json. The workflow automatically extracts the main subject from the user's input image and then generates a product image with a white background based on the user's text input.

    2. Example parameters:

      Input text

      Input image

      Output result

      Test text

      001

      002

  2. Publish the workflow and obtain the workflow_id.

    1. When publishing, select the image field of node #1 and the text field of node #6 as input fields.

    2. Select the images field of node #10 as the output field.

    3. Click Submit to publish. This creates a v1 version. In the alias management section on the right, create a new alias named main and map it to the v1 version. You can then use this alias to call the workflow. To update the version, simply switch the alias mapping without changing your code.

  3. Record the input and output format requirements of the workflow.

Copy the sample code

Easiest method (recommended)

from speedpix import Client

# Initialize the client (automatically reads configuration from environment variables).
client = Client()

# Run the AI workflow.

try:
    output = client.run(
        workflow_id="your_workflow_id",
        input={
            "text": "A beautiful landscape painting",
            "image": "./input.jpg",  # Local file path. The SDK automatically uploads the file and converts it to a URL.
        },
        alias_id="main",  # Version alias. The default is "main".
        # return_temp_files=True,  # Specifies whether to return temporary files.
    )
    output['images']['url'].save("output.png")  # Save the output image.
    # output['subject_image']['url'].save("subject_image.png")  # Save the output image.
    # output['mask_image']['url'].save("mask_image.png")  # Save the output image.
except Exception as e:
    print("An error occurred:", e)
    output = None

Asynchronous method

import asyncio
from speedpix import Client


async def main():
    client = Client()  # Automatically reads configuration from environment variables.

    # Run the workflow asynchronously.
    try:
        output = await client.async_run(
            workflow_id="your_workflow_id",
            input={
                "text": "A beautiful landscape painting",
                "image": "./input.jpg",  # Local file path. The SDK automatically uploads the file and converts it to a URL.
            },
            alias_id="main",
        )

        await output["images"]["url"].async_save("async_result.png")
    except Exception as e:
        print("An error occurred:", e)
        output = None


asyncio.run(main())

Global function method

import speedpix

try:
    # Use the global function (requires setting environment variables first).
    output = speedpix.run(
        workflow_id="your_workflow_id",
        input={
            "text": "A beautiful landscape painting",
            "image": "./input.jpg",  # Local file path. The SDK automatically uploads the file and converts it to a URL.
        },
        alias_id="main",
    )

    output["images"]["url"].save("global_output.png")  # Save the output image.
except Exception as e:
    print("An error occurred:", e)
    output = None

Run the test

# Run the test script.
python quickstart.py

# Verify the installation.
python -c "import speedpix; print('SpeedPix SDK installed successfully!')"

# Check the generated file.
ls -la result.png

Resource configuration

Shared computing power vs. dedicated resources

Intelligent Creation Workshop supports two resource types:

  • Shared computing power: Used by default. This option is cost-effective and suitable for general business scenarios.

  • Dedicated resources: Recommended for businesses sensitive to latency and success rates. This option provides more stable performance.

Configuration methods

By default, the system uses shared computing power if you do not specify a resource_config_id. If you have high requirements for latency and success rates, you can configure dedicated resources.

from speedpix import Client

# Create the client.
client = Client("your-app-key", "your-app-secret")

# Use shared computing power (default).
output1 = client.run(
    workflow_id="your-workflow-id",
    input={"prompt": "A beautiful landscape"},
    alias_id="main"
    # Shared computing power is used automatically when resource_config_id is not specified.
)

# Use dedicated resources.
output2 = client.run(
    workflow_id="your-workflow-id",
    input={"prompt": "A beautiful landscape"},
    alias_id="main",
    resource_config_id="your-dedicated-resource-id"  # Specify the dedicated resource ID.
)

# Specify dedicated resources through create_prediction.
prediction = client.predictions.create(
    workflow_id="your-workflow-id",
    input={"prompt": "A beautiful landscape"},
    alias_id="main",
    resource_config_id="your-dedicated-resource-id"
)

References


SDK API complete parameter description

1. Constructor - Client()

client = Client(
    endpoint=None,
    app_key=None,
    app_secret=None,
    timeout=30.0,
    user_agent=None
)

Parameter description:

Parameter

Type

Default value

Description

endpoint

str

https://openai.edu-aliyun.com

API endpoint address

app_key

str

Environment variable SPEEDPIX_APP_KEY

Application key

app_secret

str

Environment variable SPEEDPIX_APP_SECRET

Application password

timeout

float

30.0

Request timeout (seconds)

user_agent

str

speedpix-python/1.0.0

User agent string

Examples:

# Use environment variables (recommended).
client = Client()

# Full configuration.
client = Client(
    endpoint="https://your-endpoint.com",
    app_key="your-app-key",
    app_secret="your-app-secret",
    timeout=60.0
)

# Simplest method.
client = Client("your-app-key", "your-app-secret")

2. Run a workflow - client.run()

output = client.run(workflow_id, input, **kwargs)

Parameter description:

Parameter

Type

Required

Default value

Description

workflow_id

str

Yes

-

Workflow ID

input

dict

Yes

-

Workflow input parameters

alias_id

str

No

"main"

Version alias

version_id

str

No

-

Version ID (use either this or alias_id)

wait

bool

No

True

Specifies whether to wait for completion

file_encoding_strategy

str

No

"url"

File encoding strategy: url or base64

polling_interval

float

No

1.0

Polling interval (seconds)

Automatic file path handling:

  • The SDK automatically identifies file path parameters in the input.

  • It supports relative paths (such as ./image.jpg) and absolute paths.

  • It automatically uploads files and replaces the paths with accessible URLs.

  • It supports common formats such as jpg, png, gif, bmp, webp, mp4, and mov.

Examples:

# Basic usage
output = client.run(
    workflow_id="workflow-123",
    input={
        "prompt": "Generate image",
        "image": "./source.jpg",  # Automatically uploaded
        "strength": 0.8,
        "steps": 20,
    }
)

# Advanced usage
output = client.run(
    workflow_id="workflow-123",
    input={
        "prompt": "Style transfer",
        "source_image": "./input.jpg",
        "style_image": "/Users/you/style.png",
        "control_image": "./control.jpg",
    },
    alias_id="v2.1",
    file_encoding_strategy="base64",  # Use Base64 encoding for small files.
    polling_interval=2.0  # Poll every 2 seconds.
)

# Asynchronous execution (do not wait)
prediction = client.run(
    workflow_id="workflow-123",
    input={"prompt": "Complex task"},
    wait=False
)
print(f"Task ID: {prediction.id}")
result = prediction.wait()

3. Asynchronous run - client.async_run()

output = await client.async_run(workflow_id, input, **kwargs)

The parameters are the same as client.run(), but it returns a coroutine object.

4. Prediction management - client.predictions

4.1 Create a prediction - predictions.create()

prediction = client.predictions.create(
    workflow_id,
    input,
    alias_id=None,
    version_id=None,
    file_encoding_strategy="url"
)

4.2 Get a prediction - predictions.get()

prediction = client.predictions.get(prediction_id)

4.3 List predictions - predictions.list()

predictions = client.predictions.list()

Example:

# Create a prediction.
prediction = client.predictions.create(
    workflow_id="workflow-123",
    input={
        "prompt": "Generate image",
        "image": "./input.jpg",
    },
    alias_id="main"
)

# Get the prediction status.
updated = client.predictions.get(prediction.id)
print(f"Status: {updated.status}")

# Wait for completion.
result = prediction.wait()

5. File management - client.files

5.1 Upload a file - files.create()

file = client.files.create(file_input)

Parameter description:

Parameter

Type

Required

Description

file_input

str/Path/file-like

Yes

File path, Path object, or file-like object

Example:

from pathlib import Path

# Upload a local file.
file1 = client.files.create("./image.jpg")

# Upload a Path object.
file2 = client.files.create(Path("./image.jpg"))

# Upload a file-like object.
with open("./image.jpg", "rb") as f:
    file3 = client.files.create(f)

# Use the uploaded file.
output = client.run(
    workflow_id="workflow-123",
    input={
        "image": file1.access_url,  # Use the file URL.
        "prompt": "Process image",
    }
)

6. Prediction object methods

6.1 Wait for completion - prediction.wait()

result = prediction.wait(polling_interval=1.0)

6.2 Reload - prediction.reload()

updated = prediction.reload()

7. File output object - FileOutput

When the output contains a file URL, it is automatically converted to a FileOutput object:

# FileOutput methods
output['images'].save("result.png")  # Save to a local file.
buffer = output['images'].read()     # Read as bytes.
url = str(output['images'])          # Get the URL string.

8. Global functions

8.1 Module-level run - speedpix.run()

import speedpix

output = speedpix.run(
    workflow_id="workflow-123",
    input={"prompt": "test"},
    client=None  # Optional. Use a custom client.
)

8.2 Asynchronous global function - speedpix.async_run()

output = await speedpix.async_run(
    workflow_id="workflow-123",
    input={"prompt": "test"}
)

9. Error handling

from speedpix import Client, PredictionError, SpeedPixException

try:
    output = client.run("workflow-id", input={...})
except PredictionError as e:
    print(f"Prediction error: {e}")
    print(f"Prediction ID: {e.prediction.id}")
    print(f"Error details: {e.prediction.error}")
except SpeedPixException as e:
    print(f"API error: {e}")
    print(f"Status code: {e.status_code}")
except Exception as e:
    print(f"Other error: {e}")

More usage methods

Method 1: Easiest (recommended for beginners)

import speedpix

output = speedpix.run("workflow-id", {
    "input": {
        "prompt": "test",
        "image": "./input.jpg",  # File path is automatically uploaded and converted.
    }
})

Method 2: Instantiate the client

from speedpix import Client

client = Client()  # Automatically reads configuration from environment variables.
output = client.run("workflow-id", {
    "input": {
        "prompt": "test",
        "reference": "/path/to/ref.png",  # Absolute paths are supported.
    }
})

Method 3: Full control (for advanced users)

prediction = client.run("workflow-id", {
    "input": {
        "prompt": "test",
        "controlnet": "./control.jpg",  # ControlNet input file.
    },
    "wait": False  # Do not wait, return immediately.
})
result = prediction.wait()  # Manually wait for completion.

File upload examples

Upload a local file

from speedpix import Client

def upload_example():
    client = Client()
    
    # 1. Upload a local file.
    file = client.files.create("./input-image.jpg")
    
    # 2. Use the file URL in the workflow.
    output = client.run("your-workflow-id", {
        "input": {
            "image": file.access_url,  # Use the URL of the uploaded file.
            "prompt": "Process this image",
        },
        "alias_id": "main",
    })
    
    # 3. Save the result.
    if hasattr(output.get('images'), 'save'):
        output['images'].save("processed-result.png")
        print("The processed image has been saved")

upload_example()

Upload multiple files

from speedpix import Client

def multi_file_example():
    client = Client()
    
    # Upload multiple files.
    background_image = client.files.create("./background.jpg")
    mask_image = client.files.create("./mask.png")
    
    output = client.run("your-workflow-id", {
        "input": {
            "background_image": background_image.access_url,
            "mask_image": mask_image.access_url,
            "prompt": "Replace background",
        },
        "alias_id": "main",
    })
    
    if hasattr(output.get('images'), 'save'):
        output['images'].save("composite-result.png")

multi_file_example()

Common file parameter examples

# Depending on the workflow's input requirements, file parameters can be:
input_data = {
    # Image types
    "image": file.access_url,
    "input_image": file.access_url,
    "background_image": file.access_url,
    
    # Path types
    "image_path": file.access_url,
    "file_path": file.access_url,
    
    # File types
    "file": file.access_url,
    "input_file": file.access_url,
    
    # Paired with text prompts
    "prompt": "your text prompt",
    "negative_prompt": "unwanted elements",
}

Complete example: Image editing flow

End-to-end image editing example

from speedpix import Client
import os
from pathlib import Path

def complete_example():
    try:
        # 1. Initialize the client.
        client = Client()
        
        # 2. Upload input files.
        input_image = client.files.create("./input.jpg")
        style_image = client.files.create("./style.jpg")
        
        print(f"Files uploaded successfully:")
        print(f"   Input image: {input_image.access_url}")
        print(f"   Style image: {style_image.access_url}")
        
        # 3. Run the AI workflow.
        print("Processing starts...")
        output = client.run(
            workflow_id="your-workflow-id",
            input={
                "source_image": input_image.access_url,
                "style_image": style_image.access_url,
                "prompt": "Convert the image to an artistic style",
                "strength": 0.8,
                "steps": 20,
            },
            alias_id="main"
        )
        
        # 4. Save the result.
        if hasattr(output.get('images'), 'save'):
            output_path = "./processed_result.png"
            output['images'].save(output_path)
            print(f"Processing complete. Result saved to: {output_path}")
            
            # 5. Verify the output file.
            if Path(output_path).exists():
                file_size = Path(output_path).stat().st_size
                print(f"Output file size: {file_size} bytes")
            else:
                print("Output file not found")
        else:
            print("No image result found in the output")
            
    except Exception as error:
        print(f"Processing failed: {error}")
        
        # Detailed error information.
        if hasattr(error, 'prediction'):
            print(f"   Prediction ID: {error.prediction.id}")
            print(f"   Error details: {error.prediction.error}")

if __name__ == "__main__":
    complete_example()