Python SDK

Use the Python SDK to moderate content, manage assets and handle events from your server, with a thread-safe synchronous client, an asynchronous client, streamed transfers and typed results for every method. It requires Python 3.10 or later and has no runtime dependencies. The Python SDK reference lists every client option and method in detail.

Install

python -m pip install calmlens

See Versioning and support for what each version change means and where to find the changelog.

Moderate content

Keep credentials on your server. Create an API key and copy your project ID as described in Authentication. Without arguments, the client reads CALMLENS_API_KEY and CALMLENS_PROJECT_ID from the environment. assets.create() returns without waiting for the decision; assets.classify() and text.classify() wait for it. Documents, websites, audio and video always run in the background. See Waiting for the decision for supported content, webhooks and polling.

from calmlens import CalmLensServerClient

client = CalmLensServerClient()
asset = client.text.classify(text="Great photo!", external_id="comment-42")
if asset.classification.moderation.decision == "allowed":
    print("Publish", asset.id)

Methods take snake_case keyword arguments, such as client.assets.retrieve(asset_id=asset_id); the options the API requires are required arguments. Dicts passed as values, such as processing_options={"retain_content": True}, use snake_case keys too, typed as ...Params dicts such as ProcessingParams. Transform options keep the CDN's names, and metadata values are sent as given. In updates, pass None to clear a nullable field (or, for assets.move, to move to the project root), and omit a field to leave it unchanged.

Publish allowed content normally and limited content with reduced reach. Serve age-restricted content only to viewers your app allows, by passing viewer_claims={"age_confirmed": True} to the CDN methods; a signed URL or your API key alone doesn't serve it. See Age-restricted assets. Treat a status you don't recognise as not allowed, and treat failed requests the same way. See Reading classification results and Policies and actions.

Classification results

Methods return typed result objects, such as Asset and AssetClassification, read through snake_case attributes: asset.classification.moderation.decision. Nested objects, lists and maps of objects are result objects too, and a union becomes the variant its tag names, such as EvaluatedCategoryResult for a category result whose status is evaluated. Moderation fields such as classification.moderation.categories are None until moderation decides, and feature results such as classification.ocr are None until they have run. metadata and tags are always lists, empty when there are none. A field the API leaves out reads as None; "externalId" in asset tells whether the API sent it. Status and other enum values are plain strings, so a value added in a newer API version doesn't break your code.

Result objects are read-only. asset["classification"] reads a field by its API name, a field this SDK version doesn't declare stays readable, and asset.to_dict() returns the API's JSON, such as for storing it or sending it on. CalmLensObject.construct_from(json) turns that JSON back into an object. Every result also has last_response, the status, headers and request_id of the response it came from.

Waiting for a decision

assets.wait_for_decision(asset_id=..., timeout=60) retrieves the asset at once, then again after 0.5 seconds, waiting 1.5 times longer each time, up to 2 seconds between checks, until its classification.status is completed or failed, and returns it. If there is no decision within timeout seconds (default 60), it raises CalmLensTimeoutError with code sdk/timeout, and details holds the assetId and the last classificationStatus and moderationDecision. To stop waiting sooner, pass a shorter timeout.

Uploads

with open("photo.jpg", "rb") as file:
    queued = client.assets.create(
        name="photo.jpg",
        content={"data": file, "type": "image/jpeg"},
        visibility="private",
        processing_options={"retain_content": True},
    )

# Wait for the decision, retrieve it later, or respond to an asset.allowed or asset.blocked webhook.
asset = client.assets.wait_for_decision(asset_id=queued.id, timeout=30)
if asset.classification.moderation.decision == "allowed":
    signed = client.cdn.sign_asset_url(asset_id=asset.id, resource="original", expires_in=60)
    print(signed.url)

data accepts bytes or a binary file object. Files are streamed in chunks rather than read into memory, and their size is measured automatically. A stream that can't seek, such as a pipe, is sent to its end in chunks; pass its size_in_bytes when you know it (multipart parts need it). The timeout applies to a silent connection, not to the whole transfer, so large uploads and downloads are not cut off.

To upload from a link, pass url= instead of content: CalmLens downloads the file, up to 10 MiB for images and 20 MiB for other files. For multipart limits and sequential uploads, see Multipart uploads. Retain content only when you need previews, transforms or CDN delivery.

Each upload must be a supported type within that type's size and duration limits; see Asset types and limits. Documents are PDF, DOCX, DOC, RTF and ODT files, spreadsheets (XLSX, XLSM, XLS, ODS) and presentations (PPTX, PPTM, PPT, ODP). Keynote and Numbers files are refused with 415 upload/unsupported-type.

