# AI Decision

> Intelligent routing node that replaces complex flow.switch chains with a single AI-powered decision point.

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

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

Intelligent routing node that replaces complex flow.switch chains with a single AI-powered decision point.

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.

**How it works:**
- Configure named decisions with natural language criteria (e.g., "Urgent: customer is threatening to cancel and mentions legal action").
- The AI evaluates the input against ALL criteria and selects the best match.
- Output routes to the matching decision port with confidence and reasoning.
- Optionally load decision policies from a Knowledge Resource.

Far more flexible than rule-based switches — understands nuance, context, and natural language criteria.

## 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.
- `decisions` (array<object>, required): Define each decision as a named output with criteria. Each becomes a workflow port.
- `default_port` (string, optional): Port to use when no decision matches with sufficient confidence. Default: `default`.
- `include_reasoning` (boolean, optional): Include detailed reasoning in the output. Default: `true`.
- `confidence_threshold` (number, optional): Minimum confidence to route to a decision. Below this, routes to default port. Default: `0.6`.
- `knowledge_resource_id` (string, optional): Optional: load decision criteria from a Knowledge Resource.
- `language` (string, optional): Default: `en`.

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

- `default` (default): No decision matched with sufficient confidence.
- `error`: Decision evaluation failed.

## Input contract

- `text` (string, required): Input text to evaluate.
- `context` (object, optional): Optional context for decision-making.

## Output contract

- `decision` (string, optional): The selected decision label.
- `port` (string, optional): The output port to route to.
- `confidence` (number, optional): Confidence score 0-1.
- `reasoning` (string, optional): Explanation for the decision.
- `alternatives` (array, optional): Other decisions considered with their confidence.

## In expressions

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

- `$("AI Decision").item.json.decision` (string) = `""`: The selected decision label.
- `$("AI Decision").item.json.port` (string) = `"default"`: The output port to route to.
- `$("AI Decision").item.json.confidence` (number) = `0.41`: Confidence score 0-1.
- `$("AI Decision").item.json.reasoning` (string) = `"The message does not clearly match any decis…"`: Explanation for the decision.
- `$("AI Decision").item.json.alternatives` (array) = `[…] (0)`: Other decisions considered with their confidence.


## How it works

Lets the model choose one of your configured decisions for `text` and routes to that decision's `port_id`; low confidence or an unknown answer goes to the default port.

1. Merges the upstream payload with the node config (config wins) and reads `text` (falling back to `input`) and `context`.
2. Collects decisions from `decisions` and from `content.structured_data.decisions` of `knowledge_resource_id` (both are used); an item needs `port_id` and `description`, `label` defaults to `port_id`. Fails when none remain.
3. Sends a router system prompt with each decision, the default port, the threshold and a strict JSON format; the user message is `text`, prefixed by `Context: <JSON>` when `context` is set; `temperature: 0`.
4. Parses the answer as JSON; it must contain a string `port`. An unknown port is matched case-insensitively to the decisions, else replaced by `default_port`.
5. Forces `default_port` when `confidence` (0 if missing) is below `confidence_threshold`, and routes to the selected port.

## In a workflow

### Node

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

## Output ports (behaviour in the code)

### `default`

No decision matched, the confidence was below the threshold or the model named an unknown port (with `default_port` left as `default`). When a decision wins, the node leaves through that decision's `port_id` instead, which is a dynamic port named after your config.

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

### `error`

No decisions are configured, the model call failed or the answer had no `port`.

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

## Behaviour in the code

- `decisions`: Each `port_id` becomes an output port of the node: draw edges from those port ids. Items without `description` are dropped silently.
- `default_port`: Default `default`. If you rename it, draw the fallback edge from the new name; the declared `default` port is then never used.
- `knowledge_resource_id`: Adds decisions from the resource on top of `decisions`; a failed fetch is only logged.
- `text, context`: Not in the config schema, but read from the config first and then from the upstream payload.
- `timeout_ms`: Stream mode only: idle timeout between chunks, default 600000. In sync mode it is not applied to the request.
- `execution`: Declared but ignored: neither the worker nor the engine reads `retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail`, `alwaysOutputData` or `timeout_ms` from this block.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `No decisions defined. Configure at least one decision with port_id, label, and criteria.` | `error` | No item in `decisions` or in the resource has both `port_id` and `description`. |
| `Model did not return valid decision output.` | `error` | The answer was not JSON or had no string `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` is empty or not a string. Pick an LLM provider record with chat capability. |
| `LLM Invocation Error: <backend message>` | `error` | The backend rejected the call: unknown or inactive provider record, provider error, quota or content filter. Check the provider record and the backend logs. |
| `LLM Invocation Error: empty response from backend (<transport error>)` | `error` | Sync mode: the HTTP call to the backend failed (network error, non-2xx status or timeout). Long prompts often hit the request timeout; switch to `invocation_mode: "stream"`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | Stream mode: no chunk arrived within `timeout_ms`. A failed stream request shows `RemoteApiService.stream: HTTP <status> — <body>` instead. |

## Notes and limits

- When `text` is empty, the worker falls back to `input`, which at runtime is always the whole upstream payload object. The missing-text check therefore never fires and the object is sent to the model as the message. Always map `text` explicitly.
- `data.port` always equals the port the node left through. `reasoning` is `null` when `include_reasoning` is `false`; `alternatives` is passed through from the model.
- The worker returns `raw` next to `data`; the engine keeps only `data` as the node output, so `raw` is not available downstream.
- The model call goes through the Sommatic AI backend, which resolves the provider record named by `llm_provider_id` (endpoint, credentials, deployment); the orchestrator never holds provider keys. `invocation_mode: "sync"` (default) waits for the full answer; `"stream"` reads it as server-sent events and joins the chunks.
- `timeout_ms` only takes effect in stream mode, as the idle time allowed between chunks (default 600000). In sync mode the value is logged but not applied to the HTTP request, so the platform's default request timeout governs.
- In stream mode the backend endpoint does not apply sampling settings, so the fixed `temperature: 0` only takes effect in sync mode.
- No automatic retries: the engine does not honour `execution.retryOnFail`, `maxTries` or `waitBetweenTries` for this node; a failed call goes straight to `error`.


## Contracts (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
  }
]
```
