Skip to main content
Every call the SDK makes to the HiddenLayer API can fail. The network can drop, credentials can expire, or the API can reject a request. The SDK turns each of these failures into a specific Python exception so you can decide what to do: fix your input, retry later, or stop and alert someone. This page explains the exception types, what each one means, and how to handle them. It also covers the retries and timeouts the SDK applies for you, and the non-HTTP errors that the higher-level helpers can raise.

Exception hierarchy

All API exceptions are importable directly from the hiddenlayer package and inherit from hiddenlayer.HiddenLayerError:
There are two broad groups:
  • APIConnectionError: the SDK could not get a response from the API. Examples include DNS failures, refused connections, proxy errors, and timeouts.
  • APIStatusError: the API responded, but with a 4xx or 5xx HTTP status code.
Because the hierarchy is nested, catching a parent class also catches all of its children. For example, except hiddenlayer.APIStatusError catches NotFoundError, RateLimitError, and every other status error.

Status codes and exceptions

The SDK’s README error table does not list ConflictError (409). The exception exists in the SDK source and is raised for HTTP 409 responses.

Exception attributes

Use these attributes to log useful details or decide how to react:
e.request includes request headers, and e.body can include parts of your input. Do not log entire request objects in production. Log the status code, message, and only the fields you need.

Order your except clauses from specific to general

Python checks except clauses from top to bottom and runs the first one that matches. Because subclasses also match their parent classes, put the most specific exceptions first:
  1. APITimeoutError before APIConnectionError, because a timeout is a type of connection error.
  2. Specific status errors, such as AuthenticationError or RateLimitError, before APIStatusError.
  3. APIError or HiddenLayerError last, as a catch-all for anything else the SDK raises.
If you put except hiddenlayer.APIStatusError first, the more specific clauses below it never run.

Complete example

This example analyzes a prompt with Interactions and handles every category of error. It reads credentials from the HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET environment variables. See Authentication and configuration for how to set them.
When the call succeeds, the script prints the action and threat level, for example:
The actual values depend on your project’s policy. When the call fails, the script logs one clear message and exits with status 1. Each branch re-raises the exception so the caller decides whether to stop, retry later, or fall back. For guidance on what your application should do when HiddenLayer is unreachable, see Security and production guidance.

Automatic retries

The SDK retries some failed requests automatically before raising an exception. You do not need to write your own retry loop for transient errors. What is retried by default:
  • Connection errors, such as network problems
  • Timeouts
  • HTTP 408 Request Timeout
  • HTTP 409 Conflict
  • HTTP 429 Too Many Requests
  • HTTP 500 and above
The API can override this decision with an x-should-retry: true or x-should-retry: false response header. When you authenticate with a client ID and client secret, the SDK also retries a 401 response once it detects that its cached access token has expired. It discards the old token and requests a new one. How retries are spaced:
  • The default is 2 retries, so up to 3 attempts in total.
  • The delay grows exponentially, starting at 0.5 seconds and capped at 8 seconds, with a small random reduction (jitter) so many clients do not retry at the same moment.
  • If the response includes a retry-after-ms or retry-after header with a value between 0 and 60 seconds, the SDK waits that long instead.
If every attempt fails, the SDK raises the exception from the last attempt. Configure or disable retries with max_retries, either on the client or per request with with_options():
Implementing your own retry wrapper around SDK calls is usually unnecessary and can multiply the number of attempts. If you need more resilience, increase max_retries instead. A custom wrapper makes sense only for logic the SDK does not cover, such as retrying a whole multi-step workflow.

Timeouts

By default, a request times out after 60 seconds, with a 5-second limit for establishing the connection. When a request times out, the SDK raises hiddenlayer.APITimeoutError. Timed-out requests are retried, so the total wait can be longer than one timeout period. Set timeout to a number of seconds, or to an httpx.Timeout object for separate connect, read, and write limits:
The timeout setting applies to each HTTP request. It does not limit how long the model scanning helpers wait for a scan to finish. With wait_for_results=True, the helpers poll until the scan reaches a final status, with no overall time limit. See Model scanning.

Errors raised by helpers

The higher-level helpers, such as client.model_scanner and client.evaluation_sessions.red_team, run several steps for you. In addition to the API exceptions above, they can raise standard Python exceptions:
scan_file creates the scan on the HiddenLayer API before it reads the local file. If the path does not exist, FileNotFoundError is raised from Path.stat() after the scan has been started. To avoid leaving an incomplete scan, check that the file exists with os.path.isfile() before calling scan_file. Whether the incomplete scan appears in the Console needs confirmation.
A scan that fails on the server side does not raise an exception. The helper returns a ScanReport with status set to "failed". Always check report.status. See Model scanning.

Red team session errors

The AI Attack Simulation session helpers define their own exceptions in hiddenlayer.lib.red_team_exceptions. They do not inherit from HiddenLayerError:
The poll_max_wait argument of start_session() and resume_session() raises a plain Exception with the message Polling timed out after ..., not PollTimeoutError.
The session helpers try to translate HTTP errors into WorkflowNotFoundError and RedTeamSessionError by catching httpx.HTTPStatusError. However, the SDK client raises hiddenlayer.APIStatusError subclasses, not httpx.HTTPStatusError. In practice, you may receive hiddenlayer.NotFoundError or hiddenlayer.InternalServerError instead of the red team exceptions. This behavior needs confirmation. Until it is confirmed, catch both.
For complete red team workflows, see AI Attack Simulation.

Beta warnings are not exceptions

Some endpoints are in beta. When you call one, the SDK emits a hiddenlayer.BetaWarning using Python’s warnings module. A warning is a message printed to standard error. It does not stop your program and cannot be caught with try/except unless you turn it into an error. The message looks like this:
In version 3.10.0, BetaWarning is emitted by client.runtime.evaluate_request, evaluate_response, and evaluate_interaction, and by all client.evaluations.red_team methods, including calls made through client.evaluation_sessions.red_team. To hide the warning once you have accepted the beta status:
To make tests fail when code calls a beta endpoint, turn the warning into an exception:
With this filter, calling a beta endpoint raises BetaWarning as an exception. To learn what beta status means for compatibility, see Version compatibility and upgrades.

Response validation errors

APIResponseValidationError is raised only when strict response validation is enabled and the API returns data that does not match the expected schema. Strict validation is controlled by a private, unstable client option and is off by default, so you are unlikely to see this exception. By default, the SDK accepts unexpected fields and keeps them available on the response model.

Next steps