# Detect Intent

> 从输入文本中识别用户意图，并抽取用于下游路由的相关参数。

Source: https://docs.sommatic.ai/zh/nodes/ai.intent/

- 标识: `ai.intent`
- 类别: AI
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

从输入文本中识别用户意图，并抽取用于下游路由的相关参数。

该算子依据可配置的意图目录对输入文本进行分类，输出主要意图、置信度得分、抽取出的参数，以及用于工作流编排的路由提示。

**操作**
- **意图识别：** 将文本与带有描述和示例的具名意图目录进行匹配。
- **参数抽取：** 抽取与所识别意图相关的键值槽位参数。
- **路由：** 提供路由提示，引导下游工作流分支。

**适用场景**
- 根据用户意图路由聊天机器人消息（例如“book_appointment”“check_status”“complaint”）。
- 按目的对邮件进行分诊和自动归类。
- 对 Command Center 的输入分类，区分显式执行与推理辅助执行。
- 多渠道受理路由，并根据置信度升级到人工复核。

## 配置

- `llm_provider_id` (string, 可选): `LlmProviderModel` 记录的 `id`（例如 `wf-llm-provider-*`）。编排器将调用委托给后端：sync 模式调用 `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke`，stream 模式调用 `POST /chat/conversation/execute/stream-ephemeral`（SSE）。后端根据该记录解析 endpoint + api-key + deployment，并路由到相应的适配器。
- `invocation_mode` (string, 可选): LLM 调用的传输方式。`sync` 会阻塞直到收到完整响应。`stream` 通过 SSE 逐步接收 token（长文本生成必须使用）。默认为 `sync`。 默认值: `sync`. 可选值: `sync`, `stream`.
- `timeout_ms` (integer, 可选): 等待调用完成的最长时间（stream 模式下为分块之间的空闲超时）。sync 默认 30000，stream 默认 600000。
- `intents` (array<object>, 可选): 定义要识别的意图。每个意图都需要名称和描述。 默认值: `[]`.
- `allow_multiple` (boolean, 可选): 允许在单次输入中识别多个意图。 默认值: `false`.
- `confidence_threshold` (number, 可选): 置信度低于此阈值时标记为 needs_review。 默认值: `0.7`.
- `knowledge_resource_id` (string, 可选): 从 Knowledge Resource 加载意图目录，而不是使用内联配置。
- `language` (string, 可选): 输出语言代码（例如“en”“es”）。 默认值: `en`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `detected` (默认): Detected
- `unknown`: Unknown
- `error`: Error

## 输入契约

- `text` (string, 必填): 要分析意图的输入文本。
- `context` (string, 可选): 可选的对话或会话上下文。
- `channel` (string, 可选): 可选的渠道标识（chat、email、api 等）。

## 输出契约

- `primary_intent` (string, 可选): 识别出的主要意图名称或“unknown”。
- `confidence` (number, 可选): 主要意图的置信度得分（0-1）。
- `all_intents` (array<object>, 可选): 目录中所有意图的概率分布。
- `parameters` (object, 可选): 抽取出的与意图相关的键值参数。
- `routing_hint` (string, 可选): 建议的下一步操作或路由目标。
- `needs_review` (boolean, 可选): 置信度低于阈值时为 true。

## 在表达式中

后续节点可通过 `$("Detect Intent").item.json.<路径>` 读取此节点输出中的内容（请把 `Detect Intent` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `detected` 返回的路径，依据“端口”一节所示的输出。

- `$("Detect Intent").item.json.primary_intent` (string) = `"track_order"`: 识别出的主要意图名称或“unknown”。
- `$("Detect Intent").item.json.confidence` (number) = `0.92`: 主要意图的置信度得分（0-1）。
- `$("Detect Intent").item.json.all_intents` (array) = `[…] (3)`: 目录中所有意图的概率分布。
- `$("Detect Intent").item.json.parameters` (object) = `{…}`: 抽取出的与意图相关的键值参数。
- `$("Detect Intent").item.json.routing_hint` (string) = `"order-status-flow"`: 建议的下一步操作或路由目标。
- `$("Detect Intent").item.json.needs_review` (boolean) = `false`: 置信度低于阈值时为 true。
- `$("Detect Intent").item.json.parameters.order_id` (string) = `"4521"` (编辑器不提示)
- `$("Detect Intent").item.json.raw` (null) = `null` (编辑器不提示)
- `$("Detect Intent").item.json.port` (string) = `"detected"` (编辑器不提示)


