Backend Python 3.10+ Integration

Python AI Video Generation Guide: Official SDK, urllib & Async httpx

Install the official zero-dependency Python SDK, CLI & stdio MCP server via pip install git+https://github.com/AI-Chili/aichili-python.git (AI-Chili/aichili-python), or call AI Chili directly with urllib.request and httpx.AsyncClient using User-Agent: curl/8.4.0, presigned PUT uploads, and $0 POST /api/v1/generations/plan quotes.

Last updated: By AI Chili Platform & Developer Experience Team Entity: AI Chili Inc. (Vancouver, BC)
Key Endpoints: REST Gateway https://aichili.ai/api/v1 · Streamable HTTP MCP https://aichili.ai/mcp · OpenAPI 3.1 /openapi.json.

Architecture & Endpoint Overview

Python RequirementImplementation DetailWhy It Matters
Official Python SDK & MCPpip install git+https://github.com/AI-Chili/aichili-python.gitZero-dependency Python SDK, CLI & stdio MCP server (github.com/AI-Chili/aichili-python)
Explicit User-Agent'User-Agent': 'curl/8.4.0'Prevents Cloudflare error 1010 blocking Python's default urllib UA
Presigned Media UploadPOST videoapi.aichili.ai/v1/uploads/presign -> PUT -> completeStreams large PNG/MP4 references straight to object storage (<256KB JSON API cap)
Budget Guardrailplan['total_credits'] <= budget_capVerifies exact integer credit deduction at $0 before GPU dispatch
Exponential Poll + Retry-After5s -> 8s -> 12s backoff; honor HTTP 429 Retry-AfterCleanly handles multi-shot batch concurrency without busy-waiting

4-Step Implementation Blueprint

01 · Install Official SDK or Use Standard Library

Run pip install git+https://github.com/AI-Chili/aichili-python.git for the official zero-dependency Python SDK, CLI & stdio MCP server, or call the REST API directly with urllib.request / httpx.

02 · Set User-Agent & Bearer Headers

Configure User-Agent: curl/8.4.0 and Authorization: Bearer chili_sk_* on every request to aichili.ai and videoapi.aichili.ai.

03 · Upload Character Stills via Presigned URL

Request a presigned upload slot at https://videoapi.aichili.ai/v1/uploads/presign, PUT raw image bytes, and finalize the asset UUID for <Picture 1> conditioning.

04 · Batch & Poll Asynchronously with httpx

Assert $0 POST /api/v1/generations/plan quotes, then use asyncio.gather with a bounded asyncio.Semaphore(5) and unique idempotency_key values per shot.

1. Official Python SDK Install & Zero-Dependency urllib.request Client

Install AI-Chili/aichili-python via pip or run straight on standard-library Python 3 with zero external dependencies:

# Option A — Install official zero-dependency Python SDK, CLI & stdio MCP server:
# pip install git+https://github.com/AI-Chili/aichili-python.git

# Option B — Direct standard-library urllib.request client:
import json
import os
import time
import urllib.request

API_ORIGIN = "https://aichili.ai/api/v1"
API_KEY = os.environ["AICHILI_API_KEY"]

def chili_request(method: str, path: str, body: dict | None = None) -> dict:
    data = json.dumps(body).encode("utf-8") if body is not None else None
    req = urllib.request.Request(
        f"{API_ORIGIN}{path}",
        data=data,
        method=method,
        headers={
            "User-Agent": "curl/8.4.0",
            "Authorization": f"Bearer {API_KEY}",
            "Accept": "application/json",
            **({"Content-Type": "application/json"} if data is not None else {}),
        },
    )
    with urllib.request.urlopen(req, timeout=25) as resp:
        return json.loads(resp.read().decode("utf-8"))

payload = {
    "mode": "t2v",
    "model_id": "h3-vdn",
    "idempotency_key": "py-demo-shot-001",
    "params": {
        "prompt": "Lantern-lit rain across a cedar courtyard at dusk, 35mm anamorphic dolly-in, stereo rain",
        "duration_s": 15,
        "resolution": "768p",
        "ratio": "16:9",
    },
}

