# Enrich Data

> Enriquece registros agregando campos calculados, inferidos o estandarizados con un LLM.

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

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

Enriquece registros agregando campos calculados, inferidos o estandarizados con un LLM.

Elige un modo de enriquecimiento y define los campos de salida que necesitas. El operador lee el registro de entrada, aplica la estrategia elegida y devuelve el registro enriquecido con una puntuación de confianza por campo.

**Operaciones:**
- **Categorize:** Agrega etiquetas de categoría a un registro según su contenido.
- **Standardize:** Normaliza nombres, direcciones, fechas y teléfonos a formatos coherentes.
- **Infer:** Completa los valores que faltan razonando a partir del contexto disponible.
- **Augment:** Agrega campos calculados, como la antigüedad a partir del cargo o el sector a partir del nombre de la empresa.

## 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.
- `enrichment_mode` (string, obligatorio): Estrategia que se aplica: categorizar, estandarizar, inferir valores faltantes o ampliar con campos calculados. Por defecto: `categorize`. Valores permitidos: `categorize`, `standardize`, `infer`, `augment`.
- `input_fields` (array<string>, opcional): Qué campos del registro de entrada se leen.
- `output_fields` (array<object>, obligatorio): Campos que se agregan o calculan en el registro enriquecido.
- `knowledge_resource_id` (string, opcional): Opcional: datos de referencia o tablas de consulta para el enriquecimiento.
- `language` (string, opcional): Idioma de los datos de entrada. Por defecto: `en`.

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): Todos los campos solicitados se agregaron correctamente.
- `partial`: Algunos campos solicitados no se pudieron calcular.
- `error`: El enriquecimiento falló.

## Contrato de entrada

- `record` (object, obligatorio): El registro de datos que se enriquece.
- `context` (string, opcional): Contexto opcional para mejorar la precisión del enriquecimiento.

## Contrato de salida

- `enriched_record` (object, opcional): Registro original combinado con los campos nuevos.
- `added_fields` (array, opcional): Lista de los nombres de campo agregados correctamente.
- `confidence_per_field` (object, opcional): Puntuación de confianza (0-1) de cada campo agregado.

## En expresiones

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

- `$("Enrich Data").item.json.enriched_record` (object) = `{…}`: Registro original combinado con los campos nuevos.
- `$("Enrich Data").item.json.added_fields` (array) = `[…] (2)`: Lista de los nombres de campo agregados correctamente.
- `$("Enrich Data").item.json.confidence_per_field` (object) = `{…}`: Puntuación de confianza (0-1) de cada campo agregado.
- `$("Enrich Data").item.json.enriched_record.company` (string) = `"Northwind Logistics"` (El editor no la sugiere)
- `$("Enrich Data").item.json.enriched_record.title` (string) = `"Head of Operations"` (El editor no la sugiere)
- `$("Enrich Data").item.json.enriched_record.industry` (string) = `"Logistics"` (El editor no la sugiere)
- `$("Enrich Data").item.json.enriched_record.seniority` (string) = `"Director"` (El editor no la sugiere)
- `$("Enrich Data").item.json.confidence_per_field.industry` (number) = `0.93` (El editor no la sugiere)
- `$("Enrich Data").item.json.confidence_per_field.seniority` (number) = `0.81` (El editor no la sugiere)


## Cómo funciona

Añade con el modelo los `output_fields` pedidos a un `record` JSON (categorize, standardize, infer o augment) y enruta a `success` si se añadieron todos los campos o a `partial` si no.

1. Combina el payload anterior con la configuración del nodo (gana la configuración) y lee `record`, que debe ser un objeto; `output_fields` no puede estar vacío.
2. Si `input_fields` está definido, conserva solo esas claves del registro; si no, envía el registro completo, con formato legible, como mensaje de usuario.
3. Con `knowledge_resource_id`, añade el `content` del recurso como JSON bajo `Reference data for lookup:`; si la carga falla, solo se registra en el log.
4. Envía una instrucción del modo que lista cada campo de salida como `- name (type): description` y un formato JSON estricto; `temperature: 0.1`.
5. Interpreta la respuesta como JSON; debe traer `enriched_record`. Sale por `success` si todos los nombres de `output_fields` están en `added_fields`; si no, por `partial`.

## En un workflow

### Nodo

```json
{
  "node_id": "node-enrich-lead",
  "label": "Enrich lead",
  "operator_slug": "ai.enrich",
  "operator_version": "1.0.0",
  "config": {
    "record": "{{ $json.lead }}",
    "enrichment_mode": "augment",
    "input_fields": [
      "company",
      "title"
    ],
    "output_fields": [
      {
        "name": "industry",
        "type": "string",
        "description": "Industry of the company."
      },
      {
        "name": "seniority",
        "type": "string",
        "description": "Seniority implied by the job title."
      }
    ],
    "language": "en",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "invocation_mode": "sync"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "enriched_record": {
      "company": "Northwind Logistics",
      "title": "Head of Operations",
      "industry": "Logistics",
      "seniority": "Director"
    },
    "added_fields": [
      "industry",
      "seniority"
    ],
    "confidence_per_field": {
      "industry": 0.93,
      "seniority": 0.81
    }
  },
  "port": "success"
}
```

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

