# Generate Embeddings

> 将文本转换为高维向量嵌入。

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

- 标识: `ai.embed`
- 类别: AI
- 版本: 1.0.0
- 状态: 部分可用. 执行成功时该 worker 不返回端口，引擎会沿 `out` 继续，而该节点并未声明 `out`：从其成功端口引出的连线永远不会触发。修复前，请勿在其成功路径后串接其他节点。
- 执行方式: async

将文本转换为高维向量嵌入。

嵌入（Embedding）以数字列表（向量）的形式表达文本的语义。这些向量是语义搜索、聚类和 RAG（检索增强生成）工作流的基础。

**适用场景：**
- **语义搜索：** 为写入向量数据库准备数据。
- **聚类：** 将相似的支持工单归组。
- **分类：** 为下游机器学习模型提供输入。

## 配置

- `llm_provider_id` (string, 必填): 为嵌入配置的 `LlmProviderModel` 记录的 `id`（例如 `wf-llm-provider-*`）。编排器将调用委托给后端端点 `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke`（operation: embedding）。嵌入只支持 sync，不适用流式。在 webapp 的 `/cognitive-assets/llm-provider/*` 中管理。
- `timeout_ms` (integer, 可选): 等待嵌入调用完成的最长时间。默认 30000。

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

## 输出端口

- `success` (默认): 已生成嵌入。
- `error`: Error

## 输入契约

- `input` (string | array, 必填): 要嵌入的文本字符串或字符串数组。

## 输出契约

- `embeddings` (array<number>, 可选): 表示输入文本的向量。

## 在表达式中

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

- `$("Generate Embeddings").item.json.embeddings` (array) = `[…] (4)`: 表示输入文本的向量。
- `$("Generate Embeddings").item.json.raw` (null) = `null` (编辑器不提示)


## 工作原理

通过具备 embedding 能力的提供方记录，将一段文本转换为向量。部分可用：成功时从未声明的 `out` 端口输出。

