# Extract Key Phrases

> Extracts the most important phrases, terms, and concepts from text with relevance scoring.

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

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

Extracts the most important phrases, terms, and concepts from text with relevance scoring. Each phrase is optionally categorized as topic, entity, concept, or action.

## 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.
- `max_phrases` (number, optional): Maximum number of key phrases to extract. Default: `10`.
- `include_scores` (boolean, optional): Include relevance scores for each phrase. 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): Key phrases extracted successfully.
- `error`: Extraction failed.

## Input contract

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

## Output contract

- `phrases` (array, optional): Extracted phrases with relevance score and optional category.
- `top_phrase` (string, optional): The most important phrase.

## In expressions

What a later node can read from this node's output with `$("Extract Key Phrases").item.json.<path>` (write your node's label instead of `Extract Key Phrases`). **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 Key Phrases").item.json.phrases` (array) = `[…] (3)`: Extracted phrases with relevance score and optional category.
- `$("Extract Key Phrases").item.json.top_phrase` (string) = `"late delivery"`: The most important phrase.


## How it works

Asks the model for the most important key phrases of `text`, each with relevance and category, and returns them with the top phrase.

1. Merges the upstream payload with the node config (config wins) and reads `text` (falling back to `input`).
2. Sends a system prompt asking for the top `max_phrases` phrases (default 10) in `language`, scored when `include_scores` is not `false`, as strict JSON; `text` is the user message; `temperature: 0`.
3. Parses the answer as JSON; `phrases` must be an array. `top_phrase` is the model's value or, when missing, the first phrase. Routes to `success`.

## In a workflow

### Node

```json
{
  "node_id": "node-key-phrases",
  "label": "Key phrases",
  "operator_slug": "ai.keyphrases",
  "operator_version": "1.0.0",
  "config": {
    "text": "{{ $json.body }}",
    "max_phrases": 5,
    "include_scores": true,
    "language": "en",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "invocation_mode": "sync"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "phrases": [
      {
        "phrase": "late delivery",
        "relevance": 0.95,
        "category": "topic"
      },
      {
        "phrase": "refund request",
        "relevance": 0.88,
        "category": "action"
      },
      {
        "phrase": "Northwind Logistics",
        "relevance": 0.7,
        "category": "entity"
      }
    ],
    "top_phrase": "late delivery"
  },
  "port": "success"
}
```

## Output ports (behaviour in the code)

### `success`

The model returned a `phrases` array.

```json
{
  "phrases": [
    {
      "phrase": "late delivery",
      "relevance": 0.95,
      "category": "topic"
    },
    {
      "phrase": "refund request",
      "relevance": 0.88,
      "category": "action"
    },
    {
      "phrase": "Northwind Logistics",
      "relevance": 0.7,
      "category": "entity"
    }
  ],
  "top_phrase": "late delivery"
}
```

### `error`

The model call failed or the answer had no `phrases` array.

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

## Behaviour in the code

- `max_phrases`: Only written into the prompt; the code does not cut the list, so the model may return more or fewer phrases.
- `text`: Not in the config schema (it is in the input contract), but read from the config first and then from the upstream payload.
- `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 |
| --- | --- | --- |
| `Model did not return valid key phrase extraction output.` | `error` | The answer was not JSON or `phrases` was not an array. |
| `[AiKeyphrases] 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

- When `text` is empty, the worker falls back to `input`, which at runtime is always the whole upstream payload object. The missing-text check therefore never fires and the object is sent to the model as the message. Always map `text` explicitly.
- Phrases are passed through as the model returns them; their order, `relevance` and `category` are not validated.
- The worker returns `raw` next to `data`; the engine keeps only `data` as the node output, so `raw` is not available downstream.
- 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.keyphrases",
  "name": "Extract Key Phrases",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extracts the most important phrases, terms, and concepts from text with relevance scoring. Each phrase is optionally categorized as topic, entity, concept, or action.",
  "capabilities": [
    "ai",
    "nlp",
    "keyphrases",
    "extraction"
  ],
  "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
      },
      "max_phrases": {
        "type": "number",
        "title": "Max Phrases",
        "default": 10,
        "description": "Maximum number of key phrases to extract."
      },
      "include_scores": {
        "type": "boolean",
        "title": "Include Scores",
        "default": true,
        "description": "Include relevance scores for each phrase."
      },
      "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 key phrases from."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "phrases": {
        "type": "array",
        "description": "Extracted phrases with relevance score and optional category."
      },
      "top_phrase": {
        "type": "string",
        "description": "The most important phrase."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Phrases Extracted",
      "description": "Key phrases extracted successfully.",
      "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",
    "keyphrases",
    "extraction",
    "text-analysis"
  ],
  "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
    },
    "max_phrases": {
      "type": "number",
      "title": "Max Phrases",
      "default": 10,
      "description": "Maximum number of key phrases to extract."
    },
    "include_scores": {
      "type": "boolean",
      "title": "Include Scores",
      "default": true,
      "description": "Include relevance scores for each phrase."
    },
    "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 key phrases from."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "phrases": {
      "type": "array",
      "description": "Extracted phrases with relevance score and optional category."
    },
    "top_phrase": {
      "type": "string",
      "description": "The most important phrase."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Phrases Extracted",
    "description": "Key phrases extracted successfully.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Extraction failed.",
    "is_default": false,
    "supports_condition": false
  }
]
```
