# Classify Text

> Categorizes input text into one of a predefined set of labels.

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

- Slug: `ai.classify`
- Family: AI
- Version: 1.0.0
- Status: Partial. On success the worker returns no port, so the engine follows `out`, which this node does not declare: an edge drawn from its success port never fires. Until it is fixed, do not chain nodes after its success path.
- Execution: async

Categorizes input text into one of a predefined set of labels.

This operator uses Zero-Shot Classification or a fine-tuned model to determine the intent, sentiment, or topic of the text.

**Use Cases:**
- **Support Routing:** Tagging emails as 'Billing', 'Tech Support', or 'Feature Request'.
- **Sentiment Analysis:** Labeling checks as 'Positive', 'Negative', 'Neutral'.
- **Spam Detection:** Filtering content.

## Configuration

- `labels` (array<string>, optional): List of categories to classify against.
- `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.

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

- `success` (default): Classified
- `error`: Error

## Input contract

- `text` (string, required): Content to classify.

## Output contract

- `label` (string, optional): The best matching category.
- `confidence` (number, optional): Score (0-1).

## In expressions

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

- `$("Classify Text").item.json.label` (string) = `"billing"`: The best matching category.
- `$("Classify Text").item.json.confidence` (number) = `1`: Score (0-1).
- `$("Classify Text").item.json.raw` (null) = `null` (Not suggested by the editor)


## How it works

Asks the model to pick exactly one label from `labels` for `text` and returns the matching label. Partial: on success it leaves through `out`, which is not a declared port.

1. Merges the upstream payload with the node config (config wins) and reads `labels` and `text`; throws `Missing 'labels'` or `Missing 'text'` when empty.
2. Sends a system prompt listing the labels and asking for the label name only, with `text` as the user message, at `temperature: 0`.
3. Trims the answer and compares it case-insensitively with `labels`. A match returns the label as written in `labels` with `confidence: 1`; anything else returns the raw answer with `confidence: 0`.
4. Returns `{ label, confidence, raw }` with no port, so the engine routes it to `out`.

## In a workflow

### Node

```json
{
  "node_id": "node-classify-ticket",
  "label": "Classify ticket",
  "operator_slug": "ai.classify",
  "operator_version": "1.0.0",
  "config": {
    "labels": [
      "billing",
      "technical",
      "sales"
    ],
    "text": "{{ $json.body }}",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "invocation_mode": "sync"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "label": "billing",
    "confidence": 1,
    "raw": null
  },
  "port": "out"
}
```

## Output ports (behaviour in the code)

### `success`

Declared but never emitted. On success the engine follows `out`; an edge drawn from `success` never fires. The data shown is what `out` carries.

```json
{
  "label": "billing",
  "confidence": 1,
  "raw": null
}
```

### `error`

`labels` or `text` is missing, or the model call failed.

```json
{
  "error": "LLM Invocation Error: Provider not found. This may be caused by an invalid or missing LLM Provider (llm_provider_id)."
}
```

## Behaviour in the code

- `text`: Not declared in the config schema (it is in the input contract), but a `text` key in the config is read and wins over 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 |
| --- | --- | --- |
| `Missing 'labels'` | `error` | `labels` is empty or absent. |
| `Missing 'text'` | `error` | No `text` in the config or the upstream payload. Map it with an expression such as `{{ $json.body }}`. |
| `[AiClassify] 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'.. This may be caused by an invalid or missing LLM Provider (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>. This may be caused by an invalid or missing LLM Provider (llm_provider_id).` | `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>). This may be caused by an invalid or missing LLM Provider (llm_provider_id).` | `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. This may be caused by an invalid or missing LLM Provider (llm_provider_id).` | `error` | Stream mode: no chunk arrived within `timeout_ms`. A failed stream request shows `RemoteApiService.stream: HTTP <status> — <body>` instead. |

## Notes and limits

- Known defect: the success path returns no port, so the engine uses `out`, which the node does not declare. Do not chain nodes after its success path until it is fixed.
- `confidence` is not a model score: it is `1` when the answer matched a label and `0` otherwise. An unmatched answer is still returned as `label`.
- Every model error message gets the suffix `. This may be caused by an invalid or missing LLM Provider (llm_provider_id).`
- 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.
- `raw` is the provider's raw response in sync mode and `null` in stream 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.classify",
  "name": "Classify Text",
  "category": "ai",
  "version": "1.0.0",
  "description": "Categorizes input text into one of a predefined set of labels.\n\n  This operator uses Zero-Shot Classification or a fine-tuned model to determine the intent, sentiment, or topic of the text.\n\n  **Use Cases:**\n  - **Support Routing:** Tagging emails as 'Billing', 'Tech Support', or 'Feature Request'.\n  - **Sentiment Analysis:** Labeling checks as 'Positive', 'Negative', 'Neutral'.\n  - **Spam Detection:** Filtering content.",
  "capabilities": [
    "ai",
    "classification",
    "nlp"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "labels": {
        "type": "array",
        "items": {
          "type": "string"
        },
        "title": "Target Labels",
        "description": "List of categories to classify against."
      },
      "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
      },
      "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": {
      "text": {
        "type": "string",
        "description": "Content to classify."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "label": {
        "type": "string",
        "description": "The best matching category."
      },
      "confidence": {
        "type": "number",
        "description": "Score (0-1)."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Classified",
      "is_default": true
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "classifier",
    "tagging"
  ],
  "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": {
    "labels": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "title": "Target Labels",
      "description": "List of categories to classify against."
    },
    "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
    },
    "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": {
    "text": {
      "type": "string",
      "description": "Content to classify."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "label": {
      "type": "string",
      "description": "The best matching category."
    },
    "confidence": {
      "type": "number",
      "description": "Score (0-1)."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Classified",
    "is_default": true
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
