{"id":32722088,"url":"https://github.com/augustepoiroux/leaninteract","last_synced_at":"2025-11-02T21:03:02.412Z","repository":{"id":276110107,"uuid":"927984638","full_name":"augustepoiroux/LeanInteract","owner":"augustepoiroux","description":"LeanInteract: A Python Interface for Lean 4","archived":false,"fork":false,"pushed_at":"2025-10-22T12:30:51.000Z","size":2584,"stargazers_count":62,"open_issues_count":3,"forks_count":8,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-10-22T14:24:15.410Z","etag":null,"topics":["autoformalization","lean4","machine-learning","python","theorem-proving"],"latest_commit_sha":null,"homepage":"https://augustepoiroux.github.io/LeanInteract/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/augustepoiroux.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"docs/contributing.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-02-05T21:35:17.000Z","updated_at":"2025-10-22T12:30:55.000Z","dependencies_parsed_at":"2025-04-03T12:23:26.070Z","dependency_job_id":"dea5ca0b-2656-4d8f-8027-5301568ac069","html_url":"https://github.com/augustepoiroux/LeanInteract","commit_stats":null,"previous_names":["augustepoiroux/leaninteract"],"tags_count":34,"template":false,"template_full_name":null,"purl":"pkg:github/augustepoiroux/LeanInteract","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/augustepoiroux%2FLeanInteract","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/augustepoiroux%2FLeanInteract/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/augustepoiroux%2FLeanInteract/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/augustepoiroux%2FLeanInteract/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/augustepoiroux","download_url":"https://codeload.github.com/augustepoiroux/LeanInteract/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/augustepoiroux%2FLeanInteract/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":282357609,"owners_count":26656057,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-11-02T02:00:06.609Z","response_time":64,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["autoformalization","lean4","machine-learning","python","theorem-proving"],"created_at":"2025-11-02T21:01:31.184Z","updated_at":"2025-11-02T21:03:02.405Z","avatar_url":"https://github.com/augustepoiroux.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# LeanInteract\n\n[![Documentation](https://img.shields.io/badge/docs-latest-purple.svg)](https://augustepoiroux.github.io/LeanInteract/)\n[![PyPI version](https://img.shields.io/pypi/v/lean-interact.svg)](https://pypi.org/project/lean-interact/)\n[![PyPI downloads](https://img.shields.io/pepy/dt/lean-interact.svg)](https://pypi.org/project/lean-interact/)\n[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n**LeanInteract** is a Python package designed to seamlessly interact with Lean 4 through the [Lean REPL](https://github.com/leanprover-community/repl).\n\nCheck the [documentation](https://augustepoiroux.github.io/LeanInteract/) for detailed usage and examples.\n\n## Key Features\n\n- **🔗 Interactivity**: Execute Lean code and files directly from Python.\n- **🚀 Ease of Use**: LeanInteract abstracts the complexities of Lean setup and interaction.\n- **💻 Cross-platform**: Works on Windows, macOS, and Linux operating systems.\n- **🔧 Compatibility**: Supports all Lean versions between `v4.8.0-rc1` and `v4.25.0-rc2`.\n  - We backport the latest features of Lean REPL to older versions of Lean (see [fork](https://github.com/augustepoiroux/repl)).\n- **📦 Temporary Projects**: Easily instantiate temporary Lean environments.\n  - Useful for experimenting with benchmarks depending on [Mathlib](https://github.com/leanprover-community/mathlib4) like [ProofNet#](https://huggingface.co/datasets/PAug/ProofNetSharp) and [MiniF2F](https://github.com/yangky11/miniF2F-lean4).\n- **🧾 Data extraction (new in v0.9.0)**: Extract declarations and info trees for analysis and dataset building.\n- **⚡ Incremental + Parallel elaboration (new in v0.9.0)**: Automatically reuse partial computations from previous commands, and enable `Elab.async` for faster processing.\n\n## Table of Contents\n\n- [Key Features](#key-features)\n- [Installation and Setup](#installation-and-setup)\n- [Script examples](#script-examples)\n- [Usage](#usage)\n  - [Basic example](#basic-example)\n  - [Tactic mode](#tactic-mode)\n  - [Custom Lean configuration](#custom-lean-configuration)\n    - [Specific Lean version](#specific-lean-version)\n    - [Existing Lean projects](#existing-lean-projects)\n    - [Temporary project with dependencies](#temporary-project-with-dependencies)\n    - [Fine-grained temporary project](#fine-grained-temporary-project)\n- [Available Queries](#available-queries)\n  - [Command](#command)\n  - [FileCommand](#filecommand)\n  - [ProofStep](#proofstep)\n  - [Environment Pickling](#environment-pickling)\n  - [ProofState Pickling](#proofstate-pickling)\n- [Helper Commands](#helper-commands)\n- [Advanced options](#advanced-options)\n  - [LeanServer](#leanserver)\n  - [Custom Lean REPL](#custom-lean-repl)\n- [Similar tools](#similar-tools)\n- [Troubleshooting](#troubleshooting)\n- [Citation](#citation)\n- [License](#license)\n\n## Installation and Setup\n\nYou can install the LeanInteract package using the following command:\n\n```bash\npip install lean-interact\n```\n\nRequirements:\n\n- Python \u003e= 3.10\n- git\n- [Lean 4](https://leanprover-community.github.io/get_started.html)\n  - **Tip:** use the cross-platform `install-lean` command from LeanInteract.\n  - Your `elan` version should be at least `4.0.0` (`elan --version`).\n\n## Script examples\n\nIn the [`examples`](examples) directory, you will find a few scripts demonstrating how to use LeanInteract.\n\n- [`proof_generation_and_autoformalization.py`](examples/proof_generation_and_autoformalization.py): use [DeepSeek-Prover-V1.5](https://arxiv.org/abs/2408.08152), [Goedel-Prover](https://goedel-lm.github.io/), and other models on [MiniF2F](https://github.com/yangky11/miniF2F-lean4) and [ProofNet#](https://huggingface.co/datasets/PAug/ProofNetSharp) benchmarks.\n- [`beq_plus.py`](examples/beq_plus.py): run the autoformalization [BEq+](https://arxiv.org/abs/2406.07222) metric on the [ProofNetVerif](https://huggingface.co/datasets/PAug/ProofNetVerif) benchmark.\n- [`type_check.py`](examples/type_check.py): optimize type checking using environment states.\n\n## Usage\n\nFull documentation is available [here](https://augustepoiroux.github.io/LeanInteract/).\n\n### Basic example\n\nThe following code will use the default Lean version (latest available):\n\n```python\nfrom lean_interact import LeanREPLConfig, LeanServer, Command\n\nconfig = LeanREPLConfig(verbose=True) # download and build Lean REPL\nserver = LeanServer(config) # start Lean REPL\nserver.run(Command(cmd=\"theorem ex (n : Nat) : n = 5 → n = 5 := id\"))\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eOutput\u003c/summary\u003e\n\n```python\nCommandResponse(\n  env=0,\n  messages=[\n    Message(start_pos=Pos(line=1, column=0),\n    end_pos=Pos(line=1, column=42),\n    data='Goals accomplished!',\n    severity='info')\n  ]\n)\n```\n\n\u003c/details\u003e\n\nIterate on the environment state:\n\n```python\nserver.run(Command(cmd=\"example (x : Nat) : x = 5 → x = 5 := by exact ex x\", env=0))\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eOutput\u003c/summary\u003e\n\n```python\nCommandResponse(\n  env=1,\n  messages=[\n    Message(start_pos=Pos(line=1, column=0),\n    end_pos=Pos(line=1, column=50),\n    data='Goals accomplished!',\n    severity='info')\n  ]\n)\n```\n\n\u003c/details\u003e\n\nSee [Available Queries](#available-queries) for all available commands.\n\n\u003e [!NOTE]\n\u003e 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.\n\n### Tactic mode\n\n\u003e [!WARNING]\n\u003e 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](https://github.com/leanprover-community/repl/issues).\n\nFirst, let's run a command to create a theorem with a `sorry` proof:\n\n```python\nserver.run(Command(cmd=\"theorem ex (n : Nat) : n = 5 → n = 5 := sorry\"))\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eOutput\u003c/summary\u003e\n\n```python\nCommandResponse(\n  sorries=[\n    Sorry(start_pos=Pos(line=1, column=40),\n    end_pos=Pos(line=1, column=45),\n    goal='n : Nat\\n⊢ n = 5 → n = 5',\n    proof_state=0)\n  ],\n  env=0,\n  messages=[\n    Message(start_pos=Pos(line=1, column=8),\n    end_pos=Pos(line=1, column=10),\n    data=\"declaration uses 'sorry'\",\n    severity='warning')\n  ]\n)\n```\n\n\u003c/details\u003e\n\nYou can then iterate on the proof state by executing tactics:\n\n```python\nfrom lean_interact import ProofStep\n\nserver.run(ProofStep(tactic=\"intro h\", proof_state=0))\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eOutput\u003c/summary\u003e\n\n```python\nProofStepResponse(\n  proof_state=1,\n  goals=['n : Nat\\nh : n = 5\\n⊢ n = 5'],\n  proof_status='Incomplete: open goals remain'\n)\n```\n\n\u003c/details\u003e\n\n```python\nserver.run(ProofStep(tactic=\"exact h\", proof_state=1))\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eOutput\u003c/summary\u003e\n\n```python\nProofStepResponse(proof_state=2, goals=[], proof_status='Completed')\n```\n\n\u003c/details\u003e\n\nor by directly running the entire proof:\n\n```python\nserver.run(ProofStep(tactic=\"(\\nintro h\\nexact h)\", proof_state=0))\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eOutput\u003c/summary\u003e\n\n```python\nProofStepResponse(proof_state=3, goals=[], proof_status='Completed')\n```\n\n\u003c/details\u003e\n\n### Custom Lean configuration\n\n#### Specific Lean version\n\n```python\nconfig = LeanREPLConfig(lean_version=\"v4.8.0\")\n```\n\n#### Existing Lean projects\n\n```python\n# Local project\nproject = LocalProject(directory=\"path/to/your/project\")\nconfig = LeanREPLConfig(project=project)\n```\n\nor\n\n```python\n# Git project\nproject = GitProject(url=\"https://github.com/yangky11/lean4-example\", rev=\"main\")\nconfig = LeanREPLConfig(project=project)\n```\n\nYou can then use `run` as usual:\n\n```python\nfrom lean_interact import FileCommand\n\nserver = LeanServer(config)\nserver.run(FileCommand(path=\"file.lean\"))\n```\n\n\u003e [!IMPORTANT]\n\u003e Ensure the project can be *successfully* built with `lake build` before using LeanInteract.\n\n#### Temporary project with dependencies\n\n```python\nfrom lean_interact import TempRequireProject, LeanRequire\n\nproject = TempRequireProject(\n    lean_version=\"v4.8.0\", \n    require=[LeanRequire(\n        name=\"mathlib\",\n        git=\"https://github.com/leanprover-community/mathlib4.git\",\n        rev=\"v4.8.0\"\n    )]\n)\nconfig = LeanREPLConfig(project=project)\n```\n\nMathlib being a frequent requirement, a shortcut is available:\n\n```python\nproject = TempRequireProject(lean_version=\"v4.8.0\", require=\"mathlib\")\nconfig = LeanREPLConfig(project=project)\n```\n\nYou can then use Mathlib as follows:\n\n```python\nserver = LeanServer(config)\nserver.run(Command(cmd=\"\"\"import Mathlib\ntheorem ex_mathlib (x : ℝ) (y : ℚ) :\n  ( Irrational x ) -\u003e Irrational ( x + y ) := sorry\"\"\"))\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eOutput\u003c/summary\u003e\n\n```python\nCommandResponse(\n  env=0,\n  sorries=[\n    Sorry(end_pos=Pos(line=3, column=51),\n    goal='x : ℝ\\ny : ℚ\\n⊢ Irrational x → Irrational (x + ↑y)',\n    start_pos=Pos(line=3, column=46),\n    proof_state=0)\n  ],\n  messages=[\n    Message(end_pos=Pos(line=2, column=18),\n    data=\"declaration uses 'sorry'\",\n    start_pos=Pos(line=2, column=8),\n    severity='warning')\n  ]\n)\n```\n\n\u003c/details\u003e\n\n\u003e [!NOTE]\n\u003e\n\u003e - Mathlib is a large library and may take some time to download and build.\n\u003e - A separate cache is used for each unique set of dependencies.\n\n#### Fine-grained temporary project\n\nFor more control over the temporary project, you can use `TemporaryProject` to specify the content of the lakefile (`.lean` format).\n\n```python\nfrom lean_interact import TemporaryProject\n\nproject = TemporaryProject(\n    lean_version=\"v4.18.0\", \n    content=\"\"\"\nimport Lake\nopen Lake DSL\n\npackage \"dummy\" where\n  version := v!\"0.1.0\"\n\n@[default_target]\nlean_exe \"dummy\" where\n  root := `Main\n\nrequire mathlib from git\n  \"https://github.com/leanprover-community/mathlib4.git\" @ \"v4.18.0\"\n\"\"\"\n)\nconfig = LeanREPLConfig(project=project)\n```\n\n## Available Queries\n\nLeanInteract 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](src/lean_interact/interface.py) for more details.\n\n### Command\n\nExecute Lean code directly:\n\n```python\nfrom lean_interact import Command\n\n# Execute a simple theorem\nresponse = server.run(Command(cmd=\"theorem ex (n : Nat) : n = 5 → n = 5 := id\"))\n\n# Execute with options to get tactics information\nresponse = server.run(Command(cmd=\"theorem ex (n : Nat) : n = 5 → n = 5 := by simp\", all_tactics=True))\n\n# Continue in the same environment\nresponse = server.run(Command(cmd=\"#check ex\", env=response.env))\n```\n\n### FileCommand\n\nProcess Lean files:\n\n```python\nfrom lean_interact import FileCommand\n\n# Execute a Lean file\nresponse = server.run(FileCommand(path=\"myfile.lean\"))\n\n# With options for more information\nresponse = server.run(FileCommand(path=\"myfile.lean\", root_goals=True))\n```\n\nExtract Lean declarations while processing a file:\n\n```python\nresponse = server.run(FileCommand(path=\"myfile.lean\", declarations=True))\nfor d in response.declarations:\n  print(d.full_name, d.signature.pp)\n```\n\n### ProofStep\n\nWork with proofs step by step using tactics:\n\n```python\nfrom lean_interact import ProofStep\n\n# Apply a tactic to a proof state\nresponse = server.run(ProofStep(proof_state=0, tactic=\"intro h\"))\n\n# Apply multiple tactics at once\nresponse = server.run(ProofStep(proof_state=0, tactic=\"(\\nintro h\\nexact h)\"))\n```\n\n### Environment Pickling\n\nSave and restore environment states:\n\n```python\nfrom lean_interact import PickleEnvironment, UnpickleEnvironment\n\n# Save an environment\nserver.run(PickleEnvironment(env=1, pickle_to=\"env_state.olean\"))\n\n# Restore an environment\nserver.run(UnpickleEnvironment(unpickle_env_from=\"env_state.olean\"))\n```\n\n### ProofState Pickling\n\nSave and restore proof states:\n\n```python\nfrom lean_interact import PickleProofState, UnpickleProofState\n\n# Save a proof state\nserver.run(PickleProofState(proof_state=2, pickle_to=\"proof_state.olean\"))\n\n# Restore a proof state\nserver.run(UnpickleProofState(unpickle_proof_state_from=\"proof_state.olean\", env=1))\n```\n\n## Helper Commands\n\nThe following commands are installed with LeanInteract:\n\n- `install-lean`: Installs Lean 4 version manager `elan`.\n- `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.\n\n## Advanced options\n\n### LeanServer\n\nTwo versions of Lean servers are available:\n\n- **`LeanServer`**: A wrapper around Lean REPL. Interact with it using the `run` method.\n- **`AutoLeanServer`**: An experimental subclass of `LeanServer` automatically recovering from some crashes and timeouts. It also monitors memory usage to limit *out of memory* issues in multiprocessing contexts. Use the `add_to_session_cache` attribute available in the `run` method to prevent selected environment/proof states to be cleared.\n\n\u003e [!TIP]\n\u003e\n\u003e - To run multiple requests in parallel, we recommend using multiprocessing with one global `LeanREPLConfig` instance, and one `AutoLeanServer` instance per process.\n\u003e - Make sure to instantiate `LeanREPLConfig` before starting the processes to avoid conflicts during Lean REPL's download and build.\n\u003e - While `AutoLeanServer` can 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.\n\n### Custom Lean REPL\n\nTo use a forked Lean REPL project, specify the git repository using the `repl_git` parameter in the `LeanREPLConfig` and the target revision using the `repl_rev` parameter. For example:\n\n```python\nconfig = LeanREPLConfig(repl_rev=\"v4.21.0-rc3\", repl_git=\"https://github.com/leanprover-community/repl\", verbose=True)\n```\n\n\u003e [!WARNING]\n\u003e\n\u003e Custom REPL implementations may have interfaces that are incompatible with LeanInteract's standard commands. If you encounter incompatibility issues, you can use the `run_dict` method from `LeanServer` to communicate directly with the REPL using the raw JSON protocol:\n\u003e\n\u003e ```python\n\u003e # Using run_dict instead of the standard commands\n\u003e result = server.run_dict({\"cmd\": \"your_command_here\"})\n\u003e ```\n\nFor assistance, feel free to contact [us](mailto:auguste.poiroux@epfl.ch).\n\n## Similar tools\n\nWe recommend checking out these tools:\n\n- **[PyPantograph](https://github.com/lenianiva/PyPantograph)**: Based on Pantograph, offering more options for proof interactions than Lean REPL.\n- **[LeanDojo](https://github.com/lean-dojo/LeanDojo)**: Parses Lean projects to create datasets and interact with proof states.\n- **[itp-interface](https://github.com/trishullab/itp-interface)**: A Python interface for interacting and extracting data from Lean 4 and Coq.\n- **[leanclient](https://github.com/oOo0oOo/leanclient)**: Interact with the Lean LSP server.\n\nLeanInteract is inspired by **[pylean](https://github.com/zhangir-azerbayev/repl)** and **[lean4_jupyter](https://github.com/utensil/lean4_jupyter)**.\n\n## Troubleshooting\n\nCommon issues and their solutions:\n\n1. **Out of memory errors**: Reduce parallel processing or increase system memory. Alternatively, use `AutoLeanServer` with conservative memory settings\n\n2. **Timeout errors**: Currently, `LeanServer` simply stops the Lean REPL if a command times out. Use `AutoLeanServer` for automatic recovery.\n\n3. **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.\n\n4. **`Failed during Lean project setup: Command '['lake', 'update']' returned non-zero exit status 1.`**: This error may occur if your `elan` version is outdated (i.e. \u003c 4.0.0). To resolve this, update `elan` using `elan self update` or read the documentation [here](https://leanprover-community.github.io/get_started.html).\n\n5. **(Windows) Path too long error**: Windows has a maximum path length limitation of 260 characters.\nIf you get an error similar to the following one, you are likely affected by this problem:\n\n    ```\n    error: external command 'git' exited with code 128\n    ERROR    Failed during Lean project setup: Command '['lake', 'update']' returned non-zero exit status 1.\n    ```\n\n    To resolve this, you can enable long paths in Windows 10 and later versions. For more information, refer to the [Microsoft documentation](https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation).\n    Alternatively, run the following command in a terminal with administrator privileges:\n\n    ```bash\n    New-ItemProperty -Path \"HKLM:\\SYSTEM\\CurrentControlSet\\Control\\FileSystem\" -Name LongPathsEnabled -Value 1 -PropertyType DWord -Force\n    git config --system core.longpaths true\n    ```\n\n## Citation\n\nIf you use LeanInteract in your research, please cite it as follows:\n\n```bibtex\n@software{leaninteract,\n  author = {Poiroux, Auguste and Kuncak, Viktor and Bosselut, Antoine},\n  title = {LeanInteract: A Python Interface for Lean 4},\n  url = {https://github.com/augustepoiroux/LeanInteract},\n  year = {2025}\n}\n```\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faugustepoiroux%2Fleaninteract","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faugustepoiroux%2Fleaninteract","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faugustepoiroux%2Fleaninteract/lists"}