# Answer Question

> 基于所提供上下文的有据问答。

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

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

基于所提供上下文的有据问答。

该算子严格依据提供的上下文回答问题，并附带证据引用和置信度评分。在严格依据模式下，若上下文中没有足够信息，它会拒绝作答。

**能力**
- 仅依据提供的上下文文档回答问题。
- 返回将答案与源材料关联起来的证据引用。
- 识别无法回答的问题，并将其路由到专用端口。
- 支持补充性的知识资源作为额外参考。
- 为每个答案提供置信度得分和依据评估。

**适用场景**
- 针对内部文档、政策或知识库的问答。
- 基于产品文档给出有据可查的客服答复。
- 依据政策文件进行合规核验。
- 从合同或法律文件中抽取具体答案。

## 配置

- `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。
- `strict_grounding` (boolean, 可选): 仅依据提供的上下文作答。答案不在上下文中时拒绝回答。 默认值: `true`.
- `language` (string, 可选): 输出语言代码（例如“en”“es”）。 默认值: `en`.
- `knowledge_resource_id` (string, 可选): 可选的知识资源 ID，用作补充参考材料。

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

## 输出端口

- `answered` (默认): Answered
- `unanswerable`: Unanswerable
- `error`: Error

## 输入契约

- `question` (string, 必填): 要回答的问题。
- `context` (string | array, 必填): 作为答题依据的上下文文档。字符串或字符串数组。
- `metadata` (object, 可选): 关于上下文来源的可选元数据。

## 输出契约

- `answer` (string, 可选): 生成的答案。
- `confidence` (number, 可选): 置信度得分（0-1）。
- `grounded` (boolean, 可选): 答案是否有上下文依据。
- `evidence` (array<object>, 可选): 来自上下文的证据引用。
- `unanswerable` (boolean, 可选): 问题是否无法根据上下文回答。
- `reasoning` (string, 可选): 简要说明答案是如何得出的。

## 在表达式中

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

- `$("Answer Question").item.json.answer` (string) = `"Returns are accepted within 30 days of deliv…"`: 生成的答案。
- `$("Answer Question").item.json.confidence` (number) = `0.92`: 置信度得分（0-1）。
- `$("Answer Question").item.json.grounded` (boolean) = `true`: 答案是否有上下文依据。
- `$("Answer Question").item.json.evidence` (array) = `[…] (1)`: 来自上下文的证据引用。
- `$("Answer Question").item.json.unanswerable` (boolean) = `false`: 问题是否无法根据上下文回答。
- `$("Answer Question").item.json.reasoning` (string) = `"The policy section states the 30-day window."`: 简要说明答案是如何得出的。
- `$("Answer Question").item.json.raw` (null) = `null` (编辑器不提示)
- `$("Answer Question").item.json.port` (string) = `"answered"` (编辑器不提示)


## 工作原理

通过 LLM 基于你传入的 `context` 回答 `question`，返回答案及其置信度、是否有依据和引用证据。当模型表示上下文中没有答案时，路由到 `unanswerable`。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 将传入条目与解析后的配置合并（配置键优先），并从合并结果中读取输入。
3. 必须提供 `question` 和 `context`。数组形式的 `context` 会以空行拼接。
4. 若设置了 `knowledge_resource_id`，会在 `--- Supplementary Reference ---` 之后追加该资源内容。
5. 构建系统提示词：`strict_grounding`（默认 `true`）时模型只能依据上下文回答；否则可以使用通用知识，但必须设置 `grounded: false`。
6. 通过后端使用 `llm_provider_id` 记录调用 LLM。`invocation_mode: "sync"`（默认）等待完整响应；`"stream"` 通过 SSE 读取并拼接分块。
7. 解析 JSON 响应（温度 0）；若含 `unanswerable: true` 则路由到 `unanswerable`，否则路由到 `answered`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-qa-policy",
  "label": "Answer from policy",
  "operator_slug": "ai.qa",
  "operator_version": "1.0.0",
  "config": {
    "llm_provider_id": "<llm_provider_id>",
    "invocation_mode": "sync",
    "strict_grounding": true,
    "language": "en"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "answered",
  "data": {
    "answer": "Returns are accepted within 30 days of delivery.",
    "confidence": 0.92,
    "grounded": true,
    "evidence": [
      {
        "text": "Customers may return items within 30 days of delivery."
      }
    ],
    "unanswerable": false,
    "reasoning": "The policy section states the 30-day window.",
    "raw": null,
    "port": "answered"
  }
}
```

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

