# Answer Question

> Respuesta a preguntas fundamentada en el contexto proporcionado.

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

- Slug: `ai.qa`
- Familia: IA
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Respuesta a preguntas fundamentada en el contexto proporcionado.

Este operador responde una pregunta únicamente a partir del contexto suministrado, con citas de evidencia y una puntuación de confianza. En el modo de fundamentación estricta, se niega a responder cuando el contexto no contiene información suficiente.

**Capacidades**
- Responde preguntas basándose exclusivamente en los documentos de contexto proporcionados.
- Devuelve citas de evidencia que vinculan la respuesta con el material de origen.
- Detecta las preguntas sin respuesta y las dirige a un puerto dedicado.
- Admite recursos de conocimiento complementarios como referencia adicional.
- Ofrece puntuaciones de confianza y una valoración de la fundamentación de cada respuesta.

**Casos de uso**
- Preguntas y respuestas sobre documentación interna, políticas o bases de conocimiento.
- Respuestas de soporte al cliente fundamentadas en la documentación del producto.
- Verificación del cumplimiento frente a documentos de políticas.
- Extracción de respuestas concretas de contratos o documentos jurídicos.

## Configuración

- `llm_provider_id` (string, opcional): El `id` de un registro `LlmProviderModel` (p. ej. `wf-llm-provider-*`). El orquestador delega en el backend: `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` en modo sync, o `POST /chat/conversation/execute/stream-ephemeral` (SSE) en modo stream. El backend resuelve endpoint + api-key + deployment a partir del registro y enruta al adaptador correspondiente.
- `invocation_mode` (string, opcional): Transporte de la llamada al LLM. `sync` se bloquea hasta recibir la respuesta completa. `stream` consume los tokens mediante SSE (necesario para generaciones largas). Predeterminado: `sync`. Por defecto: `sync`. Valores permitidos: `sync`, `stream`.
- `timeout_ms` (integer, opcional): Tiempo máximo de espera para que termine la invocación (o tiempo máximo de inactividad entre fragmentos en modo stream). Predeterminado: 30000 en sync, 600000 en stream.
- `strict_grounding` (boolean, opcional): Responde solo a partir del contexto proporcionado. Se niega si la respuesta no está en el contexto. Por defecto: `true`.
- `language` (string, opcional): Código del idioma de salida (p. ej., "en", "es"). Por defecto: `en`.
- `knowledge_resource_id` (string, opcional): ID opcional de un recurso de conocimiento con material de referencia complementario.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `answered` (por defecto): Answered
- `unanswerable`: Unanswerable
- `error`: Error

## Contrato de entrada

- `question` (string, obligatorio): La pregunta que se responde.
- `context` (string | array, obligatorio): Documento(s) de contexto a partir de los cuales se responde. Cadena o arreglo de cadenas.
- `metadata` (object, opcional): Metadatos opcionales sobre las fuentes del contexto.

## Contrato de salida

- `answer` (string, opcional): La respuesta generada.
- `confidence` (number, opcional): Puntuación de confianza (0-1).
- `grounded` (boolean, opcional): Si la respuesta está fundamentada en el contexto.
- `evidence` (array<object>, opcional): Citas de evidencia tomadas del contexto.
- `unanswerable` (boolean, opcional): Si la pregunta no se pudo responder a partir del contexto.
- `reasoning` (string, opcional): Breve explicación de cómo se obtuvo la respuesta.

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Answer Question").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Answer Question`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `answered`, según la salida que muestra Puertos.

- `$("Answer Question").item.json.answer` (string) = `"Returns are accepted within 30 days of deliv…"`: La respuesta generada.
- `$("Answer Question").item.json.confidence` (number) = `0.92`: Puntuación de confianza (0-1).
- `$("Answer Question").item.json.grounded` (boolean) = `true`: Si la respuesta está fundamentada en el contexto.
- `$("Answer Question").item.json.evidence` (array) = `[…] (1)`: Citas de evidencia tomadas del contexto.
- `$("Answer Question").item.json.unanswerable` (boolean) = `false`: Si la pregunta no se pudo responder a partir del contexto.
- `$("Answer Question").item.json.reasoning` (string) = `"The policy section states the 30-day window."`: Breve explicación de cómo se obtuvo la respuesta.
- `$("Answer Question").item.json.raw` (null) = `null` (El editor no la sugiere)
- `$("Answer Question").item.json.port` (string) = `"answered"` (El editor no la sugiere)


## Cómo funciona

Responde a una `question` a partir del `context` que le pasas, mediante el LLM, y devuelve la respuesta con su confianza, si está fundamentada y las citas de evidencia. Enruta a `unanswerable` cuando el modelo indica que el contexto no contiene la respuesta.

