# Compose Content

> AI-powered content composition for structured business communications.

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

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

AI-powered content composition for structured business communications.

This operator generates polished content from structured parameters, using mode-specific prompts or custom PromptTemplates.

**Operations**
- **Email:** Composes a professional email from subject, key points, and tone.
- **Response:** Generates a customer service response from ticket context and resolution details.
- **Report:** Produces a report section from data points and an optional template structure.
- **Notification:** Creates a notification message from event details and target audience.
- **Custom:** Generates content using a PromptTemplate with variable hydration.

**Use Cases**
- Automating outbound email drafts in workflows.
- Generating consistent customer service replies.
- Producing report sections from structured data.
- Creating templated notifications for operational events.

## 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 (ideal for fast generations). `stream` consumes tokens via SSE (required for long generations that would exceed the HTTP timeout). Default `sync`. Default: `sync`. Allowed values: `sync`, `stream`.
- `timeout_ms` (integer, optional): 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.
- `content_type` (string, optional): The type of content to generate. Default: `email`. Allowed values: `email`, `response`, `report`, `notification`, `custom`.
- `tone` (string, optional): The tone to apply to generated content. Default: `professional`. Allowed values: `professional`, `friendly`, `formal`, `urgent`, `empathetic`.
- `language` (string, optional): Output language code (e.g., "en", "es"). Default: `en`.
- `template_id` (string, optional): PromptTemplate ID for custom content generation. Shown when: content_type = `custom`.
- `knowledge_resource_id` (string, optional): Optional knowledge resource ID for brand voice or style guidelines.

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

## Input contract

- `parameters` (object, required): Key-value pairs for content generation (subject, key_points, ticket, resolution, data, template, event, audience, etc.).
- `context` (string, optional): Optional background context to inform the content.
- `recipient` (string, optional): Optional recipient name or identifier.

## Output contract

- `content` (string, optional): The generated content body.
- `subject` (string, optional): Generated subject line (email mode).
- `metadata` (object, optional): Generation metadata (mode, tone, model).

## In expressions

What a later node can read from this node's output with `$("Compose Content").item.json.<path>` (write your node's label instead of `Compose Content`). **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.

- `$("Compose Content").item.json.content` (string) = `"Hello Ana,\n\nYour refund for order 4521 was…"`: The generated content body.
- `$("Compose Content").item.json.subject` (string) = `"Your refund was approved"`: Generated subject line (email mode).
- `$("Compose Content").item.json.metadata` (object) = `{…}`: Generation metadata (mode, tone, model).
- `$("Compose Content").item.json.metadata.content_type` (string) = `"email"` (Not suggested by the editor)
- `$("Compose Content").item.json.metadata.tone` (string) = `"friendly"` (Not suggested by the editor)
- `$("Compose Content").item.json.metadata.llm_provider_id` (string) = `"wf-llm-provider-xxxx"` (Not suggested by the editor)
- `$("Compose Content").item.json.metadata.title` (null) = `null` (Not suggested by the editor)
- `$("Compose Content").item.json.raw` (null) = `null` (Not suggested by the editor)
- `$("Compose Content").item.json.port` (string) = `"success"` (Not suggested by the editor)


## How it works

Writes an email, customer response, report section or notification with the model from `parameters`, or fills a stored prompt template in `custom` mode; optionally appends brand-voice guidelines.

1. Merges the upstream payload with the node config (config wins); throws `Missing 'parameters'` when `parameters` is not an object.
2. Builds the system prompt. For `email`, `response`, `report` and `notification` it inserts fixed fields of `parameters` (`subject`, `key_points`, `ticket`, `resolution`, `data`, `template`, `event`, `audience`), the `tone` and a JSON output format; an unknown type uses the email prompt.
3. For `custom`, fetches the prompt template `template_id` from the backend and replaces each `{{ key }}` with the matching `parameters` value; the template becomes the whole system prompt.
4. With `knowledge_resource_id`, appends `## Brand Voice / Style Guidelines` and the resource content; a failed fetch is only logged.
5. The user message holds `Recipient:`, `Context:` and every other `parameters` key as `key: value`; calls the model at `temperature: 0.5`.
6. Parses the answer as JSON for `content`, `subject` and `title`; if it is not JSON, the whole answer becomes `content` and `subject` is `null`. Routes to `success`.

## In a workflow

### Node

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

## Output ports (behaviour in the code)

### `success`

The model answered. Invalid JSON is not an error: the raw answer is used as `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` is missing, the template cannot be loaded, or the model call failed.

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

## Behaviour in the code

- `parameters, context, recipient`: Not in the config schema (they are in the input contract), but read from the config first and then from the upstream payload.
- `tone, language`: Ignored in `custom` mode, where the template is the whole system prompt. `tone` is not written into the `report` prompt either.
- `knowledge_resource_id`: Appends the resource's `content` (or `body`, or `text`) as-is. When `content` is an object, it is inserted as `[object Object]`; store the guidelines so that the value is plain text.
- `timeout_ms`: Stream mode only: idle timeout between chunks, default 600000. In sync mode it is not applied to the request.
- `execution`: Declared but ignored: neither the worker nor the engine reads `retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail`, `alwaysOutputData` or `timeout_ms` from this block.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Missing 'parameters'` | `error` | `parameters` is absent or not an object, even for `custom` mode. |
| `Missing 'template_id' for custom content type` | `error` | `content_type` is `custom` and `template_id` is empty. |
| `Prompt Template <template_id> not found` | `error` | The backend returned no template for that id. A template without `template_body`, `content` or `template` fails with `Template <template_id> has no content`; an HTTP error surfaces as `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` is empty or not a string. Pick an LLM provider record with chat capability. |
| `LLM Invocation Error: <backend message>` | `error` | The backend rejected the call: unknown or inactive provider record, provider error, quota or content filter. Check the provider record and the backend logs. |
| `LLM Invocation Error: empty response from backend (<transport error>)` | `error` | Sync mode: the HTTP call to the backend failed (network error, non-2xx status or timeout). Long prompts often hit the request timeout; switch to `invocation_mode: "stream"`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | Stream mode: no chunk arrived within `timeout_ms`. A failed stream request shows `RemoteApiService.stream: HTTP <status> — <body>` instead. |

## Notes and limits

- The prompt-template request in `custom` mode has no timeout of its own.
- The worker returns its fields at the top level instead of inside `data`, so the engine stores the whole return value as the node output: `port` and `raw` appear in `$json` next to the result fields.
- The model call goes through the Sommatic AI backend, which resolves the provider record named by `llm_provider_id` (endpoint, credentials, deployment); the orchestrator never holds provider keys. `invocation_mode: "sync"` (default) waits for the full answer; `"stream"` reads it as server-sent events and joins the chunks.
- `timeout_ms` only takes effect in stream mode, as the idle time allowed between chunks (default 600000). In sync mode the value is logged but not applied to the HTTP request, so the platform's default request timeout governs.
- In stream mode the backend endpoint does not apply sampling settings, so the fixed `temperature: 0.5` only takes effect in sync mode.
- No automatic retries: the engine does not honour `execution.retryOnFail`, `maxTries` or `waitBetweenTries` for this node; a failed call goes straight to `error`.


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