DSPy: The framework for programming—not prompting—language models
Python
feat(rlm): Add RLM Module and improve PythonInterpreter (#9193)
Isaac Miller87930f25ea4a
diff --git a/.gitignore b/.gitignoreindex 14f48d7f3..d8213fb32 100644--- a/.gitignore+++ b/.gitignore@@ -39,7 +39,6 @@ __pycache__/gpt*.txt*.envlocal/-local_*build/*.egg-info/# *.jsonldiff --git a/docs/docs/api/tools/PythonInterpreter.md b/docs/docs/api/tools/PythonInterpreter.mdindex bfc304d05..4f428b6a1 100644--- a/docs/docs/api/tools/PythonInterpreter.md+++ b/docs/docs/api/tools/PythonInterpreter.md@@ -8,6 +8,7 @@- __call__- execute- shutdown+ - startshow_source: trueshow_root_heading: trueheading_level: 2diff --git a/docs/docs/tutorials/math/index.ipynb b/docs/docs/tutorials/math/index.ipynbindex 5a6c3a853..a281f08e1 100644--- a/docs/docs/tutorials/math/index.ipynb+++ b/docs/docs/tutorials/math/index.ipynb@@ -602,14 +602,7 @@{"cell_type": "markdown","metadata": {},- "source": [- "Neat. It was pretty straightforward to improve quality from 74% to over 88% on a held-out set here.\n",- "\n",- "That said, for reasoning tasks like this, you will often want to consider more advanced strategies, like:\n",- "\n",- "- A `dspy.ReAct` module with access to a calculator function or `dspy.PythonInterpreter`\n",- "- Ensembling multiple optimized prompts with a majority vote (or an Aggregator module) on top"- ]+ "source": "Neat. It was pretty straightforward to improve quality from 74% to over 88% on a held-out set here.\n\nThat said, for reasoning tasks like this, you will often want to consider more advanced strategies, like:\n\n- A `dspy.ReAct` module with access to a calculator function or `dspy.LocalSandbox`\n- Ensembling multiple optimized prompts with a majority vote (or an Aggregator module) on top"},{"cell_type": "markdown",@@ -855,4 +848,4 @@},"nbformat": 4,"nbformat_minor": 2-}+}\ No newline at end of filediff --git a/docs/docs/tutorials/program_of_thought/index.ipynb b/docs/docs/tutorials/program_of_thought/index.ipynbindex fd0d3a8e0..6adb9894f 100644--- a/docs/docs/tutorials/program_of_thought/index.ipynb+++ b/docs/docs/tutorials/program_of_thought/index.ipynb@@ -14,37 +14,14 @@{"cell_type": "markdown","metadata": {},- "source": [- "## 1) Using PythonInterpreter\n",- "\n",- "`ProgramOfThought` integrates an adapted Python interpreter to execute code generated by LMs. \n",- "\n",- "As a brief example to demonstrate how the interpreter works, we'll create an instance of `dspy.PythonInterpreter` and demonstrate the underlying execution of `ProgramOfThought`."- ]+ "source": "## 1) Using LocalSandbox\n\n`ProgramOfThought` integrates an adapted Python sandbox to execute code generated by LMs. \n\nAs a brief example to demonstrate how the sandbox works, we'll create an instance of `dspy.LocalSandbox` and demonstrate the underlying execution of `ProgramOfThought`."},{"cell_type": "code",- "execution_count": 17,+ "execution_count": null,"metadata": {},- "outputs": [- {- "data": {- "text/plain": [- "14"- ]- },- "execution_count": 17,- "metadata": {},- "output_type": "execute_result"- }- ],- "source": [- "import dspy\n",- "interpreter = dspy.PythonInterpreter()\n",- "expr = \"value = 2*5 + 4\\nvalue\"\n",- "answer = interpreter.execute(expr)\n",- "answer"- ]+ "outputs": [],+ "source": "import dspy\nsandbox = dspy.LocalSandbox()\nexpr = \"value = 2*5 + 4\\nvalue\"\nanswer = sandbox.execute(expr)\nanswer"},{"cell_type": "markdown",@@ -211,9 +188,7 @@{"cell_type": "markdown","metadata": {},- "source": [- "We see that the generated Python code defines a function for intermediate computations and returns the final answer upon execution through the `PythonInterpreter`, getting the right answer."- ]+ "source": "We see that the generated Python code defines a function for intermediate computations and returns the final answer upon execution through the `LocalSandbox`, getting the right answer."},{"cell_type": "markdown",@@ -743,4 +718,4 @@},"nbformat": 4,"nbformat_minor": 2-}+}\ No newline at end of filediff --git a/dspy/predict/__init__.py b/dspy/predict/__init__.pyindex 1d4ddffce..906ef90ae 100644--- a/dspy/predict/__init__.py+++ b/dspy/predict/__init__.py@@ -9,6 +9,7 @@ from dspy.predict.predict import Predictfrom dspy.predict.program_of_thought import ProgramOfThoughtfrom dspy.predict.react import ReAct, Toolfrom dspy.predict.refine import Refine+from dspy.predict.rlm import RLM__all__ = ["majority",@@ -21,6 +22,7 @@ __all__ = ["ProgramOfThought","ReAct","Refine",+ "RLM","Tool","Parallel",]diff --git a/dspy/predict/program_of_thought.py b/dspy/predict/program_of_thought.pyindex 0296bf522..a854baccc 100644--- a/dspy/predict/program_of_thought.py+++ b/dspy/predict/program_of_thought.py@@ -3,6 +3,7 @@ import loggingimport reimport dspy+from dspy.primitives.code_interpreter import FinalAnswerResultfrom dspy.primitives.module import Modulefrom dspy.primitives.python_interpreter import PythonInterpreterfrom dspy.signatures.signature import Signature, ensure_signature@@ -117,7 +118,7 @@ class ProgramOfThought(Module):instr = [f"You will be given {mode_inputs} and you will respond with {mode_outputs}.",f"Generating executable Python code that programmatically computes the correct {mode_outputs}.",- "After you're done with the computation and think you have the answer, make sure to provide your answer by calling the preloaded function `final_answer()`.",+ "After you're done with the computation and think you have the answer, make sure to provide your answer by calling the preloaded function `FINAL()`.",f'You should structure your answer in a dict object, like {{"field_a": answer_a, ...}}, evaluates to the correct value mapping for {final_outputs}.',]elif mode == "regenerate":@@ -165,8 +166,11 @@ class ProgramOfThought(Module):return None, "Error: Empty code before execution."try:+ result = self.interpreter.execute(code)+ if isinstance(result, FinalAnswerResult):+ result = result.answer# Since it's more complex structure now, just blindly use json to represents all.- output = json.dumps(self.interpreter.execute(code))+ output = json.dumps(result)return output, Noneexcept Exception as e:return None, str(e)diff --git a/dspy/predict/rlm.py b/dspy/predict/rlm.pynew file mode 100644index 000000000..0517a43dc--- /dev/null+++ b/dspy/predict/rlm.py@@ -0,0 +1,639 @@+"""+Recursive Language Model (RLM) module for DSPy.++RLMs are an inference strategy where LLMs treat long contexts as part of an external+environment rather than feeding them directly to the model. The LLM writes Python code+to programmatically examine, decompose, and recursively call sub-LLMs over snippets.++Reference: "Recursive Language Models" (Zhang, Kraska, Khattab, 2025)+"""++from __future__ import annotations++import inspect+import logging+import re+import threading+from concurrent.futures import ThreadPoolExecutor, as_completed+from contextlib import contextmanager+from typing import TYPE_CHECKING, Any, Callable, Iterator++import pydantic++import dspy+from dspy.adapters.utils import parse_value, translate_field_type+from dspy.primitives.code_interpreter import SIMPLE_TYPES, CodeInterpreter, CodeInterpreterError, FinalAnswerResult+from dspy.primitives.module import Module+from dspy.primitives.prediction import Prediction+from dspy.primitives.python_interpreter import PythonInterpreter+from dspy.primitives.repl_types import REPLHistory, REPLVariable+from dspy.signatures.signature import ensure_signature+from dspy.utils.annotation import experimental++if TYPE_CHECKING:++ from dspy.signatures.signature import Signature++logger = logging.getLogger(__name__)++# TODO: Optimize this prompt across a diverse benchmark++ACTION_INSTRUCTIONS_TEMPLATE = """You are tasked with producing the following outputs given the inputs {inputs}:+{output_fields}++You have access to a Python REPL environment. Write Python code and it will be executed. You will see the output, then write more code based on what you learned. This is an iterative process.++Available:+- Variables: {inputs} (your input data)+- `llm_query(prompt)` - query a sub-LLM (~500K char capacity) for semantic analysis+- `llm_query_batched(prompts)` - query multiple prompts concurrently (much faster for multiple queries)+- `print()` - ALWAYS print to see results+- `FINAL({final_output_names})` - submit final answer when done+- `FINAL_VAR({final_var_output_names})` - submit final answer using variable names+- Standard libraries: re, json, collections, math, etc.++IMPORTANT: This is ITERATIVE. Each code block you write will execute, you'll see the output, then you decide what to do next. Do NOT try to solve everything in one step.++1. EXPLORE FIRST - Look at your data before processing it. Print samples, check types/lengths, understand the structure.+2. ITERATE - Write small code snippets, observe outputs, then decide next steps. State persists between iterations.+3. VERIFY BEFORE SUBMITTING - If results seem wrong (zeros, empty, unexpected), reconsider your approach.+4. USE llm_query FOR SEMANTICS - String matching finds WHERE things are; llm_query understands WHAT things mean.++You have max {max_llm_calls} sub-LLM calls. When done, call FINAL() or FINAL_VAR() with your answer."""++# Pattern to match markdown code fences: ```python\n...\n``` or ```\n...\n```+_CODE_FENCE_PATTERN = re.compile(r"^```(?:python|py)?\s*\n(.*?)\n```\s*$", re.DOTALL)+++def _strip_code_fences(code: str) -> str:+ code = code.strip()+ match = _CODE_FENCE_PATTERN.match(code)+ if match:+ return match.group(1)+ return code+++@experimental+class RLM(Module):+ """Recursive Language Model module.++ Uses a sandboxed REPL to let the LLM programmatically explore large contexts+ through code execution. The LLM writes Python code to examine data, call+ sub-LLMs for semantic analysis, and build up answers iteratively.++ The default interpreter is PythonInterpreter (Deno/Pyodide/WASM), but you+ can provide any CodeInterpreter implementation (e.g., MockInterpreter, or write a custom one using E2B or Modal).++ Note: RLM instances are not thread-safe when using a custom interpreter.+ Create separate RLM instances for concurrent use, or use the default+ PythonInterpreter which creates a fresh instance per forward() call.++ Example:+ ```python+ # Basic usage+ rlm = dspy.RLM("context, query -> answer", max_iterations=10)+ result = rlm(context="...very long text...", query="What is the magic number?")+ print(result.answer)+ ```+ """++ def __init__(+ self,+ signature: type[Signature] | str,+ max_iterations: int = 20,+ max_llm_calls: int = 50,+ max_output_chars: int = 100_000,+ verbose: bool = False,+ tools: dict[str, Callable[..., str]] | None = None,+ sub_lm: dspy.LM | None = None,+ interpreter: CodeInterpreter | None = None,+ ):+ """+ Args:+ signature: Defines inputs and outputs. String like "context, query -> answer"+ or a Signature class.+ max_iterations: 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.+ tools: Additional tool functions callable from interpreter code.+ Built-in tools: llm_query(prompt), llm_query_batched(prompts).+ sub_lm: LM for llm_query/llm_query_batched. Defaults to dspy.settings.lm.+ Allows using a different (e.g., cheaper) model for sub-queries.+ interpreter: CodeInterpreter implementation to use. Defaults to PythonInterpreter.+ """+ super().__init__()+ self.signature = ensure_signature(signature)+ self.max_iterations = max_iterations+ self.max_llm_calls = max_llm_calls+ self.max_output_chars = max_output_chars+ self.verbose = verbose+ self.sub_lm = sub_lm+ self._interpreter = interpreter+ self._user_tools = tools or {}+ self._validate_tools(self._user_tools)++ # Build the action and extract signatures+ action_sig, extract_sig = self._build_signatures()+ self.generate_action = dspy.Predict(action_sig)+ self.extract = dspy.Predict(extract_sig)++ # =========================================================================+ # Tool Creation and Validation+ # =========================================================================++ # Reserved tool names that conflict with built-in sandbox functions+ _RESERVED_TOOL_NAMES = frozenset({"llm_query", "llm_query_batched", "FINAL", "FINAL_VAR", "print"})++ def _validate_tools(self, tools: dict[str, Callable]) -> None:+ """Validate user-provided tools have valid names and are callable."""+ for name, func in tools.items():+ if not name.isidentifier():+ raise ValueError(f"Invalid tool name '{name}': must be a valid Python identifier")+ if name in self._RESERVED_TOOL_NAMES:+ raise ValueError(f"Tool name '{name}' conflicts with built-in sandbox function")+ if not callable(func):+ raise TypeError(f"Tool '{name}' must be callable, got {type(func).__name__}")++ def _format_tool_docs(self, tools: dict[str, Callable]) -> str:+ """Format user-provided tools for inclusion in instructions."""+ if not tools:+ return ""++ lines = ["\nAdditional tools available (use these instead of standard library equivalents):"]+ for name, func in tools.items():+ # Get function signature with return type+ try:+ sig = inspect.signature(func)+ params = []+ for p in sig.parameters.values():+ if p.annotation != inspect.Parameter.empty:+ type_name = getattr(p.annotation, "__name__", str(p.annotation))+ params.append(f"{p.name}: {type_name}")+ else:+ params.append(p.name)+ params_str = ", ".join(params)++ # Get return type+ if sig.return_annotation != inspect.Parameter.empty:+ ret_type = getattr(sig.return_annotation, "__name__", str(sig.return_annotation))+ sig_str = f"{name}({params_str}) -> {ret_type}"+ else:+ sig_str = f"{name}({params_str})"+ except (ValueError, TypeError):+ sig_str = f"{name}(...)"++ # Get first line of docstring+ doc = func.__doc__.strip().split("\n")[0] if func.__doc__ else "No description"+ lines.append(f"- `{sig_str}` - {doc}")++ return "\n".join(lines)++ def _make_llm_tools(self, max_workers: int = 8) -> dict[str, Callable]:+ """Create llm_query and llm_query_batched tools with a fresh call counter."""+ state = {"call_count": 0}+ lock = threading.Lock()+ lm = self.sub_lm++ def _check_and_increment(n: int = 1) -> None:+ with lock:+ if state["call_count"] + n > self.max_llm_calls:+ raise RuntimeError(+ f"LLM call limit exceeded: {state['call_count']} + {n} > {self.max_llm_calls}. "+ f"Use Python code for aggregation instead of making more LLM calls."+ )+ state["call_count"] += n++ def _query_lm(prompt: str) -> str:+ target_lm = lm if lm is not None else dspy.settings.lm+ if target_lm is None:+ raise RuntimeError("No LM configured. Use dspy.configure(lm=...) or pass sub_lm to RLM.")+ response = target_lm(prompt)+ return response[0] if isinstance(response, list) and response else str(response)++ def llm_query(prompt: str) -> str:+ """Query the LLM with a prompt string."""+ if not prompt:+ raise ValueError("prompt cannot be empty")+ _check_and_increment(1)+ return _query_lm(prompt)++ def llm_query_batched(prompts: list[str]) -> list[str]:+ """Query the LLM with multiple prompts concurrently."""+ if not prompts:+ return []+ _check_and_increment(len(prompts))++ results: dict[int, str] = {}+ with ThreadPoolExecutor(max_workers=max_workers) as executor:+ future_to_idx = {executor.submit(_query_lm, p): i for i, p in enumerate(prompts)}+ for future in as_completed(future_to_idx):+ idx = future_to_idx[future]+ try:+ results[idx] = future.result()+ except Exception as e:+ results[idx] = f"[ERROR] {e}"+ return [results[i] for i in range(len(prompts))]++ return {"llm_query": llm_query, "llm_query_batched": llm_query_batched}++ @property+ def tools(self) -> dict[str, Callable]:+ """User-provided tools (excludes internal llm_query/llm_query_batched)."""+ return dict(self._user_tools)++ # =========================================================================+ # Signature Building+ # =========================================================================++ def _build_signatures(self) -> tuple[Signature, Signature]:+ """Build the action and extract signatures from templates."""+ inputs_str = ", ".join(f"`{n}`" for n in self.signature.input_fields)++ # Simple names for FINAL() examples+ final_output_names = ", ".join(self.signature.output_fields.keys())++ # Final output names for FINAL_VAR() examples+ final_var_output_names = ", ".join(f"`{n}`" for n in self.signature.output_fields.keys())++ output_fields = "\n".join(+ f"- {translate_field_type(n, f)}"+ for n, f in self.signature.output_fields.items()+ )++ # Include original signature instructions (docstring) if present+ task_instructions = f"{self.signature.instructions}\n\n" if self.signature.instructions else ""++ # Format tool documentation for user-provided tools+ tool_docs = self._format_tool_docs(self._user_tools)++ action_sig = (+ dspy.Signature({}, task_instructions + ACTION_INSTRUCTIONS_TEMPLATE.format(+ inputs=inputs_str, final_output_names=final_output_names, final_var_output_names=final_var_output_names, output_fields=output_fields,+ max_llm_calls=self.max_llm_calls,+ ) + tool_docs)+ .append("variables_info", dspy.InputField(desc="Metadata about the variables available in the REPL"), type_=list[REPLVariable])+ .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("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."), type_=str)+ )++ # Extract signature: includes the original signature's output fields and task instructions.+ extract_instructions = """Based on the REPL trajectory, extract the final outputs now.++ Review your trajectory to see what information you gathered and what values you computed, then provide the final outputs."""++ # Prepend original task instructions to extract instructions so the LLM knows what task to extract for+ extended_task_instructions = ""+ if task_instructions:+ extended_task_instructions = "The trajectory was generated with the following objective: \n" + task_instructions + "\n"+ full_extract_instructions = extended_task_instructions + extract_instructions++ extract_sig = dspy.Signature(+ {**self.signature.output_fields},+ full_extract_instructions,+ )+ extract_sig = extract_sig.prepend("repl_history", dspy.InputField(desc="Your REPL interactions so far"), type_=REPLHistory)+ extract_sig = extract_sig.prepend("variables_info", dspy.InputField(desc="Metadata about the variables available in the REPL"), type_=list[REPLVariable])++ return action_sig, extract_sig++ # =========================================================================+ # Input/Output Processing+ # =========================================================================++ def _get_output_fields_info(self) -> list[dict]:+ """Get output field info for sandbox registration."""+ fields = []+ for name, field in self.signature.output_fields.items():+ annotation = getattr(field, "annotation", str)+ field_info = {"name": name}+ # Only include type for simple types that work in function signatures+ # Complex types like Literal, Union, etc. are not included+ if annotation in SIMPLE_TYPES:+ field_info["type"] = annotation.__name__+ fields.append(field_info)+ return fields++ def _build_variables(self, **input_args: Any) -> list[REPLVariable]:+ """Build REPLVariable list from input arguments with field metadata."""+ variables = []+ for name, value in input_args.items():+ field_info = self.signature.input_fields.get(name)+ variables.append(REPLVariable.from_value(name, value, field_info=field_info))+ return variables++ def _format_output(self, output: str) -> str:+ """Format and truncate REPL output."""+ if not output:+ return "(no output - did you forget to print?)"+ if len(output) > self.max_output_chars:+ return output[:self.max_output_chars] + "\n... (truncated)"+ return output++ def _validate_inputs(self, input_args: dict[str, Any]) -> None:+ """Raise ValueError if required input fields are missing."""+ missing = set(self.signature.input_fields.keys()) - set(input_args.keys())+ if missing:+ raise ValueError(f"Missing required inputs: {sorted(missing)}")++ # =========================================================================+ # CodeInterpreter Lifecycle+ # =========================================================================++ def _prepare_execution_tools(self) -> dict[str, Callable]:+ """Create fresh LLM tools and merge with user-provided tools."""+ execution_tools = self._make_llm_tools()+ execution_tools.update(self._user_tools)+ return execution_tools++ def _inject_execution_context(self, interpreter: CodeInterpreter, execution_tools: dict[str, Callable]) -> None:+ """Inject execution tools and output fields into an interpreter.++ This ensures llm_query, llm_query_batched, and typed FINAL signatures are available,+ even for user-provided interpreters. Each forward() call gets fresh tools with a+ fresh call counter, so we must inject on every execution.+ """+ interpreter.tools.update(execution_tools)+ if hasattr(interpreter, "output_fields"):+ interpreter.output_fields = self._get_output_fields_info()+ # Reset registration flag to force re-registration with fresh tools+ if hasattr(interpreter, "_tools_registered"):+ interpreter._tools_registered = False++ @contextmanager+ def _interpreter_context(self, execution_tools: dict[str, Callable]) -> Iterator[CodeInterpreter]:+ """Yield interpreter, creating PythonInterpreter if none provided at init."""+ if self._interpreter is not None:+ self._inject_execution_context(self._interpreter, execution_tools)+ yield self._interpreter+ else:+ repl = PythonInterpreter(+ tools=execution_tools,+ output_fields=self._get_output_fields_info(),+ )+ try:+ yield repl+ finally:+ repl.shutdown()++ # =========================================================================+ # Execution Core+ # =========================================================================++ def _extract_fallback(+ self,+ variables: list[REPLVariable],+ history: REPLHistory,+ output_field_names: list[str],+ ) -> Prediction:+ """Use extract module to get final answer when max iterations reached."""+ logger.warning("RLM reached max iterations, using extract to get final answer")++ extract_pred = self.extract(+ variables_info=variables,+ repl_history=history,+ )++ return Prediction(+ trajectory=[e.model_dump() for e in history],+ final_reasoning="Extract forced final answer",+ **{name: getattr(extract_pred, name) for name in output_field_names},+ )++ def _process_final_answer(+ self,+ result: FinalAnswerResult,+ output_field_names: list[str],+ ) -> tuple[dict[str, Any] | None, str | None]:+ """Validate and parse FinalAnswerResult. Returns (parsed_outputs, None) or (None, error)."""+ raw_answer = result.answer++ # Validate raw_answer is a dict+ if not isinstance(raw_answer, dict):+ return None, f"[Error] FINAL returned {type(raw_answer).__name__}, expected dict with fields: {output_field_names}"++ # Validate all required output fields are present+ missing = set(output_field_names) - set(raw_answer.keys())+ if missing:+ return None, f"[Error] Missing output fields: {sorted(missing)}. Use FINAL({', '.join(output_field_names)})"++ # Parse and validate each output field+ parsed_outputs = {}+ type_errors = []+ for name in output_field_names:+ field = self.signature.output_fields[name]+ annotation = getattr(field, "annotation", str)+ try:+ parsed_outputs[name] = parse_value(raw_answer[name], annotation)+ except (ValueError, pydantic.ValidationError) as e:+ type_errors.append(+ f"{name}: expected {annotation.__name__ if hasattr(annotation, '__name__') else annotation}, "+ f"got {type(raw_answer[name]).__name__}: {e}"+ )++ if type_errors:+ return None, "[Type Error] " + "; ".join(type_errors)++ return parsed_outputs, None++ def _process_execution_result(+ self,+ pred: Any,+ result: Any,+ history: REPLHistory,+ output_field_names: list[str],+ ) -> Prediction | REPLHistory:+ """Process interpreter result, returning Prediction if final, else updated history.++ This shared helper reduces duplication between sync and async execution paths.++ Args:+ pred: The prediction containing reasoning and code attributes+ result: Result from interpreter.execute() - FinalAnswerResult, list, str, or error string+ history: Current REPL history+ output_field_names: List of expected output field names++ Returns:+ Prediction if FINAL was called successfully, else updated REPLHistory+ """+ # Handle error strings from caught exceptions+ if isinstance(result, str) and result.startswith("[Error]"):+ output = self._format_output(result)+ return history.append(reasoning=pred.reasoning, code=pred.code, output=output)++ # Handle FINAL answer+ if isinstance(result, FinalAnswerResult):+ parsed_outputs, error = self._process_final_answer(result, output_field_names)++ if error:+ return history.append(reasoning=pred.reasoning, code=pred.code, output=error)++ final_history = history.append(+ reasoning=pred.reasoning, code=pred.code, output=f"FINAL: {parsed_outputs}"+ )+ return Prediction(+ **parsed_outputs,+ trajectory=[e.model_dump() for e in final_history],+ final_reasoning=pred.reasoning,+ )++ # Format non-final result as output+ if isinstance(result, list):+ output = "\n".join(map(str, result))+ else:+ output = str(result) if result else ""++ output = self._format_output(output)+ return history.append(reasoning=pred.reasoning, code=pred.code, output=output)++ def _execute_iteration(+ self,+ repl: CodeInterpreter,+ variables: list[REPLVariable],+ history: REPLHistory,+ iteration: int,+ input_args: dict[str, Any],+ output_field_names: list[str],+ ) -> Prediction | REPLHistory:+ """Execute one iteration. Returns Prediction if done, else updated REPLHistory."""+ action = self.generate_action(+ variables_info=variables,+ repl_history=history,+ iteration=f"{iteration + 1}/{self.max_iterations}",+ )+ if self.verbose:+ logger.info(+ f"RLM iteration {iteration + 1}/{self.max_iterations}\n"+ f"Reasoning: {action.reasoning}\nCode:\n{action.code}"+ )++ try:+ code = _strip_code_fences(action.code)+ result = repl.execute(code, variables=dict(input_args))+ except (CodeInterpreterError, SyntaxError) as e:+ result = f"[Error] {e}"++ return self._process_execution_result(action, result, history, output_field_names)++ # =========================================================================+ # Public Interface+ # =========================================================================++ def forward(self, **input_args) -> Prediction:+ """Execute RLM to produce outputs from the given inputs.++ Args:+ **input_args: Input values matching the signature's input fields++ Returns:+ Prediction with output field(s) from the signature and 'trajectory' for debugging++ Raises:+ ValueError: If required input fields are missing+ """+ self._validate_inputs(input_args)++ output_field_names = list(self.signature.output_fields.keys())+ execution_tools = self._prepare_execution_tools()+ variables = self._build_variables(**input_args)++ with self._interpreter_context(execution_tools) as repl:+ history: REPLHistory = REPLHistory()++ for iteration in range(self.max_iterations):+ result: Prediction | REPLHistory = self._execute_iteration(+ repl, variables, history, iteration, input_args, output_field_names+ )+ if isinstance(result, Prediction):+ return result+ history = result++ # Max iterations reached - use extract fallback+ return self._extract_fallback(variables, history, output_field_names)++ async def _aextract_fallback(+ self,+ variables: list[REPLVariable],+ history: REPLHistory,+ output_field_names: list[str],+ ) -> Prediction:+ """Async version: Use extract module when max iterations reached."""+ logger.warning("RLM reached max iterations, using extract to get final answer")++ extract_pred = await self.extract.acall(+ variables_info=variables,+ repl_history=history,+ )++ return Prediction(+ trajectory=[e.model_dump() for e in history],+ final_reasoning="Extract forced final answer",+ **{name: getattr(extract_pred, name) for name in output_field_names},+ )++ async def _aexecute_iteration(+ self,+ repl: CodeInterpreter,+ variables: list[REPLVariable],+ history: REPLHistory,+ iteration: int,+ input_args: dict[str, Any],+ output_field_names: list[str],+ ) -> Prediction | REPLHistory:+ """Async version: Execute one iteration."""+ pred = await self.generate_action.acall(+ variables_info=variables,+ repl_history=history,+ iteration=f"{iteration + 1}/{self.max_iterations}",+ )+ if self.verbose:+ logger.info(+ f"RLM iteration {iteration + 1}/{self.max_iterations}\n"+ f"Reasoning: {pred.reasoning}\nCode:\n{pred.code}"+ )++ try:+ code = _strip_code_fences(pred.code)+ result = repl.execute(code, variables=dict(input_args))+ except (CodeInterpreterError, SyntaxError) as e:+ result = f"[Error] {e}"++ return self._process_execution_result(pred, result, history, output_field_names)++ async def aforward(self, **input_args) -> Prediction:+ """Async version of forward(). Execute RLM to produce outputs.++ Args:+ **input_args: Input values matching the signature's input fields++ Returns:+ Prediction with output field(s) from the signature and 'trajectory' for debugging++ Raises:+ ValueError: If required input fields are missing+ """+ self._validate_inputs(input_args)++ output_field_names = list(self.signature.output_fields.keys())+ execution_tools = self._prepare_execution_tools()+ variables = self._build_variables(**input_args)++ with self._interpreter_context(execution_tools) as repl:+ history = REPLHistory()++ for iteration in range(self.max_iterations):+ result = await self._aexecute_iteration(+ repl, variables, history, iteration, input_args, output_field_names+ )+ if isinstance(result, Prediction):+ return result+ history = result++ # Max iterations reached - use extract fallback+ return await self._aextract_fallback(variables, history, output_field_names)++ def __call__(self, **input_args) -> Prediction:+ """Execute RLM. Alias for forward()."""+ return self.forward(**input_args)diff --git a/dspy/primitives/__init__.py b/dspy/primitives/__init__.pyindex 4bd9b1fd3..b45a0da2e 100644--- a/dspy/primitives/__init__.py+++ b/dspy/primitives/__init__.py@@ -1,14 +1,18 @@from dspy.primitives.base_module import BaseModule+from dspy.primitives.code_interpreter import CodeInterpreter, CodeInterpreterError, FinalAnswerResultfrom dspy.primitives.example import Examplefrom dspy.primitives.module import Modulefrom dspy.primitives.prediction import Completions, Predictionfrom dspy.primitives.python_interpreter import PythonInterpreter__all__ = [- "Example","BaseModule",- "Prediction",+ "CodeInterpreter","Completions",+ "Example",+ "FinalAnswerResult",+ "CodeInterpreterError","Module",+ "Prediction","PythonInterpreter",]diff --git a/dspy/primitives/code_interpreter.py b/dspy/primitives/code_interpreter.pynew file mode 100644index 000000000..9565faf69--- /dev/null+++ b/dspy/primitives/code_interpreter.py@@ -0,0 +1,133 @@+"""+Abstract interpreter interface for code execution environments.++This module defines the CodeInterpreter protocol that allows RLM and other+code-executing modules to work with different interpreter implementations:+- PythonInterpreter: Local Deno/Pyodide WASM interpreter+- MockInterpreter: Scriptable responses for testing+"""++from typing import Any, Callable, Protocol, runtime_checkable++# Types that can be used directly in Python function signatures for FINAL()+SIMPLE_TYPES = (str, int, float, bool, list, dict, type(None))+++class CodeInterpreterError(RuntimeError):+ """Error raised during code execution in an interpreter.++ This covers runtime errors, undefined variables, tool call failures, etc.+ SyntaxError is raised separately for invalid Python syntax.+ """+++class FinalAnswerResult:+ """Returned by interpreter.execute() when FINAL() or FINAL_VAR() is called.++ This signals that the code execution loop should terminate and return+ the contained answer to the caller.+ """++ def __init__(self, answer: Any):+ self.answer = answer++ def __repr__(self) -> str:+ return f"FinalAnswerResult({self.answer!r})"++ def __eq__(self, other: object) -> bool:+ if not isinstance(other, FinalAnswerResult):+ return NotImplemented+ return self.answer == other.answer+++@runtime_checkable+class CodeInterpreter(Protocol):+ """Protocol for code execution environments (interpreters).++ Implementations must provide:+ - start(): Initialize the interpreter (optional, can be lazy)+ - execute(): Run code and return results+ - shutdown(): Clean up resources++ The interpreter maintains state across execute() calls within a session,+ allowing variables defined in one call to be used in subsequent calls.++ Lifecycle:+ 1. Create instance (config only, no resources allocated)+ 2. start() - Initialize interpreter (explicit) or let execute() do it (lazy)+ 3. execute() - Run code (can be called many times)+ 4. shutdown() - Release resources++ Example implementations:+ - LocalInterpreter: Deno/Pyodide WASM interpreter (local)+ - MockInterpreter: Scriptable responses for testing++ Pooling:+ For interpreter pooling, call start() to pre-warm instances, then+ distribute execute() calls across the pool.+ """++ @property+ def tools(self) -> dict[str, Callable[..., str]]:+ """Tools available for interpreter code to call.++ Tools are host-side functions that can be invoked from within the+ interpreter. Each tool accepts keyword arguments and returns a string.++ Implementations should accept tools via constructor and expose them+ through this property.+ """+ ...++ def start(self) -> None:+ """Initialize the interpreter and allocate resources.++ This method prepares the interpreter for code execution. It can be called+ explicitly to pre-warm the interpreter, or implementations may call it+ lazily on first execute().++ For pooling scenarios, call start() on multiple instances to have+ them ready before distributing work.++ Calling start() multiple times should be safe (idempotent).+ """+ ...++ def execute(+ self,+ code: str,+ variables: dict[str, Any] | None = None,+ ) -> Any:+ """Execute Python code and return the result.++ Args:+ code: Python code to execute+ variables: Variables to inject into the namespace before execution.+ These are available as top-level variables in the code.++ Returns:+ One of:+ - FinalAnswerResult: If FINAL() or FINAL_VAR() was called in code+ - str: Captured stdout from print() statements+ - list: Multiple output lines+ - None: If no output was produced++ Raises:+ CodeInterpreterError: On runtime errors (undefined vars, tool failures, etc.)+ SyntaxError: On invalid Python syntax++ Note:+ State persists across calls. Variables defined in one execute()+ call are available in subsequent calls until shutdown().++ If start() was not called, implementations should call it lazily.+ """+ ...++ def shutdown(self) -> None:+ """Release resources and terminate the interpreter session.++ After shutdown(), the interpreter should not be used again.+ A new instance should be created for a fresh session.+ """+ ...diff --git a/dspy/primitives/python_interpreter.py b/dspy/primitives/python_interpreter.pyindex ad6f34ffd..4782f92af 100644--- a/dspy/primitives/python_interpreter.py+++ b/dspy/primitives/python_interpreter.py@@ -1,30 +1,51 @@+"""+Local interpreter for secure Python code execution using Deno/Pyodide.++This module provides PythonInterpreter, which runs Python code in a sandboxed+WASM environment using Deno and Pyodide. It implements the Interpreter+protocol defined in interpreter.py.+"""++import functools+import inspectimport json+import keywordimport loggingimport osimport subprocessfrom os import PathLike-from types import TracebackType-from typing import Any+from typing import Any, Callable-logger = logging.getLogger(__name__)+from dspy.primitives.code_interpreter import SIMPLE_TYPES, CodeInterpreterError, FinalAnswerResult-class InterpreterError(RuntimeError):- pass+__all__ = ["PythonInterpreter", "FinalAnswerResult", "CodeInterpreterError"]++logger = logging.getLogger(__name__)class PythonInterpreter:- r"""- PythonInterpreter that runs code in a sandboxed environment using Deno and Pyodide.+ """Local interpreter for secure Python execution using Deno and Pyodide.++ Implements the Interpreter protocol for secure code execution in a+ WASM-based sandbox. Code runs in an isolated Pyodide environment with+ no access to the host filesystem, network, or environment by default.Prerequisites:- - Deno (https://docs.deno.com/runtime/getting_started/installation/).-- Example Usage:- ```python- code_string = "print('Hello'); 1 + 2"- with PythonInterpreter() as interp:- output = interp(code_string) # If final statement is non-None, prints the numeric result, else prints captured output- ```+ Deno must be installed: https://docs.deno.com/runtime/getting_started/installation/++ Example:+ ```python+ # Basic execution+ with PythonInterpreter() as interp:+ result = interp("print(1 + 2)") # Returns "3"++ # With host-side tools+ def my_tool(question: str) -> str:+ return "answer"++ with PythonInterpreter(tools={"my_tool": my_tool}) as interp:+ result = interp("print(my_tool(question='test'))")+ ```"""def __init__(@@ -35,25 +56,35 @@ class PythonInterpreter:enable_env_vars: list[str] | None = None,enable_network_access: list[str] | None = None,sync_files: bool = True,+ tools: dict[str, Callable[..., str]] | None = None,+ output_fields: list[dict] | None = None,) -> None:"""Args:deno_command: command list to launch Deno.- enable_read_paths: Files or directories to allow reading from in the sandbox.- enable_write_paths: Files or directories to allow writing to in the sandbox.+ enable_read_paths: Files or directories to allow reading from in the sandbox.+ enable_write_paths: Files or directories to allow writing to in the sandbox.All write paths will also be able to be read from for mounting.enable_env_vars: Environment variable names to allow in the sandbox.enable_network_access: Domains or IPs to allow network access in the sandbox.sync_files: If set, syncs changes within the sandbox back to original files after execution.+ tools: Dictionary mapping tool names to callable functions.+ Each function should accept keyword arguments and return a string.+ Tools are callable directly from sandbox code by name.+ output_fields: List of output field definitions for typed FINAL signature.+ Each dict should have 'name' and optionally 'type' keys."""if isinstance(deno_command, dict):- deno_command = None # no-op, just a guard in case someone passes a dict+ raise TypeError("deno_command must be a list of strings, not a dict")self.enable_read_paths = enable_read_paths or []self.enable_write_paths = enable_write_paths or []self.enable_env_vars = enable_env_vars or []self.enable_network_access = enable_network_access or []self.sync_files = sync_files+ self.tools = dict(tools) if tools else {}+ self.output_fields = output_fields+ self._tools_registered = False# TODO later on add enable_run (--allow-run) by proxying subprocess.run through Deno.run() to fix 'emscripten does not support processes' errorif deno_command:@@ -75,7 +106,7 @@ class PythonInterpreter:allowed_read_paths.extend(str(p) for p in self.enable_write_paths)args.append(f"--allow-read={','.join(allowed_read_paths)}")- self._env_arg = ""+ self._env_arg = ""if self.enable_env_vars:user_vars = [str(v).strip() for v in self.enable_env_vars]args.append("--allow-env=" + ",".join(user_vars))@@ -95,20 +126,13 @@ class PythonInterpreter:self.deno_process = Noneself._mounted_files = False- _deno_dir_cache = None-- @classmethod- def _get_deno_dir(cls) -> str | None:- if cls._deno_dir_cache:- return cls._deno_dir_cache-+ @staticmethod+ @functools.lru_cache(maxsize=1)+ def _get_deno_dir() -> str | None:if "DENO_DIR" in os.environ:- cls._deno_dir_cache = os.environ["DENO_DIR"]- return cls._deno_dir_cache+ return os.environ["DENO_DIR"]try:- # Attempt to find deno in path or use just "deno"- # We can't easily know which 'deno' will be used if not absolute, but 'deno' is a safe betresult = subprocess.run(["deno", "info", "--json"],capture_output=True,@@ -117,11 +141,9 @@ class PythonInterpreter:)if result.returncode == 0:info = json.loads(result.stdout)- cls._deno_dir_cache = info.get("denoDir")- return cls._deno_dir_cache+ return info.get("denoDir")except Exception:logger.warning("Unable to find the Deno cache dir.")- passreturn None@@ -165,6 +187,75 @@ class PythonInterpreter:self.deno_process.stdin.write(sync_msg + "\n")self.deno_process.stdin.flush()+ def _extract_parameters(self, fn: Callable) -> list[dict]:+ """Extract parameter info from a callable for sandbox registration."""+ sig = inspect.signature(fn)+ params = []+ for name, param in sig.parameters.items():+ p = {"name": name}+ # Only include type for simple types that work in function signatures+ # Complex types like Union, Optional, etc. are not included+ if param.annotation != inspect.Parameter.empty:+ if param.annotation in SIMPLE_TYPES:+ p["type"] = param.annotation.__name__+ if param.default != inspect.Parameter.empty:+ p["default"] = param.default+ params.append(p)+ return params++ def _register_tools(self) -> None:+ """Register tools and output fields with the sandbox."""+ if self._tools_registered:+ return++ # Build registration message with typed tool signatures+ msg = {}++ if self.tools:+ tools_info = []+ for name, fn in self.tools.items():+ tools_info.append({+ "name": name,+ "parameters": self._extract_parameters(fn)+ })+ msg["register_tools"] = tools_info++ if self.output_fields:+ msg["register_outputs"] = self.output_fields++ # Skip if nothing to register+ if not msg:+ self._tools_registered = True+ return++ self.deno_process.stdin.write(json.dumps(msg) + "\n")+ self.deno_process.stdin.flush()+ response_line = self.deno_process.stdout.readline().strip()+ if not response_line:+ raise CodeInterpreterError("No response when registering tools/outputs")+ response = json.loads(response_line)+ if "tools_registered" not in response and "outputs_registered" not in response:+ raise CodeInterpreterError(f"Unexpected response when registering: {response_line}")+ self._tools_registered = True++ def _handle_tool_call(self, request: dict) -> None:+ """Handle a tool call request from the sandbox."""+ request_id, tool_name = request["id"], request["name"]+ call_args = request.get("args", {})++ try:+ if tool_name not in self.tools:+ raise CodeInterpreterError(f"Unknown tool: {tool_name}")+ result = self.tools[tool_name](*call_args.get("args", []), **call_args.get("kwargs", {}))+ is_json = isinstance(result, (list, dict))+ response = {"type": "tool_response", "id": request_id, "error": None,+ "result": json.dumps(result) if is_json else str(result or ""),+ "result_type": "json" if is_json else "string"}+ except Exception as e:+ response = {"type": "tool_response", "id": request_id, "result": None, "error": str(e)}++ self.deno_process.stdin.write(json.dumps(response) + "\n")+ self.deno_process.stdin.flush()def _ensure_deno_process(self) -> None:if self.deno_process is None or self.deno_process.poll() is not None:@@ -187,31 +278,37 @@ class PythonInterpreter:"> brew install deno\n""For additional configurations: https://docs.deno.com/runtime/getting_started/installation/")- raise InterpreterError(install_instructions) from e+ raise CodeInterpreterError(install_instructions) from edef _inject_variables(self, code: str, variables: dict[str, Any]) -> str:- # Insert Python assignments for each variable at the top of the code- injected_lines = []- for key, value in variables.items():- if not key.isidentifier():- raise InterpreterError(f"Invalid variable name: '{key}'")- python_value = self._serialize_value(value)- injected_lines.append(f"{key} = {python_value}")- injected_code = "\n".join(injected_lines) + "\n" + code- return injected_code+ """Insert Python assignments for each variable at the top of the code."""+ for key in variables:+ if not key.isidentifier() or keyword.iskeyword(key):+ raise CodeInterpreterError(f"Invalid variable name: '{key}'")+ assignments = [f"{k} = {self._serialize_value(v)}" for k, v in variables.items()]+ return "\n".join(assignments) + "\n" + code if assignments else codedef _serialize_value(self, value: Any) -> str:- # Basic safe serialization- if isinstance(value, str):+ """Serialize a Python value to a string representation for injection."""+ if value is None:+ return "None"+ elif isinstance(value, str):return repr(value)- elif isinstance(value, (int, float, bool)):+ elif isinstance(value, bool):return str(value)- elif value is None:- return "None"- elif isinstance(value, list) or isinstance(value, dict):+ elif isinstance(value, (int, float)):+ return str(value)+ elif isinstance(value, (list, dict)):return json.dumps(value)+ elif isinstance(value, tuple):+ return json.dumps(list(value))+ elif isinstance(value, set):+ try:+ return json.dumps(sorted(value))+ except TypeError:+ return json.dumps(list(value))else:- raise InterpreterError(f"Unsupported value type: {type(value).__name__}")+ raise CodeInterpreterError(f"Unsupported value type: {type(value).__name__}")def execute(self,@@ -222,6 +319,7 @@ class PythonInterpreter:code = self._inject_variables(code, variables)self._ensure_deno_process()self._mount_files()+ self._register_tools()# Send the code as JSONinput_data = json.dumps({"code": code})@@ -230,51 +328,67 @@ class PythonInterpreter:self.deno_process.stdin.flush()except BrokenPipeError:# If the process died, restart and try again once+ self._tools_registered = Falseself._ensure_deno_process()+ self._register_tools()self.deno_process.stdin.write(input_data + "\n")self.deno_process.stdin.flush()- # Read one JSON line from stdout- output_line = self.deno_process.stdout.readline().strip()- if not output_line:- # Possibly the subprocess died or gave no output- err_output = self.deno_process.stderr.read()- raise InterpreterError(f"No output from Deno subprocess. Stderr: {err_output}")+ # Read and handle messages until we get the final output.+ # Loop is needed because tool calls require back-and-forth communication.+ while True:+ output_line = self.deno_process.stdout.readline().strip()+ if not output_line:+ # Possibly the subprocess died or gave no output+ err_output = self.deno_process.stderr.read()+ raise CodeInterpreterError(f"No output from Deno subprocess. Stderr: {err_output}")- # Parse that line as JSON- try:- result = json.loads(output_line)- except json.JSONDecodeError:- # If not valid JSON, just return raw text- result = {"output": output_line}-- # If we have an error, determine if it's a SyntaxError or other error using error.errorType.- if "error" in result:- error_msg = result["error"]- error_type = result.get("errorType", "Sandbox Error")- if error_type == "FinalAnswer":- # The `FinalAnswer` trick to receive output from the sandbox interpreter,- # just simply replace the output with the arguments.- result["output"] = result.get("errorArgs", None)- elif error_type == "SyntaxError":- raise SyntaxError(f"Invalid Python syntax. message: {error_msg}")- else:- raise InterpreterError(f"{error_type}: {result.get('errorArgs') or error_msg}")-- # If there's no error or got `FinalAnswer`, return the "output" field- self._sync_files()- return result.get("output", None)+ # Parse that line as JSON+ try:+ result = json.loads(output_line)+ except json.JSONDecodeError:+ # If not valid JSON, just return raw text+ result = {"output": output_line}++ # Handle tool call requests from sandbox+ if result.get("type") == "tool_call":+ self._handle_tool_call(result)+ continue++ # Handle errors based on errorType+ if "error" in result:+ error_msg = result["error"]+ error_type = result.get("errorType", "Sandbox Error")+ error_args = result.get("errorArgs", [])++ if error_type == "FinalAnswer":+ answer = error_args[0] if error_args else None+ self._sync_files()+ return FinalAnswerResult(answer)+ elif error_type == "SyntaxError":+ raise SyntaxError(f"Invalid Python syntax. message: {error_msg}")+ else:+ raise CodeInterpreterError(f"{error_type}: {error_args or error_msg}")++ # If there's no error or got `FinalAnswer`, return the "output" field+ self._sync_files()+ return result.get("output", None)++ def start(self) -> None:+ """Initialize the Deno/Pyodide sandbox.++ This pre-warms the sandbox by starting the Deno subprocess.+ Can be called explicitly for pooling, or will be called lazily+ on first execute().++ Idempotent: safe to call multiple times.+ """+ self._ensure_deno_process()def __enter__(self):return self- # All exception fields are ignored and the runtime will automatically re-raise the exception- def __exit__(- self,- _exc_type: type[BaseException] | None,- _exc_val: BaseException | None,- _exc_tb: TracebackType | None,- ):+ def __exit__(self, *_):self.shutdown()def __call__(@@ -286,9 +400,8 @@ class PythonInterpreter:def shutdown(self) -> None:if self.deno_process and self.deno_process.poll() is None:- shutdown_message = json.dumps({"shutdown": True}) + "\n"- self.deno_process.stdin.write(shutdown_message)+ self.deno_process.stdin.write(json.dumps({"shutdown": True}) + "\n")self.deno_process.stdin.flush()self.deno_process.stdin.close()self.deno_process.wait()- self.deno_process = None+ self.deno_process = Nonediff --git a/dspy/primitives/repl_types.py b/dspy/primitives/repl_types.pynew file mode 100644index 000000000..d13af7940--- /dev/null+++ b/dspy/primitives/repl_types.py@@ -0,0 +1,147 @@+"""+REPL data types for RLM and interpreter interactions.++These types represent the state and history of REPL-based execution:+- REPLVariable: Metadata about variables available in the REPL+- REPLEntry: A single interaction (reasoning, code, output)+- REPLHistory: Container for the full interaction history+"""++from __future__ import annotations++import json+from typing import TYPE_CHECKING, Any, Iterator++import pydantic+from pydantic import Field++from dspy.adapters.utils import serialize_for_json++if TYPE_CHECKING:+ from pydantic.fields import FieldInfo++__all__ = ["REPLVariable", "REPLEntry", "REPLHistory"]+++class REPLVariable(pydantic.BaseModel):+ """Metadata about a variable available in the REPL environment."""++ name: str+ type_name: str+ desc: str = ""+ constraints: str = ""+ total_length: int+ preview: str++ model_config = pydantic.ConfigDict(frozen=True)++ @classmethod+ def from_value(+ cls,+ name: str,+ value: Any,+ field_info: FieldInfo | None = None,+ preview_chars: int = 500,+ ) -> REPLVariable:+ """Create REPLVariable from an actual value and optional field info.++ Args:+ name: Variable name+ value: The actual value+ field_info: Optional pydantic FieldInfo with desc/constraints metadata+ preview_chars: Max characters for preview+ """+ jsonable = serialize_for_json(value)+ if isinstance(jsonable, (dict, list)):+ value_str = json.dumps(jsonable, indent=2)+ else:+ value_str = str(jsonable)+ is_truncated = len(value_str) > preview_chars+ preview = value_str[:preview_chars] + ("..." if is_truncated else "")++ # Extract desc and constraints from field_info if provided+ desc = ""+ constraints = ""+ if field_info and hasattr(field_info, "json_schema_extra") and field_info.json_schema_extra:+ raw_desc = field_info.json_schema_extra.get("desc", "")+ # Skip placeholder descs like "${name}"+ if raw_desc and not raw_desc.startswith("${"):+ desc = raw_desc+ constraints = field_info.json_schema_extra.get("constraints", "")++ return cls(+ name=name,+ type_name=type(value).__name__,+ desc=desc,+ constraints=constraints,+ total_length=len(value_str),+ preview=preview,+ )++ def format(self) -> str:+ """Format variable metadata for prompt inclusion."""+ lines = [f"Variable: `{self.name}` (access it in your code)"]+ lines.append(f"Type: {self.type_name}")+ if self.desc:+ lines.append(f"Description: {self.desc}")+ if self.constraints:+ lines.append(f"Constraints: {self.constraints}")+ lines.append(f"Total length: {self.total_length:,} characters")+ lines.append(f"Preview:\n```\n{self.preview}\n```")+ return "\n".join(lines)++ @pydantic.model_serializer()+ def serialize_model(self) -> str:+ return self.format()+++class REPLEntry(pydantic.BaseModel):+ """A single REPL interaction entry containing reasoning, code, and output."""++ reasoning: str = ""+ code: str+ output: str++ model_config = pydantic.ConfigDict(frozen=True)++ def format(self, index: int, max_output_chars: int = 5000) -> str:+ """Format this entry for inclusion in prompts."""+ output = self.output+ if len(output) > max_output_chars:+ output = output[:max_output_chars] + f"\n... (truncated to {max_output_chars}/{len(self.output):,} chars)"+ reasoning_line = f"Reasoning: {self.reasoning}\n" if self.reasoning else ""+ return f"=== Step {index + 1} ===\n{reasoning_line}Code:\n```python\n{self.code}\n```\nOutput ({len(self.output):,} chars):\n{output}"+++class REPLHistory(pydantic.BaseModel):+ """Container for REPL interaction history.++ Immutable: append() returns a new instance with the entry added.+ """++ entries: list[REPLEntry] = Field(default_factory=list)++ model_config = pydantic.ConfigDict(frozen=True)++ def format(self, max_output_chars: int = 5000) -> str:+ if not self.entries:+ return "You have not interacted with the REPL environment yet."+ return "\n".join(entry.format(index=i, max_output_chars=max_output_chars) for i, entry in enumerate(self.entries))++ @pydantic.model_serializer()+ def serialize_model(self) -> str:+ return self.format()++ def append(self, *, reasoning: str = "", code: str, output: str) -> REPLHistory:+ """Return a new REPLHistory with the entry appended."""+ new_entry = REPLEntry(reasoning=reasoning, code=code, output=output)+ return REPLHistory(entries=list(self.entries) + [new_entry])++ def __len__(self) -> int:+ return len(self.entries)++ def __iter__(self) -> Iterator[REPLEntry]:+ return iter(self.entries)++ def __bool__(self) -> bool:+ return len(self.entries) > 0diff --git a/dspy/primitives/runner.js b/dspy/primitives/runner.jsindex d74653fcf..22be7e8a7 100644--- a/dspy/primitives/runner.js+++ b/dspy/primitives/runner.js@@ -1,10 +1,206 @@-// Adapted from "Simon Willison’s TILs" (https://til.simonwillison.net/deno/pyodide-sandbox)+// Adapted from "Simon Willison's TILs" (https://til.simonwillison.net/deno/pyodide-sandbox)import pyodideModule from "npm:pyodide/pyodide.js";import { readLines } from "https://deno.land/[email protected]/io/mod.ts";+// =============================================================================+// Python Code Templates+// =============================================================================++// Setup code run before each user code execution.+// Captures stdout, defines FINAL/FINAL_VAR for early termination, and+// provides a helper to extract exception args across the JS/Python boundary.+const PYTHON_SETUP_CODE = `+import sys, io, json+old_stdout, old_stderr = sys.stdout, sys.stderr+buf_stdout, buf_stderr = io.StringIO(), io.StringIO()+sys.stdout, sys.stderr = buf_stdout, buf_stderr++def last_exception_args():+ return json.dumps(sys.last_exc.args) if sys.last_exc else None++class FinalAnswer(BaseException):+ # Control-flow exception to signal completion (like StopIteration)+ pass++# Default FINAL/FINAL_VAR for single-output signatures (e.g., Program of Thought).+# Only define if not already registered with typed signatures.+if 'FINAL' not in dir():+ def FINAL(answer):+ raise FinalAnswer({"answer": answer})++if 'FINAL_VAR' not in dir():+ def FINAL_VAR(var_name):+ if var_name in globals():+ raise FinalAnswer({"answer": globals()[var_name]})+ raise NameError(f"Variable '{var_name}' not found")+`;++// Generate a tool wrapper function with typed signature.+// Parameters is an array of {name, type?, default?} objects.+// Convert a JavaScript/JSON value to Python literal syntax+const toPythonLiteral = (value) => {+ if (value === null) return 'None';+ if (value === true) return 'True';+ if (value === false) return 'False';+ return JSON.stringify(value); // Works for strings, numbers, arrays, objects+};++const makeToolWrapper = (toolName, parameters = []) => {+ // Build signature parts: "query: str, limit: int = 10"+ const sigParts = parameters.map(p => {+ let part = p.name;+ if (p.type) part += `: ${p.type}`;+ if (p.default !== undefined) part += ` = ${toPythonLiteral(p.default)}`;+ return part;+ });+ const signature = sigParts.join(', ');+ const argNames = parameters.map(p => p.name);++ // If no parameters, fall back to *args, **kwargs for flexibility+ if (parameters.length === 0) {+ return `+import json+from pyodide.ffi import run_sync, JsProxy+def ${toolName}(*args, **kwargs):+ result = run_sync(_js_tool_call("${toolName}", json.dumps({"args": args, "kwargs": kwargs})))+ return result.to_py() if isinstance(result, JsProxy) else result+`;+ }++ return `+import json+from pyodide.ffi import run_sync, JsProxy+def ${toolName}(${signature}):+ _args = [${argNames.join(', ')}]+ result = run_sync(_js_tool_call("${toolName}", json.dumps({"args": _args, "kwargs": {}})))+ return result.to_py() if isinstance(result, JsProxy) else result+`;+};++// Generate FINAL function with output field signature.+// Outputs is an array of {name, type?} objects.+const makeFinalWrapper = (outputs) => {+ if (!outputs || outputs.length === 0) {+ // Fallback to single-arg FINAL if no outputs defined+ return `+def FINAL(answer):+ raise FinalAnswer({"answer": answer})+`;+ }++ const sigParts = outputs.map(o => {+ let part = o.name;+ if (o.type) part += `: ${o.type}`;+ return part;+ });+ const dictParts = outputs.map(o => `"${o.name}": ${o.name}`);++ return `+def FINAL(${sigParts.join(', ')}):+ raise FinalAnswer({${dictParts.join(', ')}})+`;+};++// Generate FINAL_VAR function with positional args mapped to output fields.+// Usage: FINAL_VAR("var1", "var2") maps to output fields in order.+const makeFinalVarWrapper = (outputs) => {+ if (!outputs || outputs.length === 0) {+ // Single-output fallback: FINAL_VAR("var_name")+ return `+def FINAL_VAR(var_name):+ if var_name not in globals():+ raise NameError(f"Variable '{var_name}' not found")+ raise FinalAnswer({"answer": globals()[var_name]})+`;+ }++ // Multi-output: positional args mapped to fields in order+ const fieldNames = outputs.map(o => `"${o.name}"`);+ const expectedCount = outputs.length;+ const fieldList = fieldNames.join(', ');++ return `+def FINAL_VAR(*var_names):+ """Pass variable names positionally, mapped to output fields in order.++ Output fields: ${outputs.map(o => o.name).join(', ')}+ Usage: FINAL_VAR(${outputs.map(o => `"${o.name}_var"`).join(', ')})+ """+ _output_fields = [${fieldList}]+ if len(var_names) != ${expectedCount}:+ raise ValueError(+ f"FINAL_VAR expects ${expectedCount} variable names for output fields {_output_fields}, "+ f"got {len(var_names)}"+ )+ _result = {}+ for field_name, var_name in zip(_output_fields, var_names):+ if var_name not in globals():+ raise NameError(f"Variable '{var_name}' not found for output field '{field_name}'")+ _result[field_name] = globals()[var_name]+ raise FinalAnswer(_result)+`;+};++// Global handler to prevent uncaught promise rejections from crashing Deno+// These can occur during async Python <-> JS interop+globalThis.addEventListener("unhandledrejection", (event) => {+ event.preventDefault();+ console.log(JSON.stringify({+ error: `Unhandled async error: ${event.reason?.message || event.reason}`,+ errorType: "UnhandledPromiseRejection"+ }));+});+const pyodide = await pyodideModule.loadPyodide();+// Tool call support: allows Python code to call host-side functions+// The stdin reader is shared so tool_call can read responses during execution+const stdinReader = readLines(Deno.stdin);+let requestIdCounter = 0;++// This function is called from Python to invoke a host-side tool+async function toolCallBridge(name, argsJson) {+ const requestId = `req_${Date.now()}_${++requestIdCounter}`;++ try {+ // Send tool call request to host+ console.log(JSON.stringify({+ type: "tool_call",+ id: requestId,+ name: name,+ args: JSON.parse(argsJson)+ }));++ // Wait for response from host+ const { value: responseLine, done } = await stdinReader.next();+ if (done) {+ throw new Error("stdin closed while waiting for tool response");+ }++ const response = JSON.parse(responseLine);+ if (response.type !== "tool_response" || response.id !== requestId) {+ throw new Error(`Unexpected response: expected tool_response with id ${requestId}`);+ }++ if (response.error) {+ throw new Error(response.error);+ }++ // Deserialize result based on type+ if (response.result_type === "json") {+ return JSON.parse(response.result);+ }+ return response.result;+ } catch (error) {+ // Re-throw with context so Python can catch it properly+ throw new Error(`Tool bridge error for '${name}': ${error.message}`);+ }+}++// Expose the bridge to Python+pyodide.globals.set("_js_tool_call", toolCallBridge);+try {const env_vars = (Deno.args[0] ?? "").split(",").filter(Boolean);for (const key of env_vars) {@@ -20,7 +216,11 @@ os.environ[${JSON.stringify(key)}] = ${JSON.stringify(val)}console.error("Error setting environment variables in Pyodide:", e);}-for await (const line of readLines(Deno.stdin)) {+// Main loop using shared stdin reader+while (true) {+ const { value: line, done } = await stdinReader.next();+ if (done) break;+let input;try {input = JSON.parse(line);@@ -33,127 +233,85 @@ for await (const line of readLines(Deno.stdin)) {}if (input.mount_file) {- const hostPath = input.mount_file;- const virtualPath = input.virtual_path || hostPath;- try {- const contents = await Deno.readFile(hostPath);- const dirs = virtualPath.split('/').slice(1, -1);- let cur = '';- for (const d of dirs) {- cur += '/' + d;- try {- pyodide.FS.mkdir(cur);- } catch (e) {- if (!(e && e.message && e.message.includes('File exists'))) {- console.log("[DEBUG] Error creating directory in Pyodide file system:", cur, "|", e.message);- }- }+ const virtualPath = input.virtual_path || input.mount_file;+ try {+ const contents = await Deno.readFile(input.mount_file);+ const dirs = virtualPath.split('/').slice(1, -1);+ let cur = '';+ for (const d of dirs) {+ cur += '/' + d;+ try {+ pyodide.FS.mkdir(cur);+ } catch (e) {+ if (!e.message?.includes('File exists')) {+ throw e;}- pyodide.FS.writeFile(virtualPath, contents);- } catch (e) {- console.log(JSON.stringify({error: "Failed to mount file: " + e.message}));+ }}- continue;+ pyodide.FS.writeFile(virtualPath, contents);+ } catch (e) {+ console.log(JSON.stringify({error: "Failed to mount file: " + e.message}));+ }+ continue;}if (input.sync_file) {- const virtualPath = input.sync_file;- const hostPath = input.host_file || virtualPath;- try {- const contents = pyodide.FS.readFile(virtualPath);- await Deno.writeFile(hostPath, contents);- } catch (e) {- console.log("[DEBUG] Failed to sync file:", hostPath, "|", e.message);- }- continue;+ try {+ await Deno.writeFile(input.host_file || input.sync_file, pyodide.FS.readFile(input.sync_file));+ } catch (e) { /* ignore sync errors */ }+ continue;}-- // Expecting an object like { "code": "...", ... }if (typeof input !== 'object' || input === null) {- console.log(JSON.stringify({- error: "Input is not a JSON object",- errorType: "ValueError"- }));+ console.log(JSON.stringify({ error: "Input is not a JSON object", errorType: "ValueError" }));continue;}- // Check for shutdown- if (input.shutdown) {- break;- }+ if (input.shutdown) break;- const code = input.code || "";+ // Register tools and/or output fields+ if (input.register_tools || input.register_outputs) {+ const toolNames = [];- // Wrap execution in a try/catch so we can handle syntax errors, etc.- try {- await pyodide.loadPackagesFromImports(code);- // 1. Temporarily override stdout/stderr so we can capture prints.- pyodide.runPython(`-import sys-import io--# Keep references to the old stdout/stderr so we can restore them later-old_stdout = sys.stdout-old_stderr = sys.stderr--# New "file-like" buffers-buf_stdout = io.StringIO()-buf_stderr = io.StringIO()--sys.stdout = buf_stdout-sys.stderr = buf_stderr- `);-- // 2. Setup proper exception arguments extractor and FinalAnswer bridge- // The idea is borrowed from `smolagents` that uses the exception to simulate non-local exit- pyodide.runPython(`-import json+ // Register tools with typed signatures+ if (input.register_tools) {+ for (const tool of input.register_tools) {+ // Support both old format (string) and new format (object with parameters)+ if (typeof tool === 'string') {+ pyodide.runPython(makeToolWrapper(tool, []));+ toolNames.push(tool);+ } else {+ pyodide.runPython(makeToolWrapper(tool.name, tool.parameters || []));+ toolNames.push(tool.name);+ }+ }+ }-def last_exception_args():- return json.dumps(sys.last_exc.args) if sys.last_exc else None+ // Register FINAL/FINAL_VAR with output signature+ if (input.register_outputs) {+ pyodide.runPython(makeFinalWrapper(input.register_outputs));+ pyodide.runPython(makeFinalVarWrapper(input.register_outputs));+ }-class FinalAnswer(Exception):- pass+ console.log(JSON.stringify({+ tools_registered: toolNames,+ outputs_registered: input.register_outputs ? input.register_outputs.map(o => o.name) : []+ }));+ continue;+ }-def final_answer(*args):- raise FinalAnswer(*args)- `);+ const code = input.code || "";- // 3. Run the user's code asynchronously+ try {+ await pyodide.loadPackagesFromImports(code);+ pyodide.runPython(PYTHON_SETUP_CODE);+ // Run the user's codeconst result = await pyodide.runPythonAsync(code);-- // 4. Retrieve captured stdout/stderrconst capturedStdout = pyodide.runPython("buf_stdout.getvalue()");- const capturedStderr = pyodide.runPython("buf_stderr.getvalue()");-- // 5. Restore original stdout/stderr- pyodide.runPython(`-sys.stdout = old_stdout-sys.stderr = old_stderr- `);-- // 6. Build our output object according to the rules:- // - If result is None (or Python "None" => JS null), output all prints- // - Else output the result only- // Note: `None` in Python becomes `null` in JS.- let output;- if (result === null || result === undefined) {- // The final statement was None or no return => deliver printed output- // If you want to combine capturedStderr as well, you can append it- // But here we'll just do stdout for clarity- output = capturedStdout;- // If there's something in stderr, you might want to include that or log it- // output += capturedStderr;- } else {- // If the code returned a real value, just return that- try {- output = result.toJs();- } catch (e) {- output = result;- }- }+ pyodide.runPython("sys.stdout, sys.stderr = old_stdout, old_stderr");+ // If result is None, output prints; otherwise output the result+ let output = (result === null || result === undefined) ? capturedStdout : (result.toJs?.() ?? result);console.log(JSON.stringify({ output }));} catch (error) {// We have an error => check if it's a SyntaxError or something else@@ -172,12 +330,6 @@ sys.stderr = old_stderr// we do a additional `json.dumps` and `JSON.parse` on the values, to avoid the possible memory leak.errorArgs = JSON.parse(last_exception_args()) || [];}--- console.log(JSON.stringify({- error: errorMessage,- errorArgs: errorArgs,- errorType: errorType- }));+ console.log(JSON.stringify({ error: errorMessage, errorArgs, errorType }));}}\ No newline at end of filediff --git a/pyproject.toml b/pyproject.tomlindex dffa15ec8..74e7a1391 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -109,6 +109,9 @@ exclude_lines = [][tool.pytest.ini_options]+markers = [+ "integration: tests requiring external dependencies (Deno, LM)",+]filterwarnings = [# litellm uses deprecated pydantic config classes sometimes.# The issue has been fixed repeatedly, but still keeps showing up.diff --git a/tests/mock_interpreter.py b/tests/mock_interpreter.pynew file mode 100644index 000000000..8b26ff581--- /dev/null+++ b/tests/mock_interpreter.py@@ -0,0 +1,132 @@+"""+Mock interpreter for testing RLM and other code-executing modules.++This interpreter doesn't actually execute code - it returns scripted responses+or uses a custom function to generate responses. Useful for:+- Unit testing without Deno/Pyodide dependencies+- Testing specific execution paths (errors, FINAL, etc.)+- Recording what code was submitted for execution+"""++from typing import Any, Callable++from dspy.primitives.code_interpreter import CodeInterpreterError, FinalAnswerResult++__all__ = ["MockInterpreter"]+++class MockInterpreter:+ """Mock interpreter that returns scripted responses.++ Implements the Interpreter protocol for testing purposes.++ Example usage:+ ```python+ # Script specific responses+ mock = MockInterpreter(responses=[+ "data explored",+ FinalAnswerResult("42"),+ ])+ result1 = mock.execute("print(len(context))") # Returns "data explored"+ result2 = mock.execute("FINAL('42')") # Returns FinalAnswerResult("42")++ # Use custom execution function+ def custom_exec(code, variables):+ if "FINAL" in code:+ return FinalAnswerResult("done")+ return f"executed: {code[:20]}..."++ mock = MockInterpreter(execute_fn=custom_exec)+ ```+ """++ def __init__(+ self,+ responses: list[str | FinalAnswerResult | Exception] | None = None,+ execute_fn: Callable[[str, dict[str, Any]], Any] | None = None,+ tools: dict[str, Callable[..., str]] | None = None,+ ):+ """Initialize the mock interpreter.++ Args:+ responses: List of responses to return in sequence. Each call to+ execute() pops the next response. If an Exception is+ in the list, it will be raised.+ execute_fn: Custom function that receives (code, variables) and+ returns the result. Takes precedence over responses.+ tools: Dictionary mapping tool names to callable functions.+ MockInterpreter doesn't use tools, but stores them for protocol compliance.+ """+ self.responses = list(responses) if responses else []+ self.execute_fn = execute_fn+ self.tools = tools or {}+ self.call_count = 0+ self.call_history: list[tuple[str, dict[str, Any]]] = []+ self._shutdown = False++ def start(self) -> None:+ pass++ def execute(+ self,+ code: str,+ variables: dict[str, Any] | None = None,+ ) -> Any:+ """Execute code and return the next scripted response.++ Args:+ code: The code that would be executed (recorded in call_history)+ variables: Variables that would be injected (recorded in call_history)++ Returns:+ The next response from the responses list, or result from execute_fn++ Raises:+ CodeInterpreterError: If the interpreter was shutdown, or if an Exception+ is in the responses list+ """+ if self._shutdown:+ raise CodeInterpreterError("MockInterpreter has been shutdown")++ variables = variables or {}+ self.call_history.append((code, variables))+ self.call_count += 1++ # Custom function takes precedence+ if self.execute_fn is not None:+ return self.execute_fn(code, variables)++ # Return scripted responses+ if not self.responses:+ return ""++ response = self.responses.pop(0)++ if isinstance(response, Exception):+ raise response++ return response++ def shutdown(self) -> None:+ self._shutdown = True++ def reset(self) -> None:+ """Reset the interpreter state for reuse in tests."""+ self.call_count = 0+ self.call_history = []+ self._shutdown = False++ # Context manager support+ def __enter__(self) -> "MockInterpreter":+ return self++ def __exit__(self, *args: Any) -> None:+ self.shutdown()++ def __call__(+ self,+ code: str,+ variables: dict[str, Any] | None = None,+ ) -> Any:+ """Shorthand for execute()."""+ return self.execute(code, variables)diff --git a/tests/predict/test_program_of_thought.py b/tests/predict/test_program_of_thought.pyindex 3b197b611..04ab78ac8 100644--- a/tests/predict/test_program_of_thought.py+++ b/tests/predict/test_program_of_thought.py@@ -22,7 +22,7 @@ def test_pot_code_generation():[{"reasoning": "Reason_A",- "generated_code": "```python\nresult = 1+1\nfinal_answer({'answer': result})\n```",+ "generated_code": "```python\nresult = 1+1\nFINAL({'answer': result})\n```",},{"reasoning": "Reason_B", "answer": "2"},]@@ -62,7 +62,7 @@ def test_pot_support_multiple_fields():[{"reasoning": "Reason_A",- "generated_code": "```python\nmaximum = 6\nminimum = 2\nfinal_answer({'maximum': maximum, 'minimum': minimum})\n```",+ "generated_code": "```python\nmaximum = 6\nminimum = 2\nFINAL({'maximum': maximum, 'minimum': minimum})\n```",},{"reasoning": "Reason_B", "maximum": "6", "minimum": "2"},]@@ -81,11 +81,11 @@ def test_pot_code_generation_with_one_error():[{"reasoning": "Reason_A",- "generated_code": "```python\nresult = 1+0/0\nfinal_answer({'answer': result})\n```",+ "generated_code": "```python\nresult = 1+0/0\nFINAL({'answer': result})\n```",},{"reasoning": "Reason_B",- "generated_code": "```python\nresult = 1+1\nfinal_answer({'answer': result})\n```",+ "generated_code": "```python\nresult = 1+1\nFINAL({'answer': result})\n```",},{"reasoning": "Reason_C", "answer": "2"},]@@ -104,7 +104,7 @@ def test_pot_code_generation_persistent_errors():[{"reasoning": "Reason_A",- "generated_code": "```python\nresult = 1+0/0\nfinal_answer({'answer': result})\n```",+ "generated_code": "```python\nresult = 1+0/0\nFINAL({'answer': result})\n```",},]* max_itersdiff --git a/tests/predict/test_rlm.py b/tests/predict/test_rlm.pynew file mode 100644index 000000000..dd65e2691--- /dev/null+++ b/tests/predict/test_rlm.py@@ -0,0 +1,1077 @@+"""+Tests for the RLM (Recursive Language Model) module.++Test organization:+- Unit tests (no Deno required): MockInterpreter, RLM formatting, signatures+- Integration tests (@pytest.mark.integration): PythonInterpreter with Deno+"""++from contextlib import contextmanager++import pytest++from dspy.predict.rlm import RLM+from dspy.primitives.code_interpreter import CodeInterpreterError, FinalAnswerResult+from dspy.primitives.prediction import Prediction+from dspy.primitives.python_interpreter import PythonInterpreter+from dspy.primitives.repl_types import REPLEntry, REPLHistory, REPLVariable+from tests.mock_interpreter import MockInterpreter++# ============================================================================+# Test Helpers and Factories+# ============================================================================+++def make_mock_predictor(responses: list[dict], async_mode: bool = False):+ """Factory for mock predictors with scripted responses.++ Args:+ responses: List of dicts with keys like 'reasoning', 'code'.+ async_mode: If True, returns a predictor with acall() instead of __call__().+ """++ class MockPredictor:+ def __init__(self):+ self.idx = 0++ def _next_response(self):+ result = responses[self.idx % len(responses)]+ self.idx += 1+ return Prediction(**result)++ def __call__(self, **kwargs):+ return self._next_response()++ async def acall(self, **kwargs):+ return self._next_response()++ return MockPredictor()+++@contextmanager+def dummy_lm_context(responses: list[dict]):+ """Context manager for DummyLM setup."""+ import dspy+ from dspy.utils.dummies import DummyLM++ lm = DummyLM(responses)+ with dspy.context(lm=lm):+ yield lm+++# Common test tools+def echo_tool(text: str = "") -> str:+ """Echo the input text."""+ return f"Echo: {text}"+++def add_tool(a: int = 0, b: int = 0) -> str:+ """Add two numbers."""+ return str(a + b)+++def multiply_tool(a: int = 0, b: int = 0) -> str:+ """Multiply two numbers."""+ return str(a * b)++# ============================================================================+# Unit Tests: MockInterpreter+# ============================================================================+++class TestMockInterpreter:+ """Unit tests for MockInterpreter."""++ def test_scripted_responses(self):+ """Test that MockInterpreter returns scripted responses in order."""+ mock = MockInterpreter(responses=["first", "second", "third"])+ assert mock.execute("code1") == "first"+ assert mock.execute("code2") == "second"+ assert mock.execute("code3") == "third"++ def test_returns_final_answer_result(self):+ """Test that MockInterpreter can return FinalAnswerResult."""+ mock = MockInterpreter(responses=["exploring", FinalAnswerResult("42")])+ assert mock.execute("print(len(data))") == "exploring"+ result = mock.execute("FINAL('42')")+ assert isinstance(result, FinalAnswerResult)+ assert result.answer == "42"++ def test_raises_exception_from_responses(self):+ """Test that MockInterpreter raises exceptions from responses."""+ mock = MockInterpreter(responses=["ok", CodeInterpreterError("undefined variable")])+ assert mock.execute("code1") == "ok"+ with pytest.raises(CodeInterpreterError, match="undefined variable"):+ mock.execute("code2")++ def test_records_call_history(self):+ """Test that MockInterpreter records call history for test assertions."""+ mock = MockInterpreter(responses=["resp"])+ mock.execute("print(1)", variables={"x": 10})+ assert mock.call_history == [("print(1)", {"x": 10})]+++# ============================================================================+# Unit Tests: RLM Module (no interpreter needed)+# ============================================================================+++class TestRLMInitialization:+ """Tests for RLM module initialization."""++ 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+ assert rlm.generate_action is not None+ assert rlm.extract is not None+ assert rlm.tools == {} # No user tools provided+ assert "context" in rlm.signature.input_fields+ assert "query" in rlm.signature.input_fields+ assert "answer" in rlm.signature.output_fields++ def test_custom_signature(self):+ """Test RLM with custom signature."""+ rlm = RLM("document, question -> summary, key_facts", max_iterations=5)+ assert "document" in rlm.signature.input_fields+ assert "question" in rlm.signature.input_fields+ assert "summary" in rlm.signature.output_fields+ assert "key_facts" in rlm.signature.output_fields++ def test_custom_tools(self):+ """Test RLM with custom tools."""+ def custom_tool(x: str = "") -> str:+ return x.upper()++ rlm = RLM("context -> answer", max_iterations=5, tools={"custom_tool": custom_tool})+ assert "custom_tool" in rlm.tools+ assert len(rlm.tools) == 1 # Only user tools, not internal llm_query/llm_query_batched++ @pytest.mark.parametrize("tool_name", ["invalid-name", "123start"])+ def test_tool_validation_invalid_identifier(self, tool_name):+ """Test RLM rejects tool names that aren't valid Python identifiers."""+ def my_tool() -> str:+ return "result"++ with pytest.raises(ValueError, match="must be a valid Python identifier"):+ RLM("context -> answer", tools={tool_name: my_tool})++ @pytest.mark.parametrize("tool_name", ["llm_query", "FINAL", "print"])+ def test_tool_validation_reserved_names(self, tool_name):+ """Test RLM rejects tool names that conflict with built-in functions."""+ def my_tool() -> str:+ return "result"++ with pytest.raises(ValueError, match="conflicts with built-in"):+ RLM("context -> answer", tools={tool_name: my_tool})++ @pytest.mark.parametrize("invalid_value", ["not a function", 123])+ def test_tool_validation_not_callable(self, invalid_value):+ """Test RLM rejects tools that aren't callable."""+ with pytest.raises(TypeError, match="must be callable"):+ RLM("context -> answer", tools={"my_tool": invalid_value})++ def test_optional_parameters(self):+ """Test RLM optional parameters and their defaults."""+ import dspy++ # Test defaults+ rlm = RLM("context -> answer")+ assert rlm.max_llm_calls == 50+ assert rlm.sub_lm is None+ assert rlm._interpreter is None++ # Test custom values+ mock = MockInterpreter()+ mock_lm = dspy.LM("openai/gpt-4o-mini")+ rlm = RLM("context -> answer", max_llm_calls=100, sub_lm=mock_lm, interpreter=mock)+ assert rlm.max_llm_calls == 100+ assert rlm.sub_lm is mock_lm+ assert rlm._interpreter is mock++ def test_forward_validates_required_inputs(self):+ """Test that forward() raises ValueError for missing required inputs."""+ mock = MockInterpreter(responses=["result"])++ # Single missing input+ rlm = RLM("context, query -> answer", max_iterations=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)+ with pytest.raises(ValueError) as exc_info:+ rlm.forward(a="only a") # Missing 'b' and 'c'+ assert "b" in str(exc_info.value)+ assert "c" in str(exc_info.value)++ def test_batched_query_errors_have_clear_markers(self):+ """Test that errors in llm_query_batched are prefixed with [ERROR]."""+ from unittest.mock import MagicMock++ mock_lm = MagicMock()+ mock_lm.side_effect = RuntimeError("LM failed")++ rlm = RLM("context -> answer", max_llm_calls=10, sub_lm=mock_lm)+ tools = rlm._make_llm_tools()++ results = tools["llm_query_batched"](prompts=["test prompt"])+ assert len(results) == 1+ assert results[0].startswith("[ERROR]")+ assert "LM failed" in results[0]++ def test_tools_call_counter_is_thread_safe(self):+ """Test that the LLM call counter is thread-safe for concurrent llm_query_batched calls.++ The call counter must be protected by a lock since llm_query_batched uses+ ThreadPoolExecutor for concurrent execution.+ """+ from concurrent.futures import ThreadPoolExecutor+ from unittest.mock import MagicMock++ mock_lm = MagicMock()+ mock_lm.return_value = ["response"]++ rlm = RLM("context -> answer", max_llm_calls=10, sub_lm=mock_lm)+ tools = rlm._make_llm_tools()++ call_count = [0]+ errors = []++ def make_call():+ try:+ tools["llm_query"](prompt="test")+ call_count[0] += 1+ except RuntimeError as e:+ errors.append(e)++ with ThreadPoolExecutor(max_workers=5) as executor:+ futures = [executor.submit(make_call) for _ in range(10)]+ for f in futures:+ f.result()++ assert call_count[0] == 10, f"Expected 10 successful calls, got {call_count[0]}"+ assert len(errors) == 0, f"Unexpected errors: {errors}"++ with pytest.raises(RuntimeError, match="LLM call limit exceeded"):+ tools["llm_query"](prompt="one more")+++class TestRLMFormatting:+ """Tests for RLM formatting helpers."""++ def test_format_history(self):+ """Test history formatting using REPLHistory."""+ history = REPLHistory()+ history = history.append(reasoning="Need to check the data", code="print(1)", output="1")+ history = history.append(reasoning="Now calculate", code="x = 2", output="")+ formatted = history.format()+ assert "Step 1" in formatted+ assert "Step 2" in formatted+ assert "print(1)" in formatted+ assert "Need to check" in formatted++ def test_format_history_empty(self):+ """Test history formatting with empty history."""+ history = REPLHistory()+ formatted = history.format()+ assert "have not interacted with the REPL" in formatted++ def test_action_signature_has_iteration_field(self):+ """Test action signature includes iteration input field."""+ rlm = RLM("context -> answer")+ action_sig = rlm.generate_action.signature+ assert "iteration" in action_sig.input_fields++ def test_format_output(self):+ """Test output formatting."""+ rlm = RLM("context -> answer")+ formatted = rlm._format_output("output text")+ assert "output text" in formatted++ def test_format_output_empty(self):+ """Test output formatting with empty output."""+ rlm = RLM("context -> answer")+ formatted = rlm._format_output("")+ assert "no output" in formatted.lower()++ def test_format_output_truncation(self):+ """Test that long output is truncated."""+ rlm = RLM("context -> answer", max_output_chars=100)+ formatted = rlm._format_output("x" * 200)+ assert "truncated" in formatted.lower()++ def test_format_variable_info_string(self):+ """Test variable info formatting for string value using REPLVariable."""+ var = REPLVariable.from_value("context", "Hello world", preview_chars=5)+ formatted = var.format()+ assert "Variable: `context`" in formatted+ assert "Type: str" in formatted+ assert "11" in formatted # length+ assert "Hello" in formatted+ assert "..." in formatted # truncation indicator++ def test_format_variable_info_dict(self):+ """Test variable info formatting for dict value using REPLVariable."""+ var = REPLVariable.from_value("data", {"key": "value"})+ formatted = var.format()+ assert "Variable: `data`" in formatted+ assert "Type: dict" in formatted+ assert "key" in formatted++ def test_build_variables_multiple(self):+ """Test building multiple variables."""+ rlm = RLM("context, query -> answer")+ variables = rlm._build_variables(+ context="Hello world",+ query="What is this?"+ )+ assert len(variables) == 2+ formatted = "\n\n".join(v.format() for v in variables)+ assert "Variable: `context`" in formatted+ assert "Variable: `query`" in formatted+ assert "Hello world" in formatted+ assert "What is this?" in formatted+++class TestREPLTypes:+ """Tests for the REPL type classes."""++ def test_repl_history_immutability(self):+ """Test that REPLHistory.append() returns new instance."""+ h1 = REPLHistory()+ h2 = h1.append(code="print(1)", output="1")+ assert len(h1) == 0 # Original unchanged+ assert len(h2) == 1 # New has entry++ def test_repl_history_len_iter_bool(self):+ """Test REPLHistory list-like interface."""+ h = REPLHistory()+ assert len(h) == 0+ assert not bool(h)++ h = h.append(code="x = 1", output="")+ h = h.append(code="x = 2", output="")+ assert len(h) == 2+ assert bool(h)++ codes = [e.code for e in h]+ assert codes == ["x = 1", "x = 2"]++ def test_repl_entry_format(self):+ """Test REPLEntry formatting."""+ entry = REPLEntry(reasoning="test reason", code="print(1)", output="1")+ formatted = entry.format(index=0)+ assert "Step 1" in formatted+ assert "test reason" in formatted+ assert "print(1)" in formatted+ assert "1" in formatted++ def test_repl_entry_format_truncation(self):+ """Test REPLEntry output truncation."""+ entry = REPLEntry(code="print('x' * 1000)", output="x" * 1000)+ formatted = entry.format(index=0, max_output_chars=50)+ assert "truncated" in formatted++ def test_repl_variable_from_value(self):+ """Test REPLVariable.from_value() factory."""+ var = REPLVariable.from_value("test", "hello world")+ assert var.name == "test"+ assert var.type_name == "str"+ assert var.total_length == 11+ assert "hello world" in var.preview++ def test_repl_variable_truncation(self):+ """Test REPLVariable preview truncation."""+ var = REPLVariable.from_value("big", "x" * 1000, preview_chars=50)+ assert len(var.preview) == 53 # 50 + "..."+ assert var.preview.endswith("...")++ def test_repl_variable_with_field_info(self):+ """Test REPLVariable includes desc and constraints from field_info."""+ import dspy++ # Create a field with description and constraints+ field = dspy.InputField(desc="The user's question", ge=0, le=100)++ var = REPLVariable.from_value("query", "What is 2+2?", field_info=field)+ assert var.desc == "The user's question"+ assert "greater than or equal to" in var.constraints++ # Verify format includes the metadata+ formatted = var.format()+ assert "Description: The user's question" in formatted+ assert "Constraints:" in formatted++ def test_repl_variable_without_field_info(self):+ """Test REPLVariable works without field_info."""+ var = REPLVariable.from_value("data", [1, 2, 3])+ assert var.desc == ""+ assert var.constraints == ""++ # Format should not include empty desc/constraints lines+ formatted = var.format()+ assert "Description:" not in formatted+ assert "Constraints:" not in formatted++ def test_build_variables_includes_field_metadata(self):+ """Test _build_variables passes field_info to REPLVariable."""+ import dspy++ class QASig(dspy.Signature):+ """Answer questions."""+ context: str = dspy.InputField(desc="Background information")+ question: str = dspy.InputField(desc="The question to answer")+ answer: str = dspy.OutputField()++ rlm = RLM(QASig, max_iterations=3)+ variables = rlm._build_variables(context="Some text", question="What?")++ # Find the context variable+ context_var = next(v for v in variables if v.name == "context")+ assert context_var.desc == "Background information"++ question_var = next(v for v in variables if v.name == "question")+ assert question_var.desc == "The question to answer"+++class TestRLMCallMethod:+ """Tests for RLM __call__ method."""++ def test_call_is_alias_for_forward(self):+ """Test that __call__ is an alias for forward()."""+ mock = MockInterpreter(responses=[FinalAnswerResult({"answer": "42"})])+ rlm = RLM("query -> answer", max_iterations=3, interpreter=mock)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Return answer", "code": 'FINAL("42")'},+ ])++ result = rlm(query="What is the answer?")+ assert result.answer == "42"+++class TestRLMMaxIterationsFallback:+ """Tests for max_iterations reached and extract fallback."""++ def test_max_iterations_triggers_extract(self):+ """Test that reaching max_iterations uses extract fallback."""+ mock = MockInterpreter(responses=[+ "exploring...",+ "still exploring...",+ "more exploring...",+ ])+ rlm = RLM("query -> answer", max_iterations=3, interpreter=mock)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Explore 1", "code": "print('exploring')"},+ {"reasoning": "Explore 2", "code": "print('exploring')"},+ {"reasoning": "Explore 3", "code": "print('exploring')"},+ ])+ # Mock the extract predictor to return a value+ rlm.extract = make_mock_predictor([+ {"answer": "extracted_answer"},+ ])++ result = rlm.forward(query="test")+ assert result.answer == "extracted_answer"+ assert result.final_reasoning == "Extract forced final answer"+++class TestRLMToolExceptions:+ """Tests for tool exception handling."""++ def test_tool_exception_returns_error_in_output(self):+ """Test that tool exceptions are caught and returned as errors."""+ def failing_tool() -> str:+ raise RuntimeError("Tool failed!")++ mock = MockInterpreter(responses=[+ CodeInterpreterError("RuntimeError: Tool failed!"),+ FinalAnswerResult({"answer": "recovered"}),+ ])+ rlm = RLM("query -> answer", max_iterations=5, interpreter=mock, tools={"failing_tool": failing_tool})+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Call tool", "code": "failing_tool()"},+ {"reasoning": "Recover", "code": 'FINAL("recovered")'},+ ])++ result = rlm.forward(query="test")+ assert result.answer == "recovered"+++class TestRLMDynamicSignature:+ """Tests for the dynamically built RLM signatures."""++ def test_action_signature_structure(self):+ """Test action signature has required fields and instructions."""+ rlm = RLM("document, question -> summary, answer")+ action_sig = rlm.generate_action.signature++ # Required input/output fields+ assert "variables_info" in action_sig.input_fields+ assert "repl_history" in action_sig.input_fields+ assert "reasoning" in action_sig.output_fields+ assert "code" in action_sig.output_fields++ # Instructions mention key tools and variables+ instructions = action_sig.instructions+ assert "llm_query" in instructions+ assert "llm_query_batched" in instructions+ assert "FINAL" in instructions+ assert "`document`" in instructions+ assert "`question`" in instructions+ assert "`summary`" in instructions+ assert "`answer`" in instructions++ def test_extract_signature_structure(self):+ """Test extract signature has required fields for all outputs."""+ rlm = RLM("document, question -> summary, key_facts, confidence")+ extract_sig = rlm.extract.signature+ assert "variables_info" in extract_sig.input_fields+ assert "repl_history" in extract_sig.input_fields+ assert "summary" in extract_sig.output_fields+ assert "key_facts" in extract_sig.output_fields+ assert "confidence" in extract_sig.output_fields+++# ============================================================================+# Integration Tests: PythonInterpreter (require Deno)+# ============================================================================+++class TestPythonInterpreter:+ """Integration tests for the secure sandbox with tool support."""++ def test_start_prewarms_sandbox(self):+ """Test that start() pre-warms the sandbox."""+ interp = PythonInterpreter()+ try:+ # Before start, deno_process should be None+ assert interp.deno_process is None+ # After start, it should be running+ interp.start()+ assert interp.deno_process is not None+ assert interp.deno_process.poll() is None # Still running+ # Execute should work+ result = interp.execute("print(42)")+ assert "42" in result+ finally:+ interp.shutdown()++ def test_start_is_idempotent(self):+ """Test that start() can be called multiple times safely."""+ interp = PythonInterpreter()+ try:+ interp.start()+ first_process = interp.deno_process+ interp.start() # Second call - should be idempotent+ assert interp.deno_process is first_process # Same process+ finally:+ interp.shutdown()++ def test_basic_execution(self):+ """Test basic code execution."""+ with PythonInterpreter() as interp:+ result = interp.execute("print(1 + 1)")+ assert "2" in result++ def test_variable_injection(self):+ """Test variable injection."""+ with PythonInterpreter(tools={}) as interp:+ result = interp.execute(+ "print(x + y)",+ variables={"x": 10, "y": 5}+ )+ assert "15" in result++ def test_tool_call_kwargs(self):+ """Test tool call with keyword arguments."""+ def echo(message: str = "") -> str:+ return f"Echo: {message}"++ with PythonInterpreter(tools={"echo": echo}) as interp:+ result = interp.execute('print(echo(message="hello"))')+ assert "Echo: hello" in result++ def test_tool_call_positional(self):+ """Test tool call with positional arguments."""+ def greet(name: str) -> str:+ return f"Hello: {name}"++ with PythonInterpreter(tools={"greet": greet}) as interp:+ result = interp.execute('print(greet("world"))')+ assert "Hello: world" in result++ def test_multiple_tools(self):+ """Test multiple tools."""+ def add(a: int = 0, b: int = 0) -> str:+ return str(a + b)++ def multiply(a: int = 0, b: int = 0) -> str:+ return str(a * b)++ with PythonInterpreter(tools={"add": add, "multiply": multiply}) as interp:+ result = interp.execute("""+sum_result = add(a=3, b=4)+prod_result = multiply(a=3, b=4)+print(f"Sum: {sum_result}, Product: {prod_result}")+""")+ assert "Sum: 7" in result+ assert "Product: 12" in result++ def test_tool_returns_list(self):+ """Test tool that returns a list (like llm_query_batched)."""+ def batch_process(items: list | None = None) -> list:+ items = items or []+ return [f"processed_{item}" for item in items]++ with PythonInterpreter(tools={"batch_process": batch_process}) as interp:+ result = interp.execute("""+results = batch_process(items=["a", "b", "c"])+print(f"Type: {type(results).__name__}")+print(f"Length: {len(results)}")+print(f"First: {results[0]}")+print(f"All: {results}")+""")+ assert "Type: list" in result+ assert "Length: 3" in result+ assert "First: processed_a" in result++ def test_tool_returns_dict(self):+ """Test tool that returns a dict."""+ def get_info() -> dict:+ return {"name": "test", "count": 42}++ with PythonInterpreter(tools={"get_info": get_info}) as interp:+ result = interp.execute("""+info = get_info()+print(f"Type: {type(info).__name__}")+print(f"Name: {info['name']}")+print(f"Count: {info['count']}")+""")+ assert "Type: dict" in result+ assert "Name: test" in result+ assert "Count: 42" in result++ def test_state_persists(self):+ """Test that state persists across executions."""+ with PythonInterpreter(tools={}) as interp:+ interp.execute("x = 10")+ result = interp.execute("print(x + 5)")+ assert "15" in result++ def test_syntax_error(self):+ """Test syntax error handling."""+ with PythonInterpreter(tools={}) as interp:+ with pytest.raises(SyntaxError):+ interp.execute("def incomplete(")++ def test_runtime_error(self):+ """Test runtime error handling."""+ with PythonInterpreter(tools={}) as interp:+ with pytest.raises(CodeInterpreterError):+ interp.execute("undefined_variable")+++class TestSandboxSecurity:+ """Integration tests for sandbox security restrictions."""++ def test_no_network_access(self):+ """Test that network access is blocked."""+ with PythonInterpreter(tools={}) as interp:+ with pytest.raises(CodeInterpreterError) as exc_info:+ interp.execute("""+from pyodide.http import pyfetch+import asyncio+asyncio.get_event_loop().run_until_complete(pyfetch("https://example.com"))+""")+ assert "net access" in str(exc_info.value).lower() or "allow-net" in str(exc_info.value).lower()++ def test_imports_work(self):+ """Test that standard library imports work."""+ with PythonInterpreter(tools={}) as interp:+ result = interp.execute("""+import json+import re+from collections import Counter+data = {"key": "value"}+print(json.dumps(data))+""")+ assert "key" in result+++# ============================================================================+# Unit Tests: RLM with MockInterpreter (no Deno required)+# ============================================================================+++class TestRLMAsyncMock:+ """Unit tests for RLM aforward() using MockInterpreter (no Deno required)."""++ @pytest.mark.asyncio+ async def test_aforward_basic(self):+ """Test aforward() returns Prediction with expected output (MockInterpreter)."""+ mock = MockInterpreter(responses=[FinalAnswerResult({"answer": "42"})])+ rlm = RLM("query -> answer", max_iterations=3, interpreter=mock)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Return answer", "code": 'FINAL("42")'},+ ])++ result = await rlm.aforward(query="What is the answer?")+ assert result.answer == "42"++ @pytest.mark.asyncio+ async def test_aforward_int_output_mock(self):+ """Test aforward() returns int when signature expects int (MockInterpreter)."""+ mock = MockInterpreter(responses=[FinalAnswerResult({"count": 42})])+ rlm = RLM("query -> count: int", max_iterations=3, interpreter=mock)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Return count", "code": "FINAL(42)"},+ ])++ result = await rlm.aforward(query="count items")+ assert result.count == 42+ assert isinstance(result.count, int)++ @pytest.mark.asyncio+ async def test_aforward_multi_iteration_mock(self):+ """Test aforward() handles multiple iterations before FINAL (MockInterpreter)."""+ mock = MockInterpreter(responses=[+ "explored data",+ FinalAnswerResult({"answer": "done"}),+ ])+ rlm = RLM("query -> answer", max_iterations=5, interpreter=mock)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Explore first", "code": "print('exploring')"},+ {"reasoning": "Now finish", "code": 'FINAL("done")'},+ ])++ result = await rlm.aforward(query="test")+ assert result.answer == "done"+++class TestRLMTypeCoercionMock:+ """Unit tests for RLM type coercion using MockInterpreter (no Deno required)."""++ @pytest.mark.parametrize("output_field,output_type,final_value,code,expected", [+ ("count", "int", 42, "FINAL(42)", 42),+ ("score", "float", 3.14, "FINAL(3.14)", 3.14),+ ("valid", "bool", True, "FINAL(True)", True),+ ("numbers", "list[int]", [1, 2, 3], "FINAL([1, 2, 3])", [1, 2, 3]),+ ("answer", "Literal['yes', 'no']", "yes", 'FINAL("yes")', "yes"),+ ])+ def test_type_coercion(self, output_field, output_type, final_value, code, expected):+ """Test RLM type coercion for various types (MockInterpreter)."""+ mock = MockInterpreter(responses=[FinalAnswerResult({output_field: final_value})])+ rlm = RLM(f"query -> {output_field}: {output_type}", max_iterations=3, interpreter=mock)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Return value", "code": code},+ ])++ result = rlm.forward(query="test")+ assert getattr(result, output_field) == expected++ def test_type_error_retries(self):+ """Test RLM retries when type validation fails (MockInterpreter)."""+ mock = MockInterpreter(responses=[+ FinalAnswerResult({"answer": "maybe"}), # Invalid for Literal+ FinalAnswerResult({"answer": "yes"}), # Valid+ ])+ rlm = RLM("query -> answer: Literal['yes', 'no']", max_iterations=5, interpreter=mock)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Try maybe", "code": 'FINAL("maybe")'},+ {"reasoning": "Try yes", "code": 'FINAL("yes")'},+ ])++ result = rlm.forward(query="is it yes?")+ assert result.answer == "yes"+++# ============================================================================+# Integration Tests: RLM Type Coercion with PythonInterpreter+# ============================================================================+++class TestRLMTypeCoercion:+ """Tests for RLM type coercion through full forward pass with PythonInterpreter.++ Note: These tests let RLM create its own PythonInterpreter so it can register+ typed output_fields for FINAL based on the signature.+ """++ @pytest.mark.parametrize("output_field,output_type,code,expected,expected_type", [+ ("count", "int", "FINAL(42)", 42, int),+ ("score", "float", "FINAL(3.14)", 3.14, float),+ ("valid", "bool", "FINAL(True)", True, bool),+ ("numbers", "list[int]", "FINAL([1, 2, 3])", [1, 2, 3], list),+ ("data", "dict[str, str]", 'FINAL({"key": "value"})', {"key": "value"}, dict),+ ("answer", "Literal['yes', 'no']", 'FINAL("yes")', "yes", str),+ ])+ 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.generate_action = make_mock_predictor([+ {"reasoning": "Return value", "code": code},+ ])++ result = rlm.forward(query="test")+ assert getattr(result, output_field) == expected+ assert isinstance(getattr(result, output_field), expected_type)++ def test_final_var_extracts_typed_value(self):+ """Test RLM FINAL_VAR correctly extracts typed value."""+ rlm = RLM("query -> count: int", max_iterations=3)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Compute and return", "code": 'result = 42\nFINAL_VAR("result")'},+ ])++ result = rlm.forward(query="count items")+ assert result.count == 42+ assert isinstance(result.count, int)+++# ============================================================================+# Integration Tests: RLM Multiple Output Fields+# ============================================================================+++class TestRLMMultipleOutputs:+ """Tests for signatures with multiple typed output fields.++ Tests FINAL() and FINAL_VAR() calling patterns with multi-output signatures.+ """++ def test_multi_output_final_kwargs(self):+ """FINAL(field1=val1, field2=val2) with keyword args."""+ rlm = RLM("query -> name: str, count: int", max_iterations=3)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Return both outputs", "code": 'FINAL(name="alice", count=5)'},+ ])++ result = rlm.forward(query="test")+ assert result.name == "alice"+ assert result.count == 5+ assert isinstance(result.count, int)++ def test_multi_output_final_positional(self):+ """FINAL(val1, val2) with positional args mapped to field order."""+ rlm = RLM("query -> name: str, count: int", max_iterations=3)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Return both outputs positionally", "code": 'FINAL("bob", 10)'},+ ])++ result = rlm.forward(query="test")+ assert result.name == "bob"+ assert result.count == 10++ 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.generate_action = make_mock_predictor([+ {"reasoning": "Return all three", "code": 'FINAL(name="carol", age=30, active=True)'},+ ])++ result = rlm.forward(query="test")+ assert result.name == "carol"+ assert result.age == 30+ assert result.active is True++ def test_multi_output_final_missing_field_errors(self):+ """FINAL() with missing field should return error in output."""+ rlm = RLM("query -> name: str, count: int", max_iterations=3)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Missing count field", "code": 'FINAL(name="alice")'},+ {"reasoning": "Now provide both", "code": 'FINAL(name="alice", count=5)'},+ ])++ # RLM should retry after getting error for missing field+ result = rlm.forward(query="test")+ assert result.name == "alice"+ assert result.count == 5++ def test_multi_output_final_var(self):+ """FINAL_VAR("var1", "var2") maps variables to output fields."""+ rlm = RLM("query -> name: str, count: int", max_iterations=3)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Use FINAL_VAR", "code": 'n = "dave"\nc = 15\nFINAL_VAR("n", "c")'},+ ])++ result = rlm.forward(query="test")+ assert result.name == "dave"+ assert result.count == 15++ def test_multi_output_final_var_wrong_count_errors(self):+ """FINAL_VAR with wrong number of args should error and retry."""+ rlm = RLM("query -> name: str, count: int", max_iterations=3)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Wrong arg count", "code": 'n = "eve"\nFINAL_VAR("n")'}, # Missing second arg+ {"reasoning": "Now correct", "code": 'FINAL(name="eve", count=20)'},+ ])++ result = rlm.forward(query="test")+ assert result.name == "eve"+ assert result.count == 20++ def test_multi_output_final_var_undefined_errors(self):+ """FINAL_VAR with undefined variable should error and retry."""+ rlm = RLM("query -> name: str, count: int", max_iterations=3)+ rlm.generate_action = make_mock_predictor([+ {"reasoning": "Undefined var", "code": 'n = "frank"\nFINAL_VAR("n", "undefined_var")'},+ {"reasoning": "Now correct", "code": 'FINAL(name="frank", count=25)'},+ ])++ result = rlm.forward(query="test")+ assert result.name == "frank"+ assert result.count == 25++ 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.generate_action = make_mock_predictor([+ {"reasoning": "Return mixed types", "code": "FINAL(count=42, ratio=3.14, flag=True)"},+ ])++ result = rlm.forward(query="test")+ assert result.count == 42+ assert isinstance(result.count, int)+ assert result.ratio == 3.14+ assert isinstance(result.ratio, float)+ assert result.flag is True+ assert isinstance(result.flag, bool)+++# ============================================================================+# Integration Tests: RLM with DummyLM and PythonInterpreter+# ============================================================================+++class TestRLMWithDummyLM:+ """End-to-end tests using DummyLM with RLM and PythonInterpreter.++ Note: These tests let RLM create its own PythonInterpreter so it can register+ typed output_fields for FINAL based on the signature.+ """++ def test_simple_computation_e2e(self):+ """Test full RLM pipeline: DummyLM -> RLM -> PythonInterpreter -> result."""+ with dummy_lm_context([+ {"reasoning": "I need to compute 2 + 3", "code": "result = 2 + 3\nFINAL(result)"},+ ]):+ rlm = RLM("query -> answer: int", max_iterations=3)+ result = rlm.forward(query="What is 2 + 3?")++ assert result.answer == 5+ assert isinstance(result.answer, int)++ def test_multi_turn_computation_e2e(self):+ """Test RLM with multiple turns before FINAL."""+ with dummy_lm_context([+ {"reasoning": "First explore the data", "code": "x = 10\nprint(f'x = {x}')"},+ {"reasoning": "Now compute and return", "code": "y = x * 2\nFINAL(y)"},+ ]):+ rlm = RLM("query -> answer: int", max_iterations=5)+ result = rlm.forward(query="Double ten")++ assert result.answer == 20+ assert len(result.trajectory) == 2++ def test_with_input_variables_e2e(self):+ """Test RLM with input variables passed to sandbox."""+ with dummy_lm_context([+ {"reasoning": "Sum the numbers in the list", "code": "FINAL(sum(numbers))"},+ ]):+ rlm = RLM("numbers: list[int] -> total: int", max_iterations=3)+ result = rlm.forward(numbers=[1, 2, 3, 4, 5])++ assert result.total == 15++ def test_with_tool_e2e(self):+ """Test RLM calling a host-side tool through the sandbox."""+ def lookup(key: str) -> str:+ return {"apple": "red", "banana": "yellow"}.get(key, "unknown")++ with dummy_lm_context([+ {"reasoning": "Look up the color of apple", "code": 'color = lookup(key="apple")\nFINAL(color)'},+ ]):+ rlm = RLM("fruit -> color: str", max_iterations=3, tools={"lookup": lookup})+ result = rlm.forward(fruit="apple")++ assert result.color == "red"++ @pytest.mark.asyncio+ async def test_aforward_simple_computation_e2e(self):+ """Test aforward() full pipeline: DummyLM -> RLM -> PythonInterpreter -> result."""+ with dummy_lm_context([+ {"reasoning": "I need to compute 2 + 3", "code": "result = 2 + 3\nFINAL(result)"},+ ]):+ rlm = RLM("query -> answer: int", max_iterations=3)+ result = await rlm.aforward(query="What is 2 + 3?")++ assert result.answer == 5+ assert isinstance(result.answer, int)++ @pytest.mark.asyncio+ async def test_aforward_multi_turn_e2e(self):+ """Test aforward() with multiple turns before FINAL."""+ with dummy_lm_context([+ {"reasoning": "First explore the data", "code": "x = 10\nprint(f'x = {x}')"},+ {"reasoning": "Now compute and return", "code": "y = x * 2\nFINAL(y)"},+ ]):+ rlm = RLM("query -> answer: int", max_iterations=5)+ result = await rlm.aforward(query="Double ten")++ assert result.answer == 20+ assert len(result.trajectory) == 2++ @pytest.mark.asyncio+ async def test_aforward_with_input_variables_e2e(self):+ """Test aforward() with input variables passed to sandbox."""+ with dummy_lm_context([+ {"reasoning": "Sum the numbers in the list", "code": "FINAL(sum(numbers))"},+ ]):+ rlm = RLM("numbers: list[int] -> total: int", max_iterations=3)+ result = await rlm.aforward(numbers=[1, 2, 3, 4, 5])++ assert result.total == 15+++# ============================================================================+# Integration Tests: RLM with real LM (require API key and Deno)+# ============================================================================++[email protected](reason="Requires actual LM and Deno - run manually")+class TestRLMIntegration:+ """Integration tests that require a configured LM."""++ def test_simple_computation(self):+ """Test RLM on simple computation."""+ import dspy+ dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))++ rlm = RLM("context, query -> answer", max_iterations=5)+ result = rlm(+ context={"numbers": [1, 2, 3, 4, 5]},+ query="What is the sum of the numbers?"+ )+ assert "15" in result.answer++ def test_with_llm_query(self):+ """Test RLM using the llm_query tool."""+ import dspy+ dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))++ rlm = RLM("context, query -> answer", max_iterations=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."+ )+ assert "dog" in result.answer.lower()+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/tests/primitives/test_python_interpreter.py b/tests/primitives/test_python_interpreter.pyindex 9dbee7abd..bd72145e7 100644--- a/tests/primitives/test_python_interpreter.py+++ b/tests/primitives/test_python_interpreter.py@@ -4,7 +4,8 @@ import shutilimport pytest-from dspy.primitives.python_interpreter import InterpreterError, PythonInterpreter+from dspy.primitives.code_interpreter import CodeInterpreterError, FinalAnswerResult+from dspy.primitives.python_interpreter import PythonInterpreter# This test suite requires deno to be installed. Please install deno following https://docs.deno.com/runtime/getting_started/installation/if shutil.which("deno") is None:@@ -32,6 +33,18 @@ def test_user_variable_definitions():assert result == 5, "User variable assignment should work"+def test_rejects_python_keywords_as_variable_names():+ """Test that Python keywords are rejected as variable names."""+ with PythonInterpreter() as interpreter:+ # These are valid Python identifiers but reserved keywords+ # Using them as variable names would cause syntax errors+ keywords_to_test = ["for", "class", "import", "def", "return", "if", "while"]++ for keyword in keywords_to_test:+ with pytest.raises(CodeInterpreterError, match="Invalid variable name"):+ interpreter.execute("print(x)", variables={keyword: 42})++def test_failure_syntax_error():with PythonInterpreter() as interpreter:code = "+++"@@ -42,7 +55,7 @@ def test_failure_syntax_error():def test_failure_zero_division():with PythonInterpreter() as interpreter:code = "1+0/0"- with pytest.raises(InterpreterError, match="ZeroDivisionError"):+ with pytest.raises(CodeInterpreterError, match="ZeroDivisionError"):interpreter.execute(code)@@ -50,18 +63,21 @@ def test_exception_args():with PythonInterpreter() as interpreter:token = random.randint(1, 10**9)code = f"raise ValueError({token})"- with pytest.raises(InterpreterError, match=rf"ValueError: \[{token}\]"):+ with pytest.raises(CodeInterpreterError, match=rf"ValueError: \[{token}\]"):interpreter.execute(code)-def test_final_answer_trick():+def test_final_with_list():+ """Test FINAL() with a list argument returns FinalAnswerResult with dict format."""+with PythonInterpreter() as interpreter:token = random.randint(1, 10**9)- code = f"final_answer('The result is', {token})"+ code = f"FINAL(['The result is', {token}])"result = interpreter(code)- # They should maintain the same order- assert result == ["The result is", token], "The returned results are differ, `final_answer` trick doesn't work"+ assert isinstance(result, FinalAnswerResult)+ # FINAL now always returns a dict with "answer" key for single-output default+ assert result.answer == {"answer": ["The result is", token]}def test_enable_env_vars_flag():os.environ["FOO_TEST_ENV"] = "test_value"@@ -158,7 +174,7 @@ def test_enable_net_flag():f"resp = await js.fetch({test_url!r})\n""resp.status")- with pytest.raises(InterpreterError, match="PythonError"):+ with pytest.raises(CodeInterpreterError, match="PythonError"):interpreter.execute(code)with PythonInterpreter(enable_network_access=["example.com"]) as interpreter:@@ -202,3 +218,192 @@ except Exception as e:output = interpreter(malicious_code)assert secret_content in output++def test_tools_dict_is_copied():+ """Test that tools dict is defensively copied, not stored by reference."""+ tools = {"my_tool": lambda: "result"}+ sandbox = PythonInterpreter(tools=tools)++ # Modify the original dict after construction+ tools["new_tool"] = lambda: "new"++ # The sandbox should not see the new tool+ assert "new_tool" not in sandbox.tools+++def test_serialize_tuple():+ """Test that tuples can be serialized as variables."""+ with PythonInterpreter() as interpreter:+ result = interpreter.execute("x", variables={"x": (1, 2, 3)})+ assert result == [1, 2, 3] # Tuples become lists in JSON+++def test_serialize_set():+ """Test that sets can be serialized as variables."""+ with PythonInterpreter() as interpreter:+ result = interpreter.execute("sorted(x)", variables={"x": {3, 1, 2}})+ assert result == [1, 2, 3]+++def test_serialize_set_mixed_types():+ """Test that sets with mixed types can be serialized (fallback to list)."""+ with PythonInterpreter() as interpreter:+ # Mixed types can't be sorted, so they serialize as a list in arbitrary order+ # We verify the list contains the expected elements+ result = interpreter.execute("x", variables={"x": {1, "a"}})+ assert isinstance(result, list)+ assert set(result) == {1, "a"}+++def test_deno_command_dict_raises_type_error():+ """Test that passing a dict as deno_command raises TypeError."""+ with pytest.raises(TypeError, match="deno_command must be a list"):+ PythonInterpreter(deno_command={"invalid": "dict"})+++# =============================================================================+# Typed Tool Signature Tests+# =============================================================================++def test_tool_with_typed_signature():+ """Test that tools get proper typed signatures from inspect."""+ def my_tool(query: str, limit: int = 10) -> str:+ return f"searched '{query}' with limit {limit}"++ with PythonInterpreter(tools={"my_tool": my_tool}) as sandbox:+ # Tool should be callable with typed signature+ result = sandbox.execute('my_tool(query="test", limit=5)')+ assert result == "searched 'test' with limit 5"+++def test_tool_positional_args():+ """Test that tools work with positional arguments."""+ def search(query: str, limit: int = 10) -> str:+ return f"query={query}, limit={limit}"++ with PythonInterpreter(tools={"search": search}) as sandbox:+ result = sandbox.execute('search("hello")')+ assert result == "query=hello, limit=10"+++def test_tool_keyword_args():+ """Test that tools work with keyword arguments."""+ def search(query: str, limit: int = 10) -> str:+ return f"query={query}, limit={limit}"++ with PythonInterpreter(tools={"search": search}) as sandbox:+ result = sandbox.execute('search(query="hello", limit=5)')+ assert result == "query=hello, limit=5"+++def test_tool_default_args():+ """Test that tool default arguments work correctly."""+ def greet(name: str, greeting: str = "Hello") -> str:+ return f"{greeting}, {name}!"++ with PythonInterpreter(tools={"greet": greet}) as sandbox:+ # Without default+ result = sandbox.execute('greet("World")')+ assert result == "Hello, World!"++ # Overriding default+ result = sandbox.execute('greet("World", "Hi")')+ assert result == "Hi, World!"+++# =============================================================================+# Multi-Output FINAL Tests+# =============================================================================++def test_final_with_typed_signature():+ """Test FINAL with typed output signature."""++ output_fields = [+ {"name": "answer", "type": "str"},+ {"name": "confidence", "type": "float"},+ ]++ with PythonInterpreter(output_fields=output_fields) as sandbox:+ result = sandbox.execute('FINAL(answer="the answer", confidence=0.95)')++ assert isinstance(result, FinalAnswerResult)+ assert result.answer == {"answer": "the answer", "confidence": 0.95}+++def test_final_positional_args():+ """Test FINAL with positional arguments."""++ output_fields = [+ {"name": "answer", "type": "str"},+ {"name": "confidence", "type": "float"},+ ]++ with PythonInterpreter(output_fields=output_fields) as sandbox:+ result = sandbox.execute('FINAL("the answer", 0.95)')++ assert isinstance(result, FinalAnswerResult)+ assert result.answer == {"answer": "the answer", "confidence": 0.95}+++def test_final_var_multi_output():+ """Test FINAL_VAR with multiple output fields using positional args."""++ output_fields = [+ {"name": "answer", "type": "str"},+ {"name": "score", "type": "int"},+ ]++ with PythonInterpreter(output_fields=output_fields) as sandbox:+ # Positional args: variable names mapped to output fields in order+ code = """+a = "my answer"+s = 42+FINAL_VAR("a", "s")+"""+ result = sandbox.execute(code)++ assert isinstance(result, FinalAnswerResult)+ assert result.answer == {"answer": "my answer", "score": 42}+++def test_final_var_wrong_arg_count():+ """Test FINAL_VAR with wrong number of args gives clear error."""++ output_fields = [+ {"name": "answer", "type": "str"},+ {"name": "score", "type": "int"},+ ]++ with PythonInterpreter(output_fields=output_fields) as sandbox:+ with pytest.raises(CodeInterpreterError) as exc_info:+ sandbox.execute('x = 1; FINAL_VAR("x")') # Only 1 arg, expects 2+ assert "expects 2 variable names" in str(exc_info.value)+++def test_extract_parameters():+ """Test that _extract_parameters correctly extracts function signatures."""+ def example_fn(required: str, optional: int = 5, untyped=None) -> str:+ pass++ sandbox = PythonInterpreter()+ params = sandbox._extract_parameters(example_fn)++ assert len(params) == 3+ assert params[0] == {"name": "required", "type": "str"}+ assert params[1] == {"name": "optional", "type": "int", "default": 5}+ assert params[2] == {"name": "untyped", "default": None}+++def test_extract_parameters_complex_types():+ """Test that _extract_parameters handles complex types gracefully."""+ def complex_fn(items: list | None = None, data: dict[str, int] | None = None) -> list:+ pass++ sandbox = PythonInterpreter()+ params = sandbox._extract_parameters(complex_fn)++ assert len(params) == 2+ # Complex types like Union are not included in type annotation+ assert params[0] == {"name": "items", "default": None}+ assert params[1] == {"name": "data", "default": None}+diff --git a/uv.lock b/uv.lockindex 4b9f5c11b..7fde8aae7 100644--- a/uv.lock+++ b/uv.lock@@ -739,10 +739,12 @@ dependencies = [{ name = "diskcache" },{ name = "gepa" },{ name = "json-repair" },- { name = "litellm" },+ { name = "litellm", version = "1.68.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "litellm", version = "1.72.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },{ name = "numpy", version = "2.3.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },- { name = "openai" },+ { name = "openai", version = "1.75.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "openai", version = "1.88.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },{ name = "optuna" },{ name = "orjson" },{ name = "pydantic" },@@ -760,8 +762,8 @@ anthropic = [dev = [{ name = "build" },{ name = "datamodel-code-generator" },- { name = "litellm" },- { name = "litellm", extra = ["proxy"], marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "litellm", version = "1.68.0", source = { registry = "https://pypi.org/simple" }, extra = ["proxy"], marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "litellm", version = "1.72.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },{ name = "pillow" },{ name = "pre-commit" },{ name = "pytest" },@@ -773,13 +775,13 @@ langchain = [{ name = "langchain-core" },]mcp = [- { name = "mcp", version = "1.9.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "mcp", version = "1.5.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "mcp", version = "1.9.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },]test-extras = [{ name = "datasets" },{ name = "langchain-core" },- { name = "mcp", version = "1.9.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "mcp", version = "1.5.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "mcp", version = "1.9.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },{ name = "optuna" },{ name = "pandas" },@@ -1526,24 +1528,30 @@ wheels = [[[package]]name = "litellm"-version = "1.72.6"+version = "1.68.0"source = { registry = "https://pypi.org/simple" }+resolution-markers = [+ "python_full_version >= '3.12.4' and python_full_version < '3.14' and sys_platform != 'win32'",+ "python_full_version >= '3.12' and python_full_version < '3.12.4' and sys_platform != 'win32'",+ "python_full_version == '3.11.*' and sys_platform != 'win32'",+ "python_full_version < '3.11' and sys_platform != 'win32'",+]dependencies = [- { name = "aiohttp" },- { name = "click" },- { name = "httpx" },- { name = "importlib-metadata" },- { name = "jinja2" },- { name = "jsonschema" },- { name = "openai" },- { name = "pydantic" },- { name = "python-dotenv" },- { name = "tiktoken" },- { name = "tokenizers" },+ { name = "aiohttp", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "click", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "httpx", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "importlib-metadata", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "jinja2", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "jsonschema", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "openai", version = "1.75.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "pydantic", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "python-dotenv", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "tiktoken", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "tokenizers", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },]-sdist = { url = "https://files.pythonhosted.org/packages/8d/15/df75f278fd998f6d6900f692b9de2fba2814b316c123c99072a813668aac/litellm-1.72.6.tar.gz", hash = "sha256:4e5c7e4273b09b765302d2faaec30f77b42255c0055b427b55ea02b8092b8582", size = 8393603, upload-time = "2025-06-14T21:43:11.023Z" }+sdist = { url = "https://files.pythonhosted.org/packages/ba/22/138545b646303ca3f4841b69613c697b9d696322a1386083bb70bcbba60b/litellm-1.68.0.tar.gz", hash = "sha256:9fb24643db84dfda339b64bafca505a2eef857477afbc6e98fb56512c24dbbfa", size = 7314051, upload-time = "2025-05-04T05:41:48.081Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/96/c9/4aae0b77632279eef9716dbcb98edd8b36c08a9da070e2470ca9c410c0f8/litellm-1.72.6-py3-none-any.whl", hash = "sha256:e0ae98d25db4910e78b1a0a604f24c0d6875f6cdea02426b264a45d4fbdb8c46", size = 8302810, upload-time = "2025-06-14T21:43:08.628Z" },+ { url = "https://files.pythonhosted.org/packages/10/af/1e344bc8aee41445272e677d802b774b1f8b34bdc3bb5697ba30f0fb5d52/litellm-1.68.0-py3-none-any.whl", hash = "sha256:3bca38848b1a5236b11aa6b70afa4393b60880198c939e582273f51a542d4759", size = 7684460, upload-time = "2025-05-04T05:41:44.78Z" },][package.optional-dependencies]@@ -1555,15 +1563,13 @@ proxy = [{ name = "fastapi", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "fastapi-sso", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "gunicorn", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },- { name = "litellm-enterprise", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "litellm-proxy-extras", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },- { name = "mcp", version = "1.9.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "mcp", version = "1.5.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "orjson", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "pyjwt", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "pynacl", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "python-multipart", version = "0.0.18", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "pyyaml", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },- { name = "rich", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "rq", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "uvicorn", version = "0.29.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "uvloop", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },@@ -1571,22 +1577,38 @@ proxy = [][[package]]-name = "litellm-enterprise"-version = "0.1.7"+name = "litellm"+version = "1.72.6"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/28/a4/d10b32cf325cf2d02a83a489342476987c5573860ff9d1034ce37999d60a/litellm_enterprise-0.1.7.tar.gz", hash = "sha256:1feb5b799bdbd27df1e02a31fa4d18351b945b6f72e337805cf80a64dd2ec870", size = 32369, upload-time = "2025-05-30T03:37:41.652Z" }+resolution-markers = [+ "(python_full_version >= '3.14' and sys_platform != 'win32') or (python_full_version >= '3.12.4' and sys_platform == 'win32')",+ "python_full_version >= '3.12' and python_full_version < '3.12.4' and sys_platform == 'win32'",+ "python_full_version == '3.11.*' and sys_platform == 'win32'",+ "python_full_version < '3.11' and sys_platform == 'win32'",+]+dependencies = [+ { name = "aiohttp", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "click", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "httpx", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "importlib-metadata", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "jinja2", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "jsonschema", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "openai", version = "1.88.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "pydantic", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "python-dotenv", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "tiktoken", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "tokenizers", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/8d/15/df75f278fd998f6d6900f692b9de2fba2814b316c123c99072a813668aac/litellm-1.72.6.tar.gz", hash = "sha256:4e5c7e4273b09b765302d2faaec30f77b42255c0055b427b55ea02b8092b8582", size = 8393603, upload-time = "2025-06-14T21:43:11.023Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/88/5e/64aa4b1d0a3d9f2856d8f4d8dc1388894ca4d046687a1597b21573836960/litellm_enterprise-0.1.7-py3-none-any.whl", hash = "sha256:0f77aebe4103359bb7e7e7fdaf6d9024ec9ea7700b6affb60c9e4dc2cae9f243", size = 90175, upload-time = "2025-12-05T19:11:17.26Z" },+ { url = "https://files.pythonhosted.org/packages/96/c9/4aae0b77632279eef9716dbcb98edd8b36c08a9da070e2470ca9c410c0f8/litellm-1.72.6-py3-none-any.whl", hash = "sha256:e0ae98d25db4910e78b1a0a604f24c0d6875f6cdea02426b264a45d4fbdb8c46", size = 8302810, upload-time = "2025-06-14T21:43:08.628Z" },][[package]]name = "litellm-proxy-extras"-version = "0.2.3"+version = "0.1.15"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/01/50/8cb93f7bb6d04d4e88189fdc6b6a8d42c7cab4796bbcd214048eb38d57c4/litellm_proxy_extras-0.2.3.tar.gz", hash = "sha256:41fc5a5a68894786f1cbc95f86ef939662136164d8da773236f5a141127e5c0c", size = 14164, upload-time = "2025-06-04T04:09:08.033Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/90/a8/8ac27ff1601ff5c4e399bcfdf5ccba9aaef4e214d31976bd87b3a5f5c7b7/litellm_proxy_extras-0.2.3-py3-none-any.whl", hash = "sha256:00c25d94c01c242aa0aa746eb4d5788dcdfd19e6fc1768a36cd03426cb5ffd39", size = 24363, upload-time = "2025-06-04T04:09:06.661Z" },-]+sdist = { url = "https://files.pythonhosted.org/packages/d3/22/2d15f5c0198dee49f8296369486fa6319edca0c3af52e80ae2cdc1118b5a/litellm_proxy_extras-0.1.15.tar.gz", hash = "sha256:0e9b9074023eea8954183746f196d4a62f5d9fda2838fac3cb94d6ee1899a308", size = 11888, upload-time = "2025-05-03T16:29:02.297Z" }[[package]]name = "mako"@@ -1600,18 +1622,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/87/fb/99f81ac72ae23375f22b7afdb7642aba97c00a713c217124420147681a2f/mako-1.3.10-py3-none-any.whl", hash = "sha256:baef24a52fc4fc514a0887ac600f9f1cff3d82c61d4d700a1fa84d597b88db59", size = 78509, upload-time = "2025-04-10T12:50:53.297Z" },]-[[package]]-name = "markdown-it-py"-version = "3.0.0"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "mdurl", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },-]-sdist = { url = "https://files.pythonhosted.org/packages/38/71/3b932df36c1a044d397a1f92d1cf91ee0a503d91e470cbd670aa66b07ed0/markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb", size = 74596, upload-time = "2023-06-03T06:41:14.443Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/42/d7/1ec15b46af6af88f19b8e5ffea08fa375d433c998b8a7639e76935c14f1f/markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1", size = 87528, upload-time = "2023-06-03T06:41:11.019Z" },-]-[[package]]name = "markupsafe"version = "3.0.2"@@ -1672,7 +1682,7 @@ wheels = [[[package]]name = "mcp"-version = "1.9.3"+version = "1.5.0"source = { registry = "https://pypi.org/simple" }resolution-markers = ["python_full_version >= '3.12.4' and python_full_version < '3.14' and sys_platform != 'win32'",@@ -1686,14 +1696,13 @@ dependencies = [{ name = "httpx-sse", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "pydantic", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "pydantic-settings", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },- { name = "python-multipart", version = "0.0.18", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "sse-starlette", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },{ name = "starlette", version = "0.46.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },- { name = "uvicorn", version = "0.29.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'" },+ { name = "uvicorn", version = "0.29.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14' and sys_platform != 'win32'" },]-sdist = { url = "https://files.pythonhosted.org/packages/f2/df/8fefc0c6c7a5c66914763e3ff3893f9a03435628f6625d5e3b0dc45d73db/mcp-1.9.3.tar.gz", hash = "sha256:587ba38448e81885e5d1b84055cfcc0ca56d35cd0c58f50941cab01109405388", size = 333045, upload-time = "2025-06-05T15:48:25.681Z" }+sdist = { url = "https://files.pythonhosted.org/packages/6d/c9/c55764824e893fdebe777ac7223200986a275c3191dba9169f8eb6d7c978/mcp-1.5.0.tar.gz", hash = "sha256:5b2766c05e68e01a2034875e250139839498c61792163a7b221fc170c12f5aa9", size = 159128, upload-time = "2025-03-21T12:51:04.183Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/79/45/823ad05504bea55cb0feb7470387f151252127ad5c72f8882e8fe6cf5c0e/mcp-1.9.3-py3-none-any.whl", hash = "sha256:69b0136d1ac9927402ed4cf221d4b8ff875e7132b0b06edd446448766f34f9b9", size = 131063, upload-time = "2025-06-05T15:48:24.171Z" },+ { url = "https://files.pythonhosted.org/packages/c1/d1/3ff566ecf322077d861f1a68a1ff025cad337417bd66ad22a7c6f7dfcfaf/mcp-1.5.0-py3-none-any.whl", hash = "sha256:51c3f35ce93cb702f7513c12406bbea9665ef75a08db909200b07da9db641527", size = 73734, upload-time = "2025-03-21T12:51:02.597Z" },][[package]]@@ -1722,15 +1731,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/97/fc/80e655c955137393c443842ffcc4feccab5b12fa7cb8de9ced90f90e6998/mcp-1.9.4-py3-none-any.whl", hash = "sha256:7fcf36b62936adb8e63f89346bccca1268eeca9bf6dfb562ee10b1dfbda9dac0", size = 130232, upload-time = "2025-06-12T08:20:28.551Z" },]-[[package]]-name = "mdurl"-version = "0.1.2"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" },-]-[[package]]name = "more-itertools"version = "10.7.0"@@ -2042,19 +2042,50 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/e1/3d/760b1456010ed11ce87c0109007f0166078dfdada7597f0091ae76eb7305/oauthlib-3.3.0-py3-none-any.whl", hash = "sha256:a2b3a0a2a4ec2feb4b9110f56674a39b2cc2f23e14713f4ed20441dfba14e934", size = 165155, upload-time = "2025-06-17T23:19:16.771Z" },]+[[package]]+name = "openai"+version = "1.75.0"+source = { registry = "https://pypi.org/simple" }+resolution-markers = [+ "python_full_version >= '3.12.4' and python_full_version < '3.14' and sys_platform != 'win32'",+ "python_full_version >= '3.12' and python_full_version < '3.12.4' and sys_platform != 'win32'",+ "python_full_version == '3.11.*' and sys_platform != 'win32'",+ "python_full_version < '3.11' and sys_platform != 'win32'",+]+dependencies = [+ { name = "anyio", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "distro", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "httpx", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "jiter", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "pydantic", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "sniffio", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "tqdm", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+ { name = "typing-extensions", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/99/b1/318f5d4c482f19c5fcbcde190801bfaaaec23413cda0b88a29f6897448ff/openai-1.75.0.tar.gz", hash = "sha256:fb3ea907efbdb1bcfd0c44507ad9c961afd7dce3147292b54505ecfd17be8fd1", size = 429492, upload-time = "2025-04-16T16:49:29.25Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/80/9a/f34f163294345f123673ed03e77c33dee2534f3ac1f9d18120384457304d/openai-1.75.0-py3-none-any.whl", hash = "sha256:fe6f932d2ded3b429ff67cc9ad118c71327db32eb9d32dd723de3acfca337125", size = 646972, upload-time = "2025-04-16T16:49:27.196Z" },+]+[[package]]name = "openai"version = "1.88.0"source = { registry = "https://pypi.org/simple" }+resolution-markers = [+ "(python_full_version >= '3.14' and sys_platform != 'win32') or (python_full_version >= '3.12.4' and sys_platform == 'win32')",+ "python_full_version >= '3.12' and python_full_version < '3.12.4' and sys_platform == 'win32'",+ "python_full_version == '3.11.*' and sys_platform == 'win32'",+ "python_full_version < '3.11' and sys_platform == 'win32'",+]dependencies = [- { name = "anyio" },- { name = "distro" },- { name = "httpx" },- { name = "jiter" },- { name = "pydantic" },- { name = "sniffio" },- { name = "tqdm" },- { name = "typing-extensions" },+ { name = "anyio", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "distro", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "httpx", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "jiter", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "pydantic", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "sniffio", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "tqdm", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },+ { name = "typing-extensions", marker = "python_full_version >= '3.14' or sys_platform == 'win32'" },]sdist = { url = "https://files.pythonhosted.org/packages/5a/ea/bbeef604d1fe0f7e9111745bb8a81362973a95713b28855beb9a9832ab12/openai-1.88.0.tar.gz", hash = "sha256:122d35e42998255cf1fc84560f6ee49a844e65c054cd05d3e42fda506b832bb1", size = 470963, upload-time = "2025-06-17T05:04:45.856Z" }wheels = [@@ -3041,19 +3072,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/3f/51/d4db610ef29373b879047326cbf6fa98b6c1969d6f6dc423279de2b1be2c/requests_toolbelt-1.0.0-py2.py3-none-any.whl", hash = "sha256:cccfdd665f0a24fcf4726e690f65639d272bb0637b9b92dfd91a5568ccf6bd06", size = 54481, upload-time = "2023-05-01T04:11:28.427Z" },]-[[package]]-name = "rich"-version = "13.7.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "markdown-it-py", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },- { name = "pygments", marker = "python_full_version < '3.14' and sys_platform != 'win32'" },-]-sdist = { url = "https://files.pythonhosted.org/packages/b3/01/c954e134dc440ab5f96952fe52b4fdc64225530320a910473c1fe270d9aa/rich-13.7.1.tar.gz", hash = "sha256:9be308cb1fe2f1f57d67ce99e95af38a1e2bc71ad9813b0e247cf7ffbcc3a432", size = 221248, upload-time = "2024-02-28T14:51:19.472Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/87/67/a37f6214d0e9fe57f6ae54b2956d550ca8365857f42a1ce0392bb21d9410/rich-13.7.1-py3-none-any.whl", hash = "sha256:4edbae314f59eb482f54e9e30bf00d33350aaa94f4bfcd4e9e3110e64d0d7222", size = 240681, upload-time = "2024-02-28T14:51:14.353Z" },-]-[[package]]name = "rpds-py"version = "0.25.1"