# Extract Topics

> Extrae e identifica los temas principales de un contenido de texto.

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

- Slug: `ai.topics`
- Familia: IA
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Extrae e identifica los temas principales de un contenido de texto.

Analiza texto no estructurado para descubrir los temas relevantes, asignarles una puntuación de relevancia y, opcionalmente, asociarlos a una taxonomía existente mediante un Knowledge Resource vinculado.

**Operaciones:**
- **Discover:** Descubrimiento abierto de temas: el modelo identifica libremente los temas más destacados del texto.
- **Constrained:** Asocia el texto a una taxonomía predefinida cargada desde un Knowledge Resource. Solo se devuelven temas presentes en la taxonomía.

## Configuración

- `llm_provider_id` (string, opcional): El `id` de un registro `LlmProviderModel` (p. ej. `wf-llm-provider-*`). El orquestador delega en el backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` en modo sync, o `POST /chat/conversation/execute/stream-ephemeral` (SSE) en modo stream. El backend resuelve endpoint + api-key + deployment a partir del registro y enruta al adaptador correspondiente.
- `invocation_mode` (string, opcional): Transporte de la llamada al LLM. `sync` se bloquea hasta recibir la respuesta completa. `stream` consume los tokens mediante SSE (necesario para generaciones largas). Predeterminado: `sync`. Por defecto: `sync`. Valores permitidos: `sync`, `stream`.
- `timeout_ms` (integer, opcional): Tiempo máximo de espera para que termine la invocación (o tiempo máximo de inactividad entre fragmentos en modo stream). Predeterminado: 30000 en sync, 600000 en stream.
- `mode` (string, obligatorio): discover = descubrimiento abierto de temas; constrained = asociación a la taxonomía de un Knowledge Resource. Por defecto: `discover`. Valores permitidos: `discover`, `constrained`.
- `max_topics` (number, opcional): Número máximo de temas que se devuelven. Por defecto: `5`.
- `include_hierarchy` (boolean, opcional): Si es true, incluye un campo parent en cada tema para representar la jerarquía. Por defecto: `false`.
- `knowledge_resource_id` (string, opcional): Recurso de conocimiento con la taxonomía de temas para el modo constrained. Se muestra cuando: mode = `constrained`.
- `language` (string, opcional): Por defecto: `en`.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `success` (por defecto): Topics Extracted
- `error`: Error

## Contrato de entrada

- `text` (string, obligatorio): Contenido de texto del que se extraen los temas.

## Contrato de salida

- `topics` (array<object>, opcional): Temas extraídos con su puntuación de relevancia.
- `primary_topic` (string, opcional): El tema más relevante.
- `tags` (array<string>, opcional): Lista plana de los nombres de los temas como etiquetas.

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Extract Topics").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Extract Topics`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `success`, según la salida que muestra Puertos.

- `$("Extract Topics").item.json.topics` (array) = `[…] (3)`: Temas extraídos con su puntuación de relevancia.
- `$("Extract Topics").item.json.primary_topic` (string) = `"Billing"`: El tema más relevante.
- `$("Extract Topics").item.json.tags` (array) = `[…] (3)`: Lista plana de los nombres de los temas como etiquetas.


## Cómo funciona

Extrae los temas principales de `text` con el LLM, cada uno con una puntuación de relevancia. En modo `constrained` asigna el texto solo a los temas de una taxonomía guardada en un recurso de conocimiento.

1. Resuelve la configuración del nodo: las expresiones de las claves de configuración se evalúan contra la ejecución; el ítem entrante se usa tal cual.
2. Combina el ítem entrante con la configuración resuelta (las claves de configuración tienen prioridad) y lee las entradas del resultado.
3. Exige `text`. Lee `mode` de la definición del nodo tal como está guardada (predeterminado `discover`).
4. `discover`: pide hasta `max_topics` temas. `constrained`: carga la taxonomía desde `structured_data.topics` o `structured_data.categories` del recurso de conocimiento, aplana los niveles anidados `subcategories`/`children`/`items` y pide al modelo que use solo esos nombres.
5. Llama al LLM a través del backend con el registro `llm_provider_id`. `invocation_mode: "sync"` (predeterminado) espera la respuesta completa; `"stream"` la lee por SSE y une los fragmentos.
6. Interpreta la respuesta JSON (temperatura 0); `topics` debe ser un arreglo. Conserva los primeros `max_topics`, añade `parent` cuando `include_hierarchy` está activo y construye `tags` con los nombres de los temas.
7. Enruta a `success`, también con una lista vacía.

