Chalk Compute Reference

This reference documents the chalkcompute Python SDK for building and deploying containers, sandboxes, volumes, remote functions, and scaling groups on Chalk's managed compute infrastructure. Use it to spin up isolated environments, stash files in persistent volumes, and deploy versioned Python functions and classes that scale on demand.

New to Chalk Compute? Start with the Compute overview for a conceptual tour of sandboxes, containers, scaling groups, and the deployment model. Then dive into Images, Functions, Volumes, and Sandbox for task-oriented guides. The sections below document every public class and function in the SDK.

Sandbox quickstart

A full end-to-end sandbox: build an image with your code baked in, create the sandbox, exec a command inside it, read the output, and tear it down.

from chalkcompute import Image, Sandbox

img = (
    Image.debian_slim()
    .pip_install(["pandas", "requests"])
    .add_local_file(
        "./analyze.py",
        "/app/analyze.py",
    )
    .workdir("/app")
)

sandbox = Sandbox(
    image=img,
    name="analysis-scratchpad",
    cpu="2",
    memory="4Gi",
).run()

result = sandbox.exec(
    "python",
    "/app/analyze.py",
    "--input", "/data/in.csv",
)
print(result.stdout_text)

sandbox.terminate()

Declarative, composable container image builder using a fluent API.

Each builder method returns a new Image instance so intermediate images can be shared and extended. Use class methods like Image.debian_slim() or Image.base() to start, then chain pip_install, run_commands, add_local_file, etc.

Image

Class

Declarative, composable container image builder.

Uses a fluent (method-chaining) API. Each method returns a new Image instance so that intermediate images can be shared and extended.

Call build to capture a reusable image with pinned file contents. Built images work with every image= parameter and can be transferred between processes using to_json and from_json.

Examples

from chalkcompute import Image
img = (
    Image.debian_slim()
    .pip_install(["requests", "pandas"])
    .workdir("/home/user/app")
)
Attributes

Return pinned volumes retained by this image.

Returns

tuple of VolumeMount Pinned volumes retained independently of worker cleanup.

Functions

Build a reusable image and capture immutable versions of its files.Notes

With no additional volumes, building an already built image returns an equivalent copy without network calls. Authentication, polling, and timeout settings only apply when a build or volume lookup is needed.

Backing volumes persist independently of workers. Keep them while built images remain in use. Pins do not enforce runtime read-only access.

Parameters

Additional volume references, accepting the same forms as Sandbox.

name: = None

Optional retained source volume name for local volume files. Defaults to a stable name derived from the build recipe and file layout, excluding local source paths and volume file contents. Pass a name to share source volumes across recipes or make cleanup discoverable. Requires local volume files to upload.

Optional client for authentication. Defaults to the environment.

Polling interval in seconds for each build and source upload.

timeout: = 600.0

Timeout in seconds for each build and source upload.

Returns
type:

A new built image with pinned volumes, leaving this recipe unchanged.

Raises
error:

If a name is supplied without local volume files, or mounts conflict.

Serialize a built image without local paths or credentials.

Returns
type:

JSON containing the image URI and pinned volumes.

Raises
error:

If this image has not been built.

Load a built image without contacting any service.

Parameters

JSON produced by to_json.

Returns
type:

The built image represented by the JSON value.

Raises
error:

If the JSON value is invalid or does not describe a built image.

Create an image from an arbitrary base image reference.

Parameters

Full image reference (e.g. "python:3.14-slim-trixie", "ghcr.io/org/image:tag").

Returns
type:

A new Image based on the given reference.

from chalkcompute import Image
img = Image.base("python:3.14-slim-trixie")
img = Image.base("ghcr.io/my-org/my-image:latest")

Create an image based on python:<version>-slim-trixie.

Parameters

Python version tag.

Returns
type:

A new Image based on the selected Python slim image.

from chalkcompute import Image
img = Image.debian_slim()
img = Image.debian_slim("3.14.5")

Default sandbox image: Python, Git, TLS certificates, and SSH.

Uses Debian slim with /workspace as its working directory. Builds lazily through the normal image builder, and can be extended with the same methods as any other Image. A fresh spec is returned each time.

Create an image from an existing Dockerfile.

The Dockerfile contents are transmitted as a dockerfile_commands step so that additional builder methods can be chained on top.

Parameters

Path to the Dockerfile.

Returns
type:

A new Image whose build steps mirror the Dockerfile.

from chalkcompute import Image
img = Image.from_dockerfile("./Dockerfile")
img = (
    Image.from_dockerfile("./Dockerfile")
    .pip_install(["rich"])
)

Run shell commands during the image build.

Each string is executed as a separate RUN instruction.

Returns
type:

A new Image with the run steps appended.

from chalkcompute import Image
img = (
    Image.debian_slim()
    .run_commands(
        "apt-get update",
        "apt-get install -y curl git",
    )
)

Install Debian/Ubuntu system packages during the image build.

Like pip_install, accepts a sequence and returns a new image. Requires apt-get and a root build user. Updates package indexes, installs noninteractively without recommended packages, and removes indexes in one build layer. Package versions can be pinned with name=version. Other distributions can use run_commands with their package manager.

image = Image.sandbox().apt_install(["tmux"])
sandbox = Sandbox(image=image).run()
sandbox.exec("tmux", "new-session", "-d", "-s", "work")

Install Python packages via uv pip install.

Uses the uv resolver instead of pip for significantly faster installs. Requires a base image that has uv available.

Parameters

List of pip requirement specifiers (e.g. ["requests", "pandas"]).

Returns
type:

A new Image with the uv pip install step appended.

from chalkcompute import Image
img = (
    Image.base("ghcr.io/astral-sh/uv:python3.14-trixie-slim")
    .uv_pip_install(["requests", "polars"])
)

Install packages from a requirements.txt file via uv pip install.

The file is read locally and its contents are inlined into the image spec so that the file does not need to be accessible at build time. Uses the uv resolver for significantly faster installs than pip_install_from_requirements. Requires a base image that has uv available.

Parameters

Path to requirements.txt.

Returns
type:

A new Image with the uv pip install step appended.

from chalkcompute import Image
img = (
    Image.base("ghcr.io/astral-sh/uv:python3.14-trixie-slim")
    .uv_pip_install_from_requirements("./requirements.txt")
)

Install Python packages via pip.

Parameters

List of pip requirement specifiers (e.g. ["requests", "pandas"]).

Returns
type:

A new Image with the pip install step appended.

from chalkcompute import Image
img = (
    Image.debian_slim()
    .pip_install(["requests", "pandas"])
)

Install packages from a requirements.txt file.

The file is read locally and its contents are inlined into the image spec so that the file does not need to be accessible at build time.

Parameters

Path to requirements.txt.

Returns
type:

A new Image with the pip install step appended.

from chalkcompute import Image
img = (
    Image.debian_slim()
    .pip_install_from_requirements("./requirements.txt")
)

Add a local file into the image.

Each call is additive — the file is appended to the set of files (or build steps) already registered on the image, not replacing them — so add_local_file can be chained many times to bring in several files.

Parameters

Local file path.

Absolute destination path in the image.

mode: = None

Optional POSIX file permission mode. Written in octal with a 0o prefix; if omitted, strategy="volume" preserves the source file's on-disk permissions and strategy="copy" uses the image's default permissions. Common values:

  • 0o755 (rwxr-xr-x) — executable scripts and binaries; owner can read/write/execute, everyone else read/execute.
  • 0o644 (rw-r--r--) — regular data files; owner can read/write, everyone else read-only.
  • 0o600 (rw-------) — private files (credentials, secrets, SSH keys); owner read/write, no access for others.
  • 0o700 (rwx------) — owner-only directories or private executables.
  • 0o400 (r--------) — immutable/read-only files the workload must not mutate.
