# Answer Question

> Grounded question answering from provided context.

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

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

Grounded question answering from provided context.

This 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.

**Capabilities**
- Answers questions based exclusively on provided context documents.
- Returns evidence citations linking the answer to source material.
- Detects unanswerable questions and routes them to a dedicated port.
- Supports supplementary knowledge resources for additional reference.
- Provides confidence scores and grounding assessment for every answer.

**Use Cases**
- Q&A over internal documentation, policies, or knowledge bases.
- Grounded customer support answers from product documentation.
- Compliance verification against policy documents.
- Extracting specific answers from contracts or legal documents.

## 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.
- `strict_grounding` (boolean, optional): Only answer from provided context. Refuse if answer not in context. Default: `true`.
- `language` (string, optional): Output language code (e.g., "en", "es"). Default: `en`.
- `knowledge_resource_id` (string, optional): Optional knowledge resource ID for supplementary reference material.

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

- `answered` (default): Answered
- `unanswerable`: Unanswerable
- `error`: Error

## Input contract

- `question` (string, required): The question to answer.
- `context` (string | array, required): Context document(s) to answer from. String or array of strings.
- `metadata` (object, optional): Optional metadata about the context sources.

## Output contract

- `answer` (string, optional): The generated answer.
- `confidence` (number, optional): Confidence score (0-1).
- `grounded` (boolean, optional): Whether the answer is grounded in context.
- `evidence` (array<object>, optional): Evidence citations from the context.
- `unanswerable` (boolean, optional): Whether the question could not be answered from context.
- `reasoning` (string, optional): Brief explanation of how the answer was derived.

## In expressions

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

- `$("Answer Question").item.json.answer` (string) = `"Returns are accepted within 30 days of deliv…"`: The generated answer.
- `$("Answer Question").item.json.confidence` (number) = `0.92`: Confidence score (0-1).
- `$("Answer Question").item.json.grounded` (boolean) = `true`: Whether the answer is grounded in context.
- `$("Answer Question").item.json.evidence` (array) = `[…] (1)`: Evidence citations from the context.
- `$("Answer Question").item.json.unanswerable` (boolean) = `false`: Whether the question could not be answered from context.
- `$("Answer Question").item.json.reasoning` (string) = `"The policy section states the 30-day window."`: Brief explanation of how the answer was derived.
- `$("Answer Question").item.json.raw` (null) = `null` (Not suggested by the editor)
- `$("Answer Question").item.json.port` (string) = `"answered"` (Not suggested by the editor)


## How it works

Answers a `question` from the `context` you pass in, through the LLM, and returns the answer with confidence, grounding and quoted evidence. It routes to `unanswerable` when the model says the context does not contain the answer.

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 `question` and `context`. An array `context` is joined with blank lines.
4. If `knowledge_resource_id` is set, appends the resource content after `--- Supplementary Reference ---`.
5. Builds the system prompt: with `strict_grounding` (default `true`) the model may answer only from the context; otherwise it may use general knowledge and must set `grounded: false`.
6. 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.
7. Parses the JSON answer (temperature 0) and routes to `unanswerable` when it has `unanswerable: true`, otherwise to `answered`.

## In a workflow

### Node

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

## Output ports (behaviour in the code)

### `answered`

The model did not mark the question as unanswerable. The worker returns the fields at the top level, so `data` also includes `raw` and `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`

The model returned `unanswerable: true`. Same shape.

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

### `error`

Validation, the LLM call or parsing failed. `data` is `{ error }`; a parsing failure adds `raw_content` with the model text.

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

## 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.
- `strict_grounding`: Only changes the prompt. The code does not check `grounded` or `confidence`; routing depends only on the model’s `unanswerable` flag.
- `knowledge_resource_id`: If the knowledge resource cannot be loaded, the failure is only logged and the node continues without it.
- `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 'question'` | `error` | The incoming item has no `question`. |
| `Missing 'context'` | `error` | The incoming item has no `context`. |
| `Failed to parse QA result from LLM output.` | `error` | The answer had no JSON object. `data.raw_content` holds the text. |
| `[AiQa] 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

- The input `metadata` declared in the contract is not used.
- There is no size limit on `context`: everything is sent in one message, so keep it within the model window.
- 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.
- `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.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"
  }
]
```