## En un workflow

### Nodo

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

## Puertos de salida (comportamiento en el código)

### `success`

La respuesta tenía un arreglo `topics`.

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

Falló la validación, la llamada al LLM o la interpretación. `data` es `{ error }` (más `response` cuando el backend devolvió un cuerpo).

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

## Comportamiento en el código

- `llm_provider_id`: Es obligatorio en ejecución aunque el esquema no lo marque como requerido. Es el id de un registro de proveedor LLM; el backend resuelve a partir de él el endpoint, el despliegue y las credenciales.
- `mode`: Se lee de la configuración guardada del nodo, así que una expresión aquí no se evalúa. Usa un valor literal.
- `max_topics`: Debe ser un número; cualquier otro tipo (como el texto `"10"`) recurre a 5. La lista se recorta a ese tamaño.
- `knowledge_resource_id`: Obligatorio en modo `constrained`. A diferencia de otros nodos de IA, un fallo al cargarlo hace fallar el nodo.
- `timeout_ms`: `timeout_ms` solo tiene efecto en modo `stream`, como el tiempo de inactividad permitido entre fragmentos (predeterminado 600000). En modo `sync` se registra en el log, pero la petición al backend no tiene tiempo límite.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Missing input text for topic extraction.` | `error` | El ítem entrante no tiene `text`. |
| `Missing knowledge_resource_id for constrained topic extraction.` | `error` | `mode` es `constrained` pero no hay ningún recurso de taxonomía seleccionado. |
| `Knowledge resource does not contain a valid topic taxonomy (expected structured_data.topics or .categories).` | `error` | El recurso no tiene una lista `topics` ni `categories` en sus datos estructurados. |
| `Taxonomy contains no usable topic names.` | `error` | Ninguna entrada es un texto ni tiene `name`/`topic`. |
| `Model did not return valid topic extraction output.` | `error` | La respuesta no tenía un objeto JSON con un arreglo `topics`. |
| `Knowledge resource not found: <id>` | `error` | No existe ningún recurso de conocimiento con ese id. |
| `Knowledge resource "<name>" has been deleted. Update the node config to reference an active resource.` | `error` | El recurso de conocimiento referenciado fue eliminado. Selecciona uno activo. |
| `[AiTopics] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | El nodo no tiene `llm_provider_id`. Elige un proveedor LLM en la configuración del nodo; la clave antigua `model_id` no se acepta. |
| `LLM Invocation Error: <backend message>` | `error` | El backend rechazó la llamada (registro de proveedor desconocido o inactivo, error del proveedor, credenciales). Revisa el registro del proveedor. |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | No se pudo contactar con el backend o no devolvió nada en modo `sync`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | En modo `stream` no llegó ningún fragmento dentro de `timeout_ms`. |

## Notas y límites

- Los `tags` que devuelve el modelo se ignoran; `tags` siempre se construye a partir de `topics`. En modo `constrained` los nombres no se validan contra la taxonomía.
- El recurso de conocimiento se lee del backend con un tiempo límite de 10 s. Un recurso con estado `deleted` se rechaza; cualquier otro estado distinto de `active` solo se registra como advertencia.
- La respuesta del modelo se interpreta como JSON tras quitar los bloques de código Markdown; si falla, se interpreta el texto entre la primera `{` y la última `}`.
- Los campos de entrada se leen del ítem entrante (`$json`). Una clave con el mismo nombre en la configuración del nodo, que puede ser una expresión, tiene prioridad sobre la entrada.
- El worker también devuelve la respuesta del proveedor como `raw` fuera de `data`; el motor no la conserva.
- En caso de éxito el worker devuelve `port` y `data` sin el campo `ok`; el motor enruta solo por `port`.
- `timeout_ms` solo tiene efecto en modo `stream`, como el tiempo de inactividad permitido entre fragmentos (predeterminado 600000). En modo `sync` se registra en el log, pero la petición al backend no tiene tiempo límite.
- En modo `stream` la temperatura que fija este nodo no se envía al proveedor, y `raw` es `null`.
- El motor no aplica `execution.retryOnFail`, `maxTries`, `waitBetweenTries` ni `continueOnFail` a este nodo. Gestiona los fallos conectando el puerto `error`.


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