# Rewrite Text

> Rewrite text with a specific tone, style, or transformation goal.

Source: https://docs.sommatic.ai/en/nodes/ai.rewrite/

- Slug: `ai.rewrite`
- Family: AI
- Version: 1.0.0
- Status: Available
- Execution: async

Rewrite text with a specific tone, style, or transformation goal.

Transform input text while preserving its core meaning. Supports multiple rewriting strategies including tone adjustment, simplification, formalization, expansion, condensation, and fully custom instructions.

**Operations:**
- **Tone:** Rewrite in a target tone (professional, casual, empathetic, assertive, diplomatic).
- **Simplify:** Make text accessible to a general audience.
- **Formalize:** Convert to formal, business-appropriate language.
- **Expand:** Elaborate with more detail and context.
- **Condense:** Remove redundancy while preserving key information.
- **Custom:** Apply free-form rewriting instructions via an expression.

## Configuration

- `llm_provider_id` (string, optional): 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.
- `invocation_mode` (string, optional): Transport for the LLM call. `sync` blocks until the full response arrives. `stream` consumes tokens via SSE (required for long generations). Default `sync`. Default: `sync`. Allowed values: `sync`, `stream`.
- `timeout_ms` (integer, optional): Maximum time to wait for the invocation to complete (or idle timeout between chunks in stream mode). Default 30000 for sync, 600000 for stream.
- `rewrite_mode` (string, required): The rewriting strategy to apply. Default: `tone`. Allowed values: `tone`, `simplify`, `formalize`, `expand`, `condense`, `custom`.
- `target_tone` (string, optional): Target tone for the rewrite (used in tone mode). Allowed values: `professional`, `casual`, `empathetic`, `assertive`, `diplomatic`. Shown when: rewrite_mode = `tone`.
- `target_audience` (string, optional): Optional description of the intended audience (e.g. "executives", "teenagers").
- `custom_instructions` (string, optional, accepts expressions): Free-form rewriting instructions (used in custom mode). Supports expressions. Shown when: rewrite_mode = `custom`.
- `language` (string, optional): Default: `en`.
- `preserve_entities` (boolean, optional): When true, names, dates, numbers, and proper nouns are kept unchanged. Default: `true`.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `success` (default): Rewritten
- `error`: Error

## Input contract

- `text` (string, required): Text to rewrite.
- `context` (string, optional): Optional context to inform the rewrite.

## Output contract

- `rewritten_text` (string, optional): The rewritten version of the input text.
- `changes_summary` (string, optional): One-sentence summary of what was changed.

## In expressions

What a later node can read from this node's output with `$("Rewrite Text").item.json.<path>` (write your node's label instead of `Rewrite Text`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `success`, from the output shown in Ports.

- `$("Rewrite Text").item.json.rewritten_text` (string) = `"Thank you for your patience. Your order will…"`: The rewritten version of the input text.
- `$("Rewrite Text").item.json.changes_summary` (string) = `"Replaced the informal apology with a profess…"`: One-sentence summary of what was changed.


## How it works

Rewrites `text` with the LLM according to a mode (tone, simplify, formalize, expand, condense or custom instructions) and returns the new text with a one-line summary of the changes.

1. Resolves the node config: expressions in config keys are evaluated against the run; the incoming item is used as-is.
2. Merges the incoming item with the resolved config (config keys win) and reads the inputs from the result.
3. Requires `text`. Picks the instruction for `rewrite_mode` (default `tone`; unknown modes use `tone`). In `custom` mode it uses `custom_instructions`.
4. Adds `target_audience`, the entity rule (`preserve_entities`, default `true`), the input `context` and a language line when `language` is not `en`.
5. Calls the LLM through the backend with the `llm_provider_id` record. `invocation_mode: "sync"` (default) waits for the full answer; `"stream"` reads it over SSE and joins the chunks.
6. Parses the JSON answer (temperature 0.4); `rewritten_text` must be a string. Routes to `success`.