Metadata is a list of {id, value} items, such as metadata=[{"id": "campaign.id", "value": "launch-2026"}]. The value can be any JSON value. To filter or group assets by an item in the portal, use the ID of a metadata field defined there; see Asset metadata.

Upload presets

Pass upload_preset_id= on assets.create and assets.classify to apply an upload preset's folder, visibility, file types, size limit, moderation policy and processing options. To let a browser upload through a preset that requires tokens, sign a single-use token on your server with client.upload_tokens.sign(upload_preset_id=...). Signing happens locally with your API key and makes no request.

CDN methods

To upload a public image for delivery, retain its content and use an API key with Create assets (assets:create) and Share assets (assets:share). Keep the image unpublished until moderation allows it, then use its rendered CDN resource. For a private image, keep visibility private and sign its URL on your server with a key that has Share assets. See Authentication.

Fetch retained content directly from your backend with client.cdn.serve():

with client.cdn.serve(asset_id="asset_e5Gm2Rk8XqT3wLp9VbN4", resource="original") as response:
    if not 200 <= response.status < 300:
        raise RuntimeError(f"CDN returned HTTP {response.status}")
    content = response.read()
print(len(content))

The response contains raw content bytes, not the asset report. Check the response status before using the body; for text assets (such as comments sent with text.classify), decode the body as text. The request uses your server API key; private reads require Download assets permission. For private content in browsers, sign the asset URL with client.cdn.sign_asset_url() (see Signed asset URLs).

For a browser download of the stored file, sign the URL for the original resource:

signed = client.cdn.sign_asset_url(asset_id=asset.id, resource="original", expires_in=60)
print(signed.url)

The URL is signed for resource and ends in it. Only a URL signed for the original serves the stored file; one signed for another resource, or without a resource, serves every other resource beneath its grant. Without a resource, the returned URL is the base asset URL: append a resource path before fetching it.

Upload with processing_options={"retain_content": True} to retain content. The CDN delivers by the current classification.moderation.decision, and still requires available content and authorised access. See Delivery while moderation runs.

Methods

See the reference for each method's options and examples.

MethodPurpose
text.classify(text=..., ...)Classify text and wait for the decision.
assets.create(...)Upload content and return without waiting for the decision.
assets.classify(...)Upload content and wait for the decision where supported.
assets.upload_part(...)Send the next part of a multipart upload.
assets.retrieve(asset_id=...)Fetch one asset.
assets.retrieve_by_external_id(external_id=...)Fetch the asset with that externalId.
assets.wait_for_decision(asset_id=..., timeout=...)Retrieve an asset until it is completed or failed; see Waiting for a decision.
assets.list_timeline(asset_id=..., cursor=..., page_size=...) / assets.iter_timeline(asset_id=...)Page through an audio or video asset's findings timeline Preview, in time order.
assets.list(...) / assets.iter(...)List one page of assets, or iterate over every matching asset.
assets.search(query=..., ...)Search assets by keyword or meaning; see Asset search.
assets.list_children(asset_id=...) / assets.iter_children(asset_id=...)List an asset's extracted children.
assets.update(asset_id=..., ...)Update asset fields.
assets.move(asset_id=..., folder_id=...)Move an asset to a folder, or to the project root with None.
assets.retry(asset_id=...)Retry an eligible processing failure.
assets.decide(asset_id=..., decision=..., note=...)Record a reviewer's decision (allowed, limited, age-restricted, blocked or purged) with a required note. An asset pending moderation can only be blocked or purged, and purging needs confirm_purge=True; see POST /assets/:assetId/decision.
assets.request_review(asset_id=..., note=...)Send an asset to the human review queue, such as when a user reports it.
assets.remove_content(asset_id=...)Remove stored content and keep the asset record and report.
assets.delete(asset_id=...)Delete the asset record and its content.
assets.batch(asset_ids=..., operation=...)Delete up to 500 assets ("delete") or remove their stored content ("remove-content") in one queued request; see POST /projects/:projectId/assets/batch.
folders.list(), folders.iter(), folders.retrieve(), folders.create(), folders.update(), folders.move(), folders.delete()Manage folders. folders.list() returns a page of up to 50 root folders by name by default, with the ancestors needed to show their paths. Only empty folders can be deleted.
hash_lists.list(), hash_lists.iter(), hash_lists.retrieve(), hash_lists.create(), hash_lists.update(), hash_lists.delete()Manage hash lists that image uploads are compared with.
hash_lists.list_entries(), hash_lists.iter_entries(), hash_lists.add_entry(), hash_lists.remove_entry()Manage the hashes in a hash list.
policies.list(), policies.iter(), policies.retrieve(), policies.create(), policies.update(), policies.reset(), policies.upgrade(), policies.set_automatic_updates(), policies.delete()Manage the organisation's moderation policies; see Policies.
policies.retrieve_assigned() / policies.assign(policy_id=...)Read or choose the policy the project moderates with.
events.list(...) / events.iter_pages(...) / events.iter(...)Read one page of the project event feed, follow its cursor page by page, or iterate over its events.
lenses.list(), lenses.iter(), lenses.create(), lenses.retrieve(), lenses.update(), lenses.delete()Manage the project's lenses.
ensure_lens(...) / ensure_lenses(...)Create lenses, or change them to the definitions sent, by identifier.
cdn.get_asset_url(...) / cdn.serve(...)Build a CDN URL, or stream content.
cdn.sign_asset_url(asset_id=..., ...)Sign a private asset's URL.
cdn.get_asset_info(url)Read an asset URL's display info.
upload_tokens.sign(upload_preset_id=..., expires_in=...)Sign an upload token locally, without a request.