### `answered`

模型未将问题标记为无法回答。worker 在顶层返回各字段，因此 `data` 中还包含 `raw` 和 `port`。

```json
{
  "answer": "Returns are accepted within 30 days of delivery.",
  "confidence": 0.92,
  "grounded": true,
  "evidence": [
    {
      "text": "Customers may return items within 30 days of delivery."
    }
  ],
  "unanswerable": false,
  "reasoning": "The policy section states the 30-day window.",
  "raw": null,
  "port": "answered"
}
```

### `unanswerable`

模型返回了 `unanswerable: true`。结构相同。

```json
{
  "answer": "",
  "confidence": 0,
  "grounded": false,
  "evidence": [],
  "unanswerable": true,
  "reasoning": "The context does not mention shipping costs.",
  "raw": null,
  "port": "unanswerable"
}
```

### `error`

校验、LLM 调用或解析失败。`data` 为 `{ error }`；解析失败时还会附带包含模型文本的 `raw_content`。

```json
{
  "error": "Failed to parse QA result from LLM output.",
  "raw_content": "I think the answer is 30 days."
}
```

## 代码中的行为

- `llm_provider_id`: 虽然 schema 未将其标为必填，但运行时必须提供。它是 LLM 提供方记录的 id；后端据此解析端点、部署和凭据。
- `strict_grounding`: 只影响提示词。代码不会检查 `grounded` 或 `confidence`；路由仅取决于模型返回的 `unanswerable` 标志。
- `knowledge_resource_id`: 如果无法加载知识资源，只会记录失败，节点会在没有它的情况下继续执行。
- `timeout_ms`: `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing 'question'` | `error` | 传入条目中没有 `question`。 |
| `Missing 'context'` | `error` | 传入条目中没有 `context`。 |
| `Failed to parse QA result from LLM output.` | `error` | 响应中没有 JSON 对象。`data.raw_content` 中保存了该文本。 |
| `[AiQa] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | 节点缺少 `llm_provider_id`。请在节点配置中选择一个 LLM 提供方；旧的 `model_id` 键不再被接受。 |
| `LLM Invocation Error: <backend message>` | `error` | 后端拒绝了调用（提供方记录不存在或未启用、提供方错误、凭据问题）。请检查提供方记录。 |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | 在 `sync` 模式下无法连接后端，或后端未返回任何内容。 |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | 在 `stream` 模式下，`timeout_ms` 内没有收到任何分块。 |

## 说明与限制

- 契约中声明的输入 `metadata` 未被使用。
- `context` 没有大小限制：所有内容在一条消息中发送，请控制在模型窗口范围内。
- 模型响应在去除 Markdown 代码块标记后按 JSON 解析；若失败，则解析第一个 `{` 与最后一个 `}` 之间的文本。
- 输入字段从传入条目（`$json`）读取。节点配置中同名的键（可以是表达式）优先于输入。
- `timeout_ms` 仅在 `stream` 模式下生效，表示分块之间允许的空闲时间（默认 600000）。在 `sync` 模式下只会记录到日志，后端请求本身没有超时。
- 在 `stream` 模式下，此节点设置的温度不会转发给提供方，且 `raw` 为 `null`。
- 引擎不会对此节点应用 `execution.retryOnFail`、`maxTries`、`waitBetweenTries` 或 `continueOnFail`。请通过连接 `error` 端口处理失败。


## 契约（JSON Schema）

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

```json
{
  "slug": "ai.qa",
  "name": "Answer Question",
  "category": "ai",
  "version": "1.0.0",
  "description": "Grounded question answering from provided context.\n\nThis operator answers a question strictly from the supplied context, with evidence citations and confidence scoring. In strict grounding mode, it refuses to answer when the context does not contain sufficient information.\n\n**Capabilities**\n- Answers questions based exclusively on provided context documents.\n- Returns evidence citations linking the answer to source material.\n- Detects unanswerable questions and routes them to a dedicated port.\n- Supports supplementary knowledge resources for additional reference.\n- Provides confidence scores and grounding assessment for every answer.\n\n**Use Cases**\n- Q&A over internal documentation, policies, or knowledge bases.\n- Grounded customer support answers from product documentation.\n- Compliance verification against policy documents.\n- Extracting specific answers from contracts or legal documents.",
  "capabilities": [
    "ai",
    "nlp",
    "qa",
    "grounding"
  ],
  "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
      },
      "strict_grounding": {
        "type": "boolean",
        "title": "Strict Grounding",
        "description": "Only answer from provided context. Refuse if answer not in context.",
        "default": true
      },
      "language": {
        "type": "string",
        "title": "Language",
        "description": "Output language code (e.g., \"en\", \"es\").",
        "default": "en"
      },
      "knowledge_resource_id": {
        "type": "string",
        "title": "Knowledge Resource",
        "description": "Optional knowledge resource ID for supplementary reference material."
      },
      "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": {
      "question": {
        "type": "string",
        "description": "The question to answer."
      },
      "context": {
        "type": [
          "string",
          "array"
        ],
        "description": "Context document(s) to answer from. String or array of strings."
      },
      "metadata": {
        "type": "object",
        "description": "Optional metadata about the context sources."
      }
    },
    "required": [
      "question",
      "context"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "answer": {
        "type": "string",
        "description": "The generated answer."
      },
      "confidence": {
        "type": "number",
        "description": "Confidence score (0-1)."
      },
      "grounded": {
        "type": "boolean",
        "description": "Whether the answer is grounded in context."
      },
      "evidence": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "text": {
              "type": "string",
              "description": "Relevant quote from context."
            },
            "source": {
              "type": "string",
              "description": "Source identifier (if available)."
            }
          }
        },
        "description": "Evidence citations from the context."
      },
      "unanswerable": {
        "type": "boolean",
        "description": "Whether the question could not be answered from context."
      },
      "reasoning": {
        "type": "string",
        "description": "Brief explanation of how the answer was derived."
      }
    }
  },
  "ports": [
    {
      "port_id": "answered",
      "label": "Answered",
      "is_default": true
    },
    {
      "port_id": "unanswerable",
      "label": "Unanswerable"
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "qa",
    "grounding",
    "nlp"
  ],
  "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
    },
    "strict_grounding": {
      "type": "boolean",
      "title": "Strict Grounding",
      "description": "Only answer from provided context. Refuse if answer not in context.",
      "default": true
    },
    "language": {
      "type": "string",
      "title": "Language",
      "description": "Output language code (e.g., \"en\", \"es\").",
      "default": "en"
    },
    "knowledge_resource_id": {
      "type": "string",
      "title": "Knowledge Resource",
      "description": "Optional knowledge resource ID for supplementary reference material."
    },
    "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": {
    "question": {
      "type": "string",
      "description": "The question to answer."
    },
    "context": {
      "type": [
        "string",
        "array"
      ],
      "description": "Context document(s) to answer from. String or array of strings."
    },
    "metadata": {
      "type": "object",
      "description": "Optional metadata about the context sources."
    }
  },
  "required": [
    "question",
    "context"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "answer": {
      "type": "string",
      "description": "The generated answer."
    },
    "confidence": {
      "type": "number",
      "description": "Confidence score (0-1)."
    },
    "grounded": {
      "type": "boolean",
      "description": "Whether the answer is grounded in context."
    },
    "evidence": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "text": {
            "type": "string",
            "description": "Relevant quote from context."
          },
          "source": {
            "type": "string",
            "description": "Source identifier (if available)."
          }
        }
      },
      "description": "Evidence citations from the context."
    },
    "unanswerable": {
      "type": "boolean",
      "description": "Whether the question could not be answered from context."
    },
    "reasoning": {
      "type": "string",
      "description": "Brief explanation of how the answer was derived."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "answered",
    "label": "Answered",
    "is_default": true
  },
  {
    "port_id": "unanswerable",
    "label": "Unanswerable"
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
