Search and contents

Playbook answer synthesis: wiring up point-of-use SOP lookup

This guide shows how to answer a natural-language question against a Node's own Playbook store, using PlaybookAnswerer from engine/playbook_answer.py. It is the way a Node answers a question from its Playbook.

PlaybookAnswerer is glue, not new infrastructure. It composes existing pieces:

  • RetrievalQualityGate (itself wrapping EmbeddingClient and EmbeddingStore) retrieves candidate chunks under a strong, broadened or incomplete policy.
  • InferenceClient.run_plan (plus its own merge callback) synthesizes one direct answer, using the free, open prompt asset engine/prompts/point_of_use_sop_lookup.md.

Where the chunks come from

A Node with a document_intake section fills its Playbook store itself. Each document a provider delivers is chunked by its type's strategy, embedded with its context and stored. PlaybookAnswerer retrieves from that store with no further step (see retrieval-ingestion-pipeline.md).

A deactivated document is not retrieved. The store is read by document, so there is no per-chunk retraction: a document is replaced whole, or deactivated.

1. Load and version-check the prompt asset

from engine.prompt_assets import assert_version, load_prompt_asset

asset = load_prompt_asset(Path("engine/prompts/point_of_use_sop_lookup.md"))
assert_version(asset, "0.1.0")

PlaybookAnswerer doesn't load or version-check the asset itself. This is the same "loading is the caller's concern" split that config_loader.py and inference_config.py use. Do it once at startup, not per question.

2. Build the answerer over an already-constructed gate

from engine.activity_log import ActivityLog
from engine.playbook_answer import PlaybookAnswerer
from engine.retrieval_gate import RetrievalQualityGate

gate = RetrievalQualityGate(
    embedding_client, embedding_store
)  # docs/operations/retrieval-quality-gate.md
answerer = PlaybookAnswerer(
    gate,
    inference_client,  # engine.inference.InferenceClient
    asset,
    inference_profile.budget,  # the same ModelBudgetProfile Token Budget plans batches against
    activity_log,  # engine.activity_log.ActivityLog - see "Activity Log wiring" below
    "MES",  # this Node's own node_type
    node_instance_id,  # this Node's own instance id
)

Every retrieval-quality and applicability decision belongs to the gate, not this module. That covers broadening a weak query, retrying, deciding a question is genuinely unanswerable, and pre-filtering by Applicability and ApplicabilityContext. PlaybookAnswerer only asks it for a RetrievalGateResult and reacts to outcome.

3. Ask a question

result = answerer.answer("What's the procedure for calibrating a torque wrench?")
result.answer  # a synthesized, direct answer - never the raw excerpt text
result.retrieved_chunks  # the RetrievedChunk hits the answer was built from
result.grounded  # False when the gate reports INCOMPLETE, or when inference is disabled

Pass context (an ApplicabilityContext) the same way you would to the gate directly. It is forwarded unchanged:

from engine.embedding_store import ApplicabilityContext

result = answerer.answer(
    question, context=ApplicabilityContext(product_id="widget-a", unit_number=4812)
)

result.answer is always model-synthesized text when grounded is True, whether the underlying retrieval fit in one call or had to paginate. run_plan's reduce-style merge (see merging-paginated-call-results.md) reconciles a split plan's per-batch partial answers into the one result.answer a human reads. It closes over inference_client to make that one further call. A caller never needs to check whether pagination happened.

Why grounded isn't "did the model find a real answer"

grounded=False fires in two cases:

  1. The gate reported INCOMPLETE (nothing survived even the broadened retry). The answer is NOT_ENOUGH_INFORMATION, without spending a model call, since there is nothing to synthesize from.
  2. The answerer was built with inference_enabled=False (Inference Operating Mode, see inference-operating-mode.md). answer() returns the hardcoded INFERENCE_DISABLED_MESSAGE with grounded=False and no retrieved chunks, without calling the gate or the embedding client at all. It logs the dedicated inference_disabled outcome rather than not_enough_information.

STRONG and BROADENED both set grounded=True, because a real model call happened either way.

