# Check Compliance

> 依据合规政策、监管规则或业务准则评估内容。

Source: https://docs.sommatic.ai/zh/nodes/ai.compliance.check/

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

依据合规政策、监管规则或业务准则评估内容。

关联一个包含合规政策的 Knowledge Resource，该节点即可自动检查任意文本是否存在违规，并返回严重级别、具体规则引用和整改建议。

**操作：**
- **Full Check：** 对照全部政策规则做深度分析，输出详细的违规报告。
- **Quick Check：** 仅快速扫描严重违规。

非常适合法规合规（GDPR、HIPAA、SOX）、内部政策执行、内容审核工作流和审计自动化。

## 配置

- `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。
- `knowledge_resource_id` (string, 必填): 必填：包含用于检查的合规规则/政策的 Knowledge Resource。
- `check_mode` (string, 可选): Full：深度分析所有规则。Quick：仅检查严重违规。 默认值: `full`. 可选值: `full`, `quick`.
- `severity_levels` (array<string>, 可选): 违规的严重级别分类。 默认值: `["critical","major","minor","info"]`.
- `language` (string, 可选): 默认值: `en`.

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

## 输出端口

- `compliant` (默认): 内容通过全部合规检查。
- `non_compliant`: 检测到一项或多项违规。
- `error`: 合规检查失败。

## 输入契约

- `text` (string, 必填): 要评估合规性的内容。
- `document_type` (string, 可选): 可选：文档类型（合同、邮件、报告）。
- `context` (object, 可选): 可选：用于评估的附加上下文。

## 输出契约

- `compliant` (boolean, 可选): 内容是否通过全部检查。
- `violations` (array, 可选): 发现的违规列表。
- `violation_count` (number, 可选): 违规总数。
- `risk_level` (string, 可选): 整体风险评估。
- `summary` (string, 可选): 可读的合规摘要。

## 在表达式中

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

- `$("Check Compliance").item.json.compliant` (boolean) = `true`: 内容是否通过全部检查。
- `$("Check Compliance").item.json.violations` (array) = `[…] (0)`: 发现的违规列表。
- `$("Check Compliance").item.json.violation_count` (number) = `0`: 违规总数。
- `$("Check Compliance").item.json.risk_level` (string) = `"none"`: 整体风险评估。
- `$("Check Compliance").item.json.summary` (string) = `"The contract meets all payment and data rules."`: 可读的合规摘要。


## 工作原理

借助模型依据政策知识资源中的规则审查 `text`，并携带违规清单路由到 `compliant` 或 `non_compliant`。

1. 合并上游载荷与节点配置（以配置为准），读取 `text`（回退到 `input`）和 `document_type`。`knowledge_resource_id` 为空时失败。
2. 加载政策：优先把 `content.structured_data.rules`（或 `.policies`）作为规则列表，每条渲染为 `- **<name>** [<severity>]: <description>`（默认严重度 `major`）；否则把 `content.text` 作为自由文本。两者都为空时失败。
3. 发送审计员系统提示词（`check_mode: "full"` 检查全部规则，`"quick"` 只看严重和重大），附带严重度等级和严格 JSON 格式；`text` 作为用户消息；`temperature: 0`。
4. 将回答解析为 JSON，其中必须含布尔值 `compliant`。每条违规的 `severity` 转为小写，不在 `severity_levels` 中时替换为 `major`。
5. 自行重新计算 `compliant`：仅当没有任何违规的严重度不是 `info` 时为真。据此从 `compliant` 或 `non_compliant` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-check-contract",
  "label": "Check contract",
  "operator_slug": "ai.compliance.check",
  "operator_version": "1.0.0",
  "config": {
    "knowledge_resource_id": "<knowledge_resource_id>",
    "text": "{{ $json.text }}",
    "document_type": "contract",
    "check_mode": "full",
    "severity_levels": [
      "critical",
      "major",
      "minor",
      "info"
    ],
    "language": "en",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "invocation_mode": "stream",
    "timeout_ms": 120000
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "compliant": false,
    "violations": [
      {
        "rule": "Payment terms",
        "severity": "major",
        "description": "The contract sets payment at 90 days; the policy allows at most 60.",
        "location": "Clause 7: \"payment within ninety (90) days\"",
        "remediation": "Change the payment term to 60 days or fewer."
      }
    ],
    "violation_count": 1,
    "risk_level": "medium",
    "summary": "One major violation on payment terms."
  },
  "port": "non_compliant"
}
```

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

### `compliant`

没有违规，或只有 `info` 级别的违规（仍保留在 `violations` 中）。

