DSPy: The framework for programming—not prompting—language models
Python
Rename RLM max_iterations to max_iters for consistency (#9920)
Isaac Millerc2c49459525b
diff --git a/docs/docs/api/modules/RLM.md b/docs/docs/api/modules/RLM.mdindex 42fde64c1..cb5033a30 100644--- a/docs/docs/api/modules/RLM.md+++ b/docs/docs/api/modules/RLM.md@@ -107,7 +107,7 @@ $20,000,000| Parameter | Type | Default | Description ||-----------|------|---------|-------------|| `signature` | `str \| Signature` | required | Defines inputs and outputs (e.g., `"context, query -> answer"`) |-| `max_iterations` | `int` | `20` | Maximum REPL interaction loops before fallback extraction |+| `max_iters` | `int` | `20` | Maximum REPL interaction loops before fallback extraction || `max_llm_calls` | `int` | `50` | Maximum `llm_query`/`llm_query_batched` calls per execution || `max_output_chars` | `int` | `10_000` | Maximum characters to include from REPL output || `verbose` | `bool` | `False` | Log detailed execution info |@@ -136,7 +136,7 @@ import dspydspy.configure(lm=dspy.LM("openai/gpt-5"))-rlm = dspy.RLM("document, question -> answer", max_iterations=10)+rlm = dspy.RLM("document, question -> answer", max_iters=10)with open("large_report.txt") as f:document = f.read() # 500K+ charactersdiff --git a/docs/docs/diving-deeper/built-in-module-variants.md b/docs/docs/diving-deeper/built-in-module-variants.mdindex 13d01b63b..83de88ccf 100644--- a/docs/docs/diving-deeper/built-in-module-variants.md+++ b/docs/docs/diving-deeper/built-in-module-variants.md@@ -80,7 +80,7 @@ Holds three internal `ChainOfThought` predictors: `code_generate` produces Pytho**`dspy.CodeAct(signature, tools, max_iters=5, interpreter=None)`**Multiple inheritance from `ReAct` and `ProgramOfThought`. Tools must be plain `def` functions, not callable objects — the module reads `inspect.getsource(tool.func)` and injects each definition into the sandbox at the start of every `forward`. Each iteration: an inner `codeact` predictor produces Python plus a `finished` boolean; the interpreter runs the code; the trajectory dict gains a `generated_code_i` and `code_output_i` (or `observation_i` on parse/execution error). The loop exits when the LM sets `finished=True` or `max_iters` is reached. A `ChainOfThought` extractor then reads the trajectory and produces the declared outputs.-**`dspy.RLM(signature, max_iterations=20, max_llm_calls=50, max_output_chars=10_000, verbose=False, tools=None, sub_lm=None, interpreter=None)`**+**`dspy.RLM(signature, max_iters=20, max_llm_calls=50, max_output_chars=10_000, verbose=False, tools=None, sub_lm=None, interpreter=None)`**Experimental. A REPL-style code agent that exposes two built-in tools — `llm_query` and `llm_query_batched` — so generated code can call a separate `sub_lm` mid-execution. A shared counter across iterations enforces `max_llm_calls`; tool names are validated as Python identifiers; `SandboxSerializable` inputs encode into the sandbox so large contexts don’t have to be re-marshalled each turn. If the loop ends without an explicit submission, the extractor pass produces the final outputs from the trajectory.### Running modules in paralleldiff --git a/docs/docs/diving-deeper/rlm.md b/docs/docs/diving-deeper/rlm.mdindex 74964a635..995c3f8a8 100644--- a/docs/docs/diving-deeper/rlm.md+++ b/docs/docs/diving-deeper/rlm.md@@ -16,7 +16,7 @@ A normal `Predict` call puts the whole context into the prompt, so every token c### 3. The LLM drives an iterative REPL loop-`dspy.RLM` is not a single call. `forward()` runs up to `max_iterations` turns. On each turn the internal `generate_action` predictor sees the variable metadata and the prior REPL history, then emits reasoning plus one Python code block. The code runs, its output joins the `REPLHistory`, and the next turn begins. State persists across turns because the whole run shares one interpreter session. This is why the instructions push the model to explore first and take small steps: each turn is meant to build on what the last one printed.+`dspy.RLM` is not a single call. `forward()` runs up to `max_iters` turns. On each turn the internal `generate_action` predictor sees the variable metadata and the prior REPL history, then emits reasoning plus one Python code block. The code runs, its output joins the `REPLHistory`, and the next turn begins. State persists across turns because the whole run shares one interpreter session. This is why the instructions push the model to explore first and take small steps: each turn is meant to build on what the last one printed.### 4. Built-in `llm_query` tools give the loop its recursion@@ -40,7 +40,7 @@ Some inputs are not plain strings. A DataFrame, a parsed corpus, or a binary blo### 9. An extract pass salvages outputs when the loop ends early-A model can exhaust `max_iterations` without ever submitting final outputs. Rather than return nothing, `dspy.RLM` falls back to a second predictor, the `extract` step, which reads the variable metadata and the full REPL history and produces the signature’s output fields directly. You get the best answer the trajectory supports even when the model never declared itself done.+A model can exhaust `max_iters` without ever submitting final outputs. Rather than return nothing, `dspy.RLM` falls back to a second predictor, the `extract` step, which reads the variable metadata and the full REPL history and produces the signature’s output fields directly. You get the best answer the trajectory supports even when the model never declared itself done.### 10. RLM optimizes like any other module@@ -54,11 +54,11 @@ The class carries the `@experimental` decorator. The hard parts are still settli### Defining and running an RLM-**`dspy.RLM(signature, max_iterations=20, max_llm_calls=50, max_output_chars=10_000, verbose=False, tools=None, sub_lm=None, interpreter=None)`**+**`dspy.RLM(signature, max_iters=20, max_llm_calls=50, max_output_chars=10_000, verbose=False, tools=None, sub_lm=None, interpreter=None)`**The constructor parses the signature and builds the two internal predictors, formatting your task instructions, input names, and output-field types into the action prompt and creating a separate extract signature for the fallback. The budgets and the sandbox configuration are all fixed here, so one instance carries one configuration.**`forward(**inputs)` / `aforward(**inputs)` / `__call__`**-`forward()` validates the inputs against the signature, builds the variable list, opens the interpreter, and runs the loop. Each turn asks the action predictor for code, runs it, and appends the result to history until the model submits or the loop reaches `max_iterations`. `aforward()` is the async twin and uses `acall` on the predictors. Both return a `Prediction`.+`forward()` validates the inputs against the signature, builds the variable list, opens the interpreter, and runs the loop. Each turn asks the action predictor for code, runs it, and appends the result to history until the model submits or the loop reaches `max_iters`. `aforward()` is the async twin and uses `acall` on the predictors. Both return a `Prediction`.### Programming the loop with built-in tools@@ -78,8 +78,8 @@ The only way the model sees a result. REPL stdout is captured, truncated to `max### Budgeting iterations and sub-LLM calls-**`max_iterations`, `max_llm_calls`, `max_output_chars`**-Three independent limits. `max_iterations` bounds REPL turns before the extract fallback fires. `max_llm_calls` bounds recursive sub-LLM calls across the whole run. `max_output_chars` bounds how much of each REPL output reaches the model, keeping a noisy print from flooding the prompt.+**`max_iters`, `max_llm_calls`, `max_output_chars`**+Three independent limits. `max_iters` bounds REPL turns before the extract fallback fires. `max_llm_calls` bounds recursive sub-LLM calls across the whole run. `max_output_chars` bounds how much of each REPL output reaches the model, keeping a noisy print from flooding the prompt.**`sub_lm`**The model for `llm_query` and `llm_query_batched`. Left unset it falls back to `dspy.settings.lm`, so by default the loop and its sub-calls share one model.diff --git a/docs/docs/tutorials/dataframe_rlm/cohort_analysis/cohort_analysis_demo.ipynb b/docs/docs/tutorials/dataframe_rlm/cohort_analysis/cohort_analysis_demo.ipynbindex 36216fd9f..98d0ab495 100644--- a/docs/docs/tutorials/dataframe_rlm/cohort_analysis/cohort_analysis_demo.ipynb+++ b/docs/docs/tutorials/dataframe_rlm/cohort_analysis/cohort_analysis_demo.ipynb@@ -1173,7 +1173,7 @@"source": ["analyzer = dspy.RLM(\n"," CohortRetentionAnalysis,\n",- " max_iterations=15,\n",+ " max_iters=15,\n"," verbose=True,\n",")\n","\n",diff --git a/dspy/predict/rlm.py b/dspy/predict/rlm.pyindex b4deecb62..8906d03a0 100644--- a/dspy/predict/rlm.py+++ b/dspy/predict/rlm.py@@ -118,7 +118,7 @@ class RLM(Module):Examples:```python# Basic usage- rlm = dspy.RLM("context, query -> output", max_iterations=10)+ rlm = dspy.RLM("context, query -> output", max_iters=10)result = rlm(context="...very long text...", query="What is the magic number?")print(result.output)```@@ -127,7 +127,7 @@ class RLM(Module):def __init__(self,signature: type[Signature] | str,- max_iterations: int = 20,+ max_iters: int = 20,max_llm_calls: int = 50,max_output_chars: int = 10_000,verbose: bool = False,@@ -139,7 +139,7 @@ class RLM(Module):Args:signature: Defines inputs and outputs. String like "context, query -> answer"or a Signature class.- max_iterations: Maximum REPL interaction iterations.+ max_iters: Maximum REPL interaction iterations.max_llm_calls: Maximum sub-LLM calls (llm_query/llm_query_batched) per execution.max_output_chars: Maximum characters to include from REPL output.verbose: Whether to log detailed execution info.@@ -151,7 +151,7 @@ class RLM(Module):"""super().__init__()self.signature = ensure_signature(signature)- self.max_iterations = max_iterations+ self.max_iters = max_itersself.max_llm_calls = max_llm_callsself.max_output_chars = max_output_charsself.verbose = verbose@@ -311,7 +311,7 @@ class RLM(Module):) + tool_docs).append("variables_info", dspy.InputField(desc="Metadata about the variables available in the REPL"), type_=str).append("repl_history", dspy.InputField(desc="Previous REPL code executions and their outputs"), type_=REPLHistory)- .append("iteration", dspy.InputField(desc="Current iteration number (1-indexed) out of max_iterations"), type_=str)+ .append("iteration", dspy.InputField(desc="Current iteration number (1-indexed) out of max_iters"), type_=str).append("reasoning", dspy.OutputField(desc="Think step-by-step: what do you know? What remains? Plan your next action."), type_=str).append("code", dspy.OutputField(desc="Python code to execute. Use markdown code block format: ```python\\n<code>\\n```"), type_=str))@@ -600,11 +600,11 @@ class RLM(Module):action = self.generate_action(variables_info=variables_info,repl_history=history,- iteration=f"{iteration + 1}/{self.max_iterations}",+ iteration=f"{iteration + 1}/{self.max_iters}",)if self.verbose:logger.info(- f"RLM iteration {iteration + 1}/{self.max_iterations}\n"+ f"RLM iteration {iteration + 1}/{self.max_iters}\n"f"Reasoning: {action.reasoning}\nCode:\n{action.code}")@@ -643,7 +643,7 @@ class RLM(Module):regular_args = self._prepare_serializable_vars(input_args, repl)history: REPLHistory = REPLHistory(max_output_chars=self.max_output_chars)- for iteration in range(self.max_iterations):+ for iteration in range(self.max_iters):result: Prediction | REPLHistory = self._execute_iteration(repl, variables, history, iteration, regular_args, output_field_names)@@ -689,11 +689,11 @@ class RLM(Module):pred = await self.generate_action.acall(variables_info=variables_info,repl_history=history,- iteration=f"{iteration + 1}/{self.max_iterations}",+ iteration=f"{iteration + 1}/{self.max_iters}",)if self.verbose:logger.info(- f"RLM iteration {iteration + 1}/{self.max_iterations}\n"+ f"RLM iteration {iteration + 1}/{self.max_iters}\n"f"Reasoning: {pred.reasoning}\nCode:\n{pred.code}")@@ -728,7 +728,7 @@ class RLM(Module):regular_args = self._prepare_serializable_vars(input_args, repl)history = REPLHistory(max_output_chars=self.max_output_chars)- for iteration in range(self.max_iterations):+ for iteration in range(self.max_iters):result = await self._aexecute_iteration(repl, variables, history, iteration, regular_args, output_field_names)diff --git a/tests/predict/test_rlm.py b/tests/predict/test_rlm.pyindex 8b51b153e..e5a25497d 100644--- a/tests/predict/test_rlm.py+++ b/tests/predict/test_rlm.py@@ -124,8 +124,8 @@ class TestRLMInitialization:def test_basic_initialization(self):"""Test RLM module initializes correctly with signature."""- rlm = RLM("context, query -> answer", max_iterations=5)- assert rlm.max_iterations == 5+ rlm = RLM("context, query -> answer", max_iters=5)+ assert rlm.max_iters == 5assert rlm.generate_action is not Noneassert rlm.extract is not Noneassert rlm.tools == {} # No user tools provided@@ -135,7 +135,7 @@ class TestRLMInitialization:def test_custom_signature(self):"""Test RLM with custom signature."""- rlm = RLM("document, question -> summary, key_facts", max_iterations=5)+ rlm = RLM("document, question -> summary, key_facts", max_iters=5)assert "document" in rlm.signature.input_fieldsassert "question" in rlm.signature.input_fieldsassert "summary" in rlm.signature.output_fields@@ -146,7 +146,7 @@ class TestRLMInitialization:def custom_tool(x: str = "") -> str:return x.upper()- rlm = RLM("context -> answer", max_iterations=5, tools=[custom_tool])+ rlm = RLM("context -> answer", max_iters=5, tools=[custom_tool])assert "custom_tool" in rlm.toolsassert len(rlm.tools) == 1 # Only user tools, not internal llm_query/llm_query_batched@@ -207,12 +207,12 @@ class TestRLMInitialization:mock = MockInterpreter(responses=["result"])# Single missing input- rlm = RLM("context, query -> answer", max_iterations=3, interpreter=mock)+ rlm = RLM("context, query -> answer", max_iters=3, interpreter=mock)with pytest.raises(ValueError, match="Missing required input"):rlm.forward(context="some context") # Missing 'query'# Multiple missing inputs - all should be reported- rlm = RLM("a, b, c -> answer", max_iterations=3, interpreter=mock)+ rlm = RLM("a, b, c -> answer", max_iters=3, interpreter=mock)with pytest.raises(ValueError) as exc_info:rlm.forward(a="only a") # Missing 'b' and 'c'assert "b" in str(exc_info.value)@@ -495,7 +495,7 @@ class TestREPLTypes:question: str = dspy.InputField(desc="The question to answer")answer: str = dspy.OutputField()- rlm = RLM(QASig, max_iterations=3)+ rlm = RLM(QASig, max_iters=3)variables = rlm._build_variables(context="Some text", question="What?")# Find the context variable@@ -512,7 +512,7 @@ class TestRLMCallMethod:def test_call_is_alias_for_forward(self):"""Test that __call__ is an alias for forward()."""mock = MockInterpreter(responses=[FinalOutput({"answer": "42"})])- rlm = RLM("query -> answer", max_iterations=3, interpreter=mock)+ rlm = RLM("query -> answer", max_iters=3, interpreter=mock)rlm.generate_action = make_mock_predictor([{"reasoning": "Return answer", "code": 'SUBMIT("42")'},])@@ -522,16 +522,16 @@ class TestRLMCallMethod:class TestRLMMaxIterationsFallback:- """Tests for max_iterations reached and extract fallback."""+ """Tests for max_iters reached and extract fallback."""- def test_max_iterations_triggers_extract(self):- """Test that reaching max_iterations uses extract fallback."""+ def test_max_iters_triggers_extract(self):+ """Test that reaching max_iters uses extract fallback."""mock = MockInterpreter(responses=["exploring...","still exploring...","more exploring...",])- rlm = RLM("query -> answer", max_iterations=3, interpreter=mock)+ rlm = RLM("query -> answer", max_iters=3, interpreter=mock)rlm.generate_action = make_mock_predictor([{"reasoning": "Explore 1", "code": "print('exploring')"},{"reasoning": "Explore 2", "code": "print('exploring')"},@@ -559,7 +559,7 @@ class TestRLMToolExceptions:CodeInterpreterError("RuntimeError: Tool failed!"),FinalOutput({"answer": "recovered"}),])- rlm = RLM("query -> answer", max_iterations=5, interpreter=mock, tools=[failing_tool])+ rlm = RLM("query -> answer", max_iters=5, interpreter=mock, tools=[failing_tool])rlm.generate_action = make_mock_predictor([{"reasoning": "Call tool", "code": "failing_tool()"},{"reasoning": "Recover", "code": 'SUBMIT("recovered")'},@@ -574,7 +574,7 @@ class TestRLMToolExceptions:CodeInterpreterError("NameError: name 'x' is not defined"),FinalOutput({"answer": "recovered"}),])- rlm = RLM("query -> answer", max_iterations=5, interpreter=mock)+ rlm = RLM("query -> answer", max_iters=5, interpreter=mock)rlm.generate_action = make_mock_predictor([{"reasoning": "Will fail", "code": "```python\nprint(x)\n```"},{"reasoning": "Recover", "code": 'SUBMIT("recovered")'},@@ -591,7 +591,7 @@ class TestRLMToolExceptions:SyntaxError("invalid syntax"),FinalOutput({"answer": "recovered"}),])- rlm = RLM("query -> answer", max_iterations=5, interpreter=mock)+ rlm = RLM("query -> answer", max_iters=5, interpreter=mock)rlm.generate_action = make_mock_predictor([{"reasoning": "Bad code", "code": "```python\ndef incomplete(\n```"},{"reasoning": "Recover", "code": 'SUBMIT("recovered")'},@@ -606,7 +606,7 @@ class TestRLMToolExceptions:mock = MockInterpreter(responses=[FinalOutput({"answer": "recovered"}),])- rlm = RLM("query -> answer", max_iterations=5, interpreter=mock)+ rlm = RLM("query -> answer", max_iters=5, interpreter=mock)rlm.generate_action = make_mock_predictor([{"reasoning": "Wrong language", "code": "```bash\nls -la\n```"},{"reasoning": "Recover", "code": 'SUBMIT("recovered")'},@@ -856,7 +856,7 @@ class TestRLMAsyncMock:async def test_aforward_basic(self):"""Test aforward() returns Prediction with expected output (MockInterpreter)."""mock = MockInterpreter(responses=[FinalOutput({"answer": "42"})])- rlm = RLM("query -> answer", max_iterations=3, interpreter=mock)+ rlm = RLM("query -> answer", max_iters=3, interpreter=mock)rlm.generate_action = make_mock_predictor([{"reasoning": "Return answer", "code": 'SUBMIT("42")'},])@@ -868,7 +868,7 @@ class TestRLMAsyncMock:async def test_aforward_int_output_mock(self):"""Test aforward() returns int when signature expects int (MockInterpreter)."""mock = MockInterpreter(responses=[FinalOutput({"count": 42})])- rlm = RLM("query -> count: int", max_iterations=3, interpreter=mock)+ rlm = RLM("query -> count: int", max_iters=3, interpreter=mock)rlm.generate_action = make_mock_predictor([{"reasoning": "Return count", "code": "SUBMIT(42)"},])@@ -884,7 +884,7 @@ class TestRLMAsyncMock:"explored data",FinalOutput({"answer": "done"}),])- rlm = RLM("query -> answer", max_iterations=5, interpreter=mock)+ rlm = RLM("query -> answer", max_iters=5, interpreter=mock)rlm.generate_action = make_mock_predictor([{"reasoning": "Explore first", "code": "print('exploring')"},{"reasoning": "Now finish", "code": 'SUBMIT("done")'},@@ -907,7 +907,7 @@ class TestRLMTypeCoercionMock:def test_type_coercion(self, output_field, output_type, final_value, code, expected):"""Test RLM type coercion for various types (MockInterpreter)."""mock = MockInterpreter(responses=[FinalOutput({output_field: final_value})])- rlm = RLM(f"query -> {output_field}: {output_type}", max_iterations=3, interpreter=mock)+ rlm = RLM(f"query -> {output_field}: {output_type}", max_iters=3, interpreter=mock)rlm.generate_action = make_mock_predictor([{"reasoning": "Return value", "code": code},])@@ -921,7 +921,7 @@ class TestRLMTypeCoercionMock:FinalOutput({"answer": "maybe"}), # Invalid for LiteralFinalOutput({"answer": "yes"}), # Valid])- rlm = RLM("query -> answer: Literal['yes', 'no']", max_iterations=5, interpreter=mock)+ rlm = RLM("query -> answer: Literal['yes', 'no']", max_iters=5, interpreter=mock)rlm.generate_action = make_mock_predictor([{"reasoning": "Try maybe", "code": 'SUBMIT("maybe")'},{"reasoning": "Try yes", "code": 'SUBMIT("yes")'},@@ -954,7 +954,7 @@ class TestRLMTypeCoercion:])def test_type_coercion(self, output_field, output_type, code, expected, expected_type):"""Test RLM type coercion for various types with PythonInterpreter."""- rlm = RLM(f"query -> {output_field}: {output_type}", max_iterations=3)+ rlm = RLM(f"query -> {output_field}: {output_type}", max_iters=3)rlm.generate_action = make_mock_predictor([{"reasoning": "Return value", "code": code},])@@ -965,7 +965,7 @@ class TestRLMTypeCoercion:def test_submit_extracts_typed_value(self):"""Test RLM SUBMIT correctly extracts typed value."""- rlm = RLM("query -> count: int", max_iterations=3)+ rlm = RLM("query -> count: int", max_iters=3)rlm.generate_action = make_mock_predictor([{"reasoning": "Compute and return", "code": "result = 42\nSUBMIT(result)"},])@@ -989,7 +989,7 @@ class TestRLMMultipleOutputs:def test_multi_output_final_kwargs(self):"""SUBMIT(field1=val1, field2=val2) with keyword args."""- rlm = RLM("query -> name: str, count: int", max_iterations=3)+ rlm = RLM("query -> name: str, count: int", max_iters=3)rlm.generate_action = make_mock_predictor([{"reasoning": "Return both outputs", "code": 'SUBMIT(name="alice", count=5)'},])@@ -1001,7 +1001,7 @@ class TestRLMMultipleOutputs:def test_multi_output_final_positional(self):"""SUBMIT(val1, val2) with positional args mapped to field order."""- rlm = RLM("query -> name: str, count: int", max_iterations=3)+ rlm = RLM("query -> name: str, count: int", max_iters=3)rlm.generate_action = make_mock_predictor([{"reasoning": "Return both outputs positionally", "code": 'SUBMIT("bob", 10)'},])@@ -1012,7 +1012,7 @@ class TestRLMMultipleOutputs:def test_multi_output_three_fields(self):"""Signature with 3+ output fields of different types."""- rlm = RLM("query -> name: str, age: int, active: bool", max_iterations=3)+ rlm = RLM("query -> name: str, age: int, active: bool", max_iters=3)rlm.generate_action = make_mock_predictor([{"reasoning": "Return all three", "code": 'SUBMIT(name="carol", age=30, active=True)'},])@@ -1024,7 +1024,7 @@ class TestRLMMultipleOutputs:def test_multi_output_final_missing_field_errors(self):"""SUBMIT() with missing field should return error in output."""- rlm = RLM("query -> name: str, count: int", max_iterations=3)+ rlm = RLM("query -> name: str, count: int", max_iters=3)rlm.generate_action = make_mock_predictor([{"reasoning": "Missing count field", "code": 'SUBMIT(name="alice")'},{"reasoning": "Now provide both", "code": 'SUBMIT(name="alice", count=5)'},@@ -1037,7 +1037,7 @@ class TestRLMMultipleOutputs:def test_multi_output_submit_vars(self):"""SUBMIT can pass variables directly for multiple outputs."""- rlm = RLM("query -> name: str, count: int", max_iterations=3)+ rlm = RLM("query -> name: str, count: int", max_iters=3)rlm.generate_action = make_mock_predictor([{"reasoning": "Use SUBMIT", "code": 'n = "dave"\nc = 15\nSUBMIT(n, c)'},])@@ -1048,7 +1048,7 @@ class TestRLMMultipleOutputs:def test_multi_output_type_coercion(self):"""Each output field is coerced to its declared type."""- rlm = RLM("query -> count: int, ratio: float, flag: bool", max_iterations=3)+ rlm = RLM("query -> count: int, ratio: float, flag: bool", max_iters=3)rlm.generate_action = make_mock_predictor([{"reasoning": "Return mixed types", "code": "SUBMIT(count=42, ratio=3.14, flag=True)"},])@@ -1080,7 +1080,7 @@ class TestRLMWithDummyLM:with dummy_lm_context([{"reasoning": "I need to compute 2 + 3", "code": "result = 2 + 3\nSUBMIT(result)"},]):- rlm = RLM("query -> answer: int", max_iterations=3)+ rlm = RLM("query -> answer: int", max_iters=3)result = rlm.forward(query="What is 2 + 3?")assert result.answer == 5@@ -1092,7 +1092,7 @@ class TestRLMWithDummyLM:{"reasoning": "First explore the data", "code": "x = 10\nprint(f'x = {x}')"},{"reasoning": "Now compute and return", "code": "y = x * 2\nSUBMIT(y)"},]):- rlm = RLM("query -> answer: int", max_iterations=5)+ rlm = RLM("query -> answer: int", max_iters=5)result = rlm.forward(query="Double ten")assert result.answer == 20@@ -1103,7 +1103,7 @@ class TestRLMWithDummyLM:with dummy_lm_context([{"reasoning": "Sum the numbers in the list", "code": "SUBMIT(sum(numbers))"},]):- rlm = RLM("numbers: list[int] -> total: int", max_iterations=3)+ rlm = RLM("numbers: list[int] -> total: int", max_iters=3)result = rlm.forward(numbers=[1, 2, 3, 4, 5])assert result.total == 15@@ -1116,7 +1116,7 @@ class TestRLMWithDummyLM:with dummy_lm_context([{"reasoning": "Look up the color of apple", "code": 'color = lookup(key="apple")\nSUBMIT(color)'},]):- rlm = RLM("fruit -> color: str", max_iterations=3, tools=[lookup])+ rlm = RLM("fruit -> color: str", max_iters=3, tools=[lookup])result = rlm.forward(fruit="apple")assert result.color == "red"@@ -1127,7 +1127,7 @@ class TestRLMWithDummyLM:with dummy_lm_context([{"reasoning": "I need to compute 2 + 3", "code": "result = 2 + 3\nSUBMIT(result)"},]):- rlm = RLM("query -> answer: int", max_iterations=3)+ rlm = RLM("query -> answer: int", max_iters=3)result = await rlm.aforward(query="What is 2 + 3?")assert result.answer == 5@@ -1140,7 +1140,7 @@ class TestRLMWithDummyLM:{"reasoning": "First explore the data", "code": "x = 10\nprint(f'x = {x}')"},{"reasoning": "Now compute and return", "code": "y = x * 2\nSUBMIT(y)"},]):- rlm = RLM("query -> answer: int", max_iterations=5)+ rlm = RLM("query -> answer: int", max_iters=5)result = await rlm.aforward(query="Double ten")assert result.answer == 20@@ -1152,7 +1152,7 @@ class TestRLMWithDummyLM:with dummy_lm_context([{"reasoning": "Sum the numbers in the list", "code": "SUBMIT(sum(numbers))"},]):- rlm = RLM("numbers: list[int] -> total: int", max_iterations=3)+ rlm = RLM("numbers: list[int] -> total: int", max_iters=3)result = await rlm.aforward(numbers=[1, 2, 3, 4, 5])assert result.total == 15@@ -1172,7 +1172,7 @@ class TestRLMIntegration:import dspydspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))- rlm = RLM("context, query -> answer", max_iterations=5)+ rlm = RLM("context, query -> answer", max_iters=5)result = rlm(context={"numbers": [1, 2, 3, 4, 5]},query="What is the sum of the numbers?"@@ -1184,7 +1184,7 @@ class TestRLMIntegration:import dspydspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))- rlm = RLM("context, query -> answer", max_iterations=5)+ rlm = RLM("context, query -> answer", max_iters=5)result = rlm(context="The quick brown fox jumps over the lazy dog.",query="Use llm_query to describe what animal is mentioned as lazy."@@ -1265,7 +1265,7 @@ class TestPrepareSerializableVars:def test_separates_serializable_from_regular(self):"""Serializable values are injected; regular values are returned."""mock = MockInterpreter(responses=["", FinalOutput({"answer": "42"})])- rlm = RLM("data, query -> answer", max_iterations=3, interpreter=mock)+ rlm = RLM("data, query -> answer", max_iters=3, interpreter=mock)stub = _StubSerializable("payload")@@ -1287,7 +1287,7 @@ class TestPrepareSerializableVars:def test_no_serializable_returns_all(self):"""When no SandboxSerializable values exist, all args are returned."""mock = MockInterpreter(responses=[FinalOutput({"answer": "42"})])- rlm = RLM("query -> answer", max_iterations=3, interpreter=mock)+ rlm = RLM("query -> answer", max_iters=3, interpreter=mock)rlm._inject_execution_context(mock, rlm._prepare_execution_tools())regular = rlm._prepare_serializable_vars({"query": "hello"}, mock)@@ -1350,7 +1350,7 @@ class TestPrepareSerializableVars:"", # setup execution for _prepare_serializable_varsFinalOutput({"answer": "done"}),])- rlm = RLM("data, query -> answer", max_iterations=3, interpreter=mock)+ rlm = RLM("data, query -> answer", max_iters=3, interpreter=mock)rlm.generate_action = make_mock_predictor([{"reasoning": "Done", "code": 'SUBMIT("done")'},])