Pagination

Every list returns a page: a ListObject with items, has_more and next_cursor, which you can iterate and len() for its own items. page.auto_paging_iter() yields its items and then each following page's, requesting them as you go. To page by hand, omit cursor for the first page, then pass the page's next_cursor as cursor, with the same filters, until it is None; set the page size with page_size. Lists of assets, hash lists, hash list entries, policies and lenses take sort: a comma-separated list of createdAt and id, each descending when prefixed with -, such as sort="-createdAt,id". Folders sort by name (the default) or createdAt. Each list has an iterator that fetches the pages for you: assets.iter, assets.iter_children, assets.iter_timeline, folders.iter, hash_lists.iter, hash_lists.iter_entries, policies.iter and lenses.iter.

page = client.folders.list(parent_id=folder_id, page_size=50)
for folder in page.auto_paging_iter():
    print(folder.name)

for asset in client.assets.iter(filter=f"folderId=={folder_id}", sort="createdAt"):
    print(asset.name)

The event feed's next_cursor is never None. events.list() without a cursor returns no events and a next_cursor for the current time; later calls return the events after it. Use events.iter_pages to read pending pages and save the last next_cursor. See Reading the feed for cursor semantics.

cursor = client.events.list().next_cursor  # no events; starts from now
for page in client.events.iter_pages(cursor=cursor, page_size=50):
    for event in page:
        print(event.type, [(fact.key, fact.value) for fact in event.facts])
    cursor = page.next_cursor

The iterators, including auto_paging_iter, events.iter_pages and events.iter, raise sdk/invalid-response, with the cursor in details["cursor"], rather than looping when a page with more to follow repeats a cursor they already sent.

Concurrency and async code

One client is safe to share between threads, and reusing it keeps connections open between calls. In a forked worker process, such as a gunicorn or Celery worker, the client opens new connections rather than sharing the parent's.

From async code, use AsyncCalmLensServerClient. It takes the same arguments and has the same methods, awaitable, with async for over iterators and async with for CDN downloads and the client itself. It needs no extra packages: each call runs in a worker thread, so the event loop never blocks.

from calmlens import AsyncCalmLensServerClient

async with AsyncCalmLensServerClient() as client:
    asset = await client.text.classify(text=body, external_id=comment_id)
    async for event in client.events.iter(cursor=cursor):
        print(event.type)

A page from await client.assets.list() walks the following pages with async for asset in page.auto_paging_iter_async(). AsyncCalmLensServerClient.from_client(client) wraps a client you already have, such as the offline mock.

Errors and retries

Every failure raises CalmLensError or one of its subclasses, except that passing the webhook helpers anything other than the raw str or bytes body, such as a parsed dict, raises TypeError, and a call without a required argument raises Python's own TypeError. Each class is also an instance of the classes above it:

