Skip to main content

Maskena Python SDK

Python client for the Maskena API. Check texts and files for prompt injection, hidden content and data exfiltration before they reach a language model, and remove personal data.

  • Synchronous and asynchronous clients
  • Typed results and one exception class per error type
  • Automatic retries on rate limits and server errors, respecting Retry-After
  • Python 3.9 or later; one dependency (httpx)

Installation

pip install maskena

Quickstart

Create an API key in the dashboard, under API, and set it as an environment variable:

export MASKENA_API_KEY="sfk_..."
from maskena import Maskena

client = Maskena()

result = client.check("Summarize this email: ...", clean=True)

if result.flagged:
    print(result.verdict, [f.title for f in result.findings])
    safe_text = result.clean_text

flagged is True whenever the verdict is not safe. A common policy is to block dangerous content and send suspicious content to review, or to continue with clean_text.

Checking texts

result = client.check(
    user_message,
    clean=True,          # also return clean_text
    format="html",       # "text" (default), "markdown" or "html"
    depth="standard",    # "fast", "standard" (default) or "max"
)

result.verdict           # "safe", "suspicious" or "dangerous"
result.score             # 0 to 100, for ranking; not a probability
result.findings          # list of Finding(rule_id, category, severity, title, description, evidence)
result.personal_data     # PersonalData(total, occurrences, counts={"email": 1, ...})

Texts sent to check are not stored.

Scanning files

report = client.scan("contract.pdf")               # path
report = client.scan(open("contract.pdf", "rb"))   # binary file object
report = client.scan(data, filename="cv.docx")     # bytes

print(report.verdict)
for finding in report.findings:
    print(finding.severity, finding.title, finding.location)

clean = report.clean_file("pdf")
if clean:
    pdf_bytes = client.download_clean(report.id, "pdf")

Supported formats: PDF, DOCX, XLSX, PPTX, ODF, HTML, SVG, TXT, MD, CSV, JSON, YAML, source code, PNG, JPEG and ZIP. Original files are not stored. Clean versions are available until clean.expires_at.

Sanitizing documents for RAG

job = client.sanitize("manual.pdf", policy="redact", ocr="auto", chunk_size=1200, chunk_overlap=150)

print(job.risk_before.verdict, "->", job.risk_after.verdict)
for item in job.removed:
    print(item.page, item.category, item.reason)

for chunk in job.indexable_chunks:
    index.add(chunk.text, metadata={"page": chunk.page_start, "risk": chunk.risk_after})

# Or the JSON Lines format accepted by LangChain and LlamaIndex loaders:
records = client.download_chunks(job.id)

policy="redact" removes only the malicious sentence, "drop" moves the whole chunk to quarantine, and "flag" keeps the text and marks the chunk.

Async

from maskena import AsyncMaskena

async with AsyncMaskena() as client:
    result = await client.check(text)

Every method of Maskena is available as a coroutine on AsyncMaskena.

Errors

import maskena

try:
    client.check(text)
except maskena.RateLimitError as e:
    print("retry in", e.retry_after, "seconds")
except maskena.QuotaExceededError:
    ...
except maskena.APIError as e:
    print(e.status_code, e.code, e.message)
Exception Status Typical code
InvalidRequestError 400, 422 invalid_option, invalid_document, empty_file, validation_error
AuthenticationError 401 missing_api_key, invalid_api_key
QuotaExceededError 402 quota_exceeded
PermissionDeniedError 403 email_not_verified, plan_required
NotFoundError 404 not_found
RequestTooLargeError 413 file_too_large, text_too_large
RateLimitError 429 rate_limited
ServerError 5xx processing_failed, internal_error
APIConnectionError, APITimeoutError none network failure or timeout

All API errors inherit from APIError, and every exception inherits from MaskenaError. Use code in your logic; message is human-readable text in the language of the request and may change.

Retries

By default, a request is retried up to 2 times on:

  • 429, waiting for the number of seconds in Retry-After;
  • 5xx, with exponential backoff;
  • connection errors, which happen before the request reaches the server.

Timeouts are retried only for GET requests. A POST that timed out may have been processed and charged, so the library raises APITimeoutError instead of sending it again. Failed requests are never charged.

client = Maskena(max_retries=0)       # disable retries

Configuration

client = Maskena(
    api_key="sfk_...",                # default: MASKENA_API_KEY
    base_url="https://maskena.com",   # default: MASKENA_BASE_URL, then https://maskena.com
    timeout=120.0,                    # seconds per request
    max_retries=2,
    language="en",                    # "en", "pt" or "es" for titles, descriptions and error messages
    app_info="my-app/1.4",            # added to the User-Agent; helps support identify your integration
)

To use a proxy, custom TLS settings or a shared connection pool, pass your own httpx.Client (or httpx.AsyncClient) as http_client. In that case, configure the timeout on that client.

Use the client as a context manager, or call close(), to release connections.

Results

Every result object keeps the complete JSON response in raw, so fields added to the API later are available before the library is updated:

result.raw["layers"]

License

MIT

Metadata

Release files for maskena 0.1.0

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

Source distribution (sdist)

Source distribution for maskena 0.1.0
File Size Uploaded Provenance Actions
maskena-0.1.0.tar.gz 18.9 kB Without provenance Details for maskena-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for maskena 0.1.0
File Interpreter ABI Platform Actions
maskena-0.1.0-py3-none-any.whl Python 3 none any Details for maskena-0.1.0-py3-none-any.whl

Total release size: 33.4 kB

Release files / maskena-0.1.0.tar.gz

Download URL maskena-0.1.0.tar.gz
Size 18.9 kB
Tags Source
SHA-256 checksum
How to use checksums
b7280a7be3ba05db1f84ab4dc87a589290c0bb0358d58cbf1799fcb55415598a
BLAKE2b-256 checksum
How to use checksums
c0395e98375a897975c4fea5baf03fad4dfaff6d959a6518db30a675cf7145b0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.9

Release files / maskena-0.1.0-py3-none-any.whl

Download URL maskena-0.1.0-py3-none-any.whl
Size 14.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2d3f3dcdb3243fc455d7acb82433e273a19923b388c1d7c25e827842a3c89275
BLAKE2b-256 checksum
How to use checksums
8b98153724258f2b882808a4b54b2260330b4c64493693ecaf8171c0cdae39d7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.9

Security for maskena 0.1.0

Provenance

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

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

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

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

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

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