# Extract Data

> Extracts structured data (JSON) from unstructured text using an LLM.

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

- Slug: `ai.extract`
- Family: AI
- Version: 1.0.0
- Status: Partial. On success the worker returns no port, so the engine follows `out`, which this node does not declare: an edge drawn from its success port never fires. Until it is fixed, do not chain nodes after its success path.
- Execution: async

Extracts structured data (JSON) from unstructured text using an LLM.

This operator intelligently parses emails, documents, or logs and converts them into a strict JSON schema you define. It uses an LLM (Schema Mode) to guarantee the output format.

**Use Cases:**
- **Invoices:** extracting 'Total Amount', 'Due Date', 'Vendor' from OCR text.
- **Resumes:** extracting 'Skills', 'Experience', 'Contact Info' from a bio.
- **Support:** extracting 'Ticket ID', 'Severity', 'Sentiment' from a chat log.

## 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.
- `schema` (string, required): JSON Schema object defining the structure to extract.

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): Valid structure returned.
- `error`: Model failed to extract valid JSON.

## Input contract

- `input` (string, required): The unstructured text to process.

## Output contract

- `data` (object, optional): The extracted JSON object.

## In expressions

What a later node can read from this node's output with `$("Extract Data").item.json.<path>` (write your node's label instead of `Extract Data`). **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 Data").item.json.data` (object): The extracted JSON object. **The worker does not return it: reads as undefined.**
- `$("Extract Data").item.json.customer_name` (string) = `"Ana Ruiz"` (Not suggested by the editor)
- `$("Extract Data").item.json.order_id` (string) = `"4521"` (Not suggested by the editor)
- `$("Extract Data").item.json.amount` (number) = `129.9` (Not suggested by the editor)
- `$("Extract Data").item.json.currency` (string) = `"USD"` (Not suggested by the editor)


## How it works

Sends the whole upstream payload to the model with your `schema` and returns the JSON object the model extracts. Partial: on success it leaves through `out`, which is not a declared port.

1. Reads `schema` (or `structure`) from the node config; throws `Missing 'schema'` when empty.
2. Takes the input as the whole upstream payload object, serialised with `JSON.stringify`.
3. Sends a system prompt that embeds `schema` and asks for JSON only, with the serialised payload as the user message, at `temperature: 0`.
4. Removes code fences and parses the answer with strict `JSON.parse` (no partial recovery). The parsed value becomes the node output on `out`.

## In a workflow

### Node

```json
{
  "node_id": "node-extract-order",
  "label": "Extract order",
  "operator_slug": "ai.extract",
  "operator_version": "1.0.0",
  "config": {
    "model_id": "wf-llm-provider-xxxx",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "schema": "{\"type\":\"object\",\"properties\":{\"customer_name\":{\"type\":\"string\"},\"order_id\":{\"type\":\"string\"},\"amount\":{\"type\":\"number\"},\"currency\":{\"type\":\"string\"}}}",
    "invocation_mode": "sync"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "customer_name": "Ana Ruiz",
    "order_id": "4521",
    "amount": 129.9,
    "currency": "USD"
  },
  "port": "out"
}
```

## Output ports (behaviour in the code)

### `success`

Declared but never emitted. On success the engine follows `out`; an edge drawn from `success` never fires. The data shown is what `out` carries.

```json
{
  "customer_name": "Ana Ruiz",
  "order_id": "4521",
  "amount": 129.9,
  "currency": "USD"
}
```

### `error`

`schema` is missing, the model call failed or the answer was not valid JSON.

```json
{
  "error": "LLM output was not valid JSON"
}
```

## Behaviour in the code