ClassRaised for
CalmLensAPIErrorAPI error responses, and a proxy's error page in front of the API
CalmLensBadRequestError, CalmLensAuthenticationError, CalmLensPermissionDeniedError, CalmLensNotFoundError, CalmLensConflictError, CalmLensPayloadTooLargeError, CalmLensUnprocessableEntityError, CalmLensRateLimitError, CalmLensServerErrorAPI errors with HTTP 400, 401, 403, 404, 409, 413, 422, 429, and 500 or above; each is a CalmLensAPIError
CalmLensConnectionErrorNetwork failures: no complete response arrived
CalmLensTimeoutErrorA request's timeout, or assets.wait_for_decision's deadline
CalmLensCancelledErrorA cancelled AsyncCalmLensServerClient call; also an asyncio.CancelledError
CalmLensInvalidArgumentErrorInvalid arguments, detected before anything is sent; also a ValueError
CalmLensConfigurationErrorInvalid client configuration; a CalmLensInvalidArgumentError
CalmLensInvalidResponseErrorA response that isn't what the method returns, or one over max_response_bytes
CalmLensWebhookVerificationErrorWebhook deliveries that fail verification or aren't CalmLens events

Each error has a stable code (constants in calmlens.error_codes), the HTTP status, the request_id to quote to support (the response's X-Request-Id header, or the error body's requestId), the API's details object, retry_after, headers, the response body as text (up to 16,384 characters, such as a proxy's HTML page; it isn't part of str(error)), and the is_not_found, is_retryable and is_local helpers. is_local is True for errors the SDK raised without a response, such as invalid arguments, content it refuses before sending, timeouts and connection failures; they have the code the API would use, with status and request_id set to None. is_retryable is True for network failures and timeouts (including assets.wait_for_decision's sdk/timeout), 409 idempotency/request-in-progress, and HTTP 429, 500, 502, 503 and 504, whatever the error's class.

from calmlens import CalmLensAPIError, CalmLensNotFoundError

try:
    asset = client.assets.retrieve(asset_id="asset_e5Gm2Rk8XqT3wLp9VbN4")
except CalmLensNotFoundError:
    asset = None
except CalmLensAPIError as error:
    print(error.code, error.status, error.request_id)
    raise
FailureWhat the SDK doesWhat you do
Network failure or timeoutRetries reads and uploads up to max_retries times (default 2), each time waiting between half and all of a delay that starts at 0.5 seconds and doubles up to 8 secondsOnce retries run out, retry later: is_retryable is True
429, 500, 502, 503, 504 or 409 idempotency/request-in-progressRetries the same requests, waiting for Retry-After (seconds or a date; 0 retries at once) when the API sends oneA Retry-After over 60 seconds is raised to you instead: wait, then retry
assets.wait_for_decision runs out of timeRaises a CalmLensTimeoutError with sdk/timeoutWait again, or rely on a webhook
Failure of another write, such as assets.update or assets.deleteNot retriedRetry only when repeating the change is safe
Upload from a stream that can't seek, such as a pipeSent onceUpload again from the start
Upload retried from another processEach call sends a new Idempotency-Key, reused for its own retriesPass the same options={"idempotency_key": ...}
RedirectNot followed; raises sdk/http-error with its statusCheck base_url and cdn_base_url
cdn.serve failureRetries the same failures. Once retries run out, returns the last error response instead of raising; a network failure or timeout still raisesCheck the response status
SettingDefaultLimits
timeout120 secondsInactivity on a connection, not the whole transfer
upload_timeouttimeoutInactivity while sending file content and multipart parts
connect_timeout10 secondsOpening a connection
max_response_bytes32 MiBThe API response body the client reads
part_size_bytes8 MiBContent larger than this is uploaded in parts of this size, from 5 to 64 MiB

Set them, and max_retries, on the client. client.with_options(timeout=300) returns a client sharing the same connections with another timeout, upload_timeout, max_retries or max_response_bytes. For one call, pass options, as described in Request options. See Retries and idempotency for which requests are retried, and Retrying requests safely.

Request options

Every method takes options, a RequestOptions dict for that call: timeout, deadline_ms (to bound the whole call, retries included), max_retries, idempotency_key, headers, and extra_query and extra_body for parameters this SDK version doesn't know. Every request the call sends uses them, including the parts of an upload, the checks of wait_for_decision and the later pages of an iterator.

asset = client.assets.update(
    asset_id="asset_e5Gm2Rk8XqT3wLp9VbN4",
    name="Cover photo",
    options={"timeout": 10, "max_retries": 0, "idempotency_key": "rename-cover-1"},
)
print(asset.last_response.request_id)

For an endpoint this SDK version has no method for, client.request(method, path, query=..., body=..., headers=...) sends the request with your API key, retries and error classes. path is relative to base_url; a JSON object comes back as a result object.

Client setup

Without arguments, the client reads CALMLENS_API_KEY, CALMLENS_PROJECT_ID and CALMLENS_BASE_URL from the environment. Other options:

