An image from a job

Moth DocsTutorials

A script that asks for two images, follows the job until it's done and saves the files next to it.

Images, video and music don't come back in one reply. You start a job, read it every few seconds, and download its files once it has succeeded. The script below does all three with the requests package.

shell
export MOTH_API_KEY=moth_your_key_here
pip install requests
image.py
import os, sys, time
import requests

API = "https://api.runmoth.si/v1"
AUTH = {"Authorization": f"Bearer {os.environ['MOTH_API_KEY']}"}
EXT = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}

prompt = " ".join(sys.argv[1:]) or "A moth resting on a warm lamp at night"
res = requests.post(f"{API}/jobs", headers=AUTH, json={
    "model": "nano-banana-2", "prompt": prompt, "n": 2, "aspect_ratio": "3:2",
})
res.raise_for_status()
job = res.json()
print("Started", job["id"], "holding", job["held_usd"], "dollars")

while job["status"] in ("queued", "running"):
    time.sleep(3)
    job = requests.get(f"{API}/jobs/{job['id']}", headers=AUTH).json()
    print(f"{job['status']} {round(job['progress'] * 100)}%")

if job["status"] == "failed":
    sys.exit(f"The job failed and cost nothing: {job.get('error')}")

for out in job["outputs"]:
    data = requests.get("https://api.runmoth.si" + out["url"], headers=AUTH)
    data.raise_for_status()
    name = f"{job['id']}-{out['index']}.{EXT.get(out['content_type'], 'bin')}"
    with open(name, "wb") as f:
        f.write(data.content)
    print("Saved", name)
print("Charged", job["charged_usd"], "dollars")

Run it with python image.py a moth over a city at dusk, or with no words for the default prompt. It prints the job's progress, then the names of the two saved images and what they cost.

How the money moves

Starting the job holds its cost from your balance, which held_usd shows. When it succeeds you pay for each image delivered, shown in charged_usd, and a job that fails gives the whole hold back.

Video and music

The same script makes a clip or a song once you change the body. A video model takes duration_seconds and aspect_ratio, and a music model takes style and instrumental, as Images, video and music shows. Each model's limits in the catalog lists the values it takes.

Fetch files within a day. A job and its files are kept for 24 hours after it ends, and then it is gone, so save what you want to keep.