# Retrieve Context (RAG)

> 编排 RAG（检索增强生成）所需上下文的检索。

Source: https://docs.sommatic.ai/zh/nodes/ai.rag.retrieve/

- 标识: `ai.rag.retrieve`
- 类别: AI
- 版本: 1.0.0
- 状态: 实验性. 该 slug 无法解析到已注册的 worker（实现位于 `ai.rag.worker.js`，注册名为 `AiRagWorker`），因此节点无法启动。该实现本身只是用 `query` 和 `context` 填充提示词模板：不做嵌入、不做向量搜索，也不做重排序。
- 执行方式: async

编排 RAG（检索增强生成）所需上下文的检索。

这一高层算子将“嵌入 -> 向量搜索 -> 重排序”流水线抽象为单个步骤。它接收文本查询，在内部（或按配置）完成嵌入，搜索向量库，并返回最匹配的文本分块。

**适用场景：**
- “一键式”RAG 上下文检索。
- 隐藏向量处理的复杂性，简化工作流图。

## 配置

- `knowledge_base_id` (string, 必填): 要搜索的受管理知识库的 ID。
- `top_k` (number, 可选): 默认值: `3`.

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

## 输出端口

- `success` (默认): Retrieved
- `empty`: No Data
- `error`: Error

## 输入契约

- `query` (string, 必填): 用户的问题/查询。

## 输出契约

- `context` (array<string>, 可选): 检索到的文本分块。
- `sources` (array<object>, 可选): 来源的元数据（页码、文件名）。

## 在表达式中

后续节点可通过 `$("Retrieve Context (RAG)").item.json.<路径>` 读取此节点输出中的内容，即工作流编辑器在 Previous Nodes 中提示的路径（输出契约）。

- `$("Retrieve Context (RAG)").item.json.context` (array): 检索到的文本分块。
- `$("Retrieve Context (RAG)").item.json.sources` (array): 来源的元数据（页码、文件名）。


## 工作原理

实验性且无法运行：该 slug 无法解析为任何已注册的 worker，因此节点在启动前即失败。其背后的代码只会填充提示词模板，并不执行任何检索。

1. 运行器查找为该 slug 注册的 worker，未找到后回退到名称 `AiRagRetrieveWorker`，而该名称同样未注册。
2. 创建时抛出 `Worker not found: AiRagRetrieveWorker`；引擎将该步骤记录为 `error` 并使本次运行失败。

## 在工作流中

### 节点

```json
{
  "node_id": "node-rag-retrieve",
  "label": "Retrieve context",
  "operator_slug": "ai.rag.retrieve",
  "operator_version": "1.0.0",
  "config": {
    "knowledge_base_id": "<knowledge_base_id>",
    "top_k": 3
  }
}
```

### Envelope

```json
{
  "ok": false,
  "port": "error",
  "data": {
    "error": "Worker not found: AiRagRetrieveWorker"
  }
}
```

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

### `success`

永远不会触发。

### `empty`

永远不会触发。

### `error`

每次运行都会在创建 worker 时失败。错误以异常抛出，因此从 `error` 引出的连线收不到它；只有外层的 `flow.try` 能捕获。

```json
{
  "error": "Worker not found: AiRagRetrieveWorker"
}
```

## 代码中的行为

- `knowledge_base_id / top_k`: 已声明但从未读取。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Worker not found: AiRagRetrieveWorker` | `error` | 以异常抛出，而不是作为信封返回：引擎会将本次运行标记为失败，除非节点位于 `flow.try` 作用域内，此时错误会进入其 catch 分支。 |

## 说明与限制

- 尚未实现：查询向量化、知识库检索、排序以及返回 `context`/`sources`。本应承载它的 worker 文件只会替换模板中的 `{{context}}` 和 `{{query}}`。
- 不存在成功的信封：示例展示的是引擎记录的失败。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.rag.retrieve",
  "name": "Retrieve Context (RAG)",
  "category": "ai",
  "version": "1.0.0",
  "description": "Orchestrates the retrieval of context for RAG (Retrieval-Augmented Generation).\n\n  This high-level operator abstracts the Embedding -> Vector Search -> Reranking pipeline into a single step. It takes a text query, handles the embedding internally (or via configuration), searches the vector store, and returns the best matching text chunks.\n  \n  **Use Cases:**\n  - \"One-click\" RAG context retrieval.\n  - Simplifying the graph by hiding vector complexity.",
  "capabilities": [
    "rag",
    "retrieval",
    "search",
    "abstraction"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "knowledge_base_id"
    ],
    "properties": {
      "knowledge_base_id": {
        "type": "string",
        "title": "Knowledge Base",
        "description": "ID of the managed Knowledge Base to search."
      },
      "top_k": {
        "type": "number",
        "default": 3
      },
      "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": {
      "query": {
        "type": "string",
        "description": "The user question/query."
      }
    },
    "required": [
      "query"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "context": {
        "type": "array",
        "items": {
          "type": "string"
        },
        "description": "Retrieved text chunks."
      },
      "sources": {
        "type": "array",
        "items": {
          "type": "object"
        },
        "description": "Metadata about sources (page numbers, filenames)."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Retrieved",
      "is_default": true
    },
    {
      "port_id": "empty",
      "label": "No Data"
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "rag",
    "retrieval",
    "search"
  ],
  "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": [
    "knowledge_base_id"
  ],
  "properties": {
    "knowledge_base_id": {
      "type": "string",
      "title": "Knowledge Base",
      "description": "ID of the managed Knowledge Base to search."
    },
    "top_k": {
      "type": "number",
      "default": 3
    },
    "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": {
    "query": {
      "type": "string",
      "description": "The user question/query."
    }
  },
  "required": [
    "query"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "context": {
      "type": "array",
      "items": {
        "type": "string"
      },
      "description": "Retrieved text chunks."
    },
    "sources": {
      "type": "array",
      "items": {
        "type": "object"
      },
      "description": "Metadata about sources (page numbers, filenames)."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Retrieved",
    "is_default": true
  },
  {
    "port_id": "empty",
    "label": "No Data"
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
