Skip to content

Recursive Language Models (RLMs)

Skip →Tongyi DeepResearch
Agents stage 2 #6corefrontierpaperrubric 11/122025 · arXiv · ~30 min

Alex L. Zhang, Tim Kraska, Omar Khattab

Read first: CodeAct: Executable Code Actions Elicit Better LLM Agents · Effective context engineering for AI agents

Status

TL;DR. Don’t put a 10M-token input into the context window. Store it as a variable in a REPL, and let the LM write code to peek at it, grep it and split it. The LM then calls a sub-LM recursively (llm_query) on the pieces it chooses, and finally answers with FINAL(...). Long-context handling becomes an inference-time scaling problem that the model controls.

Why it matters for search people. An RLM is, in effect, an agent that programs its own retrieval and reading strategy over a corpus it was handed. On BrowseComp+ (1K), the 1,000 candidate documents are given directly as input, including the gold and evidence documents, and the RLM decides how to search them. That raises the question of when an index and a retriever beat an LM that writes its own search.

Recursive Language Model: the long prompt lives in a REPL, and the model calls itself on pieces The user's query reaches a root language model, but the very long context is not placed in its window by default. Instead it is stored as a variable inside a Python REPL. The root model writes code to peek at, search and split the variable, and calls sub-LMs through a query function on chosen snippets. Sub-LM answers come back as variables, and the root model eventually returns the final answer. The API allows sub-calls to recurse, but the default reported setup limits subcall depth to 1. user query + 10M-token context root LM reads selected excerpts, not the context by default code Python REPL (the environment) context = "…" # stored, not read print(context[:2000]) # peek hits = grep(context, r"…") parts = split(context, n=20) notes = [llm_query(q, p) for p in parts] sub-LMon part 1 sub-LMon part 2 … sub-LMon part n answers return as REPL variables recursive API; default reported setup limits subcall depth to 1 stdout (truncated) FINAL(answer)
The intended access pattern: the root LM does not read the full context but writes code against it and delegates pieces to sub-LMs. This is a design goal, not a guarantee for every input or trace.

Query: Which customer filed the most complaints about late delivery? The REPL holds context, a 2M-character support log the root LM never receives in full. Each turn the root writes code; the REPL runs it and returns truncated printed output.

# Root turn 1: peek at the size and the first lines.
print(len(context))
print(context[:300])

The REPL returns the length and 300 characters showing one ticket per line. Root window now holds: system prompt, query, this code, and that short output (a few hundred tokens of context, not 2M characters).

# Root turn 2: split into chunks and ask a sub-LM about each one.
chunks = [context[i:i + 400000] for i in range(0, len(context), 400000)]
answers = []
for chunk in chunks:
answers.append(llm_query("List customer IDs with late-delivery complaints, with counts:\n" + chunk))
print(answers[0][:200])

Each llm_query is a separate sub-LM call whose window holds the instruction plus one 400K-character chunk (about 100K tokens). Five such calls run here; their full replies sit in the answers variable, and the root sees only the first 200 characters it printed. At the paper’s default depth 1 the sub-LM is a plain LM, not another RLM.

# Root turn 3: merge the buffered answers with one more sub-call, then finish.
summary = llm_query("Merge these per-chunk counts and return the top customer ID:\n" + "\n".join(answers))
FINAL(summary)

