# Extract Relations

> Extracts semantic relationships between entities from text as subject-predicate-object triples.

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

- Slug: `ai.relation.extract`
- Family: AI
- Version: 1.0.0
- Status: Available
- Execution: async

Extracts semantic relationships between entities from text as subject-predicate-object triples.

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.

**Use Cases:**
- **Knowledge Graphs:** Build structured graphs from documents.
- **Compliance:** Extract contractual obligations and parties.
- **Intelligence:** Map relationships between people, organizations, and events.

## Configuration

- `llm_provider_id` (string, optional): 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.
- `invocation_mode` (string, optional): Transport for the LLM call. `sync` blocks until the full response arrives. `stream` consumes tokens via SSE (required for long generations). Default `sync`. Default: `sync`. Allowed values: `sync`, `stream`.
- `timeout_ms` (integer, optional): Maximum time to wait for the invocation to complete (or idle timeout between chunks in stream mode). Default 30000 for sync, 600000 for stream.
- `relation_types` (array<string>, optional): Filter to specific relation types (e.g., works_for, located_in). Leave empty for all.
- `include_evidence` (boolean, optional): Include the source text span that supports each extracted relation. Default: `true`.
- `language` (string, optional): Language of the input text. Default: `en`.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `success` (default): At least one relation was extracted.
- `error`: Extraction failed.

## Input contract

- `text` (string, required): Text to extract relations from.

## Output contract

- `relations` (array, optional): Extracted relations as subject-predicate-object triples with confidence.
- `entities` (array, optional): Unique entities referenced in the relations.
- `relation_count` (number, optional): Total number of relations extracted.

## In expressions

What a later node can read from this node's output with `$("Extract Relations").item.json.<path>` (write your node's label instead of `Extract Relations`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `success`, from the output shown in Ports.

- `$("Extract Relations").item.json.relations` (array) = `[…] (2)`: Extracted relations as subject-predicate-object triples with confidence.
- `$("Extract Relations").item.json.entities` (array) = `[…] (3)`: Unique entities referenced in the relations.
- `$("Extract Relations").item.json.relation_count` (number) = `2`: Total number of relations extracted.


## How it works

Extracts subject–predicate–object relations from `text` with the LLM and returns them with confidence, optional evidence spans and the list of entities involved.

1. Resolves the node config: expressions in config keys are evaluated against the run; the incoming item is used as-is.
2. Merges the incoming item with the resolved config (config keys win) and reads the inputs from the result.
3. Requires `text`. Builds the prompt with `relation_types` (empty = all types), `include_evidence` (default `true`) and `language` (default `en`).
4. Calls the LLM through the backend with the `llm_provider_id` record. `invocation_mode: "sync"` (default) waits for the full answer; `"stream"` reads it over SSE and joins the chunks.
5. Parses the JSON answer (temperature 0); it must contain a `relations` array. `relation_count` is recomputed from that array.
6. Always routes to `success`, also with zero relations.

## In a workflow

### Node

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

## Output ports (behaviour in the code)

### `success`

The answer was valid JSON with a `relations` array, even an empty one. The description says “at least one relation”; the code does not check it.

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

Validation, the LLM call or parsing failed. `data` is `{ error }` (plus `response` when the backend returned a body).

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

## Behaviour in the code

- `llm_provider_id`: Required at runtime although the schema does not mark it as required. It is the id of an LLM provider record; the backend resolves endpoint, deployment and credentials from it.
- `relation_types`: A prompt hint (“focus on these types”); relations of other types the model returns are not filtered out.
- `timeout_ms`: `timeout_ms` only takes effect in `stream` mode, as the idle time allowed between chunks (default 600000). In `sync` mode it is logged but the backend request has no timeout.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Missing input text for relation extraction.` | `error` | Neither `text` nor `input` is present. |
| `Model did not return valid relation extraction output.` | `error` | The answer had no JSON object with a `relations` array. |
| `[AiRelationExtract] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | The node has no `llm_provider_id`. Pick an LLM provider in the node config; the legacy `model_id` key is not accepted. |
| `LLM Invocation Error: <backend message>` | `error` | The backend rejected the call (unknown or inactive provider record, provider error, credentials). Check the provider record. |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | The backend could not be reached or returned nothing in `sync` mode. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | In `stream` mode no chunk arrived within `timeout_ms`. |

## Notes and limits

- When `text` is missing, the code falls back to `input`, which at runtime is the whole incoming item (an object), not a string. Always provide `text`.
- The model answer is parsed as JSON after removing Markdown code fences; if that fails, the text between the first `{` and the last `}` is parsed.
- Input fields are read from the incoming item (`$json`). A key with the same name in the node config, which may be an expression, takes precedence over the input.
- The worker also returns the provider response as `raw` outside `data`; the engine does not keep it.
- On success the worker returns `port` and `data` without an `ok` field; the engine routes on `port` only.
- `timeout_ms` only takes effect in `stream` mode, as the idle time allowed between chunks (default 600000). In `sync` mode it is logged but the backend request has no timeout.
- In `stream` mode the temperature this node sets is not forwarded to the provider, and `raw` is `null`.
- The engine does not apply `execution.retryOnFail`, `maxTries`, `waitBetweenTries` or `continueOnFail` to this node. Handle failures by wiring the `error` port.


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