Skip to content

SDK downloads & usage

One-call upload and processing with Python, TypeScript or Go, including recovery, batches, progress and pagination.

SDK v0.1.0 targets public API v1 and defaults to the China site. All three server-side clients wrap the 37 public JSON endpoints, whole-file PUT upload, upload readiness, task polling and streamed downloads.

AI generation uses single-request methods with application-managed idempotency keys and bodies. Check upstream generation, source archiving, and upscaling separately; the file-processing helpers below do not accept generation IDs. See generation SDK methods and state conventions.

Uploading and submitting takes one method call. submit_file / submitFile / SubmitFile uploads, waits for media readiness and submits. process_file / processFile / ProcessFile also waits for success, retrieves the result and optionally downloads it. Supply the input, tool parameters and a state-file path; the SDK saves keys, IDs and the exact request.

SDK Requirements Source archive
Python Python 3.10+, synchronous, no third-party runtime dependencies python.zip
TypeScript Node.js 22.12+, server-side ESM, generated types typescript.zip
Go Go 1.22+, standard library go.zip

These are local source packages, not published PyPI, npm or Go proxy releases. Extract and enter the language directory. In the repository these are sdk_src/python, sdk_src/typescript and sdk_src/go. Never embed an API key in browser code.

终端窗口
uv venv
uv pip install .
uv run python examples/quickstart.py

To install in your own environment, use uv pip install /absolute/path/to/sdk_src/python. Import Client from glacierai. Responses are dictionaries with camelCase fields.

终端窗口
pnpm install --frozen-lockfile
pnpm build
node examples/quickstart.mjs

Build the SDK first, then use pnpm add /absolute/path/to/sdk_src/typescript in your app. Import { Client } from @glacierai/sdk. Types are generated from the backend contract; the runnable Node example below uses .mjs.

终端窗口
go test ./...
go run ./examples/quickstart

In another project, add a local replacement in go.mod:

require github.com/LeeKenMr/SuperResolution/sdk_src/go v0.0.0
replace github.com/LeeKenMr/SuperResolution/sdk_src/go => ../glacierai-go

Replace the path with your extracted SDK directory. Import glacier "github.com/LeeKenMr/SuperResolution/sdk_src/go". Optional scalars are pointers: nil omits a field, while a pointer to int64(0) explicitly sets a zero credit cap. TaskParams is a map.

Prepare input.png and set the following environment variables. The example creates real processing tasks and uses account credits; automated SDK tests only contact a local mock.

Variable Meaning
GLACIER_API_KEY Secret provided through the environment or secret manager
GLACIER_MAX_COST_CREDITS Optional; example defaults to100, a spending cap rather than a price
GLACIER_BASE_URL Optional; defaults to https://www.chaozapi.com, without /api/v1
GLACIER_INPUT / GLACIER_OUTPUT Optional; default input.png / output.png
GLACIER_STATE_FILE Optional; default glacier-request.json

Bash: export GLACIER_STATE_FILE='jobs/photo-001.json'. PowerShell: $env:GLACIER_STATE_FILE='jobs/photo-001.json'. Only the key and input file are required to run the example; upload/task keys are generated automatically.

Use one state file per business job. The SDK saves keys and the complete request before POST, records the input SHA-256 and rejects changed files, parameters or sites on recovery. Re-run with the original state to recover the same job; use a new state file for a new job. The server quotes internally and enforces maxCostCredits, so the high-level workflow needs no separate quote call.

Downloads never overwrite files; change GLACIER_OUTPUT when necessary. State contains no keys used for API authentication or signed URLs. Keep it on durable storage and let one worker own each logical job. Distributed applications without shared durable files can store the low-level request/key records in their own database instead.

"""One-call processing. Reuse the state file after a timeout or process restart."""
import os
from glacierai import Client
client = Client(os.environ["GLACIER_API_KEY"], os.environ.get("GLACIER_BASE_URL", "https://www.chaozapi.com"))
result = client.process_file(
os.environ.get("GLACIER_INPUT", "input.png"),
"image-sr", {"type": "scale", "value": 2},
state_file=os.environ.get("GLACIER_STATE_FILE", "glacier-request.json"),
max_cost_credits=int(os.environ.get("GLACIER_MAX_COST_CREDITS", "100")),
download_to=os.environ.get("GLACIER_OUTPUT", "output.png"),
)
print("Task ID:", result["taskId"])
print("Downloaded" if result["output"] is not None else "Report: " + str(result["report"]))
Capability Python TypeScript Go
Upload and submit submit_file submitFile SubmitFile
Complete workflow process_file processFile ProcessFile
Multiple files process_files processFiles ProcessFiles
Lazy pagination iter_tasks / iter_assets iterateTasks / iterateAssets EachTask / EachAsset
Refresh and download download_result downloadResult DownloadResult
Progress callback on_progress onProgress FileOptions.OnProgress

Batches default to concurrency1, configurable from1–16. Each job needs distinct state/output paths. Results retain input order; each contains a result or error, and one failure does not stop the others. Concurrency remains subject to account benefits and the shared rate budget.

