# Summarize Text

> 由 LLM 驱动的多格式文本摘要。

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

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

由 LLM 驱动的多格式文本摘要。

该算子使用若干模式之一，将输入文本浓缩为摘要。

**操作**
- **Executive：** 面向决策者的 2-3 句高层摘要。
- **Bullets：** 以项目符号列表列出要点。
- **Abstractive：** 保留核心含义的浓缩改写。
- **Extractive：** 选取原文中最重要的句子。
- **Structured：** 生成包含 overview、key_findings、action_items 和 risks_concerns 部分的 JSON 对象。

**适用场景**
- 为相关方浓缩会议记录或报告。
- 为仪表盘和通知生成要点摘要。
- 为下游工作流处理生成结构化摘要。

## 配置

- `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。
- `summary_mode` (string, 可选): 要应用的摘要策略。 默认值: `executive`. 可选值: `executive`, `bullets`, `abstractive`, `extractive`, `structured`.
- `max_length` (number, 可选): 摘要的目标最大字数（可选）。
- `max_bullets` (number, 可选): 最多的要点数量（仅 bullets 模式）。 默认值: `5`. 显示条件: summary_mode = `bullets`.
- `language` (string, 可选): 输出语言代码（例如“en”“es”）。 默认值: `en`.
- `focus_areas` (array<string>, 可选): 摘要中需优先关注的话题或主题（可选）。

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

## 输出端口

- `success` (默认): Summarized
- `error`: Error

## 输入契约

- `text` (string, 必填): 要摘要的文本内容。
- `title` (string, 可选): 作为上下文的可选标题。
- `context` (string, 可选): 为摘要提供参考的可选背景信息。

## 输出契约

- `summary` (string, 可选): 生成的摘要文本。
- `sections` (object, 可选): 结构化各部分（仅 structured 模式）。
- `key_phrases` (array<string>, 可选): 文本中检测到的关键短语（如有）。
- `word_count` (number, 可选): 摘要的字数。
- `compression_ratio` (number, 可选): 摘要字数与原文字数之比（0-1）。

## 在表达式中

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

- `$("Summarize Text").item.json.summary` (string) = `"The supplier will deliver the missing pallet…"`: 生成的摘要文本。
- `$("Summarize Text").item.json.sections` (object) = `null`: 结构化各部分（仅 structured 模式）。
- `$("Summarize Text").item.json.key_phrases` (array) = `[…] (0)`: 文本中检测到的关键短语（如有）。
- `$("Summarize Text").item.json.word_count` (number) = `18`: 摘要的字数。
- `$("Summarize Text").item.json.compression_ratio` (number) = `0.12`: 摘要字数与原文字数之比（0-1）。
- `$("Summarize Text").item.json.raw` (null) = `null` (编辑器不提示)
- `$("Summarize Text").item.json.port` (string) = `"success"` (编辑器不提示)


## 工作原理

使用 LLM 以五种模式之一（执行摘要、要点、生成式、抽取式、结构化）对 `text` 进行摘要，返回摘要及其词数和压缩比。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 将传入条目与解析后的配置合并（配置键优先），并从合并结果中读取输入。
3. 必须提供 `text`。根据 `summary_mode`（默认 `executive`，未知模式也使用它）构建指令，并加入 `max_length`、`focus_areas`，以及当 `language` 不为 `en` 时的语言说明。
4. 用户消息由 `Title: …`、`Context: …`（若有）和 `Text: …` 组成。
5. 通过后端使用 `llm_provider_id` 记录调用 LLM。`invocation_mode: "sync"`（默认）等待完整响应；`"stream"` 通过 SSE 读取并拼接分块。
6. `structured` 模式会将 JSON 响应解析到 `sections`；若不是 JSON，则原始文本作为 `summary`，`sections` 为 `null`。其他模式下，响应文本即为摘要。
7. 按空白字符统计词数，并计算 `compression_ratio` = 摘要词数 / 输入词数。路由到 `success`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-summarize",
  "label": "Summarize thread",
  "operator_slug": "ai.summarize",
  "operator_version": "1.0.0",
  "config": {
    "llm_provider_id": "<llm_provider_id>",
    "summary_mode": "executive",
    "max_length": 60,
    "language": "en",
    "focus_areas": [
      "deadlines",
      "costs"
    ]
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "success",
  "data": {
    "summary": "The supplier will deliver the missing pallets on Friday. Finance must approve the extra freight cost before Thursday.",
    "sections": null,
    "key_phrases": [],
    "word_count": 18,
    "compression_ratio": 0.12,
    "raw": null,
    "port": "success"
  }
}
```

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

### `success`

LLM 已响应。worker 在顶层返回各字段，因此 `data` 中还包含 `raw` 和 `port`。

```json
{
  "summary": "The supplier will deliver the missing pallets on Friday. Finance must approve the extra freight cost before Thursday.",
  "sections": null,
  "key_phrases": [],
  "word_count": 18,
  "compression_ratio": 0.12,
  "raw": null,
  "port": "success"
}
```

### `error`

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

```json
{
  "error": "Missing 'text'"
}
```

## 代码中的行为

