Skip to content

Python SDK reference

Audience: Python engineers integrating Nanorix into a healthcare-AI / claims / legal-AI / agent backend. Package: nanorix (v0.7.0). The 1.0 contract freeze is planned; the current surface is stable and additive. Python: 3.9 – 3.13. Substrate framing. The SDK wraps the HTTP API documented in api-reference.md. Every public method maps 1:1 to one or more API endpoints. The SDK adds: typed exceptions, exponential-backoff retries, and helper modules for verification, signing, and compliance metadata.


Install

pip install nanorix

Or from source: github.com/nanorix-io/nanorix-sdk.

Dependencies: httpx>=0.25,<1.0, pydantic>=2.0,<3.0, cryptography>=50.0.0,<51.0.0.


Top-level surface

import os

import nanorix
import nanorix.compliance
import nanorix.helpers
import nanorix.verifier

# Construction: api_key is required; no environment variable is read for you
client = nanorix.Client(api_key="nrx_live_...")            # explicit
client = nanorix.Client(api_key=os.environ["NANORIX_API_KEY"])
client = nanorix.Client(api_key=os.environ["NANORIX_API_KEY"],
                        base_url="https://api.nanorix.io",
                        timeout=30.0, max_retries=3)        # defaults

# base_url must use https://; http:// is accepted only for localhost or 127.0.0.1,
# and any other value raises ValueError at construction

# Async variant — same surface, same method names; coroutines instead of plain returns
async_client = nanorix.AsyncClient(api_key=os.environ["NANORIX_API_KEY"])

# Resources
client.capsulefiles      # Capsulefile lifecycle
client.capsules          # capsule lifecycle + .run(), .batch(), .session()
client.cdp               # AuditProof retrieval (alias: client.audit_proofs)
client.audit_proofs      # alias of .cdp
client.egress_profiles   # named egress allowlists
client.usage             # usage summary, line-items, CSV export
client.webhooks          # webhook endpoints + deliveries

# Subpackages
nanorix.helpers          # signer, checkpoint_saver, activity_events
nanorix.verifier         # verify_auditproof()
nanorix.compliance       # framework-typed metadata builders (HIPAA, GDPR, SOC 2)

# Top-level
client.health()          # GET /v1/health
client.close()           # release HTTP transport

The default base_url, https://api.nanorix.io, is the hosted Evaluation Sandbox, for data that is not regulated. For regulated data, set base_url to your own BYOC deployment (self-hosting), for example nanorix.Client(api_key=os.environ["NANORIX_API_KEY"], base_url="https://nanorix.internal.example.com").

The timeout default of 30.0 s applies per phase of one request. Uploads use 300 s and exec uses 600 s whatever timeout is.

Client is also a context manager:

import os

import nanorix

with nanorix.Client(api_key=os.environ["NANORIX_API_KEY"]) as client:
    result, cdp = client.capsules.run(...)
# transport closed on exit

Exceptions

Full reference: error catalog.

from nanorix import (
    NanorixError,                       # base
    AuthenticationError,                # 401
    NotFoundError,                      # 404
    ConflictError,                      # 409
    BadRequestError,                    # 400
    QuotaExceededError,                 # 402, 403 (quota)
    PayloadTooLargeError,               # 413
    GoneError,                          # 410: lifetime ended before the destroy, or capsule no longer live (below)
    RateLimitError,                     # 429 (after the retry budget, or at once when not retried)
    UnprocessableEntityError,           # 422 default
    InputProvenanceRejectedError,       # 422 input_provenance_rejected
    SecretsInjectionRejectedError,      # 422 secrets_injection_rejected
    ExecutionError,                     # non-zero exit; .cdp set only in the cases below
    CeilingError,                       # not raised: see "When a capsule's lifetime ends" below
    TimeoutError,                       # not raised: an exec timeout within the 600 s exec wait raises ExecutionError, exit_code -1
)

When a capsule's lifetime ends. An exec sent after the capsule's lifetime (max_lifetime_seconds) ends raises GoneError (410) while the capsule is not destroyed yet, and ConflictError (409) once it is; a command still running when the lifetime ends can come back with exit code -1 (ExecutionError). upload(), list_outputs() and download() raise GoneError once the capsule is no longer live, for example after a destroy. In the 410 window no AuditProof exists yet: capsule.destroy() returns it, or the lifetime reaper destroys the capsule later. client.cdp.get(capsule_id) raises NotFoundError until the proof is stored, including while the destroy is pending. A NanorixError that run(), batch() or session() raises after creating the capsule carries the capsule's id as capsule_id, and the capsule's AuditProof as cdp when their cleanup destroy succeeded (below). A lifetime end after their exec raises the GoneError unchanged.

