# Retrieve Context (RAG)

> Orquesta la recuperación de contexto para RAG (Retrieval-Augmented Generation).

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

- Slug: `ai.rag.retrieve`
- Familia: IA
- Versión: 1.0.0
- Estado: Experimental. El slug no se resuelve a ningún worker registrado (la implementación está en `ai.rag.worker.js`, registrada como `AiRagWorker`), así que el nodo no se puede crear. La implementación en sí solo completa una plantilla de prompt con `query` y `context`: no genera embeddings, no hace búsqueda vectorial ni reordenamiento.
- Ejecución: async

Orquesta la recuperación de contexto para RAG (Retrieval-Augmented Generation).

Este operador de alto nivel abstrae en un solo paso el pipeline de embedding -> búsqueda vectorial -> reordenamiento. Recibe una consulta de texto, genera el embedding internamente (o según la configuración), busca en el almacén vectorial y devuelve los fragmentos de texto que mejor coinciden.

**Casos de uso:**
- Recuperación de contexto para RAG "en un clic".
- Simplificar el grafo ocultando la complejidad vectorial.

## Configuración

- `knowledge_base_id` (string, obligatorio): ID de la base de conocimiento gestionada en la que se busca.
- `top_k` (number, opcional): Por defecto: `3`.

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): Retrieved
- `empty`: No Data
- `error`: Error

## Contrato de entrada

- `query` (string, obligatorio): La pregunta o consulta del usuario.

## Contrato de salida

- `context` (array<string>, opcional): Fragmentos de texto recuperados.
- `sources` (array<object>, opcional): Metadatos de las fuentes (números de página, nombres de archivo).

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Retrieve Context (RAG)").item.json.<ruta>`, tal como lo sugiere el editor de workflows en Previous Nodes (el contrato de salida).

- `$("Retrieve Context (RAG)").item.json.context` (array): Fragmentos de texto recuperados.
- `$("Retrieve Context (RAG)").item.json.sources` (array): Metadatos de las fuentes (números de página, nombres de archivo).


## Cómo funciona

Experimental y no ejecutable: el slug no se resuelve a ningún worker registrado, así que el nodo falla antes de empezar. El código que hay detrás solo rellena una plantilla de prompt; no recupera nada.

1. El runner busca un worker registrado para este slug, no encuentra ninguno y recurre al nombre `AiRagRetrieveWorker`, que tampoco está registrado.
2. Al crearlo se lanza `Worker not found: AiRagRetrieveWorker`; el motor registra el paso en `error` y hace fallar la ejecución.

## En un workflow

### Nodo

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

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

### `success`

Nunca se activa.

### `empty`

Nunca se activa.

### `error`

Cada ejecución falla al crear el worker. El error se lanza, así que las aristas desde `error` no lo reciben; solo lo captura un `flow.try` que lo envuelva.

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

## Comportamiento en el código

- `knowledge_base_id / top_k`: Declaradas pero nunca leídas.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Worker not found: AiRagRetrieveWorker` | `error` | Se lanza como excepción, no se devuelve como sobre: el motor marca la ejecución como fallida, salvo que el nodo esté dentro de un ámbito `flow.try`, que recibe el error en su rama catch. |

## Notas y límites

- No implementado: generar el embedding de la consulta, buscar en una base de conocimiento, ordenar y devolver `context`/`sources`. El archivo del worker que la atendería solo sustituye `{{context}}` y `{{query}}` en una plantilla.
- No existe un sobre de éxito: el ejemplo muestra el fallo que registra el motor.


## Contratos (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"
  }
]
```
