# Generate Text

> Leverages Large Language Models (LLMs) to generate natural language content.

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

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

Leverages Large Language Models (LLMs) to generate natural language content.

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.

**Use Cases:**
- **Content Creation:** Drafting emails, blog posts, or reports.
- **Summarization:** Condensing long documents into executive summaries.
- **Transformation:** Rewriting text in a different tone or format.

## 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.
- `temperature` (number, optional): Controls randomness. 0 = Deterministic, 1+ = Creative. Default: `0.7`.

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): Text generated successfully.
- `error`: Provider error or timeout.

## Input contract

- `prompt` (string, required): User input/query.
- `system_prompt` (string, optional): System instructions/persona.
- `history` (array<object>, optional): Chat history for context.

## Output contract

- `content` (string, optional): Generated text.
- `usage` (object, optional): Token usage statistics.

## In expressions

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

- `$("Generate Text").item.json.content` (string) = `"Thanks for reaching out. Your order ships to…"`: Generated text.
- `$("Generate Text").item.json.usage` (object): Token usage statistics. **The worker does not return it: reads as undefined.**
- `$("Generate Text").item.json.raw` (null) = `null` (Not suggested by the editor)
- `$("Generate Text").item.json.port` (string) = `"success"` (Not suggested by the editor)


## How it works

Sends `prompt` (and an optional `system_prompt`) to the model and returns the generated text as `content`.

1. Merges the upstream payload with the node config (config wins) and reads `prompt`, `system_prompt` and `temperature` (default 0.7). Throws `Missing 'prompt' parameter` when `prompt` is empty.
2. Builds the messages: a system message when `system_prompt` is set, then `prompt` as the user message.
3. Calls the model and returns the answer text unchanged as `content`, routing to `success`.

## In a workflow

### Node

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

## Output ports (behaviour in the code)

### `success`

The model answered (an empty answer is still a success).

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

### `error`

`prompt` is missing or the model call failed.

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

## Behaviour in the code

- `model_id`: The schema lists `model_id` as required, but the worker never reads it; the provider comes from `llm_provider_id`. It appears in the example only to satisfy schema validation.
- `prompt, system_prompt`: Not in the config schema (it is in the input contract), but read from the config first and then from the upstream payload.
- `history`: Listed in the input contract but ignored: only `system_prompt` and `prompt` are sent.
- `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 'prompt' parameter` | `error` | No `prompt` in the config or the upstream payload. |
| `[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` 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

- Token usage is not returned, although the output contract lists `usage`.
- 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.
- `raw` is the provider's raw response in sync mode and `null` in stream mode.
- 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 `temperature` 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.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."
  }
]
```
