# Compose Content

> Redacción de contenido con IA para comunicaciones de negocio estructuradas.

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

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

Redacción de contenido con IA para comunicaciones de negocio estructuradas.

Este operador genera contenido pulido a partir de parámetros estructurados, con prompts específicos de cada modo o con PromptTemplates personalizadas.

**Operaciones**
- **Email:** Redacta un correo profesional a partir del asunto, los puntos clave y el tono.
- **Response:** Genera una respuesta de servicio al cliente a partir del contexto del ticket y de los detalles de la solución.
- **Report:** Produce una sección de reporte a partir de datos y de una estructura de plantilla opcional.
- **Notification:** Crea un mensaje de notificación a partir de los detalles del evento y del público destinatario.
- **Custom:** Genera contenido con una PromptTemplate y la sustitución de sus variables.

**Casos de uso**
- Automatizar borradores de correos salientes en los workflows.
- Generar respuestas de servicio al cliente coherentes.
- Producir secciones de reportes a partir de datos estructurados.
- Crear notificaciones con plantilla para eventos operativos.

## 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 (ideal para generaciones rápidas). `stream` consume los tokens mediante SSE (necesario para generaciones largas que superarían el tiempo límite de HTTP). 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, en modo stream, tiempo máximo de inactividad entre fragmentos). Predeterminado: 30000 en sync, 600000 en stream.
- `content_type` (string, opcional): El tipo de contenido que se genera. Por defecto: `email`. Valores permitidos: `email`, `response`, `report`, `notification`, `custom`.
- `tone` (string, opcional): El tono que se aplica al contenido generado. Por defecto: `professional`. Valores permitidos: `professional`, `friendly`, `formal`, `urgent`, `empathetic`.
- `language` (string, opcional): Código del idioma de salida (p. ej., "en", "es"). Por defecto: `en`.
- `template_id` (string, opcional): ID de la PromptTemplate para la generación de contenido personalizado. Se muestra cuando: content_type = `custom`.
- `knowledge_resource_id` (string, opcional): ID opcional de un recurso de conocimiento con la voz de marca o la guía de estilo.

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): Composed
- `error`: Error

## Contrato de entrada

- `parameters` (object, obligatorio): Pares clave-valor para la generación de contenido (subject, key_points, ticket, resolution, data, template, event, audience, etc.).
- `context` (string, opcional): Contexto de fondo opcional para orientar el contenido.
- `recipient` (string, opcional): Nombre o identificador opcional del destinatario.

## Contrato de salida

- `content` (string, opcional): El cuerpo del contenido generado.
- `subject` (string, opcional): Asunto generado (modo email).
- `metadata` (object, opcional): Metadatos de la generación (modo, tono, modelo).

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Compose Content").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Compose Content`). **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.

- `$("Compose Content").item.json.content` (string) = `"Hello Ana,\n\nYour refund for order 4521 was…"`: El cuerpo del contenido generado.
- `$("Compose Content").item.json.subject` (string) = `"Your refund was approved"`: Asunto generado (modo email).
- `$("Compose Content").item.json.metadata` (object) = `{…}`: Metadatos de la generación (modo, tono, modelo).
- `$("Compose Content").item.json.metadata.content_type` (string) = `"email"` (El editor no la sugiere)
- `$("Compose Content").item.json.metadata.tone` (string) = `"friendly"` (El editor no la sugiere)
- `$("Compose Content").item.json.metadata.llm_provider_id` (string) = `"wf-llm-provider-xxxx"` (El editor no la sugiere)
- `$("Compose Content").item.json.metadata.title` (null) = `null` (El editor no la sugiere)
- `$("Compose Content").item.json.raw` (null) = `null` (El editor no la sugiere)
- `$("Compose Content").item.json.port` (string) = `"success"` (El editor no la sugiere)


## Cómo funciona

Redacta con el modelo un correo, una respuesta a cliente, una sección de informe o una notificación a partir de `parameters`, o llena una plantilla de prompt guardada en modo `custom`; opcionalmente añade pautas de voz de marca.

