# Content Safety Scan

> 全面的多模态安全扫描器（文本/图像）。

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

- 标识: `ai.safety.scan`
- 类别: AI
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

全面的多模态安全扫描器（文本/图像）。

它是 Safety Filter 的扩展版本，用于分析多模态载荷，满足生产环境的安全合规要求。

**检查项：**
- PII 检测（基础）。
- 毒性/仇恨言论。
- 提示词注入检测。

## 配置

- `llm_provider_id` (string, 可选): `LlmProviderModel` 记录的 `id`（例如 `wf-llm-provider-*`）。编排器将调用委托给后端：sync 模式调用 `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke`，stream 模式调用 `POST /chat/conversation/execute/stream-ephemeral`（SSE）。后端根据该记录解析 endpoint + api-key + deployment，并路由到相应的适配器。
- `invocation_mode` (string, 可选): LLM 调用的传输方式。`sync` 会阻塞直到收到完整响应。`stream` 通过 SSE 逐步接收 token（长文本生成必须使用）。默认为 `sync`。 默认值: `sync`. 可选值: `sync`, `stream`.
- `timeout_ms` (integer, 可选): 等待调用完成的最长时间（stream 模式下为分块之间的空闲超时）。sync 默认 30000，stream 默认 600000。
- `check_toxicity` (boolean, 可选): 检测仇恨、骚扰和暴力内容。 默认值: `true`.
- `check_pii` (boolean, 可选): 检测个人身份信息。 默认值: `false`.
- `check_injection` (boolean, 可选): 检测绕过约束的企图。 默认值: `true`.
- `check_sexual` (boolean, 可选): 检测露骨或带有性暗示的内容。 默认值: `false`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `pass` (默认): Pass
- `fail`: Fail
- `error`: Error

## 输入契约

- `content` (string, 必填): 要扫描的内容。

## 输出契约

- `passed` (boolean, 可选)
- `report` (object, 可选)

## 在表达式中

后续节点可通过 `$("Content Safety Scan").item.json.<路径>` 读取此节点输出中的内容（请把 `Content Safety Scan` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `pass` 返回的路径，依据“端口”一节所示的输出。

- `$("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)` (编辑器不提示)
- `$("Content Safety Scan").item.json.report.confidence` (number) = `0.97` (编辑器不提示)
- `$("Content Safety Scan").item.json.report.active_checks` (array) = `[…] (2)` (编辑器不提示)
- `$("Content Safety Scan").item.json.report.modality` (string) = `"text"` (编辑器不提示)
- `$("Content Safety Scan").item.json.report.raw` (object) = `{…}` (编辑器不提示)


## 工作原理

使用 LLM 按已启用的安全检查（有害内容、提示词注入、色情内容、个人信息）对文本和/或图片分类，并路由到 `pass` 或 `fail`。被提供方自身内容过滤器拦截的请求同样计为 `fail`。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 从传入条目读取文本：优先 `content`，其次 `input`，若条目本身是字符串则使用条目本身。还可从条目读取可选的 `image`。两者都没有时返回 `error`。
3. 构建启用的检查项：`check_toxicity`（仇恨、骚扰、暴力）和 `check_injection`（提示词注入）除非设为 `false` 否则启用；`check_sexual` 和 `check_pii` 仅在为 `true` 时启用。
4. 处理图片：`data:` URI 原样使用；`http(s)` URL 会被下载（超时 10 秒）并内联为 base64；其他字符串按原始 base64 JPEG 处理。
5. 通过后端使用 `llm_provider_id` 记录调用 LLM。`invocation_mode: "sync"`（默认）等待完整响应；`"stream"` 通过 SSE 读取并拼接分块。
6. 取响应中的第一个 `{…}` 块（温度 0），只针对属于已启用检查项的类别标记结果。命中任一类别 → `fail`；均未命中 → `pass`。
7. 如果 LLM 调用失败且错误消息匹配 `filtered`、`content management` 或 `content polic…`，则返回 `fail`，包含全部已启用类别并带有 `_filter_source: "provider_content_policy"`。

## 在工作流中

### 节点

```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
        }
      }
    }
  }
}
```

## 输出端口 (代码中的行为)

### `pass`

没有任何已启用类别被标记。

```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`

有已启用类别被标记，或提供方的内容过滤器拦截了请求。后一种情况下 `report` 含 `_filter_source` 且没有 `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`

校验、LLM 调用或解析失败。`data` 为 `{ error }`（若后端返回了响应体，还包含 `response`）。

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

## 代码中的行为

- `llm_provider_id`: 虽然 schema 未将其标为必填，但运行时必须提供。它是 LLM 提供方记录的 id；后端据此解析端点、部署和凭据。
- `check_toxicity / check_injection / check_sexual / check_pii`: 四项全部关闭时，若存在旧版 `checks` 数组（例如 `["pii"]`）则使用它；否则评估所有类别，`active_checks` 为 `"all"`。因此全部关闭反而会检查全部类别。
- `timeout_ms`: `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing input: provide 'content', 'input', or 'image'` | `error` | 传入条目中没有 `content`、`input` 或 `image`，且本身不是字符串。这些键只从传入条目读取，不从节点配置读取。 |
| `Safety scan response could not be parsed` | `error` | 响应中没有 `{…}` 块。 |
| `<JSON.parse error>` | `error` | 响应中的 `{…}` 块不是有效的 JSON。 |
| `<image download error>` | `error` | 图片 URL 无法在 10 秒内下载完成。 |
| `[AiSafetyScan] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | 节点缺少 `llm_provider_id`。请在节点配置中选择一个 LLM 提供方；旧的 `model_id` 键不再被接受。 |
| `LLM Invocation Error: <backend message>` | `error` | 后端拒绝了调用（提供方记录不存在或未启用、提供方错误、凭据问题）。请检查提供方记录。 |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | 在 `sync` 模式下无法连接后端，或后端未返回任何内容。 |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | 在 `stream` 模式下，`timeout_ms` 内没有收到任何分块。 |

## 说明与限制

- 对于图片，模型必须支持多模态输入；用户消息以一个文本部分加一个 `image_url` 部分发送。
- 图片 URL 从编排器主机下载，因此必须能从该主机访问。
- `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。
- 在 `stream` 模式下，此节点设置的温度不会转发给提供方，且 `raw` 为 `null`。
- 引擎不会对此节点应用 `execution.retryOnFail`、`maxTries`、`waitBetweenTries` 或 `continueOnFail`。请通过连接 `error` 端口处理失败。


## 契约（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"
  }
]
```
