# Translate Text

> Traduce texto entre idiomas con un LLM que tiene en cuenta el dominio y admite glosarios.

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

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

Traduce texto entre idiomas con un LLM que tiene en cuenta el dominio y admite glosarios.

Admite registros formal, neutral e informal en los dominios general, jurídico, médico, técnico, empresarial y académico. Garantiza la coherencia terminológica con glosarios personalizados y conserva el formato original.

**Operaciones:**
- **Traducción:** Traducción precisa entre idiomas, con contexto de tono y dominio.
- **Detección automática:** Detecta automáticamente el idioma de origen cuando no se indica.
- **Aplicación del glosario:** Aplica correspondencias de términos obligatorias para mantener la coherencia.
- **Control de la formalidad:** Ajusta el registro de la salida (formal, neutral, informal).

## 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.
- `source_language` (string, opcional): Déjalo vacío para la detección automática.
- `target_language` (string, obligatorio): Código o nombre del idioma de destino (p. ej., "es", "French").
- `formality` (string, opcional): Nivel de registro de la traducción. Por defecto: `neutral`. Valores permitidos: `formal`, `neutral`, `informal`.
- `domain` (string, opcional): Dominio temático, para una terminología precisa. Por defecto: `general`. Valores permitidos: `general`, `legal`, `medical`, `technical`, `business`, `academic`.
- `glossary` (array<object>, opcional): Correspondencias de términos que se aplican durante la traducción.
- `preserve_formatting` (boolean, opcional): Conserva los párrafos, las listas y los saltos de línea originales. 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): Traducción completada correctamente.
- `error`: La traducción falló.

## Contrato de entrada

- `text` (string, obligatorio): Texto que se traduce.

## Contrato de salida

- `translated_text` (string, opcional): El contenido traducido.
- `source_language` (string, opcional): Idioma de origen (indicado o detectado).
- `target_language` (string, opcional): Idioma de destino.
- `detected_source_language` (string, opcional): Idioma de origen detectado cuando se usó la detección automática.

## En expresiones

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

- `$("Translate Text").item.json.translated_text` (string) = `"Tu pedido saldrá el 3 de diciembre."`: El contenido traducido.
- `$("Translate Text").item.json.source_language` (string) = `"en"`: Idioma de origen (indicado o detectado).
- `$("Translate Text").item.json.target_language` (string) = `"es"`: Idioma de destino.
- `$("Translate Text").item.json.detected_source_language` (string) = `"en"`: Idioma de origen detectado cuando se usó la detección automática.


## Cómo funciona