### `success`

El modelo informó todos los campos pedidos en `added_fields`.

```json
{
  "enriched_record": {
    "company": "Northwind Logistics",
    "title": "Head of Operations",
    "industry": "Logistics",
    "seniority": "Director"
  },
  "added_fields": [
    "industry",
    "seniority"
  ],
  "confidence_per_field": {
    "industry": 0.93,
    "seniority": 0.81
  }
}
```

### `partial`

Falta al menos uno de los campos pedidos en `added_fields`.

```json
{
  "enriched_record": {
    "company": "Northwind Logistics",
    "title": "Head of Operations",
    "industry": "Logistics"
  },
  "added_fields": [
    "industry"
  ],
  "confidence_per_field": {
    "industry": 0.93
  }
}
```

### `error`

Falta el registro o los campos de salida, falló la llamada al modelo o la respuesta no traía `enriched_record`.

```json
{
  "error": "Model did not return valid enrichment output."
}
```

## Comportamiento en el código

- `record`: No está en el esquema de configuración (está en el contrato de entrada), pero se lee primero de la configuración y luego del payload anterior.
- `enrichment_mode`: Un valor desconocido usa la instrucción de `categorize`.
- `input_fields`: Filtra lo que ve el modelo, pero al modelo se le pide devolver los campos originales en `enriched_record`; el código no vuelve a unir los campos que filtraste.
- `timeout_ms`: Solo en modo stream: timeout de inactividad entre fragmentos, por defecto 600000. En modo sync no se aplica a la petición.
- `execution`: Declarado pero ignorado: ni el worker ni el motor leen `retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail`, `alwaysOutputData` ni `timeout_ms` de este bloque.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Missing or invalid input record.` | `error` | `record` no existe o no es un objeto. |
| `At least one output field must be defined.` | `error` | `output_fields` está vacío. |
| `Model did not return valid enrichment output.` | `error` | La respuesta no era JSON o no traía `enriched_record`. |
| `[AiEnrich] 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` está vacío o no es un texto. Elige un registro de proveedor LLM con capacidad de chat. |
| `LLM Invocation Error: <backend message>` | `error` | El backend rechazó la llamada: registro de proveedor inexistente o inactivo, error del proveedor, cuota o filtro de contenido. Revisa el registro de proveedor y los logs del backend. |
| `LLM Invocation Error: empty response from backend (<transport error>)` | `error` | Modo sync: falló la llamada HTTP al backend (error de red, estado distinto de 2xx o timeout). Los prompts largos suelen agotar el timeout de la petición; cambia a `invocation_mode: "stream"`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | Modo stream: no llegó ningún fragmento dentro de `timeout_ms`. Si la petición de stream falla, el mensaje es `RemoteApiService.stream: HTTP <status> — <body>`. |

## Notas y límites

- `enriched_record` es lo que devuelva el modelo; el código no lo une con el registro de entrada ni valida tipos de campo. La entrada `context` se ignora.
- El worker devuelve `raw` junto a `data`; el motor solo conserva `data` como salida del nodo, así que `raw` no está disponible aguas abajo.
- La llamada al modelo pasa por el backend de Sommatic AI, que resuelve el registro de proveedor indicado en `llm_provider_id` (endpoint, credenciales, despliegue); el orquestador nunca guarda llaves del proveedor. `invocation_mode: "sync"` (por defecto) espera la respuesta completa; `"stream"` la lee como eventos SSE y une los fragmentos.
- `timeout_ms` solo tiene efecto en modo stream, como tiempo máximo de inactividad entre fragmentos (por defecto 600000). En modo sync el valor se registra en el log, pero no se aplica a la petición HTTP, así que rige el timeout por defecto de la plataforma.
- En modo stream el endpoint del backend no aplica los parámetros de muestreo, así que la `temperature: 0.1` fija solo tiene efecto en modo sync.
- El recurso de conocimiento se lee del backend en cada ejecución (timeout de 10 s). Un recurso cuyo estado no es `active` se usa igual, con una advertencia en el log.
- Sin reintentos automáticos: el motor no aplica `execution.retryOnFail`, `maxTries` ni `waitBetweenTries` en este nodo; una llamada fallida sale directamente por `error`.


## Contratos (JSON Schema)

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

```json
{
  "slug": "ai.enrich",
  "name": "Enrich Data",
  "category": "ai",
  "version": "1.0.0",
  "description": "Enrich records by adding computed, inferred, or standardized fields using an LLM.\n\n  Select an enrichment mode and define the output fields you need. The operator reads the input record, applies the chosen strategy, and returns the enriched record with confidence scores per field.\n\n  **Operations:**\n  - **Categorize:** Add category tags to a record based on its content.\n  - **Standardize:** Normalize names, addresses, dates, and phone numbers to consistent formats.\n  - **Infer:** Fill missing field values by reasoning from available context.\n  - **Augment:** Add computed fields such as seniority from job title or industry from company name.",
  "capabilities": [
    "ai",
    "enrichment",
    "data-quality",
    "augmentation"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "enrichment_mode",
      "output_fields"
    ],
    "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
      },
      "enrichment_mode": {
        "type": "string",
        "title": "Enrichment Mode",
        "enum": [
          "categorize",
          "standardize",
          "infer",
          "augment"
        ],
        "default": "categorize",
        "description": "Strategy to apply: categorize, standardize, infer missing values, or augment with computed fields."
      },
      "input_fields": {
        "type": "array",
        "title": "Input Fields",
        "items": {
          "type": "string"
        },
        "description": "Which fields from the input record to read."
      },
      "output_fields": {
        "type": "array",
        "title": "Output Fields",
        "description": "Fields to add or compute in the enriched record.",
        "items": {
          "type": "object",
          "properties": {
            "name": {
              "type": "string",
              "description": "Field name to produce."
            },
            "description": {
              "type": "string",
              "description": "What this field represents."
            },
            "type": {
              "type": "string",
              "description": "Expected data type (string, number, boolean, array)."
            }
          }
        }
      },
      "knowledge_resource_id": {
        "type": "string",
        "title": "Knowledge Resource",
        "description": "Optional: reference data or lookup tables for enrichment.",
        "ui_widget": "knowledge_resource_picker"
      },
      "language": {
        "type": "string",
        "title": "Language",
        "default": "en",
        "description": "Language of the input data."
      },
      "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": {
      "record": {
        "type": "object",
        "description": "The data record to enrich."
      },
      "context": {
        "type": "string",
        "description": "Optional context to improve enrichment accuracy."
      }
    },
    "required": [
      "record"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "enriched_record": {
        "type": "object",
        "description": "Original record merged with new fields."
      },
      "added_fields": {
        "type": "array",
        "description": "List of field names successfully added."
      },
      "confidence_per_field": {
        "type": "object",
        "description": "Confidence score (0-1) for each added field."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Enriched",
      "description": "All requested fields were added successfully.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "partial",
      "label": "Partial",
      "description": "Some requested fields could not be computed.",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Enrichment failed.",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "enrichment",
    "data-quality",
    "augmentation"
  ],
  "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": [
    "enrichment_mode",
    "output_fields"
  ],
  "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
    },
    "enrichment_mode": {
      "type": "string",
      "title": "Enrichment Mode",
      "enum": [
        "categorize",
        "standardize",
        "infer",
        "augment"
      ],
      "default": "categorize",
      "description": "Strategy to apply: categorize, standardize, infer missing values, or augment with computed fields."
    },
    "input_fields": {
      "type": "array",
      "title": "Input Fields",
      "items": {
        "type": "string"
      },
      "description": "Which fields from the input record to read."
    },
    "output_fields": {
      "type": "array",
      "title": "Output Fields",
      "description": "Fields to add or compute in the enriched record.",
      "items": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "description": "Field name to produce."
          },
          "description": {
            "type": "string",
            "description": "What this field represents."
          },
          "type": {
            "type": "string",
            "description": "Expected data type (string, number, boolean, array)."
          }
        }
      }
    },
    "knowledge_resource_id": {
      "type": "string",
      "title": "Knowledge Resource",
      "description": "Optional: reference data or lookup tables for enrichment.",
      "ui_widget": "knowledge_resource_picker"
    },
    "language": {
      "type": "string",
      "title": "Language",
      "default": "en",
      "description": "Language of the input data."
    },
    "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": {
    "record": {
      "type": "object",
      "description": "The data record to enrich."
    },
    "context": {
      "type": "string",
      "description": "Optional context to improve enrichment accuracy."
    }
  },
  "required": [
    "record"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "enriched_record": {
      "type": "object",
      "description": "Original record merged with new fields."
    },
    "added_fields": {
      "type": "array",
      "description": "List of field names successfully added."
    },
    "confidence_per_field": {
      "type": "object",
      "description": "Confidence score (0-1) for each added field."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Enriched",
    "description": "All requested fields were added successfully.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "partial",
    "label": "Partial",
    "description": "Some requested fields could not be computed.",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Enrichment failed.",
    "is_default": false,
    "supports_condition": false
  }
]
```
