# Rewrite Text

> Reescribe un texto con un tono, un estilo o un objetivo de transformación concretos.

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

- Slug: `ai.rewrite`
- Familia: IA
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Reescribe un texto con un tono, un estilo o un objetivo de transformación concretos.

Transforma el texto de entrada conservando su significado esencial. Admite varias estrategias de reescritura: ajuste del tono, simplificación, formalización, ampliación, condensación e instrucciones totalmente personalizadas.

**Operaciones:**
- **Tone:** Reescribe con un tono objetivo (profesional, informal, empático, asertivo, diplomático).
- **Simplify:** Hace el texto accesible para un público general.
- **Formalize:** Lo convierte a un lenguaje formal, apropiado para el entorno empresarial.
- **Expand:** Lo amplía con más detalle y contexto.
- **Condense:** Elimina redundancias y conserva la información clave.
- **Custom:** Aplica instrucciones de reescritura libres mediante una expresión.

## Configuración

- `llm_provider_id` (string, opcional): El `id` de un registro `LlmProviderModel` (p. ej. `wf-llm-provider-*`). El orquestador delega en el backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` en modo sync, o `POST /chat/conversation/execute/stream-ephemeral` (SSE) en modo stream. El backend resuelve endpoint + api-key + deployment a partir del registro y enruta al adaptador correspondiente.
- `invocation_mode` (string, opcional): Transporte de la llamada al LLM. `sync` se bloquea hasta recibir la respuesta completa. `stream` consume los tokens mediante SSE (necesario para generaciones largas). Predeterminado: `sync`. Por defecto: `sync`. Valores permitidos: `sync`, `stream`.
- `timeout_ms` (integer, opcional): Tiempo máximo de espera para que termine la invocación (o tiempo máximo de inactividad entre fragmentos en modo stream). Predeterminado: 30000 en sync, 600000 en stream.
- `rewrite_mode` (string, obligatorio): La estrategia de reescritura que se aplica. Por defecto: `tone`. Valores permitidos: `tone`, `simplify`, `formalize`, `expand`, `condense`, `custom`.
- `target_tone` (string, opcional): Tono objetivo de la reescritura (se usa en el modo tone). Valores permitidos: `professional`, `casual`, `empathetic`, `assertive`, `diplomatic`. Se muestra cuando: rewrite_mode = `tone`.
- `target_audience` (string, opcional): Descripción opcional del público destinatario (p. ej. "directivos", "adolescentes").
- `custom_instructions` (string, opcional, acepta expresiones): Instrucciones de reescritura libres (se usan en el modo custom). Admite expresiones. Se muestra cuando: rewrite_mode = `custom`.
- `language` (string, opcional): Por defecto: `en`.
- `preserve_entities` (boolean, opcional): Si es true, los nombres, fechas, números y nombres propios se mantienen sin cambios. Por defecto: `true`.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `success` (por defecto): Rewritten
- `error`: Error

## Contrato de entrada

- `text` (string, obligatorio): Texto que se reescribe.
- `context` (string, opcional): Contexto opcional para orientar la reescritura.

## Contrato de salida

- `rewritten_text` (string, opcional): La versión reescrita del texto de entrada.
- `changes_summary` (string, opcional): Resumen de una oración de lo que se cambió.

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Rewrite Text").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Rewrite Text`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `success`, según la salida que muestra Puertos.

- `$("Rewrite Text").item.json.rewritten_text` (string) = `"Thank you for your patience. Your order will…"`: La versión reescrita del texto de entrada.
- `$("Rewrite Text").item.json.changes_summary` (string) = `"Replaced the informal apology with a profess…"`: Resumen de una oración de lo que se cambió.


## Cómo funciona

Reescribe `text` con el LLM según un modo (tono, simplificar, formalizar, ampliar, condensar o instrucciones propias) y devuelve el texto nuevo con un resumen de una línea de los cambios.

