# Extract Topics

> Extract and identify the main topics from text content.

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

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

Extract and identify the main topics from text content.

Analyzes unstructured text to discover relevant topics, assign relevance scores, and optionally map them to an existing taxonomy via a linked Knowledge Resource.

**Operations:**
- **Discover:** Open-ended topic discovery — the model freely identifies the most salient topics from the text.
- **Constrained:** Map text to a predefined taxonomy loaded from a Knowledge Resource. Only topics present in the taxonomy are returned.

## 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.
- `mode` (string, required): discover = open-ended topic discovery; constrained = map to taxonomy from Knowledge Resource. Default: `discover`. Allowed values: `discover`, `constrained`.
- `max_topics` (number, optional): Maximum number of topics to return. Default: `5`.
- `include_hierarchy` (boolean, optional): When true, include a parent field for each topic to represent hierarchy. Default: `false`.
- `knowledge_resource_id` (string, optional): Knowledge resource containing the topic taxonomy for constrained mode. Shown when: mode = `constrained`.
- `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

- `success` (default): Topics Extracted
- `error`: Error

## Input contract

- `text` (string, required): Text content to extract topics from.

## Output contract

- `topics` (array<object>, optional): Extracted topics with relevance scores.
- `primary_topic` (string, optional): The single most relevant topic.
- `tags` (array<string>, optional): Flat list of topic names as tags.

## In expressions

What a later node can read from this node's output with `$("Extract Topics").item.json.<path>` (write your node's label instead of `Extract Topics`). **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.

- `$("Extract Topics").item.json.topics` (array) = `[…] (3)`: Extracted topics with relevance scores.
- `$("Extract Topics").item.json.primary_topic` (string) = `"Billing"`: The single most relevant topic.
- `$("Extract Topics").item.json.tags` (array) = `[…] (3)`: Flat list of topic names as tags.


## How it works

Extracts the main topics of `text` with the LLM, with a relevance score each. In `constrained` mode it maps the text only to the topics of a taxonomy stored in a knowledge resource.

1. Resolves the node config: expressions in config keys are evaluated against the run; the incoming item is used as-is.
2. Merges the incoming item with the resolved config (config keys win) and reads the inputs from the result.
3. Requires `text`. Reads `mode` from the node definition as saved (default `discover`).
4. `discover`: asks for up to `max_topics` topics. `constrained`: loads the taxonomy from `structured_data.topics` or `structured_data.categories` of the knowledge resource, flattens nested `subcategories`/`children`/`items`, and asks the model to use only those names.
5. Calls the LLM through the backend with the `llm_provider_id` record. `invocation_mode: "sync"` (default) waits for the full answer; `"stream"` reads it over SSE and joins the chunks.
6. Parses the JSON answer (temperature 0); `topics` must be an array. Keeps the first `max_topics`, adds `parent` when `include_hierarchy` is on, and builds `tags` from the topic names.
7. Routes to `success`, also with an empty list.

## In a workflow

### Node

```json
{
  "node_id": "node-topics",
  "label": "Tag ticket topics",
  "operator_slug": "ai.topics",
  "operator_version": "1.0.0",
  "config": {
    "llm_provider_id": "<llm_provider_id>",
    "mode": "discover",
    "max_topics": 3,
    "include_hierarchy": false,
    "language": "en"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "success",
  "data": {
    "topics": [
      {
        "topic": "Billing",
        "relevance": 0.92
      },
      {
        "topic": "Refunds",
        "relevance": 0.75
      },
      {
        "topic": "Account access",
        "relevance": 0.31
      }
    ],
    "primary_topic": "Billing",
    "tags": [
      "Billing",
      "Refunds",
      "Account access"
    ]
  }
}
```

## Output ports (behaviour in the code)

### `success`

The answer had a `topics` array.

```json
{
  "topics": [
    {
      "topic": "Billing",
      "relevance": 0.92
    },
    {
      "topic": "Refunds",
      "relevance": 0.75
    },
    {
      "topic": "Account access",
      "relevance": 0.31
    }
  ],
  "primary_topic": "Billing",
  "tags": [
    "Billing",
    "Refunds",
    "Account access"
  ]
}
```

### `error`

Validation, the LLM call or parsing failed. `data` is `{ error }` (plus `response` when the backend returned a body).

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

## Behaviour in the code

- `llm_provider_id`: Required at runtime although the schema does not mark it as required. It is the id of an LLM provider record; the backend resolves endpoint, deployment and credentials from it.
- `mode`: Read from the saved node config, so an expression here is not evaluated. Set a literal value.
- `max_topics`: Must be a number; any other type (such as the string `"10"`) falls back to 5. The list is truncated to this size.
- `knowledge_resource_id`: Required in `constrained` mode. Unlike other AI nodes, a load failure here fails the node.
- `timeout_ms`: `timeout_ms` only takes effect in `stream` mode, as the idle time allowed between chunks (default 600000). In `sync` mode it is logged but the backend request has no timeout.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Missing input text for topic extraction.` | `error` | The incoming item has no `text`. |
| `Missing knowledge_resource_id for constrained topic extraction.` | `error` | `mode` is `constrained` but no taxonomy resource is selected. |
| `Knowledge resource does not contain a valid topic taxonomy (expected structured_data.topics or .categories).` | `error` | The resource has no `topics` or `categories` list in its structured data. |
| `Taxonomy contains no usable topic names.` | `error` | No entry is a string or has `name`/`topic`. |
| `Model did not return valid topic extraction output.` | `error` | The answer had no JSON object with a `topics` array. |
| `Knowledge resource not found: <id>` | `error` | No knowledge resource has that id. |
| `Knowledge resource "<name>" has been deleted. Update the node config to reference an active resource.` | `error` | The referenced knowledge resource was deleted. Select an active one. |
| `[AiTopics] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | The node has no `llm_provider_id`. Pick an LLM provider in the node config; the legacy `model_id` key is not accepted. |
| `LLM Invocation Error: <backend message>` | `error` | The backend rejected the call (unknown or inactive provider record, provider error, credentials). Check the provider record. |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | The backend could not be reached or returned nothing in `sync` mode. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | In `stream` mode no chunk arrived within `timeout_ms`. |

## Notes and limits

- The `tags` the model returns are ignored; `tags` is always built from `topics`. In `constrained` mode the names are not validated against the taxonomy.
- The knowledge resource is read from the backend with a 10 s timeout. A resource with status `deleted` is rejected; any other non-`active` status is only logged as a warning.
- The model answer is parsed as JSON after removing Markdown code fences; if that fails, the text between the first `{` and the last `}` is parsed.
- Input fields are read from the incoming item (`$json`). A key with the same name in the node config, which may be an expression, takes precedence over the input.
- The worker also returns the provider response as `raw` outside `data`; the engine does not keep it.
- On success the worker returns `port` and `data` without an `ok` field; the engine routes on `port` only.
- `timeout_ms` only takes effect in `stream` mode, as the idle time allowed between chunks (default 600000). In `sync` mode it is logged but the backend request has no timeout.
- In `stream` mode the temperature this node sets is not forwarded to the provider, and `raw` is `null`.
- The engine does not apply `execution.retryOnFail`, `maxTries`, `waitBetweenTries` or `continueOnFail` to this node. Handle failures by wiring the `error` port.


## Contracts (JSON Schema)

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

```json
{
  "slug": "ai.topics",
  "name": "Extract Topics",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extract and identify the main topics from text content.\n\n  Analyzes unstructured text to discover relevant topics, assign relevance scores, and optionally map them to an existing taxonomy via a linked Knowledge Resource.\n\n  **Operations:**\n  - **Discover:** Open-ended topic discovery — the model freely identifies the most salient topics from the text.\n  - **Constrained:** Map text to a predefined taxonomy loaded from a Knowledge Resource. Only topics present in the taxonomy are returned.",
  "capabilities": [
    "ai",
    "nlp",
    "topics",
    "taxonomy",
    "tagging"
  ],
  "knowledge_binding": {
    "enabled": true,
    "resource_types": [
      "taxonomy"
    ],
    "field": "knowledge_resource_id",
    "label": "Topic Taxonomy"
  },
  "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
      },
      "mode": {
        "type": "string",
        "title": "Extraction Mode",
        "enum": [
          "discover",
          "constrained"
        ],
        "default": "discover",
        "description": "discover = open-ended topic discovery; constrained = map to taxonomy from Knowledge Resource."
      },
      "max_topics": {
        "type": "number",
        "title": "Max Topics",
        "default": 5,
        "description": "Maximum number of topics to return.",
        "minimum": 1,
        "maximum": 50
      },
      "include_hierarchy": {
        "type": "boolean",
        "title": "Include Hierarchy",
        "default": false,
        "description": "When true, include a parent field for each topic to represent hierarchy."
      },
      "knowledge_resource_id": {
        "type": "string",
        "title": "Topic Taxonomy (Knowledge Resource)",
        "description": "Knowledge resource containing the topic taxonomy for constrained mode.",
        "x-ui-widget": "knowledge-resource-picker",
        "x-knowledge-resource-types": [
          "taxonomy"
        ],
        "displayOptions": {
          "show": {
            "mode": [
              "constrained"
            ]
          }
        }
      },
      "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": [
      "mode"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string",
        "description": "Text content to extract topics from."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "topics": {
        "type": "array",
        "description": "Extracted topics with relevance scores.",
        "items": {
          "type": "object",
          "properties": {
            "topic": {
              "type": "string",
              "description": "Topic name."
            },
            "relevance": {
              "type": "number",
              "description": "Relevance score (0-1)."
            },
            "parent": {
              "type": "string",
              "description": "Parent topic (when hierarchy is enabled)."
            }
          }
        }
      },
      "primary_topic": {
        "type": "string",
        "description": "The single most relevant topic."
      },
      "tags": {
        "type": "array",
        "items": {
          "type": "string"
        },
        "description": "Flat list of topic names as tags."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Topics Extracted",
      "is_default": true
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "nlp",
    "topics",
    "taxonomy",
    "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": {
    "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
    },
    "mode": {
      "type": "string",
      "title": "Extraction Mode",
      "enum": [
        "discover",
        "constrained"
      ],
      "default": "discover",
      "description": "discover = open-ended topic discovery; constrained = map to taxonomy from Knowledge Resource."
    },
    "max_topics": {
      "type": "number",
      "title": "Max Topics",
      "default": 5,
      "description": "Maximum number of topics to return.",
      "minimum": 1,
      "maximum": 50
    },
    "include_hierarchy": {
      "type": "boolean",
      "title": "Include Hierarchy",
      "default": false,
      "description": "When true, include a parent field for each topic to represent hierarchy."
    },
    "knowledge_resource_id": {
      "type": "string",
      "title": "Topic Taxonomy (Knowledge Resource)",
      "description": "Knowledge resource containing the topic taxonomy for constrained mode.",
      "x-ui-widget": "knowledge-resource-picker",
      "x-knowledge-resource-types": [
        "taxonomy"
      ],
      "displayOptions": {
        "show": {
          "mode": [
            "constrained"
          ]
        }
      }
    },
    "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": [
    "mode"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string",
      "description": "Text content to extract topics from."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "topics": {
      "type": "array",
      "description": "Extracted topics with relevance scores.",
      "items": {
        "type": "object",
        "properties": {
          "topic": {
            "type": "string",
            "description": "Topic name."
          },
          "relevance": {
            "type": "number",
            "description": "Relevance score (0-1)."
          },
          "parent": {
            "type": "string",
            "description": "Parent topic (when hierarchy is enabled)."
          }
        }
      }
    },
    "primary_topic": {
      "type": "string",
      "description": "The single most relevant topic."
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "description": "Flat list of topic names as tags."
    }
  }
}
```

### ports

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