Guides using DSPy's RLM to explore large contexts via a sandboxed Python REPL, writing code and iterating until a final answer is produced.
Ships in dspy-api-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Guide the user through using DSPy's RLM (Recursive Language Model) module. RLM lets the LM explore data programmatically in a sandboxed Python REPL, writing code to examine inputs, querying sub-LMs for semantic analysis, and iterating until it produces a final answer.
Experimental. RLM is marked as experimental in DSPy. The API may change in future releases.
Before building with RLM, clarify:
dspy.RLM implements the Recursive Language Models approach (Zhang, Kraska, Khattab 2025). Instead of feeding the full input context into the LM's prompt, RLM:
llm_query(prompt) to do semantic analysis on slices of the data.SUBMIT(output) with a final answer.This makes RLM ideal for tasks where the input is too large for the context window, or where the LM needs to programmatically explore the data to find the answer.
| Scenario | Why RLM helps |
|---|---|
| Very large input contexts (100K+ chars) | LM sees metadata, explores programmatically instead of stuffing the context |
| Data exploration tasks | LM writes code to search, filter, aggregate |
| Tasks requiring code + reasoning | Built-in REPL combines computation with LM reasoning |
| Multi-step analysis over structured data | LM can iterate, inspect intermediate results, refine approach |
When RLM is not the right fit:
dspy.Predict or dspy.ChainOfThoughtdspy.ReActRLM's default sandbox requires Deno for the Pyodide WASM interpreter:
curl -fsSL https://deno.land/install.sh | sh
import dspy
dspy.configure(lm=dspy.LM("openai/gpt-4o")) # or "anthropic/claude-sonnet-4-5-20250929", etc.
rlm = dspy.RLM("context, query -> answer")
result = rlm(
context="...very long document or dataset...",
query="What is the total revenue for Q3?",
)
print(result.answer)
The LM will:
context (type, length, first/last chars).llm_query() for semantic questions about slices.SUBMIT(answer) when ready.dspy.RLM(
signature, # str | Signature -- required, defines inputs/outputs
max_iters=20, # max REPL interaction loops
max_llm_calls=50, # max sub-LM query calls per execution
max_output_chars=10_000,# max chars from REPL output per step
verbose=False, # enable detailed execution logging
tools=None, # list[Callable] -- custom tool functions
sub_lm=None, # dspy.LM -- separate (cheaper) LM for sub-queries
interpreter=None, # custom CodeInterpreter (defaults to PythonInterpreter)
)
When the LM writes code in the sandbox, these functions are available:
| Function | Purpose |
|---|---|
llm_query(prompt) | Query the sub-LM with a prompt (up to ~500K chars) |
llm_query_batched(prompts) | Concurrent multi-prompt queries |
print() | Display REPL output (required to see results) |
SUBMIT(output) | End execution and return the final answer |
Route expensive reasoning to a strong model while using a cheap model for sub-queries:
main_lm = dspy.LM("openai/gpt-4o") # or "anthropic/claude-sonnet-4-5-20250929", etc.
cheap_lm = dspy.LM("openai/gpt-4o-mini") # or any cheaper model
dspy.configure(lm=main_lm)
rlm = dspy.RLM("data, query -> summary", sub_lm=cheap_lm)
result = rlm(data=large_dataset, query="Summarize the key trends")
RLM supports DSPy's typed output fields, just like other modules:
rlm = dspy.RLM("logs -> error_count: int, critical_errors: list[str]")
result = rlm(logs=server_logs)
print(result.error_count) # int
print(result.critical_errors) # list[str]
Pass additional Python functions that the LM can call inside the sandbox:
def fetch_metadata(doc_id: str) -> str:
"""Look up metadata for a document by ID."""
return database.get_metadata(doc_id)
rlm = dspy.RLM("documents, query -> answer", tools=[fetch_metadata])
result = rlm(documents=docs, query="Which document has the latest revision?")
After execution, inspect the code-execute-observe steps the LM took:
result = rlm(context=data, query="Find the outlier values")
for step in result.trajectory:
print(f"Code:\n{step['code']}")
print(f"Output:\n{step['output']}\n")
This is useful for debugging, understanding the LM's exploration strategy, and building trust in the result.
async def process():
result = await rlm.aforward(context=data, query="Summarize findings")
return result.answer
| Approach | Mechanism | Best for |
|---|---|---|
| RLM | LM writes code in a REPL to explore data, calls sub-LMs, iterates until SUBMIT() | Large contexts, data exploration, programmatic analysis |
Refine (dspy.Refine) | Retry with feedback from a reward function until score threshold is met | Improving a single output with a known quality metric |
| Best-of-N | Generate N candidates, pick the best by a metric | When you want diversity of attempts and can score them |
| ChainOfThought | Single-pass step-by-step reasoning | Standard tasks that fit in context |
| Output validation | dspy.Refine / dspy.BestOfN | Reward-based retry with feedback (replaced dspy.Assert/dspy.Suggest in 3.x) |
Key difference: RLM gives the LM a code execution environment to actively explore the input, rather than just re-prompting with feedback. The LM decides its own exploration strategy.
RLM instances with custom interpreters are not thread-safe. For concurrent usage, create separate instances or use the default PythonInterpreter.
deno --version before running RLM code.dspy.ChainOfThought or dspy.Predict instead.print() in REPL code. The LM must print() values to see REPL output -- assignments alone produce no visible result. If the LM's exploration seems stuck, check the trajectory for code that computes but never prints.max_iters too low for complex tasks. Claude tends to set max_iters=5 for brevity. RLM defaults to 20 for a reason -- complex data exploration often needs 10-15 iterations. Only lower it for simple lookups.sub_lm for cost control. Every llm_query() call inside the REPL uses the main LM by default. For large-context tasks with many sub-queries, this gets expensive fast. Always set sub_lm to a cheaper model for semantic analysis calls.Install any skill:
npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill <name>
/dspy-refine/dspy-best-of-n/ai-improving-accuracy/ai-building-pipelines/ai-do if you do not have it — it routes any AI problem to the right skill and is the fastest way to work: npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill ai-doWhat SKILL.md sets; muted values are Claude Code's defaults
/dspy-api-skills:dspy-rlmfrom dspy-api-skills
npx claudepluginhub lebsral/dspy-programming-not-prompting-lms-skills --plugin dspy-api-skills39 skills in this plugin
/dspy-adaptersUse when you need to customize how DSPy formats prompts for a specific provider — switching from chat to completion format, forcing JSON output, or debugging prompt rendering issues. Common scenarios - debugging why your prompt looks wrong when sent to the model, switching from OpenAI to Anthropic and the formatting breaks, forcing the model to return valid JSON instead of markdown, working with completion-style models that do not support chat format, customizing system messages, or handling models that choke on structured output instructions. Related - ai-switching-models, ai-following-rules, ai-parsing-data. Also used for prompt template rendering, how DSPy builds the prompt, custom system message in DSPy, JSON mode not working, model ignores format instructions, switch from chat to completion API, dspy.ChatAdapter, dspy.JSONAdapter, prompt formatting issues, debug what DSPy sends to the model, dspy.XMLAdapter, XML output format./dspy-assertionsLegacy reference for dspy.Assert and dspy.Suggest, both removed in DSPy 3.x - use dspy.Refine or dspy.BestOfN instead. Use when maintaining a legacy DSPy 2.x codebase that uses dspy.Assert or dspy.Suggest, or migrating from Assert/Suggest to DSPy 3.x. Also used for dspy.Assert, dspy.Suggest, runtime validation for LLM output, retry on bad output, backtracking on constraint violation, guard rails in DSPy, migrate from Assert, migrate from Suggest, ImportError cannot import Assert, ImportError cannot import Suggest./dspy-asyncUse when you need to run DSPy modules asynchronously — FastAPI endpoints, concurrent LM calls, non-blocking execution, or integrating DSPy into async web frameworks. Common scenarios - serving DSPy behind FastAPI or Starlette, running multiple LM calls concurrently with asyncio.gather, non-blocking batch processing, combining async with streaming, or building async agent loops. Related - ai-serving-apis, dspy-parallel, dspy-streaming, dspy-utils. Also used for aforward, acall, async DSPy, await dspy, FastAPI with DSPy async, concurrent DSPy calls, asyncio with DSPy, non-blocking DSPy, async batch processing, semaphore concurrency limit, asyncio.gather DSPy, async web framework DSPy, Starlette DSPy, aiohttp DSPy./dspy-best-of-nRuns any DSPy module N times and returns the highest-scoring output via a reward function using dspy.BestOfN. Use when output quality varies across runs and you want to sample multiple completions and pick the best — trading latency for reliability on high-stakes outputs. Common scenarios - generating multiple candidate answers and picking the highest-scoring one, improving reliability on high-stakes classification, reducing variance in creative generation, getting better summaries by sampling several and selecting the best, or trading latency for quality on critical decisions. Related - ai-improving-accuracy, ai-making-consistent, dspy-refine. Also used for sample multiple completions, pick the best of several LLM outputs, majority voting for LLM, self-consistency decoding, reduce LLM output variance, generate and select pattern, best candidate selection, how to make AI more reliable by trying multiple times, brute force better quality, retry and pick best, dspy.BestOfN, quality vs latency tradeoff, n=5 completions pick best./dspy-better-togetherJointly optimize prompts and model weights using dspy.BetterTogether for maximum accuracy. Use when you have already tried prompt-only optimization and want the next level — jointly tuning prompts and model weights for maximum quality. Common scenarios - you have maxed out prompt optimization and need the next level, combining instruction tuning with weight tuning for maximum quality, making a small model match a large model through joint optimization, or squeezing the last few percent of accuracy. Related - ai-fine-tuning, ai-improving-accuracy, ai-cutting-costs. Also used for dspy.BetterTogether, joint prompt and weight optimization, beyond prompt engineering, combine fine-tuning with prompt optimization, maximum possible quality from DSPy, hybrid optimization strategy, prompt optimization hit a ceiling, fine-tune and optimize prompts at the same time, advanced DSPy optimization, best possible accuracy, what to try after MIPROv2, next level AI quality./dspy-bootstrap-few-shotAutomatically generate and select few-shot demonstrations for a DSPy program from labeled data using dspy.BootstrapFewShot - the simplest and fastest optimizer. Use when you have 50+ labeled examples and want a quick accuracy boost as your first optimization step. Common scenarios - your first optimization attempt on a new DSPy program, adding few-shot examples automatically from labeled data, quick accuracy boost before trying heavier optimizers, bootstrapping demonstrations from a teacher model, or getting started with DSPy optimization. Related - ai-improving-accuracy, dspy-labeled-few-shot. Also used for dspy.BootstrapFewShot, simplest DSPy optimizer, first optimizer to try, automatic few-shot example selection, bootstrap demonstrations from labels, quick optimization baseline, add examples to prompt automatically, teacher bootstrapping, labeled data to few-shot demos, starting point for DSPy optimization, easy accuracy improvement, how to optimize DSPy program for the first time.Other plugins' skills for the same job