Skip to main content
This page explains how to run the HiddenLayer Python SDK safely in production. It covers protecting credentials, handling data, configuring the client for reliability, choosing what happens when HiddenLayer is unreachable, and using the SDK in CI pipelines. A production checklist at the end summarizes the recommendations.

Protect your credentials

Your client ID and client secret, or your bearer token, grant access to your HiddenLayer tenant. Anyone who has them can call the API as you. Treat them like passwords.

Store credentials outside your code

Provide credentials through environment variables or a secrets manager, such as AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault. The SDK reads these environment variables automatically: If you load credentials from a secrets manager, pass them to the client explicitly instead of writing them to disk:
Never hard-code a client secret or bearer token in source code, notebooks, Dockerfiles, or configuration files that you commit. Secrets in version control are easy to leak and hard to remove from history. If a secret is exposed, delete the API key in the Console and create a new one.

Keep .env files out of version control

For local development, you can keep credentials in a .env file. The SDK does not read .env files itself. Use a third-party package such as python-dotenv to load it (pip install python-dotenv):
Add the file to .gitignore before you create it so it is never committed:

Prefer client credentials over long-lived bearer tokens

The SDK supports two authentication methods. For production, use OAuth2 client credentials, which means your application exchanges a client ID and client secret for a short-lived access token. The SDK requests the access token, caches it, and refreshes it shortly before it expires. If a token leaks from logs or memory, it stops working soon. A bearer token passed with HIDDENLAYER_TOKEN is used as is. The SDK does not refresh it. Use bearer tokens only when another system manages and rotates them for you. Configure only one method. If both are set, the client ID and client secret take precedence. See Authentication and configuration.

Apply least privilege and separate keys

  • Grant only the permissions a workload needs. A CI job that scans models does not need permission to delete models or run AI Attack Simulation. See API permissions related to products or features.
  • Use a separate API key per workload and per stage, such as development, staging, and production. If one key leaks, you can revoke it without affecting the others, and you can tell which system made a request.
  • Rotate keys before they expire. Each API key has an expiration that you choose when you create it. When a key expires, it is deleted and requests fail with AuthenticationError. Create the replacement key, deploy it, and then delete the old key. See When should I create a new API key?

Never log secrets

The client stores your credentials as attributes such as client.client_secret and client.bearer_token. Do not print, log, or include them in error reports. To check configuration, log whether a value is set, never the value itself. See the environment variable check in Troubleshooting.

Handle data responsibly

Turn off debug logging in production

Setting HIDDENLAYER_LOG=debug logs every request’s options, including the JSON request body. For Interactions and AI Runtime Security calls, that body contains user prompts and model responses.
Do not set HIDDENLAYER_LOG=debug in production. Debug logs can capture prompts, model outputs, and other sensitive data, and log pipelines often forward them to systems with broad access. Use info or leave HIDDENLAYER_LOG unset.

Understand what you send to HiddenLayer

When you call the SDK, the data you pass, such as prompts, model responses, or model files, is sent to the HiddenLayer API for the region you configured (prod-us or prod-eu). Choose the region that matches your data residency requirements. To learn how HiddenLayer collects and handles this data, see Product data collection and handling.

Clean up downloaded model files

The S3, Azure Blob Storage, and Hugging Face scanning helpers download the model to the local machine before uploading it to HiddenLayer: The SDK does not delete these files after the scan. Large models can fill the disk, and on shared machines other users or processes might be able to read them. Delete the files when the scan finishes:
For S3 and Azure, delete /tmp/<file name>, where the file name is the last segment of the S3 key or blob name.

TLS and network configuration

The HiddenLayer environments use HTTPS: Follow these rules:
  • Always use an https:// base URL for HiddenLayer SaaS. Plain http:// URLs are appropriate only for a local container on the same host or a trusted private network.
  • Do not disable TLS certificate verification. If your organization inspects TLS traffic with its own certificate authority, configure that CA on the HTTP client instead.
  • If you need a proxy or other network settings, pass a custom HTTP client. Use DefaultHttpxClient so you keep the SDK’s default timeout and connection limits:
DefaultHttpxClient accepts the same arguments as httpx.Client. See the httpx documentation for proxy and certificate options.

Configure the client for production

Reuse one client

Each client keeps a pool of HTTP connections and, with client credentials, a cached access token. Creating a new client for every request discards both, adding latency and extra token requests. Create one client when your application starts and share it. The client’s token cache is protected by a lock, so you can share a synchronous client across threads. Close the client when your application shuts down, either with a context manager or by calling close():

Set timeouts and retries deliberately

The defaults are a 60-second timeout (5 seconds to connect) and 2 retries with exponential backoff. Tune them for your workload:
  • Inline guardrails in a user-facing request path usually need a short timeout and few retries, so a slow response does not stall your users.
  • Batch jobs and CI pipelines can use a longer timeout and more retries, because finishing matters more than speed.
