Ruby SDK
Use the Ruby SDK to moderate content, manage assets and handle events from your server. It requires Ruby 3.1 or later and has no runtime dependencies.
Install
gem install calmlensFor Bundler, add gem "calmlens" to your Gemfile. Its RBS signatures type every method's options and every response, so you can check your code with Steep.
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 in the portal; see Authentication for the permissions each call needs. assets.create returns without waiting for the decision; assets.classify and text.classify wait for it. Audio and video always run in the background. See Waiting for the decision for supported content, webhooks and polling.
require 'calmlens'
client = CalmLens::ServerClient.new(api_key: ENV.fetch('CALMLENS_API_KEY'), project_id: ENV.fetch('CALMLENS_PROJECT_ID'))
asset = client.text.classify(text: 'Great photo!', external_id: 'comment-42')
puts "Publish #{asset['id']}" if %w[allowed limited].include?(asset['classification']['moderation']['status'])Options use snake_case; responses are Hashes with the API's field names. snake_case keys are converted at any depth, and camelCase keys are also accepted, so processingOptions: {features: {faceDetection: {enabled: true, ageEstimation: true}}} is the same as processing_options: {features: {face_detection: {enabled: true, age_estimation: true}}}. Keys inside metadata are sent as you wrote them. The type signatures describe options with snake_case Symbol keys; see Types. Every method also takes request_options: for per-call timeouts, retries and idempotency keys; see Request options.
Publish allowed content normally and limited content with reduced reach; see Limited assets. Serve an age-restricted one only to viewers your app allows, by passing viewer_claims: {age_confirmed: true} to the CDN methods or to cdn.sign_asset_url, which add them to the URL; a signed URL or your API key alone doesn't serve it. See Age-restricted assets. Statuses and fields added to the API later are returned unchanged. Treat a status you don't recognise as not allowed. See Reading classification results.
Waiting for a decision
assets.wait_for_decision retrieves the asset at once, then again after 0.5 seconds, waiting 1.5 times longer each time, up to 2 seconds between checks, and returns it once its classification.status is completed or failed. If there's no decision within timeout: seconds (default 60), it raises CalmLens::TimeoutError with code sdk/timeout, and details holds 'assetId' and the last 'classificationStatus' and 'moderationStatus'. To stop waiting early, stop the thread running the call.
queued = client.assets.create(name: 'note.txt', content: {data: 'Hello', type: 'text/plain'})
decided = client.assets.wait_for_decision(asset_id: queued['id'], timeout: 30)Uploads
Uploads accept plain text, base64, a binary String or an IO. An IO is streamed without being read into memory. Files, Tempfiles and StringIOs know their size; a pipe or socket of unknown length is sent with chunked transfer encoding, or pass size_in_bytes: when you know it.
File.open('clip.mp4', 'rb') do |file|
client.assets.create(name: 'clip.mp4', content: {data: file, type: 'video/mp4'})
endContent larger than 8 MiB (part_size_bytes:) that the client can read again, such as a binary String or a File, is uploaded in parts for you: each part is retried on its own, and calling again with the same request_options: {idempotency_key:} resumes an interrupted upload. To send parts yourself, start with part:; whether a multipart upload was started with assets.create (returns without waiting) or assets.classify (waits for the decision) is fixed by the first part, so later parts can come from another process; pass total_size_in_bytes: at the start if you know the file size. See Multipart uploads.
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 and size limit. 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
Fetch retained content directly from your backend with client.cdn.serve:
result = client.cdn.serve(asset_id: "asset_5Gm2Rk8XqT3wLp9VbN4c", resource: "original")
puts resultThe response contains raw content bytes, not the asset report. Check the response status before using the body; for text assets (such as those created by text.classify), decode the body as UTF-8 text. Give cdn.serve a block to stream the body instead of holding it in memory:
File.open('photo.jpg', 'wb') do |file|
client.cdn.serve(asset_id: asset_id) do |response|
raise "CDN returned #{response.status}" unless response.success?
response.each_chunk { |chunk| file.write(chunk) }
end
endThe request uses your server API key; private reads require Download assets permission. For private content in browsers, sign the asset URL with cdn.sign_asset_url instead (see Signed asset URLs).
Upload with processing_options: {keep_content_after_processing: true} to retain content. The CDN delivers by the current classification.moderation.status, and still requires available content and authorised access. See Delivery while moderation runs.
Methods
The Ruby SDK reference lists client settings and each area's options in detail.
| Method | Purpose |
|---|---|
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.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.each_timeline_segment(asset_id:) | Page through an audio or video asset's findings timeline Preview, in time order, or iterate over its segments. |
assets.list(...) / assets.each(...) | List one page of assets, or iterate over every matching asset. filter: 'folderId==fldr_…' lists one folder's assets. |
assets.search(query:, ...) | Search assets by meaning and by name, ID, external ID, description and tags, best match first; see Asset search. |
assets.list_children(asset_id:) / assets.each_child(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 nil. |
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.explain(asset_id:, rerun:) | Fetch the full policy evidence for a decision (which rules and findings produced it), or with rerun: true moderate the asset again under the current policy. |
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 /. |
folders.list, folders.each, 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.each, 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.each_entry, hash_lists.add_entry, hash_lists.remove_entry | Manage the hashes in a hash list. |
policies.list, policies.each, policies.retrieve, policies.retrieve_assigned, policies.create, policies.update, policies.reset, policies.upgrade, policies.set_automatic_updates, policies.delete, policies.assign | Manage the organisation's moderation policies and choose the one the project uses; see Policies. |
events.list(...) / events.each_page(...) / events.each(...) | Read one page of the project event feed, follow its cursor page by page, or iterate over its events. |
ensure_lens(...) / ensure_lenses(...) | Create lenses, or change them to these definitions, by identifier. |
lenses.list, lenses.each, lenses.create, lenses.retrieve, lenses.update, lenses.delete | Manage the project's lenses one by one. |
cdn.get_asset_url(...) / cdn.serve(...) | Build a public asset URL or a resource URL beneath it, or stream content. |
cdn.sign_asset_url(asset_id:, ...) | Sign a private asset's URL for browsers and apps. |
cdn.get_asset_info(url) | Read an asset URL's display info (/info). |
upload_tokens.sign(upload_preset_id:) | Sign an upload token locally, without a request. |
Pagination
Every list returns a cursor page: items, hasMore and nextCursor. Pass a page's nextCursor as cursor:, with the same filters, to fetch the next page, and set its size with page_size: (1 to 100, default 50). Sort with sort:, a comma-separated list of fields, each descending when prefixed with -, such as '-createdAt,id'. Assets, hash lists, hash list entries, policies and lenses sort by createdAt and id; folders by name (the default) or createdAt. Treat the cursor as opaque.
page = client.folders.list(parent_id: folder_id, sort: '-createdAt')
page = client.folders.list(parent_id: folder_id, sort: '-createdAt', cursor: page['nextCursor']) if page['hasMore']Every list has an iterator that fetches pages as you iterate: assets.each, assets.each_child, assets.each_timeline_segment, folders.each, hash_lists.each, hash_lists.each_entry, policies.each, lenses.each, events.each and events.each_page. Without a block they return an Enumerator, so client.assets.each(filter: 'classification.moderation.status==allowed').first(5) requests only the pages it needs.
The event feed's nextCursor is never nil. events.list without cursor: returns no events and a nextCursor for the current time; events.each_page yields the pages after a cursor until hasMore is false. Persist each page's nextCursor once its events are handled. See Reading the feed for event cursors.
cursor = client.events.list['nextCursor'] # no events; starts from now
client.events.each_page(cursor: cursor, page_size: 50) do |page|
page['items'].each { |event| puts event['type'] }
cursor = page['nextCursor']
endErrors and retries
Every error is a CalmLens::Error with code, status, request_id (from X-Request-Id, or the error body's requestId), headers, retry_after (whole seconds), details (the API's details object, such as validation issues, or nil) and the original exception in cause. CalmLens::ErrorCodes lists the API's error codes. Subclasses let you rescue by kind:
| Class | Raised for |
|---|---|
CalmLens::NotFoundError, RateLimitError, ConflictError and the other APIError classes | API error responses |
ConnectionError, TimeoutError | No response arrived; TimeoutError also when wait_for_decision runs out of time |
InvalidArgumentError (sdk/invalid-argument), ConfigurationError (sdk/invalid-config) | Problems found before anything is sent, including an option the method doesn't take, such as a misspelt external_id |
| Failure | What the SDK does | What you do |
|---|---|---|
| Connection failure or timeout | Retries reads, uploads and cdn.serve up to max_retries: times (default 2), waiting 0.5 seconds and twice as long each time after that (up to 8 seconds), half of each wait random | Once retries run out, retry later: retryable? is true |
429, 500, 502, 503, 504 or 409 idempotency/request-in-progress | Retries the same requests, waiting for Retry-After (seconds or an HTTP date) when the API sends one | A Retry-After over 60 seconds is raised to you instead: wait, then retry |
wait_for_decision runs out of time | Raises TimeoutError (sdk/timeout) | Wait again, or rely on a webhook |
Failure of another write, such as assets.update or assets.delete | Retried only when you pass request_options: {idempotency_key: '...'} | Pass a key when repeating the change must be safe |
| Upload from an IO that can't rewind, such as a pipe | Sent once | Upload again from the start |
| Upload retried from another process | Each call sends a new Idempotency-Key, reused for its own retries | Pass request_options: {idempotency_key: '...'} |
| Redirect | Not followed; fails with sdk/http-error and the redirect's status | Check base_url: and cdn_base_url: |
cdn.serve failure | Retries the same failures, then returns the last response | Check response.status |
| Setting | Default | Limits |
|---|---|---|
timeout: | 120 seconds | Each socket read or write, not the whole transfer |
open_timeout: | 10 seconds | Connecting |
upload_timeout: | None | Each binary upload attempt as a whole |
max_response_bytes: | 32 MiB | The response body the client reads; a larger one fails with sdk/response-too-large |
part_size_bytes: | 8 MiB | Content larger than this is uploaded in parts of this size, from 5 to 64 MiB |
Override any of them per call with request_options:. See Retrying requests safely, and Errors and Retries and timeouts for every error class and the backoff rules.
Reuse one client: it pools keep-alive connections, is safe across threads and reconnects in forked worker processes. Call close when finished.
Webhooks
Verify the exact raw body, then parse it, with CalmLens.parse_webhook_event. It raises CalmLens::WebhookVerificationError with sdk/invalid-webhook-signature for an invalid signature or stale timestamp, or with sdk/invalid-webhook-payload for a verified body that isn't a CalmLens event, such as one without createdAt or projectId. Passing an already parsed Hash instead of the raw body raises CalmLens::InvalidArgumentError (sdk/invalid-argument).
In Rails, read request.raw_post:
event = CalmLens.parse_webhook_event(
payload: request.raw_post,
signature: request.headers[CalmLens::WEBHOOK_SIGNATURE_HEADER],
timestamp: request.headers[CalmLens::WEBHOOK_TIMESTAMP_HEADER],
secret: ENV.fetch('CALMLENS_WEBHOOK_SECRET')
)In Sinatra or another Rack app, read request.body.read and pass the headers with headers: request.env:
event = CalmLens.parse_webhook_event(payload: request.body.read, headers: request.env,
secret: ENV.fetch('CALMLENS_WEBHOOK_SECRET'))headers: also takes a Hash with names in any case, where a repeated header is an Array of its values, or Net::HTTPHeader. The event has the same fields as an events.list item: event.id, project_id, type, severity, title, description, asset_id, asset, facts and created_at, where description, asset_id and asset are nil when the event has none. Fields CalmLens adds later are kept: event.to_payload returns the whole body as received.
Respond quickly and process the event afterwards, for example in a background job. Deduplicate by the event's id: redeliveries have a new x-calmlens-delivery ID but keep the same event ID. CalmLens.verify_webhook_signature and CalmLens.verify_webhook_request(payload:, headers:, secret:) return true or false instead of raising. event.test? and CalmLens.test_webhook_event?(event) are true for a test send from the portal or CLI. See Webhooks, and Webhooks in the reference for header constants and the signature tolerance.
Command-line tool
See Local development to install the CLI, forward signed events and trigger test uploads.
Testing
Use CalmLens::MockServerClient from calmlens/testing for offline tests. See Ruby testing.