# Content Safety Scan

> Comprehensive multi-modal safety scanner (Text/Image).

Source: https://docs.sommatic.ai/en/nodes/ai.safety.scan/

- Slug: `ai.safety.scan`
- Family: AI
- Version: 1.0.0
- Status: Available
- Execution: async

Comprehensive multi-modal safety scanner (Text/Image).

This is a broader version of the Safety Filter, designed for analyzing multimodal payloads for production safety compliance.

**Checks:**
- PII Detection (Basic).
- Toxicity/Hate Speech.
- Prompt Injection Detection.

## Configuration

- `llm_provider_id` (string, optional): The `id` of a `LlmProviderModel` record (e.g. `wf-llm-provider-*`). The orchestrator delegates to the backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` for sync mode, or `POST /chat/conversation/execute/stream-ephemeral` (SSE) for stream mode. The backend resolves endpoint + api-key + deployment from the record and routes to the correct adapter.
- `invocation_mode` (string, optional): Transport for the LLM call. `sync` blocks until the full response arrives. `stream` consumes tokens via SSE (required for long generations). Default `sync`. Default: `sync`. Allowed values: `sync`, `stream`.
- `timeout_ms` (integer, optional): Maximum time to wait for the invocation to complete (or idle timeout between chunks in stream mode). Default 30000 for sync, 600000 for stream.
- `check_toxicity` (boolean, optional): Detect hate, harassment, and violence. Default: `true`.
- `check_pii` (boolean, optional): Detect personally identifiable information. Default: `false`.
- `check_injection` (boolean, optional): Detect attempts to bypass constraints. Default: `true`.
- `check_sexual` (boolean, optional): Detect explicit or suggestive content. Default: `false`.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `pass` (default): Pass
- `fail`: Fail
- `error`: Error

## Input contract

- `content` (string, required): Content to scan.

## Output contract

- `passed` (boolean, optional)
- `report` (object, optional)

## In expressions

What a later node can read from this node's output with `$("Content Safety Scan").item.json.<path>` (write your node's label instead of `Content Safety Scan`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `pass`, from the output shown in Ports.

- `$("Content Safety Scan").item.json.passed` (boolean) = `true`
- `$("Content Safety Scan").item.json.report` (object) = `{…}`
- `$("Content Safety Scan").item.json.report.flagged_categories` (array) = `[…] (0)` (Not suggested by the editor)
- `$("Content Safety Scan").item.json.report.confidence` (number) = `0.97` (Not suggested by the editor)
- `$("Content Safety Scan").item.json.report.active_checks` (array) = `[…] (2)` (Not suggested by the editor)
- `$("Content Safety Scan").item.json.report.modality` (string) = `"text"` (Not suggested by the editor)
- `$("Content Safety Scan").item.json.report.raw` (object) = `{…}` (Not suggested by the editor)


## How it works

Classifies text and/or an image with the LLM against the enabled safety checks (toxicity, prompt injection, sexual content, PII) and routes to `pass` or `fail`. A request blocked by the provider’s own content filter also counts as `fail`.

1. Resolves the node config: expressions in config keys are evaluated against the run; the incoming item is used as-is.
2. Reads the text from the incoming item: `content`, else `input`, else the item itself when it is a string. Reads an optional `image` from the item. Without both it returns `error`.
3. Builds the active checks: `check_toxicity` (hate, harassment, violence) and `check_injection` (prompt-injection) are on unless `false`; `check_sexual` and `check_pii` only when `true`.
4. Prepares the image: a `data:` URI is used as-is, an `http(s)` URL is downloaded (10 s timeout) and inlined as base64, and any other string is treated as raw base64 JPEG.
5. Calls the LLM through the backend with the `llm_provider_id` record. `invocation_mode: "sync"` (default) waits for the full answer; `"stream"` reads it over SSE and joins the chunks.
6. Takes the first `{…}` block of the answer (temperature 0) and flags the result only for categories that belong to the active checks. Any such category → `fail`; none → `pass`.
7. If the LLM call fails with a message matching `filtered`, `content management` or `content polic…`, it returns `fail` with all active categories and `_filter_source: "provider_content_policy"`.

## In a workflow

### Node

```json
{
  "node_id": "node-safety-scan",
  "label": "Scan user message",
  "operator_slug": "ai.safety.scan",
  "operator_version": "1.0.0",
  "config": {
    "llm_provider_id": "<llm_provider_id>",
    "check_toxicity": true,
    "check_injection": true,
    "check_sexual": false,
    "check_pii": false
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "pass",
  "data": {
    "passed": true,
    "report": {
      "flagged_categories": [],
      "confidence": 0.97,
      "active_checks": [
        "toxicity",
        "injection"
      ],
      "modality": "text",
      "raw": {
        "flagged": false,
        "confidence": 0.97,
        "categories": {
          "hate": false,
          "harassment": false,
          "violence": false,
          "prompt-injection": false,
          "sexual": false,
          "pii": false
        }
      }
    }
  }
}
```

## Output ports (behaviour in the code)

### `pass`

No active category was flagged.

```json
{
  "passed": true,
  "report": {
    "flagged_categories": [],
    "confidence": 0.97,
    "active_checks": [
      "toxicity",
      "injection"
    ],
    "modality": "text",
    "raw": {
      "flagged": false,
      "confidence": 0.97,
      "categories": {
        "hate": false,
        "harassment": false,
        "violence": false,
        "prompt-injection": false,
        "sexual": false,
        "pii": false
      }
    }
  }
}
```

### `fail`

An active category was flagged, or the provider’s content filter blocked the request. In the second case `report` has `_filter_source` and no `raw`.

```json
{
  "passed": false,
  "report": {
    "flagged_categories": [
      "prompt-injection"
    ],
    "confidence": 0.9,
    "active_checks": [
      "toxicity",
      "injection"
    ],
    "modality": "text",
    "raw": {
      "flagged": true,
      "confidence": 0.9,
      "categories": {
        "hate": false,
        "harassment": false,
        "violence": false,
        "prompt-injection": true,
        "sexual": false,
        "pii": false
      }
    }
  }
}
```

### `error`

Validation, the LLM call or parsing failed. `data` is `{ error }` (plus `response` when the backend returned a body).

```json
{
  "error": "Missing input: provide 'content', 'input', or 'image'"
}
```

## Behaviour in the code

- `llm_provider_id`: Required at runtime although the schema does not mark it as required. It is the id of an LLM provider record; the backend resolves endpoint, deployment and credentials from it.
- `check_toxicity / check_injection / check_sexual / check_pii`: With all four off, the legacy `checks` array (e.g. `["pii"]`) is used if present; otherwise every category is evaluated and `active_checks` is `"all"`. Turning everything off therefore scans everything.
- `timeout_ms`: `timeout_ms` only takes effect in `stream` mode, as the idle time allowed between chunks (default 600000). In `sync` mode it is logged but the backend request has no timeout.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Missing input: provide 'content', 'input', or 'image'` | `error` | The incoming item has no `content`, `input` or `image`, and is not a string. These keys are read from the incoming item only, not from the node config. |
| `Safety scan response could not be parsed` | `error` | The answer had no `{…}` block. |
| `<JSON.parse error>` | `error` | The `{…}` block in the answer is not valid JSON. |
| `<image download error>` | `error` | The image URL could not be downloaded within 10 s. |
| `[AiSafetyScan] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | The node has no `llm_provider_id`. Pick an LLM provider in the node config; the legacy `model_id` key is not accepted. |
| `LLM Invocation Error: <backend message>` | `error` | The backend rejected the call (unknown or inactive provider record, provider error, credentials). Check the provider record. |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | The backend could not be reached or returned nothing in `sync` mode. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | In `stream` mode no chunk arrived within `timeout_ms`. |

## Notes and limits

- For images the model must accept multimodal input; the user message is sent as a text part plus an `image_url` part.
- Image URLs are fetched from the orchestrator host, so they must be reachable from it.
- `timeout_ms` only takes effect in `stream` mode, as the idle time allowed between chunks (default 600000). In `sync` mode it is logged but the backend request has no timeout.
- In `stream` mode the temperature this node sets is not forwarded to the provider, and `raw` is `null`.
- The engine does not apply `execution.retryOnFail`, `maxTries`, `waitBetweenTries` or `continueOnFail` to this node. Handle failures by wiring the `error` port.


## Contracts (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "ai.safety.scan",
  "name": "Content Safety Scan",
  "category": "ai",
  "version": "1.0.0",
  "description": "Comprehensive multi-modal safety scanner (Text/Image).\n\n  This is a broader version of the Safety Filter, designed for analyzing multimodal payloads for production safety compliance.\n\n  **Checks:**\n  - PII Detection (Basic).\n  - Toxicity/Hate Speech.\n  - Prompt Injection Detection.",
  "capabilities": [
    "safety",
    "security",
    "scan"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "llm_provider_id": {
        "type": "string",
        "title": "LLM Provider",
        "description": "The `id` of a `LlmProviderModel` record (e.g. `wf-llm-provider-*`). The orchestrator delegates to the backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` for sync mode, or `POST /chat/conversation/execute/stream-ephemeral` (SSE) for stream mode. The backend resolves endpoint + api-key + deployment from the record and routes to the correct adapter.",
        "x-ui-widget": "llm-provider-picker",
        "x-llm-provider-capabilities": [
          "chat"
        ]
      },
      "invocation_mode": {
        "type": "string",
        "title": "Invocation Mode",
        "description": "Transport for the LLM call. `sync` blocks until the full response arrives. `stream` consumes tokens via SSE (required for long generations). Default `sync`.",
        "enum": [
          "sync",
          "stream"
        ],
        "default": "sync"
      },
      "timeout_ms": {
        "type": "integer",
        "title": "Timeout (ms)",
        "description": "Maximum time to wait for the invocation to complete (or idle timeout between chunks in stream mode). Default 30000 for sync, 600000 for stream.",
        "minimum": 1000
      },
      "check_toxicity": {
        "type": "boolean",
        "title": "Toxicity/Hate Speech",
        "description": "Detect hate, harassment, and violence.",
        "default": true
      },
      "check_pii": {
        "type": "boolean",
        "title": "PII Detection",
        "description": "Detect personally identifiable information.",
        "default": false
      },
      "check_injection": {
        "type": "boolean",
        "title": "Prompt Injection",
        "description": "Detect attempts to bypass constraints.",
        "default": true
      },
      "check_sexual": {
        "type": "boolean",
        "title": "Sexual Content",
        "description": "Detect explicit or suggestive content.",
        "default": false
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "content": {
        "type": "string",
        "description": "Content to scan."
      }
    },
    "required": [
      "content"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "passed": {
        "type": "boolean"
      },
      "report": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "pass",
      "label": "Pass",
      "is_default": true
    },
    {
      "port_id": "fail",
      "label": "Fail"
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "safety",
    "scan",
    "security"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "llm_provider_id": {
      "type": "string",
      "title": "LLM Provider",
      "description": "The `id` of a `LlmProviderModel` record (e.g. `wf-llm-provider-*`). The orchestrator delegates to the backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` for sync mode, or `POST /chat/conversation/execute/stream-ephemeral` (SSE) for stream mode. The backend resolves endpoint + api-key + deployment from the record and routes to the correct adapter.",
      "x-ui-widget": "llm-provider-picker",
      "x-llm-provider-capabilities": [
        "chat"
      ]
    },
    "invocation_mode": {
      "type": "string",
      "title": "Invocation Mode",
      "description": "Transport for the LLM call. `sync` blocks until the full response arrives. `stream` consumes tokens via SSE (required for long generations). Default `sync`.",
      "enum": [
        "sync",
        "stream"
      ],
      "default": "sync"
    },
    "timeout_ms": {
      "type": "integer",
      "title": "Timeout (ms)",
      "description": "Maximum time to wait for the invocation to complete (or idle timeout between chunks in stream mode). Default 30000 for sync, 600000 for stream.",
      "minimum": 1000
    },
    "check_toxicity": {
      "type": "boolean",
      "title": "Toxicity/Hate Speech",
      "description": "Detect hate, harassment, and violence.",
      "default": true
    },
    "check_pii": {
      "type": "boolean",
      "title": "PII Detection",
      "description": "Detect personally identifiable information.",
      "default": false
    },
    "check_injection": {
      "type": "boolean",
      "title": "Prompt Injection",
      "description": "Detect attempts to bypass constraints.",
      "default": true
    },
    "check_sexual": {
      "type": "boolean",
      "title": "Sexual Content",
      "description": "Detect explicit or suggestive content.",
      "default": false
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "content": {
      "type": "string",
      "description": "Content to scan."
    }
  },
  "required": [
    "content"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "passed": {
      "type": "boolean"
    },
    "report": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "pass",
    "label": "Pass",
    "is_default": true
  },
  {
    "port_id": "fail",
    "label": "Fail"
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
