# AI Decision

> 智能路由节点：用单个 AI 决策点取代复杂的 flow.switch 链。

Source: https://docs.sommatic.ai/zh/nodes/ai.decision/

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

智能路由节点：用单个 AI 决策点取代复杂的 flow.switch 链。

用自然语言定义决策条件，由 LLM 路由到正确的输出端口。每个决策都会成为工作流图中一个具名输出端口。

**工作原理：**
- 用自然语言条件配置具名决策（例如“紧急：客户威胁取消合作并提到要采取法律行动”）。
- AI 依据所有条件评估输入，并选出最佳匹配。
- 输出携带置信度和推理过程，路由到匹配的决策端口。
- 可选地从 Knowledge Resource 加载决策策略。

比基于规则的分支灵活得多：能够理解细微差别、上下文和自然语言条件。

## 配置

- `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。
- `decisions` (array<object>, 必填): 将每个决策定义为带条件的具名输出。每个决策都会成为一个工作流端口。
- `default_port` (string, 可选): 没有决策以足够置信度匹配时使用的端口。 默认值: `default`.
- `include_reasoning` (boolean, 可选): 在输出中包含详细的推理过程。 默认值: `true`.
- `confidence_threshold` (number, 可选): 路由到某个决策所需的最低置信度。低于此值时路由到默认端口。 默认值: `0.6`.
- `knowledge_resource_id` (string, 可选): 可选：从 Knowledge Resource 加载决策条件。
- `language` (string, 可选): 默认值: `en`.

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

## 输出端口

- `default` (默认): 没有决策以足够置信度匹配。
- `error`: 决策评估失败。

## 输入契约

- `text` (string, 必填): 要评估的输入文本。
- `context` (object, 可选): 用于决策的可选上下文。

## 输出契约

- `decision` (string, 可选): 选定的决策标签。
- `port` (string, 可选): 要路由到的输出端口。
- `confidence` (number, 可选): 置信度得分 0-1。
- `reasoning` (string, 可选): 对该决策的解释。
- `alternatives` (array, 可选): 曾考虑的其他决策及其置信度。

## 在表达式中

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

- `$("AI Decision").item.json.decision` (string) = `""`: 选定的决策标签。
- `$("AI Decision").item.json.port` (string) = `"default"`: 要路由到的输出端口。
- `$("AI Decision").item.json.confidence` (number) = `0.41`: 置信度得分 0-1。
- `$("AI Decision").item.json.reasoning` (string) = `"The message does not clearly match any decis…"`: 对该决策的解释。
- `$("AI Decision").item.json.alternatives` (array) = `[…] (0)`: 曾考虑的其他决策及其置信度。


## 工作原理

让模型为 `text` 从已配置的决策中选择一个，并路由到该决策的 `port_id`；置信度低或回答未知时走默认端口。

1. 合并上游载荷与节点配置（以配置为准），读取 `text`（回退到 `input`）和 `context`。
2. 从 `decisions` 以及 `knowledge_resource_id` 的 `content.structured_data.decisions` 收集决策（两者都会使用）；每项需要 `port_id` 和 `description`，`label` 默认为 `port_id`。一个都没有时失败。
3. 发送路由器系统提示词，包含每个决策、默认端口、阈值及严格 JSON 格式；用户消息为 `text`，若有 `context` 则前置 `Context: <JSON>`；`temperature: 0`。
4. 将回答解析为 JSON，其中必须含字符串 `port`。未知端口会与决策做不区分大小写的匹配，仍不匹配则替换为 `default_port`。
5. 当 `confidence`（缺失按 0）低于 `confidence_threshold` 时强制使用 `default_port`，并路由到选定端口。

## 在工作流中

### 节点

```json
{
  "node_id": "node-route-message",
  "label": "Route message",
  "operator_slug": "ai.decision",
  "operator_version": "1.0.0",
  "config": {
    "text": "{{ $json.body }}",
    "decisions": [
      {
        "port_id": "billing",
        "label": "Billing question",
        "description": "Charges, invoices, refunds or payment methods."
      },
      {
        "port_id": "technical",
        "label": "Technical issue",
        "description": "Errors, outages or something that does not work."
      }
    ],
    "default_port": "default",
    "confidence_threshold": 0.6,
    "include_reasoning": true,
    "language": "en",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "invocation_mode": "sync"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "decision": "Billing question",
    "port": "billing",
    "confidence": 0.86,
    "reasoning": "The customer asks why they were charged twice; no technical failure is described.",
    "alternatives": [
      {
        "port": "technical",
        "label": "Technical issue",
        "confidence": 0.09
      }
    ]
  },
  "port": "billing"
}
```

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

### `default`

没有匹配的决策、置信度低于阈值，或模型给出了未知端口（`default_port` 保持为 `default` 时）。当某个决策胜出时，节点改从该决策的 `port_id` 输出，这是按配置命名的动态端口。

```json
{
  "decision": "",
  "port": "default",
  "confidence": 0.41,
  "reasoning": "The message does not clearly match any decision.",
  "alternatives": []
}
```

### `error`

未配置决策、模型调用失败或回答缺少 `port`。

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

## 代码中的行为

- `decisions`: 每个 `port_id` 都会成为节点的输出端口：请从这些端口 id 画出连线。缺少 `description` 的项会被静默丢弃。
- `default_port`: 默认为 `default`。若改名，请从新名称画出兜底连线，此时声明的 `default` 端口将不再使用。
- `knowledge_resource_id`: 在 `decisions` 之外追加资源中的决策；获取失败只记录日志。
- `text, context`: 不在配置 schema 中，但会先从配置读取，再从上游载荷读取。
- `timeout_ms`: 仅限 stream 模式：片段之间的空闲超时，默认 600000。在 sync 模式下不会作用于请求。
- `execution`: 已声明但被忽略：worker 和引擎都不会读取该块中的 `retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`alwaysOutputData` 或 `timeout_ms`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `No decisions defined. Configure at least one decision with port_id, label, and criteria.` | `error` | `decisions` 或资源中没有任何同时具备 `port_id` 和 `description` 的项。 |
| `Model did not return valid decision output.` | `error` | 回答不是 JSON 或缺少字符串 `port`。 |
| `[AiDecision] 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`。
- `data.port` 始终等于节点实际输出的端口。`include_reasoning` 为 `false` 时 `reasoning` 为 `null`；`alternatives` 原样取自模型。
- 该 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 模式下生效。
- 不会自动重试：引擎不会为本节点执行 `execution.retryOnFail`、`maxTries` 或 `waitBetweenTries`；调用失败会直接从 `error` 输出。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.decision",
  "name": "AI Decision",
  "category": "ai",
  "version": "1.0.0",
  "description": "Intelligent routing node that replaces complex flow.switch chains with a single AI-powered decision point.\n\n  Define decision criteria in natural language and let the LLM route to the correct output port. Each decision becomes a named output port in the workflow graph.\n\n  **How it works:**\n  - Configure named decisions with natural language criteria (e.g., \"Urgent: customer is threatening to cancel and mentions legal action\").\n  - The AI evaluates the input against ALL criteria and selects the best match.\n  - Output routes to the matching decision port with confidence and reasoning.\n  - Optionally load decision policies from a Knowledge Resource.\n\n  Far more flexible than rule-based switches — understands nuance, context, and natural language criteria.",
  "capabilities": [
    "routing",
    "decision",
    "classification",
    "ai-switch"
  ],
  "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
      },
      "decisions": {
        "type": "array",
        "title": "Decisions",
        "description": "Define each decision as a named output with criteria. Each becomes a workflow port.",
        "items": {
          "type": "object",
          "properties": {
            "port_id": {
              "type": "string",
              "description": "Port identifier (lowercase, no spaces, e.g., \"urgent\", \"billing\")"
            },
            "label": {
              "type": "string",
              "description": "Human-readable label (e.g., \"Urgent Escalation\")"
            },
            "description": {
              "type": "string",
              "description": "Natural language criteria for when this decision applies"
            }
          }
        }
      },
      "default_port": {
        "type": "string",
        "title": "Default Port",
        "default": "default",
        "description": "Port to use when no decision matches with sufficient confidence."
      },
      "include_reasoning": {
        "type": "boolean",
        "title": "Include Reasoning",
        "default": true,
        "description": "Include detailed reasoning in the output."
      },
      "confidence_threshold": {
        "type": "number",
        "title": "Confidence Threshold",
        "default": 0.6,
        "description": "Minimum confidence to route to a decision. Below this, routes to default port."
      },
      "knowledge_resource_id": {
        "type": "string",
        "title": "Decision Policy",
        "description": "Optional: load decision criteria from a Knowledge Resource.",
        "ui_widget": "knowledge_resource_picker"
      },
      "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": [
      "decisions"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string",
        "description": "Input text to evaluate."
      },
      "context": {
        "type": "object",
        "description": "Optional context for decision-making."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "decision": {
        "type": "string",
        "description": "The selected decision label."
      },
      "port": {
        "type": "string",
        "description": "The output port to route to."
      },
      "confidence": {
        "type": "number",
        "description": "Confidence score 0-1."
      },
      "reasoning": {
        "type": "string",
        "description": "Explanation for the decision."
      },
      "alternatives": {
        "type": "array",
        "description": "Other decisions considered with their confidence."
      }
    }
  },
  "ports": [
    {
      "port_id": "default",
      "label": "Default",
      "description": "No decision matched with sufficient confidence.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Decision evaluation failed.",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "routing",
    "decision",
    "switch",
    "classification"
  ],
  "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
    },
    "decisions": {
      "type": "array",
      "title": "Decisions",
      "description": "Define each decision as a named output with criteria. Each becomes a workflow port.",
      "items": {
        "type": "object",
        "properties": {
          "port_id": {
            "type": "string",
            "description": "Port identifier (lowercase, no spaces, e.g., \"urgent\", \"billing\")"
          },
          "label": {
            "type": "string",
            "description": "Human-readable label (e.g., \"Urgent Escalation\")"
          },
          "description": {
            "type": "string",
            "description": "Natural language criteria for when this decision applies"
          }
        }
      }
    },
    "default_port": {
      "type": "string",
      "title": "Default Port",
      "default": "default",
      "description": "Port to use when no decision matches with sufficient confidence."
    },
    "include_reasoning": {
      "type": "boolean",
      "title": "Include Reasoning",
      "default": true,
      "description": "Include detailed reasoning in the output."
    },
    "confidence_threshold": {
      "type": "number",
      "title": "Confidence Threshold",
      "default": 0.6,
      "description": "Minimum confidence to route to a decision. Below this, routes to default port."
    },
    "knowledge_resource_id": {
      "type": "string",
      "title": "Decision Policy",
      "description": "Optional: load decision criteria from a Knowledge Resource.",
      "ui_widget": "knowledge_resource_picker"
    },
    "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": [
    "decisions"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string",
      "description": "Input text to evaluate."
    },
    "context": {
      "type": "object",
      "description": "Optional context for decision-making."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "decision": {
      "type": "string",
      "description": "The selected decision label."
    },
    "port": {
      "type": "string",
      "description": "The output port to route to."
    },
    "confidence": {
      "type": "number",
      "description": "Confidence score 0-1."
    },
    "reasoning": {
      "type": "string",
      "description": "Explanation for the decision."
    },
    "alternatives": {
      "type": "array",
      "description": "Other decisions considered with their confidence."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "default",
    "label": "Default",
    "description": "No decision matched with sufficient confidence.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Decision evaluation failed.",
    "is_default": false,
    "supports_condition": false
  }
]
```
