LeanInteract is a Python package designed to seamlessly interact with Lean 4 through the Lean REPL.
- 🔗 Interactivity: Execute Lean code and files directly from Python.
- 🚀 Ease of Use: LeanInteract abstracts the complexities of Lean setup and interaction.
- 💻 Cross-platform: Works on Windows, macOS, and Linux operating systems.
- 🔧 Compatibility: Supports all Lean versions between
v4.7.0-rc1andv4.19.0-rc2.- We backport the latest features of Lean REPL to older versions of Lean.
- 📦 Temporary Projects: Easily instantiate temporary Lean environments.
- Key Features
- Installation and Setup
- Script examples
- Usage
- Available Queries
- Helper Commands
- Advanced options
- Similar tools
- Troubleshooting
- Contributing
- Citation
- License
You can install the LeanInteract package using the following command:
pip install lean-interactRequirements:
- Python >= 3.10
- git
- Lean 4 (Tip: use the
install-leancommand from LeanInteract)
In the examples directory, you will find a few scripts demonstrating how to use LeanInteract.
proof_generation_and_autoformalization.py: use DeepSeek-Prover-V1.5, Goedel-Prover, and other models on MiniF2F and ProofNet# benchmarks.beq_plus.py: run the autoformalization BEq+ metric on the ProofNetVerif benchmark.type_check.py: optimize type checking using environment states.
The following code will use the default Lean version (latest available):
from lean_interact import LeanREPLConfig, LeanServer, Command
config = LeanREPLConfig(verbose=True) # download and build Lean REPL
server = LeanServer(config) # start Lean REPL
server.run(Command(cmd="theorem ex (n : Nat) : n = 5 → n = 5 := id"))Output
CommandResponse(
env=0,
messages=[
Message(start_pos=Pos(line=1, column=0),
end_pos=Pos(line=1, column=42),
data='Goals accomplished!',
severity='info')
]
)Iterate on the environment state:
server.run(Command(cmd="example (x : Nat) : x = 5 → x = 5 := by exact ex x", env=0))Output
CommandResponse(
env=1,
messages=[
Message(start_pos=Pos(line=1, column=0),
end_pos=Pos(line=1, column=50),
data='Goals accomplished!',
severity='info')
]
)See Available Queries for all available commands.
Note
The initial invocation of LeanREPLConfig might take some time as it downloads and builds Lean REPL. Future executions with identical parameters will be significantly quicker due to caching.
Warning
This feature is experimental in Lean REPL and may not work as expected: some valid proofs might be incorrectly rejected. Please report any issues you encounter here.
First, let's run a command to create a theorem with a sorry proof:
server.run(Command(cmd="theorem ex (n : Nat) : n = 5 → n = 5 := sorry"))Output
CommandResponse(
sorries=[
Sorry(start_pos=Pos(line=1, column=40),
end_pos=Pos(line=1, column=45),
goal='n : Nat\n⊢ n = 5 → n = 5',
proof_state=0)
],
env=0,
messages=[
Message(start_pos=Pos(line=1, column=8),
end_pos=Pos(line=1, column=10),
data="declaration uses 'sorry'",
severity='warning')
]
)You can then iterate on the proof state by executing tactics:
from lean_interact import ProofStep
server.run(ProofStep(tactic="intro h", proof_state=0))Output
ProofStepResponse(
proof_state=1,
goals=['n : Nat\nh : n = 5\n⊢ n = 5'],
proof_status='Incomplete: open goals remain'
)server.run(ProofStep(tactic="exact h", proof_state=1))Output
ProofStepResponse(proof_state=2, goals=[], proof_status='Completed')or by directly running the entire proof:
server.run(ProofStep(tactic="(\nintro h\nexact h)", proof_state=0))Output
ProofStepResponse(proof_state=3, goals=[], proof_status='Completed')config = LeanREPLConfig(lean_version="v4.7.0")config = LeanREPLConfig(project=LocalProject("path/to/your/project"))or
config = LeanREPLConfig(project=GitProject("https://github.com/yangky11/lean4-example"))You can then use run as usual:
from lean_interact import FileCommand
server = LeanServer(config)
server.run(FileCommand(path="file.lean"))Important
Ensure the project can be successfully built with lake build before using LeanInteract.
from lean_interact import TempRequireProject
config = LeanREPLConfig(lean_version="v4.7.0", project=TempRequireProject([LeanRequire(
name="mathlib",
git="https://github.com/leanprover-community/mathlib4.git",
rev="v4.7.0"
)]))Mathlib being a frequent requirement, a shortcut is available:
config = LeanREPLConfig(lean_version="v4.7.0", project=TempRequireProject("mathlib"))You can then use Mathlib as follows:
server = LeanServer(config)
server.run(Command(cmd="""import Mathlib
theorem ex_mathlib (x : ℝ) (y : ℚ) :
( Irrational x ) -> Irrational ( x + y ) := sorry"""))Output
CommandResponse(
env=0,
sorries=[
Sorry(end_pos=Pos(line=3, column=51),
goal='x : ℝ\ny : ℚ\n⊢ Irrational x → Irrational (x + ↑y)',
start_pos=Pos(line=3, column=46),
proof_state=0)
],
messages=[
Message(end_pos=Pos(line=2, column=18),
data="declaration uses 'sorry'",
start_pos=Pos(line=2, column=8),
severity='warning')
]
)Note
- Mathlib is a large library and may take some time to download and build.
- A separate cache is used for each unique set of dependencies.
For more control over the temporary project, you can use TemporaryProject to specify the content of the lakefile (.lean format).
from lean_interact import TemporaryProject
config = LeanREPLConfig(lean_version="v4.18.0", project=TemporaryProject("""
import Lake
open Lake DSL
package "dummy" where
version := v!"0.1.0"
@[default_target]
lean_exe "dummy" where
root := `Main
require mathlib from git
"https://github.com/leanprover-community/mathlib4.git" @ "v4.18.0"
"""))LeanInteract supports various types of queries to interact with the Lean REPL. We briefly describe them in this section. You can check the file interface.py for more details.
Execute Lean code directly:
from lean_interact import Command
# Execute a simple theorem
response = server.run(Command(cmd="theorem ex (n : Nat) : n = 5 → n = 5 := id"))
# Execute with options to get tactics information
response = server.run(Command(cmd="theorem ex (n : Nat) : n = 5 → n = 5 := by simp", all_tactics=True))
# Continue in the same environment
response = server.run(Command(cmd="#check ex", env=response.env))Process Lean files:
from lean_interact import FileCommand
# Execute a Lean file
response = server.run(FileCommand(path="myfile.lean"))
# With options for more information
response = server.run(FileCommand(path="myfile.lean", root_goals=True))Work with proofs step by step using tactics:
from lean_interact import ProofStep
# Apply a tactic to a proof state
response = server.run(ProofStep(proof_state=0, tactic="intro h"))
# Apply multiple tactics at once
response = server.run(ProofStep(proof_state=0, tactic="(\nintro h\nexact h)"))Save and restore environment states:
from lean_interact import PickleEnvironment, UnpickleEnvironment
# Save an environment
server.run(PickleEnvironment(env=1, pickle_to="env_state.olean"))
# Restore an environment
server.run(UnpickleEnvironment(unpickle_env_from="env_state.olean"))Save and restore proof states:
from lean_interact import PickleProofState, UnpickleProofState
# Save a proof state
server.run(PickleProofState(proof_state=2, pickle_to="proof_state.olean"))
# Restore a proof state
server.run(UnpickleProofState(unpickle_proof_state_from="proof_state.olean", env=1))The following commands are installed with LeanInteract:
install-lean: Installs Lean 4 version managerelan.clear-lean-cache: Removes all Lean REPL versions and temporary projects in the package cache. This can help resolve some issues. If it does, please open an issue.
Two versions of Lean servers are available:
LeanServer: A wrapper around Lean REPL. Interact with it using therunmethod.AutoLeanServer: An experimental subclass ofLeanServerautomatically recovering from some crashes and timeouts. It also monitors memory usage to limit out of memory issues in multiprocessing contexts. Use theadd_to_session_cacheattribute available in therunmethod to prevent selected environment/proof states to be cleared.
Tip
- To run multiple requests in parallel, we recommend using multiprocessing with one global
LeanREPLConfiginstance, and oneAutoLeanServerinstance per process. - Make sure to instantiate
LeanREPLConfigbefore starting the processes to avoid conflicts during Lean REPL's download and build. - While
AutoLeanServercan help prevent crashes, it is not a complete solution. If you encounter crashes, consider reducing the number of parallel processes or increasing the memory available to your system.
To use a forked Lean REPL project, specify the git repository using the repl_git parameter in the LeanREPLConfig. Your fork should have a similar versioning format to https://github.com/augustepoiroux/repl (i.e. having a branch with commits for each Lean version). For assistance, feel free to contact us.
We recommend checking out these tools:
- PyPantograph: Based on Pantograph, offering more options for proof interactions than Lean REPL.
- LeanDojo: Parses Lean projects to create datasets and interact with proof states.
- itp-interface: A Python interface for interacting and extracting data from Lean 4 and Coq.
- leanclient: Interact with the Lean LSP server.
LeanInteract is inspired by pylean and lean4_jupyter.
Common issues and their solutions:
-
Out of memory errors: Reduce parallel processing or increase system memory. Alternatively, use
AutoLeanServerwith conservative memory settings -
Timeout errors: Currently,
LeanServersimply stops the Lean REPL if a command times out. UseAutoLeanServerfor automatic recovery. -
Long waiting times during first run: This is expected as Lean REPL is being downloaded and built. Additionally, if you are importing Mathlib it will take even more time. Subsequent runs will be much faster.
-
(Windows) Path too long error: Windows has a maximum path length limitation of 260 characters. If you get an error similar to the following one, you are likely affected by this problem:
error: external command 'git' exited with code 128 ERROR Failed during Lean project setup: Command '['lake', 'update']' returned non-zero exit status 1.To resolve this, you can enable long paths in Windows 10 and later versions. For more information, refer to the Microsoft documentation. Alternatively, run the following command in a terminal with administrator privileges:
New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" -Name LongPathsEnabled -Value 1 -PropertyType DWord -Force git config --system core.longpaths true
Contributions are welcome! Here's how you can help:
- Fork the repository
- Create a feature branch:
git checkout -b feature-name - Commit your changes:
git commit -am 'Add new feature' - Push to the branch:
git push origin feature-name - Submit a pull request
If you use LeanInteract in your research, please cite it as follows:
@software{leaninteract,
author = {Poiroux, Auguste and Kuncak, Viktor and Bosselut, Antoine},
title = {LeanInteract: A Python Interface for Lean 4},
url = {https://github.com/augustepoiroux/lean-interact},
year = {2025}
}This project is licensed under the MIT License - see the LICENSE file for details.