Skip to main content
This page explains how to run the HiddenLayer SDKs safely in production. It covers protecting credentials, handling data, configuring the client for reliability, choosing what happens when HiddenLayer is unreachable, and using the SDKs 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. Every 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, regenerate the client secret in the Console.

Keep .env files out of version control

For local development, you can keep credentials in a .env file. The SDKs don’t read .env files themselves:
Use a third-party package such as python-dotenv to load the file (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 SDKs support 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 gets a new one shortly before it expires. If a token leaks from logs or memory, it stops working soon. A bearer token, passed as the token option or in HIDDENLAYER_TOKEN, is used as is. The SDK never refreshes it. Use bearer tokens only when another system manages and rotates them for you. In Python and TypeScript, the token option also takes a function that returns the current token, which the client calls before each request. Configure only one method. If both are set, the token wins: each SDK uses a token you pass, then a client ID and secret you pass, then HIDDENLAYER_TOKEN, then HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET. See Authentication and configuration.

Apply least privilege and separate credentials

  • 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 Permissions for products and features.
  • Use a separate client credential per workload and per stage, such as development, staging, and production. If one leaks, you can replace or remove it without affecting the others, and you can tell which system made a request.
  • Regenerate client secrets before they expire. Each client credential has an expiration that you choose when you create it. When it expires, HiddenLayer deletes it, and requests fail with 401 Unauthorized. Before then, regenerate the client secret or create a new client credential. The old secret stops working as soon as you regenerate it. To switch without downtime, create a new client credential, deploy it, and then delete the old one.

Never log secrets

Don’t print, log, or include in error reports the values you pass to the client. To check configuration, log whether a value is set, never the value itself. See the environment variable check in Troubleshooting. The SDKs’ own logging redacts credentials. At the debug level, they replace the Authorization header and other credential headers with [REDACTED].

Handle data responsibly

Keep debug logging off in production

The SDKs’ logging is silent by default. When you turn it on at the debug level, it records each request’s method, URL, and headers, with credentials redacted, but not request or response bodies. See Turn on debug logging.
Leave SDK debug logging off in production, and don’t add your own logging of prompts and model responses unless you need it. For AI Runtime Security calls, payloads contain user prompts and model output, and log pipelines often forward logs to systems with broad access.

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 scans download the model to the local machine before uploading it to HiddenLayer. What happens to the download depends on the SDK:
The files stay on disk 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 regions use HTTPS: Follow these rules:
  • Always use an https:// base URL for HiddenLayer SaaS, and for a self-hosted deployment on another host when it supports TLS. A plain http:// URL sends your credentials and prompts unencrypted, so use one only for a local container on the same host or on a trusted private network.
  • Do not disable TLS certificate verification. If your organization inspects TLS traffic with its own certificate authority (CA), trust that CA instead.
  • If you need a proxy or other network settings, configure the HTTP client the SDK uses:
Pass your own httpx.Client as httpx_client. The SDK uses it for API calls, the access token exchange, and model file uploads. Give it the SDK’s defaults, a 60-second timeout and following redirects, because the SDK applies them only to the client it creates itself:
See the httpx documentation for proxy and certificate options. Use an httpx.AsyncClient with AsyncHiddenLayer.

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 access token cache is safe to share across threads. Closing the client differs by SDK:
  • Python: call close() at shutdown, or use the client in a with block. For AsyncHiddenLayer, call await client.aclose() or use async with. An httpx_client that you pass in stays open, so close that yourself.
  • TypeScript: there is nothing to close.
  • Java: HiddenLayerClient and AsyncHiddenLayerClient are AutoCloseable. Call close() at shutdown, or use try-with-resources, to release the connection pool. Always close an AsyncHiddenLayerClient: its scanners run on threads of their own, which keep the JVM alive until close() stops them.

Set timeouts and retries deliberately

The defaults are a 60-second timeout 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 the timeout and retries for a single call with per-request options: request_options={"timeout": 5.0, "max_retries": 5} in Python, { timeoutInSeconds: 5, maxRetries: 5 } as the last argument in TypeScript, or RequestOptions.builder().timeout(5).maxRetries(5).build() as the last argument in Java. See Error handling for which errors are retried.

Connection limits

The client the SDK creates uses httpx’s default limits: up to 100 concurrent connections, with up to 20 idle connections kept open for reuse. For different limits, pass your own httpx.Client with an httpx.Limits object:

Use the async client for high concurrency

To send many requests concurrently without a thread per request, use each SDK’s asynchronous API: AsyncHiddenLayer with asyncio in Python, the promise-based client in TypeScript, or AsyncHiddenLayerClient in Java, whose methods return CompletableFutures. This example evaluates a batch of prompts concurrently with Runtime v2 interaction evaluations:
In Python, install the optional aiohttp backend with pip install "hiddenlayer-sdk[aiohttp]". When it’s installed, AsyncHiddenLayer sends its requests with aiohttp. See Installation.

Be deliberate with beta APIs

Some APIs, such as AI Attack Simulation (red team evaluations and sessions), are beta and log a warning the first time you call them. The Runtime v2 evaluation endpoints are not beta. 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==6.0.0, @hiddenlayerai/hiddenlayer-sdk@5.0.0, or hiddenlayer-java:6.0.0, and upgrade deliberately.
  • Run your tests against each new version before you deploy it.
  • Silence 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: timeouts, failed connections, 429, and 5xx responses. Authentication, permission, and request errors, missing credentials, an invalid base URL, and responses the SDK can’t parse indicate a problem that you need to fix, so raise them.
Expected result: the answer depends on your project’s policy. With a policy that reports prompt injection without blocking it, the example prints True (true in TypeScript and Java): the prompt is allowed, and the detection is recorded. If HiddenLayer is unreachable, the example logs the failure and prints False, or True when GUARDRAIL_FAIL_OPEN=true. The BLOCK action depends on your project’s policy. See Runtime security for the other actions, and for how to forward the redacted payload when the action is REDACT.

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 client credential 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, or with files that failed to scan, did not fully check the model.
This program scans a folder and fails the build when needed. It takes the folder and the model name as arguments:
A GitHub Actions step that runs it might look like this:
The TypeScript step assumes @hiddenlayerai/hiddenlayer-sdk and tsx are in your package.json. The Java step assumes a Gradle project with the application plugin and ScanGate as its main class. 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:
Deleting a model and terminating a running AI Attack Simulation workflow can’t be undone. Use a client credential that has delete permissions only where you need them, confirm IDs before you call 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 client credential with only the permissions it needs.
  • You have a plan to regenerate client secrets before they expire.
  • Secrets are never printed or logged.
  • SDK debug logging is off in production.
  • The client’s region matches your data residency requirements.
  • Every base URL uses HTTPS, except a local container or a host on a trusted private network, and TLS verification is enabled.
  • Your application creates one client and reuses it. In Python and Java, it closes the client at shutdown.
  • Timeouts and retries are set for each workload.
  • You use the asynchronous API for high-concurrency 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 the scan status, and have a job timeout.
  • In Python, files downloaded by the S3, Azure, and Hugging Face helpers are deleted after scanning.
  • Delete and terminate operations are restricted and reviewed.