1. Resuelve la configuración del nodo: las expresiones de las claves de configuración se evalúan contra la ejecución; el ítem entrante se usa tal cual.
2. Combina el ítem entrante con la configuración resuelta (las claves de configuración tienen prioridad) y lee las entradas del resultado.
3. Exige `question` y `context`. Un `context` en forma de arreglo se une con líneas en blanco.
4. Si se define `knowledge_resource_id`, añade el contenido del recurso tras `--- Supplementary Reference ---`.
5. Construye el prompt de sistema: con `strict_grounding` (predeterminado `true`) el modelo solo puede responder desde el contexto; si no, puede usar conocimiento general y debe marcar `grounded: false`.
6. Llama al LLM a través del backend con el registro `llm_provider_id`. `invocation_mode: "sync"` (predeterminado) espera la respuesta completa; `"stream"` la lee por SSE y une los fragmentos.
7. Interpreta la respuesta JSON (temperatura 0) y enruta a `unanswerable` cuando trae `unanswerable: true`; si no, a `answered`.

## En un workflow

### Nodo

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

## Puertos de salida (comportamiento en el código)

### `answered`

El modelo no marcó la pregunta como sin respuesta. El worker devuelve los campos en el nivel superior, así que `data` incluye también `raw` y `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`

El modelo devolvió `unanswerable: true`. Misma forma.

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

### `error`

Falló la validación, la llamada al LLM o la interpretación. `data` es `{ error }`; un fallo de interpretación añade `raw_content` con el texto del modelo.

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

## Comportamiento en el código

- `llm_provider_id`: Es obligatorio en ejecución aunque el esquema no lo marque como requerido. Es el id de un registro de proveedor LLM; el backend resuelve a partir de él el endpoint, el despliegue y las credenciales.
- `strict_grounding`: Solo cambia el prompt. El código no comprueba `grounded` ni `confidence`; el enrutamiento depende solo del indicador `unanswerable` del modelo.
- `knowledge_resource_id`: Si el recurso de conocimiento no se puede cargar, el fallo solo se registra y el nodo continúa sin él.
- `timeout_ms`: `timeout_ms` solo tiene efecto en modo `stream`, como el tiempo de inactividad permitido entre fragmentos (predeterminado 600000). En modo `sync` se registra en el log, pero la petición al backend no tiene tiempo límite.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Missing 'question'` | `error` | El ítem entrante no tiene `question`. |
| `Missing 'context'` | `error` | El ítem entrante no tiene `context`. |
| `Failed to parse QA result from LLM output.` | `error` | La respuesta no tenía un objeto JSON. `data.raw_content` contiene el texto. |
| `[AiQa] Missing 'llm_provider_id' in node config (LlmProviderModel.id, e.g. 'wf-llm-provider-*'). …` | `error` | El nodo no tiene `llm_provider_id`. Elige un proveedor LLM en la configuración del nodo; la clave antigua `model_id` no se acepta. |
| `LLM Invocation Error: <backend message>` | `error` | El backend rechazó la llamada (registro de proveedor desconocido o inactivo, error del proveedor, credenciales). Revisa el registro del proveedor. |
| `LLM Invocation Error: empty response from backend (<reason>).` | `error` | No se pudo contactar con el backend o no devolvió nada en modo `sync`. |
| `RemoteApiService.stream: idle timeout after <timeout_ms>ms` | `error` | En modo `stream` no llegó ningún fragmento dentro de `timeout_ms`. |

## Notas y límites

- El `metadata` de entrada declarado en el contrato no se usa.
- No hay límite de tamaño para `context`: todo se envía en un solo mensaje, así que mantenlo dentro de la ventana del modelo.
- La respuesta del modelo se interpreta como JSON tras quitar los bloques de código Markdown; si falla, se interpreta el texto entre la primera `{` y la última `}`.
- Los campos de entrada se leen del ítem entrante (`$json`). Una clave con el mismo nombre en la configuración del nodo, que puede ser una expresión, tiene prioridad sobre la entrada.
- `timeout_ms` solo tiene efecto en modo `stream`, como el tiempo de inactividad permitido entre fragmentos (predeterminado 600000). En modo `sync` se registra en el log, pero la petición al backend no tiene tiempo límite.
- En modo `stream` la temperatura que fija este nodo no se envía al proveedor, y `raw` es `null`.
- El motor no aplica `execution.retryOnFail`, `maxTries`, `waitBetweenTries` ni `continueOnFail` a este nodo. Gestiona los fallos conectando el puerto `error`.


## Contratos (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"
  }
]
```
