> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hiddenlayer.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Troubleshooting

> Diagnose and fix common problems with the HiddenLayer SDKs for Python, TypeScript, and Java, including installation, authentication, connection, and model scanning issues.

This page lists common problems with the HiddenLayer SDKs, grouped by the symptom you see. Each entry explains the likely cause and how to fix it. If your problem is not listed, work through the [debug checklist](#debug-checklist) at the end of the page.

For background on the error types mentioned here, see [Error handling](https://docs.hiddenlayer.ai/docs/integrations/sdk/error_handling.md).

## Installation and setup

> [accordion] The SDK can't be found or imported
>
> **Cause:** The SDK is not installed where your code runs. This usually happens when you install the package in one environment or project and run your code from another.
>
> **Fix:** Install the package into the environment or project that runs your code, then check that it resolves.
>
> > [tab] Python
> >
> > `ModuleNotFoundError: No module named 'hiddenlayer'` means the package isn't installed for the interpreter that runs your code. Activate your project's virtual environment, then install and check with that interpreter:
> >
> > ```bash theme={null}
> > python -m pip install hiddenlayer-sdk
> > python -c "import hiddenlayer; print(hiddenlayer.__version__)"
> > ```
> >
> > The package name on PyPI is `hiddenlayer-sdk`, but the import name is `hiddenlayer`. Installing a package named `hiddenlayer` does not install this SDK.
>
> > [tab] TypeScript
> >
> > `Cannot find module '@hiddenlayerai/hiddenlayer-sdk'` means the package isn't in the project's `node_modules`. Install it from the project root and check the installed version:
> >
> > ```bash theme={null}
> > npm install @hiddenlayerai/hiddenlayer-sdk
> > npm ls @hiddenlayerai/hiddenlayer-sdk
> > ```
> >
> > In CommonJS, import the client by name: `const { HiddenLayer } = require("@hiddenlayerai/hiddenlayer-sdk");`. The SDK runs on the server, with Node.js 22 or later.
>
> > [tab] Java
> >
> > `package com.hiddenlayer.api does not exist` means the dependency isn't on the compile classpath. Depend on `com.hiddenlayer.api:hiddenlayer-java:6.0.0` alone, and remove any dependency on `hiddenlayer-java-core` or `hiddenlayer-java-client-okhttp`, which were separate artifacts before 3.0.0. Check what your build resolves:
> >
> > ```bash Gradle theme={null}
> > ./gradlew dependencies --configuration runtimeClasspath | grep hiddenlayer
> > ```
> >
> > ```bash Maven theme={null}
> > mvn dependency:tree -Dincludes=com.hiddenlayer.api
> > ```
>
> See [Installation](https://docs.hiddenlayer.ai/docs/integrations/sdk/installation.md).

> [accordion] A storage SDK is missing when you scan a model from S3, Azure Blob Storage, or Hugging Face
>
> **Cause:** The scans that download a model first use the cloud provider's or Hugging Face's own library. The HiddenLayer SDK doesn't install it.
>
> **Fix:** Install the library named in the error into the same environment or project as the SDK.
>
> | Scan | Python package | TypeScript package |
> | - | - | - |
> | S3 | `boto3` | `@aws-sdk/client-s3` |
> | Azure Blob Storage | `azure-identity` and `azure-storage-blob` | `@azure/storage-blob` |
> | Hugging Face | `huggingface_hub` | `@huggingface/hub` |
>
> In Python the error is an `ImportError`, such as `Python package boto3 is not installed.` In TypeScript, the scan throws an error naming the package to install. The Java SDK has no download helpers for these sources. See [Scan models](https://docs.hiddenlayer.ai/docs/integrations/sdk/model_scanning.md).

> [accordion] The installed version is older than expected, or a method is missing
>
> **Cause:** Your project still resolves an older version of the SDK. This happens when you upgrade in a different environment, when a lock file or version pin holds an old version, or when an IDE uses a different interpreter or project.
>
> **Fix:**
>
> 1. Check the version your code actually uses. See [Check the SDK version](#check-the-sdk-version).
> 2. Upgrade with the same tool that installed it, and check for pins in `requirements.txt`, `pyproject.toml`, `package.json`, the lock file, `build.gradle`, or `pom.xml`.
> 3. If you're coming from an earlier major version, read its migration guide. Many names changed in Python 4.0.0, TypeScript 4.0.0, and Java 3.0.0.
>
> See [Version compatibility and upgrades](https://docs.hiddenlayer.ai/docs/integrations/sdk/versioning.md).

## Configuration errors

> [accordion] Unknown environment, or requests go to the wrong URL
>
> **Cause:** The client's region setting has a value the SDK does not recognize, or another setting overrides it.
>
> **Fix:** Use one of the supported regions, or a base URL:
>
> | Region | Base URL |
> | - | - |
> | `prod-us` (default) | `https://api.us.hiddenlayer.ai` |
> | `prod-eu` | `https://api.eu.hiddenlayer.ai` |
>
> * **Python** raises `ValueError: Unknown environment: ...` for any name other than `prod-us` or `prod-eu`.
> * **TypeScript** treats any other string as a URL, so a misspelled region name fails when the first request is sent.
> * **Java** has two regions, `Environment.PROD_US` and `Environment.PROD_EU`. For any other base URL, use `.url(...)`.
>
> A base URL wins over the region: `base_url` in Python, `baseUrl` in TypeScript, or `.url(...)` in Java. The `HIDDENLAYER_BASE_URL` environment variable is used only when you set neither a region nor a base URL in code. To connect to any other endpoint, such as a self-hosted container, use a base URL instead of a region.

> [accordion] Java: IllegalStateException when you build the client
>
> **Cause:** `build()` found neither a token nor both a client ID and a client secret, in the builder or in the environment.
>
> **Fix:** Set `HIDDENLAYER_CLIENT_ID` and `HIDDENLAYER_CLIENT_SECRET` (or `HIDDENLAYER_TOKEN`) in the environment of the JVM, or pass them to the builder. Python and TypeScript clients construct without credentials and fail on the first request instead. See [Authentication and configuration](https://docs.hiddenlayer.ai/docs/integrations/sdk/authentication.md).

## Authentication and permission errors

> [accordion] 401 Unauthorized, or an error about missing credentials
>
> **Cause:** The API did not accept your credentials. Common reasons:
>
> * **Missing environment variables.** Python and TypeScript clients construct without credentials. Each request then fails before it is sent, with an error that starts `No HiddenLayer credentials:` and names the options and variables to set: an `ApiError` with no status code in Python, or a `HiddenLayerError` with no status code in TypeScript.
> * **Wrong client ID or client secret**, including typos or extra whitespace. The SDK exchanges them for an access token before your first request. A rejected exchange raises `UnauthorizedError` with status 401, whichever method you called. The body's `error` is `invalid_client`, and its `error_description` says what was rejected: `Invalid client authentication credentials.` for a wrong client secret, or `client_id: ... is not valid.` for an unknown client ID.
> * **Expired or deleted client credential.** Client credentials have an expiration set when they are created. When a client credential expires, HiddenLayer deletes it.
> * **Credentials for the wrong region.** A client credential created in the US Console does not work against the EU API, and the reverse. The SDK requests its access token from the region you configured, so the credentials must belong to that region.
> * **Bearer token expired.** If you use a token (`HIDDENLAYER_TOKEN` or the token option), the SDK never refreshes it for you.
> * **A token takes precedence over client credentials.** Each SDK uses the first credential it finds: a token you pass, then a client ID and secret you pass, then `HIDDENLAYER_TOKEN`, then `HIDDENLAYER_CLIENT_ID` and `HIDDENLAYER_CLIENT_SECRET`. A stale `HIDDENLAYER_TOKEN` wins over client credentials in the environment.
>
> **Fix:**
>
> 1. Run the [environment variable check](#check-environment-variables) to confirm that the variables are set in the process that runs your code.
> 2. In the Console, confirm that the client credential exists and has not expired. If it was deleted, [create a new client credential](https://docs.hiddenlayer.ai/docs/products/console/apikey_aisec_platform.md#create-a-client-credential). To keep a client credential from expiring, [regenerate the client secret](https://docs.hiddenlayer.ai/docs/products/console/apikey_aisec_platform.md#regenerate-a-client-secret) before it expires.
> 3. Confirm that the client's region (`prod-us` or `prod-eu`) matches the region where you created the client credential.
> 4. If you use a bearer token, get a new one, or switch to a client ID and client secret so the SDK refreshes access tokens automatically.
> 5. Unset `HIDDENLAYER_TOKEN` if you mean to use client credentials from the environment.
>
> The typed error for 401 is `UnauthorizedError` in Python and Java and `HiddenLayerApi.UnauthorizedError` in TypeScript, on endpoints that declare it; other endpoints raise the base error with status 401. See [Authentication and configuration](https://docs.hiddenlayer.ai/docs/integrations/sdk/authentication.md).

> [accordion] 403 Forbidden
>
> **Cause:** Your credentials are valid, but the client credential does not have permission for the operation you called. For example, a client credential that can run model scans might not be allowed to delete models.
>
> **Fix:** In the Console, create a new client credential with the permissions the operation needs. You can't change a client credential's permissions after you create it. See [Permissions for products and features](https://docs.hiddenlayer.ai/docs/products/console/apikey_aisec_platform.md#permissions-for-products-and-features). Grant only the permissions your workload needs.
>
> The typed error is `ForbiddenError` (`HiddenLayerApi.ForbiddenError` in TypeScript).

> [accordion] 404 Not Found
>
> **Cause:** The API could not find the resource. Common reasons:
>
> * The ID is wrong. Check for typos, and check that you passed the right kind of ID, for example a scan ID rather than a model ID.
> * The resource exists in a different region. Resources created in `prod-us` are not visible from `prod-eu`.
> * The resource is not available yet. For example, scan results can take a moment to appear after you start a scan. When they read a scan's results, the scanning helpers try up to 5 times on a 404 before they raise it.
>
> **Fix:** Check the ID and the client's region. If the resource was just created, wait briefly and try again.
>
> The typed error is `NotFoundError` (`HiddenLayerApi.NotFoundError` in TypeScript), on endpoints that declare it.

## Connection and rate limit errors

> [accordion] The SDK can't connect to HiddenLayer
>
> **Cause:** The request never got a response. Common reasons:
>
> * No network access, or a DNS failure
> * A corporate proxy or firewall is blocking outbound HTTPS traffic
> * A typo in the base URL or `HIDDENLAYER_BASE_URL`
> * A local AI Runtime Security container is not running or is listening on a different port
>
> How each SDK reports it:
>
> | Python | TypeScript | Java |
> | - | - | - |
> | An `httpx.TransportError`, such as `httpx.ConnectError`. Failed connections are retried first. | A `HiddenLayerError` with no `statusCode`. Network errors are not retried. | A `HiddenLayerException` whose cause is the `IOException`. Network errors are not retried. |
>
> **Fix:**
>
> 1. Run a request that tells a connection failure apart from an API error. Any status code, even 401 or 403, means the SDK reached HiddenLayer. If no credentials are set, the Python and TypeScript versions report that the request wasn't sent and name the variables to set:
>
> ```python Python theme={null}
> import httpx
> from hiddenlayer import HiddenLayer, InteractionEvaluationRequestMetadata
> from hiddenlayer.core import ApiError
>
> client = HiddenLayer()
>
> try:
>     client.runtime.evaluate_interaction(
>         metadata=InteractionEvaluationRequestMetadata(
>             model="gpt-4o", provider="openai", requester_id="connectivity-check"
>         ),
>         interaction={"model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}]},
>     )
> except httpx.TransportError as e:
>     print("Could not reach HiddenLayer:", repr(e))
> except ApiError as e:
>     if e.status_code is None:  # Raised before sending, such as when no credentials are set
>         print("The request was not sent:", e.body)
>     else:
>         print("Connected. The API returned status", e.status_code, e.body)
> else:
>     print("Connected successfully.")
> ```
>
> ```typescript TypeScript theme={null}
> import { HiddenLayer, HiddenLayerError, HiddenLayerTimeoutError } from "@hiddenlayerai/hiddenlayer-sdk";
>
> const client = new HiddenLayer();
>
> try {
>     await client.runtime.evaluateInteraction({
>         metadata: { model: "gpt-4o", provider: "openai", requester_id: "connectivity-check" },
>         interaction: { model: "gpt-4o", messages: [{ role: "user", content: "Hello" }] },
>     });
>     console.log("Connected successfully.");
> } catch (err) {
>     if (err instanceof HiddenLayerTimeoutError) {
>         console.log("The request timed out:", err.message);
>     } else if (err instanceof HiddenLayerError && err.statusCode === undefined) {
>         // No response: the connection failed, or the request wasn't sent, such as when no credentials are set.
>         console.log("No response from HiddenLayer:", err.message, err.cause ?? "");
>     } else if (err instanceof HiddenLayerError) {
>         console.log("Connected. The API returned status", err.statusCode, err.body);
>     } else {
>         throw err;
>     }
> }
> ```
>
> ```java Java theme={null}
> import com.hiddenlayer.api.HiddenLayerClient;
> import com.hiddenlayer.api.HiddenLayerClientBuilder;
> import com.hiddenlayer.api.core.HiddenLayerApiException;
> import com.hiddenlayer.api.core.HiddenLayerException;
> import com.hiddenlayer.api.resources.runtime.requests.InteractionEvaluationRequest;
> import com.hiddenlayer.api.resources.runtime.types.InteractionEvaluationRequestInteraction;
> import com.hiddenlayer.api.types.InteractionEvaluationRequestMetadata;
> import java.util.Collections;
> import java.util.LinkedHashMap;
> import java.util.Map;
>
> public final class TrConnectionCheck {
>     public static void main(String[] args) {
>         Map<String, Object> message = new LinkedHashMap<>();
>         message.put("role", "user");
>         message.put("content", "Hello");
>         Map<String, Object> payload = new LinkedHashMap<>();
>         payload.put("model", "gpt-4o");
>         payload.put("messages", Collections.singletonList(message));
>
>         try (HiddenLayerClient client = new HiddenLayerClientBuilder().build()) {
>             client.runtime().evaluateInteraction(InteractionEvaluationRequest.builder()
>                     .metadata(InteractionEvaluationRequestMetadata.builder()
>                             .model("gpt-4o")
>                             .requesterId("connectivity-check")
>                             .provider("openai")
>                             .build())
>                     .interaction(InteractionEvaluationRequestInteraction.of(payload))
>                     .build());
>             System.out.println("Connected successfully.");
>         } catch (HiddenLayerApiException e) {
>             System.out.println("Connected. The API returned status " + e.statusCode() + ": " + e.body());
>         } catch (HiddenLayerException e) {
>             System.out.println("Could not reach HiddenLayer: " + e.getCause());
>         }
>     }
> }
> ```
>
> 2. Check the region or base URL the client uses.
> 3. If you are behind a proxy, configure it. See [TLS and network configuration](https://docs.hiddenlayer.ai/docs/integrations/sdk/security.md#tls-and-network-configuration).
> 4. If you use a local container, confirm that it is running and that the base URL uses the correct host and port.

> [accordion] The request timed out
>
> **Cause:** A request took longer than the timeout. The default is 60 seconds. Large payloads, slow networks, or temporary API load can cause this. No SDK retries a request that timed out.
>
> | Python | TypeScript | Java |
> | - | - | - |
> | `httpx.TimeoutException` | `HiddenLayerTimeoutError` | `HiddenLayerException`, with the timeout as its cause |
>
> **Fix:** Increase the timeout for the client, or for a single request with per-request options:
>
> ```python Python theme={null}
> from hiddenlayer import HiddenLayer
>
> client = HiddenLayer(timeout=120.0)
> ```
>
> ```typescript TypeScript theme={null}
> import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";
>
> const client = new HiddenLayer({ timeoutInSeconds: 120 });
> ```
>
> ```java Java theme={null}
> import com.hiddenlayer.api.HiddenLayerClient;
> import com.hiddenlayer.api.HiddenLayerClientBuilder;
>
> HiddenLayerClient client = new HiddenLayerClientBuilder().timeout(120).build();
> ```
>
> See [Error handling](https://docs.hiddenlayer.ai/docs/integrations/sdk/error_handling.md).

> [accordion] 429 Too Many Requests
>
> **Cause:** You are sending more requests than the API allows. Every SDK retries 429 responses twice by default, honoring any `Retry-After` header, and raises the error only after all retries fail. No SDK has a dedicated rate limit error: check for status 429 on the base error (`ApiError` in Python, `HiddenLayerError` in TypeScript, `HiddenLayerApiException` in Java).
>
> **Fix:**
>
> * Reduce request concurrency or volume.
> * Increase the maximum retries (`max_retries`, `maxRetries`) so the SDK waits longer before giving up.
> * Avoid adding your own retry loop on top of the SDK's retries, which can make rate limiting worse.

## Model scanning issues

> [accordion] Couldn't download model ...
>
> **Cause:** An S3 or Azure Blob Storage scan could not download the model before scanning it. Common reasons are a wrong bucket, key, container, or blob name, missing cloud credentials, or no write access to the local download directory. Python raises a `RuntimeError` and TypeScript an `Error`, each with a message that starts with `Couldn't download model`.
>
> **Fix:**
>
> 1. Read the original error from the storage SDK: `e.__cause__` in Python. In TypeScript it is part of the message.
> 2. Confirm that the object exists and that your cloud credentials can read it. Without a client of your own, the S3 scan uses the AWS SDK's default credential chain. In Python, the Azure scan uses `DefaultAzureCredential` by default.
> 3. Python downloads to `/tmp`; TypeScript downloads to the operating system's temporary directory. Confirm that the process can write there.

> [accordion] A scan seems to hang
>
> **Cause:** By default, the scanning helpers wait until the scan is done, failed, or canceled. They poll with increasing delays, up to 30 seconds apart, and have no overall time limit, so a slow or stuck scan blocks your program. The client timeout applies only to each HTTP request.
>
> **Fix:**
>
> * For large models or CI pipelines, start the scan without waiting: `wait_for_results=False` in Python, `waitForResults: false` in TypeScript, or `.waitForResults(false)` on the Java options. Then read the scan's results later. See [Scan models](https://docs.hiddenlayer.ai/docs/integrations/sdk/model_scanning.md).
> * To enforce your own limit, run the scan on a worker thread or task and stop waiting after a deadline, or set a job-level timeout in your CI system.

> [accordion] The scan status is failed
>
> **Cause:** The scan finished, but the scanner could not process one or more files. The helpers return a report whose status is `failed` instead of raising an error.
>
> **Fix:** Read the report to find which files failed and why. Pass the scan ID as the first argument:
>
> ```python Python theme={null}
> import sys
>
> from hiddenlayer import HiddenLayer
>
> client = HiddenLayer()
> report = client.model_scanner.scan_result(scan_id=sys.argv[1])
>
> print("Status:", report.status)
> print("Files that failed to scan:", report.summary.files_failed_to_scan)
> for file_result in report.file_results or []:
>     if file_result.file_error:
>         print(file_result.file_location, "->", "; ".join(file_result.file_error))
> ```
>
> ```typescript TypeScript theme={null}
> import { getScanResults, HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";
>
> const client = new HiddenLayer();
> const report = await getScanResults(client, process.argv[2]);
>
> console.log("Status:", report.status);
> console.log("Files that failed to scan:", report.summary.files_failed_to_scan);
> for (const fileResult of report.file_results ?? []) {
>     if (fileResult.file_error?.length) {
>         console.log(fileResult.file_location, "->", fileResult.file_error.join("; "));
>     }
> }
> ```
>
> ```java Java theme={null}
> import com.hiddenlayer.api.HiddenLayerClient;
> import com.hiddenlayer.api.HiddenLayerClientBuilder;
> import com.hiddenlayer.api.lib.ScanUtils;
> import com.hiddenlayer.api.types.ScanFileResultV3;
> import com.hiddenlayer.api.types.ScanReportOfRecordV3;
> import java.util.Collections;
> import java.util.List;
>
> public final class TrScanFailed {
>     public static void main(String[] args) {
>         try (HiddenLayerClient client = new HiddenLayerClientBuilder().build()) {
>             ScanReportOfRecordV3 report = ScanUtils.getScanResults(client, args[0]);
>
>             System.out.println("Status: " + report.getStatus());
>             System.out.println("Files that failed to scan: " + report.getSummary().getFilesFailedToScan().orElse(0L));
>             for (ScanFileResultV3 fileResult : report.getFileResults().orElse(Collections.<ScanFileResultV3>emptyList())) {
>                 List<String> errors = fileResult.getFileError().orElse(Collections.<String>emptyList());
>                 if (!errors.isEmpty()) {
>                     System.out.println(fileResult.getFileLocation() + " -> " + String.join("; ", errors));
>                 }
>             }
>         }
>     }
> }
> ```
>
> Unsupported or corrupted files are a common cause. If the errors are not clear, contact support with the scan ID.

> [accordion] Python on Windows: errors writing to /tmp
>
> **Cause:** In Python, `scan_s3_model` and `scan_azure_blob_model` always download to `/tmp`, and `scan_huggingface_model` downloads to `/tmp/<repo_id>` by default. That path may not exist on Windows. The TypeScript scans use the operating system's temporary directory instead.
>
> **Fix:** For Hugging Face models, pass a Windows path as `local_dir`. For S3 and Azure, download the file yourself and call `scan_file`, or run the scan from WSL or a Linux container.

## Warnings in your output

> [accordion] \[BETA] ... This endpoint is not GA or Production ready
>
> **Cause:** You called a beta endpoint, such as an AI Attack Simulation (red team) method. The warning is informational. Your request still succeeded. Each SDK reports it once per endpoint: as a `hiddenlayer.BetaWarning` through Python's `warnings` module, with `console.warn` in TypeScript, or through the `java.util.logging` logger `com.hiddenlayer.api.lib.BetaWarning` in Java. The Runtime v2 evaluation endpoints are not beta and don't warn.
>
> **Fix:** Review what beta status means in [Version compatibility and upgrades](https://docs.hiddenlayer.ai/docs/integrations/sdk/versioning.md). If you accept the risk, hide the warning:
>
> > [tab] Python
> >
> > ```python theme={null}
> > import warnings
> >
> > import hiddenlayer
> >
> > warnings.filterwarnings("ignore", category=hiddenlayer.BetaWarning)
> > ```
>
> > [tab] TypeScript
> >
> > The TypeScript SDK has no option to turn the warning off. It logs once per endpoint per process.
>
> > [tab] Java
> >
> > ```java theme={null}
> > import java.util.logging.Level;
> > import java.util.logging.Logger;
> >
> > public final class TrBetaFilter {
> >     // Keep a reference: java.util.logging holds loggers weakly, and a collected logger loses its level.
> >     private static final Logger BETA_WARNINGS = Logger.getLogger("com.hiddenlayer.api.lib.BetaWarning");
> >
> >     public static void main(String[] args) {
> >         BETA_WARNINGS.setLevel(Level.OFF);
> >     }
> > }
> > ```

## Debug checklist

If your problem is not listed above, work through these steps. They collect the information support needs.

### Check the SDK version

```bash Python theme={null}
python -c "import hiddenlayer; print(hiddenlayer.__version__)"
```

```bash TypeScript theme={null}
npm ls @hiddenlayerai/hiddenlayer-sdk
```

```bash Java theme={null}
./gradlew dependencies --configuration runtimeClasspath | grep hiddenlayer-java
```

With Maven, run `mvn dependency:tree -Dincludes=com.hiddenlayer.api`. Compare the version with the latest release on [PyPI](https://pypi.org/project/hiddenlayer-sdk/), [npm](https://www.npmjs.com/package/@hiddenlayerai/hiddenlayer-sdk), or [Maven Central](https://central.sonatype.com/artifact/com.hiddenlayer.api/hiddenlayer-java).

### Check environment variables

This script reports whether each variable the SDKs read is set, without printing secret values:

```python Python theme={null}
import os

VARIABLES = [
    "HIDDENLAYER_CLIENT_ID",
    "HIDDENLAYER_CLIENT_SECRET",
    "HIDDENLAYER_TOKEN",
    "HIDDENLAYER_BASE_URL",
]

for name in VARIABLES:
    value = os.environ.get(name)
    if value is None:
        status = "not set"
    elif value.strip() == "":
        status = "set but empty"
    elif value != value.strip():
        status = "set (has leading or trailing whitespace)"
    else:
        status = "set"
    print(f"{name}: {status}")
```

```typescript TypeScript theme={null}
const VARIABLES = ["HIDDENLAYER_CLIENT_ID", "HIDDENLAYER_CLIENT_SECRET", "HIDDENLAYER_TOKEN", "HIDDENLAYER_BASE_URL"];

for (const name of VARIABLES) {
    const value = process.env[name];
    let status = "set";
    if (value === undefined) {
        status = "not set";
    } else if (value.trim() === "") {
        status = "set but empty";
    } else if (value !== value.trim()) {
        status = "set (has leading or trailing whitespace)";
    }
    console.log(`${name}: ${status}`);
}
```

```java Java theme={null}
public final class TrEnvCheck {
    public static void main(String[] args) {
        String[] variables = {
            "HIDDENLAYER_CLIENT_ID", "HIDDENLAYER_CLIENT_SECRET", "HIDDENLAYER_TOKEN", "HIDDENLAYER_BASE_URL"
        };
        for (String name : variables) {
            String value = System.getenv(name);
            String status = "set";
            if (value == null) {
                status = "not set";
            } else if (value.trim().isEmpty()) {
                status = "set but empty";
            } else if (!value.equals(value.trim())) {
                status = "set (has leading or trailing whitespace)";
            }
            System.out.println(name + ": " + status);
        }
    }
}
```

You need either both `HIDDENLAYER_CLIENT_ID` and `HIDDENLAYER_CLIENT_SECRET`, or `HIDDENLAYER_TOKEN`. If both kinds are set, the token wins. `HIDDENLAYER_BASE_URL` is used only when the code sets no region or base URL. The SDKs no longer read `HIDDENLAYER_LOG` or `HIDDENLAYER_CUSTOM_HEADERS`.

### Turn on debug logging

The SDKs' logging is silent by default. To log each request, configure the client with the `debug` level and turn off `silent`:

```python Python theme={null}
from hiddenlayer import HiddenLayer

client = HiddenLayer(logging={"level": "debug", "silent": False})
```

```typescript TypeScript theme={null}
import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";

const client = new HiddenLayer({ logging: { level: "debug", silent: false } });
```

```java Java theme={null}
import com.hiddenlayer.api.HiddenLayerClient;
import com.hiddenlayer.api.HiddenLayerClientBuilder;
import com.hiddenlayer.api.core.LogConfig;
import com.hiddenlayer.api.core.LogLevel;

HiddenLayerClient client = new HiddenLayerClientBuilder()
        .logging(LogConfig.builder().level(LogLevel.DEBUG).silent(false).build())
        .build();
```

At the `debug` level, the SDKs log each request's method, URL, and headers, and each response's status code. TypeScript and Java also log the response headers. They replace credentials, such as the `Authorization` request header and `Set-Cookie` response headers, with `[REDACTED]`, and they don't log request or response bodies.

Python's default logger writes through the standard `logging` module, under the logger name `fern`, and prints only each message, such as `DEBUG - Making HTTP request`. To see the method, URL, and headers, pass your own logger in the configuration (`logging={"level": "debug", "silent": False, "logger": my_logger}`). It needs `debug`, `info`, `warn`, and `error` methods, and receives the details as keyword arguments.

> [!WARNING]
>
> Debug logs still show URLs and the other headers your requests carry. Use debug logging only while troubleshooting, don't share the logs publicly, and review them before you send them to anyone.

### Inspect raw response headers

Response headers can explain what happened, for example whether a request was blocked or rate limited. They also carry the correlation ID (`x-correlation-id`) that support can use to find the request. Use the raw-response accessor to read them, or read them from the error:

```python Python theme={null}
from hiddenlayer import HiddenLayer, InteractionEvaluationRequestMetadata
from hiddenlayer.core import ApiError

client = HiddenLayer()

try:
    raw = client.runtime.with_raw_response.evaluate_interaction(
        metadata=InteractionEvaluationRequestMetadata(model="gpt-4o", provider="openai", requester_id="debug-check"),
        interaction={"model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}]},
    )
except ApiError as e:
    print("Status:", e.status_code)
    print("Headers:", e.headers)
    print("Body:", e.body)
else:
    print("Status:", raw.status_code)
    print("Headers:", raw.headers)
    print("Action:", raw.data.outcome.action)
```

```typescript TypeScript theme={null}
import { HiddenLayer, HiddenLayerError } from "@hiddenlayerai/hiddenlayer-sdk";

const client = new HiddenLayer();

try {
    const { data, rawResponse } = await client.runtime
        .evaluateInteraction({
            metadata: { model: "gpt-4o", provider: "openai", requester_id: "debug-check" },
            interaction: { model: "gpt-4o", messages: [{ role: "user", content: "Hello" }] },
        })
        .withRawResponse();
    console.log("Status:", rawResponse.status);
    console.log("Headers:", Object.fromEntries(rawResponse.headers.entries()));
    console.log("Action:", data.outcome.action);
} catch (err) {
    if (!(err instanceof HiddenLayerError)) {
        throw err;
    }
    console.log("Status:", err.statusCode);
    console.log("Correlation ID:", err.rawResponse?.headers.get("x-correlation-id"));
    console.log("Body:", err.body);
}
```

```java Java theme={null}
import com.hiddenlayer.api.HiddenLayerClient;
import com.hiddenlayer.api.HiddenLayerClientBuilder;
import com.hiddenlayer.api.core.BaseHiddenLayerClientHttpResponse;
import com.hiddenlayer.api.core.HiddenLayerApiException;
import com.hiddenlayer.api.resources.runtime.requests.InteractionEvaluationRequest;
import com.hiddenlayer.api.resources.runtime.types.InteractionEvaluationRequestInteraction;
import com.hiddenlayer.api.types.InteractionEvaluationRequestMetadata;
import com.hiddenlayer.api.types.InteractionEvaluationResponse;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

public final class TrRawHeaders {
    public static void main(String[] args) {
        Map<String, Object> message = new LinkedHashMap<>();
        message.put("role", "user");
        message.put("content", "Hello");
        Map<String, Object> payload = new LinkedHashMap<>();
        payload.put("model", "gpt-4o");
        payload.put("messages", Collections.singletonList(message));

        try (HiddenLayerClient client = new HiddenLayerClientBuilder().build()) {
            BaseHiddenLayerClientHttpResponse<InteractionEvaluationResponse> raw = client.runtime()
                    .withRawResponse()
                    .evaluateInteraction(InteractionEvaluationRequest.builder()
                            .metadata(InteractionEvaluationRequestMetadata.builder()
                                    .model("gpt-4o")
                                    .requesterId("debug-check")
                                    .provider("openai")
                                    .build())
                            .interaction(InteractionEvaluationRequestInteraction.of(payload))
                            .build());
            System.out.println("Headers: " + raw.headers());
            System.out.println("Action: " + raw.body().getOutcome().getAction());
        } catch (HiddenLayerApiException e) {
            System.out.println("Status: " + e.statusCode());
            System.out.println("Headers: " + e.headers());
            System.out.println("Body: " + e.body());
        }
    }
}
```

### Contact support

If you still need help, contact HiddenLayer through the [Support Portal](https://docs.hiddenlayer.ai/docs/resources/support/support_portal.md). Include:

* The SDK, its version, and the language runtime version (Python, Node.js, or Java)
* The region (`prod-us` or `prod-eu`) or base URL
* The full error type and message
* Relevant IDs, such as a scan ID, workflow ID, evaluation ID, or the correlation ID from the response headers
* Debug logs with secrets and sensitive data removed

Never send your client secret or bearer token to support.