## In a workflow

### Node

```json
{
  "node_id": "node-rewrite",
  "label": "Make reply professional",
  "operator_slug": "ai.rewrite",
  "operator_version": "1.0.0",
  "config": {
    "llm_provider_id": "<llm_provider_id>",
    "rewrite_mode": "tone",
    "target_tone": "professional",
    "target_audience": "customers",
    "language": "en",
    "preserve_entities": true
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "success",
  "data": {
    "rewritten_text": "Thank you for your patience. Your order will ship on 3 December.",
    "changes_summary": "Replaced the informal apology with a professional tone."
  }
}
```

## Output ports (behaviour in the code)

### `success`

The model returned a `rewritten_text` string.

```json
{
  "rewritten_text": "Thank you for your patience. Your order will ship on 3 December.",
  "changes_summary": "Replaced the informal apology with a professional tone."
}
```

### `error`

Validation, the LLM call or parsing failed. `data` is `{ error }` (plus `response` when the backend returned a body).

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

## Behaviour in the code

- `llm_provider_id`: Required at runtime although the schema does not mark it as required. It is the id of an LLM provider record; the backend resolves endpoint, deployment and credentials from it.
- `target_tone`: Used only in `tone` mode. When unset the code uses `professional`.
- `custom_instructions`: Used only in `custom` mode; it may be an expression. When empty, the instruction is “Rewrite the text following the user context.”
- `timeout_ms`: `timeout_ms` only takes effect in `stream` mode, as the idle time allowed between chunks (default 600000). In `sync` mode it is logged but the backend request has no timeout.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Missing input text for rewriting.` | `error` | The incoming item has no `text`. |
| `Model did not return valid rewrite output.` | `error` | The answer had no JSON object with a `rewritten_text` string. |
| `[AiRewrite] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | The node has no `llm_provider_id`. Pick an LLM provider in the node config; the legacy `model_id` key is not accepted. |
| `LLM Invocation Error: <backend message>` | `error` | The backend rejected the call (unknown or inactive provider record, provider error, credentials). Check the provider record. |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | The backend could not be reached or returned nothing in `sync` mode. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | In `stream` mode no chunk arrived within `timeout_ms`. |

## Notes and limits

- The model answer is parsed as JSON after removing Markdown code fences; if that fails, the text between the first `{` and the last `}` is parsed.
- Input fields are read from the incoming item (`$json`). A key with the same name in the node config, which may be an expression, takes precedence over the input.
- The worker also returns the provider response as `raw` outside `data`; the engine does not keep it.
- On success the worker returns `port` and `data` without an `ok` field; the engine routes on `port` only.
- `timeout_ms` only takes effect in `stream` mode, as the idle time allowed between chunks (default 600000). In `sync` mode it is logged but the backend request has no timeout.
- In `stream` mode the temperature this node sets is not forwarded to the provider, and `raw` is `null`.
- The engine does not apply `execution.retryOnFail`, `maxTries`, `waitBetweenTries` or `continueOnFail` to this node. Handle failures by wiring the `error` port.


## Contracts (JSON Schema)

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