If chunks were retrieved but the model itself judges them insufficient (the prompt asset's own instruction: "if the excerpts don't answer the question, say so rather than guessing"), grounded is still True. The model's answer is exactly what it should be, an honest "the Playbook doesn't cover this."

PlaybookAnswer only exposes the gate's proceed-or-don't split (grounded), not its full STRONG, BROADENED or INCOMPLETE outcome. A caller that needs to distinguish a confident answer from a broadened-retry one should call RetrievalQualityGate.retrieve directly instead of going through PlaybookAnswerer.

A failed synthesis raises, never returns an empty answer

A synthesis call that exhausts its own retry budget without succeeding never reaches grounded at all. answer() routes result.merged through engine.inference.raise_if_failed, which raises PlaybookAnswerError (engine.exceptions.PlaybookAnswerError) instead of returning grounded=True over empty or failed text.

InferenceClient.call and run_plan themselves never raise on a model or transport failure. Retries are exhausted and reported through CallOutcome.success instead, since whether that should abort a caller's larger job is caller policy, not the client's. PlaybookAnswerer is that caller, and its policy is fail-closed: a grounded=True answer is a promise that a real synthesis call actually produced it, so an exhausted retry budget must surface as a raised exception, not a confident-looking empty answer.

This covers both shapes result.merged can take:

  • A one-batch plan. merged is that batch's own CallOutcome (run_plan never invokes merge for a single batch), so a failed single call is caught directly.
  • A multi-batch plan. merged is _reduce_merge's own reduce-call outcome. _reduce_merge itself checks before making that call whether any underlying batch actually succeeded. If every batch failed, it reports failure directly without spending a further model call, rather than sending the model an empty "Partial answers:" section. The default validator only rejects a blank response, so a model asked to reconcile nothing could easily still produce plausible-looking text. That would otherwise report merged.success=True despite zero real synthesis input. It is the same "don't spend a model call when there's nothing to work with" policy INCOMPLETE retrieval already uses one step earlier in this flow.

Activity Log wiring

Every answer() call writes exactly one ActivityLogEntry, through the shared Activity Log wiring (see wiring-task-execution-to-activity-log.md). PlaybookAnswerer doesn't write it directly. It wraps its question and synthesis logic as a trivial one-step Prompt Chaining Task, purely so the run goes through that shared mechanism. This is the same composition dispatch_claimed_entry in engine/trigger_queue.py uses for the same reason.

  • trigger is always "point_of_use_question" and task_type is always "retrieval support" (engine.playbook_answer.TRIGGER and TASK_TYPE). They are fixed by this module, not supplied per call, so every caller logs under the same, correct vocabulary.
  • outcome is "grounded" or "not_enough_information" (PlaybookAnswer.grounded).
  • reference_ids maps each retrieved chunk's id to its source_document_id. An INCOMPLETE answer (nothing retrieved) logs reference_ids={}. A grounded answer, which a model wrote, adds prompt_name and prompt_version beside the chunks. Query which questions drew on a given SOP with activity_log.query(reference_id="torque-wrench-sop").
  • A raised PlaybookAnswerError (exhausted synthesis retries) still logs exactly one ActivityLogEntry. The exception path in log_task_execution, which every Task-shaped consumer in this codebase shares, writes a terminal error:-prefixed outcome before re-raising. The Activity Log therefore stays a complete record even of a failed run.

Pitfalls

  • The excerpts sent to the model carry source_document_id and document_type tags, not just raw text. _chunk_item prefixes each excerpt with [source: ..., type: ...] so the synthesis model can cite which SOP a claim came from (the prompt asset asks it to). Don't strip this if writing a replacement prompt asset that still wants citations.
  • A reduce-style merge costs a real, additional model call, the same pitfall merging-paginated-call-results.md calls out. It is only paid when retrieval returns enough chunks to split across batches, but budget for it.
  • PlaybookAnswerer takes an already-constructed gate and client. It builds nothing itself. There is no config-schema wiring inside this module. A Node Type assembles its own EmbeddingProfile, InferenceProfile, EmbeddingStore and RetrievalQualityGate the usual way (see retrieval-embedding-infra.md, retrieval-quality-gate.md and changing-the-inference-model.md) and hands the gate to PlaybookAnswerer.
  • activity_log, node_type and node_instance_id are required, not optional. There is no logging-disabled mode. Every answer() call is a real Task run per the Node Type Agreement's Activity Log facet, so a caller always supplies its own real identity, not a placeholder.

Release: v0.11.0