## 工作原理

依据意图目录（内联和/或来自知识资源）识别 `text` 中的用户意图，并携带提取出的参数路由到 `detected` 或 `unknown`。

1. 合并上游载荷与节点配置（以配置为准），读取 `text`、`context` 和 `channel`；`text` 为空时抛出 `Missing 'text'`。
2. 从 `intents` 收集意图（每项需有 `name`），并追加 `knowledge_resource_id` 中 `content.structured_data.intents` 里名称尚未出现的意图（不区分大小写）。一个都没有时失败。
3. 发送包含目录、阈值和严格 JSON 格式的分类器系统提示词；用户消息拼接 `Channel:`、`Context:` 和 `text`；`temperature: 0`。
4. 将回答解析为 JSON。`primary_intent` 与目录做不区分大小写的匹配，其他任何值都改为 `unknown`。`all_intents` 中缺失的目录意图会以置信度 0 补上。
5. `needs_review` 取模型给出的值，缺失时为 `confidence < confidence_threshold`。除非意图为 `unknown`，否则从 `detected` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-detect-intent",
  "label": "Detect intent",
  "operator_slug": "ai.intent",
  "operator_version": "1.0.0",
  "config": {
    "text": "{{ $json.message }}",
    "channel": "chat",
    "intents": [
      {
        "name": "track_order",
        "description": "The user wants to know where an order is",
        "examples": "where is my order, tracking number"
      },
      {
        "name": "cancel_order",
        "description": "The user wants to cancel an order"
      },
      {
        "name": "refund",
        "description": "The user asks for money back"
      }
    ],
    "allow_multiple": false,
    "confidence_threshold": 0.7,
    "language": "en",
    "llm_provider_id": "wf-llm-provider-xxxx",
    "invocation_mode": "sync"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "primary_intent": "track_order",
    "confidence": 0.92,
    "all_intents": [
      {
        "intent": "track_order",
        "confidence": 0.92
      },
      {
        "intent": "cancel_order",
        "confidence": 0.05
      },
      {
        "intent": "refund",
        "confidence": 0.03
      }
    ],
    "parameters": {
      "order_id": "4521"
    },
    "routing_hint": "order-status-flow",
    "needs_review": false,
    "raw": null,
    "port": "detected"
  },
  "port": "detected"
}
```

## 输出端口 (代码中的行为)

### `detected`

主意图属于目录中的意图，无论置信度高低。低置信度请查看 `needs_review`。

```json
{
  "primary_intent": "track_order",
  "confidence": 0.92,
  "all_intents": [
    {
      "intent": "track_order",
      "confidence": 0.92
    },
    {
      "intent": "cancel_order",
      "confidence": 0.05
    },
    {
      "intent": "refund",
      "confidence": 0.03
    }
  ],
  "parameters": {
    "order_id": "4521"
  },
  "routing_hint": "order-status-flow",
  "needs_review": false,
  "raw": null,
  "port": "detected"
}
```

### `unknown`

模型回答为 `unknown`、未给出意图，或给出了目录之外的名称。

```json
{
  "primary_intent": "unknown",
  "confidence": 0.2,
  "all_intents": [
    {
      "intent": "track_order",
      "confidence": 0.1
    },
    {
      "intent": "cancel_order",
      "confidence": 0.05
    },
    {
      "intent": "refund",
      "confidence": 0.05
    }
  ],
  "parameters": {},
  "routing_hint": null,
  "needs_review": true,
  "raw": null,
  "port": "unknown"
}
```

### `error`

缺少 `text` 或目录、模型调用失败或回答不是 JSON。

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

## 代码中的行为

- `confidence_threshold`: 不会改变端口：低置信度的目录意图仍走 `detected`。仅在模型未给出 `needs_review` 时用于设置该值。
- `text, context, channel`: 不在配置 schema 中（位于输入契约中），但会先从配置读取，再从上游载荷读取。
- `timeout_ms`: 仅限 stream 模式：片段之间的空闲超时，默认 600000。在 sync 模式下不会作用于请求。
- `execution`: 已声明但被忽略：worker 和引擎都不会读取该块中的 `retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail`、`alwaysOutputData` 或 `timeout_ms`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'text'` | `error` | 配置和上游载荷中都没有 `text`。 |
| `No intents found. Provide intents in the config or link a Knowledge Resource with an intent catalog.` | `error` | `intents` 和资源都没有提供带 `name` 的意图。若没有内联意图且资源获取失败，则返回该获取错误。 |
| `Model did not return valid JSON output` | `error` | 回答无法解析为 JSON 对象。 |
| `[AiIntent] 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` 为空或不是字符串。请选择具备 chat 能力的 LLM 提供方记录。 |
| `LLM Invocation Error: <backend message>` | `error` | 后端拒绝了调用：提供方记录不存在或未激活、提供方报错、配额或内容过滤。请检查提供方记录和后端日志。 |
| `LLM Invocation Error: empty response from backend (<transport error>)` | `error` | sync 模式：对后端的 HTTP 调用失败（网络错误、非 2xx 状态或超时）。长提示词常会触发请求超时，请改用 `invocation_mode: "stream"`。 |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | stream 模式：在 `timeout_ms` 内未收到任何片段。若流式请求本身失败，消息为 `RemoteApiService.stream: HTTP <status> — <body>`。 |

