Current section
Files
Jump to
Current section
Files
lib/snakebridge_generated/dspy/rlm.ex
# Generated by SnakeBridge v0.16.0 - DO NOT EDIT MANUALLY
# Regenerate with: mix compile
# Library: dspy 3.2.0
# Python module: dspy
# Python class: RLM
defmodule Dspy.RLM do
@moduledoc """
Experimental: This class may change or be removed in a future release without warning.
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.
## Examples
```python
# Basic usage
rlm = dspy.RLM("context, query -> output", max_iterations=10)
result = rlm(context="...very long text...", query="What is the magic number?")
print(result.output)
```
"""
def __snakebridge_python_name__, do: "dspy"
def __snakebridge_python_class__, do: "RLM"
def __snakebridge_library__, do: "dspy"
@opaque t :: SnakeBridge.Ref.t()
@doc """
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: List of tool functions or dspy.Tool objects 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.
## Parameters
- `signature` (term())
- `max_iterations` (term())
- `max_llm_calls` (term())
- `max_output_chars` (term())
- `verbose` (term())
- `tools` (term())
- `sub_lm` (term())
- `interpreter` (term())
"""
@spec new(term(), term(), term(), term(), term(), term(), term(), term(), keyword()) ::
{:ok, SnakeBridge.Ref.t()} | {:error, Snakepit.Error.t()}
def new(
signature,
max_iterations,
max_llm_calls,
max_output_chars,
verbose,
tools,
sub_lm,
interpreter,
opts \\ []
) do
SnakeBridge.Runtime.call_class(
__MODULE__,
:__init__,
[
signature,
max_iterations,
max_llm_calls,
max_output_chars,
verbose,
tools,
sub_lm,
interpreter
],
opts
)
end
@doc """
Load the saved module. You may also want to check out dspy.load, if you want to
load an entire program, not just the state for an existing program.
## Parameters
- `path` - Path to the saved state file, which should be a .json or a .pkl file (type: `String.t()`)
- `allow_pickle` - If True, allow loading .pkl files, which can run arbitrary code. This is dangerous and should only be used if you are sure about the source of the file and in a trusted environment. (type: `boolean()`)
- `allow_unsafe_lm_state` - If True, preserves unsafe LM endpoint keys (e.g., `api_base`, `base_url`, and `model_list`) from loaded state. Enable only for trusted files. (type: `boolean()`)
## Returns
- `term()`
"""
@spec load(SnakeBridge.Ref.t(), term(), list(term()), keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def load(ref, path, args, opts \\ []) do
{args, opts} = SnakeBridge.Runtime.normalize_args_opts(args, opts)
SnakeBridge.Runtime.call_method(ref, :load, [path] ++ List.wrap(args), opts)
end
@doc """
Deep copy the module.
This is a tweak to the default python deepcopy that only deep copies `self.parameters()`, and for other
attributes, we just do the shallow copy.
## Returns
- `term()`
"""
@spec deepcopy(SnakeBridge.Ref.t(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def deepcopy(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :deepcopy, [], opts)
end
@doc """
Python method `RLM._set_lm_usage`.
## Parameters
- `tokens` (%{optional(String.t()) => term()})
- `output` (term())
## Returns
- `term()`
"""
@spec _set_lm_usage(SnakeBridge.Ref.t(), %{optional(String.t()) => term()}, term(), keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def _set_lm_usage(ref, tokens, output, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_set_lm_usage, [tokens, output], opts)
end
@doc """
Build REPLVariable list from input arguments with field metadata.
## Parameters
- `input_args` (term())
## Returns
- `list(Dspy.Primitives.ReplTypes.REPLVariable.t())`
"""
@spec _build_variables(SnakeBridge.Ref.t(), keyword()) ::
{:ok, list(Dspy.Primitives.ReplTypes.REPLVariable.t())} | {:error, Snakepit.Error.t()}
def _build_variables(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_build_variables, [], opts)
end
@doc """
Save the module.
Save the module to a directory or a file. There are two modes:
- `save_program=False`: Save only the state of the module to a json or pickle file, based on the value of
the file extension.
- `save_program=True`: Save the whole module to a directory via cloudpickle, which contains both the state and
architecture of the model.
If `save_program=True` and `modules_to_serialize` are provided, it will register those modules for serialization
with cloudpickle's `register_pickle_by_value`. This causes cloudpickle to serialize the module by value rather
than by reference, ensuring the module is fully preserved along with the saved program. This is useful
when you have custom modules that need to be serialized alongside your program. If None, then no modules
will be registered for serialization.
We also save the dependency versions, so that the loaded model can check if there is a version mismatch on
critical dependencies or DSPy version.
## Parameters
- `path` - Path to the saved state file, which should be a .json or .pkl file when `save_program=False`, and a directory when `save_program=True`. (type: `String.t()`)
- `save_program` - If True, save the whole module to a directory via cloudpickle, otherwise only save the state. (type: `boolean()`)
- `modules_to_serialize` - A list of modules to serialize with cloudpickle's `register_pickle_by_value`. If None, then no modules will be registered for serialization. (type: `list()`)
## Returns
- `term()`
"""
@spec save(SnakeBridge.Ref.t(), term(), list(term()), keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def save(ref, path, args, opts \\ []) do
{args, opts} = SnakeBridge.Runtime.normalize_args_opts(args, opts)
SnakeBridge.Runtime.call_method(ref, :save, [path] ++ List.wrap(args), opts)
end
@doc """
Processes a list of dspy.Example instances in parallel using the Parallel module.
## Parameters
- `examples` - List of dspy.Example instances to process.
- `num_threads` - Number of threads to use for parallel processing.
- `max_errors` - Maximum number of errors allowed before stopping execution. If ``None``, inherits from ``dspy.settings.max_errors``.
- `return_failed_examples` - Whether to return failed examples and exceptions.
- `provide_traceback` - Whether to include traceback information in error logs.
- `disable_progress_bar` - Whether to display the progress bar.
- `timeout` - Seconds before a straggler task is resubmitted. Set to 0 to disable.
- `straggler_limit` - Only check for stragglers when this many or fewer tasks remain.
## Returns
- `term()`
"""
@spec batch(SnakeBridge.Ref.t(), list(term()), list(term()), keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def batch(ref, examples, args, opts \\ []) do
{args, opts} = SnakeBridge.Runtime.normalize_args_opts(args, opts)
SnakeBridge.Runtime.call_method(ref, :batch, [examples] ++ List.wrap(args), opts)
end
@doc """
Async version of forward(). Execute RLM to produce outputs.
## Raises
- `ArgumentError` - If required input fields are missing
## Parameters
- `input_args` (term())
## Returns
- `term()`
"""
@spec aforward(SnakeBridge.Ref.t(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def aforward(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :aforward, [], opts)
end
@doc """
Get output field info for sandbox registration.
## Returns
- `list(%{optional(term()) => term()})`
"""
@spec _get_output_fields_info(SnakeBridge.Ref.t(), keyword()) ::
{:ok, list(%{optional(term()) => term()})} | {:error, Snakepit.Error.t()}
def _get_output_fields_info(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_get_output_fields_info, [], opts)
end
@doc """
Validate user-provided tools have valid names.
## Parameters
- `tools` (%{optional(String.t()) => term()})
## Returns
- `nil`
"""
@spec _validate_tools(SnakeBridge.Ref.t(), %{optional(String.t()) => term()}, keyword()) ::
{:ok, nil} | {:error, Snakepit.Error.t()}
def _validate_tools(ref, tools, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_validate_tools, [tools], opts)
end
@doc """
Get the language model used by this module's predictors.
Returns the language model if all predictors use the same LM.
Raises an error if multiple different LMs are in use.
## Raises
- `ArgumentError` - If multiple different language models are being used by the predictors in this module.
## Returns
- `term()`
"""
@spec get_lm(SnakeBridge.Ref.t(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def get_lm(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :get_lm, [], opts)
end
@doc """
Process interpreter result, returning Prediction if final, else updated history.
This shared helper reduces duplication between sync and async execution paths.
## Parameters
- `pred` - The prediction containing reasoning and code attributes
- `code` - Code to record in history (already stripped when possible)
- `result` - Result from interpreter.execute() - FinalOutput, list, str, or error string
- `history` - Current REPL history
- `output_field_names` - List of expected output field names
## Returns
- `term()`
"""
@spec _process_execution_result(
SnakeBridge.Ref.t(),
term(),
String.t(),
term(),
Dspy.Primitives.ReplTypes.REPLHistory.t(),
list(String.t()),
keyword()
) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def _process_execution_result(ref, pred, code, result, history, output_field_names, opts \\ []) do
SnakeBridge.Runtime.call_method(
ref,
:_process_execution_result,
[pred, code, result, history, output_field_names],
opts
)
end
@doc """
Python method `RLM.dump_state`.
## Parameters
- `json_mode` (term() default: True)
## Returns
- `term()`
"""
@spec dump_state(SnakeBridge.Ref.t(), list(term()), keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def dump_state(ref, args, opts \\ []) do
{args, opts} = SnakeBridge.Runtime.normalize_args_opts(args, opts)
SnakeBridge.Runtime.call_method(ref, :dump_state, [] ++ List.wrap(args), opts)
end
@doc """
Create fresh LLM tools and merge with user-provided tools.
## Returns
- `%{optional(String.t()) => term()}`
"""
@spec _prepare_execution_tools(SnakeBridge.Ref.t(), keyword()) ::
{:ok, %{optional(String.t()) => term()}} | {:error, Snakepit.Error.t()}
def _prepare_execution_tools(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_prepare_execution_tools, [], opts)
end
@doc """
Format user-provided tools for inclusion in instructions.
## Parameters
- `tools` (%{optional(String.t()) => term()})
## Returns
- `String.t()`
"""
@spec _format_tool_docs(SnakeBridge.Ref.t(), %{optional(String.t()) => term()}, keyword()) ::
{:ok, String.t()} | {:error, Snakepit.Error.t()}
def _format_tool_docs(ref, tools, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_format_tool_docs, [tools], opts)
end
@doc """
Python method `RLM.load_state`.
## Parameters
- `state` (term())
- `allow_unsafe_lm_state` (term() keyword-only default: False)
## Returns
- `term()`
"""
@spec load_state(SnakeBridge.Ref.t(), term(), keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def load_state(ref, state, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :load_state, [state], opts)
end
@doc """
Return all Predict modules in this module.
## Examples
iex> import dspy
iex> class MyProgram(dspy.Module):
...> def __init__(self):
...> super().__init__()
...> self.qa = dspy.Predict("question -> answer")
...>
iex> program = MyProgram()
iex> len(program.predictors())
1
## Returns
- `term()`
"""
@spec predictors(SnakeBridge.Ref.t(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def predictors(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :predictors, [], opts)
end
@doc """
Raise ValueError if required input fields are missing.
## Parameters
- `input_args` (%{optional(String.t()) => term()})
## Returns
- `nil`
"""
@spec _validate_inputs(SnakeBridge.Ref.t(), %{optional(String.t()) => term()}, keyword()) ::
{:ok, nil} | {:error, Snakepit.Error.t()}
def _validate_inputs(ref, input_args, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_validate_inputs, [input_args], opts)
end
@doc """
Execute code in the interpreter, returning the result or an error string.
## Parameters
- `repl` (term())
- `code` (String.t())
- `input_args` (%{optional(String.t()) => term()})
## Returns
- `term()`
"""
@spec _execute_code(
SnakeBridge.Ref.t(),
term(),
String.t(),
%{optional(String.t()) => term()},
keyword()
) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def _execute_code(ref, repl, code, input_args, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_execute_code, [repl, code, input_args], opts)
end
@doc """
Async version: Execute one iteration.
## Parameters
- `repl` (term())
- `variables` (list(Dspy.Primitives.ReplTypes.REPLVariable.t()))
- `history` (Dspy.Primitives.ReplTypes.REPLHistory.t())
- `iteration` (integer())
- `input_args` (%{optional(String.t()) => term()})
- `output_field_names` (list(String.t()))
## Returns
- `term()`
"""
@spec _aexecute_iteration(
SnakeBridge.Ref.t(),
term(),
list(Dspy.Primitives.ReplTypes.REPLVariable.t()),
Dspy.Primitives.ReplTypes.REPLHistory.t(),
integer(),
%{optional(String.t()) => term()},
list(String.t()),
keyword()
) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def _aexecute_iteration(
ref,
repl,
variables,
history,
iteration,
input_args,
output_field_names,
opts \\ []
) do
SnakeBridge.Runtime.call_method(
ref,
:_aexecute_iteration,
[repl, variables, history, iteration, input_args, output_field_names],
opts
)
end
@doc """
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.
## Parameters
- `interpreter` (term())
- `execution_tools` (%{optional(String.t()) => term()})
## Returns
- `nil`
"""
@spec _inject_execution_context(
SnakeBridge.Ref.t(),
term(),
%{optional(String.t()) => term()},
keyword()
) :: {:ok, nil} | {:error, Snakepit.Error.t()}
def _inject_execution_context(ref, interpreter, execution_tools, opts \\ []) do
SnakeBridge.Runtime.call_method(
ref,
:_inject_execution_context,
[interpreter, execution_tools],
opts
)
end
@doc """
Create llm_query and llm_query_batched tools with a fresh call counter.
## Parameters
- `max_workers` (integer() default: 8)
## Returns
- `%{optional(String.t()) => term()}`
"""
@spec _make_llm_tools(SnakeBridge.Ref.t(), list(term()), keyword()) ::
{:ok, %{optional(String.t()) => term()}} | {:error, Snakepit.Error.t()}
def _make_llm_tools(ref, args, opts \\ []) do
{args, opts} = SnakeBridge.Runtime.normalize_args_opts(args, opts)
SnakeBridge.Runtime.call_method(ref, :_make_llm_tools, [] ++ List.wrap(args), opts)
end
@doc """
Yield interpreter, creating PythonInterpreter if none provided at init.
## Parameters
- `execution_tools` (%{optional(String.t()) => term()})
## Returns
- `term()`
"""
@spec _interpreter_context(SnakeBridge.Ref.t(), %{optional(String.t()) => term()}, keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def _interpreter_context(ref, execution_tools, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_interpreter_context, [execution_tools], opts)
end
@doc """
Set the language model for all predictors in this module.
This method recursively sets the language model for all Predict
instances contained within this module.
## Parameters
- `lm` - The language model instance to use for all predictors.
## Examples
iex> import dspy
iex> lm = dspy.LM("openai/gpt-4o-mini")
iex> program = dspy.Predict("question -> answer")
iex> program.set_lm(lm)
## Returns
- `term()`
"""
@spec set_lm(SnakeBridge.Ref.t(), term(), keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def set_lm(ref, lm, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :set_lm, [lm], opts)
end
@doc """
Display the LM call history for this module.
Prints a formatted view of the most recent language model calls
made by this module, useful for debugging and understanding
the module's behavior.
## Parameters
- `n` - The number of recent history entries to display. Defaults to 1.
- `file` - An optional file-like object to write output to. When provided, ANSI color codes are automatically disabled. Defaults to `None` (prints to stdout).
## Returns
- `nil`
"""
@spec inspect_history(SnakeBridge.Ref.t(), list(term()), keyword()) ::
{:ok, nil} | {:error, Snakepit.Error.t()}
def inspect_history(ref, args, opts \\ []) do
{args, opts} = SnakeBridge.Runtime.normalize_args_opts(args, opts)
SnakeBridge.Runtime.call_method(ref, :inspect_history, [] ++ List.wrap(args), opts)
end
@doc """
Python method `RLM._format_output`.
## Parameters
- `output` (String.t())
## Returns
- `String.t()`
"""
@spec _format_output(SnakeBridge.Ref.t(), String.t(), keyword()) ::
{:ok, String.t()} | {:error, Snakepit.Error.t()}
def _format_output(ref, output, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_format_output, [output], opts)
end
@doc """
Unlike PyTorch, handles (non-recursive) lists of parameters too.
## Returns
- `term()`
"""
@spec named_parameters(SnakeBridge.Ref.t(), keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def named_parameters(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :named_parameters, [], opts)
end
@doc """
Deep copy the module and reset all parameters.
## Returns
- `term()`
"""
@spec reset_copy(SnakeBridge.Ref.t(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def reset_copy(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :reset_copy, [], opts)
end
@doc """
Python method `RLM._base_init`.
## Returns
- `term()`
"""
@spec _base_init(SnakeBridge.Ref.t(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def _base_init(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_base_init, [], opts)
end
@doc """
Find all sub-modules in the module, as well as their names.
Say `self.children[4]['key'].sub_module` is a sub-module. Then the name will be
`children[4]['key'].sub_module`. But if the sub-module is accessible at different
paths, only one of the paths will be returned.
## Parameters
- `type_` (term() default: None)
- `skip_compiled` (term() default: False)
## Returns
- `term()`
"""
@spec named_sub_modules(SnakeBridge.Ref.t(), list(term()), keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def named_sub_modules(ref, args, opts \\ []) do
{args, opts} = SnakeBridge.Runtime.normalize_args_opts(args, opts)
SnakeBridge.Runtime.call_method(ref, :named_sub_modules, [] ++ List.wrap(args), opts)
end
@doc """
Use extract module to get final output when max iterations reached.
## Parameters
- `variables` (list(Dspy.Primitives.ReplTypes.REPLVariable.t()))
- `history` (Dspy.Primitives.ReplTypes.REPLHistory.t())
- `output_field_names` (list(String.t()))
## Returns
- `term()`
"""
@spec _extract_fallback(
SnakeBridge.Ref.t(),
list(Dspy.Primitives.ReplTypes.REPLVariable.t()),
Dspy.Primitives.ReplTypes.REPLHistory.t(),
list(String.t()),
keyword()
) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def _extract_fallback(ref, variables, history, output_field_names, opts \\ []) do
SnakeBridge.Runtime.call_method(
ref,
:_extract_fallback,
[variables, history, output_field_names],
opts
)
end
@doc """
Build the action and extract signatures from templates.
## Returns
- `term()`
"""
@spec _build_signatures(SnakeBridge.Ref.t(), keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def _build_signatures(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_build_signatures, [], opts)
end
@doc """
Execute one iteration. Returns Prediction if done, else updated REPLHistory.
## Parameters
- `repl` (term())
- `variables` (list(Dspy.Primitives.ReplTypes.REPLVariable.t()))
- `history` (Dspy.Primitives.ReplTypes.REPLHistory.t())
- `iteration` (integer())
- `input_args` (%{optional(String.t()) => term()})
- `output_field_names` (list(String.t()))
## Returns
- `term()`
"""
@spec _execute_iteration(
SnakeBridge.Ref.t(),
term(),
list(Dspy.Primitives.ReplTypes.REPLVariable.t()),
Dspy.Primitives.ReplTypes.REPLHistory.t(),
integer(),
%{optional(String.t()) => term()},
list(String.t()),
keyword()
) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def _execute_iteration(
ref,
repl,
variables,
history,
iteration,
input_args,
output_field_names,
opts \\ []
) do
SnakeBridge.Runtime.call_method(
ref,
:_execute_iteration,
[repl, variables, history, iteration, input_args, output_field_names],
opts
)
end
@doc """
Normalize tools list to a dict of Tool objects keyed by name.
## Parameters
- `tools` (term())
## Returns
- `%{optional(String.t()) => term()}`
"""
@spec _normalize_tools(SnakeBridge.Ref.t(), term(), keyword()) ::
{:ok, %{optional(String.t()) => term()}} | {:error, Snakepit.Error.t()}
def _normalize_tools(ref, tools, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_normalize_tools, [tools], opts)
end
@doc """
Execute RLM to produce outputs from the given inputs.
## Raises
- `ArgumentError` - If required input fields are missing
## Parameters
- `input_args` (term())
## Returns
- `term()`
"""
@spec forward(SnakeBridge.Ref.t(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def forward(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :forward, [], opts)
end
@doc """
Async version: Use extract module when max iterations reached.
## Parameters
- `variables` (list(Dspy.Primitives.ReplTypes.REPLVariable.t()))
- `history` (Dspy.Primitives.ReplTypes.REPLHistory.t())
- `output_field_names` (list(String.t()))
## Returns
- `term()`
"""
@spec _aextract_fallback(
SnakeBridge.Ref.t(),
list(Dspy.Primitives.ReplTypes.REPLVariable.t()),
Dspy.Primitives.ReplTypes.REPLHistory.t(),
list(String.t()),
keyword()
) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def _aextract_fallback(ref, variables, history, output_field_names, opts \\ []) do
SnakeBridge.Runtime.call_method(
ref,
:_aextract_fallback,
[variables, history, output_field_names],
opts
)
end
@doc """
Python method `RLM.acall`.
## Parameters
- `args` (term())
- `kwargs` (term())
## Returns
- `term()`
"""
@spec acall(SnakeBridge.Ref.t(), list(term()), keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def acall(ref, args, opts \\ []) do
{args, opts} = SnakeBridge.Runtime.normalize_args_opts(args, opts)
SnakeBridge.Runtime.call_method(ref, :acall, [] ++ List.wrap(args), opts)
end
@doc """
Return all named Predict modules in this module.
Iterates through all parameters and returns those that are instances
of ``dspy.Predict``, along with their names.
## Examples
iex> import dspy
iex> class MyProgram(dspy.Module):
...> def __init__(self):
...> super().__init__()
...> self.qa = dspy.Predict("question -> answer")
...> self.summarize = dspy.Predict("text -> summary")
...>
iex> program = MyProgram()
iex> for name, p in program.named_predictors():
...> print(name)
qa
summarize
## Returns
- `term()`
"""
@spec named_predictors(SnakeBridge.Ref.t(), keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def named_predictors(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :named_predictors, [], opts)
end
@doc """
Validate and parse FinalOutput. Returns (parsed_outputs, None) or (None, error).
## Parameters
- `result` (term())
- `output_field_names` (list(String.t()))
## Returns
- `{term(), term()}`
"""
@spec _process_final_output(SnakeBridge.Ref.t(), term(), list(String.t()), keyword()) ::
{:ok, {term(), term()}} | {:error, Snakepit.Error.t()}
def _process_final_output(ref, result, output_field_names, opts \\ []) do
SnakeBridge.Runtime.call_method(
ref,
:_process_final_output,
[result, output_field_names],
opts
)
end
@doc """
Python method `RLM.parameters`.
## Returns
- `term()`
"""
@spec parameters(SnakeBridge.Ref.t(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def parameters(ref, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :parameters, [], opts)
end
@doc """
Apply a function to all named predictors in this module.
This method iterates through all Predict instances in the module
and applies the given function to each, replacing the original
predictor with the function's return value.
## Parameters
- `func` - A callable that takes a Predict instance and returns a new Predict instance (or compatible object).
## Returns
Returns `Module`. Returns self for method chaining.
## Examples
iex> import dspy
iex> class MyProgram(dspy.Module):
...> def __init__(self):
...> super().__init__()
...> self.qa = dspy.Predict("question -> answer")
...>
iex> program = MyProgram()
iex> program.map_named_predictors(lambda p: p)
"""
@spec map_named_predictors(SnakeBridge.Ref.t(), term(), keyword()) ::
{:ok, term()} | {:error, Snakepit.Error.t()}
def map_named_predictors(ref, func, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :map_named_predictors, [func], opts)
end
@spec _reserved_tool_names(SnakeBridge.Ref.t()) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def _reserved_tool_names(ref) do
SnakeBridge.Runtime.get_attr(ref, :_RESERVED_TOOL_NAMES)
end
@spec tools(SnakeBridge.Ref.t()) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def tools(ref) do
SnakeBridge.Runtime.get_attr(ref, :tools)
end
end