"""The question->DSL translator (phase 3b) — the LLM at the INPUT boundary. One structured-output call (the MASK/EXTRACT class): the question + the store's relation vocabulary in; a typed DSL term out; VALIDATED BEFORE EXECUTION — a mistranslation is an invalid term caught deterministically, never a wrong answer. The model never sees the goal, the evidence, or the answer; it sees the question and which relations exist. If the question is not translatable, the call returns None and the caller falls back to the judge path, honestly. """ from __future__ import annotations from typing import Any import dspy from .prover import validate_query class TranslateToDSL(dspy.Signature): """You are the TRANSLATE-TO-QUERY step of a reasoning machine. Turn the question into ONE typed query over the knowledge graph, choosing from the given relations ONLY. The machine executes the query deterministically. Shapes you may build: - lookup: {"subject": "", "rel_any": [""], "bind": ""} - a second lookup with {"subject": "?x", "rel_any": [...], "bind": "", "same_value_as": ""} — anyone holding the SAME value (e.g. the same office) as the first lookup bound - filters: {"open_now": [""]} (the fact holds now), {"before": ["", ""]} (a's window ended before b's started), {"neq_value": ["", ""]} (a bound name differs from the literal — e.g. exclude the queried entity) - select: "all" (every binding — the question asks for the SET) or "latest_end" (the most recent one that ended) If the question cannot be expressed with these shapes, return an empty query ({} or null) — never force a wrong translation.""" question: str = dspy.InputField() relations: str = dspy.InputField( desc="the relations that exist in the graph, comma separated") query: dict | None = dspy.OutputField( desc="the typed query as JSON, or null when not expressible") _KNOWN_FILTERS = {"open_now", "before", "neq_value"} _KNOWN_SELECTS = {"all", "latest_end"} def translate(expert, question: str, relations: list[str]) -> dict | None: """One call: question + relation vocabulary -> a validated DSL term. None when the model declines or the proposal is invalid — the caller falls back to the judge path (the prover never executes an invalid term; code decides, the model proposes). """ pred = expert.translate_dspy(question=question, relations=", ".join(sorted(set(relations)))) q = getattr(pred, "query", None) if not q: return None ok, _reason = validate_query(q) return q if ok else None