1. Combina el payload anterior con la configuración del nodo (gana la configuración); lanza `Missing 'parameters'` si `parameters` no es un objeto.
2. Construye el prompt de sistema. Para `email`, `response`, `report` y `notification` inserta campos fijos de `parameters` (`subject`, `key_points`, `ticket`, `resolution`, `data`, `template`, `event`, `audience`), el `tone` y un formato de salida JSON; un tipo desconocido usa el prompt de email.
3. Para `custom`, obtiene del backend la plantilla de prompt `template_id` y reemplaza cada `{{ key }}` por el valor correspondiente de `parameters`; la plantilla pasa a ser todo el prompt de sistema.
4. Con `knowledge_resource_id`, añade `## Brand Voice / Style Guidelines` y el contenido del recurso; si la carga falla, solo se registra en el log.
5. El mensaje de usuario incluye `Recipient:`, `Context:` y cada otra clave de `parameters` como `clave: valor`; llama al modelo a `temperature: 0.5`.
6. Interpreta la respuesta como JSON para `content`, `subject` y `title`; si no es JSON, toda la respuesta pasa a `content` y `subject` es `null`. Sale por `success`.

## En un workflow

### Nodo

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

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

### `success`

El modelo respondió. Un JSON inválido no es un error: la respuesta cruda se usa como `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`

Falta `parameters`, no se puede cargar la plantilla o falló la llamada al modelo.

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

## Comportamiento en el código

- `parameters, context, recipient`: No están en el esquema de configuración (están en el contrato de entrada), pero se leen primero de la configuración y luego del payload anterior.
- `tone, language`: Se ignoran en modo `custom`, donde la plantilla es todo el prompt de sistema. `tone` tampoco se escribe en el prompt de `report`.
- `knowledge_resource_id`: Añade tal cual el `content` del recurso (o `body`, o `text`). Si `content` es un objeto, se inserta como `[object Object]`; guarda las pautas de forma que el valor sea texto plano.
- `timeout_ms`: Solo en modo stream: timeout de inactividad entre fragmentos, por defecto 600000. En modo sync no se aplica a la petición.
- `execution`: Declarado pero ignorado: ni el worker ni el motor leen `retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail`, `alwaysOutputData` ni `timeout_ms` de este bloque.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Missing 'parameters'` | `error` | `parameters` no existe o no es un objeto, incluso en modo `custom`. |
| `Missing 'template_id' for custom content type` | `error` | `content_type` es `custom` y `template_id` está vacío. |
| `Prompt Template <template_id> not found` | `error` | El backend no devolvió plantilla para ese id. Una plantilla sin `template_body`, `content` ni `template` falla con `Template <template_id> has no content`; un error HTTP aparece como `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` está vacío o no es un texto. Elige un registro de proveedor LLM con capacidad de chat. |
| `LLM Invocation Error: <backend message>` | `error` | El backend rechazó la llamada: registro de proveedor inexistente o inactivo, error del proveedor, cuota o filtro de contenido. Revisa el registro de proveedor y los logs del backend. |
| `LLM Invocation Error: empty response from backend (<transport error>)` | `error` | Modo sync: falló la llamada HTTP al backend (error de red, estado distinto de 2xx o timeout). Los prompts largos suelen agotar el timeout de la petición; cambia a `invocation_mode: "stream"`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | Modo stream: no llegó ningún fragmento dentro de `timeout_ms`. Si la petición de stream falla, el mensaje es `RemoteApiService.stream: HTTP <status> — <body>`. |

## Notas y límites

- La petición de la plantilla de prompt en modo `custom` no tiene timeout propio.
- El worker devuelve sus campos en el primer nivel en lugar de dentro de `data`, así que el motor guarda todo el valor devuelto como salida del nodo: `port` y `raw` aparecen en `$json` junto a los campos del resultado.
- La llamada al modelo pasa por el backend de Sommatic AI, que resuelve el registro de proveedor indicado en `llm_provider_id` (endpoint, credenciales, despliegue); el orquestador nunca guarda llaves del proveedor. `invocation_mode: "sync"` (por defecto) espera la respuesta completa; `"stream"` la lee como eventos SSE y une los fragmentos.
- `timeout_ms` solo tiene efecto en modo stream, como tiempo máximo de inactividad entre fragmentos (por defecto 600000). En modo sync el valor se registra en el log, pero no se aplica a la petición HTTP, así que rige el timeout por defecto de la plataforma.
- En modo stream el endpoint del backend no aplica los parámetros de muestreo, así que la `temperature: 0.5` fija solo tiene efecto en modo sync.
- Sin reintentos automáticos: el motor no aplica `execution.retryOnFail`, `maxTries` ni `waitBetweenTries` en este nodo; una llamada fallida sale directamente por `error`.


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