- `llm_provider_id`: 虽然 schema 未将其标为必填，但运行时必须提供。它是 LLM 提供方记录的 id；后端据此解析端点、部署和凭据。
- `summary_mode`: 温度：`extractive` 为 0，`abstractive` 为 0.3，其余为 0.2。只有 `structured` 会填充 `sections` 和 `key_phrases`（复制自 `key_findings`）；其他模式返回 `sections: null` 和 `key_phrases: []`。
- `max_bullets`: 默认 5。在 `extractive` 模式下也决定选取的句子数，尽管 schema 只在 `bullets` 模式下显示它。
- `max_length`: 以词数表示的提示词提示；输出不会被截断。
- `timeout_ms`: `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'text'` | `error` | 传入条目中没有 `text`。 |
| `[AiSummarize] 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` 内没有收到任何分块。 |

## 说明与限制

- 输入字段从传入条目（`$json`）读取。节点配置中同名的键（可以是表达式）优先于输入。
- `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。
- 在 `stream` 模式下，此节点设置的温度不会转发给提供方，且 `raw` 为 `null`。
- 引擎不会对此节点应用 `execution.retryOnFail`、`maxTries`、`waitBetweenTries` 或 `continueOnFail`。请通过连接 `error` 端口处理失败。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.summarize",
  "name": "Summarize Text",
  "category": "ai",
  "version": "1.0.0",
  "description": "Multi-format text summarization powered by LLM.\n\nThis operator condenses input text into a summary using one of several modes.\n\n**Operations**\n- **Executive:** 2-3 sentence high-level summary for decision-makers.\n- **Bullets:** Key points as a bullet-point list.\n- **Abstractive:** Condensed rewrite preserving core meaning.\n- **Extractive:** Selects the most important original sentences.\n- **Structured:** Produces a JSON object with overview, key_findings, action_items, and risks_concerns sections.\n\n**Use Cases**\n- Condensing meeting transcripts or reports for stakeholders.\n- Generating bullet-point digests for dashboards and notifications.\n- Producing structured summaries for downstream workflow processing.",
  "capabilities": [
    "ai",
    "nlp",
    "summarization",
    "text"
  ],
  "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
      },
      "summary_mode": {
        "type": "string",
        "title": "Summary Mode",
        "description": "The summarization strategy to apply.",
        "enum": [
          "executive",
          "bullets",
          "abstractive",
          "extractive",
          "structured"
        ],
        "default": "executive"
      },
      "max_length": {
        "type": "number",
        "title": "Max Length (words)",
        "description": "Target maximum words for the summary (optional)."
      },
      "max_bullets": {
        "type": "number",
        "title": "Max Bullets",
        "description": "Maximum number of bullet points (bullets mode only).",
        "default": 5,
        "displayOptions": {
          "show": {
            "summary_mode": [
              "bullets"
            ]
          }
        }
      },
      "language": {
        "type": "string",
        "title": "Language",
        "description": "Output language code (e.g., \"en\", \"es\").",
        "default": "en"
      },
      "focus_areas": {
        "type": "array",
        "items": {
          "type": "string"
        },
        "title": "Focus Areas",
        "description": "Topics or themes to prioritize in the summary (optional)."
      },
      "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": "The text content to summarize."
      },
      "title": {
        "type": "string",
        "description": "Optional title or heading for context."
      },
      "context": {
        "type": "string",
        "description": "Optional background context to inform the summary."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "summary": {
        "type": "string",
        "description": "The generated summary text."
      },
      "sections": {
        "type": "object",
        "description": "Structured sections (structured mode only)."
      },
      "key_phrases": {
        "type": "array",
        "items": {
          "type": "string"
        },
        "description": "Key phrases detected in the text (when available)."
      },
      "word_count": {
        "type": "number",
        "description": "Word count of the summary."
      },
      "compression_ratio": {
        "type": "number",
        "description": "Ratio of summary words to original words (0-1)."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Summarized",
      "is_default": true
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "nlp",
    "summarize",
    "text"
  ],
  "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
    },
    "summary_mode": {
      "type": "string",
      "title": "Summary Mode",
      "description": "The summarization strategy to apply.",
      "enum": [
        "executive",
        "bullets",
        "abstractive",
        "extractive",
        "structured"
      ],
      "default": "executive"
    },
    "max_length": {
      "type": "number",
      "title": "Max Length (words)",
      "description": "Target maximum words for the summary (optional)."
    },
    "max_bullets": {
      "type": "number",
      "title": "Max Bullets",
      "description": "Maximum number of bullet points (bullets mode only).",
      "default": 5,
      "displayOptions": {
        "show": {
          "summary_mode": [
            "bullets"
          ]
        }
      }
    },
    "language": {
      "type": "string",
      "title": "Language",
      "description": "Output language code (e.g., \"en\", \"es\").",
      "default": "en"
    },
    "focus_areas": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "title": "Focus Areas",
      "description": "Topics or themes to prioritize in the summary (optional)."
    },
    "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": "The text content to summarize."
    },
    "title": {
      "type": "string",
      "description": "Optional title or heading for context."
    },
    "context": {
      "type": "string",
      "description": "Optional background context to inform the summary."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "summary": {
      "type": "string",
      "description": "The generated summary text."
    },
    "sections": {
      "type": "object",
      "description": "Structured sections (structured mode only)."
    },
    "key_phrases": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "description": "Key phrases detected in the text (when available)."
    },
    "word_count": {
      "type": "number",
      "description": "Word count of the summary."
    },
    "compression_ratio": {
      "type": "number",
      "description": "Ratio of summary words to original words (0-1)."
    }
  }
}
```

### ports

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