# Extract Relations

> Extrae de un texto las relaciones semánticas entre entidades como tripletas sujeto-predicado-objeto.

Source: https://docs.sommatic.ai/es/nodes/ai.relation.extract/

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

Extrae de un texto las relaciones semánticas entre entidades como tripletas sujeto-predicado-objeto.

Produce una salida lista para un grafo de conocimiento que identifica quién hizo qué a quién, cuándo y dónde. Opcionalmente, filtra por tipos de relación concretos e incluye los fragmentos de texto que sirven de evidencia.

**Casos de uso:**
- **Grafos de conocimiento:** Construir grafos estructurados a partir de documentos.
- **Cumplimiento:** Extraer las obligaciones contractuales y las partes.
- **Inteligencia:** Mapear las relaciones entre personas, organizaciones y eventos.

## 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.
- `relation_types` (array<string>, opcional): Filtra por tipos de relación concretos (p. ej., works_for, located_in). Déjalo vacío para todos.
- `include_evidence` (boolean, opcional): Incluye el fragmento del texto de origen que respalda cada relación extraída. Por defecto: `true`.
- `language` (string, opcional): Idioma del texto 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): Se extrajo al menos una relación.
- `error`: La extracción falló.

## Contrato de entrada

- `text` (string, obligatorio): Texto del que se extraen las relaciones.

## Contrato de salida

- `relations` (array, opcional): Relaciones extraídas como tripletas sujeto-predicado-objeto, con su confianza.
- `entities` (array, opcional): Entidades únicas mencionadas en las relaciones.
- `relation_count` (number, opcional): Número total de relaciones extraídas.

## En expresiones

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

- `$("Extract Relations").item.json.relations` (array) = `[…] (2)`: Relaciones extraídas como tripletas sujeto-predicado-objeto, con su confianza.
- `$("Extract Relations").item.json.entities` (array) = `[…] (3)`: Entidades únicas mencionadas en las relaciones.
- `$("Extract Relations").item.json.relation_count` (number) = `2`: Número total de relaciones extraídas.


## Cómo funciona

Extrae relaciones sujeto–predicado–objeto de `text` con el LLM y las devuelve con su confianza, fragmentos de evidencia opcionales y la lista de entidades implicadas.

1. Resuelve la configuración del nodo: las expresiones de las claves de configuración se evalúan contra la ejecución; el ítem entrante se usa tal cual.
2. Combina el ítem entrante con la configuración resuelta (las claves de configuración tienen prioridad) y lee las entradas del resultado.
3. Exige `text`. Construye el prompt con `relation_types` (vacío = todos los tipos), `include_evidence` (predeterminado `true`) y `language` (predeterminado `en`).
4. Llama al LLM a través del backend con el registro `llm_provider_id`. `invocation_mode: "sync"` (predeterminado) espera la respuesta completa; `"stream"` la lee por SSE y une los fragmentos.
5. Interpreta la respuesta JSON (temperatura 0); debe contener un arreglo `relations`. `relation_count` se recalcula a partir de ese arreglo.
6. Siempre enruta a `success`, también con cero relaciones.

## En un workflow

### Nodo

```json
{
  "node_id": "node-relations",
  "label": "Extract relations",
  "operator_slug": "ai.relation.extract",
  "operator_version": "1.0.0",
  "config": {
    "llm_provider_id": "<llm_provider_id>",
    "relation_types": [
      "works_for",
      "located_in"
    ],
    "include_evidence": true,
    "language": "en"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "success",
  "data": {
    "relations": [
      {
        "subject": "Ana Ruiz",
        "predicate": "works_for",
        "object": "Example Corp",
        "confidence": 0.94,
        "evidence": "Ana Ruiz, who works for Example Corp"
      },
      {
        "subject": "Example Corp",
        "predicate": "located_in",
        "object": "Lisbon",
        "confidence": 0.88,
        "evidence": "Example Corp’s Lisbon office"
      }
    ],
    "entities": [
      "Ana Ruiz",
      "Example Corp",
      "Lisbon"
    ],
    "relation_count": 2
  }
}
```

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

### `success`

La respuesta fue JSON válido con un arreglo `relations`, aunque esté vacío. La descripción dice «al menos una relación»; el código no lo comprueba.

```json
{
  "relations": [
    {
      "subject": "Ana Ruiz",
      "predicate": "works_for",
      "object": "Example Corp",
      "confidence": 0.94,
      "evidence": "Ana Ruiz, who works for Example Corp"
    },
    {
      "subject": "Example Corp",
      "predicate": "located_in",
      "object": "Lisbon",
      "confidence": 0.88,
      "evidence": "Example Corp’s Lisbon office"
    }
  ],
  "entities": [
    "Ana Ruiz",
    "Example Corp",
    "Lisbon"
  ],
  "relation_count": 2
}
```

### `error`

Falló la validación, la llamada al LLM o la interpretación. `data` es `{ error }` (más `response` cuando el backend devolvió un cuerpo).

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

## Comportamiento en el código