When an error's cdp, capsule_id and cleanup_error are set. Every NanorixError has capsule_id, cdp and cleanup_error, None unless set. When run(), batch() or session() raise a NanorixError after creating the capsule, they destroy the capsule, set capsule_id, and set cdp to its AuditProof when that destroy succeeds. The three name one capsule: an error that already carries a proof is left as it is, and one whose capsule_id names another capsule gets no proof and no cleanup_error. In those two cases the error does not name the capsule the call created; client.capsules.list() finds it. When that destroy fails, or the error came from their final destroy, the error carries capsule_id and no cdp; the list after this paragraph says what to do. When that destroy failed with a NanorixError, the error also carries that destroy's own error as cleanup_error, unless it already carries one, so you can read its status_code and body: a 503 auditproof_signing_unavailable there (AuditProofSigningUnavailableError, with retry_signing_url and pause_window_expires_at) means the capsule's status is signing_failed, so POST retry-signing as the list's first item says, without reading the status first. An exception that is not a NanorixError, such as one your on_record callback raises, is raised unchanged, without the id or the proof. That includes a KeyboardInterrupt, a SystemExit and a cancelled task's asyncio.CancelledError raised after create() returns and before the final destroy: these too get the cleanup destroy before they are raised, so the first Ctrl-C waits for that destroy (bounded by the client's timeout and retries, and the Retry-After of any 429), and asyncio.timeout() or asyncio.wait_for() around async run() raises only after it answers. An interrupt during create() can leave an empty capsule, which client.capsules.list() finds. Only async run() can be cancelled; there is no async batch() or session(). In the sync methods, a second interrupt during the cleanup destroy ends that destroy and goes out in place of the first, and an interrupt during the final destroy ends that destroy. A cancellation or an interrupt during the cleanup destroy after a NanorixError ends the wait for that destroy (async) or that destroy (sync) and goes out in place of the error, which then gets no capsule_id from the call (it is the new exception's __context__). In async run(), a further cancellation during the cleanup destroy, or a cancellation during the final destroy, ends the wait for that destroy at once with CancelledError, and the destroy runs on while the event loop runs: leaving async with (closing the client) waits for it, at most the client's timeout (with timeout=None, without a bound), before it closes the client, a destroy still running after that wait may not complete, asyncio.run() cancels it when the main coroutine ends, a failure after the wait ended is not reported, and client.capsules.list() finds a capsule it left live. Under anyio cancel scopes (anyio.fail_after, Starlette and FastAPI) the further cancellation comes at once, so run() does not wait for the cleanup destroy, and inside such a scope that has been cancelled, leaving async with does not wait for it either: open the client outside the scope. batch() and session() raise ExecutionError with exit_code 0 when the capsule did not write results.jsonl or state.bin (the download answered 404); any other failed download is raised unchanged. ExecutionError.cdp is also set when a batch() with on_record_error="abort_batch" stops on a record error (if that destroy fails, its error is raised instead of ExecutionError). Inside a @workload function, the decorator sets .cdp and .capsule_id on an exception the function raises that carries neither, to the proof and id of the capsule the decorator created, when that capsule's destroy succeeds. An exception that already names a capsule (a .cdp or .capsule_id that run(), batch() or session() set for the capsule that held the data) is kept as it is; the decorator's own proof is on the function's last_audit_proof and given to on_audit_proof either way. When the decorator's own destroy fails, an exception that carries neither field gets the decorator's capsule id as .capsule_id and no .cdp, for the recovery below. When that destroy failed with a NanorixError, the decorator also sets .cleanup_error to that destroy's own error as run() does: on a NanorixError that carries no .cdp, names no other capsule and carries no .cleanup_error yet. In an async function with an AsyncClient, the decorator's cleanup destroy, and its destroy after the function returns, each run as their own task, as in async run(): a cancellation during either ends only the wait for it, and leaving async with waits for it as above. When a cancellation ends that wait, the destroy goes on, but its proof is not set on last_audit_proof or given to on_audit_proof, so last_audit_proof keeps what it held before, and client.capsules.list() finds a capsule that destroy left live.

When an error carries capsule_id and no cdp, read client.capsules.get(capsule_id) and act on its status:

  • signing_failed: POST, with a developer key or above, to the path /v1/capsules/{capsule_id}/retry-signing before the pause window ends. A 503 auditproof_signing_unavailable means signing is still unavailable and the window started again: POST again before the pause_window_expires_at its body gives. A 409 naming a signing buffer overflow means POST again later. A 500 saying the capsule cannot be retried means retry-signing cannot complete its proof.
  • volatile_destroyed or destroyed_pending_cdp: the destroy is still running; read the status again shortly.
  • active or executing: the capsule was not destroyed and still holds its data; destroy it.
  • expired, or the read raises GoneError: the capsule is past its lifetime and the reaper destroys it; read the status again later.
  • destroyed: client.cdp.get(capsule_id) returns the proof.
  • destroyed_no_proof or expired_unclean: no destroy or retry-signing request you send produces a proof for it.

An exec's timeout ends the command on the server, unless the capsule's lifetime (max_lifetime_seconds) ends it first. execute() waits for the exec's response for that timeout plus 60 seconds and never less than 600 seconds, whatever the client's own timeout is; without an exec timeout, execute() waits up to 600 seconds for the exec's response, so give a command that may run longer a timeout. When the command ends within that wait, a nonzero exit raises ExecutionError, and an exec stopped by its timeout comes back with exit_code -1. The SDK sends these requests again on each retry (three by default) after a timeout, a network error or a 429, 500, 502, 503 or 504: a GET or HEAD, and a capsule or capsulefile create carrying an Idempotency-Key that matches [A-Za-z0-9_-]{1,255} (the SDK adds one when you pass none). A create retried after the first create has finished returns that capsule or Capsulefile; a create retried while the first is still running, or after a 5xx, can create a second one. Any request is sent again when its connection failed before it was sent, and any request to /v1/capsules or /v1/capsulefiles or a path under them, an exec, an upload, a record commit (POST /v1/capsules/:id/record) and a destroy among them, is sent again after a 429 once it has waited out the 429's Retry-After, because on those paths the API's rate limiters answer before the request is handled. Every request other than a GET, a HEAD or a keyed create, an exec, a record commit and a destroy among them, is not sent again after a timeout, a network error once it may have been sent, or a 500, 502, 503 or 504: the SDK raises NanorixError at once, with the response's status_code when there was one, and its message says the request may have reached the server and was not sent again, and for an exec that the command may have run (not when the exec's 503 carries the error code isolation_unavailable, which means the command was not run). The exception is a destroy's 503 auditproof_signing_unavailable, which raises AuditProofSigningUnavailableError as before. Outside those paths, a 429 on a request other than a GET or a HEAD raises RateLimitError at once, with its retry_after and the same message. The retry helpers in nanorix.debug (with_retry, async_with_retry, retry_context) do not send again a request the SDK raised that message for, nor one that raised AuditProofSigningUnavailableError. A proxy or load balancer in front of your deployment with a shorter request timeout answers first, often with 504, and the SDK raises that answer to an exec the same way.

Exceptions are importable from the package root (from nanorix import ...).

Every exception carries status_code: Optional[int] and body: Optional[Dict[str, Any]]. The body["error"]["request_id"] field is the support-ticket correlation id; quote it when filing.


client.capsulefiles

Class: Capsulefiles (sync) / AsyncCapsulefiles (async).

create(...)

def create(
    self,
    *,
    name: str,
    runtime: str,
    entrypoint: str,
    files: Union[List[str], Dict[str, bytes], Dict[str, BinaryIO]],
    description: Optional[str] = None,
    labels: Optional[Dict[str, str]] = None,
    env_vars: Optional[Dict[str, str]] = None,
    capsule_memory_mb: Optional[int] = None,
    input_path: Optional[str] = None,
    output_path: Optional[str] = None,
    egress_declaration: Optional[List[str]] = None,
    idempotency_key: Optional[str] = None,
) -> Capsulefile

Creates a Capsulefile, uploads source files, and always finalizes it. Maps to POST /v1/capsulefiles + POST /v1/capsulefiles/:id/files + POST /v1/capsulefiles/:id/finalize.

Argument Type Notes
name str Unique per user: a name you already use for a Capsulefile raises ConflictError.
runtime str python3.11, python3.12 or node22.
entrypoint str Shell command.
files list[str] OR dict[str, bytes] OR dict[str, file object] Required. Local paths to upload, in-memory {filename: bytes}, or {filename: file-like object}.
description str Optional free text.
labels dict[str, str] Sent by the SDK; the API does not store labels today, so the Capsulefile's labels reads back {}.
env_vars dict Available inside the sealed sandbox.
capsule_memory_mb int Memory for each capsule created from this Capsulefile, in MB. This call stores the value as given; the validate and cost-estimate endpoints (nanorix capsulefiles validate, nanorix capsulefiles estimate-cost) accept 64 to 32768. At capsule create (POST /v1/capsules), a value above your tier's ceiling (none on an install with billing off) is refused with 400 invalid_parameters, and a value above the server's per-capsule limit with 400 capsule_memory_exceeds_server_limit; neither is lowered to fit. Omit it to get the smaller of your tier's ceiling and the server's limit. The POST /v1/capsules response carries the limit the runtime wrote as memory_limit_bytes, which client.capsules.create() does not expose: for capsule = client.capsules.create(...), read getattr(client.capsules.get(capsule.id), "memory_limit_bytes", None), which is present only when the API server process that answers runs the capsule.
input_path, output_path str Optional paths inside the capsule.
egress_declaration list[str] Exact hosts, leading-dot suffixes or canonical IP literals; lowercase; no scheme, path, port or CIDR.
idempotency_key str Sent as the Idempotency-Key header of POST /v1/capsulefiles; when omitted the SDK generates a UUIDv4 once per call and sends it on every retry. A retry after the first create has finished returns that Capsulefile; a retry sent while the first is still running, or after a 5xx, can create a second one. The key must match [A-Za-z0-9_-]{1,255}; the SDK treats a create whose key does not match like a create without a key, so it is not sent again after a timeout, a network error once the request may have been sent, or a 5xx. It is still sent again after a connection that failed before sending, and after a 429.

This method has no data_classification, packages or finalize argument, and no memory_mb argument. There is no install step: bundle the packages' files in files, or use nanorix build, which does that from packages:. The call always finalizes.

Returns: Capsulefile model with .id, .status, .content_hash, .name, etc.

Raises: BadRequestError (schema invalid), ConflictError (name in use), QuotaExceededError.

Example:

cf = client.capsulefiles.create(
    name="med-ai-extraction",
    runtime="python3.12",
    entrypoint="python /data/input/capsulefile/main.py",
    files=["main.py"],
    egress_declaration=["api.anthropic.com"],
    capsule_memory_mb=512,
    env_vars={"ANTHROPIC_MODEL": "claude-3-5-sonnet-latest"},
)
print(cf.id, cf.content_hash)

list(...) / get(id) / delete(id)

Standard list/get/delete. Maps to GET /v1/capsulefiles, GET /v1/capsulefiles/:id, DELETE /v1/capsulefiles/:id.

for cf in client.capsulefiles.list().capsulefiles:
    print(cf.id, cf.name, cf.status)

cf = client.capsulefiles.get("cf_aB3dE9xQ")
client.capsulefiles.delete("cf_aB3dE9xQ")

update(id, **kwargs)

Not available: it raises NotImplementedError.

wait_until_finalized(capsulefile_id, *, timeout: float = 120.0, poll_interval: float = 2.0)

Polls get() until the status is finalized. create() finalizes before it returns and gives back the finalized record, so this is for waiting on a Capsulefile another process is finalizing.

upload_dir(id, dir_path)

Convenience: uploads every file under dir_path recursively. Returns the file count.


client.capsules

Class: Capsules (sync) / AsyncCapsules (async).

create(...) → LiveCapsule

def create(
    self,
    *,
    capsulefile: Optional[str] = None,
    max_lifetime_seconds: Optional[int] = None,
    egress_profile: Optional[str] = None,
    metadata: Optional[Dict[str, str]] = None,
    cdp_kind: Optional[str] = None,
    declare_activity: bool = False,
    parent_cdp_id: Optional[str] = None,
    signing_mode: Optional[str] = None,
    idempotency_key: Optional[str] = None,
    data_classification: Optional[str] = None,
    jurisdiction: Optional[str] = None,
    label: Optional[str] = None,
) -> LiveCapsule

Creates a capsule. Returns a LiveCapsule with workspace methods (.upload(), .execute(), .list_outputs(), .download(), .destroy(), .refresh()).

metadata carries customer-declared context in the AuditProof as given; the capsule_started event (signed on 2.1 and 2.2) carries its metadata_hash; no shipped verifier compares the two. Use nanorix.compliance to construct typed framework context (HIPAA, GDPR, SOC 2) or pass a plain Dict[str, str]. Server constraints: 16 keys max, 64-char keys, 256-char values, 4 KB total. The nanorix:* prefix is reserved.

data_classification is your declaration of the data the capsule handles: PHI, PII, financial, credentials or general, in any letter case. The SDK sends it as given; the API refuses any other value with HTTP 400 and records it, lowercased, as capsule_context.data_classification in the capsule's AuditRecord, outside the AuditProof's signature. Nanorix does not check it against the data. When you omit it the SDK sends nothing and the API records general.

jurisdiction is your declaration of the capsule's jurisdiction: us, ca, gb, au, in, eu-fr, eu-de or eu-nl. The SDK sends it as given; the API lowercases it, refuses any other value with HTTP 400 (invalid_parameters, with a message starting invalid_jurisdiction) and records it as the AuditProof's jurisdiction, under its signature. When you omit it the SDK sends nothing and the API records your account's declared jurisdiction where that names one country (US is us, UK is gb, CA is ca, AU is au, IN is in); for an account declared EU or OTHER it refuses the create with HTTP 400 (invalid_parameters, with a message starting invalid_jurisdiction), so name one. It is separate from your organization's jurisdiction, declared at signup or by an organization admin, which the AuditRecord's capsule_context.jurisdiction and regulatory_context use.

label is an optional name for the capsule, stored with it.

Maps to: POST /v1/capsules.

run(...) → (outputs, cdp)

def run(
    self,
    *,
    capsulefile: str,
    inputs: Optional[Dict[str, Union[bytes, BinaryIO]]] = None,
    command: Optional[str] = None,
    timeout: Optional[int] = None,
    max_lifetime_seconds: Optional[int] = None,
    metadata: Optional[Dict[str, str]] = None,
    data_classification: Optional[str] = None,
    jurisdiction: Optional[str] = None,
    label: Optional[str] = None,
    egress_profile: Optional[str] = None,
    cdp_kind: Optional[str] = None,
    declare_activity: bool = False,
    idempotency_key: Optional[str] = None,
) -> Tuple[Dict[str, bytes], CdpAccess]

One-shot lifecycle: create → upload → execute → download → destroy. The create arguments go to create() unchanged; one you omit is not sent.

Returns: (outputs, cdp) where:

  • outputs — Dict[str, bytes] mapping output filename → content.
  • cdp — CdpAccess with .full() and .to_dict() (the full proof) and .verification() (the summary projection with no per-step chain).

Raises: ExecutionError if the customer entrypoint exits non-zero; .cdp holds the AuditProof when run()'s own destroy after that exit succeeds, and is None otherwise. Any other error, a GoneError at the end of the capsule's lifetime among them, is raised unchanged after run() tries to destroy the capsule; a NanorixError carries capsule_id, and cdp when that destroy succeeds.

Example (Pattern 3, single-shot extraction):

outputs, cdp = client.capsules.run(
    capsulefile="cf_aB3dE9xQ",
    inputs={"input.pdf": open("test.pdf", "rb").read()},
    metadata={"matter_id": "ACME-001"},
    data_classification="PII",
)
print(outputs["extraction.json"][:200])
print("AuditProof id:", cdp.full().id)
print("final_hash:", cdp.full().final_hash)

batch(...) → BatchResult

Anthropic-Batches-shape batch processing. Per-record custom_id discipline + RFC 6962 Merkle-root computed client-side for byte-equivalent verifier replay.

def batch(
    self,
    *,
    capsulefile: str,
    records: Iterable[Dict[str, Any]],
    on_record: Optional[Callable[[BatchRecord], None]] = None,
    record_id_field: str = "custom_id",
    on_record_error: str = "fail_isolated",   # or "abort_batch"
    max_lifetime_seconds: Optional[int] = None,
    metadata: Optional[Dict[str, str]] = None,
    timeout: Optional[int] = None,
    data_classification: Optional[str] = None,
    jurisdiction: Optional[str] = None,
) -> BatchResult

Returns: BatchResult with .merkle_root, .audit_proof, .records (per-record outcomes), .success_count, .error_count.

The customer entrypoint reads /data/input/records.jsonl (one JSON per line, each carrying custom_id) and writes /data/output/results.jsonl with {custom_id, status: "succeeded"|"errored", output, error_code, error_message}.

Use for: Pattern 4 / 6 (claims, e-discovery, batch extraction).

session(...) → SessionResult

LangGraph-shape session-mode for stateful multi-capsule reasoning chains. Customer-managed encrypted state continuity via parent_cdp_id chain.

def session(
    self,
    *,
    capsulefile: str,
    session_id: str,
    parent_cdp_id: Optional[str] = None,
    initial_state: Optional[bytes] = None,
    max_lifetime_seconds: Optional[int] = None,
    metadata: Optional[Dict[str, str]] = None,
    timeout: Optional[int] = None,
    data_classification: Optional[str] = None,
    jurisdiction: Optional[str] = None,
) -> SessionResult

Returns: SessionResult with .cdp, .state_output_bytes, .parent_cdp_id.

The customer entrypoint reads /data/input/state.bin and writes /data/output/state.bin. Customer is responsible for KMS-encryption of state bytes BEFORE upload and AFTER download. Use for: Pattern 2 (long-running agent), Pattern 4 (multi-step reasoning).

list() / get(id)

list() → CapsuleList (paginated). get(id) → Capsule model.

LiveCapsule workspace methods

LiveCapsule is the handle returned by create(). Methods:

Method Maps to
.id (property) capsule id
.status (property) current status
.upload(filename, data) POST /v1/capsules/:id/upload?filename=...
.execute(command=None, *, timeout=None) POST /v1/capsules/:id/exec
.list_outputs() GET /v1/capsules/:id/output
.download(filename) GET /v1/capsules/:id/output/:filename
.destroy() → CdpAccess DELETE /v1/capsules/:id
.refresh() → LiveCapsule GET /v1/capsules/:id

Workspace-mode example (capsule stays alive across multiple exec calls):

capsule = client.capsules.create(capsulefile="cf_aB3dE9xQ")
capsule.upload("input.pdf", pdf_bytes)
result = capsule.execute(command="python /data/input/capsulefile/main.py", timeout=60)
print(result.stdout)

# Iterate without re-uploading
result2 = capsule.execute(command="python /data/input/capsulefile/main.py --verbose")

# Destroy and get the AuditProof
cdp = capsule.destroy()
print(cdp.full().final_hash)

client.cdp (alias: client.audit_proofs)

Class: CdpResource / AsyncCdpResource.

def get(self, capsule_id: str) -> CdpAccess
def verify(self, capsule_id: str) -> AuditProof   # the verification proof object

get() retrieves the full proof for a destroyed capsule (GET /v1/capsules/:id/cdp); verify() retrieves the AuditProof summary projection (GET /v1/capsules/:id/cdp/verify?format=presentation). For the canonical offline-verifiable document, use nanorix.debug.download_auditproof or fetch the endpoint without the format parameter.

CdpAccess exposes:

  • .full() → CdpDocument — the full proof, the document that verifies offline. It carries the capsule's activity trail (uploaded and downloaded file names; commands only as hashes) and your metadata (not covered by the signature), as a typed model.
  • .verification() → AuditProof — the summary projection (aggregate counts, document_hash, attestation, your metadata and the capsule ID; no file names or per-step chain). It has no hash chain, so the offline verifier cannot check it; POST /v1/verify checks it with a reduced scope.
  • .to_dict() → dict — the full proof as a dictionary. Write it to a file: that file is what nanorix.verifier.verify(), the nanorix-verify CLI and nanorix.io/verify accept.
  • .verify_url → str — the verifier page, https://nanorix.io/verify/. It does not open a proof by ID; drop the saved proof file into it.
  • .id — the capsule ID. The proof's own fields (attestation, chain, final_hash and the rest) are in .to_dict(); document_hash is on .verification().

client.audit_proofs is the brand-aligned alias; both names point at the same resource and will coexist forever for forever-stability.


client.egress_profiles

Class: EgressProfiles / AsyncEgressProfiles. Tier: Developer, Team and Enterprise: the API refuses create, update and add_rule on a Free account. On a Developer account create refuses a second profile; Team and Enterprise accounts can create more. create, update, delete, add_rule and remove_rule are for organization admins only; list, get and list_rules are open to every member. Naming a profile on capsules.create(egress_profile=...) is for Team and Enterprise accounts; the API looks the profile up by name.

client.egress_profiles.create(name="...", description="...")
client.egress_profiles.list()
client.egress_profiles.get(profile_id)
client.egress_profiles.update(profile_id, name=None, description=None)
client.egress_profiles.delete(profile_id)
client.egress_profiles.add_rule(profile_id, "api.example.com", port=443, description=None)
client.egress_profiles.list_rules(profile_id)
client.egress_profiles.remove_rule(profile_id, rule_id)

add_rule takes profile_id and domain_pattern (an exact host name, a leading-dot wildcard such as ".example.com", or an IP address, a private one only where the deployment allows private destinations) by position or name; port (default 443) and description are keyword-only, as are create's description and update's name and description. For the patterns the API refuses, see the API reference for POST /v1/egress/profiles/:id/rules.

Maps to: /v1/egress/profiles/....


client.webhooks

Class: Webhooks / AsyncWebhooks.

client.webhooks.create(url="https://...", events=["cdp.generated"], description="...")
client.webhooks.list()
client.webhooks.get(webhook_id)
client.webhooks.update(webhook_id, url=None, events=None, description=None, active=None)
client.webhooks.delete(webhook_id)
client.webhooks.test(webhook_id)
client.webhooks.deliveries(webhook_id)

The secret returned from create() is shown once. Use Webhook.verify_signature() from nanorix.resources.webhooks in your handler; it returns False when the signature does not match or the timestamp is more than five minutes old.

from nanorix.resources.webhooks import Webhook

if not Webhook.verify_signature(
    payload=request.body,                                  # raw body, bytes
    signature=request.headers["X-Nanorix-Signature"],      # "sha256=<hex>"
    secret=os.environ["NANORIX_WEBHOOK_SECRET"],
    timestamp=int(request.headers["X-Nanorix-Timestamp"]),  # Unix seconds
):
    return 401

Maps to: /v1/webhooks/.... Full event-type catalog at integrations/webhooks.md.


client.usage

Class: Usage / AsyncUsage.

client.usage.summary(billing_cycle: Optional[str] = None) -> UsageSummary
client.usage.estimate() -> Dict[str, Any]
client.usage.list_items(billing_cycle=None, **filters) -> Iterator[UsageItem]
client.usage.export_csv(billing_cycle=None, **filters) -> bytes

list_items() yields UsageItem records (paginated automatically). export_csv() returns the raw CSV bytes — same shape as the API's /v1/usage/items.csv.

Maps to: /v1/usage/....


nanorix.helpers

Module Exports
nanorix.helpers.signer Ed25519FileKey, sign_activity_event, verify_event_attestation, EventAttestation — customer-side Ed25519 signing of ActivityEvents
nanorix.helpers.checkpoint_saver NanorixCheckpointSaver — LangGraph checkpoint saver that writes to an ArtifactStorage you supply (not re-exported from nanorix.helpers)
nanorix.helpers.activity_events emit_tool_call_attempted and the other emit_* writers — append events to the activity record file inside the capsule
from nanorix.helpers.signer import Ed25519FileKey, sign_activity_event

signer = Ed25519FileKey("signing_key.pem")  # a PEM Ed25519 private key; Ed25519FileKey.generate(path) writes one for tests
event = {"event": "tool_call_attempted", "tool_call_id": "call-1", "tool_name": "search"}
attestation = sign_activity_event(signer, event, event_id="evt-001")
print(attestation.to_wire_dict())

nanorix.verifier

from pathlib import Path

from nanorix.verifier import TrustChain, VerifierPolicy, verify_auditproof

# Pass the file's bytes, not json.load output: a parsed dict has lost the
# original bytes and the earlier copies of a repeated key, so a document the
# reference verifier refuses can verify on that route.
proof = Path("auditproof.json").read_bytes()

# The key list and the identity fingerprint that must have signed it. For Nanorix's own
# authority: https://verify.nanorix.io/.well-known/trust-chain.json and
# https://verify.nanorix.io/.well-known/identity.txt (confirm it through a channel you trust).
with open("trust-chain.json", "rb") as f, open("identity.txt") as pin:
    chain = TrustChain.from_key_list(f.read(), pin.read().strip())

result = verify_auditproof(
    proof,
    policy=VerifierPolicy(
        trust_chain=chain,
        reject_diagnostic=True,
        required_region="us-central1",
    ),
)

# Gate on the status, never on `valid`: `valid` is also true at stage 7
# (not_anchored), where the signature checks only against the key the proof carries.
if result.status != "verified":
    print("status:", result.status)  # "not_anchored" or "not_verified"
    print("stage_reached:", result.stage_reached)
    if result.failure_reason is not None:
        print("failure:", result.failure_reason.type)

valid is true when the chain and the signature hold under the key used, and on its own says nothing about who signed. It is deprecated: reading it raises a FutureWarning. Read result.status ("verified" only at stage 8) or result.ok; verify()'s result carries the same two.

reject_diagnostic=True refuses, at stage 2 with diagnostic_proof_refused, an AuditProof whose signed activity trail records diagnostic mode (a diagnostic_mode_enabled event), and every AuditProof whose activity is unsigned, which cannot show that the proof was not run in diagnostic mode: cdp_version 1.0, which signs only final_hash, or 2.1 or 2.2 without a signature. Only a verified result (stage 8, with trust_chain) ties the trail to a key in the pinned key list; at stage 7 the key is the one the proof carries.

required_region is compared with the region on the capsule_started activity event (signed on 2.1 and 2.2). Under it every AuditProof whose region is unsigned is refused at stage 2 with region_mismatch and an empty actual: cdp_version 1.0, which signs only final_hash, or 2.1 or 2.2 without a signature. Only a verified result (stage 8, with trust_chain) ties the region to a key in the pinned key list.

Cross-impl byte-equivalence: verify_auditproof() produces output byte-equivalent to the Rust nanorix-verify and Go auditproof-verifier-go CLIs on the corpus wire form (valid, failure_reason, stage_reached) of the reference corpus, given the file's bytes. The FailureReason enum is identical across all five paths (Rust, Go, Python, TypeScript, server-side POST /v1/verify).

The failure-reason enum is closed-set and byte-equivalent across all verifier implementations.


nanorix.compliance

Framework-typed metadata builders that produce Dict[str, str] payloads for metadata=... arguments above. Customer-declared context that is carried in the AuditProof's metadata as given; the capsule_started event (signed on 2.1 and 2.2) carries its metadata_hash; no shipped verifier compares the two.

from nanorix.compliance import HipaaContext  # also GdprContext, Soc2Context

metadata = HipaaContext(
    covered_entity="ce-001",
    minimum_necessary_purpose="treatment",
    business_associate="ba-002",
).to_metadata()

outputs, cdp = client.capsules.run(
    capsulefile="cf_...",
    inputs={"input.pdf": pdf_bytes},
    metadata=metadata,
)

The contexts cover the framework-typed surface that procurement teams expect to see traced in the AuditProof. The metadata is customer-defined; the compliance helpers are Nanorix-published convenience builders, not Nanorix-imposed schemas.


Request middleware

nanorix.integrations.fastapi_middleware.NanorixMiddleware (FastAPI and Starlette, pip install 'nanorix[fastapi]') and nanorix.integrations.flask_middleware.NanorixMiddleware (Flask, pip install 'nanorix[flask]') create one capsule for each request they wrap. The handler runs in your own process, not in the capsule. The AuditProof carries the capsule's metadata as given, and for these middleware it holds:

Key Value
sdk_wrapper_kind "middleware"
nanorix:framework the framework= you gave, or the framework_per_route= label of the longest prefix the request path starts with
nanorix:framework_version framework_version=, when you pass one
sdk_agent_id agent_id=, when you pass one
sdk_request_method the HTTP method, in plain text
sdk_request_path by default, sha512: followed by the lowercase hex SHA-512 of the UTF-8 bytes of the request path, cut at its first ? or #. With record_raw_path=True, that cut path itself; a path over 256 bytes, or one containing ~sha512:, becomes at most its first 120 bytes plus ~sha512: and its SHA-512

The path is the one the framework gives: request.url.path on Starlette, request.path on Flask. Request and response bodies, the query string, the fragment, headers, status and latency do not reach the AuditProof.

import hashlib

from nanorix.integrations.fastapi_middleware import NanorixMiddleware

app.add_middleware(NanorixMiddleware, client=client, framework="HIPAA", capsulefile="cf_...")
# A request to /patients/MRN123?ssn=... puts this value under sdk_request_path:
"sha512:" + hashlib.sha512("/patients/MRN123".encode("utf-8")).hexdigest()

# Opt in to the path itself. The query string and fragment are still cut; a
# percent-encoded ? or # is not cut, except on Flask, which decodes it,
# and on FastAPI with Starlette before 1.9.
app.add_middleware(NanorixMiddleware, client=client, framework="HIPAA",
                   capsulefile="cf_...", record_raw_path=True)

The digest keeps the path out of the AuditProof, but it does not make the path secret: anyone who can list the possible paths, such as every short record number, can hash each one and find the match. Given the same path string (valid Unicode), the Python and TypeScript SDKs write byte-identical values. The frameworks hand over that string differently, though: FastAPI and Flask give the path percent-decoded, while Express and Next.js keep its percent-escapes; Express and Flask give it relative to where the app or middleware is mounted, and Next.js without its basePath and locale; and a percent-encoded ? or # is not cut, except on Flask, which decodes it, and on FastAPI with Starlette before 1.9. A path with a percent-escape, which includes every non-ASCII path, can therefore get different values from different middleware.

A request that gets a capsule can also write an ActivityEvent to your app's own activity file (/data/activity_events.jsonl unless NANORIX_ACTIVITY_BUFFER_PATH or NANORIX_BUFFER_PATH is set); a failed write drops it, and the first failed write of each middleware raises a RuntimeWarning that names the path. A request without a capsule writes none: on FastAPI a failed capsule create fails the request, and Flask runs the request without one. When the handler raises or returns a 5xx status, the event holds the request method and path in plain text, without the query string, and for a raised exception its message; Flask can write two events for one exception.


Async client

nanorix.AsyncClient exposes the same surface as Client with async def coroutines and AsyncIterator for paginated endpoints:

import os

import nanorix

async with nanorix.AsyncClient(api_key=os.environ["NANORIX_API_KEY"]) as client:
    cf = await client.capsulefiles.create(...)
    outputs, cdp = await client.capsules.run(capsulefile=cf.id, inputs=...)

    async for cap in client.capsules.list():
        print(cap.id, cap.status)

End-to-end mapping to the API surface

Every Python SDK method maps to one or more API endpoints documented in api-reference.md:

Python method API endpoint
Client.health() GET /v1/health
client.capsulefiles.create() POST /v1/capsulefiles (+ files + finalize)
client.capsulefiles.list() GET /v1/capsulefiles
client.capsulefiles.get(id) GET /v1/capsulefiles/:id
client.capsulefiles.delete(id) DELETE /v1/capsulefiles/:id
client.capsules.create() POST /v1/capsules
LiveCapsule.upload() POST /v1/capsules/:id/upload
LiveCapsule.execute() POST /v1/capsules/:id/exec
LiveCapsule.list_outputs() GET /v1/capsules/:id/output
LiveCapsule.download() GET /v1/capsules/:id/output/:filename
LiveCapsule.destroy() DELETE /v1/capsules/:id
client.capsules.list() GET /v1/capsules
client.capsules.get(id) GET /v1/capsules/:id
client.cdp.get() / client.audit_proofs.get() GET /v1/capsules/:id/cdp
client.cdp.verify() GET /v1/capsules/:id/cdp/verify
client.egress_profiles.* /v1/egress/profiles/...
client.webhooks.* /v1/webhooks/...
client.usage.* /v1/usage/...
nanorix.verifier.verify_auditproof() offline (no network)

client.capsules.run(), .batch(), and .session() are SDK-side compositions over create + upload + exec + destroy, not separate endpoints.


Cross-references

Forever-Standard discipline. Every public Python SDK method, every keyword argument, every exception class, every model field is permanent. New methods / args / classes / fields are additive only. The internal-vs-external naming alias (client.cdp ↔ client.audit_proofs) is structural, not transitional — both names exist forever.