Skip to main content

Phala Cloud Python SDK

Python SDK for Phala Cloud API, aligned with @phala/cloud action surface.

Goals

  • Pythonic API (snake_case, sync-first REPL experience)
  • Sync + Async parity
  • Pydantic request/response validation
  • Safe calls (safe_*) without exceptions

Requirements

  • Python >= 3.10
  • uv (for development)

Installation

pip install phala-cloud

Quickstart

Sync

from phala_cloud import create_client

client = create_client(api_key="<api-key>")
me = client.get_current_user()
print(me.model_dump())

Async

import asyncio
from phala_cloud import create_async_client


async def main() -> None:
    client = create_async_client(api_key="<api-key>")
    me = await client.get_current_user()
    print(me.model_dump())
    await client.aclose()


asyncio.run(main())

Configuration

Environment variables

  • PHALA_CLOUD_API_KEY
  • PHALA_OIDC_TOKEN
  • PHALA_CLOUD_WORKSPACE
  • PHALA_CLOUD_API_PREFIX (e.g. https://cloud-api.phala.com/api/v1)

Client options

  • api_key
  • bearer_token
  • workspace
  • base_url
  • version (2025-10-28 / 2026-01-21 / 2026-05-22 / 2026-06-23 / 2026-11-11, default 2026-11-11)
  • timeout
  • headers
  • use_cookie_auth

The SDK sets User-Agent to phala-cloud-sdk-python/<version> python/<x.y.z> httpx/<ver>. A User-Agent in headers replaces that default.

A non-empty client option takes precedence over its corresponding environment variable. After resolving both credentials, the SDK uses the API key if both are set. This includes an API key from PHALA_CLOUD_API_KEY when bearer_token is set explicitly. Cookie auth suppresses both generated authentication headers; it does not remove headers supplied by the caller. The SDK removes surrounding whitespace from the workspace value.

When you supply http_client, its base URL and timeout control requests; configure them on that client. Watch streams use their own read timeout, as described below. The SDK does not close the supplied client.

Does the SDK follow redirects?

No. Redirects can send your API key to another server, so the SDK stops at the first response. This applies to API calls and SSE streams. Set base_url to the final API URL instead of relying on a redirect.

Direct calls raise ApiError for 3xx responses. request_full returns the original status, headers, and body with ok=False, so you can inspect the response without following it.

The SDK ignores follow_redirects=True on SDK requests, including requests made with a supplied http_client. It does not change that client's settings or close the supplied client. Custom transports must not follow redirects internally.

API Style

  • Direct methods: raise on HTTP/validation errors
  • Safe methods (safe_*): return SafeResult
  • Function-style wrappers available in phala_cloud.actions

Example:

result = client.safe_get_kms_list()
if result.ok:
    print(result.data.items)
else:
    print(result.error)

How do I commit a prepared CVM update?

Pass the CVM ID and the one-time token to commit_cvm_update. compose_hash and transaction_hash are optional. If you omit the compose hash, the server reads it from the token. If you omit the transaction hash, the server checks whether the compose hash is already allowed on-chain. The server still validates the token and the update.

How do I wait for an on-chain update to take effect?

On an Ethereum or Base KMS, Phala Cloud accepts an update or a create, waits for chain finality, and only then applies it. The response carries correlation_id (and finality_wait with progress). Pass the CVM ID and that correlation_id to wait_for_cvm_finality. It polls until the operation completes and returns it.

commit_cvm_compose_file_update returns that correlation_id too, and accepts transaction_hash (the registration transaction hash, or "already-registered").

operation = client.wait_for_cvm_finality("my-cvm", correlation_id, timeout=1800, poll_interval=15)

timeout and poll_interval are in seconds; the defaults are 1800 and 15. A failed or cancelled operation raises CvmFinalityOperationError with status, failure_reason and error_message. A timeout raises CvmFinalityTimeoutError. The operation keeps running after a timeout. Both inherit from CvmFinalityWaitError. Network errors, 408, 425, 429 and 5xx responses are retried until the timeout. Other HTTP errors are raised at once. The async client has the same method; use await. To list operations yourself, call get_cvm_operations.

By default a new update silently replaces an update that is still waiting for finality. To be told first, set confirm_finality_replacement="none" on the update. If another update is waiting, the call raises CvmFinalityReplacementRequiredError (HTTP 412, ERR-03-067) with that update's correlation_id and stage. Then either wait for the pending update, or send its correlation_id as confirm_finality_replacement to replace it. Leave the field out to keep the default. Every method that updates a CVM accepts it, such as patch_cvm, update_docker_compose, update_pre_launch_script, upgrade_pre_launch_script and commit_cvm_update. The safe_* methods return the same exception in result.error.

from phala_cloud import CvmFinalityReplacementRequiredError

update = {"id": "my-cvm", "public_logs": True}
try:
    client.patch_cvm({**update, "confirm_finality_replacement": "none"})
except CvmFinalityReplacementRequiredError as exc:
    # Wait for the pending update ...
    client.wait_for_cvm_finality("my-cvm", exc.correlation_id)
    client.patch_cvm(update)
    # ... or replace it instead:
    # client.patch_cvm({**update, "confirm_finality_replacement": exc.correlation_id})

How do I change a CVM's app compose settings?

Send compose to patch_cvm as a JSON Merge Patch: a set field sets the value, a field set to None removes the key, and a field you leave out is unchanged. requirements merges per key and cannot change gpu_policy. Turning on requirements.ephemeral_data_disk erases data on every boot, so it also needs confirm_data_wipe=True. To turn init scripts on or off, see How do I choose init scripts for a CVM?.

client.patch_cvm({
    "id": "my-cvm",
    "compose": {"secure_time": True, "swap_size": None, "requirements": {"health_check": True}},
})

How do I choose init scripts for a CVM?

Init scripts run on every boot, before your containers start. Phala Cloud provides them. You can turn each one on or off, but you cannot change a script or add your own. Phala Cloud also decides the order they run in.

To see the scripts for one CVM, call get_cvm_init_scripts. For each script it tells you whether the CVM runs it, whether you can turn it on, and if not, why. has_custom_scripts is true when Phala Cloud support has also set scripts on this CVM. Changing the selection removes those scripts, so check it first.

To turn scripts on or off, send the full list of names as init_scripts to patch_cvm. When you create a CVM, send init_scripts to provision_cvm. Some settings stop using or erase data on disk: docker_cleanup, runtime_tmpfs and requirements.ephemeral_data_disk. Turning one of them on needs confirm_data_wipe=True, also when you turn it on with provision_cvm_compose_file_update.

client.patch_cvm({"id": "my-cvm", "init_scripts": ["runtime_tmpfs"], "confirm_data_wipe": True})

How do I check the exact script that runs?

Call get_managed_init_scripts. It needs no API key. It returns each script's full text and its SHA-256 hash. The scripts a CVM runs are part of its app compose, so the compose hash covers their exact bytes.

How do I gate a CVM with a launch token?

On create, send launch_token (at least 32 bytes) or generate_launch_token=True; the commit response carries a newly issued token once. To rotate, call set_app_launch_token (omit launch_token to have Phala Cloud generate one), then set each CVM's compose.requirements.launch_token_hash to the returned hash before it restarts. clear_app_launch_token removes the token after every CVM has dropped the hash. get_cvm_user_config returns the token to members who can read the CVM. Phala Cloud and the node operator can read the token, so it protects only against parties who know the public compose.

How do I compute a compose hash locally?

get_compose_hash(compose, os_image_version="0.6.0") hashes the compose the way Phala Cloud does for that OS image: below 0.6.0 manifest_version is 2 and init_script is a single string, from 0.6.0 they are "3" and a list. Without os_image_version both fields are hashed as given.

How does watching a CVM retry?

watch_cvm_state reconnects after a server timeout event, an incomplete stream, or a transient network failure. Set max_retries to limit reconnects; the default is unlimited. Set retry_delay in seconds (default 5). The aliases maxRetries and retryDelay also work. The stream read timeout is the requested timeout plus interval plus 5 seconds.

Only a complete event finishes the watch. The server may send an error event and then continue streaming. If retries are exhausted, the SDK raises RequestError with the last available server and network error details. HTTP errors use the same SDK exception types as other requests and are not retried. In async code, cancelling the task closes the stream and propagates cancellation. Previous versions raised TimeoutError on retry exhaustion; catch RequestError instead.

Are blockchain actions supported?

The Python SDK no longer exposes add_compose_hash, deploy_app_auth, or their safe wrappers. These wrappers did not implement the blockchain operations. Use the JavaScript SDK for these operations instead.

How do I encrypt environment variables?

Pass the output of parse_env_vars or dstack_sdk.EnvVar objects to encrypt_env_vars(envs, public_key_hex). It returns the encrypted string synchronously. In async code, use await async_encrypt_env_vars(envs, public_key_hex) instead.

This changes the previous encrypt_env_vars behavior: code that awaited it must switch to async_encrypt_env_vars.

How do I upgrade to these SDK changes?

  • Replace await encrypt_env_vars(...) with await async_encrypt_env_vars(...). The encrypt_env_vars function now returns a string synchronously.
  • Use the JavaScript SDK for add_compose_hash and deploy_app_auth. Their Python wrappers have been removed.
  • Catch RequestError instead of TimeoutError when watch retries are exhausted. Watch HTTP errors now use SDK exceptions instead of httpx.HTTPStatusError.
  • Do not rely on a raw state event followed by a closed stream as a successful watch result. Only a complete event finishes the watch. Timeouts, incomplete streams, and transient network failures use the reconnect budget.
  • patch_cvm validates gpus as {"gpus": [{"slot": ..., "product_id": ...}], "attach_mode": ...}, the shape the API accepts. Other shapes now fail validation instead of being sent and ignored. patch_cvm also accepts instance_type, and prepare_only=True sends X-Prepare-Only: true; the 465 result then includes commit_token, commit_url, api_commit_url and onchain_status.
  • update_cvm_visibility now calls PATCH /cvms/{id} instead of the deprecated PATCH /cvms/{id}/visibility. It returns message, correlation_id and status instead of the CVM record; call get_cvm_info if you need the record.
  • update_cvm_resources no longer sends allow_restart, which the API ignores. The field is deprecated.
  • get_compose_hash now drops null storage_discard, event_log_version, snapshotter and verity_volumes and always emits tproxy_enabled (defaulting to gateway_enabled), as the API does. A compose without tproxy_enabled hashes differently than before.
  • create_app_instance now returns ReplicaVM (top-level teepod_id, vcpu, memory, disk_size, finality_wait) instead of CvmInfo.
  • get_app_list now returns dstack_apps and total_pages. get_app_info is the full app record (app_id, created_at, kms_type, ...), not only id and name.

Development

cd python

# Install dependencies
uv sync

# Run tests
make test

# Lint & format
make check

E2E Test

E2E tests cover sync + async, direct + safe styles, and full interface paths.

Required:

  • PHALA_CLOUD_E2E_API_KEY — your Phala Cloud API key

Optional:

  • PHALA_CLOUD_E2E_BASE_URL — defaults to https://cloud-api.phala.com/api/v1

Run

cd python
PHALA_CLOUD_E2E_API_KEY="<api-key>" make e2e

Or put them in python/.env.test:

PHALA_CLOUD_E2E_API_KEY=<api-key>
# PHALA_CLOUD_E2E_BASE_URL=https://cloud-api.phala.com/api/v1

Then simply:

cd python
make e2e

License

Apache-2.0

Metadata

Release files for phala-cloud 0.4.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for phala-cloud 0.4.6
File Size Uploaded Provenance Actions
phala_cloud-0.4.6.tar.gz 199.4 kB With provenance Details for phala_cloud-0.4.6.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for phala-cloud 0.4.6
File Interpreter ABI Platform Actions
phala_cloud-0.4.6-py3-none-any.whl Python 3 none any Details for phala_cloud-0.4.6-py3-none-any.whl

Total release size: 273.9 kB

Release files / phala_cloud-0.4.6.tar.gz

Download URL phala_cloud-0.4.6.tar.gz
Size 199.4 kB
Tags Source
SHA-256 checksum
How to use checksums
4e89511f454f61ad912a334cce1c6e64538236efcbbc1a38bd06901d246e590d
BLAKE2b-256 checksum
How to use checksums
9c131259aa461fe214646b66a26a830d24797de407b9d84b6465765e17202bc8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / phala_cloud-0.4.6-py3-none-any.whl

Download URL phala_cloud-0.4.6-py3-none-any.whl
Size 74.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6f83cc9a2593ed6bce80ebbfa0618130a67e6debfdb2221126682e8e1d432241
BLAKE2b-256 checksum
How to use checksums
d41b339de1a637b00633ff7345efe7bfd28fe21b421e355b54cb4ae3da12989e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for phala-cloud 0.4.6

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for phala_cloud-0.4.6.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page