A Guide to Setting Up a Local Lean 4 Proof Automation Environment for Mathematical Research
TuBrief 편집팀
2026년 8월 10일
0
Computing/Software원본 영상을 바탕으로 AI의 도움을 받아 작성했습니다. 원본 영상이 기준입니다.
커뮤니티의 다른 글
댓글 (0)
Log in to leave a comment
아직 작성된 글이 없습니다
원본 영상을 바탕으로 AI의 도움을 받아 작성했습니다. 원본 영상이 기준입니다.
Log in to leave a comment
아직 작성된 글이 없습니다
When deploying large-scale mathematical problem-solving systems on a lab desktop, high-level architecture overviews are of no help. Here, we outline the practical steps to directly set up a local Lean 4 pipeline and integrate long-running multi-agents to fully automate mathematical exploration tasks.
Manually installing Lean 4 in a development environment and relying on the VS Code Language Server Protocol causes severe bottlenecks during large-scale AI verification. If Mathlib4 precompiled binaries are not cached, local CPUs will directly recompile hundreds of thousands of theorems, taking over 180 minutes just to set up the environment. To handle code verification requests at a rate of dozens per second or more, you must switch to a FastAPI-based Kimina Lean Server pipeline.
The specific setup procedure to shorten the setup time for long-running mathematical problem verification tasks from 180 minutes to under 20 minutes is as follows:
lean-toolchain file at the project root directory. Enter the text leanprover/lean4:v4.15.0 inside the file.lakefile.lean configuration file and specify the Mathlib4 package and the repl repository that handles stdio-based JSON input/output.`lean
import Lake
open Lake DSL
package «proof_automation» {
}
require mathlib from git
"https://github.com/leanprover-community/mathlib4.git" @ "v4.15.0"
require repl from git
"https://github.com/leanprover-community/repl.git" @ "main"
@[default_target]
lean_lib «ProofAutomation» {
}
`
`bash
lake update
lake exe cache get
lake build
`
Once this task is complete, precompiled caches are received instantly, preparing a fully functional local REPL execution environment in under 20 minutes, capable of simultaneously verifying up to 50 proof clauses per second.
Attempting to prove complex theorems with a single large language model prompt call causes it to lose sub-goals or enter infinite loops as the context grows longer. You must apply a hierarchical Directed Acyclic Graph (DAG) architecture that separates roles into a root agent responsible for problem partitioning and sub-agents executing isolated sub-tactics.
Adopting the JSON format as the agent communication specification and isolating scopes to pass prompts can reduce API token consumption by more than 40 percent. The JSON schema used when calling sub-agents is as follows:
`json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "SubAgentProofTask",
"type": "object",
"properties": {
"task_id": { "type": "string" },
"target_hypothesis": { "type": "string" },
"current_goal_state": { "type": "string" },
"previous_failure_logs": {
"type": "array",
"items": {
"type": "object",
"properties": {
"attempted_tactic": { "type": "string" },
"error_message": { "type": "string" }
}
}
},
"sub_goal_target": { "type": "string" }
},
"required": ["task_id", "target_hypothesis", "current_goal_state", "sub_goal_target"]
}
`
The step-by-step control sequence to block infinite loops caused by agent hallucinations and operate a stable hierarchical structure is as follows:
proofState string returned from the Lean REPL using the SHA-256 algorithm and store it in memory. If the same state hash is detected repeatedly 3 or more times, prune that exploration branch.SIGKILL signal upon exceedance to immediately reorganize the REPL process.In proof exploration tasks lasting several hours, sending the entire conversation history to the backend API with every request causes token usage to skyrocket. You must build a caching layer based on LeanExplore and Vector DB, and control input token overhead by summarizing and reflecting already verified intermediate tactic results into the memory graph in the form of auxiliary lemmas.
Register the environment identifier of the REPL session on the backend server to eliminate repetitive import Mathlib statements at the top of prompts. This alone can instantly reduce input tokens by 50 to 70 percent. The implementation procedure for the control pipeline to prevent API cost explosions caused by budget limit excesses is as follows:
.leanflow/cache/ and .leanflow/workflow-state/ paths in the local environment directory.CostMonitor module to additively track tokens and costs consumed during API calls in real-time.`python
import sys
import json
import logging
class CostMonitor:
def init(self, max_budget_usd: float, token_cost_per_1k: float):
self.max_budget = max_budget_usd
self.cost_per_1k = token_cost_per_1k
self.total_tokens_used = 0
self.current_cost = 0.0
def track_usage(self, prompt_tokens: int, completion_tokens: int):
tokens_in_call = prompt_tokens + completion_tokens
self.total_tokens_used += tokens_in_call
self.current_cost += (tokens_in_call / 1000.0) * self.cost_per_1k
logging.info(f"[TELEMETRY] Used Tokens: {tokens_in_call} | Total Cost: ${self.current_cost:.4f}")
if self.current_cost >= self.max_budget:
self.trigger_safe_pause()
def trigger_safe_pause(self):
logging.warning("[WARNING] Target budget threshold reached. Pausing workflow...")
with open(".leanflow/workflow-state/checkpoint.json", "w") as f:
json.dump({"status": "PAUSED_BUDGET_EXCEEDED", "tokens": self.total_tokens_used}, f)
sys.exit(0)
`
The approach where AI agents generate code and humans manually review errors is a fatal bottleneck for overall research. JSON-parsed data such as syntax errors, type mismatches, and unresolved goals output by the Lean REPL compiler must be directly connected as feedback input to the agent.
How the auto-correction control loop—which replaces manual reviews and improves research speed by more than 2x—operates is as follows:
`python
def parse_lean_repl_output(repl_response_json: str):
data = json.loads(repl_response_json)
parsed_diagnostics = {
"has_error": False,
"errors": [],
"open_sorries": []
}
if "messages" in data:
for msg in data["messages"]:
if msg.get("severity") == "error":
parsed_diagnostics["has_error"] = True
parsed_diagnostics["errors бассейны" if False else "errors"].append({
"line": msg["pos"]["line"],
"column": msg["pos"]["column"],
"data": msg["data"]
})
if "sorries" in data:
for sorry in data["sorries"]:
parsed_diagnostics["open_sorries"].append({
"goal": sorry["goal"],
"proof_state": sorry["proofState"],
"line": sorry["pos"]["line"]
})
return parsed_diagnostics
`
Fully verified clean code passes through doc-gen4 and paperproof conversion tools, automatically generating logical graph visualizations and LaTeX contexts ready for immediate insertion into research papers.
`bash
lake build LeanAutomation:docs
lean-graph extract --input Main.lean --output proof_dependency.json
`