- `llm_provider_id`: Es obligatorio en ejecución aunque el esquema no lo marque como requerido. Es el id de un registro de proveedor LLM; el backend resuelve a partir de él el endpoint, el despliegue y las credenciales.
- `relation_types`: Es una indicación en el prompt («céntrate en estos tipos»); las relaciones de otros tipos que devuelva el modelo no se filtran.
- `timeout_ms`: `timeout_ms` solo tiene efecto en modo `stream`, como el tiempo de inactividad permitido entre fragmentos (predeterminado 600000). En modo `sync` se registra en el log, pero la petición al backend no tiene tiempo límite.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Missing input text for relation extraction.` | `error` | No llegan ni `text` ni `input`. |
| `Model did not return valid relation extraction output.` | `error` | La respuesta no tenía un objeto JSON con un arreglo `relations`. |
| `[AiRelationExtract] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | El nodo no tiene `llm_provider_id`. Elige un proveedor LLM en la configuración del nodo; la clave antigua `model_id` no se acepta. |
| `LLM Invocation Error: <backend message>` | `error` | El backend rechazó la llamada (registro de proveedor desconocido o inactivo, error del proveedor, credenciales). Revisa el registro del proveedor. |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | No se pudo contactar con el backend o no devolvió nada en modo `sync`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | En modo `stream` no llegó ningún fragmento dentro de `timeout_ms`. |

## Notas y límites

- Cuando falta `text`, el código recurre a `input`, que en ejecución es el ítem entrante completo (un objeto), no un texto. Proporciona siempre `text`.
- La respuesta del modelo se interpreta como JSON tras quitar los bloques de código Markdown; si falla, se interpreta el texto entre la primera `{` y la última `}`.
- Los campos de entrada se leen del ítem entrante (`$json`). Una clave con el mismo nombre en la configuración del nodo, que puede ser una expresión, tiene prioridad sobre la entrada.
- El worker también devuelve la respuesta del proveedor como `raw` fuera de `data`; el motor no la conserva.
- En caso de éxito el worker devuelve `port` y `data` sin el campo `ok`; el motor enruta solo por `port`.
- `timeout_ms` solo tiene efecto en modo `stream`, como el tiempo de inactividad permitido entre fragmentos (predeterminado 600000). En modo `sync` se registra en el log, pero la petición al backend no tiene tiempo límite.
- En modo `stream` la temperatura que fija este nodo no se envía al proveedor, y `raw` es `null`.
- El motor no aplica `execution.retryOnFail`, `maxTries`, `waitBetweenTries` ni `continueOnFail` a este nodo. Gestiona los fallos conectando el puerto `error`.


## Contratos (JSON Schema)

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

```json
{
  "slug": "ai.relation.extract",
  "name": "Extract Relations",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extracts semantic relationships between entities from text as subject-predicate-object triples.\n\n  Produces knowledge-graph-ready output that identifies who did what to whom, when, and where. Optionally filter to specific relation types and include evidence text spans.\n\n  **Use Cases:**\n  - **Knowledge Graphs:** Build structured graphs from documents.\n  - **Compliance:** Extract contractual obligations and parties.\n  - **Intelligence:** Map relationships between people, organizations, and events.",
  "capabilities": [
    "ai",
    "nlp",
    "relation-extraction",
    "knowledge-graph"
  ],
  "config_schema": {
    "type": "object",
    "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
      },
      "relation_types": {
        "type": "array",
        "title": "Relation Types",
        "items": {
          "type": "string"
        },
        "description": "Filter to specific relation types (e.g., works_for, located_in). Leave empty for all."
      },
      "include_evidence": {
        "type": "boolean",
        "title": "Include Evidence",
        "default": true,
        "description": "Include the source text span that supports each extracted relation."
      },
      "language": {
        "type": "string",
        "title": "Language",
        "default": "en",
        "description": "Language of the input text."
      },
      "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 extract relations from."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "relations": {
        "type": "array",
        "description": "Extracted relations as subject-predicate-object triples with confidence."
      },
      "entities": {
        "type": "array",
        "description": "Unique entities referenced in the relations."
      },
      "relation_count": {
        "type": "number",
        "description": "Total number of relations extracted."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Relations Found",
      "description": "At least one relation was extracted.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Extraction failed.",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "nlp",
    "relation-extraction",
    "knowledge-graph",
    "triples"
  ],
  "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",
  "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
    },
    "relation_types": {
      "type": "array",
      "title": "Relation Types",
      "items": {
        "type": "string"
      },
      "description": "Filter to specific relation types (e.g., works_for, located_in). Leave empty for all."
    },
    "include_evidence": {
      "type": "boolean",
      "title": "Include Evidence",
      "default": true,
      "description": "Include the source text span that supports each extracted relation."
    },
    "language": {
      "type": "string",
      "title": "Language",
      "default": "en",
      "description": "Language of the input text."
    },
    "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 extract relations from."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "relations": {
      "type": "array",
      "description": "Extracted relations as subject-predicate-object triples with confidence."
    },
    "entities": {
      "type": "array",
      "description": "Unique entities referenced in the relations."
    },
    "relation_count": {
      "type": "number",
      "description": "Total number of relations extracted."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Relations Found",
    "description": "At least one relation was extracted.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Extraction failed.",
    "is_default": false,
    "supports_condition": false
  }
]
```