## 说明与限制

- 会要求模型给出 `reasoning`，但不会返回。`parameters` 作为对象原样取自模型。
- 该 worker 将字段直接放在返回值顶层而非 `data` 内，因此引擎把整个返回值存为节点输出：`port` 和 `raw` 会与结果字段一起出现在 `$json` 中。
- `raw` 在 sync 模式下是提供方的原始响应，在 stream 模式下为 `null`。
- 模型调用经由 Sommatic AI 后端完成，后端根据 `llm_provider_id` 指定的提供方记录解析端点、凭据和部署；编排器从不持有提供方密钥。`invocation_mode: "sync"`（默认）等待完整回答；`"stream"` 以 SSE 事件读取回答并拼接各片段。
- `timeout_ms` 仅在 stream 模式下生效，表示片段之间允许的最长空闲时间（默认 600000）。在 sync 模式下该值只写入日志，不会作用于 HTTP 请求，因此以平台默认请求超时为准。
- 在 stream 模式下，后端端点不应用采样参数，因此固定的 `temperature: 0` 仅在 sync 模式下生效。
- 每次运行都会从后端读取知识资源（超时 10 秒）。状态不是 `active` 的资源仍会被使用，并在日志中记录警告。
- 不会自动重试：引擎不会为本节点执行 `execution.retryOnFail`、`maxTries` 或 `waitBetweenTries`；调用失败会直接从 `error` 输出。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.intent",
  "name": "Detect Intent",
  "category": "ai",
  "version": "1.0.0",
  "description": "Detects user intent from text input and extracts relevant parameters for downstream routing.\n\nThis operator classifies input text against a configurable intent catalog, producing a primary intent, confidence score, extracted parameters, and routing hints for workflow orchestration.\n\n**Operations**\n- **Intent Detection:** Matches text against a catalog of named intents with descriptions and examples.\n- **Parameter Extraction:** Extracts key-value slot parameters relevant to the detected intent.\n- **Routing:** Provides routing hints to guide downstream workflow branching.\n\n**Use Cases**\n- Chatbot message routing based on user intent (e.g., \"book_appointment\", \"check_status\", \"complaint\").\n- Email triage and automatic categorization by purpose.\n- Command Center input classification for explicit vs. inference-assisted execution.\n- Multi-channel intake routing with confidence-based human review escalation.",
  "capabilities": [
    "ai",
    "nlp",
    "intent",
    "classification",
    "routing"
  ],
  "knowledge_binding": {
    "enabled": true,
    "resource_types": [
      "intent_catalog"
    ],
    "field": "knowledge_resource_id",
    "label": "Intent Catalog"
  },
  "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
      },
      "intents": {
        "type": "array",
        "title": "Intent Catalog",
        "description": "Define the intents to detect. Each needs a name and description.",
        "items": {
          "type": "object",
          "properties": {
            "name": {
              "type": "string",
              "title": "Intent Name"
            },
            "description": {
              "type": "string",
              "title": "Description"
            },
            "examples": {
              "type": "string",
              "title": "Example Phrases"
            }
          },
          "required": [
            "name",
            "description"
          ]
        },
        "default": []
      },
      "allow_multiple": {
        "type": "boolean",
        "title": "Allow Multiple Intents",
        "description": "Allow detecting multiple intents in a single input.",
        "default": false
      },
      "confidence_threshold": {
        "type": "number",
        "title": "Confidence Threshold",
        "description": "Flag as needs_review when confidence falls below this threshold.",
        "default": 0.7,
        "minimum": 0,
        "maximum": 1
      },
      "knowledge_resource_id": {
        "type": "string",
        "title": "Intent Catalog (Knowledge Resource)",
        "description": "Load intent catalog from a Knowledge Resource instead of inline config.",
        "ui_widget": "knowledge_resource_picker"
      },
      "language": {
        "type": "string",
        "title": "Language",
        "description": "Output language code (e.g., \"en\", \"es\").",
        "default": "en"
      },
      "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": "The text input to analyze for intent."
      },
      "context": {
        "type": "string",
        "description": "Optional conversation or session context."
      },
      "channel": {
        "type": "string",
        "description": "Optional channel identifier (chat, email, api, etc.)."
      }
    },
    "required": [
      "text"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "primary_intent": {
        "type": "string",
        "description": "The detected primary intent name or \"unknown\"."
      },
      "confidence": {
        "type": "number",
        "description": "Confidence score (0-1) for the primary intent."
      },
      "all_intents": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "intent": {
              "type": "string"
            },
            "confidence": {
              "type": "number"
            }
          }
        },
        "description": "Probability distribution across all catalog intents."
      },
      "parameters": {
        "type": "object",
        "description": "Extracted key-value parameters relevant to the intent."
      },
      "routing_hint": {
        "type": "string",
        "description": "Suggested next action or routing target."
      },
      "needs_review": {
        "type": "boolean",
        "description": "True when confidence is below the threshold."
      }
    }
  },
  "ports": [
    {
      "port_id": "detected",
      "label": "Detected",
      "is_default": true
    },
    {
      "port_id": "unknown",
      "label": "Unknown"
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "nlp",
    "intent",
    "routing",
    "classification"
  ],
  "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
    },
    "intents": {
      "type": "array",
      "title": "Intent Catalog",
      "description": "Define the intents to detect. Each needs a name and description.",
      "items": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "title": "Intent Name"
          },
          "description": {
            "type": "string",
            "title": "Description"
          },
          "examples": {
            "type": "string",
            "title": "Example Phrases"
          }
        },
        "required": [
          "name",
          "description"
        ]
      },
      "default": []
    },
    "allow_multiple": {
      "type": "boolean",
      "title": "Allow Multiple Intents",
      "description": "Allow detecting multiple intents in a single input.",
      "default": false
    },
    "confidence_threshold": {
      "type": "number",
      "title": "Confidence Threshold",
      "description": "Flag as needs_review when confidence falls below this threshold.",
      "default": 0.7,
      "minimum": 0,
      "maximum": 1
    },
    "knowledge_resource_id": {
      "type": "string",
      "title": "Intent Catalog (Knowledge Resource)",
      "description": "Load intent catalog from a Knowledge Resource instead of inline config.",
      "ui_widget": "knowledge_resource_picker"
    },
    "language": {
      "type": "string",
      "title": "Language",
      "description": "Output language code (e.g., \"en\", \"es\").",
      "default": "en"
    },
    "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": "The text input to analyze for intent."
    },
    "context": {
      "type": "string",
      "description": "Optional conversation or session context."
    },
    "channel": {
      "type": "string",
      "description": "Optional channel identifier (chat, email, api, etc.)."
    }
  },
  "required": [
    "text"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "primary_intent": {
      "type": "string",
      "description": "The detected primary intent name or \"unknown\"."
    },
    "confidence": {
      "type": "number",
      "description": "Confidence score (0-1) for the primary intent."
    },
    "all_intents": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "intent": {
            "type": "string"
          },
          "confidence": {
            "type": "number"
          }
        }
      },
      "description": "Probability distribution across all catalog intents."
    },
    "parameters": {
      "type": "object",
      "description": "Extracted key-value parameters relevant to the intent."
    },
    "routing_hint": {
      "type": "string",
      "description": "Suggested next action or routing target."
    },
    "needs_review": {
      "type": "boolean",
      "description": "True when confidence is below the threshold."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "detected",
    "label": "Detected",
    "is_default": true
  },
  {
    "port_id": "unknown",
    "label": "Unknown"
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
