# Compose Content

> 由 AI 驱动的结构化商务沟通内容撰写。

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

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

由 AI 驱动的结构化商务沟通内容撰写。

该算子根据结构化参数生成精炼的内容，使用特定于模式的提示词或自定义 PromptTemplate。

**操作**
- **Email：** 根据主题、要点和语气撰写专业邮件。
- **Response：** 根据工单上下文和解决方案详情生成客服回复。
- **Report：** 根据数据点和可选的模板结构生成报告章节。
- **Notification：** 根据事件详情和目标受众生成通知消息。
- **Custom：** 使用 PromptTemplate 并填充变量来生成内容。

**适用场景**
- 在工作流中自动起草外发邮件。
- 生成风格一致的客服回复。
- 根据结构化数据生成报告章节。
- 为运营事件创建模板化通知。

## 配置

- `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（长文本生成可能超出 HTTP 超时时必须使用）。默认为 `sync`。 默认值: `sync`. 可选值: `sync`, `stream`.
- `timeout_ms` (integer, 可选): 等待调用完成的最长时间（stream 模式下为分块之间的空闲超时）。sync 默认 30000，stream 默认 600000。
- `content_type` (string, 可选): 要生成的内容类型。 默认值: `email`. 可选值: `email`, `response`, `report`, `notification`, `custom`.
- `tone` (string, 可选): 生成内容所采用的语气。 默认值: `professional`. 可选值: `professional`, `friendly`, `formal`, `urgent`, `empathetic`.
- `language` (string, 可选): 输出语言代码（例如“en”“es”）。 默认值: `en`.
- `template_id` (string, 可选): 用于自定义内容生成的 PromptTemplate ID。 显示条件: content_type = `custom`.
- `knowledge_resource_id` (string, 可选): 可选的知识资源 ID，用于品牌语调或写作风格指南。

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

## 输出端口

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

## 输入契约

- `parameters` (object, 必填): 用于内容生成的键值对（subject、key_points、ticket、resolution、data、template、event、audience 等）。
- `context` (string, 可选): 为内容提供参考的可选背景信息。
- `recipient` (string, 可选): 可选的收件人名称或标识。

## 输出契约

- `content` (string, 可选): 生成的内容正文。
- `subject` (string, 可选): 生成的主题行（email 模式）。
- `metadata` (object, 可选): 生成元数据（模式、语气、模型）。

## 在表达式中

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

- `$("Compose Content").item.json.content` (string) = `"Hello Ana,\n\nYour refund for order 4521 was…"`: 生成的内容正文。
- `$("Compose Content").item.json.subject` (string) = `"Your refund was approved"`: 生成的主题行（email 模式）。
- `$("Compose Content").item.json.metadata` (object) = `{…}`: 生成元数据（模式、语气、模型）。
- `$("Compose Content").item.json.metadata.content_type` (string) = `"email"` (编辑器不提示)
- `$("Compose Content").item.json.metadata.tone` (string) = `"friendly"` (编辑器不提示)
- `$("Compose Content").item.json.metadata.llm_provider_id` (string) = `"wf-llm-provider-xxxx"` (编辑器不提示)
- `$("Compose Content").item.json.metadata.title` (null) = `null` (编辑器不提示)
- `$("Compose Content").item.json.raw` (null) = `null` (编辑器不提示)
- `$("Compose Content").item.json.port` (string) = `"success"` (编辑器不提示)


## 工作原理

借助模型根据 `parameters` 撰写邮件、客户回复、报告章节或通知，或在 `custom` 模式下填充已保存的提示词模板；可选附加品牌语调规范。

1. 合并上游载荷与节点配置（以配置为准）；`parameters` 不是对象时抛出 `Missing 'parameters'`。
2. 构建系统提示词。`email`、`response`、`report`、`notification` 会插入 `parameters` 中的固定字段（`subject`、`key_points`、`ticket`、`resolution`、`data`、`template`、`event`、`audience`）、`tone` 及 JSON 输出格式；未知类型使用 email 提示词。
3. `custom` 模式会从后端获取提示词模板 `template_id`，把每个 `{{ key }}` 替换为 `parameters` 中对应的值；模板即为完整的系统提示词。
4. 设置了 `knowledge_resource_id` 时，追加 `## Brand Voice / Style Guidelines` 及资源内容；获取失败只记录日志。
5. 用户消息包含 `Recipient:`、`Context:` 以及 `parameters` 中其余各键（格式为 `key: value`）；以 `temperature: 0.5` 调用模型。
6. 将回答解析为 JSON 以获取 `content`、`subject` 和 `title`；不是 JSON 时整段回答作为 `content`，`subject` 为 `null`。从 `success` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-compose-reply",
  "label": "Compose reply",
  "operator_slug": "ai.compose",
  "operator_version": "1.0.0",
  "config": {
    "content_type": "email",
    "tone": "friendly",
    "language": "en",
    "parameters": {
      "subject": "Your refund was approved",
      "key_points": "{{ $json.resolution_summary }}",
      "order_id": "{{ $json.order_id }}"
    },
    "recipient": "{{ $json.customer_name }}",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "invocation_mode": "sync"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "content": "Hello Ana,\n\nYour refund for order 4521 was approved and will reach your card within 5 business days.\n\nBest regards,\nSupport",
    "subject": "Your refund was approved",
    "metadata": {
      "content_type": "email",
      "tone": "friendly",
      "llm_provider_id": "wf-llm-provider-xxxx",
      "title": null
    },
    "raw": null,
    "port": "success"
  },
  "port": "success"
}
```

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

### `success`

模型已回答。JSON 无效不算错误：原始回答直接作为 `content`。

```json
{
  "content": "Hello Ana,\n\nYour refund for order 4521 was approved and will reach your card within 5 business days.\n\nBest regards,\nSupport",
  "subject": "Your refund was approved",
  "metadata": {
    "content_type": "email",
    "tone": "friendly",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "title": null
  },
  "raw": null,
  "port": "success"
}
```

### `error`

缺少 `parameters`、无法加载模板或模型调用失败。

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

## 代码中的行为

- `parameters, context, recipient`: 不在配置 schema 中（位于输入契约中），但会先从配置读取，再从上游载荷读取。
- `tone, language`: 在 `custom` 模式下被忽略，因为模板即完整系统提示词。`report` 提示词中也不写入 `tone`。
- `knowledge_resource_id`: 原样追加资源的 `content`（或 `body`、`text`）。若 `content` 是对象，会被插入为 `[object Object]`；请确保规范以纯文本存储。
- `timeout_ms`: 仅限 stream 模式：片段之间的空闲超时，默认 600000。在 sync 模式下不会作用于请求。
- `execution`: 已声明但被忽略：worker 和引擎都不会读取该块中的 `retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`alwaysOutputData` 或 `timeout_ms`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'parameters'` | `error` | `parameters` 不存在或不是对象，`custom` 模式也不例外。 |
| `Missing 'template_id' for custom content type` | `error` | `content_type` 为 `custom` 但 `template_id` 为空。 |
| `Prompt Template <template_id> not found` | `error` | 后端未返回该 id 的模板。模板缺少 `template_body`、`content` 和 `template` 时报 `Template <template_id> has no content`；HTTP 错误显示为 `Request failed with status code <status>`。 |
| `[Compose] 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'.` | `error` | `llm_provider_id` 为空或不是字符串。请选择具备 chat 能力的 LLM 提供方记录。 |
| `LLM Invocation Error: <backend message>` | `error` | 后端拒绝了调用：提供方记录不存在或未激活、提供方报错、配额或内容过滤。请检查提供方记录和后端日志。 |
| `LLM Invocation Error: empty response from backend (<transport error>)` | `error` | sync 模式：对后端的 HTTP 调用失败（网络错误、非 2xx 状态或超时）。长提示词常会触发请求超时，请改用 `invocation_mode: "stream"`。 |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | stream 模式：在 `timeout_ms` 内未收到任何片段。若流式请求本身失败，消息为 `RemoteApiService.stream: HTTP <status> — <body>`。 |