Which tokens go where: the 2M characters enter only sub-LM windows, each chunk once; the root window holds code, truncated prints and the final short answer; the merge call sees the per-chunk replies, not the raw log. Cost therefore scales with how much of context the root chooses to send to sub-calls, which is why model-chosen fan-out gives the cost tails discussed below.

  • Latency and cost vary: recursion depth and fan-out are model-chosen and can blow up.
  • The authors fine-tuned an 8B model on teacher trajectories and ran a separate small RL study (Qwen3-4B). What does RL on RLM trajectories look like at scale?
  • The later Zhang and Khattab essay on harnesses as compositional generalizers (2026) reports 8–32× length generalization; that is the essay’s experiment, not a result of this paper.
  • How does an RLM compare with a classic retrieve-then-read pipeline over a proper index, at equal cost? This is a natural BrowseComp-Plus study.
  • Before: DSPy (LM calls as program modules), CodeAct, context compaction, MemGPT.
  • After / alongside: Weight-space programming, where the LM, working in a Python kernel, reads and edits weights instead of a prompt.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    An RLM receives a 10M-token context as a REPL variable. The root LM (GPT-5) splits it into chunks of 500K characters (assume about 4 characters per token) and calls a sub-LM (GPT-5-mini) once per chunk, buffering the answers. Estimate the number of sub-calls, the total sub-LM input tokens, and how much of the root LM's window is used. Then redo the count for a pairwise task that needs every pair of chunks seen together.

    What a strong answer covers
    • 10M tokens × 4 = 40M characters, and 40M / 500K = 80 chunks: about 80 sub-calls of roughly 125K tokens each.
    • Total sub-LM input ≈ 10M tokens plus a small per-call prompt, so the work is linear in context length.
    • The root sees only metadata about the variable, a truncated stdout prefix each turn, and the 80 short answers, so it stays far below GPT-5's 272K window no matter how long the input is.
    • Pairwise: 80 × 79 / 2 = 3,160 calls with 2 chunks each, about 790M input tokens. A better plan is to extract compact per-chunk features in one linear pass and then pair the features in code or in a few calls.
    • Sub-calls are blocking and sequential in the paper's implementation, so latency grows with the call count; parallel or asynchronous sub-calls are an obvious fix.
  2. Mechanism

    The RLM paper motivates offloading the prompt with "context rot": quality degrades as context grows, and faster for more complex tasks, but it gives no mechanism. Propose mechanistic hypotheses for context rot, explain how recursion through a REPL sidesteps each, and say how you would tell the hypotheses apart.

    What a strong answer covers
    • Attention dilution: softmax normalizes over more tokens, so the weight on the few relevant ones shrinks and distractors add noise. Sub-calls over smaller chunks keep relevant tokens a larger share.
    • Distractor interference: similar but irrelevant passages compete for attention. Chunked processing isolates them, and code (regex, slicing) can filter before any LM reads the text.
    • Position and length effects: models see few very long training sequences, so middle-of-context and long-range retrieval are weak (lost in the middle). Chunks keep every call within the well-trained length range.
    • Task complexity: aggregating over every item, or every pair, requires many reasoning steps across the whole context in one pass. The REPL turns this into an explicit loop with state in variables.
    • To separate the hypotheses: vary context length at fixed task complexity, vary the number of distractors at fixed length, and vary the needle position.
  3. What if…

    The RLM results vary with recursion depth. With GPT-5, depth 0 (REPL but no sub-calls) scores 36.0 on OOLONG against 56.0 at depth 1, and OOLONG-Pairs rises from 43.9 at depth 0 to 76.0 at depth 3. With Qwen3-Coder on CodeQA, depth 0 scores 66.0 and every deeper setting is lower. Explain both patterns and design the ablation you would run to choose a depth for a new task.

    What a strong answer covers
    • Depth 0 still offloads the context: the root can search, slice and grep the variable in code and read only what it needs, which is enough when the answer sits in a few places, as in code lookups.
    • Aggregation tasks need semantic judgments on almost every item (for example labelling each entry), which code alone cannot do; sub-LM calls are the only way to read everything.
    • Sub-calls add cost and error: syntax errors and malformed outputs propagate through sub-RLMs, and Qwen3-Coder needed an explicit warning to stop it making thousands of sub-calls.
    • Ablation for a new task: estimate how much of the context the answer depends on, run depths 0–2 at matched budget, and log sub-call counts, error propagation and cost per correct answer.
  4. Critique

    On BrowseComp-Plus with 1,000 documents (6–11M input tokens), RLM with GPT-5 reaches 91.3% at an average of USD 0.99 per query, against 70.5% for a compaction agent and 51.0% for CodeAct with BM25. Critique this evaluation from an IR perspective and propose an experiment that could change the conclusion.

    What a strong answer covers
    • The 1,000 documents are sampled so that the gold and evidence documents are guaranteed to be present. This tests reading a small fixed pool, not search over the benchmark's full corpus.
    • Costs are skewed: the median RLM run is cheaper than the base model's, but the mean is higher because of outlier trajectories. Report the full cost and latency distribution, since sub-calls are sequential.
    • How strong was the retrieval baseline? A tuned retriever with a reranker over a 1,000-document pool should be cheap and strong; BM25 inside CodeAct is a weak representative of IR.
    • Depth 0 already scores 88.0 here, so much of the gain comes from code access to the documents rather than recursion.
    • Experiment: grow the pool from 1,000 documents to the full corpus and compare RLM against a tuned retrieve-and-read agent at matched cost. If retrieval wins at scale, RLM is a reading strategy, not a replacement for search.
  5. Research idea

    Pitch a research project that combines RLMs with a proper retrieval index, framed around a question an IR group is well placed to answer. State the hypothesis, the system design, the evaluation, and the main risk.

    What a strong answer covers
    • Hypothesis: giving the root a search tool over the context (BM25 or a dense index built on the fly) beats chunk-and-scan at equal cost on sparse-evidence tasks, while chunk-and-scan stays better on dense aggregation.
    • System: the root chooses between search() and llm_query() over chunks; log which it uses and when.
    • Evaluation across task complexity: S-NIAH (constant), OOLONG (linear), OOLONG-Pairs (quadratic) and BrowseComp-Plus at several context lengths, reporting accuracy against cost and latency.
    • Follow-up: post-train the root policy on filtered trajectories, as the paper did for RLM-Qwen3-8B, so it learns when to search and when to scan.
    • Risk: per-query index build cost, and evidence that can only be recognized by semantic reading is missed by the index.
  6. Connect

    Compare RLMs with two other ways of handling inputs longer than the context window: summarization-based context compaction and retrieval-augmented generation. For each, say what information can be lost and on which task type (constant, linear or quadratic in input length) it should fail.

    What a strong answer covers
    • Compaction repeatedly summarizes; it loses details not foreseen as relevant, and fails on exact-item questions asked later and on linear or pairwise aggregation.
    • RAG keeps the top-k chunks by similarity; it suits constant-complexity needle tasks but fails on aggregation, where the answer depends on all items rather than a few similar ones.
    • RLM keeps the whole context as a variable and decides in code what to read, so it can run linear and quadratic passes, at higher cost and latency.
    • Evidence with GPT-5: on OOLONG-Pairs the base model scores 0.1 F1 and the compaction agent 0.1, while RLM reaches 58.0 at depth 1.
    • All three are policies for deciding what enters the context window; an RLM makes that policy code written by the model.

Done with this page?

Status