Skip to content

fsafey/rlm

 
 

Repository files navigation


Recursive Language Models (RLMs)

Full PaperBlogpostDocumentationRLM Minimal

Style Test

Paper Preview

Overview

Recursive Language Models (RLMs) are a task-agnostic inference paradigm for language models (LMs) to handle near-infinite length contexts by enabling the LM to programmatically examine, decompose, and recursively call itself over its input. RLMs replace the canonical llm.completion(prompt, model) call with a rlm.completion(prompt, model) call. RLMs offload the context as a variable in a REPL environment that the LM can interact with and launch sub-LM calls inside of.

This repository provides an extensible inference engine for using RLMs around standard API-based and local LLMs. The initial experiments and idea were proposed in a blogpost in 2025, with expanded results in an arXiv preprint.

Note

This repository contains inference code for RLMs with support for various sandbox environments. Open-source contributions are welcome. This repository is maintained by the authors of the paper from the MIT OASYS lab.

Quick Setup

You can try out RLMs quickly by installing from PyPi:

pip install rlms

The default RLM client uses a REPL environment that runs on the host process through Python exec calls. It uses the same virtual environment as the host process (i.e. it will have access to the same dependencies), but with some limitations in its available global modules.

Zero-Config: Claude CLI Backend

If you have Claude Code installed and authenticated, you can run RLMs with no API keys or environment variables — the claude_cli backend shells out to claude -p, inheriting your existing session:

from rlm import RLM

rlm = RLM(
    backend="claude_cli",
    backend_kwargs={"model_name": "claude-cli"},
    verbose=True,
)

print(rlm.completion("Print me the first 100 powers of two, each on a newline.").response)

Important

Environment isolation: The Claude CLI client automatically strips ANTHROPIC_API_KEY, CLAUDECODE, and all CLAUDE_CODE_* variables from the subprocess environment. This ensures claude -p uses the authenticated Max/Pro session rather than switching to API-key billing (which may have a separate, lower credit balance). Prompts are passed via stdin to avoid OS argument size limits with large inputs.

API-Based Backends

Alternatively, use any supported API backend by setting the appropriate environment variable:

from rlm import RLM

rlm = RLM(
    backend="openai",
    backend_kwargs={"model_name": "gpt-5-nano"},
    verbose=True,
)

print(rlm.completion("Print me the first 100 powers of two, each on a newline.").response)
Manual Setup

Set up the dependencies with uv (or your virtual environment of choice):

curl -LsSf https://astral.sh/uv/install.sh | sh
uv init && uv venv --python 3.12  # change version as needed
uv pip install -e .

This project includes a Makefile to simplify common tasks.

  • make install: Install base dependencies.
  • make check: Run linter, formatter, and tests.
  • make admin: Launch the admin workbench and open the RLM search page in your browser.
  • make admin-dev: Same as admin, but starts the RLM backend from this repo on :8092 so you can test local changes end-to-end.

To run a quick test:

make quickstart

REPL Environments

We support two types of REPL environments -- isolated, and non-isolated. Non-isolated environments (default) run code execution on the same machine as the RLM (e.g. through exec), which is pretty reasonable for some local low-risk tasks, like simple benchmarking, but can be problematic if the prompts or tool calls can interact with malicious users. Fully isolated environments used Cloud-based sandboxes (e.g. Prime Sandboxes, Modal Sandboxes) to run code generated by the RLM, ensuring completely isolation from the host process. Environments can be added, but we natively support the following: local (default), modal, prime.

rlm = RLM(
    environment="...", # "local", "docker", "modal", "prime"
    environment_kwargs={...},
)

Local Environments

The default local environment LocalREPL runs in the same process as the RLM itself, with specified global and local namespaces for minimal security. Using this REPL is generally safe, but should not be used for production settings. It also shares the same virtual environment (e.g. Conda or uv) as the host process.

Docker Docker (requires Docker installed)

We also support a Docker-based environment called DockerREPL that launches the REPL environment as a Docker image. By default, we use the python:3.11-slim image, but the user can specify custom images as well.

Isolated Environments

We support several different REPL environments that run on separate, cloud-based machines. Whenever a recursive sub-call is made in these instances, it is requested from the host process.

Modal Sandboxes Modal

To use Modal Sandboxes as the REPL environment, you need to install and authenticate your Modal account.

uv add modal  # add modal library
modal setup   # authenticate account

Prime Intellect Sandboxes Prime Intellect

Note

Prime Intellect Sandboxes are currently a beta feature. See the documentation for more information. We noticed slow runtimes when using these sandboxes, which is currently an open issue.

To use Prime Sandboxes, install the SDK and set your API key:

uv pip install -e ".[prime]"
export PRIME_API_KEY=...

Model Providers

Backend Key Notes
claude_cli None Shells out to claude -p via stdin. Zero config if Claude Code is authenticated. Strips ANTHROPIC_API_KEY from env to use session auth.
openai OPENAI_API_KEY GPT-4o, GPT-5, etc.
anthropic ANTHROPIC_API_KEY Claude via API.
gemini GOOGLE_API_KEY Gemini models.
portkey PORTKEY_API_KEY Gateway to any provider.
openrouter OPENROUTER_API_KEY Multi-provider router.
litellm varies Unified interface to 100+ models.
vllm None Local models via OpenAI-compatible server (base_url required).
azure_openai AZURE_OPENAI_API_KEY Azure-hosted OpenAI models.

To view or add support for more clients, start by looking at rlm/clients/.

Relevant Reading

If you use this code or repository in your research, please cite:

@misc{zhang2025recursivelanguagemodels,
      title={Recursive Language Models}, 
      author={Alex L. Zhang and Tim Kraska and Omar Khattab},
      year={2025},
      eprint={2512.24601},
      archivePrefix={arXiv},
      primaryClass={cs.AI},
      url={https://arxiv.org/abs/2512.24601}, 
}

Optional Debugging: Visualizing RLM Trajectories

We additionally provide a simple visualizer tool to examine and view the code, sub-LM, and root-LM calls of an RLM trajectory. To save log files (.jsonl) on every completion call that can be viewed in the visualizer, initialize the RLMLogger object and pass it into the RLM on initialization:

from rlm.logger import RLMLogger
from rlm import RLM

logger = RLMLogger(log_dir="./logs")
rlm = RLM(
    ...
    logger=logger
)

To run the visualizer locally, we use Node.js and shadcn/ui:

cd visualizer/
npm run dev        # default localhost:3001

You'll have the option to select saved .jsonl files

RLM Visualizer Example

About

RLM Agentic Search — agentic search engine using Recursive Language Models. The LM decides how to search, decompose queries, cross-reference, and synthesize answers with citations.

Resources

License

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors

Languages

  • Python 99.1%
  • Other 0.9%