Traduce `text` a `target_language` con el LLM, respetando el registro, el dominio temático, un glosario y el formato original. Sin `source_language`, el modelo lo detecta.

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` y `target_language`.
4. Construye el prompt con `domain` (cuando no es `general`), `formality` (predeterminado `neutral`), las entradas del glosario que tienen `source` y `target`, y la regla de formato (`preserve_formatting`, predeterminado `true`).
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,2); `translated_text` no puede estar vacío. Añade `detected_source_language` cuando no se indicó `source_language`. Enruta a `success`.

## En un workflow

### Nodo

```json
{
  "node_id": "node-translate",
  "label": "Translate to Spanish",
  "operator_slug": "ai.translate",
  "operator_version": "1.0.0",
  "config": {
    "llm_provider_id": "<llm_provider_id>",
    "source_language": "",
    "target_language": "es",
    "formality": "neutral",
    "domain": "business",
    "glossary": [
      {
        "source": "order",
        "target": "pedido"
      }
    ],
    "preserve_formatting": true
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "success",
  "data": {
    "translated_text": "Tu pedido saldrá el 3 de diciembre.",
    "source_language": "en",
    "target_language": "es",
    "detected_source_language": "en"
  }
}
```

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

### `success`

El modelo devolvió un `translated_text` no vacío. `detected_source_language` solo aparece cuando `source_language` estaba vacío.

```json
{
  "translated_text": "Tu pedido saldrá el 3 de diciembre.",
  "source_language": "en",
  "target_language": "es",
  "detected_source_language": "en"
}
```

### `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": "Missing target_language configuration."
}
```

## 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_language / source_language`: Se escriben en el prompt tal como se indican: sirve un código (`es`) o un nombre (`French`). No se validan.
- `glossary`: Las entradas sin `source` o `target` se descartan. El glosario es una instrucción del prompt; la salida no se comprueba contra él.
- `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 translation.` | `error` | El ítem entrante no tiene `text`. |
| `Missing target_language configuration.` | `error` | `target_language` está vacío. |
| `Model did not return valid translation output.` | `error` | La respuesta no tenía un objeto JSON con un `translated_text` no vacío. |
| `[AiTranslate] 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.translate",
  "name": "Translate Text",
  "category": "ai",
  "version": "1.0.0",
  "description": "Translate text between languages using LLM-powered translation with domain awareness and glossary support.\n\n  Supports formal, neutral, and informal registers across general, legal, medical, technical, business, and academic domains. Enforce term consistency with custom glossaries and preserve original formatting.\n\n  **Operations:**\n  - **Translation:** Accurate cross-language translation with tone and domain context.\n  - **Auto-detection:** Automatically detect source language when not specified.\n  - **Glossary enforcement:** Apply mandatory term mappings for consistency.\n  - **Formality control:** Adjust output register (formal, neutral, informal).",
  "capabilities": [
    "ai",
    "translation",
    "nlp",
    "localization"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "target_language"
    ],
    "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
      },
      "source_language": {
        "type": "string",
        "title": "Source Language",
        "default": "",
        "description": "Leave empty for auto-detection."
      },
      "target_language": {
        "type": "string",
        "title": "Target Language",
        "description": "Target language code or name (e.g., \"es\", \"French\")."
      },
      "formality": {
        "type": "string",
        "title": "Formality",
        "enum": [
          "formal",
          "neutral",
          "informal"
        ],
        "default": "neutral",
        "description": "Register level for the translated output."
      },
      "domain": {
        "type": "string",
        "title": "Domain",
        "enum": [
          "general",
          "legal",
          "medical",
          "technical",
          "business",
          "academic"
        ],
        "default": "general",
        "description": "Subject domain for terminology accuracy."
      },
      "glossary": {
        "type": "array",
        "title": "Glossary",
        "description": "Term mappings to enforce during translation.",
        "items": {
          "type": "object",
          "properties": {
            "source": {
              "type": "string",
              "description": "Source term"
            },
            "target": {
              "type": "string",
              "description": "Required translation"
            }
          }
        }
      },
      "preserve_formatting": {
        "type": "boolean",
        "title": "Preserve Formatting",
        "default": true,
        "description": "Keep original paragraphs, lists, and line breaks."
      },
      "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": {
      "text": {
        "type": "string",
        "description": "Text to translate."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "translated_text": {
        "type": "string",
        "description": "The translated content."
      },
      "source_language": {
        "type": "string",
        "description": "Source language (provided or detected)."
      },
      "target_language": {
        "type": "string",
        "description": "Target language."
      },
      "detected_source_language": {
        "type": "string",
        "description": "Detected source language when auto-detection was used."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Translated",
      "description": "Translation completed successfully.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Translation failed.",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "translation",
    "nlp",
    "localization",
    "i18n"
  ],
  "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": [
    "target_language"
  ],
  "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
    },
    "source_language": {
      "type": "string",
      "title": "Source Language",
      "default": "",
      "description": "Leave empty for auto-detection."
    },
    "target_language": {
      "type": "string",
      "title": "Target Language",
      "description": "Target language code or name (e.g., \"es\", \"French\")."
    },
    "formality": {
      "type": "string",
      "title": "Formality",
      "enum": [
        "formal",
        "neutral",
        "informal"
      ],
      "default": "neutral",
      "description": "Register level for the translated output."
    },
    "domain": {
      "type": "string",
      "title": "Domain",
      "enum": [
        "general",
        "legal",
        "medical",
        "technical",
        "business",
        "academic"
      ],
      "default": "general",
      "description": "Subject domain for terminology accuracy."
    },
    "glossary": {
      "type": "array",
      "title": "Glossary",
      "description": "Term mappings to enforce during translation.",
      "items": {
        "type": "object",
        "properties": {
          "source": {
            "type": "string",
            "description": "Source term"
          },
          "target": {
            "type": "string",
            "description": "Required translation"
          }
        }
      }
    },
    "preserve_formatting": {
      "type": "boolean",
      "title": "Preserve Formatting",
      "default": true,
      "description": "Keep original paragraphs, lists, and line breaks."
    },
    "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": {
    "text": {
      "type": "string",
      "description": "Text to translate."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "translated_text": {
      "type": "string",
      "description": "The translated content."
    },
    "source_language": {
      "type": "string",
      "description": "Source language (provided or detected)."
    },
    "target_language": {
      "type": "string",
      "description": "Target language."
    },
    "detected_source_language": {
      "type": "string",
      "description": "Detected source language when auto-detection was used."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Translated",
    "description": "Translation completed successfully.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Translation failed.",
    "is_default": false,
    "supports_condition": false
  }
]
```