- `model_id`: The schema lists `model_id` as required, but the worker never reads it; the provider comes from `llm_provider_id`. It appears in the example only to satisfy schema validation.
- `schema`: Inserted into the prompt as text. Store it as a string (a JSON Schema or a plain description); an object would be inserted as `[object Object]`. `structure` is an undeclared alias.
- `input`: Cannot be set on the node: the runtime replaces it with the upstream payload, so the model always receives the whole previous output. Trim that output upstream (e.g. with `data.transform`) to control what is sent.
- `timeout_ms`: Stream mode only: idle timeout between chunks, default 600000. In sync mode it is not applied to the request.
- `execution`: Declared but ignored: neither the worker nor the engine reads `retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail`, `alwaysOutputData` or `timeout_ms` from this block.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Missing 'schema'` | `error` | Neither `schema` nor `structure` is set. |
| `LLM output was not valid JSON` | `error` | The answer had text around the JSON or was malformed. Tighten the schema description or use `ai.legal.extract.structured-multi-pass`, which retries with corrections. |
| `[AiExtract] 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` is empty or not a string. Pick an LLM provider record with chat capability. |
| `LLM Invocation Error: <backend message>` | `error` | The backend rejected the call: unknown or inactive provider record, provider error, quota or content filter. Check the provider record and the backend logs. |
| `LLM Invocation Error: empty response from backend (<transport error>)` | `error` | Sync mode: the HTTP call to the backend failed (network error, non-2xx status or timeout). Long prompts often hit the request timeout; switch to `invocation_mode: "stream"`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | Stream mode: no chunk arrived within `timeout_ms`. A failed stream request shows `RemoteApiService.stream: HTTP <status> — <body>` instead. |

## Notes and limits

- Known defect: the success path returns no port, so the engine uses `out`, which the node does not declare. Do not chain nodes after its success path until it is fixed.
- The output is the extracted object itself (not wrapped in `data`), and `raw` is dropped. The result is not validated against `schema`.
- The model call goes through the Sommatic AI backend, which resolves the provider record named by `llm_provider_id` (endpoint, credentials, deployment); the orchestrator never holds provider keys. `invocation_mode: "sync"` (default) waits for the full answer; `"stream"` reads it as server-sent events and joins the chunks.
- `timeout_ms` only takes effect in stream mode, as the idle time allowed between chunks (default 600000). In sync mode the value is logged but not applied to the HTTP request, so the platform's default request timeout governs.
- In stream mode the backend endpoint does not apply sampling settings, so the fixed `temperature: 0` only takes effect in sync mode.
- No automatic retries: the engine does not honour `execution.retryOnFail`, `maxTries` or `waitBetweenTries` for this node; a failed call goes straight to `error`.


## Contracts (JSON Schema)

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

```json
{
  "slug": "ai.extract",
  "name": "Extract Data",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extracts structured data (JSON) from unstructured text using an LLM.\n\n  This operator intelligently parses emails, documents, or logs and converts them into a strict JSON schema you define. It uses an LLM (Schema Mode) to guarantee the output format.\n\n  **Use Cases:**\n  - **Invoices:** extracting 'Total Amount', 'Due Date', 'Vendor' from OCR text.\n  - **Resumes:** extracting 'Skills', 'Experience', 'Contact Info' from a bio.\n  - **Support:** extracting 'Ticket ID', 'Severity', 'Sentiment' from a chat log.",
  "capabilities": [
    "llm",
    "extraction",
    "parsing",
    "structured-output"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "model_id",
      "schema"
    ],
    "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
      },
      "schema": {
        "type": "string",
        "title": "Extraction Schema",
        "format": "json",
        "description": "JSON Schema object defining the structure to extract."
      },
      "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": {
      "input": {
        "type": "string",
        "description": "The unstructured text to process."
      }
    },
    "required": [
      "input"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "data": {
        "type": "object",
        "description": "The extracted JSON object."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Extracted",
      "is_default": true,
      "description": "Valid structure returned."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Model failed to extract valid JSON."
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "extract",
    "llm",
    "parse"
  ],
  "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": [
    "model_id",
    "schema"
  ],
  "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
    },
    "schema": {
      "type": "string",
      "title": "Extraction Schema",
      "format": "json",
      "description": "JSON Schema object defining the structure to extract."
    },
    "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": {
    "input": {
      "type": "string",
      "description": "The unstructured text to process."
    }
  },
  "required": [
    "input"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "data": {
      "type": "object",
      "description": "The extracted JSON object."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Extracted",
    "is_default": true,
    "description": "Valid structure returned."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Model failed to extract valid JSON."
  }
]
```
