Mage SDK · Python

The Mage Python SDK

Generate images, video, and audio from Python with sync and asyncio clients and typed configs for every Mage model.

Get an API keyRead the Python guideSource on GitHub
pip install mage-space

At a glance

The Mage Python SDK is the official, open-source client for the Mage API, published as mage-space. Install it with "pip install mage-space", set MAGE_API_KEY, and call mage.run with a model id and a config to get finished images, video, or audio from any of 28 models. It runs on Python 3.10 or later, and every generation is paid in Gems.

Setup

Install the Python SDK and run a model

  1. Install the package

    Add mage-space to your project.

    pip install mage-space
  2. Set your API key

    Create a key in API → API Keys on mage.space and export it. The client reads MAGE_API_KEY.

    export MAGE_API_KEY="mage_sk_..."
  3. Generate

    Call run with a model id and its config. It waits for the result and returns it; the output is at result.url.

    from mage_space import Mage
    
    mage = Mage()  # reads MAGE_API_KEY
    
    request = mage.run("mango", {
        "prompt": "Editorial portrait in soft daylight, 35mm film look",
        "aspect_ratio": "4:5",
        "model_id": "mango-v3",
    })
    
    print(request["result"]["url"])

Examples

The Python SDK in practice

Each example starts from a client that reads MAGE_API_KEY.

Submit now, wait later
from mage_space import Mage

mage = Mage()  # reads MAGE_API_KEY

submitted = mage.generate("cherry", {
    "prompt": "Waves rolling onto a black sand beach at sunset",
    "resolution": "720p",
    "duration": "5",
})

final = mage.requests.wait(
    submitted["request_id"],
    timeout=900,
    on_update=lambda request: print(request["status"]),
)
Upload a file
from mage_space import Mage

mage = Mage()  # reads MAGE_API_KEY

clip = mage.uploads.upload("clip.mp4")  # a path, bytes, or a binary file

mage.run("cherry", {
    "prompt": "Restyle this clip as a watercolor painting",
    "videos": [clip["url"]],
})
Use a saved character
from mage_space import Mage

mage = Mage()  # reads MAGE_API_KEY

mage.characters.create(
    name="Ana",
    handle="ana",
    image="https://example.com/ana.png",
)

mage.run("mango", {"prompt": "@ana walking through a night market"})
Handle errors
from mage_space import Mage, MageAPIError, MageGenerationError

mage = Mage()  # reads MAGE_API_KEY

try:
    mage.run("mango", {"prompt": "A lighthouse at night"})
except MageAPIError as error:
    if error.code == "insufficient_gems":
        print("Gems needed:", error.body["error"]["gems_required"])
    else:
        raise
except MageGenerationError as error:
    print("No output:", error.code)

Why the SDK

What the SDK handles for you

One call, finished media

run submits the generation, polls with the backoff the API recommends, and resolves to the completed request with result.url.

Retries that never pay twice

Every submission carries an idempotency key. Network errors and server errors are retried with backoff, and a retried submission is never charged again.

Uploads in one call

Files too large for a data URL go through a signed upload, with the ticket, the PUT, and the size check handled for you.

Clear errors

API refusals carry their HTTP status, error code, and request id; failed or cancelled generations and timeouts have their own error types.

Sync and asyncio

Mage and AsyncMage share every method. The async client fits web servers, notebooks, and pipelines that run many generations at once.

Typed configs

Each model has a TypedDict, such as MangoConfig, generated from the API reference. Annotate a config with it and your type checker checks the fields.

Reference

The Python SDK at a glance

The same methods cover every model; the model is the first argument.

MethodWhat it does
mage.run(model, config)Submit a generation, wait for it, and return the completed request.
mage.generate(model, config)Submit a generation and return the request at once.
mage.requests.get / cancel / waitRead, stop, or wait for a request by id.
mage.uploads.upload(data)Upload a path, bytes, or file of up to 100 MB and return its URL.
mage.characters / mage.referencesList, create, and delete saved characters and references.
mage.account.get()Your Gems balance.
mage.architectures.list()The live model catalog with options and prices.

Models

Start with these models

Image · from 37 Gems

Guava API

Photorealism that passes for a photograph

Image · from 135 Gems

Mango API

Our flagship image family

Image · from 68 Gems

Nano Banana 2 API

Crisp, readable text, up to 4K

Video · from 618 Gems

Cherry API

Our flagship video family

Video · from 245 Gems

Lemon API

Every video feature, at a friendlier price

Audio · from 19 Gems

Seed Audio API

Voices, music, and sound effects from one prompt

FAQ

Frequently asked questions

Does the Python SDK support asyncio?

Yes. AsyncMage has the same methods as Mage, awaited, and works as an async context manager.

Which Python versions does the SDK support?

Python 3.10 and later. Its only dependencies are httpx and typing-extensions.

Can I use the Python SDK in a notebook or a data pipeline?

Yes. Use Mage in scripts and notebooks, or AsyncMage with asyncio to run many generations at once. The account runs up to 20 generations in flight.

Are the Mage SDKs free and open source?

Yes. The SDKs and the ComfyUI nodes are MIT-licensed on GitHub, and installing them is free. You pay only for the generations you run, in Gems, at each model’s listed price.

Do new Mage models work with an older SDK?

Yes. Pass the new model’s id as a string and it runs; the SDK checks its config against the fields every model shares. A bot updates the types whenever the API reference changes, so new models arrive with their own types in the next release.

How do the SDKs avoid paying twice for a retried request?

Every submission carries an Idempotency-Key. The SDK makes a new key per call and reuses it when it retries that call itself, so a retried submission returns the original request and charges nothing.

Are the SDKs stable?

They are in beta at 0.x, so a minor version may still change them. The API itself is versioned separately and stays stable within v1.

How much does the Mage API cost?

There is no subscription or monthly fee. Each generation is paid in Gems at its model's listed price, and 1,000 Gems cost $1 on the standard pack. Every model page lists its default-settings price, and each response reports the exact charge. A generation that fails is refunded; one Mage's content policy blocks is not. A request your balance cannot cover is refused before anything is charged.

Do I need a Mage membership to use the API?

No. The API runs on Gems alone. Membership plans and their unlimited in-app generation do not apply to API requests, so any Mage account with Gems can call it.

Can I use API outputs commercially?

Yes. Content you create with Mage, including through the API and MCP server, can be used commercially. Attribution is appreciated but not required.

Start building with Mage

One account, one Gems balance, every model. Pay only for what you generate.

Get an API keyRead the Python guide

Related