1. 从上游载荷取文本：先取 `$json.input`，否则取 `$json.text`。两者都没有时抛出 `Missing 'input'`。
2. 通过后端使用 `llm_provider_id` 发送一次 embedding 请求。
3. 返回不带端口的 `{ embeddings, raw }`，因此引擎将其路由到 `out`。`embeddings` 是单个向量（数字数组）；后端回答中没有向量时为 `null`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-embed-chunk",
  "label": "Embed chunk",
  "operator_slug": "ai.embed",
  "operator_version": "1.0.0",
  "config": {
    "llm_provider_id": "wf-llm-provider-xxxx",
    "timeout_ms": 30000
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "embeddings": [
      0.0123,
      -0.0456,
      0.0789,
      0.0012
    ],
    "raw": null
  },
  "port": "out"
}
```

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

### `success`

已声明但从不发出。成功时引擎走 `out`；从 `success` 画出的连线永远不会触发。下列数据为 `out` 携带的内容。

```json
{
  "embeddings": [
    0.0123,
    -0.0456,
    0.0789,
    0.0012
  ],
  "raw": null
}
```

### `error`

未找到文本、输入不是字符串或 embedding 调用失败。

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

## 代码中的行为

- `input`: 无法在节点上设置：运行时会用上游载荷替换任何已配置的 `input`。请调整上一个节点的输出，使 `$json.input` 或 `$json.text` 存放该字符串，例如使用 `data.transform`。
- `timeout_ms`: 会传给客户端，但不会作用于 HTTP 请求；以平台默认请求超时为准。
- `execution`: 已声明但被忽略：worker 和引擎都不会读取该块中的 `retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`alwaysOutputData` 或 `timeout_ms`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'input'` | `error` | 上游载荷中既没有 `input` 也没有 `text`。节点上配置的值不会被使用（见配置说明）。 |
| `LlmInvocationClientService.invokeEmbedding: input (string) is required.` | `error` | 文本不是字符串，例如字符串数组。每次运行只支持一个字符串；列表请使用 `flow.split`。 |
| `[AiEmbed] 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` 为空或不是字符串。请选择具备 embedding 能力的提供方记录。 |
| `LLM Invocation Error (embedding): <backend message>` | `error` | 后端拒绝了调用（提供方记录不存在、提供方不支持 embedding、提供方报错）。HTTP 失败时显示 `LLM Invocation Error (embedding): empty response from backend (<transport error>)`。 |

## 说明与限制

- 已知缺陷：成功路径不返回端口，引擎因此使用节点未声明的 `out`。在修复之前，不要在其成功路径之后串接节点。
- 输入契约允许数组，但实际只支持单个字符串；输出是一个向量，而非向量列表。
- embedding 始终为同步调用，`invocation_mode` 不适用。后端返回时，`raw` 为提供方的原始响应。
- 不会自动重试：引擎不会为本节点执行 `execution.retryOnFail`、`maxTries` 或 `waitBetweenTries`；调用失败会直接从 `error` 输出。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "ai.embed",
  "name": "Generate Embeddings",
  "category": "ai",
  "version": "1.0.0",
  "description": "Converts text into high-dimensional vector embeddings.\n\n  Embeddings capture the semantic meaning of text as a list of numbers (vectors). These vectors are essential for semantic search, clustering, and RAG (Retrieval Augmented Generation) workflows.\n\n  **Use Cases:**\n  - **Semantic Search:** Preparing data for vector database storage.\n  - **Clustering:** Grouping similar support tickets.\n  - **Classification:** Feeding downstream ML models.",
  "capabilities": [
    "llm",
    "embeddings",
    "vector",
    "nlp"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "llm_provider_id"
    ],
    "properties": {
      "llm_provider_id": {
        "type": "string",
        "title": "LLM Provider (Embedding)",
        "description": "The `id` of a `LlmProviderModel` record configured for embeddings (e.g. `wf-llm-provider-*`). The orchestrator delegates to the backend endpoint `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` (operation: embedding). Embedding is sync-only — streaming does not apply. Managed in the webapp at `/cognitive-assets/llm-provider/*`.",
        "x-ui-widget": "llm-provider-picker",
        "x-llm-provider-capabilities": [
          "embedding"
        ]
      },
      "timeout_ms": {
        "type": "integer",
        "title": "Timeout (ms)",
        "description": "Maximum time to wait for the embedding call to complete. Default 30000.",
        "minimum": 1000
      },
      "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": {
      "input": {
        "type": [
          "string",
          "array"
        ],
        "description": "Text string or array of strings to embed."
      }
    },
    "required": [
      "input"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "embeddings": {
        "type": "array",
        "items": {
          "type": "number"
        },
        "description": "Vector(s) representing the input text."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Success",
      "is_default": true,
      "description": "Embeddings generated."
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "vector",
    "embedding"
  ],
  "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": [
    "llm_provider_id"
  ],
  "properties": {
    "llm_provider_id": {
      "type": "string",
      "title": "LLM Provider (Embedding)",
      "description": "The `id` of a `LlmProviderModel` record configured for embeddings (e.g. `wf-llm-provider-*`). The orchestrator delegates to the backend endpoint `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` (operation: embedding). Embedding is sync-only — streaming does not apply. Managed in the webapp at `/cognitive-assets/llm-provider/*`.",
      "x-ui-widget": "llm-provider-picker",
      "x-llm-provider-capabilities": [
        "embedding"
      ]
    },
    "timeout_ms": {
      "type": "integer",
      "title": "Timeout (ms)",
      "description": "Maximum time to wait for the embedding call to complete. Default 30000.",
      "minimum": 1000
    },
    "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": {
    "input": {
      "type": [
        "string",
        "array"
      ],
      "description": "Text string or array of strings to embed."
    }
  },
  "required": [
    "input"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "embeddings": {
      "type": "array",
      "items": {
        "type": "number"
      },
      "description": "Vector(s) representing the input text."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Success",
    "is_default": true,
    "description": "Embeddings generated."
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
