# Translate Text

> 使用 LLM 驱动的翻译在不同语言之间转换文本，具备领域感知并支持术语表。

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

- 标识: `ai.translate`
- 类别: AI
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

使用 LLM 驱动的翻译在不同语言之间转换文本，具备领域感知并支持术语表。

支持正式、中性和非正式三种语体，覆盖通用、法律、医疗、技术、商务和学术等领域。可通过自定义术语表保证术语一致，并保留原始格式。

**操作：**
- **翻译：** 结合语气和领域上下文进行准确的跨语言翻译。
- **自动检测：** 未指定源语言时自动检测。
- **术语表约束：** 应用强制的术语映射以保持一致性。
- **语体控制：** 调整输出语体（正式、中性、非正式）。

## 配置

- `llm_provider_id` (string, 可选): `LlmProviderModel` 记录的 `id`（例如 `wf-llm-provider-*`）。编排器将调用委托给后端：sync 模式调用 `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke`，stream 模式调用 `POST /chat/conversation/execute/stream-ephemeral`（SSE）。后端根据该记录解析 endpoint + api-key + deployment，并路由到相应的适配器。
- `invocation_mode` (string, 可选): LLM 调用的传输方式。`sync` 会阻塞直到收到完整响应。`stream` 通过 SSE 逐步接收 token（长文本生成必须使用）。默认为 `sync`。 默认值: `sync`. 可选值: `sync`, `stream`.
- `timeout_ms` (integer, 可选): 等待调用完成的最长时间（stream 模式下为分块之间的空闲超时）。sync 默认 30000，stream 默认 600000。
- `source_language` (string, 可选): 留空则自动检测。
- `target_language` (string, 必填): 目标语言代码或名称（例如“es”“French”）。
- `formality` (string, 可选): 译文的语体级别。 默认值: `neutral`. 可选值: `formal`, `neutral`, `informal`.
- `domain` (string, 可选): 用于保证术语准确性的学科领域。 默认值: `general`. 可选值: `general`, `legal`, `medical`, `technical`, `business`, `academic`.
- `glossary` (array<object>, 可选): 翻译时强制使用的术语映射。
- `preserve_formatting` (boolean, 可选): 保留原文的段落、列表和换行。 默认值: `true`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `success` (默认): 翻译成功完成。
- `error`: 翻译失败。

## 输入契约

- `text` (string, 必填): 要翻译的文本。

## 输出契约

- `translated_text` (string, 可选): 翻译后的内容。
- `source_language` (string, 可选): 源语言（指定的或检测到的）。
- `target_language` (string, 可选): 目标语言。
- `detected_source_language` (string, 可选): 使用自动检测时检测出的源语言。

## 在表达式中

后续节点可通过 `$("Translate Text").item.json.<路径>` 读取此节点输出中的内容（请把 `Translate Text` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `success` 返回的路径，依据“端口”一节所示的输出。

- `$("Translate Text").item.json.translated_text` (string) = `"Tu pedido saldrá el 3 de diciembre."`: 翻译后的内容。
- `$("Translate Text").item.json.source_language` (string) = `"en"`: 源语言（指定的或检测到的）。
- `$("Translate Text").item.json.target_language` (string) = `"es"`: 目标语言。
- `$("Translate Text").item.json.detected_source_language` (string) = `"en"`: 使用自动检测时检测出的源语言。


## 工作原理

使用 LLM 将 `text` 翻译为 `target_language`，遵循语体、专业领域、术语表和原有格式。未提供 `source_language` 时由模型检测。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 将传入条目与解析后的配置合并（配置键优先），并从合并结果中读取输入。
3. 必须提供 `text` 和 `target_language`。
4. 使用 `domain`（不为 `general` 时）、`formality`（默认 `neutral`）、同时含 `source` 和 `target` 的术语表条目以及格式规则（`preserve_formatting`，默认 `true`）构建提示词。
5. 通过后端使用 `llm_provider_id` 记录调用 LLM。`invocation_mode: "sync"`（默认）等待完整响应；`"stream"` 通过 SSE 读取并拼接分块。
6. 解析 JSON 响应（温度 0.2），`translated_text` 不能为空。未提供 `source_language` 时添加 `detected_source_language`。路由到 `success`。

## 在工作流中

### 节点

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

## 输出端口 (代码中的行为)

### `success`

模型返回了非空的 `translated_text`。仅当 `source_language` 为空时才包含 `detected_source_language`。

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

### `error`

校验、LLM 调用或解析失败。`data` 为 `{ error }`（若后端返回了响应体，还包含 `response`）。

```json
{
  "error": "Missing target_language configuration."
}
```

## 代码中的行为

- `llm_provider_id`: 虽然 schema 未将其标为必填，但运行时必须提供。它是 LLM 提供方记录的 id；后端据此解析端点、部署和凭据。
- `target_language / source_language`: 按原样写入提示词：代码（`es`）或名称（`French`）均可。不做校验。
- `glossary`: 缺少 `source` 或 `target` 的条目会被丢弃。术语表只是提示词中的指令；不会据此校验输出。
- `timeout_ms`: `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing input text for translation.` | `error` | 传入条目中没有 `text`。 |
| `Missing target_language configuration.` | `error` | `target_language` 为空。 |
| `Model did not return valid translation output.` | `error` | 响应中没有含非空 `translated_text` 的 JSON 对象。 |
| `[AiTranslate] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | 节点缺少 `llm_provider_id`。请在节点配置中选择一个 LLM 提供方；旧的 `model_id` 键不再被接受。 |
| `LLM Invocation Error: <backend message>` | `error` | 后端拒绝了调用（提供方记录不存在或未启用、提供方错误、凭据问题）。请检查提供方记录。 |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | 在 `sync` 模式下无法连接后端，或后端未返回任何内容。 |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | 在 `stream` 模式下，`timeout_ms` 内没有收到任何分块。 |

## 说明与限制

- 模型响应在去除 Markdown 代码块标记后按 JSON 解析；若失败，则解析第一个 `{` 与最后一个 `}` 之间的文本。
- 输入字段从传入条目（`$json`）读取。节点配置中同名的键（可以是表达式）优先于输入。
- Worker 还会在 `data` 之外以 `raw` 返回提供方的原始响应；引擎不会保留它。
- 成功时 worker 返回 `port` 和 `data`，不含 `ok` 字段；引擎只依据 `port` 路由。
- `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。
- 在 `stream` 模式下，此节点设置的温度不会转发给提供方，且 `raw` 为 `null`。
- 引擎不会对此节点应用 `execution.retryOnFail`、`maxTries`、`waitBetweenTries` 或 `continueOnFail`。请通过连接 `error` 端口处理失败。


## 契约（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
  }
]
```