strategy:
'copy' | 'volume'
= 'volume'

"copy" inlines the file contents into the image spec and rejects files larger than 32 KiB or additions that would make the image's total copied content exceed 32 KiB. "volume" (default) defers the file as a lazy reference to be mounted at sandbox start.

Returns
type:

A new Image with the file registered for inclusion.

Raises
error:

If strategy="copy" exceeds the per-file or total copied-content limit.

from chalkcompute import Image
img = (
    Image.debian_slim()
    .add_local_file(
        "./config.yaml",
        "/app/config.yaml",
    )
    .add_local_file(
        "./entrypoint.sh",
        "/app/entrypoint.sh",
        mode=0o755,
        strategy="copy",
    )
)

Add an entire local directory into the image.

Each call is additive — the directory's files are appended to the set already registered on the image, so add_local_dir can be chained with other add_local_dir / add_local_file calls to merge sources from multiple locations.

Automatically respects .gitignore and .chalkignore files found at any level within src (each scoped to its directory subtree, matching go-git's behavior). The .git/ directory is always excluded. Negation patterns (!) are supported.

Parameters

Local directory path.

Absolute destination directory in the image.

strategy:
'copy' | 'volume'
= 'volume'

"copy" inlines all file contents into the image spec and rejects files larger than 32 KiB or additions that would make the image's total copied content exceed 32 KiB. "volume" (default) defers each file as a lazy reference to be mounted at sandbox start.

Additional glob patterns to skip (matched against relative paths). These are applied on top of patterns loaded from ignore files, e.g. ["data/**", "*.csv"].

archive: = False

When True (volume strategy only), tar the directory into a single file for upload instead of individual files. The caller is responsible for extracting at the destination.

Returns
type:

A new Image with the directory registered for inclusion.

Raises
error:

If strategy="copy" exceeds the per-file or total copied-content limit.

from chalkcompute import Image
img = (
    Image.debian_slim()
    .add_local_dir(
        "./src",
        "/app/src",
        exclude=["*.pyc", "__pycache__"],
    )
)

Add local Python modules or packages to /app in the image. Wraps add_local_dir and add_local_file with sanity checking.

Raises ValueError if a name is dotted, cannot be found on the local Python path, or does not resolve to a pure-Python module or package.

from chalkcompute import Image
img = Image.debian_slim().add_local_python_source("helpers", "mypkg")

Add raw Dockerfile instructions.

These are injected verbatim into the generated Dockerfile. Each call is additive — instructions are appended to any previous build steps (including prior dockerfile_commands calls), not replacing them — so you can split a Dockerfile across multiple calls and interleave with other builder methods.

Parameters

List of Dockerfile instructions (e.g. ["RUN echo hello", "EXPOSE 8080"]).

Returns
type:

A new Image with the Dockerfile commands appended.

from chalkcompute import Image
img = (
    Image.debian_slim()
    .dockerfile_commands([
        "USER root",
        "EXPOSE 8080",
    ])
)

Set environment variables in the image.

Parameters

Mapping of variable names to literal strings. Pass Secret values in the runtime consumer's env instead (for example, Sandbox(env=...)).

Returns
type:

A new Image with the environment variables applied.

from chalkcompute import Image
img = (
    Image.debian_slim()
    .env({
        "LOG_LEVEL": "DEBUG",
        "PORT": "8080",
    })
)

Set the working directory in the image.

Parameters

Absolute path for the working directory.

Returns
type:

A new Image with the working directory set.

from chalkcompute import Image
img = (
    Image.debian_slim()
    .workdir("/home/user/app")
)

Set the container entrypoint.

The ENTRYPOINT is the executable that always runs when the container starts. Unlike cmd — which provides default arguments that callers can override at run time — the entrypoint is fixed: callers can't swap it out by passing a different command to Container.run or kubectl exec, only append to it.

Together, ENTRYPOINT and CMD form the full command that runs in the container:

  • With only an entrypoint: ENTRYPOINT runs with no args.
  • With only a CMD: the first element of CMD is treated as the executable and the rest as its arguments.
  • With both: the full command is ENTRYPOINT + CMD, where CMD supplies the default (overridable) arguments.

Each call replaces any previously set entrypoint.

Use exec-form (["python", "-m", "my_app"]) rather than shell-form ("python -m my_app") — exec-form skips the shell wrapper and makes signals (SIGTERM, SIGINT) reach your process directly, which matters for graceful shutdown.

Parameters

Entrypoint as exec-form list (e.g. ["/bin/bash"]).

Returns
type:

A new Image with the entrypoint set.

from chalkcompute import Image
img = (
    Image.debian_slim()
    .entrypoint(["python", "-m", "my_app"])
)

Set the container CMD.

The CMD is the default argument list passed to the container's entrypoint when the container starts. Unlike entrypoint — which sets the executable that always runs — CMD defines the default arguments that can be overridden at run time (for example, by a Container.run(command=[...]) call or a Kubernetes pod spec).

If no entrypoint is set, the first element of CMD is treated as the executable. If an entrypoint is set, CMD is appended to it.

Parameters

CMD as exec-form list (e.g. ["/bin/bash", "-l"]).

Returns
type:

A new Image with the CMD set.

Run python -m my_app by default, but allow the caller to override the module at run time:

from chalkcompute import Image
img = (
    Image.debian_slim()
    .entrypoint(["python"])
    .cmd(["-m", "my_app"])
)

Return the image URI when no custom build is needed.

A bare Image.base(...) or Image.debian_slim() is equivalent to its base image string. Once the image carries build steps, lazy files, or image config, callers must keep sending the full image spec.

Reconstruct an Image from an ImageSpec (inverse of to_proto; volume files excluded).

Reconstruct an Image from a serialized ImageSpec byte string.

High-level container abstraction backed by the Chalk ContainerService.

Orchestrates image building, local file upload via volumes, and container lifecycle in a single API. Use Container(image=...).run() to start, .exec() to run commands, and .stop() to clean up.

A managed container backed by the Chalk ContainerService.

Orchestrates image building, local file upload via volumes, and container lifecycle in a single high-level API.

Examples

Build an image, run a container, and exec a command inside it:

from chalkcompute import Container, Image
c = Container(
    image=(
        Image.debian_slim()
        .pip_install(["requests"])
        .add_local_file("./script.py", "/app/script.py")
    ),
    cpu="1",
    memory="2Gi",
    env={"LOG_LEVEL": "INFO"},
).run()
result = c.exec("python", "/app/script.py")
result.stdout_text
'hello\n'
c.stop()
Attributes

Opaque container identifier assigned by the service.

None until run (or from_id / from_name) has resolved the container against the service.

The most recently fetched ContainerInfo snapshot.

None until the container has been started or attached to. Populated by run, from_id, and from_name. Call refresh_info to fetch the latest state from the service.

The fully qualified registry URI of the image the container uses.

Set after run finishes the image build (or, if the container was constructed with a string image reference, equal to that reference). None before the container has been started.

Functions

Attach to an existing container by ID.

Parameters

Opaque container identifier assigned by the service.

Returns
type:

A Container handle bound to the existing container.

Raises

If the container cannot be found.

Attach to an existing container by name.

Parameters

DNS-safe container name.

Returns
type:

A Container handle bound to the existing container.

Raises

If the container cannot be found.

List all running containers in the current environment.

Returns

Info records for all active containers, ordered by creation time descending.

Raises

If the request fails.

Mount a named volume or volume handle into the container.

Must be called before run. Returns self for chaining.

Parameters

Name or handle of the Chalk volume to mount. Handles preserve their selected ref or pinned version.

Absolute path inside the container where the volume is mounted.

Returns
type:

self, to allow chaining.

from chalkcompute import Container, Image
c = (
    Container(image=Image.debian_slim())
    .mount_volume("my-data", "/data")
    .run()
)

Build the image, upload local files, and start the container.

Walks through three phases and blocks until the container is ready (or raises): (1) build the image via CustomImageService, (2) if the Image has add_local_file / add_local_dir entries registered with strategy="volume", upload them to a managed volume and attach it, (3) start the container and poll until it reaches the Running state.

Parameters

Seconds between status polls for both build and startup.

Maximum seconds to wait for the image build to complete.

Maximum seconds to wait for the container to reach Running.

Returns
type:

self, to allow chaining.

Raises

If the container fails to start or times out.

If the image build fails.

Build an image from scratch, start a container, inspect it, and tear it down:

from chalkcompute import Container, Image
img = (
    Image.debian_slim()
    .pip_install(["requests"])
    .add_local_file(
        "./app.py",
        "/app/app.py",
    )
    .workdir("/app")
)
c = Container(
    image=img,
    cpu="1",
    memory="2Gi",
    env={"LOG_LEVEL": "INFO"},
)
c.run()
c.info.status
'Running'
c.stop()

Execute a command in the running container.

The command runs as a one-shot process inside the already-started container (equivalent to docker exec). Output is captured in full and returned at once; use exec if you need a streaming interface.

Parameters

Optional execution timeout in seconds.

Returns

The stdout, stderr, and exit code of the executed command.

Raises

If the container is not running or the exec fails.

Build an image, start a container, run a few commands against it, and clean up:

from chalkcompute import Container, Image
c = Container(
    image=(
        Image.debian_slim()
        .pip_install(["requests"])
        .add_local_file(
            "./fetch.py",
            "/app/fetch.py",
        )
    ),
    cpu="1",
    memory="2Gi",
).run()
hello = c.exec(
    "python",
    "/app/fetch.py",
    "https://example.com",
)
hello.exit_code
0
hello.stdout_text.splitlines()[0]
'<!doctype html>'
err = c.exec("ls", "/does-not-exist")
err.exit_code
2
err.stderr_text
"ls: cannot access '/does-not-exist': No such file or directory\n"
c.stop()

Start a persistent command session in the running container.

The returned ContainerSession can stream output, accept stdin, detach, and later be reattached with attach_session.

Attach a new stream to an existing persistent session.

Fetch metadata for a persistent session owned by this container.

List persistent sessions owned by this container.

Stop the container and clean up temporary volumes.

Parameters

Optional grace period before forceful termination.

Fetch latest container status from the server.

Returns

The latest metadata for the container.

Raises

If no container ID is set (run() was never called).

Metadata about a running container.

Attributes

Opaque container identifier assigned by the service.

DNS-safe container name.

Lifecycle state reported by the service (e.g. "Running").

Underlying Kubernetes pod name.

Optional URL exposing the container's port, if one is published.

Result of a one-shot command executed inside a container.

Returned by exec. All three fields are populated once the command has finished — ExecResult does not stream.

Attributes

Raw bytes written to standard output by the command.

Raw bytes written to standard error by the command.

POSIX exit status of the command (0 on success, non-zero on error; signals are encoded as 128 + signum where applicable).

stdout decoded as UTF-8 (with errors="replace").

Convenience for the common case where the command emits text. Invalid UTF-8 bytes are replaced with U+FFFD rather than raising.

stderr decoded as UTF-8 (with errors="replace").

Same UTF-8-with-replacement semantics as stdout_text.

Base exception for Container errors.

Raised when the custom image build fails.

Low-level sandbox management backed by the Chalk SandboxService (gRPC).

Provides bidirectional streaming exec, interactive stdin/signal control, and fine-grained process lifecycle management.

Client for the Sandbox service.

Functions

Initialize the RPC client.

Parameters
target: = 'localhost:50051'

RPC server address (e.g. "localhost:50051" or "https://sandbox.example.com").

Backward-compatible TLS signal. The object is not inspected; prefer use_tls for new code.

use_tls: = None

Whether to use HTTPS for the ConnectRPC transport. When omitted, this remains compatible with the old behavior: passing any credentials object enables TLS.

metadata:
_GrpcMetadata | None
= None

Optional default metadata to send with every RPC call.

Create a SandboxClient from ambient Chalk credentials.

Close the underlying HTTP clients.

Construct and run a sandbox in one call.

If image is an Image spec, this method builds it first and sends the resulting image URI to the sandbox service. If wait is True (the default), this method polls GetSandbox until the sandbox reaches "ready" (or "error").

Parameters
image: = None

Container image to use — either a string reference (e.g. "ubuntu:latest") or a declarative Image builder. If omitted, uses sandbox.

name: = None

Optional name for the sandbox.

cpu: = None

Optional CPU limit (e.g. "1", "500m").

memory: = None

Optional memory limit (e.g. "512Mi", "1Gi").

gpu: = None
env: = None

Environment variables as strings or single-value Secret references. The mapping key sets the injected name.

secrets:
_SecretList | None
= None
volumes:
_VolumeList | None
= None

Optional Volume handles, VolumeMount specifications, or (name_or_volume, mount_path) pairs to mount into the sandbox. Volume handles preserve their selected ref or pinned version.

port: = None
entrypoint:
_StrList | None
= None

Optional command to run as the sandbox container's main process.

lifetime: = None

Optional network egress policy. Reuses the same NetworkPolicy type accepted by containers.

tags: = None

Optional restart behavior. Use RestartPolicy.NEVER or RestartPolicy.ALWAYS.

Whether to give the sandbox a platform-managed Chalk identity. The identity is exposed inside the sandbox through the standard CHALK_WEB_IDENTITY_TOKEN_FILE environment variable.

Optional SSH aliases mapped to SshDest instances.

wait: = True

If True, poll until the sandbox is ready (default True).

Seconds between GetSandbox polls (default 0.5).

timeout: = 600.0

Maximum seconds to wait for the sandbox to become ready (default 600).

Returns
type:

A sandbox handle.

Create a configured sandbox using this client.

Parameters

A configured sandbox that has not been run.

wait: = True

If True, poll until the sandbox is ready (default True).

Seconds between readiness polls.

timeout: = 600.0

Maximum seconds to wait for the sandbox to become ready.

Returns
type:

The created sandbox.

Get a sandbox handle by ID.

Does not validate the sandbox exists until you call a method on it.

Parameters

Sandbox identifier.

Returns
type:

A sandbox handle.

List all sandboxes.

Returns
type:
_SandboxInfoList

One entry per sandbox.

Sandbox

Class

A managed sandbox backed by the Chalk SandboxService.

create constructs and immediately runs a sandbox. To configure a Sandbox before running it, construct one and pass it to run. Use exec to run commands and terminate to shut the sandbox down when you're done.

Examples

from chalkcompute import Image, SandboxClient
with SandboxClient.from_env() as client:
    sandbox = client.create(
        Image.debian_slim().pip_install(["numpy"]),
    )
    result = sandbox.exec(
        "python",
        "-c",
        "import numpy; print(numpy.__version__)",
    )
    sandbox.terminate()
result.stdout_text.strip()
'2.5.1'
Attributes

Opaque sandbox identifier assigned by the service.

None until run has created the sandbox.

The most recently fetched SandboxInfo snapshot.

None until the sandbox has been started or attached to.

The fully qualified registry URI of the image the sandbox uses.

Set after run finishes the image build (or, if the sandbox was constructed with a string image reference, equal to that reference). None before the sandbox has been started.

Git operations inside this sandbox (requires Git in custom images).

Functions

Transport the existing sandbox ID, never its credentials or spec.

Restore a handle without I/O; operations use the receiver's identity.

Configure a sandbox to be created by run.sandbox_id Existing sandbox ID. With no client, authentication is resolved lazily from the receiver's environment on the first operation. This form never creates a sandbox and cannot be mixed with image configuration.

Notes

Calling run without a client creates one from the environment. Prefer using an explicit SandboxClient. Its create method is a shortcut for constructing and immediately running a sandbox. For other setup, construct a Sandbox and pass it to run.

Parameters
image: = None

Container image to use, either a string reference such as "ubuntu:latest" or a declarative Image. If omitted, uses sandbox (Python, Git, SSH, and /workspace).

name: = None

Optional DNS-safe sandbox name.

cpu: = None

Optional CPU limit, for example "2" or "500m".

memory: = None

Optional memory limit, for example "4Gi" or "512Mi".

gpu: = None

Optional GPU request, for example "nvidia-l4".

env: = None

Environment variables as strings or single-value Secret references. The mapping key sets the injected name, overriding aliases and prefixes.

Optional Secret references to inject.

volumes:
_VolumeList | None
= None

Optional Volume handles, VolumeMount specifications, or (name_or_volume, mount_path) pairs to mount into the sandbox. Volume handles preserve their selected ref or pinned version. Each volume must already exist; run fails if one is missing.

port: = None

Optional published port.

Optional command to run as the sandbox container's main process.

lifetime: = None

Optional max lifetime as a protobuf duration string (for example "30s" or "300s").

Optional network egress policy. Reuses the same NetworkPolicy type accepted by Container.

Optional ComputeClass (K8S or HOST).

tags: = None

Optional labels attached to the sandbox spec.

Optional restart behavior. Use NEVER or ALWAYS.

Whether to give the sandbox a platform-managed Chalk identity. The identity is exposed inside the sandbox through the standard CHALK_WEB_IDENTITY_TOKEN_FILE environment variable.

Optional SSH aliases mapped to SshDest instances. Managed SSH sandboxes run on host compute.

client: = None
sandbox = Sandbox(image="ubuntu:latest")
with SandboxClient.from_env() as client:
    client.run(sandbox)

Attach to an existing sandbox by ID.

Attach to an existing sandbox by name.

List all sandboxes in the current environment.

Force-refresh sandbox info from the server.

Mount a named volume or volume handle into the sandbox.

Must be called before the sandbox is run. Returns self for chaining.

from chalkcompute import Sandbox, SandboxClient
sandbox = Sandbox(image="ubuntu:latest")
sandbox.mount_volume("my-data", "/data")
with SandboxClient.from_env() as client:
    client.run(sandbox)

Expose credentials to requests bound for specific hosts.

String credentials name existing Chalk secrets. Use from_local_env to read a credential from the local environment when the sandbox starts.

The sandbox receives a placeholder in each credential's environment variable. Its network policy replaces that placeholder when it appears in headers on requests to the supplied hosts.

Must be called before the sandbox is run. Returns self for chaining.

Parameters

A host pattern or sequence of host patterns allowed to use the credentials.

Existing Chalk secret names or explicit Secret references.

sandbox = (
    Sandbox(image="ubuntu:latest")
    .add_credentials("api.openai.com", "OPENAI_API_KEY")
    .add_credentials(
        ["api.slack.com", "*.slack.com"],
        Secret.from_local_env("SLACK_BOT_TOKEN"),
    )
)
with SandboxClient.from_env() as client:
    client.run(sandbox)

Create the sandbox and optionally wait until it is ready.

Parameters
wait: = True

If True, poll until the sandbox is ready (default True).

Seconds between readiness polls.

timeout: = 600.0

Maximum seconds to wait for the sandbox to become ready.

Returns
type:

self, to allow chaining.

Execute a command and wait for it to complete.

Parameters

Command binary or script to execute.

args: = ()

Optional timeout in seconds.

workdir: = None

Optional working directory inside the sandbox.

env: = None

Optional environment variables to set for the command.

Reattach and replay buffered output after transient transport disconnects. Disable to handle disconnects yourself.

Returns

Result with stdout/stderr and exit code.

Execute a command and stream events as they arrive.

Parameters

Command binary or script to execute.

args: = ()

Optional timeout in seconds.

workdir: = None

Optional working directory inside the sandbox.

env: = None

Optional environment variables to set for the command.

Start a command and return an ExecProcess handle for interactive use.

The caller can write to stdin, send signals, and iterate output.

Parameters

Command binary or script to execute.

args: = ()

Optional timeout in seconds.

workdir: = None

Optional working directory inside the sandbox.

env: = None

Optional environment variables to set for the command.

Returns

Handle for interacting with the running process.

Run Python source in the sandbox with structured output capture.

The server wraps source in a capture harness that injects a save_artifact(obj, *, name=None, kind=None, content_type=None) helper into the namespace and, after the source finishes, inspects the namespace for plotly/altair figures bound to variables. Everything saved or captured is persisted to the Chalk artifact store server-side — the sandbox itself never receives credentials — and returned as Artifact handles.

Parameters

Python source to execute. Bare final expressions do not print; charts are captured regardless of printing.

Optional timeout in seconds for the python process.

workdir: = None

Optional working directory inside the sandbox.

env: = None

Optional environment variables for the process.

Inspect the namespace for plotly/altair figures after execution (default True).

Byte budget across all artifacts from this execution; artifacts past it are reported in skipped_artifacts.

Returns

Buffered stdout/stderr, exit status, and persisted artifacts.

Terminate this sandbox.

Parameters

Optional grace period to allow running processes to shut down.

Information about a sandbox.

Attributes

Sandbox identifier.

Current lifecycle status of the sandbox.

Timestamp when the sandbox was created.

Optional human-readable name for the sandbox.

Optional identifier of the image build associated with this sandbox.

Backend-provided explanation for the current lifecycle status.

Additional diagnostic output for the current lifecycle status.

A single event from a streaming exec call.

Attributes

V2 session identifier, set when the process session starts.

Stdout text chunk, if this event carries stdout output.

Stderr text chunk, if this event carries stderr output.

Exit code of the process, set on the process-exited event.

Signal number that terminated the process, if any.

Error code string, set on error events.

Error message string, set on error events.

Handle to a running exec stream, allowing stdin writes and signal sends.

Attributes

V2 session identifier once the process session starts.

Functions

Send data to the process's stdin.

Parameters

Bytes or string to write to stdin. Strings are UTF-8 encoded.

Signal EOF on stdin.

Send a signal to the process.

Parameters
sig: = signal.SIGTERM

Signal number to send. Defaults to SIGTERM.

Iterate over output events from the process.

Consume all output and return the final result.

If the response stream is interrupted after the session starts, reconnect and replay buffered events by default. Set auto_reattach=False to handle transport disconnects yourself.

Returns

Aggregated stdout, stderr, exit code, and signal information.

SandboxError

Exception

Base exception for sandbox errors.

Raised when a sandbox is not found.

Raised when a sandbox has terminated.

Raised when a custom sandbox image build fails.

Raised when command execution fails.

Persistent named volumes backed by object storage.

VolumeClient manages volume lifecycle; Volume provides file operations (read, write, list, delete, batch upload).

Client for the Chalk Volume service.

Functions

Initialize the typed volume control plane and native data plane.

Parameters
endpoint: = 'http://localhost:50051'

Volume service endpoint. Values without a scheme are converted to http:// or https:// depending on credentials.

token: = ''

Optional bearer token used for service authentication.

env_id: = None

Chalk environment id to send with requests.

Optional commit author URN. If omitted, the native client derives one from the request credentials.

extra_headers:
builtins.list[tuple[str, str]] | None
= None

Additional request headers to send with every call.

chalk_server: = 'go-api'

Target Chalk server name.

Optional TLS/SSL credentials marker. If set, schemeless endpoints use https://.

Optional default metadata. authorization, x-chalk-env-id, and x-chalk-server are translated into native client settings.

Accepted for compatibility with the gRPC-backed constructor and ignored by the native client.

Create a volume client using environment authentication.

Parameters

Chalk client supplying authentication. Defaults to environment auth.

Returns

Client that owns its connection and closes it on context exit or an explicit close call.

Create a client from an authenticated ConnectClient.

Parameters

An authenticated ConnectClient. Auth is ensured automatically if not already done.

Returns

A new client with endpoint, token, and environment settings derived from the ConnectClient.

Close owned RPC resources and reject subsequent operations.

Create a new named volume.

Parameters

Name for the new volume.

Optional volume kind, e.g. "source_code" for volumes that hold deployed function source files.

Returns
type:

A handle to the newly created volume.

Return a handle by name without validating that it exists.

Parameters

Name of the existing volume.

Returns
type:

A handle that fetches metadata lazily on first use.

Look up a volume by name, verifying it exists.

Parameters

Name of the volume.

Returns
type:

A handle with metadata pre-fetched.

Raises

If the volume does not exist.

Return whether a volume with name exists.

Probes GetVolume with the default version selector. A not-found response maps to False; any other client error propagates so a transient failure is never mistaken for "absent".

Upload an image's lazy local files into volumes.

Creates one volume per destination directory and commits files in batches. Returned mounts follow the default mutable ref.

Parameters

Image whose lazy local files should be uploaded.

Prefix used when naming the generated volumes.

Returns
type:
builtins.list[VolumeMount]

One VolumeMount per created volume.

Stage an image's lazy local files into source-code volumes.

Reuses (or creates, source_code-kind) one stable volume per destination directory — named from volume_name — and uploads the file bytes, but does not commit. Each staged upload is returned as a typed chalk.volume.v2.CommitIntent for ExternalFunctionVersionSpec.volume_commits: the server commits the intent and stamps the resulting version_id onto the spec volume with the matching name, so every replica is pinned to that immutable snapshot.

On reused volumes the intent carries a recursive remove of root, which the server applies as "replace the base tree": the committed version is exactly the staged files, so redeploys never leak stale files into new versions.

Parameters

Image whose lazy local files should be staged.

Stable name for the volume, typically derived from the function or class name so redeploys append versions to the same volume. A per-directory suffix is added when the image spans multiple destination directories.

Returns
type:
tuple[builtins.list[VolumeMount], builtins.list[pb_v2.CommitIntent]]

One mount and one commit-intent dict per volume.

Delete a volume by name.

Parameters

Volume to delete.

List all volumes the caller has access to.

Parameters
limit: = 100

Page size used when traversing the server-side cursor.

Returns
type:
builtins.list[VolumeInfo]

One entry per volume.

Volume

Class

A handle to a volume using the v2 volume service.

Volumes expose immutable snapshots behind mutable refs. The Python API supports direct file writes, reads, listing, and version lookup. Each write produces a new immutable version; the main ref (or a caller-provided ref) advances to point at the latest committed version.

Examples

Write a file, advance the ref, and read the result back:

from chalkcompute import Volume
with Volume("models") as vol:
    vol.put_file("config.yaml", b"lr: 0.01\n")
    vol.read_file("config.yaml")
b'lr: 0.01\n'

Pin a handle to a previous version and read from it:

previous = vol.at_version(vol.versions()[-2].id)
_ = previous.read_file("config.yaml")
Attributes

Volume name.

Pinned version id, or None for a ref-tracking handle.

Mutable ref tracked by this handle.

Cached volume metadata, fetched on first access.

Returns

VolumeInfo Metadata for this volume.

Cached version metadata for the current ref or pinned version.

Returns

VersionInfo The version this handle currently points at.

Raises

VolumeError If the volume has no version yet (newly created, no commits).

Functions

Initialize a volume handle.

Parameters

Volume name.

Optional VolumeClient. If None, one is constructed from a default ConnectClient.

If set, pin this handle to a specific immutable version. Such handles are read-only; mutating operations raise VolumeError.

ref: = 'main'

Mutable ref to read/write through (defaults to "main").

If True (the default), the volume is created on first access if it does not already exist. Ignored when version_id is set.

Refresh volume and version metadata from the server.

Returns

Fresh metadata for this volume.

Read a file's contents at the current version.

Parameters

File path within the volume.

Returns
type:

The raw file bytes.

Write a file, committing a new version on the current ref.

Small payloads are committed inline; large payloads are chunked and uploaded to object storage before the commit completes.

Parameters

Destination path within the volume.

File contents (bytes or str).

Returns
type:

self, to allow chaining.

Upload a local file into the volume.

Parameters

Destination path within the volume.

Local file to read and upload.

Returns
type:

self, to allow chaining.

Upload a directory, overwriting files without deleting other content.Notes

Empty directories are omitted. Uploads may make multiple commits. A failed upload can leave earlier commits visible.

Parameters

Local directory to upload recursively.

Relative destination within the volume. Defaults to its root.

Returns
type:

self, with its cached version updated after commits complete.

Raises
error:

If paths are invalid or the directory contains symlinks or special files.

If the volume is closed, pinned, or an upload fails.

Clone a Git repository and upload its checkout to this volume.

Requires the git executable on the local machine. The checkout includes Git metadata so it can be used as a working repository after mounting the volume.

Parameters

Repository URL accepted by git clone.

Destination directory within the volume.

revision: = 'main'

Branch, tag, or commit SHA to check out.

Remove a file, committing a new version on the current ref.

Parameters

File path within the volume.

Returns
type:

self, to allow chaining.

List files at the current version.

Parameters

Only return entries under this directory prefix.

If True (the default), descend into subdirectories.

Returns
type:

One entry per matching file or directory.

Iterate over files at the current version.

Parameters

Only return entries under this directory prefix.

Context manager that commits staged writes as one version.

Files staged within the block are bundled into a single commit when the block exits (or when max_files_per_commit is reached).

Parameters
max_files_per_commit: = _BATCH_MAX_FILES

Maximum files per commit before flushing automatically.

with vol.batch_upload() as batch:
    batch.put("a.txt", b"hello")
    batch.put("b.txt", b"world")

Copy a Chalk Dataset revision into a volume.

Only the revision's output parquet files are ingested with matching partitioning.

Parameters

Revision id or an object with a revision_id attribute.

Optional destination directory within the volume.

timeout: = 600.0

Deadline in seconds for each dataset download-URI stream.

Number of full stream passes after staging failures. Each new pass obtains fresh signed URLs and skips files already staged.

Optional callback receiving cumulative staged file and byte counts.

Returns

The newly committed volume version.

List all versions of this volume.

Parameters
limit: = 100

Page size used when traversing the server-side cursor.

Returns

One entry per immutable version, ordered by the server.

Fetch the latest committed version on this handle's ref.

Returns

The version currently pointed at by the ref.

Raises

If the volume has no committed versions yet.

Return a read-only handle pinned to a specific version.

Mutating operations on the returned handle raise VolumeError.

Parameters

The immutable version to pin to.

Returns
type:

A new handle pointing at version_id.

Return a mutable handle tracking an existing ref.

Parameters

Name of the ref to open.

Returns
type:

A mutable handle tracking name.

Create an independent ref at this handle's current version.

The returned handle reads and writes through the new ref. Forking a version-pinned handle starts exactly at that immutable version.

Parameters

Name for the new ref.

Returns
type:

A mutable handle tracking the new ref.

List the forks for this volume.

Delete this handle's fork without deleting its versions.

Raises

If this handle tracks the main ref or is pinned to a version.

Create a mount specification for this handle.

Fork handles mount their mutable ref. Version-pinned handles mount an immutable snapshot. The default path is /volumes/<volume-name>.

Delete this volume and all of its versions.

Raises

If called on a version-pinned (read-only) handle.

Download a file from the current version to a local path.

Parameters

File path within the volume.

Local destination path to write.

Download the current version into a local directory.

Parameters

Local destination directory.

Close the underlying client used by this Volume.

Safe to call multiple times.

Enter a context that closes the volume on exit.

Close the volume on context exit.

Metadata about a volume.

Attributes

name Name of the volume. created_at Timestamp when the volume was created.

Metadata about a file inside a volume.

Attributes

path File path within the volume. size File size in bytes. updated_at Timestamp when the file was last updated.

VolumeError

Exception

Base exception for volume errors.

Raised when a volume is not found.

Deploy Python functions as versioned, autoscaling remote functions.

Remote functions turn an ordinary Python callable into a managed service. Chalk packages the function into a container image, deploys it as a ScalingGroup, routes incoming calls over gRPC, and handles replica autoscaling, warm-pool management, batching, and retries. Input and output Arrow schemas are inferred from the function's type hints so callers can invoke it with native Python values and the transport layer stays hidden.

The decorator form, function, is the common entrypoint: annotate any callable with @chalkcompute.function(image=..., cpu=..., memory=...) and call .deploy() to publish a new version. For the imperative API — useful when wrapping functions defined elsewhere or deploying programmatically — construct a RemoteFunction directly.

Use RetryPolicy to configure automatic retries, and catch the FunctionError / FunctionBuildError hierarchy for deploy-time and runtime failures.

Decorator that deploys a function as a versioned remote function.

Locally, decoration validates the function, starts deployment in a background worker, and returns. The worker:

  1. Derives Arrow schemas from the function's type hints
  2. Builds a deploy image with a handler shim
  3. Registers the function version via ExternalFunctionCatalogService
  4. If CHALK_FUNCTION_LOCAL_SDK_COPY=1, includes local SDK source in the deploy image for unreleased feature iteration.

Deployments of consecutive, distinctly named functions overlap. Remote calls and lifecycle operations wait for their function's deployment before proceeding. A script containing only decorated definitions also waits for all queued deployments before interpreter shutdown.

Remotely (inside the container): Lifecycle methods become no-ops. Calling the symbol runs the local Python body in-process; .remote() / .defer() dispatch to the deployed function (resolved lazily by name), so a function can invoke a sibling without RemoteFunction.from_name(...).

Parameters
func:
Callable[..., Any] | None
= None
image:
_Image | None
= None

Container image to deploy in. Defaults to Image.debian_slim().

cpu: = None

CPU resource request (e.g. "1", "500m").

memory: = None

Memory resource request (e.g. "1Gi", "512Mi").

gpu: = None

GPU resource request (e.g. "nvidia-l4", "2:nvidia-a100"). Format is "<count>:<type>" or just "<type>" for a single GPU.

name: = None

Custom function name. Defaults to the function's __name__.

env:
Mapping[str, str | _Secret] | None
= None

Environment variables as strings or single-value Secret references. The mapping key sets the injected name, overriding aliases and prefixes.

secrets:
list[_Secret] | None
= None

List of Secret references to inject.

List of Volume handles, VolumeMount specifications, or (name_or_volume, mount_path) tuples for persistent storage. Volume handles preserve their selected ref or pinned version.

tags: = None
readiness_probe:
_ReadinessProbe | None
= None

Minimum number of replicas.

Maximum number of replicas.

Graceful termination period in seconds before replicas are forcibly killed during scale-down. Defaults to 30s on the server.

How often (in seconds) the autoscaler scrapes metrics to make scaling decisions. Defaults to 60s on the server.

Target CPU utilization percentage (0-100) that drives autoscaling.

Target GPU utilization percentage (1-100) that drives autoscaling, read from DCGM. Requires gpu and min_replicas >= 1: the utilization series exists only while replicas do, so this trigger cannot scale a group up from zero.

Target pending-request queue depth per replica. When set, the autoscaler scales on the function's own queue depth.

cron_scaling_trigger:
_CronScalingTrigger | None
= None

Sets a replica floor during specified cron-defined time windows, independent of the other autoscaling triggers.

scale_from_zero_request_policy:
_ScaleFromZeroRequestPolicy | None
= None

Wire format for arguments and results. Currently only "pyarrow" is supported.

options: = None

Arbitrary key-value options forwarded to the Chalk platform.

Maximum time in milliseconds to buffer incoming items before invoking the handler. Defaults to 1000 ms when batching is enabled. When batching is enabled, handler args are lists.

Maximum number of items to accumulate before invoking the handler. Defaults to 10 when batching is enabled.

Retry policy for handler invocations. Pass an int for simple max-attempts with default exponential backoff, or a RetryPolicy for full control. Enforced before each outbound RPC, not in the handler.

Rate limit policy for outbound calls. Pass an int for a simple "N per second" cap with a per-function key, or a RateLimitPolicy for full control (rate, per, key). Multiple functions sharing the same key share one bucket — used when a downstream service imposes a throughput limit across callers.

Concurrency policy: cap on in-flight handler invocations. Pass an int for a simple max_concurrent cap with a per-function key, or a ConcurrencyPolicy for full control (max_concurrent, key). Multiple functions sharing the same key share one gate — independent of rate_limit (which caps rate, not in-flight count).

Queue quota: cap on the number of pending items that may be enqueued for this function at once. Pass an int for the cap, or a QueuePolicy (currently equivalent — QueuePolicy(max_items=N)). Defaults to 500,000 items when unset. Submitting past the cap raises a gRPC RESOURCE_EXHAUSTED error — clients should back off or call purge() on the function to drain the queue if items were erroneously added.

schedule: = None

Optional crontab or Chalk duration string for invoking a no-input function on a schedule (e.g. "0 * * * *" or "1h").

Mapping of model_name -> output_type for Chalk models that should be auto-bound into the local chalkdf catalog before the function body runs. Each entry becomes a bind_model call invoked by the handler shim on import, so F.catalog_call("model.<name>", ..., output_type=<type>) resolves without any explicit setup in the function body. For advanced overrides (version, method_name, qualified_name) call bind_model directly inside the function.

Server-side remote-function tracing is enabled by default. Use TracingPolicy for sampling. Set False to explicitly turn tracing off.

import chalkcompute
@chalkcompute.function
def add(x: int, y: int) -> int:
    return x + y
add.remote(1, 2)   # wire call to the deployed function
add(1, 2)          # runs the Python body in-process

A versioned remote function backed by ExternalFunctionCatalogService.

Deploys a Python function as a ScalingGroup and registers it with input/output Arrow schemas derived from the function's type hints.

Most users should prefer the function decorator; use RemoteFunction directly when you need the imperative API (for example, when wrapping a function defined elsewhere, or when constructing deployments programmatically).

Examples

Decorator form — the most common entrypoint:

import chalkcompute
from chalkcompute import Image
@chalkcompute.function(
    image=(
        Image.debian_slim()
        .pip_install(["numpy"])
    ),
    cpu="1",
    memory="2Gi",
    min_replicas=1,
    max_replicas=4,
)
def embed(text: str) -> list[float]:
    import numpy as np
    return np.ones(8).tolist()
embed.remote("hello world")
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

Imperative form, for constructing a RemoteFunction from an existing callable:

from chalkcompute import RemoteFunction, Image
def square(x: int) -> int:
    return x * x
fn = RemoteFunction(
    square,
    image=Image.debian_slim(),
    min_replicas=1,
    max_replicas=2,
)
fn.deploy()
fn.remote(7)
49
fn(7)  # runs the local Python body in-process
49
Functions

Attach to an existing function version by ID.

This compatibility alias retains the historical version-ID meaning. Prefer from_version_id or from_function_id in new code.

Attach through an immutable version ID.

Parameters

Identifier of the function version.

Returns

A handle bound to the existing version.

Attach to an external function's currently selected version.

Parameters

Name of the function.

Returns

A handle bound to the existing version.

Attach to a stable external function by ID.

Ensure the definition is deployed, reusing an unchanged version.

Parameters

Seconds between status polls.

Maximum seconds to wait for the image build.

Maximum seconds to wait for the scaling group to become ready.

Create a new version even when unchanged, reusing image/source artifacts.

Returns

self for chaining.

Wait until the backing scaling group is ready to serve.

A min_replicas=0 function counts as ready once it reaches ScaledToZero, matching what deploy waits for.

Parameters
timeout: = 120.0

Maximum seconds to wait.

Seconds between status polls.

Returns

self for chaining.

Raises

If the function has not been deployed or never becomes ready.

Return a call-scoped function handle with an overridden request time.

The returned handle shares this function's deployment and clients but sends x-chalk-request-timestamp on subsequent calls and deferred enqueues.

Invoke the underlying Python function locally, in-process.

This runs the original function body in the current process — it does not dispatch to the deployed remote function. Use remote for a synchronous wire call, or defer to enqueue one and get a handle back.

Invoke the deployed remote function over the wire.

Returns
type:

Scalar result for single-row calls, or a list of results otherwise. For generator functions, returns an iterator of result batches.

Enqueue this function call and return a handle immediately.

Drop pending queued calls for this function.

List immutable versions belonging to this external function.

Select an existing immutable version without creating a new one.

Delete this external function and all of its versions.

Fetch latest function version info from the server.

Returns

Updated version info.

Raises

If the function has not been deployed or the RPC fails.

Metadata about a deployed function version.

Attributes

Unique identifier of the function version.

Registered function name.

Monotonic version number for this function.

Name of the scaling group backing this version.

Stable identifier of the parent external function.

Immutable scaling-group revision linked to this version.

Time at which this immutable version was created.

Whether the parent external function currently serves this version.

Retry configuration for handler invocations.

Construct via the named constructors rather than instantiating directly. With exponential backoff, wait times grow geometrically (initial, initial * multiplier, initial * multiplier^2, ...) capped at max_wait. With linear, wait times are constant between retries. A plain int passed to function(retries=3) is shorthand for RetryPolicy.exponential(attempts=3). By default all Exception subclasses trigger a retry; pass a tuple of exception classes to retry_on to narrow the set.

Examples

RetryPolicy.exponential(attempts=5, initial=1.0, max_wait=30.0)
RetryPolicy.linear(attempts=3, delay=2.0)
RetryPolicy.exponential(
    attempts=3,
    retry_on=(ConnectionError, TimeoutError, OSError),
)
Attributes

Maximum number of retry attempts (not counting the initial call).

Base wait time in seconds before the first retry.

Multiplier applied to wait time on each successive retry. Use 2.0 for exponential backoff (the default) or 1.0 for fixed delay.

Upper bound on wait time between retries.

If True, add random jitter to wait times to avoid thundering herd.

retry_on
tuple[type[BaseException], ...]

Tuple of exception types that trigger a retry. Non-matching exceptions propagate immediately without consuming retry budget.

Shared-bucket identifier. Functions using the same key share one retry context. Defaults to the function's qualified name if omitted.

Functions

Create a policy with exponential backoff.

Parameters

Maximum number of retry attempts.

Base wait time in seconds before the first retry.

Multiplier applied to wait time on each successive retry.

Upper bound on wait time between retries.

jitter: = True

If True, add random jitter to wait times.

retry_on:
tuple[type[BaseException], ...]
= (Exception)

Exception types that trigger a retry.

key: = None
Returns

A configured RetryPolicy.

RetryPolicy.exponential(attempts=5, initial=0.5, max_wait=30.0)
RetryPolicy.exponential(attempts=3, retry_on=(TimeoutError,))

Create a policy with fixed delay between retries.

Parameters

Maximum number of retry attempts.

Fixed wait time in seconds between retries.

jitter: = False

If True, add random jitter to wait times.

retry_on:
tuple[type[BaseException], ...]
= (Exception)

Exception types that trigger a retry.

key: = None
Returns

A configured RetryPolicy.

RetryPolicy.linear(attempts=3, delay=2.0)
RetryPolicy.linear(
    attempts=5,
    delay=0.5,
    retry_on=(ConnectionError, TimeoutError),
)

FunctionError

Exception

Base exception for Function errors.

Raised when the function image build fails.

Deploy Python classes with multiple methods as versioned remote functions.

Use @chalkcompute.cls() with @chalkcompute.method() to mark methods for deployment. Lifecycle hooks @before() and @after() run startup and shutdown logic in each method's container.

Decorator that deploys a class as versioned remote functions.

Locally (at decoration time):

  1. Scans the class for @method, @before, @after
  2. Builds a deploy image with per-method handler shims
  3. Registers each method via ExternalFunctionCatalogService
  4. If CHALK_FUNCTION_LOCAL_SDK_COPY=1, includes local SDK source in the deploy image for unreleased feature iteration.

Remotely (inside the container): Lifecycle methods become no-ops. Accessing a @method runs the local method body in-process when called; .remote() / .defer() dispatch to the deployed method (resolved lazily by name), so a method can invoke a sibling without RemoteClass.from_name(...).

Parameters
user_cls:
type | None
= None
image:
_Image | None
= None

Container image to deploy in. Defaults to Image.debian_slim().

cpu: = None

CPU resource request (e.g. "1", "500m").

memory: = None

Memory resource request (e.g. "1Gi", "512Mi").

gpu: = None

GPU resource request (e.g. "nvidia-l4", "2:nvidia-a100").

name: = None

Custom class name. Defaults to the class's __name__.

env:
Mapping[str, str | _Secret] | None
= None

Environment variables as strings or single-value Secret references. The mapping key sets the injected name, overriding aliases and prefixes.

secrets:
list[_Secret] | None
= None

List of Secret references to inject.

List of Volume handles, VolumeMount specifications, or (name_or_volume, mount_path) tuples for persistent storage. Volume handles preserve their selected ref or pinned version.

tags: = None
readiness_probe:
_ReadinessProbe | None
= None

Minimum number of replicas per method.

Maximum number of replicas per method.

Graceful termination period in seconds before replicas are forcibly killed during scale-down. Defaults to 30s on the server.

How often (in seconds) the autoscaler scrapes metrics to make scaling decisions. Defaults to 60s on the server.

Target CPU utilization percentage (0-100) that drives autoscaling.

Target GPU utilization percentage (1-100) that drives autoscaling, read from DCGM. Requires gpu and min_replicas >= 1: the utilization series exists only while replicas do, so this trigger cannot scale a group up from zero.

Target pending-request queue depth per replica. When set, the autoscaler scales on each method's own queue depth.

cron_scaling_trigger:
_CronScalingTrigger | None
= None

Sets a replica floor during specified cron-defined time windows, independent of the other autoscaling triggers.

scale_from_zero_request_policy:
_ScaleFromZeroRequestPolicy | None
= None

Wire format for arguments and results. Currently only "pyarrow" is supported.

options: = None

Arbitrary key-value options forwarded to the Chalk platform.

Maximum time in milliseconds to buffer incoming items before invoking the handler. Defaults to 1000 ms when batching is enabled. When batching is enabled, handler args are lists.

Maximum number of items to accumulate before invoking the handler. Defaults to 10 when batching is enabled.

Retry policy for handler invocations. Pass an int for simple max-attempts with default exponential backoff, or a RetryPolicy for full control. Enforced before each outbound RPC, not in the handler.

Rate limit policy for outbound calls. Pass an int for a simple "N per second" cap with a per-method key, or a RateLimitPolicy for full control (rate, per, key). Multiple methods sharing the same key share one bucket — used when a downstream service imposes a throughput limit across callers.

Concurrency policy: cap on in-flight handler invocations. Pass an int for a simple max_concurrent cap with a per-method key, or a ConcurrencyPolicy for full control (max_concurrent, key). Multiple methods sharing the same key share one gate — independent of rate_limit (which caps rate, not in-flight count).

Queue quota policy: cap on queued calls per key. Pass an int for a simple max_queue_depth cap with a per-method key, or a QueuePolicy for full control.

schedule: = None

Optional crontab or Chalk duration string applied to every no-input @method in the class (e.g. "0 * * * *" or "1h").

Mark a class method for remote deployment.

Mark a method as the startup hook (called before the server starts).

Mark a method as the shutdown hook (called when the process exits).

A managed class backed by ExternalFunctionCatalogService.

Deploys each @method as a separate function version with its own scaling group, sharing a single container image. Lifecycle hooks (@before / @after) run in every method's container.

Most users should prefer the cls decorator.

Examples

Deploy a stateful class with an expensive warm-up step, then call individual methods remotely:

import chalkcompute
from chalkcompute import Image
img = (
    Image.debian_slim()
    .pip_install(["sentence-transformers"])
)
@chalkcompute.cls(
    image=img,
    cpu="2",
    memory="4Gi",
    min_replicas=1,
    max_replicas=2,
)
class Embedder:
    @chalkcompute.before
    def load(self):
        from sentence_transformers import SentenceTransformer
        self.model = SentenceTransformer("all-MiniLM-L6-v2")
    @chalkcompute.method
    def embed(self, text: str) -> list[float]:
        return self.model.encode(text).tolist()
    @chalkcompute.method
    def embed_batch(self, texts: list[str]) -> list[list[float]]:
        return self.model.encode(texts).tolist()
    @chalkcompute.after
    def shutdown(self):
        del self.model
Embedder.deploy()
e = Embedder()
vec = e.embed("hello world")
batch = e.embed_batch(["a", "b", "c"])
Functions

Attach to an existing remote class by name.

Discovers all function versions whose functionName starts with {name}. and rebuilds a RemoteClass with callable methods.

Parameters

Class name previously used at deploy time.

Returns

A handle bound to the existing versions.

Raises
error:

If no function versions are found for the given name.

Deploy all methods, reusing unchanged function versions.

force_new_version=True creates fresh versions while still reusing image builds and source uploads.

Parameters

Seconds between status polls.

Maximum seconds to wait for the image build.

Maximum seconds to wait for scaling groups to become ready.

Returns

self for chaining.

Wait until all backing scaling groups have ready replicas.

Parameters
timeout: = 120.0

Maximum seconds to wait per method.

Seconds between status polls.

Returns

self for chaining.

Delete all function versions and clean up volumes.

Fetch latest info for all methods from the server.

Returns

Mapping of method name to updated FunctionVersionInfo.

ClassError

Exception

Base exception for RemoteClass errors.

Raised when the class image build fails.

Managed scaling groups for deploying HTTP/gRPC services.

Orchestrates image building, local file upload, and scaling group lifecycle. Use .call() to make HTTP requests to the deployed service.

A managed scaling group backed by ScalingGroupManagerService.

Orchestrates image building, local file upload via volumes, and scaling-group lifecycle in a single high-level API.

Examples

from chalkcompute import ScalingGroup, Image
img = (
    Image.debian_slim()
    .pip_install(["flask"])
    .add_local_file("./app.py", "/app/app.py")
    .entrypoint(["python", "/app/app.py"])
)
sg = ScalingGroup(
    image=img,
    port=8080,
    authenticated=True,
).deploy().wait_ready()
resp = sg.call("/health", method="GET")
sg.delete()
Functions

Attach to an existing scaling group by ID.

Parameters

Opaque scaling-group identifier assigned by the service.

Returns

A ScalingGroup handle bound to the existing resource.

Raises

If the scaling group cannot be found.

Attach to an existing scaling group by name.

Parameters

DNS-safe scaling-group name.

Returns

A ScalingGroup handle bound to the existing resource.

Raises

If the scaling group cannot be found.

Build the image, upload local files, and create the scaling group.

Parameters

Seconds between status polls for both build and startup.

Maximum seconds to wait for the image build to complete.

Maximum seconds to wait for the scaling group to have at least one ready and available replica.

Returns

self, to allow chaining.

Raises

If deployment fails or times out.

List immutable revisions for this scaling group.

Select an existing immutable revision without creating a new one.

Make an HTTP request to the scaling group's endpoint.

Parameters
path: = '/'

URL path appended to the scaling group's web_url.

method: = 'POST'

HTTP method.

json: = None

Optional JSON-serializable body.

data: = None

Optional raw bytes body (mutually exclusive with json).

headers: = None

Optional HTTP headers. Authenticated scaling groups automatically receive the current Chalk bearer token unless this contains an Authorization header.

Request timeout in seconds.

Returns

A buffered HTTP response satisfying the SDK's structural response protocol.

Raises

If the scaling group has no web_url yet.

Wait until a running scaling group has at least one ready replica.

Parameters
timeout: = 120.0

Maximum seconds to wait before giving up.

Seconds between status polls.

Returns

self, to allow chaining.

Raises

If the group enters a terminal failed state or never becomes ready before the timeout elapses.

Delete the scaling group and clean up associated volumes.

Fetch latest scaling-group status from the server.

Returns

The latest metadata for the scaling group.

Raises

If no scaling-group ID is set (deploy() was never called).

Metadata about a scaling group.

Attributes

Opaque scaling-group identifier assigned by the service.

DNS-safe scaling-group name.

Lifecycle state reported by the service (e.g. "Running").

URL to which HTTP traffic should be sent, if ready.

Number of replicas currently ready to serve traffic.

Number of replicas available behind the service endpoint.

Immutable revision currently selected to serve traffic.

Base exception for ScalingGroup errors.

Raised when the custom image build fails.

References to secrets available to a sandbox, container, or remote function.

Use Secret.from_name(...) to reference a secret by name; the secret value is resolved at runtime from the Chalk secret store and injected as an environment variable.

Secret

Class

A reference to a Chalk secret or integration to inject as env vars.

Construct instances via the factory methods rather than instantiating directly.

Examples

Secret.from_chalk_env("OPENAI_API_TOKEN")
Secret.from_chalk_integration("prod_postgres")
Secret.from_local_env("OPENAI_API_KEY")
Secret.from_local_env("OPENAI_API_KEY", env_var_name="API_KEY")
Secret.from_local_env_file(".env")
Attributes

Whether this secret requires local resolution before container start.

Returns

bool True if the secret is built from a local env var or env file.

Functions

Reference a standalone secret by name (e.g. "OPENAI_API_TOKEN").

The secret's value is injected as an environment variable with the same name, unless alias or prefix is given.

Parameters

Name of the Chalk secret.

alias: = None

Rename the env var exposed in the container.

prefix: = None

Optional prefix applied to the env var name.

Returns
type:

A secret reference.

Reference an integration by name (e.g. "prod_postgres").

All secrets associated with the integration are injected as env vars.

Parameters

Name of the Chalk integration.

keys: = None

Limit injection to the listed keys.

aliases: = None

Rename specific keys when exposing them as env vars.

prefix: = None

Optional prefix applied to every injected env var.

Returns
type:

A secret reference bound to the named integration.

Deprecated alias for from_chalk_env.

.. deprecated:: Use from_chalk_env instead.

Deprecated alias for from_chalk_integration.

.. deprecated:: Use from_chalk_integration instead.

Inject a local environment variable as a secret into the container.

Reads os.environ[local_env_var] at container start time, upserts it as a Chalk secret, and injects it as an env var in the container.

Parameters

Name of the local environment variable to read.

Name for the env var inside the container. Defaults to local_env_var.

Returns
type:

A lazy secret reference resolved at Container.run() time.

Inject all variables from a local .env file as secrets.

Reads the file at container start time, upserts each KEY=VALUE pair as a Chalk secret, and injects them as env vars in the container. Lines starting with # and blank lines are ignored.

Parameters

Path to the local .env file.

Returns
type:

A lazy secret reference resolved at Container.run() time.