```json
{
  "slug": "ai.rewrite",
  "name": "Rewrite Text",
  "category": "ai",
  "version": "1.0.0",
  "description": "Rewrite text with a specific tone, style, or transformation goal.\n\n  Transform input text while preserving its core meaning. Supports multiple rewriting strategies including tone adjustment, simplification, formalization, expansion, condensation, and fully custom instructions.\n\n  **Operations:**\n  - **Tone:** Rewrite in a target tone (professional, casual, empathetic, assertive, diplomatic).\n  - **Simplify:** Make text accessible to a general audience.\n  - **Formalize:** Convert to formal, business-appropriate language.\n  - **Expand:** Elaborate with more detail and context.\n  - **Condense:** Remove redundancy while preserving key information.\n  - **Custom:** Apply free-form rewriting instructions via an expression.",
  "capabilities": [
    "ai",
    "nlp",
    "rewriting",
    "tone",
    "transformation"
  ],
  "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
      },
      "rewrite_mode": {
        "type": "string",
        "title": "Rewrite Mode",
        "enum": [
          "tone",
          "simplify",
          "formalize",
          "expand",
          "condense",
          "custom"
        ],
        "default": "tone",
        "description": "The rewriting strategy to apply."
      },
      "target_tone": {
        "type": "string",
        "title": "Target Tone",
        "enum": [
          "professional",
          "casual",
          "empathetic",
          "assertive",
          "diplomatic"
        ],
        "description": "Target tone for the rewrite (used in tone mode).",
        "displayOptions": {
          "show": {
            "rewrite_mode": [
              "tone"
            ]
          }
        }
      },
      "target_audience": {
        "type": "string",
        "title": "Target Audience",
        "description": "Optional description of the intended audience (e.g. \"executives\", \"teenagers\")."
      },
      "custom_instructions": {
        "type": "string",
        "title": "Custom Instructions",
        "format": "expression",
        "description": "Free-form rewriting instructions (used in custom mode). Supports expressions.",
        "displayOptions": {
          "show": {
            "rewrite_mode": [
              "custom"
            ]
          }
        }
      },
      "language": {
        "type": "string",
        "title": "Language",
        "default": "en"
      },
      "preserve_entities": {
        "type": "boolean",
        "title": "Preserve Entities",
        "default": true,
        "description": "When true, names, dates, numbers, and proper nouns are kept unchanged."
      },
      "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": [
      "rewrite_mode"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string",
        "description": "Text to rewrite."
      },
      "context": {
        "type": "string",
        "description": "Optional context to inform the rewrite."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "rewritten_text": {
        "type": "string",
        "description": "The rewritten version of the input text."
      },
      "changes_summary": {
        "type": "string",
        "description": "One-sentence summary of what was changed."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Rewritten",
      "is_default": true
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "nlp",
    "rewrite",
    "tone",
    "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
    },
    "rewrite_mode": {
      "type": "string",
      "title": "Rewrite Mode",
      "enum": [
        "tone",
        "simplify",
        "formalize",
        "expand",
        "condense",
        "custom"
      ],
      "default": "tone",
      "description": "The rewriting strategy to apply."
    },
    "target_tone": {
      "type": "string",
      "title": "Target Tone",
      "enum": [
        "professional",
        "casual",
        "empathetic",
        "assertive",
        "diplomatic"
      ],
      "description": "Target tone for the rewrite (used in tone mode).",
      "displayOptions": {
        "show": {
          "rewrite_mode": [
            "tone"
          ]
        }
      }
    },
    "target_audience": {
      "type": "string",
      "title": "Target Audience",
      "description": "Optional description of the intended audience (e.g. \"executives\", \"teenagers\")."
    },
    "custom_instructions": {
      "type": "string",
      "title": "Custom Instructions",
      "format": "expression",
      "description": "Free-form rewriting instructions (used in custom mode). Supports expressions.",
      "displayOptions": {
        "show": {
          "rewrite_mode": [
            "custom"
          ]
        }
      }
    },
    "language": {
      "type": "string",
      "title": "Language",
      "default": "en"
    },
    "preserve_entities": {
      "type": "boolean",
      "title": "Preserve Entities",
      "default": true,
      "description": "When true, names, dates, numbers, and proper nouns are kept unchanged."
    },
    "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": [
    "rewrite_mode"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string",
      "description": "Text to rewrite."
    },
    "context": {
      "type": "string",
      "description": "Optional context to inform the rewrite."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "rewritten_text": {
      "type": "string",
      "description": "The rewritten version of the input text."
    },
    "changes_summary": {
      "type": "string",
      "description": "One-sentence summary of what was changed."
    }
  }
}
```

### ports

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