outcomes = client.process_files([
{"path": "a.png", "tool_id": "image-sr", "params": {"type": "scale", "value": 2},
"state_file": "jobs/a.json", "max_cost_credits": 100, "download_to": "a-out.png"},
{"path": "b.png", "tool_id": "image-sr", "params": {"type": "scale", "value": 2},
"state_file": "jobs/b.json", "max_cost_credits": 100, "download_to": "b-out.png"},
], concurrency=2)
for item in outcomes:
print(item["index"], item["error"] or item["result"]["taskId"])
for task in client.iter_tasks({"status": "succeeded", "limit": 50}, max_items=100):
print(task["id"])

TypeScript accepts {path, task, options} jobs with processFiles(jobs, {concurrency: 2}); inspect each result/error. Use for await with iterateTasks(query, {maxItems: 100}). Go accepts FileJob{Path, Input, Options} and returns ordered []BatchOutcome with Result/Err; EachTask(ctx, query, callback) stops when the callback returns false. Package READMEs include examples.

Progress events contain phase and the relevant task/upload/assetId/taskId (capitalized Go fields). Phases are uploading, preparing, submitted, task, downloading and completed. task.progress is server-reported0–1 progress and can regress. Upload events signal the stage, not byte percentages. Keep callbacks short; Python/Go batch callbacks can run concurrently.

For a completed task, call download_result(task_id, "result.png"), downloadResult(taskId, path) or DownloadResult(ctx, id, path, FileOptions{}). The helper refreshes signed URLs on retries. Report-only results return structured data without creating an empty file.

Operation Python TypeScript Go
Tools / wallet / benefits list_tools / get_wallet / get_subscription_benefits listTools / getWallet / getSubscriptionBenefits ListTools / GetWallet / GetSubscriptionBenefits
Upload and prepare upload_file uploadFile UploadFile
Quote / submit quote_task / create_task quoteTask / createTask QuoteTask / CreateTask
Status / wait / result get_task / wait_for_task / get_task_result getTask / waitForTask / getTaskResult GetTask / WaitForTask / GetTaskResult
Cancel cancel_task cancelTask CancelTask
Page tasks / assets page_tasks / list_assets pageTasks / listAssets PageTasks / ListAssets
Download download download Download

All methods are in operations.py, operations.gen.ts and operations.gen.go, including upload sessions, deletion, version downloads and legacy watermark endpoints. Python/TS use objects for queries; Go uses url.Values. Pass nextCursor back until null, retaining filters. The older listTasks array is not full history.

Optional bodies: Python complete_upload(asset_id), TS completeUpload(assetId, undefined), Go CompleteUpload(ctx, assetID, nil). HTTP 204 becomes Python None, TS undefined or a Go empty struct.

Low-level methods send one request; callers manage keys for createTask. High-level submitFile/processFile/downloadResult save and reuse the original request and attempt temporary network failures and HTTP429/500/502/503/504 up to3 times, including the initial attempt. They honor Retry-After and exponential backoff, and never rerun failed tasks. Configure Python max_attempts/retry_delay, TS maxAttempts/retryDelayMs or Go FileOptions.MaxAttempts/RetryDelay; attempts range1–10, with a default base delay of1 second.

Error Action
APIError Inspect HTTP status, code, request ID and Retry-After; see error handling
TaskError The task failed or was canceled; inspect the attached task and stop fetching its result
WaitTimeout Local waiting ended; remote work continues, so retain the ID and resume polling
File transfer failure Keep assetId; refresh the existing upload/result ticket instead of creating a processing job

Python uses request_id/retry_after (seconds), TypeScript requestId/retryAfterMs (milliseconds), Go RequestID/RetryAfter (duration). Non-JSON proxy failures still retain HTTP status.

Default JSON timeout is60 seconds, file timeout30 minutes. Each wait polls every15 seconds for up to30 minutes. High-level Python uses wait_timeout/poll_interval; individual wait methods use timeout/poll_interval. TypeScript uses timeoutMs/pollIntervalMs, Go uses context deadlines and FileOptions.PollInterval. Wait helpers handle temporary read failures within the deadline. All active tasks share the key’s120-request rolling-minute budget.

Python cancel_event accepts threading.Event; setting it stops waiting, backoff and subsequent steps with WaitCanceled. In-flight synchronous requests still wait for response or timeout. TypeScript uses AbortSignal, Go context. Local cancellation never stops remote work; call the cancel endpoint explicitly and poll the terminal state.

The high-level upload helper automates whole-file PUT. Chunked and form-upload endpoints are wrapped, but concurrency, resume state and multipart bodies require caller orchestration; see uploads. put_upload/putUpload/PutUpload also sends a single PUT part and returns headers including ETag. Downloads stream to disk.

submitFile/processFile save and verify SHA-256; lower-level uploadFile and server idempotency compare metadata only. Keep input bytes unchanged during each call. Use low-level methods for database checkpoints or chunk orchestration.

High-level file methods accept tiers in tool params, maxCostCredits, fitToLimits, nextSteps, rush and useImagePack (extra Python fields go in task_options). For existing assets/versions or explicit quoteId use createTask. Quotes are estimates; report tasks may have null output.

Give the AI integration skill to an assistant to adapt your project; the source ZIPs include it.