# Extract Topics

> 从文本内容中抽取并识别主要话题。

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

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

从文本内容中抽取并识别主要话题。

分析非结构化文本以发现相关话题、给出相关性得分，并可选地通过关联的 Knowledge Resource 将其映射到既有分类体系。

**操作：**
- **Discover：** 开放式话题发现，由模型自由识别文本中最突出的话题。
- **Constrained：** 将文本映射到从 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。
- `mode` (string, 必填): discover = 开放式话题发现；constrained = 映射到 Knowledge Resource 中的分类体系。 默认值: `discover`. 可选值: `discover`, `constrained`.
- `max_topics` (number, 可选): 返回话题的最大数量。 默认值: `5`.
- `include_hierarchy` (boolean, 可选): 为 true 时，为每个话题附带 parent 字段以表示层级。 默认值: `false`.
- `knowledge_resource_id` (string, 可选): constrained 模式下包含话题分类体系的知识资源。 显示条件: mode = `constrained`.
- `language` (string, 可选): 默认值: `en`.

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

## 输出端口

- `success` (默认): Topics Extracted
- `error`: Error

## 输入契约

- `text` (string, 必填): 要从中抽取话题的文本内容。

## 输出契约

- `topics` (array<object>, 可选): 抽取出的话题，附带相关性得分。
- `primary_topic` (string, 可选): 最相关的单个话题。
- `tags` (array<string>, 可选): 以标签形式给出的话题名称平铺列表。

## 在表达式中

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

- `$("Extract Topics").item.json.topics` (array) = `[…] (3)`: 抽取出的话题，附带相关性得分。
- `$("Extract Topics").item.json.primary_topic` (string) = `"Billing"`: 最相关的单个话题。
- `$("Extract Topics").item.json.tags` (array) = `[…] (3)`: 以标签形式给出的话题名称平铺列表。


## 工作原理

使用 LLM 提取 `text` 的主要主题，并为每个主题给出相关度得分。`constrained` 模式只会将文本映射到知识资源中存储的分类体系主题。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 将传入条目与解析后的配置合并（配置键优先），并从合并结果中读取输入。
3. 必须提供 `text`。从已保存的节点定义中读取 `mode`（默认 `discover`）。
4. `discover`：请求最多 `max_topics` 个主题。`constrained`：从知识资源的 `structured_data.topics` 或 `structured_data.categories` 加载分类体系，展平嵌套的 `subcategories`/`children`/`items`，并要求模型只使用这些名称。
5. 通过后端使用 `llm_provider_id` 记录调用 LLM。`invocation_mode: "sync"`（默认）等待完整响应；`"stream"` 通过 SSE 读取并拼接分块。
6. 解析 JSON 响应（温度 0），`topics` 必须为数组。保留前 `max_topics` 个，在开启 `include_hierarchy` 时添加 `parent`，并根据主题名称生成 `tags`。
7. 路由到 `success`，即使列表为空。

## 在工作流中

### 节点

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

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

### `success`

响应中包含 `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`

校验、LLM 调用或解析失败。`data` 为 `{ error }`（若后端返回了响应体，还包含 `response`）。

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

## 代码中的行为

- `llm_provider_id`: 虽然 schema 未将其标为必填，但运行时必须提供。它是 LLM 提供方记录的 id；后端据此解析端点、部署和凭据。
- `mode`: 从已保存的节点配置中读取，因此此处的表达式不会被求值。请设置字面值。
- `max_topics`: 必须为数字；其他类型（如字符串 `"10"`）会回退为 5。列表会被截断到该长度。
- `knowledge_resource_id`: `constrained` 模式下必填。与其他 AI 节点不同，此处加载失败会导致节点失败。
- `timeout_ms`: `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing input text for topic extraction.` | `error` | 传入条目中没有 `text`。 |
| `Missing knowledge_resource_id for constrained topic extraction.` | `error` | `mode` 为 `constrained`，但未选择分类体系资源。 |
| `Knowledge resource does not contain a valid topic taxonomy (expected structured_data.topics or .categories).` | `error` | 该资源的结构化数据中没有 `topics` 或 `categories` 列表。 |
| `Taxonomy contains no usable topic names.` | `error` | 没有任何条目是字符串或含有 `name`/`topic`。 |
| `Model did not return valid topic extraction output.` | `error` | 响应中没有含 `topics` 数组的 JSON 对象。 |
| `Knowledge resource not found: <id>` | `error` | 不存在该 id 的知识资源。 |
| `Knowledge resource "<name>" has been deleted. Update the node config to reference an active resource.` | `error` | 所引用的知识资源已被删除。请选择一个有效的资源。 |
| `[AiTopics] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | 节点缺少 `llm_provider_id`。请在节点配置中选择一个 LLM 提供方；旧的 `model_id` 键不再被接受。 |
| `LLM Invocation Error: <backend message>` | `error` | 后端拒绝了调用（提供方记录不存在或未启用、提供方错误、凭据问题）。请检查提供方记录。 |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | 在 `sync` 模式下无法连接后端，或后端未返回任何内容。 |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | 在 `stream` 模式下，`timeout_ms` 内没有收到任何分块。 |

## 说明与限制

- 模型返回的 `tags` 会被忽略；`tags` 始终根据 `topics` 生成。在 `constrained` 模式下，名称不会与分类体系进行校验。
- 知识资源从后端读取，超时时间为 10 秒。状态为 `deleted` 的资源会被拒绝；其他非 `active` 状态只会记录警告。
- 模型响应在去除 Markdown 代码块标记后按 JSON 解析；若失败，则解析第一个 `{` 与最后一个 `}` 之间的文本。
- 输入字段从传入条目（`$json`）读取。节点配置中同名的键（可以是表达式）优先于输入。
- Worker 还会在 `data` 之外以 `raw` 返回提供方的原始响应；引擎不会保留它。
- 成功时 worker 返回 `port` 和 `data`，不含 `ok` 字段；引擎只依据 `port` 路由。
- `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。
- 在 `stream` 模式下，此节点设置的温度不会转发给提供方，且 `raw` 为 `null`。
- 引擎不会对此节点应用 `execution.retryOnFail`、`maxTries`、`waitBetweenTries` 或 `continueOnFail`。请通过连接 `error` 端口处理失败。


## 契约（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"
  }
]
```
