> ## 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.

# Quickstart

> Install the HiddenLayer Python SDK, configure credentials, and analyze your first LLM interaction in a few minutes.

In this quickstart, you install the SDK, set your credentials, and send one LLM interaction (a user prompt and a model response) to the HiddenLayer AI Runtime Security Interactions endpoint for analysis.

This example uses `client.interactions.analyze` because it is a generally available (non-beta) endpoint and needs no model files or other setup. It is a quick way to confirm that your installation, credentials, and network access work.

## Before you begin

You need:

* Python 3.9 or later (3.11 or later recommended).
* A HiddenLayer client ID and client secret with Interactions (Read, Write) permissions. See [Create API Key](/docs/products/console/apikey_aisec_platform#create-api-key).
* Your region: `prod-us` (default) or `prod-eu`.

For details, see [Prerequisites](/docs/integrations/sdk_python/prerequisites).

## Make your first request

**1. Create a project folder and virtual environment**

A virtual environment keeps the SDK and its dependencies isolated from other Python projects.

**macOS/Linux**

```bash theme={null}
mkdir hiddenlayer-quickstart
cd hiddenlayer-quickstart
python3 -m venv .venv
source .venv/bin/activate
```

**Windows**

```powershell theme={null}
mkdir hiddenlayer-quickstart
cd hiddenlayer-quickstart
py -m venv .venv
.venv\Scripts\Activate.ps1
```

**2. Install the SDK**

```bash theme={null}
python -m pip install --upgrade pip
python -m pip install hiddenlayer-sdk
```

For more options, see [Installation](/docs/integrations/sdk_python/installation).

**3. Set your credentials**

The client reads your client ID and client secret from environment variables, so you never have to put them in code.

**macOS/Linux**

```bash theme={null}
export HIDDENLAYER_CLIENT_ID="your-client-id"
export HIDDENLAYER_CLIENT_SECRET="your-client-secret"
```

**Windows**

```powershell theme={null}
$env:HIDDENLAYER_CLIENT_ID = "your-client-id"
$env:HIDDENLAYER_CLIENT_SECRET = "your-client-secret"
```

Replace the placeholders with your values. If your API key is in the EU region, change `environment="prod-us"` to `environment="prod-eu"` in the script in the next step.

> [!NOTE]
>
> These variables last only for the current terminal session. If you open a new terminal, set them again, or use a `.env` file as described in [Authentication and configuration](/docs/integrations/sdk_python/authentication#optional-use-a-env-file).

**4. Create quickstart.py**

Create a file named `quickstart.py` in your project folder with this content:

```python quickstart.py theme={null}
import sys

import hiddenlayer
from hiddenlayer import HiddenLayer


def main() -> int:
    # The client reads HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET
    # from the environment. Use "prod-eu" if your API key is in the EU region.
    client = HiddenLayer(environment="prod-us")

    try:
        response = client.interactions.analyze(
            # Metadata describes where the interaction came from.
            metadata={
                "model": "gpt-4o",               # The LLM that produced the output
                "requester_id": "quickstart-user",  # Who sent the prompt
                "provider": "openai",            # Optional: the LLM provider
            },
            # The prompt sent to the LLM.
            input={
                "messages": [
                    {"role": "user", "content": "What is the largest moon of Jupiter?"}
                ]
            },
            # The LLM's reply.
            output={
                "messages": [
                    {"role": "assistant", "content": "The largest moon of Jupiter is Ganymede."}
                ]
            },
        )
    except hiddenlayer.AuthenticationError:
        print("Authentication failed (401). Check HIDDENLAYER_CLIENT_ID, "
              "HIDDENLAYER_CLIENT_SECRET, and that the environment matches your API key's region.")
        return 1
    except hiddenlayer.PermissionDeniedError:
        print("Permission denied (403). Make sure your API key has Interactions permissions.")
        return 1
    except hiddenlayer.APIConnectionError as e:
        print(f"Could not reach the HiddenLayer API: {e.__cause__!r}")
        return 1
    except hiddenlayer.APIStatusError as e:
        print(f"The API returned an error: HTTP {e.status_code}: {e.message}")
        return 1
    finally:
        client.close()

    # The overall verdict. It can be absent, so check before using it.
    if response.evaluation is not None:
        print(f"Action:       {response.evaluation.action}")
        print(f"Threat level: {response.evaluation.threat_level}")
        print(f"Detections:   {response.evaluation.has_detections}")

    # One entry per analysis (detector) that ran on the interaction.
    print("Analyses:")
    for analysis in response.analysis:
        print(f"  - {analysis.name} ({analysis.phase}): detected={analysis.detected}")

    return 0


if __name__ == "__main__":
    sys.exit(main())
```

The `try` block catches the most common errors and prints a hint for each. `APIStatusError` is listed last because it is the parent class of `AuthenticationError` and `PermissionDeniedError`, so it catches any other HTTP error status.

**5. Run the script**

```bash theme={null}
python quickstart.py
```

## Expected result

The script prints the overall evaluation, followed by one line per analysis. The output looks similar to this example. Analysis names, the number of analyses, and the results depend on your project's policy and on the interaction you send, so your values will differ.

```text theme={null}
Action:       Allow
Threat level: None
Detections:   False
Analyses:
  - block_list (input): detected=False
  - prompt_injection (input): detected=False
  - personally_identifiable_information (input): detected=False
  ...
```

What the fields mean:

| Field | Description |
| - | - |
| `evaluation.action` | The recommended action based on your policy: `Allow`, `Alert`, `Redact`, or `Block`. |
| `evaluation.threat_level` | The overall threat level: `None`, `Low`, `Medium`, `High`, or `Critical`. |
| `evaluation.has_detections` | `True` if any analysis found a threat. |
| `analysis[].name` | The name of an analysis that ran on the interaction. |
| `analysis[].phase` | The part of the interaction the analysis ran on, such as input or output. |
| `analysis[].detected` | `True` if this analysis found something. |

The response also includes `metadata` (such as `event_id` and processing time), `analyzed_data` (the content that was analyzed), and `modified_data` (the input and output after any redaction). To see everything, print `response.to_json()`.

For a description of the Interactions response, see [Getting started with Interactions](/docs/products/runtime/interactions).

## What just happened

1. **The client read its configuration.** `HiddenLayer()` read `HIDDENLAYER_CLIENT_ID` and `HIDDENLAYER_CLIENT_SECRET` from the environment and set the base URL to `https://api.us.hiddenlayer.ai` for `prod-us`.
2. **The client obtained an access token.** Before sending the request, the SDK exchanged your client ID and client secret for an OAuth2 access token at `https://api.us.hiddenlayer.ai/oauth2/token`. It caches this token and refreshes it automatically, so you do not manage tokens yourself.
3. **The client sent the request.** It sent the metadata, input, and output to the Interactions endpoint with the token in the `Authorization` header. If the request had failed with a temporary error, such as a timeout or HTTP 429 or 5xx, the SDK would have retried up to two times.
4. **The SDK parsed the response.** The JSON response was converted into an `InteractionAnalyzeResponse` Pydantic model, so you can read fields as attributes, such as `response.evaluation.action`.

To learn more about clients, resources, and response models, see [Core concepts](/docs/integrations/sdk_python/core_concepts).

> **Optional: async version**
>
> If your application uses `asyncio`, use `AsyncHiddenLayer`. It takes the same arguments and reads the same environment variables. Await each call.
>
> ```python quickstart_async.py theme={null}
> import asyncio
> import sys
>
> import hiddenlayer
> from hiddenlayer import AsyncHiddenLayer
>
>
> async def main() -> int:
>     async with AsyncHiddenLayer(environment="prod-us") as client:
>         try:
>             response = await client.interactions.analyze(
>                 metadata={
>                     "model": "gpt-4o",
>                     "requester_id": "quickstart-user",
>                     "provider": "openai",
>                 },
>                 input={
>                     "messages": [
>                         {"role": "user", "content": "What is the largest moon of Jupiter?"}
>                     ]
>                 },
>                 output={
>                     "messages": [
>                         {"role": "assistant", "content": "The largest moon of Jupiter is Ganymede."}
>                     ]
>                 },
>             )
>         except hiddenlayer.AuthenticationError:
>             print("Authentication failed (401). Check your credentials and region.")
>             return 1
>         except hiddenlayer.PermissionDeniedError:
>             print("Permission denied (403). Check your API key's Interactions permissions.")
>             return 1
>         except hiddenlayer.APIConnectionError as e:
>             print(f"Could not reach the HiddenLayer API: {e.__cause__!r}")
>             return 1
>         except hiddenlayer.APIStatusError as e:
>             print(f"The API returned an error: HTTP {e.status_code}: {e.message}")
>             return 1
>
>     if response.evaluation is not None:
>         print(f"Action:       {response.evaluation.action}")
>         print(f"Threat level: {response.evaluation.threat_level}")
>     for analysis in response.analysis:
>         print(f"  - {analysis.name}: detected={analysis.detected}")
>     return 0
>
>
> if __name__ == "__main__":
>     sys.exit(asyncio.run(main()))
> ```

## If it fails

> **ModuleNotFoundError: No module named 'hiddenlayer'**
>
> The virtual environment is not active, or the SDK is installed in a different environment. Activate `.venv` and run `python -m pip install hiddenlayer-sdk`. See [Installation](/docs/integrations/sdk_python/installation#common-installation-errors).

> **Authentication failed (401)**
>
> The client could not get a valid token. Check that both environment variables are set in the same terminal where you run the script, that the values have no extra spaces or quotes, and that `environment` matches the region where the API key was created. See [Troubleshooting](/docs/integrations/sdk_python/troubleshooting).

> **Permission denied (403)**
>
> Your API key is valid but lacks permission for the Interactions endpoint. Create a key with Interactions (Read, Write) permissions. See [Create API Key](/docs/products/console/apikey_aisec_platform#create-api-key).

> **Could not reach the HiddenLayer API**
>
> The SDK could not connect after retrying. Check your network, firewall, and proxy settings, and confirm the base URL. To configure a proxy, see [Authentication and configuration](/docs/integrations/sdk_python/authentication#use-a-proxy).

> **ValueError: Ambiguous URL**
>
> `HIDDENLAYER_BASE_URL` is set in your environment and the script also passes `environment`. Unset the variable, or see [How the client resolves the base URL](/docs/integrations/sdk_python/authentication#how-the-client-resolves-the-base-url).

For more problems and fixes, see [Troubleshooting](/docs/integrations/sdk_python/troubleshooting) and [Error handling](/docs/integrations/sdk_python/error_handling).

## Next steps

> **[Scan models](/docs/integrations/sdk_python/model_scanning)**
>
> Scan model files for malicious code and vulnerabilities.

> **[Runtime security](/docs/integrations/sdk_python/runtime_security)**
>
> Protect LLM applications and agents with Interactions and the agentic evaluation endpoints.

> **[Attack simulation](/docs/integrations/sdk_python/attack_simulation)**
>
> Run red team sessions against your AI application.

> **[Core concepts](/docs/integrations/sdk_python/core_concepts)**
>
> Understand clients, resources, and response models.