1. Resuelve la configuración del nodo: las expresiones de las claves de configuración se evalúan contra la ejecución; el ítem entrante se usa tal cual.
2. Combina el ítem entrante con la configuración resuelta (las claves de configuración tienen prioridad) y lee las entradas del resultado.
3. Exige `text`. Elige la instrucción de `rewrite_mode` (predeterminado `tone`; los modos desconocidos usan `tone`). En modo `custom` usa `custom_instructions`.
4. Añade `target_audience`, la regla de entidades (`preserve_entities`, predeterminado `true`), el `context` de entrada y una línea de idioma cuando `language` no es `en`.
5. Llama al LLM a través del backend con el registro `llm_provider_id`. `invocation_mode: "sync"` (predeterminado) espera la respuesta completa; `"stream"` la lee por SSE y une los fragmentos.
6. Interpreta la respuesta JSON (temperatura 0,4); `rewritten_text` debe ser un texto. Enruta a `success`.

## En un workflow

### Nodo

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

## Puertos de salida (comportamiento en el código)

### `success`

El modelo devolvió un texto en `rewritten_text`.

```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`

Falló la validación, la llamada al LLM o la interpretación. `data` es `{ error }` (más `response` cuando el backend devolvió un cuerpo).

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

## Comportamiento en el código

- `llm_provider_id`: Es obligatorio en ejecución aunque el esquema no lo marque como requerido. Es el id de un registro de proveedor LLM; el backend resuelve a partir de él el endpoint, el despliegue y las credenciales.
- `target_tone`: Solo se usa en modo `tone`. Si no se define, el código usa `professional`.
- `custom_instructions`: Solo se usa en modo `custom`; puede ser una expresión. Si está vacío, la instrucción es «Rewrite the text following the user context.»
- `timeout_ms`: `timeout_ms` solo tiene efecto en modo `stream`, como el tiempo de inactividad permitido entre fragmentos (predeterminado 600000). En modo `sync` se registra en el log, pero la petición al backend no tiene tiempo límite.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Missing input text for rewriting.` | `error` | El ítem entrante no tiene `text`. |
| `Model did not return valid rewrite output.` | `error` | La respuesta no tenía un objeto JSON con un texto en `rewritten_text`. |
| `[AiRewrite] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | El nodo no tiene `llm_provider_id`. Elige un proveedor LLM en la configuración del nodo; la clave antigua `model_id` no se acepta. |
| `LLM Invocation Error: <backend message>` | `error` | El backend rechazó la llamada (registro de proveedor desconocido o inactivo, error del proveedor, credenciales). Revisa el registro del proveedor. |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | No se pudo contactar con el backend o no devolvió nada en modo `sync`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | En modo `stream` no llegó ningún fragmento dentro de `timeout_ms`. |

## Notas y límites

- La respuesta del modelo se interpreta como JSON tras quitar los bloques de código Markdown; si falla, se interpreta el texto entre la primera `{` y la última `}`.
- Los campos de entrada se leen del ítem entrante (`$json`). Una clave con el mismo nombre en la configuración del nodo, que puede ser una expresión, tiene prioridad sobre la entrada.
- El worker también devuelve la respuesta del proveedor como `raw` fuera de `data`; el motor no la conserva.
- En caso de éxito el worker devuelve `port` y `data` sin el campo `ok`; el motor enruta solo por `port`.
- `timeout_ms` solo tiene efecto en modo `stream`, como el tiempo de inactividad permitido entre fragmentos (predeterminado 600000). En modo `sync` se registra en el log, pero la petición al backend no tiene tiempo límite.
- En modo `stream` la temperatura que fija este nodo no se envía al proveedor, y `raw` es `null`.
- El motor no aplica `execution.retryOnFail`, `maxTries`, `waitBetweenTries` ni `continueOnFail` a este nodo. Gestiona los fallos conectando el puerto `error`.


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