# Generate Text

> 利用大语言模型（LLM）生成自然语言内容。

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

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

利用大语言模型（LLM）生成自然语言内容。

该算子连接已配置的 LLM 供应商（例如 OpenAI、Anthropic、本地模型），根据给定提示词生成文本。它支持系统指令、温度控制和上下文注入。

**适用场景：**
- **内容创作：** 起草邮件、博客文章或报告。
- **摘要：** 将长文档浓缩为执行摘要。
- **改写：** 以不同语气或格式重写文本。

## 配置

- `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。
- `temperature` (number, 可选): 控制随机性。0 = 确定性，1 及以上 = 更具创造性。 默认值: `0.7`.

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

## 输出端口

- `success` (默认): 文本生成成功。
- `error`: 供应商错误或超时。

## 输入契约

- `prompt` (string, 必填): 用户输入/查询。
- `system_prompt` (string, 可选): 系统指令/角色设定。
- `history` (array<object>, 可选): 作为上下文的对话历史。

## 输出契约

- `content` (string, 可选): 生成的文本。
- `usage` (object, 可选): Token 用量统计。

## 在表达式中

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

- `$("Generate Text").item.json.content` (string) = `"Thanks for reaching out. Your order ships to…"`: 生成的文本。
- `$("Generate Text").item.json.usage` (object): Token 用量统计。 **worker 不返回：读取结果为 undefined.**
- `$("Generate Text").item.json.raw` (null) = `null` (编辑器不提示)
- `$("Generate Text").item.json.port` (string) = `"success"` (编辑器不提示)


## 工作原理

将 `prompt`（及可选的 `system_prompt`）发送给模型，并以 `content` 返回生成的文本。

1. 合并上游载荷与节点配置（以配置为准），读取 `prompt`、`system_prompt` 和 `temperature`（默认 0.7）。`prompt` 为空时抛出 `Missing 'prompt' parameter`。
2. 构建消息：有 `system_prompt` 时先放系统消息，再把 `prompt` 作为用户消息。
3. 调用模型，把回答文本原样作为 `content` 返回，并从 `success` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-draft-answer",
  "label": "Draft answer",
  "operator_slug": "ai.generate",
  "operator_version": "1.0.0",
  "config": {
    "model_id": "wf-llm-provider-xxxx",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "system_prompt": "You are a concise customer support agent.",
    "prompt": "Answer this customer message: {{ $json.body }}",
    "temperature": 0.3,
    "invocation_mode": "stream",
    "timeout_ms": 60000
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "content": "Thanks for reaching out. Your order ships tomorrow and should arrive within three business days.",
    "raw": null,
    "port": "success"
  },
  "port": "success"
}
```

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

### `success`

模型已回答（空回答也算成功）。

```json
{
  "content": "Thanks for reaching out. Your order ships tomorrow and should arrive within three business days.",
  "raw": null,
  "port": "success"
}
```

### `error`

缺少 `prompt` 或模型调用失败。

```json
{
  "error": "Missing 'prompt' parameter"
}
```

## 代码中的行为

- `model_id`: schema 把 `model_id` 列为必填，但 worker 从不读取它；提供方取自 `llm_provider_id`。示例中包含它仅为通过 schema 校验。
- `prompt, system_prompt`: 不在配置 schema 中（位于输入契约中），但会先从配置读取，再从上游载荷读取。
- `history`: 列在输入契约中但被忽略：只发送 `system_prompt` 和 `prompt`。
- `timeout_ms`: 仅限 stream 模式：片段之间的空闲超时，默认 600000。在 sync 模式下不会作用于请求。
- `execution`: 已声明但被忽略：worker 和引擎都不会读取该块中的 `retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`alwaysOutputData` 或 `timeout_ms`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'prompt' parameter` | `error` | 配置和上游载荷中都没有 `prompt`。 |
| `[AiGenerate] 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>`。 |

## 说明与限制

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


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.generate",
  "name": "Generate Text",
  "category": "ai",
  "version": "1.0.0",
  "description": "Leverages Large Language Models (LLMs) to generate natural language content.\n\n  This operator connects to configured LLM providers (e.g., OpenAI, Anthropic, Local) to produce text based on a given prompt. It supports system instructions, temperature control, and context injection.\n\n  **Use Cases:**\n  - **Content Creation:** Drafting emails, blog posts, or reports.\n  - **Summarization:** Condensing long documents into executive summaries.\n  - **Transformation:** Rewriting text in a different tone or format.",
  "capabilities": [
    "llm",
    "generative-ai",
    "nlp",
    "text"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "model_id"
    ],
    "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
      },
      "temperature": {
        "type": "number",
        "default": 0.7,
        "minimum": 0,
        "maximum": 2,
        "title": "Temperature",
        "description": "Controls randomness. 0 = Deterministic, 1+ = Creative."
      },
      "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": {
      "prompt": {
        "type": "string",
        "description": "User input/query."
      },
      "system_prompt": {
        "type": "string",
        "description": "System instructions/persona."
      },
      "history": {
        "type": "array",
        "items": {
          "type": "object"
        },
        "description": "Chat history for context."
      }
    },
    "required": [
      "prompt"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "content": {
        "type": "string",
        "description": "Generated text."
      },
      "usage": {
        "type": "object",
        "description": "Token usage statistics."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Success",
      "is_default": true,
      "description": "Text generated successfully."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Provider error or timeout."
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "llm",
    "gpt",
    "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",
  "required": [
    "model_id"
  ],
  "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
    },
    "temperature": {
      "type": "number",
      "default": 0.7,
      "minimum": 0,
      "maximum": 2,
      "title": "Temperature",
      "description": "Controls randomness. 0 = Deterministic, 1+ = Creative."
    },
    "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": {
    "prompt": {
      "type": "string",
      "description": "User input/query."
    },
    "system_prompt": {
      "type": "string",
      "description": "System instructions/persona."
    },
    "history": {
      "type": "array",
      "items": {
        "type": "object"
      },
      "description": "Chat history for context."
    }
  },
  "required": [
    "prompt"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "content": {
      "type": "string",
      "description": "Generated text."
    },
    "usage": {
      "type": "object",
      "description": "Token usage statistics."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Success",
    "is_default": true,
    "description": "Text generated successfully."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Provider error or timeout."
  }
]
```
