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:
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):
.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 withHIDDENLAYER_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 asclient.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
SettingHIDDENLAYER_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.
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:
/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. Plainhttp://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
DefaultHttpxClientso 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 callingclose():
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.
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 ashiddenlayer.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 onasyncio, such as a FastAPI service, use AsyncHiddenLayer. It sends many requests concurrently without a thread per request:
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.
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.
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_IDandHIDDENLAYER_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
faileddid not fully check the model.
Irreversible operations
Some SDK methods permanently change data in your tenant:Production checklist
- Credentials come from environment variables or a secrets manager, never from source code.
-
.envfiles 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_LOGis unset or set toinfoin production, neverdebug. - 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_retriesare set for each workload. - You use
AsyncHiddenLayerfor high-concurrencyasyncioapplications. - 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.

