---
name: glacierai-api-integration
description: Integrate the chaozapi China public API v1 into server applications using Python, TypeScript or Go, with durable uploads, idempotent jobs, polling, cost caps and result downloads.
---

## Goal and scope

Inspect the target application's language, HTTP abstraction, configuration, background jobs and storage. Implement the integration in that structure, including configuration examples and tests. Use the commercial public API, not internal Inference/GPU services or workspace login endpoints.

## Connection and resources

- Site origin: `https://www.chaozapi.com`. HTTP prefix: `/api/v1`. SDK constructors accept the origin only.
- Header: `Authorization: Bearer <GLACIER_API_KEY>`. Create a `gk_…` key in Account → API. Store it server-side; do not embed it in browsers, URLs or logs. JWTs/cookies cannot replace API keys.
- Site accounts, keys, credits and storage are separate. Use the key's issuing site.
- JSON fields are camelCase. Omit unused optional request fields; do not invent fields or send null unless allowed. Ignore unknown response fields. Treat IDs as opaque UUIDs.
- [Public OpenAPI](https://www.chaozapi.com/docs/api/openapi.json), [API docs](https://www.chaozapi.com/docs/en/api/), [SDK guide](https://www.chaozapi.com/docs/en/api/sdk/).
- [Python source](https://www.chaozapi.com/docs/api/sdk/python.zip), [TypeScript source](https://www.chaozapi.com/docs/api/sdk/typescript.zip), [Go source](https://www.chaozapi.com/docs/api/sdk/go.zip). SDK v0.1.0 is distributed as local source, not published registry packages.

## Adapt the application

1. Add the provider in the existing server-side integration layer and reuse configuration, errors, storage and job infrastructure.
2. Prefer the one-call SDK workflow below. Assign a durable state file per business job and store its path, remote task ID and terminal state in your app. The SDK persists keys, asset ID, exact request JSON and SHA-256 before submission. Use low-level methods with equivalent database checkpoints when file state does not fit the application.
3. Run uploads and polling in background jobs. Expose your own job creation/status endpoints to the UI. Display queued/running/succeeded/failed/canceled and cancelRequested.
4. Use a separate file HTTP client with no API authorization or cookies. Store completed results in existing application storage; signed links are temporary.
5. Test locally with a mock server. For authorized real verification, use the user's test input and cost cap and retain requestId/taskId. Do not equate mock tests with production GPU/storage verification.

## Prefer the one-call SDK

Do not require callers to orchestrate upload, completion, quoting, submission and polling for an ordinary local file:

~~~python
import os
from glacierai import Client
client = Client(os.environ["GLACIER_API_KEY"])
result = client.process_file(
    "input.png", "image-sr", {"type": "scale", "value": 2},
    state_file="jobs/photo-001.json", max_cost_credits=100, download_to="output.png",
)
~~~

- submit_file/submitFile/SubmitFile uploads and submits, returning a task. process_file/processFile/ProcessFile also waits and optionally downloads. TS arguments: `(path, {toolId, params, maxCostCredits}, {stateFile, downloadTo})`. Go: `(ctx, path, CreateTaskInput{ToolID, Params, MaxCostCredits}, FileOptions{StateFile, DownloadTo})`, with a pointer for the cap.
- Each business job has a distinct state file. The SDK generates keys, persists before POST and checks SHA-256, site and parameters on resume. It submits without a volatile quoteId; the server quotes internally and enforces the cap.100 is an example budget, not a price. Keep original state and unchanged input for recovery; new jobs get new state. State contains no API secret or signed URL. Use durable storage and one worker per logical job.
- Temporary network failures and HTTP429/500/502/503/504 receive at most3 attempts by default, with Retry-After and backoff, using the same key/body. Input/auth/balance/conflict/gone failures are not blindly retried. Failed tasks are never rerun automatically. Configure max_attempts/maxAttempts/MaxAttempts from1–10.
- process_files/processFiles/ProcessFiles defaults to concurrency1, configurable1–16. Python jobs are process_file keyword dictionaries; TS jobs are `{path, task, options}`; Go jobs are FileJob. State/output paths must be distinct. Results retain input order with result/error (Go Result/Err). Retry only failed original jobs; concurrency does not increase account rights or replace shared rate limits.
- on_progress/onProgress/OnProgress emits phase and task/upload/IDs. Phases: uploading/preparing/submitted/task/downloading/completed. task.progress is0–1; upload has no byte percentages. Python/Go batch callbacks may run concurrently.
- iter_tasks/iter_assets, iterateTasks/iterateAssets and EachTask/EachAsset fetch pages lazily. Python max_items and TS maxItems bound results; Go callbacks return false to stop.
- download_result/downloadResult/DownloadResult refreshes signed URLs by task ID and retries downloads without resubmission. Reports with output=null create no file. Existing destinations are never overwritten.
- Python cancel_event, TS signal and Go ctx stop local operations only. Python synchronous in-flight requests still await response/timeout. Explicitly use cancelTask to stop remote work. Default polling is15 seconds with a30-minute limit per wait; configure Python wait_timeout/poll_interval, TS timeoutMs/pollIntervalMs or Go context/PollInterval.
- File helpers automate whole-file PUT. Use low-level APIs for chunk scheduling and distributed database state. Existing asset/version inputs or explicit quoteId use createTask, not file helpers.

## Low-level HTTP workflow (for custom integrations)

### Discover capabilities

GET /tools returns toolId, kind, param, limits, price and tiers. A null price or unavailable tier is not executable. Animated media has separate animated/animatedAvailable/animatedScales/animatedPrice fields. Do not hardcode prices, supported scales or limits.

image-sr/video-sr use `{"type":"scale","value":2}` with optional fast/pro tier. Color tools use faceProtect; interpolation uses fps; detection/person/attack tools use none. Read the live catalog and quote for actual choices.

Current China automatic video removal uses `toolId:"watermark"` and `params:{"type":"none"}`. Do not require watermark-find/mask or regions. Historical schemas/endpoints do not imply current worker support.

### Upload and wait for readiness

Read GET /assets/upload-limits. POST /assets/uploads with the exact file size:

~~~json
{"name":"input.png","mimeType":"image/png","sizeBytes":123456}
~~~

Pass a durable upload Idempotency-Key (recommended). Upload and task keys have separate namespaces. The response contains assetId/uploadUrl/method/headers/expiresAt; headers is an array of name/value pairs.

- For PUT send raw bytes and ticket headers, with **no API key**.
- multipart:true selects POST form: append every formFields entry first, the fileField file last, and let the HTTP library set the boundary.
- resumable:true selects chunked upload. POST /assets/{id}/upload-session resumes; POST /assets/{id}/upload-parts signs parts. Numbers start at 1, SHA-256 is lowercase hex of the raw part. Save ETag, hashes and routeGeneration; skip only matching stored parts.
- POST /assets/{id}/complete after storage succeeds; optional body carries routeGeneration and parts. Poll GET /assets/{id}/upload-status until ready. preparing means media validation, failed is terminal, pending cannot be processed.
- POST /assets/{id}/upload-ticket refreshes the same session. A replay returning preparing/ready with an empty URL must not upload again. Handle 410 UPLOAD_SESSION_EXPIRED and 503 UPLOAD_STORAGE_UNAVAILABLE explicitly.
- Use full returned file URLs without replacing hosts or signatures. The API does not fetch arbitrary input URLs; download remote inputs yourself first.

### Quote and submit

POST /tasks/quote is optional; if used, require problem=null and an unexpired quoteId. It locks pricing, not balance or compute. Submit the unchanged selection with quoteId and a maxCostCredits cap, or submit directly with a cap:

~~~json
{"assetId":"REAL_READY_ASSET_ID","toolId":"image-sr","params":{"type":"scale","value":2},"maxCostCredits":100}
~~~

POST /tasks requires Idempotency-Key: 1–128 letters, digits, dot, underscore, colon or hyphen. Persist before sending. **Retry the same key and entire body, including quoteId.** After an uncertain response, replay before requoting or changing the key.

202 means accepted, not finished. Save id/status/urls. urls.status/result/cancel already include /api/v1: join with the site origin. Same key/different body returns 409 IDEMPOTENCY_CONFLICT. A cleaned-up job returns 410 TASK_GONE; replaying a failed task does not rerun it.

sourceVersionId selects an existing version. fitToLimits permits proportional downscaling. nextSteps supports at most five later steps. Requote changed selections; do not assume all tool combinations are valid.

### Poll, cancel and retrieve results

GET /tasks/{id}, normally every 15 seconds, honoring Retry-After. progress is 0–1. Internal retries can move running back to queued. Only succeeded/failed/canceled are terminal.

On success, GET /tasks/{id}/result. If output is non-null, download output.downloadUrl **without the API key**. Otherwise consume report or other structured fields. watermarkAnalysisUrl is an authenticated API path, not a signed file link.

urlExpiresAt is the signature lifetime. Refresh result or POST /assets/{assetId}/versions/{versionId}/download-url after expiry, without creating another task. Asset retention expiresAt is different: deleted artifacts return 410 RESULT_GONE and cannot be recovered by refreshing.

POST /tasks/{id}/cancel is idempotent. running plus cancelRequested=true is not yet canceled: keep polling. Local timeout, process exit, context cancellation or AbortSignal never cancels remote work. A task that finishes before cancellation can still succeed and be charged.

### AI generation and upscaled delivery (/v1/generations*)

- **Discover & estimate**: Call `GET /api/v1/generation-models` for `billingMode` (`tokens`, `duration`, or `image`) and availability, then `POST /api/v1/generations/estimate` (`read` scope) for `generationCredits`, `upscaleCredits`, AI-eligible `balanceCredits`, and excluded `giftCredits`.
- **Seedance HD delivery**. Estimate `1080p` or `2k` and create with `mode:"auto_upscale"` and matching `downloadResolution`. Successful delivery settles one charge at the saved rates using actual provider usage and processing. Confirmed failure or cancellation releases the full hold. All paid subscription credits qualify for HD. For a 480p original, estimate with `resolution: "480p"`, then submit `mode: "preview"` and `sku: "preview"` without `downloadResolution`. The original settles at the saved rate using actual provider usage. Pass the quoted `originalFunding` and `originalQuoteKey` when creating a 480p order to lock the funding group and rate. Request and confirm a fresh quote if either changes. Images and historical orders retain their original billing and download terms.
- **Upgrading a purchased 480p original**. Request the additional charge from `POST /api/v1/generations/{id}/exports/quote`. The quote credits the original purchase and applies a minimum processing charge for the export. Check `costCredits`, the eligible `balanceCredits` and output dimensions before submitting the chosen resolution and approved `maxCostCredits`. Verified top-up principal and paid plan credits can pay for this upgrade.
- **Gift credits excluded**: Free gift credits cannot pay for AI generation and insufficient paid credits return `402`.
- **Submit & read usage/bill**: `POST /api/v1/generations` requires `write` scope, a durable `Idempotency-Key`, and `maxCostCredits`. Poll `GET /api/v1/generations/{id}` (15s suggested). Read `completionTokens`, structured `usage` (`billingMode`, `completionTokens`, `billedSeconds`), and `bill` (`generationCredits`, `upscaleCredits`, `totalCredits`). Retrieve upscaled deliverables via `POST /api/v1/generations/{id}/exports/{taskId}/download-url` without sending the API key to signed file URLs.
- **Completion and recovery**: With `deliveryOnly=true`, `status=succeeded` confirms HD delivery. For 480p originals, images and earlier orders it confirms upstream generation; originals also require `sourceStatus=ready`. Inspect the export's `task.status` through `autoTaskId`; `autoStatus=submitted` is not delivery completion. Null `bill.upscaleCredits` means automatic upscaling has not settled, not free service. This bill excludes later manual exports; each has its own `export.task.costCredits`. `submission_unknown` requires provider reconciliation: never resubmit with a new key or assume a refund. Upstream generation cancellation is not exposed; stopping local polling does not stop billing. Existing upscaling tasks use ordinary task cancellation.
- **SDK and pagination**: Generation methods make one request and callers persist keys/bodies themselves. `processFile` / `waitForTask` do not accept generation IDs. Generation/export lists are arrays; pass the last ID (`task.id` for exports) as `before`. Download tickets contain `url`; pass it to the SDK download method without API credentials.

## Cost and recovery

Submission reserves estimated credits; success settles actual output. A running task's costCredits=0 is not free processing. Wallet balanceCredits already excludes reservedCredits. Failed/canceled tasks release reservations. maxCostCredits caps final cost; do not recalculate billing client-side.

| Condition | Action |
| --- | --- |
| 400/422 | Correct input; no blind retries |
| 401/403 | Check site, key, expiry and scopes |
| 402 | Surface balance/account constraints |
| 409 TASK_NOT_READY | Keep waiting; TASK_FAILED/TASK_CANCELED are terminal |
| QUOTE_EXPIRED/QUOTE_MISMATCH | First recover any original submission; requote only for a confirmed new logical job |
| IDEMPOTENCY_CONFLICT | Inspect saved request, do not blindly rotate keys |
| 410 | Handle the specific expired/deleted resource code |
| 429, 500/502/503/504, network failure | Bounded retry with Retry-After; submissions retain original key/body |

Errors are application/problem+json with status/code/detail/requestId/errors?. Match code, not Chinese detail text. Fall back to HTTP status for unknown codes and handle non-JSON proxy errors. Log IDs/status, not keys or signed URLs.

Each key permits120 requests per rolling60 seconds; active jobs share the budget. GET /benefits exposes account concurrency; more keys do not increase compute quotas. Low-level SDK methods send one request. High-level workflows have bounded retries; wait helpers retry transient reads within a deadline (30 minutes per wait by default).

## SDK method mapping

| Operation | Python | TypeScript | Go |
| --- | --- | --- | --- |
| Client | Client(key, origin) | new Client({apiKey, baseUrl}) | NewClient(key, origin) |
| Submit / complete workflow | submit_file / process_file | submitFile / processFile | SubmitFile / ProcessFile |
| Batch | process_files | processFiles | ProcessFiles |
| Lazy pagination | iter_tasks / iter_assets | iterateTasks / iterateAssets | EachTask / EachAsset |
| Download by task ID | download_result | downloadResult | DownloadResult |
| Upload and prepare | upload_file(path, mime, idempotency_key=key) | uploadFile(path, mime, key) | UploadFile(ctx, path, mime, key) |
| Quote | quote_task(body) | quoteTask(body) | QuoteTask(ctx, body) |
| Submit | create_task(body, idempotency_key=key) | createTask(body, key) | CreateTask(ctx, body, key) |
| Wait | wait_for_task(id) | waitForTask(id) | WaitForTask(ctx, id, 15*time.Second) |
| Result | get_task_result(id) | getTaskResult(id) | GetTaskResult(ctx, id) |
| Download | download(url, path) | download(url, path) | Download(ctx, url, path) |
| Page tasks | page_tasks(query) | pageTasks(query) | PageTasks(ctx, url.Values) |

Python returns dicts; TypeScript has generated types; Go optional scalars are pointers and TaskParams is a map. TaskError contains the terminal failed/canceled task; WaitTimeout identifies the resource to resume. High-level workflows verify SHA-256 and persist the original request; low-level uploadFile compares metadata only. High-level uploads automate whole-file PUT; chunk/form APIs remain available for explicit orchestration.

## Acceptance

Deliver configuration, code changes, durable job state and test commands. Verify preparing→ready, one task for repeated keys, failure/cancellation, null outputs, Retry-After, credential-free file requests and expired-link refresh. State clearly which checks used mocks and which exercised production storage/GPU.
