# HiddenLayer Python SDK

The HiddenLayer platform enhances the developer experience for protecting artificial intelligence (AI) and machine learning (ML) models without needing to write complex code or manage the underlying infrastructure.

The HiddenLayer SDK uses Python to provide a simple and efficient way to interact with the HiddenLayer API. This guide will walk you through how to install and use the HiddenLayer Python SDK to retrieve AI Runtime Security and AI Supply Chain Security information.

This SDK can be used to interact with the following HiddenLayer services:

- AI Supply Chain Security (model scanning)
- AI Runtime Security — Interactions (LLM input/output analysis)
- AI Runtime Security — Agentic evaluation endpoints
- AI Attack Simulation (red team evaluations)


Active Development
This project is under active development. The full API surface is documented in the SDK's api.md.
Some endpoints are marked **Beta**; see the Beta API Guidelines on the Developer Portal.

## Before You Begin

The following are required for using the HiddenLayer Python SDK:

- Python 3.9+ (this should include pip)
- HiddenLayer API key and secret; see [Create API Key](/docs/products/console/apikey_aisec_platform#create-api-key)


## Install SDK

Install the `hiddenlayer-sdk` package with pip.

```
pip install hiddenlayer-sdk
```

The HiddenLayer Python SDK offers functionality to interact with other services, such as Hugging Face, AWS, and Azure.

- For the optional async `aiohttp` HTTP backend:

```
pip install hiddenlayer-sdk[aiohttp]
```
- To scan models from Hugging Face, AWS S3, or Azure Blob Storage, install the platform packages separately as needed:

```
pip install huggingface_hub
pip install boto3
pip install azure-identity azure-storage-blob
```


## Usage Overview

The main client exposed by the SDK is `hiddenlayer.HiddenLayer`, which provides access to all HiddenLayer services exposed via API. An async equivalent (`AsyncHiddenLayer`) is also available with the same interface.

```python
from hiddenlayer import HiddenLayer

client = HiddenLayer(
    # Defaults to "prod-us"; use "prod-eu" for the EU region.
    # environment="prod-eu",
    # Credentials are sourced from the environment by default:
    #   HIDDENLAYER_CLIENT_ID, HIDDENLAYER_CLIENT_SECRET (OAuth2)
    #   HIDDENLAYER_TOKEN (bearer token)
)
```

API methods are grouped by resource on the client, for example:

```
client.<resource>.<method>(<parameters>)
```

For the full list of resources and methods, see the SDK's api.md and the Developer Portal.

## Authentication

To authenticate to HiddenLayer, generate a client ID and secret from the platform UI. See [Create API Key](/docs/products/console/apikey_aisec_platform#create-api-key).

The SDK supports two authentication methods:

- **OAuth2 client credentials** — set `HIDDENLAYER_CLIENT_ID` and `HIDDENLAYER_CLIENT_SECRET`, or pass `client_id` / `client_secret` directly.
- **Bearer token** — set `HIDDENLAYER_TOKEN`, or pass `bearer_token` directly.


```python
from hiddenlayer import HiddenLayer

client = HiddenLayer(
    client_id="...",      # Your HiddenLayer API Client ID
    client_secret="...",  # Your HiddenLayer API Secret Key
)
```

To target a custom endpoint (for example a locally running Runtime Security container), set `base_url` when constructing the client, or set the `HIDDENLAYER_BASE_URL` environment variable.

## Async Usage

An async client is available with the same interface as the synchronous client. Import `AsyncHiddenLayer` and `await` each API call:

```python
import asyncio
from hiddenlayer import AsyncHiddenLayer

client = AsyncHiddenLayer()

async def main() -> None:
    response = await client.interactions.analyze(
        metadata={
            "model": "gpt-5",
            "requester_id": "user-1234",
        },
        input={
            "messages": [
                {"role": "user", "content": "What is the largest moon of Jupiter?"}
            ]
        },
    )
    print(response.analysis)

asyncio.run(main())
```

For improved concurrency with the async client, install `hiddenlayer-sdk[aiohttp]` and pass `http_client=DefaultAioHttpClient()`.
See the SDK README for details.

## Data Models

The HiddenLayer Python SDK uses Pydantic to represent data for APIs, which makes the code more readable and type-safe and easier to work with. Request parameters use TypedDicts. Responses are Pydantic models under `hiddenlayer.types`, with helpers such as `model.to_json()` and `model.to_dict()`.

Specific data models are organized under `hiddenlayer.types`. Each resource exposes its own request and response types — see the SDK's api.md for the full inventory.

## Example Usage

The HiddenLayer Python SDK comes with a number of examples demonstrating how to use the library for various common use-cases.

These examples and more are located in the `examples` directory of the GitHub repository (including `demo.py` for model scanning and `red_team/` for Attack Simulation).

### Initiate Client

```python
from hiddenlayer import HiddenLayer

client = HiddenLayer(
    # environment="prod-eu",  # default is "prod-us"
    client_id="...",
    client_secret="...",
)
```

### Scanning Models

#### Scanning a model on disk

```python
scan_results = client.model_scanner.scan_file(
    model_name="sdk_example_model",
    model_path="./models/example_model.xgb",
)

print(scan_results)
```

You can also scan an entire directory with `client.model_scanner.scan_folder(...)`.

#### Scanning a Hugging Face model

Requires `pip install huggingface_hub`.

```python
huggingface_scan_results = client.model_scanner.scan_huggingface_model(
    repo_id="drhyrum/bert-tiny-torch-vuln",
    model_name="bert-tiny-torch-vuln",
)

print(huggingface_scan_results)
```

Alternatively, use the community scanner without downloading the model first:

```python
from hiddenlayer.lib import CommunityScanSource

huggingface_scan_results = client.community_scanner.community_scan(
    model_name="bert-tiny-torch-vuln",
    model_path="drhyrum/bert-tiny-torch-vuln",
    model_source=CommunityScanSource.HUGGING_FACE,
)

print(huggingface_scan_results)
```

#### Scanning from cloud storage

```python
# Requires: pip install boto3
s3_results = client.model_scanner.scan_s3_model(
    model_name="my-s3-model",
    bucket="my-bucket",
    key="models/example_model.xgb",
)

# Requires: pip install azure-identity azure-storage-blob
azure_results = client.model_scanner.scan_azure_blob_model(
    model_name="my-azure-model",
    account_url="https://mystorageaccount.blob.core.windows.net",
    container="my-container",
    blob="models/example_model.xgb",
)
```

### Runtime Security

#### Analyzing LLM Interactions

Use `client.interactions.analyze` to send LLM input and output to the Interactions endpoint.
For a full walkthrough and an example response, see [Getting Started with Interactions](/docs/products/runtime/interactions).

```python
response = client.interactions.analyze(
    metadata={
        "model": "gpt-5",
        "requester_id": "user-1234",
        "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."}
        ]
    },
)
print(response)
```

To target a locally running Runtime Security container instead of the SaaS endpoint, set `base_url="http://localhost:8000"` (or your container's URL) when constructing the client.

#### Agentic evaluation endpoints

Use `client.runtime.evaluate_request`, `client.runtime.evaluate_response`, and `client.runtime.evaluate_interaction` for Agentic Runtime Security use cases. For a full walkthrough, see [Get Started with Agentic Runtime Security](/docs/products/runtime/agentic/get_started).

```python
response = client.runtime.evaluate_request(
    body={
        "model": "gpt-4o",
        "messages": [
            {"role": "user", "content": "What is the largest moon of Jupiter?"}
        ],
    },
)
print(response)
```

### AI Attack Simulation

Use `client.evaluation_sessions.red_team` (high-level session helpers) or `client.evaluations.red_team` (low-level API) to drive red team evaluations. For a full walkthrough, see [Configuring an Attack Simulation against an Application](/docs/products/ai-attack-simulation/custom-attack-sim/basic-custom-attack).

```python
import asyncio
from hiddenlayer import AsyncHiddenLayer

client = AsyncHiddenLayer()

async def main() -> None:
    session = await client.evaluation_sessions.red_team.start_session(
        name="sdk-example-session",
        target_model="my-app",
        execution_strategy_type="static_prompt_set",
        # prompt_set_id="...",
        max_turns=3,
    )
    print(session.workflow_id)

asyncio.run(main())
```

## Advanced Configuration

The SDK supports retries, timeouts, pagination helpers, raw/streaming responses, and a custom httpx client. Defaults and examples are in the SDK README.

Common client options include:

```python
from hiddenlayer import HiddenLayer

client = HiddenLayer(
    timeout=20.0,     # default is 1 minute
    max_retries=2,    # default is 2
    # base_url="http://localhost:8000",
)
```

To check the installed package version at runtime:

```python
import hiddenlayer

print(hiddenlayer.__version__)
```