File size: 9,375 Bytes
747f607 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | """Orquestador LangGraph: PLAN→RETRIEVE→GENERATE→FORMALIZE→VERIFY→(ADVANCE|CRITIQUE)→DONE|FAIL.
Regla del Crítico (corrige el solapamiento k=kmax / k>=kmax de la ec. 7):
k = intentos fallidos del subobjetivo actual (tope k_max)
r = replanificaciones usadas en el problema (tope r_max)
REPLAN solo si r < r_max; RETRY solo si k < k_max; si no, FAIL.
"""
import time
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from .contracts import (Action, RunConfig, PlannerIn, PlannerOut, Lemma,
GeneratorIn, FormalizerIn, VerifierOut, CriticIn, CriticOut)
from .agents import (assemble_code, build_critic_text, build_formalizer_text, build_generator_text,
build_rag_queries, parse_critic, parse_subgoals)
from .llm import LLM
from .logger import JsonlLogger
from .retriever import retrieve_many
class GraphState(TypedDict, total=False):
problem_id: str
problem: str
subgoals: list[str]
i: int # índice del subobjetivo actual
k: int # intentos fallidos en el subobjetivo actual
r: int # replanificaciones usadas
retrieved: list[dict]
sketch: str
lean_code: str
verdict: bool
trace: str
hint: str
action: str
history: list[dict]
proofs: list[str] # pruebas Lean aceptadas por subobjetivo
llm_calls: int
statement_lean: str # modo teorema completo: enunciado fijo del dataset (si falta, modo por subobjetivos)
status: str # RUNNING | DONE | FAIL
failure_reason: str
def build_graph(llm: LLM, retriever, verifier, cfg: RunConfig, logger: JsonlLogger,
prompts: dict[str, str] | None = None):
"""retriever(subgoal, k) -> list[Lemma-like dict]; verifier(lean_code) -> (bool, trace)."""
P = prompts or {}
whole = lambda s: bool(s.get("statement_lean")) # modo teorema completo
def _llm(agent: str, text: str):
t0 = time.perf_counter()
res = llm.call(agent, P.get(agent, "{x}").format(x=text))
return res, int((time.perf_counter() - t0) * 1000)
def _log(state, agent, decision, res=None, ms=0):
logger.log(problem_id=state["problem_id"], config=cfg.name, agent=agent,
subgoal=state.get("i", 0), attempt=state.get("k", 0), decision=decision,
tokens_in=getattr(res, "tokens_in", 0), tokens_out=getattr(res, "tokens_out", 0),
latency_ms=ms)
def plan(state: GraphState):
if not cfg.use_planner:
_log(state, "planner", "skipped")
return {"subgoals": [state["problem"]], "i": 0, "k": 0, "proofs": []}
inp = PlannerIn(problem=state["problem"])
hint = f"\nHINT: {state['hint']}" if state.get("hint") else ""
res, ms = _llm("planner", inp.problem + hint)
steps = parse_subgoals(res.text)
out = PlannerOut(subgoals=steps or [state["problem"]]) # respuesta inservible: un solo paso
_log(state, "planner", f"{len(out.subgoals)} subgoals" if steps else "fallback", res, ms)
return {"subgoals": out.subgoals, "i": 0, "k": 0, "proofs": [],
"llm_calls": state.get("llm_calls", 0) + 1}
def retrieve(state: GraphState):
if not cfg.use_rag:
_log(state, "retriever", "skipped")
return {"retrieved": []}
t0 = time.perf_counter()
if whole(state): # cada paso del plan es una consulta corta
raw = retrieve_many(retriever, build_rag_queries(state, cfg.rag_query), cfg.top_k)
else:
raw = retriever(state["subgoals"][state["i"]], cfg.top_k)
lemmas = [Lemma(**{k: l[k] for k in ("name", "signature", "score") if k in l}).model_dump() for l in raw]
_log(state, "retriever", f"{len(lemmas)} lemmas", ms=int((time.perf_counter() - t0) * 1000))
return {"retrieved": lemmas}
def generate(state: GraphState):
if whole(state):
text = build_generator_text(state)
else:
text = GeneratorIn(subgoal=state["subgoals"][state["i"]], lemmas=state.get("retrieved", []),
hint=state.get("hint")).model_dump_json()
res, ms = _llm("generator", text)
_log(state, "generator", "sketch", res, ms)
return {"sketch": res.text, "llm_calls": state.get("llm_calls", 0) + 1}
def formalize(state: GraphState):
if whole(state):
res, ms = _llm("formalizer", build_formalizer_text(state))
code = assemble_code(state["statement_lean"], res.text)
else:
inp = FormalizerIn(sketch=state["sketch"], lemmas=state.get("retrieved", []))
res, ms = _llm("formalizer", inp.model_dump_json())
code = res.text
_log(state, "formalizer", "lean_code" if code else "no_tactics", res, ms)
return {"lean_code": code, "llm_calls": state.get("llm_calls", 0) + 1}
def verify(state: GraphState):
t0 = time.perf_counter()
if not state["lean_code"]: # nada que verificar: fallo de formalización, no de infraestructura
ok, trace = False, "formalization_failure: el modelo no produjo tácticas"
elif whole(state):
ok, trace = verifier(state["lean_code"], state["statement_lean"]) # compara con el enunciado del dataset
else:
ok, trace = verifier(state["lean_code"])
out = VerifierOut(verdict=ok, trace=trace)
_log(state, "verifier", "accepted" if ok else "rejected", ms=int((time.perf_counter() - t0) * 1000))
hist = state.get("history", []) + [{"i": state["i"], "k": state.get("k", 0),
"verdict": ok, "trace": trace[:2000]}]
return {"verdict": out.verdict, "trace": out.trace, "history": hist}
def advance(state: GraphState):
nxt = len(state["subgoals"]) if whole(state) else state["i"] + 1 # teorema completo: una sola verificación
return {"proofs": state.get("proofs", []) + [state["lean_code"]], "i": nxt, "k": 0, "hint": ""}
def critique(state: GraphState):
k = state.get("k", 0) + 1
r = state.get("r", 0)
calls = state.get("llm_calls", 0)
if not cfg.use_critic: # ablación: un intento, sin análisis
_log(state, "critic", "FAIL (critic off)")
return {"action": Action.FAIL.value, "k": k, "failure_reason": "critic_disabled"}
if calls >= cfg.max_llm_calls:
_log(state, "critic", "FAIL (budget)")
return {"action": Action.FAIL.value, "k": k, "failure_reason": "llm_budget"}
text = (build_critic_text({**state, "k": k - 1}) if whole(state)
else CriticIn(trace=state["trace"], history=state["history"]).model_dump_json())
res, ms = _llm("critic", text)
act, hint = parse_critic(res.text) # tolerante: nunca rompe la corrida
proposed = CriticOut(action=Action(act), hint=hint)
if proposed.action == Action.REPLAN and r < cfg.r_max:
action, upd = Action.REPLAN, {"r": r + 1, "k": 0}
elif proposed.action in (Action.RETRY, Action.REPLAN) and k < cfg.k_max:
action, upd = Action.RETRY, {"k": k}
else:
action, upd = Action.FAIL, {"k": k, "failure_reason": "retries_exhausted"}
_log(state, "critic", action.value, res, ms)
return {**upd, "action": action.value, "hint": proposed.hint, "llm_calls": calls + 1}
def done(state: GraphState):
_log(state, "orchestrator", "DONE")
return {"status": "DONE"}
def fail(state: GraphState):
_log(state, "orchestrator", f"FAIL:{state.get('failure_reason', '')}")
return {"status": "FAIL"}
after_verify = lambda s: "advance" if s["verdict"] else "critique"
after_advance = lambda s: "retrieve" if s["i"] < len(s["subgoals"]) else "done"
after_critic = lambda s: {"RETRY": "generate", "REPLAN": "plan", "FAIL": "fail"}[s["action"]]
g = StateGraph(GraphState)
for name, fn in [("plan", plan), ("retrieve", retrieve), ("generate", generate),
("formalize", formalize), ("verify", verify), ("advance", advance),
("critique", critique), ("done", done), ("fail", fail)]:
g.add_node(name, fn)
g.add_edge(START, "plan")
g.add_edge("plan", "retrieve")
g.add_edge("retrieve", "generate")
g.add_edge("generate", "formalize")
g.add_edge("formalize", "verify")
g.add_conditional_edges("verify", after_verify, {"advance": "advance", "critique": "critique"})
g.add_conditional_edges("advance", after_advance, {"retrieve": "retrieve", "done": "done"})
g.add_conditional_edges("critique", after_critic, {"generate": "generate", "plan": "plan", "fail": "fail"})
g.add_edge("done", END)
g.add_edge("fail", END)
return g.compile()
def run_problem(graph, problem_id: str, problem: str, statement_lean: str | None = None) -> GraphState:
init = {"problem_id": problem_id, "problem": problem, "history": [],
"llm_calls": 0, "status": "RUNNING", "r": 0, "k": 0, "i": 0}
if statement_lean:
init["statement_lean"] = statement_lean
return graph.invoke(init, config={"recursion_limit": 200})
|