## 说明与限制

- `custom` 模式下获取提示词模板的请求没有单独的超时设置。
- 该 worker 将字段直接放在返回值顶层而非 `data` 内，因此引擎把整个返回值存为节点输出：`port` 和 `raw` 会与结果字段一起出现在 `$json` 中。
- 模型调用经由 Sommatic AI 后端完成，后端根据 `llm_provider_id` 指定的提供方记录解析端点、凭据和部署；编排器从不持有提供方密钥。`invocation_mode: "sync"`（默认）等待完整回答；`"stream"` 以 SSE 事件读取回答并拼接各片段。
- `timeout_ms` 仅在 stream 模式下生效，表示片段之间允许的最长空闲时间（默认 600000）。在 sync 模式下该值只写入日志，不会作用于 HTTP 请求，因此以平台默认请求超时为准。
- 在 stream 模式下，后端端点不应用采样参数，因此固定的 `temperature: 0.5` 仅在 sync 模式下生效。
- 不会自动重试：引擎不会为本节点执行 `execution.retryOnFail`、`maxTries` 或 `waitBetweenTries`；调用失败会直接从 `error` 输出。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.compose",
  "name": "Compose Content",
  "category": "ai",
  "version": "1.0.0",
  "description": "AI-powered content composition for structured business communications.\n\nThis operator generates polished content from structured parameters, using mode-specific prompts or custom PromptTemplates.\n\n**Operations**\n- **Email:** Composes a professional email from subject, key points, and tone.\n- **Response:** Generates a customer service response from ticket context and resolution details.\n- **Report:** Produces a report section from data points and an optional template structure.\n- **Notification:** Creates a notification message from event details and target audience.\n- **Custom:** Generates content using a PromptTemplate with variable hydration.\n\n**Use Cases**\n- Automating outbound email drafts in workflows.\n- Generating consistent customer service replies.\n- Producing report sections from structured data.\n- Creating templated notifications for operational events.",
  "capabilities": [
    "ai",
    "nlp",
    "content-generation",
    "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 (ideal for fast generations). `stream` consumes tokens via SSE (required for long generations that would exceed the HTTP timeout). 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, in stream mode, the idle timeout between chunks). Default 30000 for sync, 600000 for stream.",
        "minimum": 1000
      },
      "content_type": {
        "type": "string",
        "title": "Content Type",
        "description": "The type of content to generate.",
        "enum": [
          "email",
          "response",
          "report",
          "notification",
          "custom"
        ],
        "default": "email"
      },
      "tone": {
        "type": "string",
        "title": "Tone",
        "description": "The tone to apply to generated content.",
        "enum": [
          "professional",
          "friendly",
          "formal",
          "urgent",
          "empathetic"
        ],
        "default": "professional"
      },
      "language": {
        "type": "string",
        "title": "Language",
        "description": "Output language code (e.g., \"en\", \"es\").",
        "default": "en"
      },
      "template_id": {
        "type": "string",
        "title": "Prompt Template ID",
        "description": "PromptTemplate ID for custom content generation.",
        "displayOptions": {
          "show": {
            "content_type": [
              "custom"
            ]
          }
        }
      },
      "knowledge_resource_id": {
        "type": "string",
        "title": "Knowledge Resource",
        "description": "Optional knowledge resource ID for brand voice or style guidelines."
      },
      "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": {
      "parameters": {
        "type": "object",
        "description": "Key-value pairs for content generation (subject, key_points, ticket, resolution, data, template, event, audience, etc.)."
      },
      "context": {
        "type": "string",
        "description": "Optional background context to inform the content."
      },
      "recipient": {
        "type": "string",
        "description": "Optional recipient name or identifier."
      }
    },
    "required": [
      "parameters"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "content": {
        "type": "string",
        "description": "The generated content body."
      },
      "subject": {
        "type": "string",
        "description": "Generated subject line (email mode)."
      },
      "metadata": {
        "type": "object",
        "description": "Generation metadata (mode, tone, model)."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Composed",
      "is_default": true
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "compose",
    "content",
    "email",
    "nlp"
  ],
  "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 (ideal for fast generations). `stream` consumes tokens via SSE (required for long generations that would exceed the HTTP timeout). 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, in stream mode, the idle timeout between chunks). Default 30000 for sync, 600000 for stream.",
      "minimum": 1000
    },
    "content_type": {
      "type": "string",
      "title": "Content Type",
      "description": "The type of content to generate.",
      "enum": [
        "email",
        "response",
        "report",
        "notification",
        "custom"
      ],
      "default": "email"
    },
    "tone": {
      "type": "string",
      "title": "Tone",
      "description": "The tone to apply to generated content.",
      "enum": [
        "professional",
        "friendly",
        "formal",
        "urgent",
        "empathetic"
      ],
      "default": "professional"
    },
    "language": {
      "type": "string",
      "title": "Language",
      "description": "Output language code (e.g., \"en\", \"es\").",
      "default": "en"
    },
    "template_id": {
      "type": "string",
      "title": "Prompt Template ID",
      "description": "PromptTemplate ID for custom content generation.",
      "displayOptions": {
        "show": {
          "content_type": [
            "custom"
          ]
        }
      }
    },
    "knowledge_resource_id": {
      "type": "string",
      "title": "Knowledge Resource",
      "description": "Optional knowledge resource ID for brand voice or style guidelines."
    },
    "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": {
    "parameters": {
      "type": "object",
      "description": "Key-value pairs for content generation (subject, key_points, ticket, resolution, data, template, event, audience, etc.)."
    },
    "context": {
      "type": "string",
      "description": "Optional background context to inform the content."
    },
    "recipient": {
      "type": "string",
      "description": "Optional recipient name or identifier."
    }
  },
  "required": [
    "parameters"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "content": {
      "type": "string",
      "description": "The generated content body."
    },
    "subject": {
      "type": "string",
      "description": "Generated subject line (email mode)."
    },
    "metadata": {
      "type": "object",
      "description": "Generation metadata (mode, tone, model)."
    }
  }
}
```

### ports

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