---
title: "Gray Swan Cygnal Guardrails on LiteLLM AI Gateway"
url: "/docs/proxy/guardrails/grayswan"
canonical_url: "https://docs.litellm.ai/docs/proxy/guardrails/grayswan"
type: "docs"
last_updated: "2026-11-23"
summary: "Monitor or block policy violations, jailbreaks and indirect prompt injection with Gray Swan Cygnal on the LiteLLM AI Gateway, including Claude Code traffic."
related:
  - "/docs/proxy/guardrails/enkryptai"
  - "/docs/proxy/guardrails/guardrails_ai"
---
# Gray Swan Cygnal Guardrails on LiteLLM AI Gateway

> Index of all LiteLLM docs: https://docs.litellm.ai/llms.txt


Use [Gray Swan Cygnal](https://docs.grayswan.ai/cygnal/monitor-requests) to continuously monitor conversations for policy violations, indirect prompt injection (IPI), jailbreak attempts, and other safety risks.

Cygnal returns a `violation` score between `0` and `1` (higher means more likely to violate policy), plus metadata such as violated rule indices, mutation detection, and IPI flags. LiteLLM can automatically block or monitor requests based on this signal.

---

## Quick Start

### 1. Obtain Credentials

1. Log in to our Gray Swan platform and generate a Cygnal API key. 

    For existing customers, you should already have access to our [platform](https://platform.grayswan.ai).

    For new users, please register at this [page](https://hubs.ly/Q03-sX1J0) and we are more than happy to give you an onboarding!

2. Configure environment variables for the LiteLLM proxy host:

    ```bash
    export GRAYSWAN_API_KEY="your-grayswan-key"
    export GRAYSWAN_API_BASE="https://api.grayswan.ai"
    ```

### 2. Configure `config.yaml`

Add a guardrail entry that references the Gray Swan integration. Below is our recommended settings.

```yaml
model_list:                                 # this part is a standard litellm configuration for reference
  - model_name: openai/gpt-6-luna
    litellm_params:
      model: openai/gpt-6-luna
      api_key: os.environ/OPENAI_API_KEY

guardrails:
  - guardrail_name: "cygnal-monitor"
    litellm_params:
      guardrail: grayswan
      mode: [pre_call, post_call]            # monitor both input and output
      api_key: os.environ/GRAYSWAN_API_KEY
      api_base: os.environ/GRAYSWAN_API_BASE  # optional
      optional_params:
        on_flagged_action: passthrough         # or "block" or "monitor"
        violation_threshold: 0.5               # score >= threshold is flagged
        reasoning_mode: hybrid                 # off | hybrid | thinking
        policy_id: "your-cygnal-policy-id"     # Optional: Your Cygnal policy ID. Defaults to a content safety policy if empty.
      streaming_end_of_stream_only: true       # For streaming API, only send the assembled message to Cygnal (post_call only). Defaults to false.
      default_on: true
      guardrail_timeout: 30                   # Defaults to 30 seconds. Change accordingly.
      fail_open: true                         # Defaults to true; set to false to propagate guardrail errors.

general_settings:
  master_key: "your-litellm-master-key"

litellm_settings:
  set_verbose: true
```

### 3. Launch the Proxy

```bash
litellm --config config.yaml --port 4000
```

---

## Choosing Guardrail Modes

Gray Swan can run during `pre_call`, `during_call`, and `post_call` stages. Combine modes based on your latency and coverage requirements. 

| Mode         | When it Runs      | Protects              | Typical Use Case |
|--------------|-------------------|-----------------------|------------------|
| `pre_call`   | Before LLM call   | User input only       | Block prompt injection before it reaches the model |
| `during_call`| Parallel to call  | User input only       | Low-latency monitoring without blocking |
| `post_call`  | After response    | Model outputs, judged with the request context | Scan answers and tool calls for policy violations, leaked secrets, or IPI |

When using `during_call` with `on_flagged_action: block` or `on_flagged_action: passthrough`:

- **The LLM call runs in parallel** with the guardrail check using `asyncio.gather`
- **LLM tokens are still consumed** even if the guardrail detects a violation
- The guardrail exception prevents the response from reaching the user, but **does not cancel the running LLM task**
- This means you pay full LLM costs while returning an error/passthrough message to the user

**Recommendation:** Use `pre_call` and `post_call` instead of `during_call` for `passthrough` (or `block`) `on_flagged_action` (see our recommended configuration above). Reserve `during_call` for `monitor` mode ONLY when you want low-latency logging without impacting the user experience.

### What Cygnal receives on `post_call`

On `post_call`, LiteLLM sends Cygnal the request conversation followed by the model's answer, so Cygnal can tell whether the answer, and any tool call in it, is justified by what came before. The answer includes its tool calls, and the request's `tools` definitions are sent alongside the messages. This means a `post_call`-only setup also sends the user's prompts and tool results for that request to Gray Swan

Answers that contain only tool calls are scanned too. With `on_flagged_action: block` a flagged tool call returns 400 instead of reaching the client, and with `fail_open: false` a Cygnal error fails the request the same way it does for a text answer

The [skip flags](./quick_start#skip-system-messages-in-guardrail-evaluation) limit what is sent. `skip_system_message_in_guardrail` and `skip_tool_message_in_guardrail` drop those messages from the conversation, and `scan_only_tool_results` keeps only tool results and leaves out the request `tools`. The model's answer is always sent. If LiteLLM cannot read the conversation for an endpoint, Cygnal receives the answer alone

With streaming and no `streaming_end_of_stream_only`, each sampled chunk check carries the same conversation, so set `streaming_end_of_stream_only: true` to send it once per response

### When Cygnal does not return a usable score

LiteLLM acts on a Cygnal reply only when it is a JSON object with `error` unset or false and a `violation` number from `0` to `1`. Any other reply counts as a failed check, the same as a timeout or an HTTP error from Cygnal. That covers a reply with `error: true` (even when it also carries a score), a missing or `null` `violation`, a string or boolean score, a score below `0` or above `1`, and `NaN` or infinite values

A failed check follows `fail_open`. With the default `fail_open: true` the request proceeds and LiteLLM logs the guardrail status as `guardrail_failed_to_respond`. With `fail_open: false` the request fails with a 500, or ends with an error event when a streamed `post_call` response has already started

---

## Work with Claude Code

Follow the official litellm [guide](https://docs.litellm.ai/docs/tutorials/claude_responses_api) on setting up Claude Code with litellm, with the guardrail part mentioned above added to your litellm configuration. Cygnal natively supports coding agent policies defense. Define your own policy or use the provided coding policies on the platform. The example config we show above is also the recommended setup for Claude Code (with the `policy_id` replaced with an appropriate one).

---

## Per-request overrides via `extra_body`

You can override parts of the Gray Swan guardrail configuration on a per-request basis by passing `litellm_metadata.guardrails[*].grayswan.extra_body`.

`extra_body` is merged into the Cygnal request body and takes precedence over specific fields from `config.yaml`, which are `policy_id`, `violation_threshold`, and `reasoning_mode`.

If you include a `metadata` field inside `extra_body`, it is forwarded to the Cygnal API as-is under the request body's `metadata` field.

Example:

```bash
curl -X POST "http://0.0.0.0:4000/v1/messages?beta=true" \
  -H "Authorization: Bearer token" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openrouter/anthropic/claude-sonnet-5",
    "messages": [{"role": "user", "content": "hello"}],
    "litellm_metadata": {
      "guardrails": [
        {
          "cygnal-monitor": {
            "extra_body": {
              "policy_id": "specific policy id you want to use",
              "metadata": {
                "user": "health-check"
              }
            }
          }
        }
      ]
    }
  }'
```

OpenAI client:

```python
from openai import OpenAI

client = OpenAI(api_key="anything", base_url="http://0.0.0.0:4000")

resp = client.responses.create(
    model="openrouter/anthropic/claude-sonnet-5",
    input="hello",
    extra_body={
        "litellm_metadata": {
            "guardrails": [
                {
                    "cygnal-monitor": {
                        "extra_body": {
                            "policy_id": "69038214e5cdb6befc5e991e",
                            "metadata": {"trace_id": "trace-123"},
                        }
                    }
                }
            ]
        }
    },
)
```

Anthropic client:

```python
from anthropic import Anthropic

client = Anthropic(api_key="anything", base_url="http://0.0.0.0:4000")

resp = client.messages.create(
    model="openrouter/anthropic/claude-sonnet-5",
    max_tokens=256,
    messages=[{"role": "user", "content": "hello"}],
    extra_body={
        "litellm_metadata": {
            "guardrails": [
                {
                    "cygnal-monitor": {
                        "extra_body": {
                            "policy_id": "69038214e5cdb6befc5e991e",
                            "metadata": {"trace_id": "trace-123"},
                        }
                    }
                }
            ]
        }
    },
)
```

Notes:

- The guardrail name (for example, `cygnal-monitor`) must match the `guardrail_name` in `config.yaml`.
- Per-request guardrail overrides may require a premium license, depending on your proxy settings.

---

## Configuration Reference

| Parameter                             | Type            | Description |
|---------------------------------------|-----------------|-------------|
| `api_key`                             | string          | Gray Swan Cygnal API key. Reads from `GRAYSWAN_API_KEY` if omitted. |
| `api_base`                            | string          | Override for the Gray Swan API base URL. Defaults to `https://api.grayswan.ai` or `GRAYSWAN_API_BASE`. |
| `mode`                                | string or list  | Guardrail stages (`pre_call`, `during_call`, `post_call`). |
| `optional_params.on_flagged_action`   | string          | `monitor` (log only), `block` (raise `HTTPException`), or `passthrough` (replace response content with violation message, no 400 error). |
| `optional_params.violation_threshold` | number (0-1)    | Scores at or above this value are considered violations. |
| `optional_params.reasoning_mode`      | string          | `off`, `hybrid`, or `thinking`. Enables Cygnal's reasoning capabilities. |
| `optional_params.categories`          | object          | Map of custom category names to descriptions. |
| `optional_params.policy_id`           | string          | Gray Swan policy identifier. |
| `guardrail_timeout`                   | number          | Timeout in seconds for the Cygnal request. Defaults to 30. |
| `fail_open`                           | boolean         | If true, the request proceeds and the failure is logged when Cygnal errors, times out, or returns a reply without a usable score; if false, the request fails. Defaults to true. See [When Cygnal does not return a usable score](#when-cygnal-does-not-return-a-usable-score). |
| `streaming_end_of_stream_only`        | boolean         | For streaming `post_call`, only send the final assembled response to Cygnal. Defaults to false. |
| `default_on`                          | boolean         | Run the guardrail on every request by default. |

## Related pages

- [EnkryptAI Guardrails](https://docs.litellm.ai/docs/proxy/guardrails/enkryptai.md)
- [Guardrails AI](https://docs.litellm.ai/docs/proxy/guardrails/guardrails_ai.md)