OptionUse
app_info={"name": ..., "version": ..., "url": ...}Adds your application to the User-Agent header, as name/version (url)
default_headersHeaders sent with every request; a call's options["headers"] take precedence
ssl_contextThe ssl.SSLContext the client verifies TLS with, such as one loading your organisation's CA bundle
proxyA proxy URL for every request, instead of the HTTPS_PROXY, HTTP_PROXY and NO_PROXY environment variables
transportYour own HTTP stack: a callable that sends a TransportRequest (method, url, headers, body) and returns a response with status, headers and read()
loggerThe logging.Logger the client logs requests to; the default is the calmlens logger
on_attemptCalled with a RequestAttempt (operation, method, path, attempt, delay, status, request_id, duration) after every attempt at a request, retries included

The client logs one INFO line per request and a DEBUG line for each attempt it retries. Set CALMLENS_LOG=info or CALMLENS_LOG=debug to print them to standard error. Logs and attempts never include your API key, request or response bodies, upload tokens or signed URLs.

Webhooks

Verify the exact raw request body, then parse it, with parse_webhook_event. It accepts only the raw str or bytes body: a body that was parsed and serialised again rarely has the same bytes, so the signature would not match.

import os
from calmlens import CalmLensWebhookVerificationError, error_codes, parse_webhook_event

def handle_webhook(raw_body: bytes, headers) -> int:
    try:
        event = parse_webhook_event(raw_body, headers=headers, secret=os.environ["CALMLENS_WEBHOOK_SECRET"])
    except CalmLensWebhookVerificationError as error:
        # A forged or stale delivery is 401; a verified body that is not an event is 400.
        return 401 if error.code == error_codes.SDK_INVALID_WEBHOOK_SIGNATURE else 400
    # Queue the work, keyed by event.id, then respond quickly.
    return 204

Pass the raw body your framework received:

FrameworkRaw bodyHeaders
Flaskrequest.get_data()request.headers
Djangorequest.body (exempt the view from CSRF)request.headers
FastAPI or Starletteawait request.body() (don't declare a body model)request.headers

verify_webhook_signature takes the same arguments and returns True or False. Both read the x-calmlens-signature and x-calmlens-timestamp headers from headers, by name in any case, joining a header repeated in the request with ,, or take them as signature= and timestamp=. Timestamps more than 5 minutes from the current time are rejected; tolerance_seconds= changes that.

parse_webhook_event raises CalmLensWebhookVerificationError with sdk/invalid-webhook-signature for a missing, wrong or stale signature, and with sdk/invalid-webhook-payload for a verified body that isn't a CalmLens event. The parsed event is a result object with the same fields as an event from events.list: id, project_id, type, severity, title, description, asset_id, asset_sequence, facts and created_at; events carry only the asset's ID, so call client.events.retrieve_asset(event) for the asset as it is now. It keeps fields, event types and fact keys it doesn't know. get_event_fact(event, key) returns one fact's value, or None when the event doesn't carry it, and get_event_facts(event) returns every fact's value by key, such as {"flagged-categories": ["hate"]}; a key repeated in the event keeps its first value. is_test_webhook_event(event) tells a test send from the portal or the CLI from a real event. Deliveries also carry x-calmlens-delivery, which stays the same across a delivery's retries; a redelivery gets a new one, so deduplicate on the event id. See Webhooks.

Deduplicating by event.id stops a redelivery being applied twice, but it doesn't put events in order: a retry can arrive after a later event about the same asset. Store the highest asset_sequence you've applied for each asset, and apply an event only when is_newer_asset_event(event, last_sequence) is true, so a late asset.allowed never undoes a later asset.blocked. See Event order.

Test webhooks locally

Your tests and CI need no CLI: the testing helpers build and sign deliveries offline, so your handler's verification runs unchanged. To forward your project's real events to a handler on your machine, install the calmlens CLI, a standalone executable for macOS, Linux and Windows:

curl -fsSL https://calmlens.com/install.sh | sh

Then run calmlens login and calmlens listen --forward-to <url>. See Local development for Windows, Homebrew, release downloads and npm, sending portal test events through a tunnel, and creating test events with calmlens trigger.

Testing

Use MockCalmLensServerClient from calmlens.testing for offline tests. See Python testing.

Last updated

Cookies on CalmLens

We use essential cookies for sign-in and security. With your permission, functional cookies remember your preferences and Google Analytics measures website use and signups. Optional ad measurement cookies link Google ad clicks to signups. Personalised advertising stays off. Manage cookies