plan = chili_request("POST", "/generations/plan", payload)
assert plan["total_credits"] <= 20, f"Unexpected credit quote: {plan}"

job = chili_request("POST", "/generations", payload)
delay = 5.0
while job["status"] in ("queued", "running"):
    time.sleep(delay)
    delay = min(delay * 1.4, 15.0)
    job = chili_request("GET", f"/generations/{job['id']}")

print("Finished status:", job["status"], "output:", job.get("output_asset"))

2. Async httpx Reference Upload + Multi-Reference Generation

Uploads a character portrait via presigned storage, binds <Picture 1>, quotes credits, and polls with Retry-After support:

import asyncio
import os
from pathlib import Path
import httpx

GATEWAY = "https://aichili.ai/api/v1"
CONTROL_PLANE = "https://videoapi.aichili.ai/v1"
AUTH_HEADERS = {
    "User-Agent": "curl/8.4.0",
    "Authorization": f"Bearer {os.environ['AICHILI_API_KEY']}",
}

async def upload_reference_png(client: httpx.AsyncClient, img_path: Path) -> str:
    raw = img_path.read_bytes()
    pre = await client.post(
        f"{CONTROL_PLANE}/uploads/presign",
        headers=AUTH_HEADERS,
        json={"filename": img_path.name, "content_type": "image/png", "size_bytes": len(raw)},
    )
    pre.raise_for_status()
    slot = pre.json()
    put_res = await client.put(slot["upload_url"], content=raw, headers={"Content-Type": "image/png"})
    put_res.raise_for_status()
    if "complete_url" in slot:
        await client.post(slot["complete_url"], headers=AUTH_HEADERS)
    return slot["asset_id"]

async def render_character_shot(img_path: Path) -> dict:
    async with httpx.AsyncClient(timeout=25.0) as client:
        asset_id = await upload_reference_png(client, img_path)
        body = {
            "mode": "i2v",
            "model_id": "h3-vdn",
            "idempotency_key": f"char-shot-{img_path.stem}",
            "params": {
                "prompt": "<Picture 1> turns toward warm paper lanterns under evening snowfall, 85mm close-up",
                "duration_s": 15,
                "resolution": "1080p",
                "ratio": "9:16",
                "ref_asset_ids": [asset_id],
                "ref_roles": ["reference_image"],
            },
        }
        plan = (await client.post(f"{GATEWAY}/generations/plan", headers=AUTH_HEADERS, json=body)).raise_for_status().json()
        print(f"Verified quote: {plan['total_credits']} credits")
        job = (await client.post(f"{GATEWAY}/generations", headers=AUTH_HEADERS, json=body)).raise_for_status().json()
        while job["status"] in ("queued", "running"):
            await asyncio.sleep(6)
            poll = await client.get(f"{GATEWAY}/generations/{job['id']}", headers=AUTH_HEADERS)
            if poll.status_code == 429:
                await asyncio.sleep(int(poll.headers.get("Retry-After", "10")))
                continue
            job = poll.raise_for_status().json()
        return job

Recommended AI Chili Engines for Python (SDK, urllib & httpx)

Frequently Asked Questions

Why did urllib.request throw HTTP Error 403 (code 1010) before I added User-Agent?

Cloudflare blocks Python's default 'Python-urllib/3.x' signature at the edge. Setting 'User-Agent': 'curl/8.4.0' resolves it across every *.aichili.ai endpoint.

What is the maximum JSON request body size on https://aichili.ai/api/v1/*?

256 KB. Always upload images and reference videos via presigned URLs (/v1/uploads/presign) and pass their UUIDs in params.ref_asset_ids instead of base64-encoding media inside JSON.

Can I generate OpenAPI client stubs automatically for Python?

Yes. Point openapi-python-client or datamodel-code-generator directly at https://aichili.ai/openapi.json (OpenAPI 3.1.0).

Explore Other Stack Integrations