### Install HiAPI SDK with pip Source: https://github.com/hiapiai/hiapi-python/blob/main/README.md Install the hiapi package using pip. Requires Python 3.8 or later. ```bash pip install hiapi ``` -------------------------------- ### Full configuration example Source: https://github.com/hiapiai/hiapi-python Shows how to instantiate the HiAPI client with all constructor options, including fallback to environment variables. The first client uses only the HIAPI_API_KEY environment variable; the second sets all options explicitly. The final block demonstrates per-call webhook verification with a secret override. ```python import os from hiapi import HiAPI client = HiAPI() # api_key from HIAPI_API_KEY, everything else default client = HiAPI( api_key="sk-...", # or set HIAPI_API_KEY (required if unset) base_url="https://api.hiapi.ai", # "/v1" is appended automatically timeout=60.0, # per-request seconds max_retries=2, # 429/503 + retryable failures webhook_secret=os.environ.get("HIAPI_WEBHOOK_SECRET"), # fallback: HIAPI_WEBHOOK_SECRET ) # Webhook verification without any client-level secret: from hiapi import HiAPI client = HiAPI(api_key="sk-...") task = client.webhooks.verify( body, headers, secret="whsec_...", # per-call override; client-level default optional ) ``` -------------------------------- ### Quick start: run a task and read output Source: https://github.com/hiapiai/hiapi-python/blob/main/README.md Create a HiAPI client, run a task with the seedance-2-0 model, and print output URLs. Blocks until terminal state; raises TaskFailed on failure and PollTimeout if not finished within timeout (default 600s). A poll timeout does not cancel the task; retrieve it later with task_id. ```python from hiapi import HiAPI client = HiAPI(api_key="sk-...") # or set HIAPI_API_KEY task = client.tasks.run( model="seedance-2-0", input={"prompt": "a cyan glass data center entrance", "resolution": "1080p"}, on_update=lambda t: print("status:", t.status), ) for out in task.output: print(out.type, out.url) # e.g. "video https://cdn.hiapi.ai/tasks/..." ``` -------------------------------- ### GET /v1/tasks Source: https://github.com/hiapiai/hiapi-python Lists tasks with pagination. Supports page and size query parameters. The response can be an object with a page array under various keys or a bare array. ```APIDOC ## GET /v1/tasks ### Description Lists tasks with pagination. Supports page and size query parameters. The response can be an object with a page array under various keys or a bare array. ### Method GET ### Endpoint /v1/tasks ### Parameters #### Query Parameters - **page** (int) - Optional - Page number, default 1. - **size** (int) - Optional - Page size, default 20. ### Response #### Success Response (200) - **data** (object or array) - May be an object with a page array under one of `tasks`, `items`, `list`, `data`, `records` plus `page`/`size`/`total`; or a bare array (wrapped with echoed page/size). ``` -------------------------------- ### Direct verification example Source: https://github.com/hiapiai/hiapi-python Shows how to verify a webhook callback using the raw request body and headers. On failure, it returns HTTP 400 and does not process or acknowledge the callback. ```python from hiapi import verify_webhook, WebhookVerificationError raw_body = request.get_data() # raw bytes, as received sig = request.headers.get("X-HiAPI-Signature") ts = request.headers.get("X-HiAPI-Timestamp") try: task = verify_webhook(raw_body, signature=sig, timestamp=ts, secret="whsec_...") except WebhookVerificationError: return 400 # do not process; do not ack ``` -------------------------------- ### TaskPage Source: https://github.com/hiapiai/hiapi-python One page of GET /v1/tasks (newest first). Contains a list of tasks, pagination metadata, and the raw source dictionary. ```APIDOC ## TaskPage ### Description One page of `GET /v1/tasks` (newest first). ### Fields - **items** (`List[Task]`) - Optional - Tasks on this page, newest first. - **page** (`Optional[int]`) - Optional - Requested page number (echoed). - **size** (`Optional[int]`) - Optional - Requested page size (echoed). - **total** (`Optional[int]`) - Optional - Total task count, if the API returns it. - **raw** (`Dict[str, Any]`) - Optional - Full source dict; `repr=False`. ### Class Method - `from_dict(cls, d: Dict[str, Any]) -> TaskPage` ### Notes `from_dict` accepts the page array under **any** of `"tasks"`, `"items"`, `"list"`, `"data"`, `"records"` (first key with a list value wins) so a paginated list never silently parses to empty; the full payload is kept in `raw`. ``` -------------------------------- ### GET /v1/tasks/{taskId} Source: https://github.com/hiapiai/hiapi-python Retrieves a single task by its ID. The task ID is URL-encoded. This endpoint is idempotent and auto-retried on network errors. ```APIDOC ## GET /v1/tasks/{taskId} ### Description Retrieves a task by its ID. The task ID is URL-encoded. This endpoint is idempotent and auto-retried on network errors. ### Method GET ### Endpoint /v1/tasks/{taskId} ### Parameters #### Path Parameters - **taskId** (string) - Required - The task ID to retrieve. ### Response #### Success Response (200) - **taskId** (string) - Task id. - **model** (string) - Model name (resolved full name `base@route` when submitted with a `route`). - **status** (string) - One of `queued`, `handling`, `archiving`, `success`, `fail`. - **created** (int) - Unix seconds of creation. - **completed** (int) - Unix seconds of completion; the API sends `0` (not omitted) while non-terminal — the SDK normalizes `0`/absent to `None`. - **storage** (string?) - Output storage location. - **route** (string?) - Echoed only when submitted with an explicit `route`. - **output** (array) - `[{url, type, expireAt}]` — artifacts (only on `success`). - **error** (object?) - `{code, message}` — failure reason (only on `fail`). ### Status codes / errors | Status | SDK exception | |--------|---------------| | 404 | `NotFoundError` — task does not exist or does not belong to this account | | 401 | `AuthenticationError` | | 429 / 503 | retried automatically, then `APIError` / `ServiceUnavailableError` | | network failure | `APIConnectionError` (after retries) | ``` -------------------------------- ### TaskPage dataclass with from_dict Source: https://github.com/hiapiai/hiapi-python One page of GET /v1/tasks (newest first). from_dict accepts the page array under any of "tasks", "items", "list", "data", "records" (first key with a list value wins). ```python @dataclass class TaskPage: items: List[Task] = field(default_factory=list) page: Optional[int] = None size: Optional[int] = None total: Optional[int] = None raw: Dict[str, Any] = field(default_factory=dict, repr=False) @classmethod def from_dict(cls, d: Dict[str, Any]) -> TaskPage ``` -------------------------------- ### Using OnUpdate callback with Tasks.run Source: https://github.com/hiapiai/hiapi-python Example of passing an on_update callback to Tasks.run. Import OnUpdate from hiapi.resources.tasks if needed for annotations. ```python from hiapi import HiAPI client = HiAPI(api_key="sk-...") def on_update(task) -> None: # type: OnUpdate print(f"{task.task_id}: {task.status}") task = client.tasks.run(model="seedance-2-0", input={"prompt": "hi"}, on_update=on_update) ``` -------------------------------- ### Create task with route parameter Source: https://github.com/hiapiai/hiapi-python/blob/main/README.md Use the 'route' parameter to select a specific route (e.g., 'ext') for models that expose multiple routes. Omitting 'route' or passing 'default' uses the default route; unknown routes fail with a 400 listing available routes. ```python created = client.tasks.create( model="gpt-image-2/text-to-image", route="ext", # preferred over model="...@ext" input={"prompt": "..."}, ) ``` -------------------------------- ### Create, retrieve, wait, and list tasks Source: https://github.com/hiapiai/hiapi-python/blob/main/README.md Shows the lower-level task API: create a task with model and input, then retrieve, wait, or list tasks. The 'input' fields are model-specific; pass 'callback' separately, not inside 'input'. ```python created = client.tasks.create( model="seedance-2-0", input={"prompt": "...", "resolution": "720p"}, callback={"url": "https://your-app.com/hiapi/callback", "when": "final"}, ) print(created.task_id) task = client.tasks.retrieve(created.task_id) # one status check task = client.tasks.wait(created.task_id, poll_interval=3, timeout=900) page = client.tasks.list(page=1, size=20) # newest first ``` -------------------------------- ### HiAPI.__init__ Source: https://github.com/hiapiai/hiapi-python Constructs the HiAPI client, resolving the API key, building the internal HTTP transport, and creating the bound tasks and webhooks resources. This is the single entry point of the SDK. ```APIDOC ## HiAPI.__init__ ### Description Constructs the HiAPI client, resolving the API key, building the internal HTTP transport, and creating the bound tasks and webhooks resources. This is the single entry point of the SDK. ### Method Constructor ### Signature ```python def __init__( self, api_key: Optional[str] = None, *, base_url: str = DEFAULT_BASE_URL, timeout: float = DEFAULT_TIMEOUT, max_retries: int = DEFAULT_MAX_RETRIES, webhook_secret: Optional[str] = None, ) -> None ``` ### Parameters - `api_key` (Optional[str]) - Optional* - Account API key (`sk-...`). Falls back to the `HIAPI_API_KEY` environment variable. - `base_url` (str) - Optional - API base URL, including the `/v1` prefix. Default: `"https://api.hiapi.ai/v1"`. - `timeout` (float) - Optional - Per-request socket timeout in seconds. Default: `60.0`. - `max_retries` (int) - Optional - Retries for 429/503 and retryable network errors (exponential backoff). Default: `2`. - `webhook_secret` (Optional[str]) - Optional - Default signing key for `client.webhooks.verify`; falls back to the `HIAPI_WEBHOOK_SECRET` environment variable. \* `api_key` is required in effect: if neither `api_key` nor `HIAPI_API_KEY` is set, the constructor raises `HiAPIError("missing API key: pass api_key=... or set the HIAPI_API_KEY environment variable")`. ### Notes - `base_url` normalization: trailing slashes are stripped and a missing `/v1` suffix is appended, so both `"https://api.hiapi.ai"` and `"https://api.hiapi.ai/v1"` are accepted. ### Instance Attributes - `api_key` (str) - The resolved API key (`api_key` argument or `HIAPI_API_KEY` env var). - `base_url` (str) - Base URL as passed (not normalized; the normalized form lives on the transport). - `tasks` (Tasks) - Bound task-lifecycle resource. - `webhooks` (Webhooks) - Bound webhook-verification helper. ``` -------------------------------- ### Webhook Delivery (Server → You) Source: https://github.com/hiapiai/hiapi-python Documentation for incoming webhook callbacks from HiAPI to your server. When a Webhook signing key is set, HiAPI POSTs task callbacks to your callback.url with signed headers that must be verified against the raw body. ```APIDOC ## [POST] callback.url ### Description HiAPI delivers task callbacks to your configured callback.url when a Webhook signing key is set in the HiAPI console. The callback contains the full Task JSON and must be verified using the provided signature headers. ### Method POST ### Endpoint `callback.url` (configured in HiAPI console) ### Headers - **X-HiAPI-Timestamp** (string) - Required - Unix seconds as a string - **X-HiAPI-Signature** (string) - Required - `hex( HMAC_SHA256(secret, timestamp + "." + body) )` ### Request Body The full `Task` JSON object (same shape as the GET `data` object). ### Response #### Success Response (2xx) Return 2xx only after processing succeeds. Non-2xx responses trigger redelivery. ### Notes - Signature must be verified against the **raw body** - Delivery is at-least-once and may be concurrent - Reject oversized bodies before reading (e.g., `MAX_CONTENT_LENGTH` in Flask) - 1 MiB is the example threshold - SDK side verification: `verify_webhook` / `client.webhooks.verify` ``` -------------------------------- ### run Source: https://github.com/hiapiai/hiapi-python The one-call workflow: `create` followed by `wait`. `callback`, `route`, and `idempotency_key` are forwarded to `create`; `poll_interval`, `timeout`, and `on_update` are forwarded to `wait`. ```APIDOC ## run ### Description The one-call workflow: `create` followed by `wait`. `callback`, `route`, and `idempotency_key` are forwarded to `create`; `poll_interval`, `timeout`, and `on_update` are forwarded to `wait`. ### Method run ### Parameters #### Path Parameters - `model` (str) - Required - See `create`. - `input` (Dict[str, Any]) - Required - See `create`. #### Query Parameters - `callback` (Optional[Dict[str, Any]]) - Optional (default: `None`) - See `create` (independent of polling; set it if you also want a webhook). - `route` (Optional[str]) - Optional (default: `None`) - See `create`. - `idempotency_key` (Optional[str]) - Optional (default: `None`) - See `create`. - `poll_interval` (float) - Optional (default: `3.0`) - See `wait`. - `timeout` (float) - Optional (default: `600.0`) - See `wait`. - `on_update` (Optional[OnUpdate]) - Optional (default: `None`) - See `wait`. ### Response #### Success Response (200) - Returns the terminal `Task` (status `"success"`). ### Throws - Anything `create` or `wait` throws — `TaskFailed` on task failure, `PollTimeout` when the timeout elapses, and the submission-time `APIError` subclasses (e.g. `IdempotencyKeyMismatchError`, `InvalidRequestError`). ### Request Example ```python from hiapi import HiAPI, PollTimeout, TaskFailed client = HiAPI() # reads HIAPI_API_KEY try: task = client.tasks.run( model="seedance-2-0", input={"prompt": "a cyan glass data center entrance", "resolution": "1080p"}, on_update=lambda t: print("status:", t.status), poll_interval=3.0, timeout=600, ) except TaskFailed as exc: print("task failed:", exc.code, exc.message) except PollTimeout as exc: print("still running after", exc.timeout, "s — retrieve later:", exc.task_id) else: for out in task.output: print(out.type, out.url) ``` ``` -------------------------------- ### Basic construction and use of HiAPI client Source: https://github.com/hiapiai/hiapi-python Constructs a HiAPI client with an optional API key (falls back to HIAPI_API_KEY environment variable), runs a task with a model and input, and prints output type and URL as they stream. ```python from hiapi import HiAPI # api_key is optional when HIAPI_API_KEY is set client = HiAPI(api_key="sk-...") task = client.tasks.run( model="seedance-2-0", input={"prompt": "a cyan glass data center entrance", "resolution": "1080p"}, on_update=lambda t: print("status:", t.status), ) for out in task.output: print(out.type, out.url) # e.g. "video https://cdn.hiapi.ai/tasks/..." ``` -------------------------------- ### HiAPI Client Configuration Source: https://github.com/hiapiai/hiapi-python/blob/main/README.md Instantiate the HiAPI client with optional parameters. The api_key and webhook_secret fall back to environment variables HIAPI_API_KEY and HIAPI_WEBHOOK_SECRET respectively. base_url defaults to 'https://api.hiapi.ai/v1', timeout is 60.0 seconds per request, and max_retries is 2. ```python HiAPI( api_key=None, # falls back to HIAPI_API_KEY base_url="https://api.hiapi.ai/v1", timeout=60.0, # per-request seconds max_retries=2, webhook_secret=None, # falls back to HIAPI_WEBHOOK_SECRET ) ``` -------------------------------- ### Lower-level control with idempotent submission Source: https://github.com/hiapiai/hiapi-python Shows manual create, retrieve, wait, and list calls with an explicit API key. Uses idempotency_key to avoid duplicate submissions and handles IdempotencyKeyMismatchError. The route parameter is preferred over model="...@ext". ```python from hiapi import HiAPI, IdempotencyKeyMismatchError client = HiAPI(api_key="sk-...") created = client.tasks.create( model="seedance-2-0", input={"prompt": "...", "resolution": "720p"}, callback={"url": "https://your-app.com/hiapi/callback", "when": "final"}, route="ext", # preferred over model="...@ext" idempotency_key="order-8472:video", ) print(created.task_id, created.idempotent_replay) # replay means cache hit try: task = client.tasks.retrieve(created.task_id) # one status check task = client.tasks.wait(created.task_id, poll_interval=3, timeout=900) page = client.tasks.list(page=1, size=20) # newest first except IdempotencyKeyMismatchError as exc: print("key reused with a different body — bug in key construction:", exc) ``` -------------------------------- ### create Source: https://github.com/hiapiai/hiapi-python Submit a generation task (image/video/audio) and return immediately with its task_id. The task is processed asynchronously server-side. ```APIDOC ## POST /v1/tasks ### Description Submit a task and return immediately with its `task_id`; the task is processed asynchronously server-side. ### Method POST ### Endpoint /v1/tasks ### Parameters #### Request Body - **model** (str) - Required - Model name, e.g. `"seedance-2-0"`. May carry a route suffix (`"x@ext"`). - **input** (Dict[str, Any]) - Required - The model's business parameters (fields vary per model — see the HiAPI model docs). Do **not** put callback/webhook fields here; pass `callback` separately or the request is rejected. - **callback** (Optional[Dict[str, Any]]) - Optional - Webhook delivery config, e.g. `{"url": "...", "when": "final"}`. - **route** (Optional[str]) - Optional - Model route (e.g. `"ext"`, `"pro"`) — the preferred spelling of the `model@route` suffix. `""` and `None` both mean "no route" and are omitted from the body. An unknown route is rejected with a 400 that lists the available routes. - **idempotency_key** (Optional[str]) - Optional - Sent as the `Idempotency-Key` header (≤ 255 bytes). Makes the POST safe to retry; enables network-error retries for this request. ### Response #### Success Response (200) - **task_id** (string) - The task ID. - **idempotent_replay** (boolean) - True when the server answered from its idempotency cache. ### Throws - `InvalidRequestError` - malformed body, unknown route - `IdempotencyKeyMismatchError` - 422, key reused with a different body — **not** retryable - `IdempotencyKeyProcessingError` - 409, first request still in flight — the transport retries this automatically ``` -------------------------------- ### Create task with idempotency key Source: https://github.com/hiapiai/hiapi-python/blob/main/README.md Pass an 'idempotency_key' to make task submission safe to retry. The SDK retries on network errors and 409 responses, and reusing a key with a different body raises 'IdempotencyKeyMismatchError'. ```python created = client.tasks.create( model="seedance-2-0", input={"prompt": "..."}, idempotency_key="order-8472:video", # a stable key you derive per job ) if created.idempotent_replay: print("hit the idempotency cache; no new task created") ``` -------------------------------- ### Error handling for missing API key and webhook secret Source: https://github.com/hiapiai/hiapi-python Shows how a missing API key is rejected at construction time, with recovery, and that webhook secret is resolved lazily at verify time. ```python import os from hiapi import HiAPI, HiAPIError os.environ.pop("HIAPI_API_KEY", None) try: client = HiAPI() except HiAPIError as exc: print("configure an API key first:", exc) # "missing API key: pass api_key=... or set the HIAPI_API_KEY environment variable" client = HiAPI(api_key="sk-...") # recovery # Automated callbacks need a signing secret; it is resolved lazily at verify # time, so constructing without one only fails when a callback arrives: receiver = HiAPI(api_key="sk-...", webhook_secret="whsec_...") ``` -------------------------------- ### run method signature Source: https://github.com/hiapiai/hiapi-python One-call workflow that combines create and wait. Forwards callback, route, and idempotency_key to create; poll_interval, timeout, and on_update to wait. Returns the terminal Task with status 'success'. Throws anything create or wait throws, including TaskFailed, PollTimeout, and APIError subclasses. ```python def run( self, *, model: str, input: Dict[str, Any], callback: Optional[Dict[str, Any]] = None, route: Optional[str] = None, idempotency_key: Optional[str] = None, poll_interval: float = DEFAULT_POLL_INTERVAL, timeout: float = DEFAULT_TIMEOUT, on_update: Optional[OnUpdate] = None, ) -> Task ``` -------------------------------- ### AuthenticationError Source: https://github.com/hiapiai/hiapi-python Exception raised when the server returns a 401 status code, indicating a missing or invalid API key. ```APIDOC ## AuthenticationError ### Description Exception raised when the server returns a 401 status code, indicating a missing or invalid API key. ### Source `errors.py:55` ``` -------------------------------- ### Verify webhook signature in Flask Source: https://github.com/hiapiai/hiapi-python/blob/main/README.md Use this Flask endpoint to verify signed webhook callbacks against the raw request body. Requires a webhook signing key set in the HiAPI console and a client initialized with the webhook secret. Returns 400 on verification failure and 200 after processing; callbacks are delivered at least once and may arrive concurrently, so make the handler idempotent. ```python # Flask example from flask import Flask, request from hiapi import HiAPI, WebhookVerificationError app = Flask(__name__) app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024 # 1 MiB — reject oversized bodies before reading client = HiAPI(api_key="sk-...", webhook_secret="whsec_...") @app.post("/hiapi/callback") def callback(): try: task = client.webhooks.verify(request.get_data(), request.headers) except WebhookVerificationError: return "", 400 if task.succeeded and task.output: print(task.output[0].url) return "", 200 # ack with 2xx; HiAPI retries non-2xx ``` -------------------------------- ### NotFoundError Source: https://github.com/hiapiai/hiapi-python Exception raised when the server returns a 404 status code, indicating that a task does not exist or does not belong to the user. ```APIDOC ## NotFoundError ### Description Exception raised when the server returns a 404 status code, indicating that a task does not exist or does not belong to the user. ### Source `errors.py:59` ``` -------------------------------- ### list Source: https://github.com/hiapiai/hiapi-python List your tasks, newest first (paginated). Returns a TaskPage with items, page, size, and total. ```APIDOC ## GET /v1/tasks?page=&size= ### Description List your tasks, newest first (paginated). ### Method GET ### Endpoint /v1/tasks?page=&size= ### Parameters #### Query Parameters - **page** (int) - Optional - 1-based page number. Default: 1 - **size** (int) - Optional - Page size. Default: 20 ### Response #### Success Response (200) - **items** (array) - The page array taken from the first of `"tasks"`, `"items"`, `"list"`, `"data"`, `"records"` keys present in the response. - **page** (int) - The current page number. - **size** (int) - The page size. - **total** (int) - The total number of tasks. ``` -------------------------------- ### Webhooks Resource Source: https://github.com/hiapiai/hiapi-python Resource for verifying webhook signatures to ensure callback authenticity. ```APIDOC ## Webhooks Resource ### Description Provides webhook signature verification functionality to validate callback authenticity using HMAC-SHA256. ### Methods #### verify() -> Task Verifies the HMAC-SHA256 callback signature over the raw body and timestamp freshness, then parses the payload into a Task object. ### Usage Example ```python # Verify a webhook result = client.webhooks.verify(body=raw_body, headers=headers) ``` ``` -------------------------------- ### ServiceUnavailableError Source: https://github.com/hiapiai/hiapi-python Exception raised when the server returns a 503 status code, indicating that the platform is temporarily unavailable. ```APIDOC ## ServiceUnavailableError ### Description Exception raised when the server returns a 503 status code, indicating that the platform is temporarily unavailable. ### Source `errors.py:63` ``` -------------------------------- ### Webhooks class definition Source: https://github.com/hiapiai/hiapi-python Defines the Webhooks bound helper class with its constructor and verify method signatures. Instantiated by HiAPI.__init__ as client.webhooks, using the client's webhook_secret which falls back to HIAPI_WEBHOOK_SECRET. ```python class Webhooks: def __init__(self, client: HiAPI, secret: Optional[str]) -> None # webhooks.py:108 def verify( self, body: Union[bytes, str], headers: Mapping[str, Any], *, secret: Optional[str] = None, tolerance: int = DEFAULT_TOLERANCE, now: Optional[int] = None, ) -> Task # webhooks.py:112 ``` -------------------------------- ### Tasks Resource Source: https://github.com/hiapiai/hiapi-python Resource for managing task lifecycle operations including creation, retrieval, listing, waiting, and running tasks. ```APIDOC ## Tasks Resource ### Description Provides methods to create, retrieve, list, wait for, and run tasks through the HiAPI unified async task API. ### Methods #### create() -> CreatedTask Creates a new task by POSTing to /v1/tasks. #### retrieve() -> Task Retrieves a task by ID using GET /v1/tasks/{id}. #### list() -> TaskPage Lists tasks using GET /v1/tasks?page=&size=. #### wait() -> Task Polls the retrieve method in a loop until the task reaches a terminal state. Raises TaskFailed or PollTimeout. #### run() -> Task Combines create and wait operations in a single call. ### Usage Example ```python # Create a task created = client.tasks.create() # Retrieve a task task = client.tasks.retrieve(id="task-id") # List tasks page = client.tasks.list(page=1, size=10) # Wait for task completion task = client.tasks.wait(id="task-id") # Run task (create + wait) task = client.tasks.run() ``` ``` -------------------------------- ### Import all public symbols from hiapi package root Source: https://github.com/hiapiai/hiapi-python One import line gives access to the entire public API surface, including the client, models, errors, and webhook verification. All runtime dependencies are stdlib only, requiring Python 3.8+. ```python from hiapi import ( HiAPI, Task, Output, TaskError, CreatedTask, TaskPage, verify_webhook, HiAPIError, APIError, APIConnectionError, AuthenticationError, NotFoundError, ServiceUnavailableError, InvalidRequestError, ModelUnavailableError, TaskFailedError, TaskTimeoutError, StorageUnavailableError, IdempotencyKeyProcessingError, IdempotencyKeyMismatchError, TaskFailed, PollTimeout, WebhookVerificationError, ) from hiapi import __version__ ``` -------------------------------- ### CreatedTask dataclass with from_dict Source: https://github.com/hiapiai/hiapi-python Thin response model for POST /v1/tasks. Contains task_id and idempotent_replay flag; from_dict parses the response dict. ```python @dataclass class CreatedTask: task_id: str idempotent_replay: bool = False raw: Dict[str, Any] = field(default_factory=dict, repr=False) @classmethod def from_dict(cls, d: Dict[str, Any], *, idempotent_replay: bool = False) -> CreatedTask ``` -------------------------------- ### Internal request helper methods Source: https://github.com/hiapiai/hiapi-python Internal methods for making HTTP requests. _request returns the parsed JSON envelope; _request_with_headers also returns lower-cased response headers. Both raise APIError subclasses on non-2xx responses and APIConnectionError on network failures. ```python def _request( self, method: str, path: str, *, body: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, Any]] = None, extra_headers: Optional[Dict[str, str]] = None, ) -> Dict[str, Any] ``` ```python def _request_with_headers( self, method: str, path: str, *, body: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, Any]] = None, extra_headers: Optional[Dict[str, str]] = None, ) -> Tuple[Dict[str, Any], Dict[str, str]] ``` -------------------------------- ### StorageUnavailableError Source: https://github.com/hiapiai/hiapi-python Exception raised when the server returns an error with the error code STORAGE_UNAVAILABLE. ```APIDOC ## StorageUnavailableError ### Description Exception raised when the server returns an error with the error code STORAGE_UNAVAILABLE. ### Source `errors.py:83` ``` -------------------------------- ### HiAPI constructor signature Source: https://github.com/hiapiai/hiapi-python Constructor for the HiAPI client. Accepts an optional API key, base URL, timeout, max retries, and webhook secret. Raises HiAPIError if no API key is provided via argument or environment variable. ```python def __init__( self, api_key: Optional[str] = None, *, base_url: str = DEFAULT_BASE_URL, timeout: float = DEFAULT_TIMEOUT, max_retries: int = DEFAULT_MAX_RETRIES, webhook_secret: Optional[str] = None, ) -> None ``` -------------------------------- ### POST /v1/tasks Source: https://github.com/hiapiai/hiapi-python Submits a new task to the HiAPI service. This endpoint accepts model-specific input parameters and returns a task ID for tracking. The SDK method client.tasks.create() wraps this endpoint. ```APIDOC ## [POST] /v1/tasks ### Description Submits a new task to the HiAPI service. This endpoint accepts model-specific input parameters and returns a task ID for tracking. The SDK method client.tasks.create() wraps this endpoint. ### Method POST ### Endpoint /v1/tasks ### Parameters #### Request Body - **model** (string) - Required - Model name (may carry a `@route` suffix, e.g. `"x@ext"`). - **input** (object) - Required - Model-defined business parameters — see the HiAPI model docs. - **route** (string) - Optional - Route name (e.g. `"ext"`); omitted when `None`/`""`. Unknown routes → 400 listing the available routes. - **callback** (object) - Optional - `{"url": string, "when": "final"}` — webhook delivery config. Must not go inside `input`. #### Headers - **Idempotency-Key** (string) - Optional - ≤ 255 bytes; SDK param `idempotency_key`. ### Response #### Success Response (200) - **taskId** (string) - New task id (e.g. `"tk-hiapi-abc123"`). Response header `idempotent-replay: true` signals the server answered from the idempotency cache: `taskId` refers to the task created by the first identical request, and **no** new task was created (SDK maps this to `CreatedTask.idempotent_replay`). ### Status codes / errors | Status | error_code | SDK exception | |--------|-----------|---------------| | 400 | `INVALID_REQUEST` | `InvalidRequestError` (bad request — e.g. callback fields inside `input`, unknown `route`) | | 400 | (none) | `InvalidRequestError` (status fallback) | | 401 | — | `AuthenticationError` | | 403 | — | `APIError` (base class) | | 404 | — | `NotFoundError` | | 409 | `IDEMPOTENCY_KEY_PROCESSING` | `IdempotencyKeyProcessingError` (first request still in flight — auto-retried with key) | | 422 | `IDEMPOTENCY_KEY_MISMATCH` | `IdempotencyKeyMismatchError` (key reused with different body — not retryable) | | 429 | — | `APIError` (auto-retried) | | 503 | — | `ServiceUnavailableError` (auto-retried) | | any other error_code | `MODEL_UNAVAILABLE` / `TASK_FAILED` / `TASK_TIMEOUT` / `STORAGE_UNAVAILABLE` | `ModelUnavailableError` / `TaskFailedError` / `TaskTimeoutError` / `StorageUnavailableError` | ``` -------------------------------- ### Models Source: https://github.com/hiapiai/hiapi-python Data models representing API objects including Task, Output, TaskError, CreatedTask, and TaskPage. ```APIDOC ## Models ### Description Data models representing API objects. All models are dataclasses with defensive from_dict parsing; unknown wire fields are preserved in .raw. ### Available Models #### Task Represents a task in the system. #### Output Represents task output data. #### TaskError Represents task error information. #### CreatedTask Represents a newly created task. #### TaskPage Represents a paginated list of tasks. ### Usage Example ```python from hiapi import Task, Output, TaskError, CreatedTask, TaskPage # Models are typically returned from API calls task = client.tasks.retrieve(id="task-id") ``` ``` -------------------------------- ### CreatedTask Source: https://github.com/hiapiai/hiapi-python Thin response model for POST /v1/tasks, containing just the new task id. Includes an idempotent replay flag and the raw source dictionary. ```APIDOC ## CreatedTask ### Description Thin response of `POST /v1/tasks` — just the new task id. ### Fields - **task_id** (`str`) - Required - The new task id (`d["taskId"]`). - **idempotent_replay** (`bool`) - Optional - `True` when the server answered from the idempotency cache: `task_id` is the task created by the first identical request, and **no** new task was created. Set from the `idempotent-replay` response header by `Tasks.create`. - **raw** (`Dict[str, Any]`) - Optional - Full source dict; `repr=False`. ### Class Method - `from_dict(cls, d: Dict[str, Any], *, idempotent_replay: bool = False) -> CreatedTask` ``` -------------------------------- ### Error Catalog Source: https://github.com/hiapiai/hiapi-python List of all error classes raised by the HiAPI Python SDK, their trigger conditions, source locations, and retryability. ```APIDOC ## Error Catalog ### Description List of all error classes raised by the HiAPI Python SDK, their trigger conditions, source locations, and retryability. ### Errors | Error | Trigger condition | Source location | Retryable? | |-------|-------------------|-----------------|------------| | `AuthenticationError` | HTTP 401 — missing / invalid API key | `errors.py:55`; map `errors.py:157` | no | | `NotFoundError` | HTTP 404 — task does not exist or does not belong to this account | `errors.py:59`; map `errors.py:157` | no | | `ServiceUnavailableError` | HTTP 503 — platform temporarily unavailable | `errors.py:63`; map `errors.py:157` | **yes — transport auto-retries 503 up to `max_retries` with backoff** (`_transport.py:30`, `:83`) | | `InvalidRequestError` | `error_code=INVALID_REQUEST` (also HTTP-400 status fallback) — fix the request; do not retry as-is | `errors.py:67`; map `errors.py:147` | no | | `ModelUnavailableError` | `error_code=MODEL_UNAVAILABLE` — retry shortly or switch models | `errors.py:71`; map `errors.py:148` | retryable by caller | | `TaskFailedError` | `error_code=TASK_FAILED` on a synchronous response (distinct from `TaskFailed` below) | `errors.py:75`; map `errors.py:149` | no | | `TaskTimeoutError` | `error_code=TASK_TIMEOUT` — the upstream task timed out | `errors.py:79`; map `errors.py:150` | retryable | | `StorageUnavailableError` | `error_code=STORAGE_UNAVAILABLE` — output storage error | `errors.py:83`; map `errors.py:151` | retryable | | `IdempotencyKeyProcessingError` | HTTP 409 + `error_code=IDEMPOTENCY_KEY_PROCESSING` — the first request with this `Idempotency-Key` is still in flight | `errors.py:87`; map `errors.py:152`; retry logic `_transport.py:131` | **yes — auto-retried when a key was sent, honouring `Retry-After` (capped at 60s), up to `max_retries`** | | `IdempotencyKeyMismatchError` | HTTP 422 + `error_code=IDEMPOTENCY_KEY_MISMATCH` — this `Idempotency-Key` was already used with a different request body | `errors.py:95`; map `errors.py:153` | **no — key construction is buggy** | | `APIConnectionError` | network-level failure (DNS, connection reset, socket timeout — `OSError` including `socket.timeout`/`TimeoutError`); message `"request to failed: "` | `errors.py:101`; raised `_transport.py:155` | dependent (see below) | | `TaskFailed` | a polled task reached terminal `status=fail` | `errors.py:105`; raised in `Tasks.wait` (`resources/tasks.py:113`) | no — task is terminal | | `PollTimeout` | `run()`/`wait()` exceeded `timeout` seconds without a terminal state | `errors.py:124`; raised `resources/tasks.py:116` | no — task may still finish; `retrieve()` it | | `WebhookVerificationError` | callback verification: missing/blank headers, blank secret, non-integer timestamp, stale timestamp (beyond `tolerance`), signature mismatch, or non-JSON verified body | `errors.py:141`; raised `webhooks.py:43-83` | no — reject with 4xx so the server redelivers only if appropriate | | `APIError` (base) | any other non-2xx response (e.g. 402, 403); also JSON framing failures: non-JSON body / non-object body (`_decode_json`, `_transport.py:223`) | `errors.py:30` | no | | `HiAPIError` (base) | missing API key at client construction (`client.py:55`); catch-all base | `errors.py:26` | n/a | | `ValueError` (stdlib) | `Tasks.wait`/`run` with `poll_interval <= 0` or `timeout < 0` | `resources/tasks.py:99-102` | n/a | ``` -------------------------------- ### Advanced configuration of HiAPI client Source: https://github.com/hiapiai/hiapi-python Configures base URL, timeout, max retries, and webhook secret. The base URL appends '/v1' if omitted; timeout is per-request socket timeout; max_retries covers 429/503 and retryable network errors. ```python from hiapi import HiAPI client = HiAPI( api_key="sk-...", base_url="https://api.hiapi.ai/v1", # "/v1" is appended if omitted timeout=30.0, # per-request socket timeout max_retries=2, # 429/503 + retryable network errors webhook_secret="whsec_...", # default for client.webhooks.verify ) ``` -------------------------------- ### Output dataclass with from_dict Source: https://github.com/hiapiai/hiapi-python Defines the Output dataclass for a generated artifact. The from_dict classmethod parses the wire format (camelCase) into snake_case attributes, tolerating missing fields and keeping unknown fields in raw. ```python @dataclass class Output: url: str type: str expire_at: Optional[int] = None raw: Dict[str, Any] = field(default_factory=dict, repr=False) @classmethod def from_dict(cls, d: Dict[str, Any]) -> Output ``` -------------------------------- ### client.tasks.retrieve Source: https://github.com/hiapiai/hiapi-python Retrieves a task by its ID. Returns a Task object with status, output, and error information. ```APIDOC ## client.tasks.retrieve ### Description Retrieves a task by its ID. Returns a Task object with status, output, and error information. ### Method client.tasks.retrieve ### Parameters #### Path Parameters - **task_id** (str) - Required - The task ID to retrieve ### Response #### Success Response - **status** (str) - Task status: "queued" | "handling" | "archiving" | "success" | "fail" - **is_terminal** (bool) - Whether the task has reached a terminal state - **succeeded** (bool) - Whether the task succeeded - **output** (array) - List of output objects, each with `type`, `url`, and `expire_at` fields - **error** (object) - Error object with `code` and `message` fields (present on failure) ### Request Example ```python from hiapi import HiAPI client = HiAPI(api_key="sk-...") task = client.tasks.retrieve("tk-hiapi-abc123") print(task.status) # "queued" | "handling" | "archiving" | "success" | "fail" print(task.is_terminal, task.succeeded) if task.succeeded: for out in task.output: # `expire_at` is when this URL stops working (~7 days after creation) print(out.type, out.url, out.expire_at) elif task.error: print(task.error.code, task.error.message) ``` ``` -------------------------------- ### Output.from_dict Source: https://github.com/hiapiai/hiapi-python Classmethod to parse a dictionary into an Output dataclass instance. It maps wire fields (camelCase) to snake_case attributes and tolerates missing or malformed fields. ```APIDOC ## Output.from_dict ### Description Classmethod to parse a dictionary into an Output dataclass instance. It maps wire fields (camelCase) to snake_case attributes and tolerates missing or malformed fields. ### Method from_dict ### Signature ```python @classmethod def from_dict(cls, d: Dict[str, Any]) -> Output ``` ### Parameters #### Input - **d** (Dict[str, Any]) - Required - The source dictionary containing the wire-format fields. ### Returns - **Output** - An Output instance with parsed attributes. ### Field Mapping - `url` ← `d["url"]` - `type` ← `d["type"]` - `expire_at` ← `d["expireAt"]` ### Fields | Field | Type | Required | Description | |-------|------|----------|-------------| | `url` | `str` | yes (default `""`) | Temporary output URL (expires about 7 days after creation — each output carries `expire_at`). | | `type` | `str` | yes (default `""`) | Artifact kind, e.g. `"video"`, `"image"`, `"audio"`. | | `expire_at` | `Optional[int]` | no | Unix seconds when the URL expires; from the wire field `expireAt`. | | `raw` | `Dict[str, Any]` | no | The full source dict; `repr=False`. | ```