You can also override settings for a single call with client.with_options(timeout=..., max_retries=...). See Error handling for which errors are retried.

Connection limits

By default, the SDK allows up to 100 concurrent connections and keeps up to 20 idle connections open for reuse. These values are available as hiddenlayer.DEFAULT_CONNECTION_LIMITS. If you need different limits, pass an httpx.Limits object to DefaultHttpxClient:

Use the async client for high concurrency

If your application is built on asyncio, such as a FastAPI service, use AsyncHiddenLayer. It sends many requests concurrently without a thread per request:
For more throughput, install the optional aiohttp backend with pip install "hiddenlayer-sdk[aiohttp]" and pass http_client=DefaultAioHttpClient(). See Installation.

Be deliberate with beta APIs

AI Runtime Security evaluation endpoints (client.runtime.*) and AI Attack Simulation (client.evaluations.red_team.* and client.evaluation_sessions.red_team.*) emit hiddenlayer.BetaWarning in version 3.10.0. Beta APIs can change in any release, including minor releases. If you depend on them in production:
  • Pin an exact SDK version, such as hiddenlayer-sdk==3.10.0, and upgrade deliberately.
  • Run your tests against each new version before you deploy it.
  • Filter the warning only after you have accepted the risk.
See Version compatibility and upgrades.

Decide what happens when HiddenLayer is unreachable

When you use HiddenLayer as a runtime guardrail, your application must decide what to do if the check fails, for example because of a network outage, a timeout, or a server error. There are two approaches:
  • Fail closed: Block the request when the check cannot run. This is safer, because no unchecked prompt reaches your model, but an outage makes your feature unavailable.
  • Fail open: Allow the request when the check cannot run. This keeps your feature available, but unchecked prompts can reach your model during an outage.
The right choice depends on your risk tolerance and the sensitivity of your application, so it is your decision. Many teams fail closed for high-risk actions, such as tools that change data, and fail open for low-risk features. Whichever you choose, log every failure so you can detect outages and review what passed through unchecked. Only apply fail-open or fail-closed logic to availability problems. Authentication, permission, and request errors indicate a configuration problem that you need to fix, so raise them.
APITimeoutError is a subclass of APIConnectionError, so the example also handles timeouts. The Block action depends on your project’s policy. See Runtime security for the other actions and how to use modified_data for redaction.

Use the SDK in CI pipelines

A common use of the SDK in CI is a model scanning gate: scan a model before it is merged or deployed, and fail the pipeline if the scan finds problems.
  • Store credentials in your CI system’s secret store, such as GitHub Actions secrets or GitLab CI/CD variables, and expose them to the job as HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET. Never echo them in job output.
  • Use a dedicated API key for CI with only the permissions it needs to scan models.
  • Decide the failure condition, such as any detection of high or critical severity, and exit with a non-zero status when it is met.
  • Treat a failed scan as a failure. A scan with status failed did not fully check the model.
This script scans a folder and fails the build when needed:
A generic GitHub Actions step that runs it might look like this:
Model scans wait for results with no overall time limit, so set a job-level timeout in your CI system. HiddenLayer also provides a ready-made GitHub Action for model scanning.

Irreversible operations

Some SDK methods permanently change data in your tenant:
client.models.delete(model_id) deletes a model from HiddenLayer, and client.evaluation_sessions.red_team.terminate_session(workflow_id) stops a running AI Attack Simulation workflow. Neither can be undone. Use an API key that has delete permissions only where you need them, confirm IDs before calling these methods, and avoid running them automatically without a review step.

Production checklist

  • Credentials come from environment variables or a secrets manager, never from source code.
  • .env files are listed in .gitignore.
  • You authenticate with a client ID and client secret rather than a long-lived bearer token.
  • Each workload and stage has its own API key with only the permissions it needs.
  • You have a plan to rotate API keys before they expire.
  • Secrets are never printed or logged.
  • HIDDENLAYER_LOG is unset or set to info in production, never debug.
  • The client’s environment matches your data residency requirements.
  • All base URLs use HTTPS, and TLS verification is enabled.
  • Your application creates one client and reuses it, and closes it at shutdown.
  • Timeouts and max_retries are set for each workload.
  • You use AsyncHiddenLayer for high-concurrency asyncio applications.
  • You pin the SDK version, especially if you use beta APIs.
  • You chose fail-open or fail-closed behavior for runtime guardrails, and you log every failure.
  • CI jobs use secrets from the CI secret store, check report.status, and have a job timeout.
  • Files downloaded by the S3, Azure, and Hugging Face helpers are deleted after scanning.
  • Delete and terminate operations are restricted and reviewed.