```json
{
  "compliant": true,
  "violations": [],
  "violation_count": 0,
  "risk_level": "none",
  "summary": "The contract meets all payment and data rules."
}
```

### `non_compliant`

至少有一条高于 `info` 级别的违规。

```json
{
  "compliant": false,
  "violations": [
    {
      "rule": "Payment terms",
      "severity": "major",
      "description": "The contract sets payment at 90 days; the policy allows at most 60.",
      "location": "Clause 7: \"payment within ninety (90) days\"",
      "remediation": "Change the payment term to 60 days or fewer."
    }
  ],
  "violation_count": 1,
  "risk_level": "medium",
  "summary": "One major violation on payment terms."
}
```

### `error`

缺少政策或文本、模型调用失败或回答无效。

```json
{
  "error": "Model did not return valid compliance check output."
}
```

## 代码中的行为

- `text, document_type`: 不在配置 schema 中，但会先从配置读取，再从上游载荷读取。`document_type` 会在提示词中加入 `The document is a <type>.`。输入中的 `context` 会被忽略。
- `severity_levels`: 会列在提示词中并用于校验回答；未知严重度改为 `major`。只有字面值 `info` 不参与合规判定。
- `timeout_ms`: 仅限 stream 模式：片段之间的空闲超时，默认 600000。在 sync 模式下不会作用于请求。
- `execution`: 已声明但被忽略：worker 和引擎都不会读取该块中的 `retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`alwaysOutputData` 或 `timeout_ms`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `A Knowledge Resource with compliance rules is required. Link a policy document in the node configuration.` | `error` | `knowledge_resource_id` 为空。 |
| `Knowledge Resource has no policy content. Add rules as text or structured_data.rules array.` | `error` | 资源既没有 `content.text`，也没有 `structured_data.rules` / `policies` 数组。 |
| `Model did not return valid compliance check output.` | `error` | 回答不是 JSON 或缺少布尔值 `compliant`。 |
| `Knowledge resource not found: <knowledge_resource_id>` | `error` | 该 id 不对应任何知识资源。已删除的资源会报 `Knowledge resource "<name>" has been deleted. Update the node config to reference an active resource.` |
| `[AiComplianceCheck] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). The legacy 'model_id' alias is no longer supported — update the node config to use 'llm_provider_id'.` | `error` | `llm_provider_id` 为空或不是字符串。请选择具备 chat 能力的 LLM 提供方记录。 |
| `LLM Invocation Error: <backend message>` | `error` | 后端拒绝了调用：提供方记录不存在或未激活、提供方报错、配额或内容过滤。请检查提供方记录和后端日志。 |
| `LLM Invocation Error: empty response from backend (<transport error>)` | `error` | sync 模式：对后端的 HTTP 调用失败（网络错误、非 2xx 状态或超时）。长提示词常会触发请求超时，请改用 `invocation_mode: "stream"`。 |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | stream 模式：在 `timeout_ms` 内未收到任何片段。若流式请求本身失败，消息为 `RemoteApiService.stream: HTTP <status> — <body>`。 |

## 说明与限制

- 当 `text` 为空时，worker 会退而使用 `input`，而运行时 `input` 始终是上游传入的完整对象。因此“缺少文本”的校验永远不会触发，该对象会被当作消息发送给模型。请始终显式映射 `text`。
- `risk_level` 和 `summary` 来自模型；缺少 `risk_level` 时，合规为 `none`，不合规为 `medium`。
- 该 worker 在 `data` 旁返回 `raw`；引擎只把 `data` 存为节点输出，因此下游无法读取 `raw`。
- 模型调用经由 Sommatic AI 后端完成，后端根据 `llm_provider_id` 指定的提供方记录解析端点、凭据和部署；编排器从不持有提供方密钥。`invocation_mode: "sync"`（默认）等待完整回答；`"stream"` 以 SSE 事件读取回答并拼接各片段。
- `timeout_ms` 仅在 stream 模式下生效，表示片段之间允许的最长空闲时间（默认 600000）。在 sync 模式下该值只写入日志，不会作用于 HTTP 请求，因此以平台默认请求超时为准。
- 在 stream 模式下，后端端点不应用采样参数，因此固定的 `temperature: 0` 仅在 sync 模式下生效。
- 每次运行都会从后端读取知识资源（超时 10 秒）。状态不是 `active` 的资源仍会被使用，并在日志中记录警告。
- 不会自动重试：引擎不会为本节点执行 `execution.retryOnFail`、`maxTries` 或 `waitBetweenTries`；调用失败会直接从 `error` 输出。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.compliance.check",
  "name": "Check Compliance",
  "category": "ai",
  "version": "1.0.0",
  "description": "Evaluate content against compliance policies, regulatory rules, or business guidelines.\n\n  Link a Knowledge Resource containing your compliance policy and this node will automatically check any text for violations — returning severity levels, specific rule citations, and remediation suggestions.\n\n  **Operations:**\n  - **Full Check:** Deep analysis against all policy rules with detailed violation reports.\n  - **Quick Check:** Fast scan for critical violations only.\n\n  Ideal for regulatory compliance (GDPR, HIPAA, SOX), internal policy enforcement, content review workflows, and audit automation.",
  "capabilities": [
    "compliance",
    "audit",
    "governance",
    "policy",
    "risk"
  ],
  "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
      },
      "knowledge_resource_id": {
        "type": "string",
        "title": "Compliance Policy",
        "description": "REQUIRED: Knowledge Resource containing the compliance rules/policy to check against.",
        "ui_widget": "knowledge_resource_picker"
      },
      "check_mode": {
        "type": "string",
        "title": "Check Mode",
        "enum": [
          "full",
          "quick"
        ],
        "default": "full",
        "description": "Full: deep analysis of all rules. Quick: critical violations only."
      },
      "severity_levels": {
        "type": "array",
        "title": "Severity Levels",
        "default": [
          "critical",
          "major",
          "minor",
          "info"
        ],
        "items": {
          "type": "string"
        },
        "description": "Severity classification for violations."
      },
      "language": {
        "type": "string",
        "title": "Language",
        "default": "en"
      },
      "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
          }
        }
      }
    },
    "required": [
      "knowledge_resource_id"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string",
        "description": "Content to evaluate for compliance."
      },
      "document_type": {
        "type": "string",
        "description": "Optional: type of document (contract, email, report)."
      },
      "context": {
        "type": "object",
        "description": "Optional: additional context for evaluation."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "compliant": {
        "type": "boolean",
        "description": "Whether the content passes all checks."
      },
      "violations": {
        "type": "array",
        "description": "List of violations found."
      },
      "violation_count": {
        "type": "number",
        "description": "Total number of violations."
      },
      "risk_level": {
        "type": "string",
        "description": "Overall risk assessment."
      },
      "summary": {
        "type": "string",
        "description": "Human-readable compliance summary."
      }
    }
  },
  "ports": [
    {
      "port_id": "compliant",
      "label": "Compliant",
      "description": "Content passes all compliance checks.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "non_compliant",
      "label": "Non-Compliant",
      "description": "One or more violations detected.",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Compliance check failed.",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "compliance",
    "audit",
    "governance",
    "policy"
  ],
  "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
    },
    "knowledge_resource_id": {
      "type": "string",
      "title": "Compliance Policy",
      "description": "REQUIRED: Knowledge Resource containing the compliance rules/policy to check against.",
      "ui_widget": "knowledge_resource_picker"
    },
    "check_mode": {
      "type": "string",
      "title": "Check Mode",
      "enum": [
        "full",
        "quick"
      ],
      "default": "full",
      "description": "Full: deep analysis of all rules. Quick: critical violations only."
    },
    "severity_levels": {
      "type": "array",
      "title": "Severity Levels",
      "default": [
        "critical",
        "major",
        "minor",
        "info"
      ],
      "items": {
        "type": "string"
      },
      "description": "Severity classification for violations."
    },
    "language": {
      "type": "string",
      "title": "Language",
      "default": "en"
    },
    "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
        }
      }
    }
  },
  "required": [
    "knowledge_resource_id"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string",
      "description": "Content to evaluate for compliance."
    },
    "document_type": {
      "type": "string",
      "description": "Optional: type of document (contract, email, report)."
    },
    "context": {
      "type": "object",
      "description": "Optional: additional context for evaluation."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "compliant": {
      "type": "boolean",
      "description": "Whether the content passes all checks."
    },
    "violations": {
      "type": "array",
      "description": "List of violations found."
    },
    "violation_count": {
      "type": "number",
      "description": "Total number of violations."
    },
    "risk_level": {
      "type": "string",
      "description": "Overall risk assessment."
    },
    "summary": {
      "type": "string",
      "description": "Human-readable compliance summary."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "compliant",
    "label": "Compliant",
    "description": "Content passes all compliance checks.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "non_compliant",
    "label": "Non-Compliant",
    "description": "One or more violations detected.",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Compliance check failed.",
    "is_default": false,
    "supports_condition": false
  }
]
```
