# Generate Text

> Usa modelos de lenguaje de gran tamaño (LLM) para generar contenido en lenguaje natural.

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

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

Usa modelos de lenguaje de gran tamaño (LLM) para generar contenido en lenguaje natural.

Este operador se conecta a los proveedores de LLM configurados (p. ej., OpenAI, Anthropic, locales) para producir texto a partir de un prompt. Admite instrucciones de sistema, control de la temperatura e inyección de contexto.

**Casos de uso:**
- **Creación de contenido:** Redactar correos, artículos de blog o reportes.
- **Resumen:** Condensar documentos extensos en resúmenes ejecutivos.
- **Transformación:** Reescribir un texto con otro tono o formato.

## 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.
- `temperature` (number, opcional): Controla la aleatoriedad. 0 = determinista, 1 o más = creativo. Por defecto: `0.7`.

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): Texto generado correctamente.
- `error`: Error del proveedor o tiempo agotado.

## Contrato de entrada

- `prompt` (string, obligatorio): Entrada o consulta del usuario.
- `system_prompt` (string, opcional): Instrucciones de sistema o personalidad.
- `history` (array<object>, opcional): Historial del chat como contexto.

## Contrato de salida

- `content` (string, opcional): Texto generado.
- `usage` (object, opcional): Estadísticas de uso de tokens.

## En expresiones

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

- `$("Generate Text").item.json.content` (string) = `"Thanks for reaching out. Your order ships to…"`: Texto generado.
- `$("Generate Text").item.json.usage` (object): Estadísticas de uso de tokens. **El worker no la devuelve: se lee como undefined.**
- `$("Generate Text").item.json.raw` (null) = `null` (El editor no la sugiere)
- `$("Generate Text").item.json.port` (string) = `"success"` (El editor no la sugiere)


## Cómo funciona

Envía `prompt` (y un `system_prompt` opcional) al modelo y devuelve el texto generado en `content`.

1. Combina el payload anterior con la configuración del nodo (gana la configuración) y lee `prompt`, `system_prompt` y `temperature` (por defecto 0,7). Lanza `Missing 'prompt' parameter` si `prompt` está vacío.
2. Arma los mensajes: un mensaje de sistema si hay `system_prompt` y luego `prompt` como mensaje de usuario.
3. Llama al modelo y devuelve el texto de la respuesta sin cambios en `content`, saliendo por `success`.

## En un workflow

### Nodo

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

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

### `success`

El modelo respondió (una respuesta vacía también cuenta como éxito).

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

### `error`

Falta `prompt` o falló la llamada al modelo.

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

## Comportamiento en el código

- `model_id`: El esquema marca `model_id` como obligatorio, pero el worker nunca lo lee; el proveedor sale de `llm_provider_id`. Aparece en el ejemplo solo para cumplir la validación del esquema.
- `prompt, system_prompt`: No está en el esquema de configuración (está en el contrato de entrada), pero se lee primero de la configuración y luego del payload anterior.
- `history`: Aparece en el contrato de entrada pero se ignora: solo se envían `system_prompt` y `prompt`.
- `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 'prompt' parameter` | `error` | No hay `prompt` en la configuración ni en el payload anterior. |
| `[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` 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

- No se devuelve el uso de tokens, aunque el contrato de salida menciona `usage`.
- 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.
- `raw` es la respuesta cruda del proveedor en modo sync y `null` en modo stream.
- 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 `temperature` 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.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."
  }
]
```
