# Generated by SnakeBridge v0.15.0 - DO NOT EDIT MANUALLY # Regenerate with: mix compile # Library: dspy 3.1.2 # Python module: dspy defmodule Dspy do @moduledoc """ SnakeBridge bindings for `dspy`. ## Version - Requested: 3.1.2 - Observed at generation: 3.1.2 ## Runtime Options All functions accept a `__runtime__` option for controlling execution behavior: Dspy.some_function(args, __runtime__: [timeout: 120_000]) ### Supported runtime options - `:timeout` - Call timeout in milliseconds (default: 120,000ms / 2 minutes) - `:timeout_profile` - Use a named profile (`:default`, `:ml_inference`, `:batch_job`, `:streaming`) - `:stream_timeout` - Timeout for streaming operations (default: 1,800,000ms / 30 minutes) - `:session_id` - Override the session ID for this call - `:pool_name` - Target a specific Snakepit pool (multi-pool setups) - `:affinity` - Override session affinity (`:hint`, `:strict_queue`, `:strict_fail_fast`) ### Timeout Profiles - `:default` - 2 minute timeout for regular calls - `:ml_inference` - 10 minute timeout for ML/LLM workloads - `:batch_job` - Unlimited timeout for long-running jobs - `:streaming` - 2 minute timeout, 30 minute stream_timeout ### Example with timeout override # For a long-running ML inference call Dspy.predict(data, __runtime__: [timeout_profile: :ml_inference]) # Or explicit timeout Dspy.predict(data, __runtime__: [timeout: 600_000]) # Route to a pool and enforce strict affinity Dspy.predict(data, __runtime__: [pool_name: :strict_pool, affinity: :strict_queue]) See `SnakeBridge.Defaults` for global timeout configuration. """ @doc false def __snakebridge_python_name__, do: "dspy" @doc false def __snakebridge_library__, do: "dspy" @doc """ Wraps a DSPy program so that it can be called asynchronously. This is useful for running a program in parallel with another task (e.g., another DSPy program). This implementation propagates the current thread's configuration context to the worker thread. ## Parameters - `program` - The DSPy program to be wrapped for asynchronous execution. ## Returns - `term()` """ @spec asyncify(term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def asyncify(program, opts \\ []) do SnakeBridge.Runtime.call(__MODULE__, :asyncify, [program], opts) end @doc """ Python binding for `dspy.bootstrap_trace_data`. ## Parameters - `program` (term()) - `dataset` (list(term())) - `metric` (term() | nil default: None) - `num_threads` (term() default: None) - `raise_on_error` (term() default: True) - `capture_failed_parses` (term() default: False) - `failure_score` (float() default: 0) - `format_failure_score` (float() default: -1) - `log_format_failures` (boolean() default: False) - `callback_metadata` (term() default: None) ## Returns - `list(term())` """ @spec bootstrap_trace_data(term(), list(term())) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data(term(), list(term()), keyword()) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data(term(), list(term()), term() | nil) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data(term(), list(term()), term() | nil, keyword()) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data(term(), list(term()), term() | nil, term()) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data(term(), list(term()), term() | nil, term(), keyword()) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data(term(), list(term()), term() | nil, term(), term()) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data(term(), list(term()), term() | nil, term(), term(), keyword()) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data(term(), list(term()), term() | nil, term(), term(), term()) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( term(), list(term()), term() | nil, term(), term(), term(), keyword() ) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data(term(), list(term()), term() | nil, term(), term(), term(), float()) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( term(), list(term()), term() | nil, term(), term(), term(), float(), keyword() ) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( term(), list(term()), term() | nil, term(), term(), term(), float(), float() ) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( term(), list(term()), term() | nil, term(), term(), term(), float(), float(), keyword() ) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( term(), list(term()), term() | nil, term(), term(), term(), float(), float(), boolean() ) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( term(), list(term()), term() | nil, term(), term(), term(), float(), float(), boolean(), keyword() ) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( term(), list(term()), term() | nil, term(), term(), term(), float(), float(), boolean(), term() ) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( term(), list(term()), term() | nil, term(), term(), term(), float(), float(), boolean(), term(), keyword() ) :: {:ok, list(term())} | {:error, Snakepit.Error.t()} def bootstrap_trace_data(program, dataset) do SnakeBridge.Runtime.call(__MODULE__, :bootstrap_trace_data, [program, dataset], []) end def bootstrap_trace_data(program, dataset, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :bootstrap_trace_data, [program, dataset], opts) end def bootstrap_trace_data(program, dataset, metric) do SnakeBridge.Runtime.call(__MODULE__, :bootstrap_trace_data, [program, dataset, metric], []) end def bootstrap_trace_data(program, dataset, metric, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :bootstrap_trace_data, [program, dataset, metric], opts) end def bootstrap_trace_data(program, dataset, metric, num_threads) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [program, dataset, metric, num_threads], [] ) end def bootstrap_trace_data(program, dataset, metric, num_threads, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [program, dataset, metric, num_threads], opts ) end def bootstrap_trace_data(program, dataset, metric, num_threads, raise_on_error) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [program, dataset, metric, num_threads, raise_on_error], [] ) end def bootstrap_trace_data(program, dataset, metric, num_threads, raise_on_error, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [program, dataset, metric, num_threads, raise_on_error], opts ) end def bootstrap_trace_data( program, dataset, metric, num_threads, raise_on_error, capture_failed_parses ) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [program, dataset, metric, num_threads, raise_on_error, capture_failed_parses], [] ) end def bootstrap_trace_data( program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, opts ) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [program, dataset, metric, num_threads, raise_on_error, capture_failed_parses], opts ) end def bootstrap_trace_data( program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score ) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [ program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score ], [] ) end def bootstrap_trace_data( program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score, opts ) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [ program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score ], opts ) end def bootstrap_trace_data( program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score, format_failure_score ) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [ program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score, format_failure_score ], [] ) end def bootstrap_trace_data( program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score, format_failure_score, opts ) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [ program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score, format_failure_score ], opts ) end def bootstrap_trace_data( program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score, format_failure_score, log_format_failures ) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [ program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score, format_failure_score, log_format_failures ], [] ) end def bootstrap_trace_data( program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score, format_failure_score, log_format_failures, opts ) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [ program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score, format_failure_score, log_format_failures ], opts ) end def bootstrap_trace_data( program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score, format_failure_score, log_format_failures, callback_metadata ) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [ program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score, format_failure_score, log_format_failures, callback_metadata ], [] ) end def bootstrap_trace_data( program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score, format_failure_score, log_format_failures, callback_metadata, opts ) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :bootstrap_trace_data, [ program, dataset, metric, num_threads, raise_on_error, capture_failed_parses, failure_score, format_failure_score, log_format_failures, callback_metadata ], opts ) end @doc """ DSPy Cache `Cache` provides 2 levels of caching (in the given order): 1. In-memory cache - implemented with cachetools.LRUCache 2. On-disk cache - implemented with diskcache.FanoutCache ## Returns - `term()` """ @spec cache() :: {:ok, term()} | {:error, Snakepit.Error.t()} def cache() do SnakeBridge.Runtime.get_module_attr(__MODULE__, :cache) end @doc """ Python binding for `dspy.configure`. ## Parameters - `kwargs` (term()) ## Returns - `term()` """ @spec configure(keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def configure(opts \\ []) do SnakeBridge.Runtime.call(__MODULE__, :configure, [], opts) end @doc """ Configure the cache for DSPy. ## Parameters - `enable_disk_cache` - Whether to enable on-disk cache. - `enable_memory_cache` - Whether to enable in-memory cache. - `disk_cache_dir` - The directory to store the on-disk cache. - `disk_size_limit_bytes` - The size limit of the on-disk cache. - `memory_max_entries` - The maximum number of entries in the in-memory cache. To allow the cache to grow without bounds, set this parameter to `math.inf` or a similar value. ## Returns - `term()` """ @spec configure_cache() :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec configure_cache(keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec configure_cache(term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec configure_cache(term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec configure_cache(term(), term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec configure_cache(term(), term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec configure_cache(term(), term(), term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec configure_cache(term(), term(), term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec configure_cache(term(), term(), term(), term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec configure_cache(term(), term(), term(), term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec configure_cache(term(), term(), term(), term(), integer()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec configure_cache(term(), term(), term(), term(), integer(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def configure_cache() do SnakeBridge.Runtime.call(__MODULE__, :configure_cache, [], []) end def configure_cache(opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :configure_cache, [], opts) end def configure_cache(enable_disk_cache) do SnakeBridge.Runtime.call(__MODULE__, :configure_cache, [enable_disk_cache], []) end def configure_cache(enable_disk_cache, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :configure_cache, [enable_disk_cache], opts) end def configure_cache(enable_disk_cache, enable_memory_cache) do SnakeBridge.Runtime.call( __MODULE__, :configure_cache, [enable_disk_cache, enable_memory_cache], [] ) end def configure_cache(enable_disk_cache, enable_memory_cache, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :configure_cache, [enable_disk_cache, enable_memory_cache], opts ) end def configure_cache(enable_disk_cache, enable_memory_cache, disk_cache_dir) do SnakeBridge.Runtime.call( __MODULE__, :configure_cache, [enable_disk_cache, enable_memory_cache, disk_cache_dir], [] ) end def configure_cache(enable_disk_cache, enable_memory_cache, disk_cache_dir, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :configure_cache, [enable_disk_cache, enable_memory_cache, disk_cache_dir], opts ) end def configure_cache( enable_disk_cache, enable_memory_cache, disk_cache_dir, disk_size_limit_bytes ) do SnakeBridge.Runtime.call( __MODULE__, :configure_cache, [enable_disk_cache, enable_memory_cache, disk_cache_dir, disk_size_limit_bytes], [] ) end def configure_cache( enable_disk_cache, enable_memory_cache, disk_cache_dir, disk_size_limit_bytes, opts ) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :configure_cache, [enable_disk_cache, enable_memory_cache, disk_cache_dir, disk_size_limit_bytes], opts ) end def configure_cache( enable_disk_cache, enable_memory_cache, disk_cache_dir, disk_size_limit_bytes, memory_max_entries ) do SnakeBridge.Runtime.call( __MODULE__, :configure_cache, [ enable_disk_cache, enable_memory_cache, disk_cache_dir, disk_size_limit_bytes, memory_max_entries ], [] ) end def configure_cache( enable_disk_cache, enable_memory_cache, disk_cache_dir, disk_size_limit_bytes, memory_max_entries, opts ) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :configure_cache, [ enable_disk_cache, enable_memory_cache, disk_cache_dir, disk_size_limit_bytes, memory_max_entries ], opts ) end @doc """ Python binding for `dspy.configure_dspy_loggers`. ## Parameters - `root_module_name` (term()) ## Returns - `term()` """ @spec configure_dspy_loggers(term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def configure_dspy_loggers(root_module_name, opts \\ []) do SnakeBridge.Runtime.call(__MODULE__, :configure_dspy_loggers, [root_module_name], opts) end @doc """ Context manager for temporary configuration changes at the thread level. Does not affect global configuration. Changes only apply to the current thread. If threads are spawned inside this block using ParallelExecutor, they will inherit these overrides. ## Parameters - `kwargs` (term()) ## Returns - `term()` """ @spec context(keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def context(opts \\ []) do SnakeBridge.Runtime.call(__MODULE__, :context, [], opts) end @doc """ Python binding for `dspy.disable_litellm_logging`. ## Returns - `term()` """ @spec disable_litellm_logging(keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def disable_litellm_logging(opts \\ []) do SnakeBridge.Runtime.call(__MODULE__, :disable_litellm_logging, [], opts) end @doc """ Disables the `DSPyLoggingStream` used by event logging APIs throughout DSPy (`eprint()`, `logger.info()`, etc), silencing all subsequent event logs. ## Returns - `term()` """ @spec disable_logging(keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def disable_logging(opts \\ []) do SnakeBridge.Runtime.call(__MODULE__, :disable_logging, [], opts) end @doc """ DSPy Cache `Cache` provides 2 levels of caching (in the given order): 1. In-memory cache - implemented with cachetools.LRUCache 2. On-disk cache - implemented with diskcache.FanoutCache ## Returns - `term()` """ @spec dspy_cache() :: {:ok, term()} | {:error, Snakepit.Error.t()} def dspy_cache() do SnakeBridge.Runtime.get_module_attr(__MODULE__, "DSPY_CACHE") end @doc """ Python binding for `dspy.enable_litellm_logging`. ## Returns - `term()` """ @spec enable_litellm_logging(keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def enable_litellm_logging(opts \\ []) do SnakeBridge.Runtime.call(__MODULE__, :enable_litellm_logging, [], opts) end @doc """ Enables the `DSPyLoggingStream` used by event logging APIs throughout DSPy (`eprint()`, `logger.info()`, etc), emitting all subsequent event logs. This reverses the effects of `disable_logging()`. ## Returns - `term()` """ @spec enable_logging(keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def enable_logging(opts \\ []) do SnakeBridge.Runtime.call(__MODULE__, :enable_logging, [], opts) end @doc """ Python binding for `dspy.ensure_signature`. ## Parameters - `signature` (term()) - `instructions` (term() default: None) ## Returns - `term()` """ @spec ensure_signature(term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec ensure_signature(term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec ensure_signature(term(), term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec ensure_signature(term(), term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def ensure_signature(signature) do SnakeBridge.Runtime.call(__MODULE__, :ensure_signature, [signature], []) end def ensure_signature(signature, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :ensure_signature, [signature], opts) end def ensure_signature(signature, instructions) do SnakeBridge.Runtime.call(__MODULE__, :ensure_signature, [signature, instructions], []) end def ensure_signature(signature, instructions, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :ensure_signature, [signature, instructions], opts) end @doc """ Infer a prefix from an attribute name by converting it to a human-readable format. ## Examples "camelCaseText" -> "Camel Case Text" "snake_case_text" -> "Snake Case Text" "text2number" -> "Text 2 Number" "HTMLParser" -> "HTML Parser" ## Parameters - `attribute_name` (String.t()) ## Returns - `String.t()` """ @spec infer_prefix(String.t(), keyword()) :: {:ok, String.t()} | {:error, Snakepit.Error.t()} def infer_prefix(attribute_name, opts \\ []) do SnakeBridge.Runtime.call(__MODULE__, :infer_prefix, [attribute_name], opts) end @doc """ Python binding for `dspy.InputField`. ## Parameters - `kwargs` (term()) ## Returns - `term()` """ @spec input_field(keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def input_field(opts \\ []) do SnakeBridge.Runtime.call(__MODULE__, "InputField", [], opts) end @doc """ The global history shared across all LMs. ## Parameters - `n` (integer() default: 1) ## Returns - `term()` """ @spec inspect_history() :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec inspect_history(keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec inspect_history(integer()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec inspect_history(integer(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def inspect_history() do SnakeBridge.Runtime.call(__MODULE__, :inspect_history, [], []) end def inspect_history(opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :inspect_history, [], opts) end def inspect_history(n) do SnakeBridge.Runtime.call(__MODULE__, :inspect_history, [n], []) end def inspect_history(n, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :inspect_history, [n], opts) end @doc """ Load saved DSPy model. This method is used to load a saved DSPy model with `save_program=True`, i.e., the model is saved with cloudpickle. ## Parameters - `path` - Path to the saved model. (type: `String.t()`) - `allow_pickle` - Whether to allow loading the model with pickle. This is dangerous and should only be used if you are sure you trust the source of the model. (type: `boolean()`) ## Returns - `term()` """ @spec load(String.t()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec load(String.t(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec load(String.t(), boolean()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec load(String.t(), boolean(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def load(path) do SnakeBridge.Runtime.call(__MODULE__, :load, [path], []) end def load(path, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :load, [path], opts) end def load(path, allow_pickle) do SnakeBridge.Runtime.call(__MODULE__, :load, [path, allow_pickle], []) end def load(path, allow_pickle, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :load, [path, allow_pickle], opts) end @doc """ Load the settings from a file using cloudpickle. ## Parameters - `path` - The file path to load the settings from. ## Returns - `%{optional(String.t()) => term()}` """ @spec load_settings(String.t(), keyword()) :: {:ok, %{optional(String.t()) => term()}} | {:error, Snakepit.Error.t()} def load_settings(path, opts \\ []) do SnakeBridge.Runtime.call(__MODULE__, :load_settings, [path], opts) end @doc """ Returns the most common completion for the target field (or the last field) in the signature. When normalize returns None, that completion is ignored. In case of a tie, earlier completion are prioritized. ## Parameters - `prediction_or_completions` (term()) - `normalize` (term() default: ) - `field` (term() default: None) ## Returns - `term()` """ @spec majority(term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec majority(term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec majority(term(), term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec majority(term(), term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec majority(term(), term(), term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec majority(term(), term(), term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def majority(prediction_or_completions) do SnakeBridge.Runtime.call(__MODULE__, :majority, [prediction_or_completions], []) end def majority(prediction_or_completions, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :majority, [prediction_or_completions], opts) end def majority(prediction_or_completions, normalize) do SnakeBridge.Runtime.call(__MODULE__, :majority, [prediction_or_completions, normalize], []) end def majority(prediction_or_completions, normalize, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :majority, [prediction_or_completions, normalize], opts) end def majority(prediction_or_completions, normalize, field) do SnakeBridge.Runtime.call( __MODULE__, :majority, [prediction_or_completions, normalize, field], [] ) end def majority(prediction_or_completions, normalize, field, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :majority, [prediction_or_completions, normalize, field], opts ) end @doc """ Create a new Signature subclass with the specified fields and instructions. ## Parameters - `signature` - Either a string in the format "input1, input2 -> output1, output2" or a dictionary mapping field names to tuples of (type, FieldInfo). - `instructions` - Optional string containing instructions/prompt for the signature. If not provided, defaults to a basic description of inputs and outputs. - `signature_name` - Optional string to name the generated Signature subclass. Defaults to "StringSignature". - `custom_types` - Optional dictionary mapping type names to their actual type objects. Useful for resolving custom types that aren't built-ins or in the typing module. ## Returns - `term()` """ @spec make_signature(term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec make_signature(term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec make_signature(term(), term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec make_signature(term(), term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec make_signature(term(), term(), String.t()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec make_signature(term(), term(), String.t(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec make_signature(term(), term(), String.t(), term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec make_signature(term(), term(), String.t(), term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def make_signature(signature) do SnakeBridge.Runtime.call(__MODULE__, :make_signature, [signature], []) end def make_signature(signature, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :make_signature, [signature], opts) end def make_signature(signature, instructions) do SnakeBridge.Runtime.call(__MODULE__, :make_signature, [signature, instructions], []) end def make_signature(signature, instructions, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :make_signature, [signature, instructions], opts) end def make_signature(signature, instructions, signature_name) do SnakeBridge.Runtime.call( __MODULE__, :make_signature, [signature, instructions, signature_name], [] ) end def make_signature(signature, instructions, signature_name, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :make_signature, [signature, instructions, signature_name], opts ) end def make_signature(signature, instructions, signature_name, custom_types) do SnakeBridge.Runtime.call( __MODULE__, :make_signature, [signature, instructions, signature_name, custom_types], [] ) end def make_signature(signature, instructions, signature_name, custom_types, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :make_signature, [signature, instructions, signature_name, custom_types], opts ) end @doc """ Python binding for `dspy.OutputField`. ## Parameters - `kwargs` (term()) ## Returns - `term()` """ @spec output_field(keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def output_field(opts \\ []) do SnakeBridge.Runtime.call(__MODULE__, "OutputField", [], opts) end @doc """ A singleton class for DSPy configuration settings. Thread-safe global configuration. - 'configure' can be called by only one 'owner' thread (the first thread that calls it). - Other threads see the configured global values from 'main_thread_config'. - 'context' sets thread-local overrides. These overrides propagate to threads spawned inside that context block, when (and only when!) using a ParallelExecutor that copies overrides. 1. Only one unique thread (which can be any thread!) can call dspy.configure. 2. It affects a global state, visible to all. As a result, user threads work, but they shouldn't be mixed with concurrent changes to dspy.configure from the "main" thread. (TODO: In the future, add warnings: if there are near-in-time user-thread reads followed by .configure calls.) 3. Any thread can use dspy.context. It propagates to child threads created with DSPy primitives: Parallel, asyncify, etc. ## Returns - `term()` """ @spec settings() :: {:ok, term()} | {:error, Snakepit.Error.t()} def settings() do SnakeBridge.Runtime.get_module_attr(__MODULE__, :settings) end @doc """ Wrap a DSPy program so that it streams its outputs incrementally, rather than returning them all at once. It also provides status messages to the user to indicate the progress of the program, and users can implement their own status message provider to customize the status messages and what module to generate status messages for. ## Parameters - `program` - The DSPy program to wrap with streaming functionality. - `status_message_provider` - A custom status message generator to use instead of the default one. Users can implement their own status message generator to customize the status messages and what module to generate status messages for. - `stream_listeners` - A list of stream listeners to capture the streaming output of specific fields of sub predicts in the program. When provided, only the target fields in the target predict will be streamed to the user. - `include_final_prediction_in_output_stream` - Whether to include the final prediction in the output stream, only useful when `stream_listeners` is provided. If `False`, the final prediction will not be included in the output stream. When the program hit cache, or no listeners captured anything, the final prediction will still be included in the output stream even if this is `False`. - `is_async_program` - Whether the program is async. If `False`, the program will be wrapped with `asyncify`, otherwise the program will be called with `acall`. - `async_streaming` - Whether to return an async generator or a sync generator. If `False`, the streaming will be converted to a sync generator. ## Returns - `term()` """ @spec streamify(term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec streamify(term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec streamify(term(), term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec streamify(term(), term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec streamify(term(), term(), term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec streamify(term(), term(), term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec streamify(term(), term(), term(), boolean()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec streamify(term(), term(), term(), boolean(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec streamify(term(), term(), term(), boolean(), boolean()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec streamify(term(), term(), term(), boolean(), boolean(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec streamify(term(), term(), term(), boolean(), boolean(), boolean()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec streamify(term(), term(), term(), boolean(), boolean(), boolean(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def streamify(program) do SnakeBridge.Runtime.call(__MODULE__, :streamify, [program], []) end def streamify(program, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :streamify, [program], opts) end def streamify(program, status_message_provider) do SnakeBridge.Runtime.call(__MODULE__, :streamify, [program, status_message_provider], []) end def streamify(program, status_message_provider, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :streamify, [program, status_message_provider], opts) end def streamify(program, status_message_provider, stream_listeners) do SnakeBridge.Runtime.call( __MODULE__, :streamify, [program, status_message_provider, stream_listeners], [] ) end def streamify(program, status_message_provider, stream_listeners, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :streamify, [program, status_message_provider, stream_listeners], opts ) end def streamify( program, status_message_provider, stream_listeners, include_final_prediction_in_output_stream ) do SnakeBridge.Runtime.call( __MODULE__, :streamify, [ program, status_message_provider, stream_listeners, include_final_prediction_in_output_stream ], [] ) end def streamify( program, status_message_provider, stream_listeners, include_final_prediction_in_output_stream, opts ) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :streamify, [ program, status_message_provider, stream_listeners, include_final_prediction_in_output_stream ], opts ) end def streamify( program, status_message_provider, stream_listeners, include_final_prediction_in_output_stream, is_async_program ) do SnakeBridge.Runtime.call( __MODULE__, :streamify, [ program, status_message_provider, stream_listeners, include_final_prediction_in_output_stream, is_async_program ], [] ) end def streamify( program, status_message_provider, stream_listeners, include_final_prediction_in_output_stream, is_async_program, opts ) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :streamify, [ program, status_message_provider, stream_listeners, include_final_prediction_in_output_stream, is_async_program ], opts ) end def streamify( program, status_message_provider, stream_listeners, include_final_prediction_in_output_stream, is_async_program, async_streaming ) do SnakeBridge.Runtime.call( __MODULE__, :streamify, [ program, status_message_provider, stream_listeners, include_final_prediction_in_output_stream, is_async_program, async_streaming ], [] ) end def streamify( program, status_message_provider, stream_listeners, include_final_prediction_in_output_stream, is_async_program, async_streaming, opts ) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call( __MODULE__, :streamify, [ program, status_message_provider, stream_listeners, include_final_prediction_in_output_stream, is_async_program, async_streaming ], opts ) end @doc """ Convert an async DSPy module to a sync program. There are two modes of this function: - `in_place=True` (recommended): Modify the module in place. But this may not work if you already have a `forward` method which does different things from `aforward`. - `in_place=False`: Return a wrapper module. This changes the module's architecture, but it's more robust. ## Parameters - `program` - The async program to convert, must have an `aforward` method implemented. - `in_place` - If True, modify the module in place. Otherwise, return a wrapper module. ## Returns - `term()` """ @spec syncify(term()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec syncify(term(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec syncify(term(), boolean()) :: {:ok, term()} | {:error, Snakepit.Error.t()} @spec syncify(term(), boolean(), keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def syncify(program) do SnakeBridge.Runtime.call(__MODULE__, :syncify, [program], []) end def syncify(program, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :syncify, [program], opts) end def syncify(program, in_place) do SnakeBridge.Runtime.call(__MODULE__, :syncify, [program, in_place], []) end def syncify(program, in_place, opts) when is_list(opts) and (opts == [] or (is_tuple(hd(opts)) and tuple_size(hd(opts)) == 2 and is_atom(elem(hd(opts), 0)))) do SnakeBridge.Runtime.call(__MODULE__, :syncify, [program, in_place], opts) end @doc """ Context manager for tracking LM usage. ## Returns - `term()` """ @spec track_usage(keyword()) :: {:ok, term()} | {:error, Snakepit.Error.t()} def track_usage(opts \\ []) do SnakeBridge.Runtime.call(__MODULE__, :track_usage, [], opts) end @doc false def __functions__ do [ {:enable_logging, 0, __MODULE__, "Enables the `DSPyLoggingStream` used by event logging APIs throughout DSPy"}, {:track_usage, 0, __MODULE__, "Context manager for tracking LM usage."}, {:answer_exact_match, 2, __MODULE__, "Evaluate exact match or F1-thresholded match for an example/prediction pair."}, {:ensure_signature, 1, __MODULE__, ""}, {:bootstrap_trace_data, 2, __MODULE__, ""}, {:streamify, 1, __MODULE__, "Wrap a DSPy program so that it streams its outputs incrementally, rather than returning them"}, {:dspy_cache, 0, __MODULE__, "DSPy Cache"}, {:disable_litellm_logging, 0, __MODULE__, ""}, {:disable_logging, 0, __MODULE__, "Disables the `DSPyLoggingStream` used by event logging APIs throughout DSPy"}, {:configure_cache, 0, __MODULE__, "Configure the cache for DSPy."}, {:streaming_response, 1, __MODULE__, "Convert a DSPy program output stream to an OpenAI-compatible output stream that can be"}, {:bootstrap_trace_data, 2, __MODULE__, ""}, {:answer_passage_match, 2, __MODULE__, "Return True if any passage in `pred.context` contains the answer(s)."}, {:configure, 0, __MODULE__, ""}, {:download, 1, __MODULE__, ""}, {:infer_prefix, 1, __MODULE__, "Infer a prefix from an attribute name by converting it to a human-readable format."}, {:asyncify, 1, __MODULE__, "Wraps a DSPy program so that it can be called asynchronously. This is useful for running a"}, {:em, 2, __MODULE__, "Compute the Exact Match (EM) metric between a prediction and reference answers."}, {:majority, 1, __MODULE__, "Returns the most common completion for the target field (or the last field) in the signature."}, {:infer_prefix, 1, __MODULE__, "Infer a prefix from an attribute name by converting it to a human-readable format."}, {:dummy_rm, 0, __MODULE__, ""}, {:with_callbacks, 1, __MODULE__, "Decorator to add callback functionality to instance methods."}, {:configure_dspy_loggers, 1, __MODULE__, ""}, {:streamify, 1, __MODULE__, "Wrap a DSPy program so that it streams its outputs incrementally, rather than returning them"}, {:ensure_signature, 1, __MODULE__, ""}, {:majority, 1, __MODULE__, "Returns the most common completion for the target field (or the last field) in the signature."}, {:disable_litellm_logging, 0, __MODULE__, ""}, {:inspect_history, 0, __MODULE__, "The global history shared across all LMs."}, {:output_field, 0, __MODULE__, ""}, {:settings, 0, __MODULE__, "A singleton class for DSPy configuration settings."}, {:cache, 0, __MODULE__, "DSPy Cache"}, {:output_field, 0, __MODULE__, ""}, {:load, 1, __MODULE__, "Load saved DSPy model."}, {:configure_cache, 0, __MODULE__, "Configure the cache for DSPy."}, {:normalize_text, 1, __MODULE__, "Normalize text for string and token comparisons."}, {:load_settings, 1, __MODULE__, "Load the settings from a file using cloudpickle."}, {:make_signature, 1, __MODULE__, "Create a new Signature subclass with the specified fields and instructions."}, {:enable_litellm_logging, 0, __MODULE__, ""}, {:context, 0, __MODULE__, "Context manager for temporary configuration changes at the thread level."}, {:apply_sync_streaming, 1, __MODULE__, "Convert the async streaming generator to a sync generator."}, {:make_signature, 1, __MODULE__, "Create a new Signature subclass with the specified fields and instructions."}, {:experimental, 0, __MODULE__, "Decorator / decorator creator for marking APIs experimental in the docstring."}, {:syncify, 1, __MODULE__, "Convert an async DSPy module to a sync program."}, {:input_field, 0, __MODULE__, ""}, {:enable_litellm_logging, 0, __MODULE__, ""}, {:pretty_print_history, 1, __MODULE__, "Prints the last n prompts and their completions."}, {:input_field, 0, __MODULE__, ""}, {:inspect_history, 0, __MODULE__, "The global history shared across all LMs."} ] end @doc false def __classes__ do [ {Dspy.Prediction, "A prediction object that contains the output of a DSPy module.\n\nPrediction inherits from Example.\n\nTo allow feedback-augmented scores, Prediction supports comparison operations\n(<, >, <=, >=) for Predictions with a `score` field. The comparison operations\ncompare the 'score' values as floats. For equality comparison, Predictions are equal\nif their underlying data stores are equal (inherited from Example).\n\nArithmetic operations (+, /, etc.) are also supported for Predictions with a 'score'\nfield, operating on the score value."}, {Dspy.Evaluate.CompleteAndGrounded, ""}, {Dspy.OldOutputField, "A more ergonomic datatype that infers prefix and desc if omitted."}, {Dspy.BootstrapFewShotWithRandomSearch, ""}, {Dspy.Primitives.ReplTypes.REPLHistory, "Container for REPL interaction history.\n\nImmutable: append() returns a new instance with the entry added."}, {Dspy.Predict.Parallel, ""}, {Dspy.Streaming.StreamListener, "Class that listens to the stream to capture the streeaming of a specific output field of a predictor."}, {Dspy.CodeInterpreter, "Protocol for code execution environments (interpreters).\n\nImplementations must provide:\n- start(): Initialize the interpreter (optional, can be lazy)\n- execute(): Run code and return results\n- shutdown(): Clean up resources\n\nThe interpreter maintains state across execute() calls within a session,\nallowing variables defined in one call to be used in subsequent calls.\n\nLifecycle:\n 1. Create instance (config only, no resources allocated)\n 2. start() - Initialize interpreter (explicit) or let execute() do it (lazy)\n 3. execute() - Run code (can be called many times)\n 4. shutdown() - Release resources\n\nExample implementations:\n - LocalInterpreter: Deno/Pyodide WASM interpreter (local)\n - MockInterpreter: Scriptable responses for testing\n\nPooling:\n For interpreter pooling, call start() to pre-warm instances, then\n distribute execute() calls across the pool."}, {Dspy.BootstrapFewShot, ""}, {Dspy.Adapters.Types.Type, "Base class to support creating custom types for DSPy signatures.\n\nThis is the parent class of DSPy custom types, e.g, dspy.Image. Subclasses must implement the `format` method to\nreturn a list of dictionaries (same as the Array of content parts in the OpenAI API user message's content field).\n\nExample:\n\n ```python\n class Image(Type):\n url: str\n\n def format(self) -> list[dict[str, Any]]:\n return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n ```"}, {Dspy.EvaluateClass, "DSPy Evaluate class.\n\nThis class is used to evaluate the performance of a DSPy program. Users need to provide a evaluation dataset and\na metric function in order to use this class. This class supports parallel evaluation on the provided dataset."}, {Dspy.Teleprompt.BootstrapFewShot, ""}, {Dspy.Predict.CodeAct, "CodeAct is a module that utilizes the Code Interpreter and predefined tools to solve the problem."}, {Dspy.Clients.TrainingJob, "Represents the result of an asynchronous computation."}, {Dspy.Embeddings, ""}, {Dspy.Retrievers.Embeddings, ""}, {Dspy.AvatarOptimizer, ""}, {Dspy.Teleprompt.GEPA, "Experimental: This class may change or be removed in a future release without warning (introduced in v3.0.0).\n\n\nGEPA is an evolutionary optimizer, which uses reflection to evolve text components\nof complex systems. GEPA is proposed in the paper [GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning](https://arxiv.org/abs/2507.19457).\nThe GEPA optimization engine is provided by the `gepa` package, available from [https://github.com/gepa-ai/gepa](https://github.com/gepa-ai/gepa).\n\nGEPA captures full traces of the DSPy module's execution, identifies the parts of the trace\ncorresponding to a specific predictor, and reflects on the behaviour of the predictor to\npropose a new instruction for the predictor. GEPA allows users to provide textual feedback\nto the optimizer, which is used to guide the evolution of the predictor. The textual feedback\ncan be provided at the granularity of individual predictors, or at the level of the entire system's\nexecution.\n\nTo provide feedback to the GEPA optimizer, implement a metric as follows:\n```\ndef metric(\n gold: Example,\n pred: Prediction,\n trace: Optional[DSPyTrace] = None,\n pred_name: Optional[str] = None,\n pred_trace: Optional[DSPyTrace] = None,\n) -> float | ScoreWithFeedback:\n \"\"\"\n This function is called with the following arguments:\n - gold: The gold example.\n - pred: The predicted output.\n - trace: Optional. The trace of the program's execution.\n - pred_name: Optional. The name of the target predictor currently being optimized by GEPA, for which\n the feedback is being requested.\n - pred_trace: Optional. The trace of the target predictor's execution GEPA is seeking feedback for.\n\n Note the `pred_name` and `pred_trace` arguments. During optimization, GEPA will call the metric to obtain\n feedback for individual predictors being optimized. GEPA provides the name of the predictor in `pred_name`\n and the sub-trace (of the trace) corresponding to the predictor in `pred_trace`.\n If available at the predictor level, the metric should return {'score': float, 'feedback': str} corresponding\n to the predictor.\n If not available at the predictor level, the metric can also return a text feedback at the program level\n (using just the gold, pred and trace).\n If no feedback is returned, GEPA will use a simple text feedback consisting of just the score:\n f\"This trajectory got a score of {score}.\"\n \"\"\"\n ...\n```\n\nGEPA can also be used as a batch inference-time search strategy, by passing `valset=trainset, track_stats=True, track_best_outputs=True`, and using the\n`detailed_results` attribute of the optimized program (returned by `compile`) to get the Pareto frontier of the batch. `optimized_program.detailed_results.best_outputs_valset` will contain the best outputs for each task in the batch.\n\nExample:\n```\ngepa = GEPA(metric=metric, track_stats=True)\nbatch_of_tasks = [dspy.Example(...) for task in tasks]\nnew_prog = gepa.compile(student, trainset=trainset, valset=batch_of_tasks)\npareto_frontier = new_prog.detailed_results.val_aggregate_scores\n# pareto_frontier is a list of scores, one for each task in the batch.\n```\n\nArgs:\n metric: The metric function to use for feedback and evaluation.\n auto: The auto budget to use for the run. Options: \"light\", \"medium\", \"heavy\".\n max_full_evals: The maximum number of full evaluations to perform.\n max_metric_calls: The maximum number of metric calls to perform.\n reflection_minibatch_size: The number of examples to use for reflection in a single GEPA step. Default is 3.\n candidate_selection_strategy: The strategy to use for candidate selection. Default is \"pareto\",\n which stochastically selects candidates from the Pareto frontier of all validation scores.\n Options: \"pareto\", \"current_best\".\n reflection_lm: The language model to use for reflection. Required parameter. GEPA benefits from\n a strong reflection model. Consider using `dspy.LM(model='gpt-5', temperature=1.0, max_tokens=32000)`\n for optimal performance.\n skip_perfect_score: Whether to skip examples with perfect scores during reflection. Default is True.\n instruction_proposer: Optional custom instruction proposer implementing GEPA's ProposalFn protocol.\n **Default: None (recommended for most users)** - Uses GEPA's proven instruction proposer from\n the [GEPA library](https://github.com/gepa-ai/gepa), which implements the\n [`ProposalFn`](https://github.com/gepa-ai/gepa/blob/main/src/gepa/core/adapter.py). This default\n proposer is highly capable and was validated across diverse experiments reported in the GEPA\n paper and tutorials.\n\n See documentation on custom instruction proposers\n [here](https://dspy.ai/api/optimizers/GEPA/GEPA_Advanced/#custom-instruction-proposers).\n\n **Advanced Feature**: Only needed for specialized scenarios:\n - **Multi-modal handling**: Processing dspy.Image inputs alongside textual information\n - **Nuanced control over constraints**: Fine-grained control over instruction length, format,\n and structural requirements beyond standard feedback mechanisms\n - **Domain-specific knowledge injection**: Specialized terminology or context that cannot be\n provided through feedback_func alone\n - **Provider-specific prompting**: Optimizations for specific LLM providers (OpenAI, Anthropic)\n with unique formatting preferences\n - **Coupled component updates**: Coordinated updates of multiple components together rather\n than independent optimization\n - **External knowledge integration**: Runtime access to databases, APIs, or knowledge bases\n\n The default proposer handles the vast majority of use cases effectively. Use\n MultiModalInstructionProposer() from dspy.teleprompt.gepa.instruction_proposal for visual\n content or implement custom ProposalFn for highly specialized requirements.\n\n Note: When both instruction_proposer and reflection_lm are set, the instruction_proposer is called\n in the reflection_lm context. However, reflection_lm is optional when using a custom instruction_proposer.\n Custom instruction proposers can invoke their own LLMs if needed.\n component_selector: Custom component selector implementing the [ReflectionComponentSelector](https://github.com/gepa-ai/gepa/blob/main/src/gepa/proposer/reflective_mutation/base.py) protocol,\n or a string specifying a built-in selector strategy. Controls which components (predictors) are selected\n for optimization at each iteration. Defaults to 'round_robin' strategy which cycles through components\n one at a time. Available string options: 'round_robin' (cycles through components sequentially),\n 'all' (selects all components for simultaneous optimization). Custom selectors can implement strategies\n using LLM-driven selection logic based on optimization state and trajectories.\n See [gepa component selectors](https://github.com/gepa-ai/gepa/blob/main/src/gepa/strategies/component_selector.py)\n for available built-in selectors and the ReflectionComponentSelector protocol for implementing custom selectors.\n add_format_failure_as_feedback: Whether to add format failures as feedback. Default is False.\n use_merge: Whether to use merge-based optimization. Default is True.\n max_merge_invocations: The maximum number of merge invocations to perform. Default is 5.\n num_threads: The number of threads to use for evaluation with `Evaluate`. Optional.\n failure_score: The score to assign to failed examples. Default is 0.0.\n perfect_score: The maximum score achievable by the metric. Default is 1.0. Used by GEPA\n to determine if all examples in a minibatch are perfect.\n log_dir: The directory to save the logs. GEPA saves elaborate logs, along with all candidate\n programs, in this directory. Running G"}, {Dspy.Streaming.StatusMessageProvider, "Provides customizable status message streaming for DSPy programs.\n\nThis class serves as a base for creating custom status message providers. Users can subclass\nand override its methods to define specific status messages for different stages of program execution,\neach method must return a string.\n\nExample:\n```python\nclass MyStatusMessageProvider(StatusMessageProvider):\n def lm_start_status_message(self, instance, inputs):\n return f\"Calling LM with inputs {inputs}...\"\n\n def module_end_status_message(self, outputs):\n return f\"Module finished with output: {outputs}!\"\n\nprogram = dspy.streamify(dspy.Predict(\"q->a\"), status_message_provider=MyStatusMessageProvider())\n```"}, {Dspy.GEPA, "Experimental: This class may change or be removed in a future release without warning (introduced in v3.0.0).\n\n\nGEPA is an evolutionary optimizer, which uses reflection to evolve text components\nof complex systems. GEPA is proposed in the paper [GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning](https://arxiv.org/abs/2507.19457).\nThe GEPA optimization engine is provided by the `gepa` package, available from [https://github.com/gepa-ai/gepa](https://github.com/gepa-ai/gepa).\n\nGEPA captures full traces of the DSPy module's execution, identifies the parts of the trace\ncorresponding to a specific predictor, and reflects on the behaviour of the predictor to\npropose a new instruction for the predictor. GEPA allows users to provide textual feedback\nto the optimizer, which is used to guide the evolution of the predictor. The textual feedback\ncan be provided at the granularity of individual predictors, or at the level of the entire system's\nexecution.\n\nTo provide feedback to the GEPA optimizer, implement a metric as follows:\n```\ndef metric(\n gold: Example,\n pred: Prediction,\n trace: Optional[DSPyTrace] = None,\n pred_name: Optional[str] = None,\n pred_trace: Optional[DSPyTrace] = None,\n) -> float | ScoreWithFeedback:\n \"\"\"\n This function is called with the following arguments:\n - gold: The gold example.\n - pred: The predicted output.\n - trace: Optional. The trace of the program's execution.\n - pred_name: Optional. The name of the target predictor currently being optimized by GEPA, for which\n the feedback is being requested.\n - pred_trace: Optional. The trace of the target predictor's execution GEPA is seeking feedback for.\n\n Note the `pred_name` and `pred_trace` arguments. During optimization, GEPA will call the metric to obtain\n feedback for individual predictors being optimized. GEPA provides the name of the predictor in `pred_name`\n and the sub-trace (of the trace) corresponding to the predictor in `pred_trace`.\n If available at the predictor level, the metric should return {'score': float, 'feedback': str} corresponding\n to the predictor.\n If not available at the predictor level, the metric can also return a text feedback at the program level\n (using just the gold, pred and trace).\n If no feedback is returned, GEPA will use a simple text feedback consisting of just the score:\n f\"This trajectory got a score of {score}.\"\n \"\"\"\n ...\n```\n\nGEPA can also be used as a batch inference-time search strategy, by passing `valset=trainset, track_stats=True, track_best_outputs=True`, and using the\n`detailed_results` attribute of the optimized program (returned by `compile`) to get the Pareto frontier of the batch. `optimized_program.detailed_results.best_outputs_valset` will contain the best outputs for each task in the batch.\n\nExample:\n```\ngepa = GEPA(metric=metric, track_stats=True)\nbatch_of_tasks = [dspy.Example(...) for task in tasks]\nnew_prog = gepa.compile(student, trainset=trainset, valset=batch_of_tasks)\npareto_frontier = new_prog.detailed_results.val_aggregate_scores\n# pareto_frontier is a list of scores, one for each task in the batch.\n```\n\nArgs:\n metric: The metric function to use for feedback and evaluation.\n auto: The auto budget to use for the run. Options: \"light\", \"medium\", \"heavy\".\n max_full_evals: The maximum number of full evaluations to perform.\n max_metric_calls: The maximum number of metric calls to perform.\n reflection_minibatch_size: The number of examples to use for reflection in a single GEPA step. Default is 3.\n candidate_selection_strategy: The strategy to use for candidate selection. Default is \"pareto\",\n which stochastically selects candidates from the Pareto frontier of all validation scores.\n Options: \"pareto\", \"current_best\".\n reflection_lm: The language model to use for reflection. Required parameter. GEPA benefits from\n a strong reflection model. Consider using `dspy.LM(model='gpt-5', temperature=1.0, max_tokens=32000)`\n for optimal performance.\n skip_perfect_score: Whether to skip examples with perfect scores during reflection. Default is True.\n instruction_proposer: Optional custom instruction proposer implementing GEPA's ProposalFn protocol.\n **Default: None (recommended for most users)** - Uses GEPA's proven instruction proposer from\n the [GEPA library](https://github.com/gepa-ai/gepa), which implements the\n [`ProposalFn`](https://github.com/gepa-ai/gepa/blob/main/src/gepa/core/adapter.py). This default\n proposer is highly capable and was validated across diverse experiments reported in the GEPA\n paper and tutorials.\n\n See documentation on custom instruction proposers\n [here](https://dspy.ai/api/optimizers/GEPA/GEPA_Advanced/#custom-instruction-proposers).\n\n **Advanced Feature**: Only needed for specialized scenarios:\n - **Multi-modal handling**: Processing dspy.Image inputs alongside textual information\n - **Nuanced control over constraints**: Fine-grained control over instruction length, format,\n and structural requirements beyond standard feedback mechanisms\n - **Domain-specific knowledge injection**: Specialized terminology or context that cannot be\n provided through feedback_func alone\n - **Provider-specific prompting**: Optimizations for specific LLM providers (OpenAI, Anthropic)\n with unique formatting preferences\n - **Coupled component updates**: Coordinated updates of multiple components together rather\n than independent optimization\n - **External knowledge integration**: Runtime access to databases, APIs, or knowledge bases\n\n The default proposer handles the vast majority of use cases effectively. Use\n MultiModalInstructionProposer() from dspy.teleprompt.gepa.instruction_proposal for visual\n content or implement custom ProposalFn for highly specialized requirements.\n\n Note: When both instruction_proposer and reflection_lm are set, the instruction_proposer is called\n in the reflection_lm context. However, reflection_lm is optional when using a custom instruction_proposer.\n Custom instruction proposers can invoke their own LLMs if needed.\n component_selector: Custom component selector implementing the [ReflectionComponentSelector](https://github.com/gepa-ai/gepa/blob/main/src/gepa/proposer/reflective_mutation/base.py) protocol,\n or a string specifying a built-in selector strategy. Controls which components (predictors) are selected\n for optimization at each iteration. Defaults to 'round_robin' strategy which cycles through components\n one at a time. Available string options: 'round_robin' (cycles through components sequentially),\n 'all' (selects all components for simultaneous optimization). Custom selectors can implement strategies\n using LLM-driven selection logic based on optimization state and trajectories.\n See [gepa component selectors](https://github.com/gepa-ai/gepa/blob/main/src/gepa/strategies/component_selector.py)\n for available built-in selectors and the ReflectionComponentSelector protocol for implementing custom selectors.\n add_format_failure_as_feedback: Whether to add format failures as feedback. Default is False.\n use_merge: Whether to use merge-based optimization. Default is True.\n max_merge_invocations: The maximum number of merge invocations to perform. Default is 5.\n num_threads: The number of threads to use for evaluation with `Evaluate`. Optional.\n failure_score: The score to assign to failed examples. Default is 0.0.\n perfect_score: The maximum score achievable by the metric. Default is 1.0. Used by GEPA\n to determine if all examples in a minibatch are perfect.\n log_dir: The directory to save the logs. GEPA saves elaborate logs, along with all candidate\n programs, in this directory. Running G"}, {Dspy.Adapters.Adapter, "Base Adapter class.\n\nThe Adapter serves as the interface layer between DSPy module/signature and Language Models (LMs). It handles the\ncomplete transformation pipeline from DSPy inputs to LM calls and back to structured outputs.\n\nKey responsibilities:\n - Transform user inputs and signatures into properly formatted LM prompts, which also instructs the LM to format\n the response in a specific format.\n - Parse LM outputs into dictionaries matching the signature's output fields.\n - Enable/disable native LM features (function calling, citations, etc.) based on configuration.\n - Handle conversation history, few-shot examples, and custom type processing.\n\nThe adapter pattern allows DSPy to work with different LM interfaces while maintaining a consistent programming\nmodel for users."}, {Dspy.Teleprompt.LabeledFewShot, ""}, {Dspy.Signatures.OldInputField, "A more ergonomic datatype that infers prefix and desc if omitted."}, {Dspy.Adapters.Types.Code, "Code type in DSPy.\n\nThis type is useful for code generation and code analysis.\n\nExample 1: dspy.Code as output type in code generation:\n\n```python\nimport dspy\n\ndspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\n\nclass CodeGeneration(dspy.Signature):\n '''Generate python code to answer the question.'''\n\n question: str = dspy.InputField(description=\"The question to answer\")\n code: dspy.Code[\"java\"] = dspy.OutputField(description=\"The code to execute\")\n\n\npredict = dspy.Predict(CodeGeneration)\n\nresult = predict(question=\"Given an array, find if any of the two numbers sum up to 10\")\nprint(result.code)\n```\n\nExample 2: dspy.Code as input type in code analysis:\n\n```python\nimport dspy\nimport inspect\n\ndspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\nclass CodeAnalysis(dspy.Signature):\n '''Analyze the time complexity of the function.'''\n\n code: dspy.Code[\"python\"] = dspy.InputField(description=\"The function to analyze\")\n result: str = dspy.OutputField(description=\"The time complexity of the function\")\n\n\npredict = dspy.Predict(CodeAnalysis)\n\n\ndef sleepsort(x):\n import time\n\n for i in x:\n time.sleep(i)\n print(i)\n\nresult = predict(code=inspect.getsource(sleepsort))\nprint(result.result)\n```"}, {Dspy.Module, ""}, {Dspy.Adapters.Code, "Code type in DSPy.\n\nThis type is useful for code generation and code analysis.\n\nExample 1: dspy.Code as output type in code generation:\n\n```python\nimport dspy\n\ndspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\n\nclass CodeGeneration(dspy.Signature):\n '''Generate python code to answer the question.'''\n\n question: str = dspy.InputField(description=\"The question to answer\")\n code: dspy.Code[\"java\"] = dspy.OutputField(description=\"The code to execute\")\n\n\npredict = dspy.Predict(CodeGeneration)\n\nresult = predict(question=\"Given an array, find if any of the two numbers sum up to 10\")\nprint(result.code)\n```\n\nExample 2: dspy.Code as input type in code analysis:\n\n```python\nimport dspy\nimport inspect\n\ndspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\nclass CodeAnalysis(dspy.Signature):\n '''Analyze the time complexity of the function.'''\n\n code: dspy.Code[\"python\"] = dspy.InputField(description=\"The function to analyze\")\n result: str = dspy.OutputField(description=\"The time complexity of the function\")\n\n\npredict = dspy.Predict(CodeAnalysis)\n\n\ndef sleepsort(x):\n import time\n\n for i in x:\n time.sleep(i)\n print(i)\n\nresult = predict(code=inspect.getsource(sleepsort))\nprint(result.result)\n```"}, {Dspy.Adapters.Reasoning, "Reasoning type in DSPy.\n\nThis type is useful when you want the DSPy output to include the reasoning of the LM. We build this type so that\nDSPy can support the reasoning model and non-reasoning model with the same code.\n\nThis is a str-like type, you can convert a string directly to a Reasoning object, and from DSPy adapters'\nperspective, `Reasoning` is treated as a string."}, {Dspy.ColBERTv2, "Wrapper for the ColBERTv2 Retrieval."}, {Dspy.Datasets.Dataset, ""}, {Dspy.Primitives.PythonInterpreter, "Local interpreter for secure Python execution using Deno and Pyodide.\n\nImplements the Interpreter protocol for secure code execution in a\nWASM-based sandbox. Code runs in an isolated Pyodide environment with\nno access to the host filesystem, network, or environment by default.\n\nPrerequisites:\n Deno must be installed: https://docs.deno.com/runtime/getting_started/installation/\n\nExample:\n ```python\n # Basic execution\n with PythonInterpreter() as interp:\n result = interp(\"print(1 + 2)\") # Returns \"3\"\n\n # With host-side tools\n def my_tool(question: str) -> str:\n return \"answer\"\n\n with PythonInterpreter(tools={\"my_tool\": my_tool}) as interp:\n result = interp(\"print(my_tool(question='test'))\")\n ```"}, {Dspy.LM, "A language model supporting chat or text completion requests for use with DSPy modules."}, {Dspy.Evaluate.SemanticF1, ""}, {Dspy.Streaming.StatusMessage, "Dataclass that wraps a status message for status streaming."}, {Dspy.InferRules, ""}, {Dspy.Primitives.PythonInterpreter.FinalOutput, "Returned by interpreter.execute() when SUBMIT() is called.\n\nThis signals that the code execution loop should terminate and return\nthe contained output to the caller."}, {Dspy.Utils.StatusMessageProvider, "Provides customizable status message streaming for DSPy programs.\n\nThis class serves as a base for creating custom status message providers. Users can subclass\nand override its methods to define specific status messages for different stages of program execution,\neach method must return a string.\n\nExample:\n```python\nclass MyStatusMessageProvider(StatusMessageProvider):\n def lm_start_status_message(self, instance, inputs):\n return f\"Calling LM with inputs {inputs}...\"\n\n def module_end_status_message(self, outputs):\n return f\"Module finished with output: {outputs}!\"\n\nprogram = dspy.streamify(dspy.Predict(\"q->a\"), status_message_provider=MyStatusMessageProvider())\n```"}, {Dspy.TwoStepAdapter, "A two-stage adapter that:\n 1. Uses a simpler, more natural prompt for the main LM\n 2. Uses a smaller LM with chat adapter to extract structured data from the response of main LM\nThis adapter uses a common __call__ logic defined in base Adapter class.\nThis class is particularly useful when interacting with reasoning models as the main LM since reasoning models\nare known to struggle with structured outputs.\n\nExample:\n```\nimport dspy\nlm = dspy.LM(model=\"openai/o3-mini\", max_tokens=16000, temperature = 1.0)\nadapter = dspy.TwoStepAdapter(dspy.LM(\"openai/gpt-4o-mini\"))\ndspy.configure(lm=lm, adapter=adapter)\nprogram = dspy.ChainOfThought(\"question->answer\")\nresult = program(\"What is the capital of France?\")\nprint(result)\n```"}, {Dspy.Datasets.Colors, ""}, {Dspy.BestOfN, ""}, {Dspy.Clients.Provider, ""}, {Dspy.Reasoning, "Reasoning type in DSPy.\n\nThis type is useful when you want the DSPy output to include the reasoning of the LM. We build this type so that\nDSPy can support the reasoning model and non-reasoning model with the same code.\n\nThis is a str-like type, you can convert a string directly to a Reasoning object, and from DSPy adapters'\nperspective, `Reasoning` is treated as a string."}, {Dspy.Adapter, "Base Adapter class.\n\nThe Adapter serves as the interface layer between DSPy module/signature and Language Models (LMs). It handles the\ncomplete transformation pipeline from DSPy inputs to LM calls and back to structured outputs.\n\nKey responsibilities:\n - Transform user inputs and signatures into properly formatted LM prompts, which also instructs the LM to format\n the response in a specific format.\n - Parse LM outputs into dictionaries matching the signature's output fields.\n - Enable/disable native LM features (function calling, citations, etc.) based on configuration.\n - Handle conversation history, few-shot examples, and custom type processing.\n\nThe adapter pattern allows DSPy to work with different LM interfaces while maintaining a consistent programming\nmodel for users."}, {Dspy.ChainOfThought, ""}, {Dspy.BaseModule, ""}, {Dspy.MultiChainComparison, ""}, {Dspy.PythonInterpreter, "Local interpreter for secure Python execution using Deno and Pyodide.\n\nImplements the Interpreter protocol for secure code execution in a\nWASM-based sandbox. Code runs in an isolated Pyodide environment with\nno access to the host filesystem, network, or environment by default.\n\nPrerequisites:\n Deno must be installed: https://docs.deno.com/runtime/getting_started/installation/\n\nExample:\n ```python\n # Basic execution\n with PythonInterpreter() as interp:\n result = interp(\"print(1 + 2)\") # Returns \"3\"\n\n # With host-side tools\n def my_tool(question: str) -> str:\n return \"answer\"\n\n with PythonInterpreter(tools={\"my_tool\": my_tool}) as interp:\n result = interp(\"print(my_tool(question='test'))\")\n ```"}, {Dspy.Propose.GroundedProposer, "Helper class that provides a standard way to create an ABC using\ninheritance."}, {Dspy.SIMBA, "SIMBA (Stochastic Introspective Mini-Batch Ascent) optimizer for DSPy.\n\nSIMBA is a DSPy optimizer that uses the LLM to analyze its own performance and \ngenerate improvement rules. It samples mini-batches, identifies challenging examples \nwith high output variability, then either creates self-reflective rules or adds \nsuccessful examples as demonstrations.\n\nFor more details, see: https://dspy.ai/api/optimizers/SIMBA/"}, {Dspy.Experimental.Document, "Experimental: This class may change or be removed in a future release without warning (introduced in v3.0.4).\n\nA document type for providing content that can be cited by language models.\n\n This type represents documents that can be passed to language models for citation-enabled\n responses, particularly useful with Anthropic's Citations API. Documents include the content\n and metadata that helps the LM understand and reference the source material.\n\n Attributes:\n data: The text content of the document\n title: Optional title for the document (used in citations)\n media_type: MIME type of the document content (defaults to \"text/plain\")\n context: Optional context information about the document\n\n Example:\n ```python\n import dspy\n from dspy.signatures import Signature\n from dspy.experimental import Document, Citations\n\n class AnswerWithSources(Signature):\n '''Answer questions using provided documents with citations.'''\n documents: list[Document] = dspy.InputField()\n question: str = dspy.InputField()\n answer: str = dspy.OutputField()\n citations: Citations = dspy.OutputField()\n\n # Create documents\n docs = [\n Document(\n data=\"The Earth orbits the Sun in an elliptical path.\",\n title=\"Basic Astronomy Facts\"\n ),\n Document(\n data=\"Water boils at 100°C at standard atmospheric pressure.\",\n title=\"Physics Fundamentals\",\n )\n ]\n\n # Use with a citation-supporting model\n lm = dspy.LM(\"anthropic/claude-opus-4-1-20250805\")\n predictor = dspy.Predict(AnswerWithSources)\n result = predictor(documents=docs, question=\"What temperature does water boil?\", lm=lm)\n print(result.citations)\n ```\n "}, {Dspy.Predict.BestOfN, ""}, {Dspy.Utils.DummyVectorizer, "Simple vectorizer based on n-grams."}, {Dspy.Utils.BaseCallback, "A base class for defining callback handlers for DSPy components.\n\nTo use a callback, subclass this class and implement the desired handlers. Each handler\nwill be called at the appropriate time before/after the execution of the corresponding component. For example, if\nyou want to print a message before and after an LM is called, implement `the on_llm_start` and `on_lm_end` handler.\nUsers can set the callback globally using `dspy.configure` or locally by passing it to the component\nconstructor.\n\n\nExample 1: Set a global callback using `dspy.configure`.\n\n```\nimport dspy\nfrom dspy.utils.callback import BaseCallback\n\nclass LoggingCallback(BaseCallback):\n\n def on_lm_start(self, call_id, instance, inputs):\n print(f\"LM is called with inputs: {inputs}\")\n\n def on_lm_end(self, call_id, outputs, exception):\n print(f\"LM is finished with outputs: {outputs}\")\n\ndspy.configure(\n callbacks=[LoggingCallback()]\n)\n\ncot = dspy.ChainOfThought(\"question -> answer\")\ncot(question=\"What is the meaning of life?\")\n\n# > LM is called with inputs: {'question': 'What is the meaning of life?'}\n# > LM is finished with outputs: {'answer': '42'}\n```\n\nExample 2: Set a local callback by passing it to the component constructor.\n\n```\nlm_1 = dspy.LM(\"gpt-3.5-turbo\", callbacks=[LoggingCallback()])\nlm_1(question=\"What is the meaning of life?\")\n\n# > LM is called with inputs: {'question': 'What is the meaning of life?'}\n# > LM is finished with outputs: {'answer': '42'}\n\nlm_2 = dspy.LM(\"gpt-3.5-turbo\")\nlm_2(question=\"What is the meaning of life?\")\n# No logging here because only `lm_1` has the callback set.\n```"}, {Dspy.Clients.BaseLM, "Base class for handling LLM calls.\n\nMost users can directly use the `dspy.LM` class, which is a subclass of `BaseLM`. Users can also implement their\nown subclasses of `BaseLM` to support custom LLM providers and inject custom logic. To do so, simply override the\n`forward` method and make sure the return format is identical to the\n[OpenAI response format](https://platform.openai.com/docs/api-reference/responses/object).\n\nExample:\n\n```python\nfrom openai import OpenAI\n\nimport dspy\n\n\nclass MyLM(dspy.BaseLM):\n def forward(self, prompt, messages=None, **kwargs):\n client = OpenAI()\n return client.chat.completions.create(\n model=self.model,\n messages=messages or [{\"role\": \"user\", \"content\": prompt}],\n **self.kwargs,\n )\n\n\nlm = MyLM(model=\"gpt-4o-mini\")\ndspy.configure(lm=lm)\nprint(dspy.Predict(\"q->a\")(q=\"Why did the chicken cross the kitchen?\"))\n```"}, {Dspy.Predict.Tool, "Tool class.\n\nThis class is used to simplify the creation of tools for tool calling (function calling) in LLMs. Only supports\nfunctions for now."}, {Dspy.Primitives.FinalOutput, "Returned by interpreter.execute() when SUBMIT() is called.\n\nThis signals that the code execution loop should terminate and return\nthe contained output to the caller."}, {Dspy.Datasets.MATH, ""}, {Dspy.Adapters.Types.ToolCalls, "Base class to support creating custom types for DSPy signatures.\n\nThis is the parent class of DSPy custom types, e.g, dspy.Image. Subclasses must implement the `format` method to\nreturn a list of dictionaries (same as the Array of content parts in the OpenAI API user message's content field).\n\nExample:\n\n ```python\n class Image(Type):\n url: str\n\n def format(self) -> list[dict[str, Any]]:\n return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n ```"}, {Dspy.Signature, ""}, {Dspy.BetterTogether, ""}, {Dspy.Clients.Embedder, "DSPy embedding class.\n\nThe class for computing embeddings for text inputs. This class provides a unified interface for both:\n\n1. Hosted embedding models (e.g. OpenAI's text-embedding-3-small) via litellm integration\n2. Custom embedding functions that you provide\n\nFor hosted models, simply pass the model name as a string (e.g., \"openai/text-embedding-3-small\"). The class will use\nlitellm to handle the API calls and caching.\n\nFor custom embedding models, pass a callable function that:\n- Takes a list of strings as input.\n- Returns embeddings as either:\n - A 2D numpy array of float32 values\n - A 2D list of float32 values\n- Each row should represent one embedding vector\n\nArgs:\n model: The embedding model to use. This can be either a string (representing the name of the hosted embedding\n model, must be an embedding model supported by litellm) or a callable that represents a custom embedding\n model.\n batch_size (int, optional): The default batch size for processing inputs in batches. Defaults to 200.\n caching (bool, optional): Whether to cache the embedding response when using a hosted model. Defaults to True.\n **kwargs: Additional default keyword arguments to pass to the embedding model.\n\nExamples:\n Example 1: Using a hosted model.\n\n ```python\n import dspy\n\n embedder = dspy.Embedder(\"openai/text-embedding-3-small\", batch_size=100)\n embeddings = embedder([\"hello\", \"world\"])\n\n assert embeddings.shape == (2, 1536)\n ```\n\n Example 2: Using any local embedding model, e.g. from https://huggingface.co/models?library=sentence-transformers.\n\n ```python\n # pip install sentence_transformers\n import dspy\n from sentence_transformers import SentenceTransformer\n\n # Load an extremely efficient local model for retrieval\n model = SentenceTransformer(\"sentence-transformers/static-retrieval-mrl-en-v1\", device=\"cpu\")\n\n embedder = dspy.Embedder(model.encode)\n embeddings = embedder([\"hello\", \"world\"], batch_size=1)\n\n assert embeddings.shape == (2, 1024)\n ```\n\n Example 3: Using a custom function.\n\n ```python\n import dspy\n import numpy as np\n\n def my_embedder(texts):\n return np.random.rand(len(texts), 10)\n\n embedder = dspy.Embedder(my_embedder)\n embeddings = embedder([\"hello\", \"world\"], batch_size=1)\n\n assert embeddings.shape == (2, 10)\n ```"}, {Dspy.ProgramOfThought, "A DSPy module that runs Python programs to solve a problem.\nThis module requires deno to be installed. Please install deno following https://docs.deno.com/runtime/getting_started/installation/\n\nExample:\n```\nimport dspy\n\nlm = dspy.LM('openai/gpt-4o-mini')\ndspy.configure(lm=lm)\npot = dspy.ProgramOfThought(\"question -> answer\")\npot(question=\"what is 1+1?\")\n```"}, {Dspy.Predict.MultiChainComparison, ""}, {Dspy.Predict.RLM, "Experimental: This class may change or be removed in a future release without warning.\n\nRecursive Language Model module.\n\n Uses a sandboxed REPL to let the LLM programmatically explore large contexts\n through code execution. The LLM writes Python code to examine data, call\n sub-LLMs for semantic analysis, and build up answers iteratively.\n\n The default interpreter is PythonInterpreter (Deno/Pyodide/WASM), but you\n can provide any CodeInterpreter implementation (e.g., MockInterpreter, or write a custom one using E2B or Modal).\n\n Note: RLM instances are not thread-safe when using a custom interpreter.\n Create separate RLM instances for concurrent use, or use the default\n PythonInterpreter which creates a fresh instance per forward() call.\n\n Example:\n ```python\n # Basic usage\n rlm = dspy.RLM(\"context, query -> output\", max_iterations=10)\n result = rlm(context=\"...very long text...\", query=\"What is the magic number?\")\n print(result.output)\n ```\n "}, {Dspy.Adapters.Type, "Base class to support creating custom types for DSPy signatures.\n\nThis is the parent class of DSPy custom types, e.g, dspy.Image. Subclasses must implement the `format` method to\nreturn a list of dictionaries (same as the Array of content parts in the OpenAI API user message's content field).\n\nExample:\n\n ```python\n class Image(Type):\n url: str\n\n def format(self) -> list[dict[str, Any]]:\n return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n ```"}, {Dspy.Retrievers.Retrieve, ""}, {Dspy.Teleprompt.COPRO, ""}, {Dspy.Adapters.Types.History, "Class representing the conversation history.\n\nThe conversation history is a list of messages, each message entity should have keys from the associated signature.\nFor example, if you have the following signature:\n\n```\nclass MySignature(dspy.Signature):\n question: str = dspy.InputField()\n history: dspy.History = dspy.InputField()\n answer: str = dspy.OutputField()\n```\n\nThen the history should be a list of dictionaries with keys \"question\" and \"answer\".\n\nExample:\n ```\n import dspy\n\n dspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\n class MySignature(dspy.Signature):\n question: str = dspy.InputField()\n history: dspy.History = dspy.InputField()\n answer: str = dspy.OutputField()\n\n history = dspy.History(\n messages=[\n {\"question\": \"What is the capital of France?\", \"answer\": \"Paris\"},\n {\"question\": \"What is the capital of Germany?\", \"answer\": \"Berlin\"},\n ]\n )\n\n predict = dspy.Predict(MySignature)\n outputs = predict(question=\"What is the capital of France?\", history=history)\n ```\n\nExample of capturing the conversation history:\n ```\n import dspy\n\n dspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\n class MySignature(dspy.Signature):\n question: str = dspy.InputField()\n history: dspy.History = dspy.InputField()\n answer: str = dspy.OutputField()\n\n predict = dspy.Predict(MySignature)\n outputs = predict(question=\"What is the capital of France?\")\n history = dspy.History(messages=[{\"question\": \"What is the capital of France?\", **outputs}])\n outputs_with_history = predict(question=\"Are you sure?\", history=history)\n ```"}, {Dspy.Adapters.ToolCalls, "Base class to support creating custom types for DSPy signatures.\n\nThis is the parent class of DSPy custom types, e.g, dspy.Image. Subclasses must implement the `format` method to\nreturn a list of dictionaries (same as the Array of content parts in the OpenAI API user message's content field).\n\nExample:\n\n ```python\n class Image(Type):\n url: str\n\n def format(self) -> list[dict[str, Any]]:\n return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n ```"}, {Dspy.ToolCalls, "Base class to support creating custom types for DSPy signatures.\n\nThis is the parent class of DSPy custom types, e.g, dspy.Image. Subclasses must implement the `format` method to\nreturn a list of dictionaries (same as the Array of content parts in the OpenAI API user message's content field).\n\nExample:\n\n ```python\n class Image(Type):\n url: str\n\n def format(self) -> list[dict[str, Any]]:\n return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n ```"}, {Dspy.Adapters.Types.Image, "Base class to support creating custom types for DSPy signatures.\n\nThis is the parent class of DSPy custom types, e.g, dspy.Image. Subclasses must implement the `format` method to\nreturn a list of dictionaries (same as the Array of content parts in the OpenAI API user message's content field).\n\nExample:\n\n ```python\n class Image(Type):\n url: str\n\n def format(self) -> list[dict[str, Any]]:\n return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n ```"}, {Dspy.BootstrapFewShotWithOptuna, ""}, {Dspy.Primitives.ReplTypes.REPLVariable, "Metadata about a variable available in the REPL environment."}, {Dspy.Adapters.JSONAdapter, "Default Adapter for most language models.\n\nThe ChatAdapter formats DSPy signatures into a format compatible with most language models.\nIt uses delimiter patterns like `[[ ## field_name ## ]]` to clearly separate input and output fields in\nthe message content.\n\nKey features:\n - Structures inputs and outputs using field header markers for clear field delineation.\n - Provides automatic fallback to JSONAdapter if the chat format fails."}, {Dspy.Retrieve, ""}, {Dspy.Type, "Base class to support creating custom types for DSPy signatures.\n\nThis is the parent class of DSPy custom types, e.g, dspy.Image. Subclasses must implement the `format` method to\nreturn a list of dictionaries (same as the Array of content parts in the OpenAI API user message's content field).\n\nExample:\n\n ```python\n class Image(Type):\n url: str\n\n def format(self) -> list[dict[str, Any]]:\n return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n ```"}, {Dspy.Utils.StatusMessage, "Dataclass that wraps a status message for status streaming."}, {Dspy.XMLAdapter, "Default Adapter for most language models.\n\nThe ChatAdapter formats DSPy signatures into a format compatible with most language models.\nIt uses delimiter patterns like `[[ ## field_name ## ]]` to clearly separate input and output fields in\nthe message content.\n\nKey features:\n - Structures inputs and outputs using field header markers for clear field delineation.\n - Provides automatic fallback to JSONAdapter if the chat format fails."}, {Dspy.Teleprompt.BootstrapFewShotWithRandomSearch, ""}, {Dspy.Adapters.Audio, "Base class to support creating custom types for DSPy signatures.\n\nThis is the parent class of DSPy custom types, e.g, dspy.Image. Subclasses must implement the `format` method to\nreturn a list of dictionaries (same as the Array of content parts in the OpenAI API user message's content field).\n\nExample:\n\n ```python\n class Image(Type):\n url: str\n\n def format(self) -> list[dict[str, Any]]:\n return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n ```"}, {Dspy.Signatures.Signature, ""}, {Dspy.KNN, ""}, {Dspy.Primitives.Module, ""}, {Dspy.Embedder, "DSPy embedding class.\n\nThe class for computing embeddings for text inputs. This class provides a unified interface for both:\n\n1. Hosted embedding models (e.g. OpenAI's text-embedding-3-small) via litellm integration\n2. Custom embedding functions that you provide\n\nFor hosted models, simply pass the model name as a string (e.g., \"openai/text-embedding-3-small\"). The class will use\nlitellm to handle the API calls and caching.\n\nFor custom embedding models, pass a callable function that:\n- Takes a list of strings as input.\n- Returns embeddings as either:\n - A 2D numpy array of float32 values\n - A 2D list of float32 values\n- Each row should represent one embedding vector\n\nArgs:\n model: The embedding model to use. This can be either a string (representing the name of the hosted embedding\n model, must be an embedding model supported by litellm) or a callable that represents a custom embedding\n model.\n batch_size (int, optional): The default batch size for processing inputs in batches. Defaults to 200.\n caching (bool, optional): Whether to cache the embedding response when using a hosted model. Defaults to True.\n **kwargs: Additional default keyword arguments to pass to the embedding model.\n\nExamples:\n Example 1: Using a hosted model.\n\n ```python\n import dspy\n\n embedder = dspy.Embedder(\"openai/text-embedding-3-small\", batch_size=100)\n embeddings = embedder([\"hello\", \"world\"])\n\n assert embeddings.shape == (2, 1536)\n ```\n\n Example 2: Using any local embedding model, e.g. from https://huggingface.co/models?library=sentence-transformers.\n\n ```python\n # pip install sentence_transformers\n import dspy\n from sentence_transformers import SentenceTransformer\n\n # Load an extremely efficient local model for retrieval\n model = SentenceTransformer(\"sentence-transformers/static-retrieval-mrl-en-v1\", device=\"cpu\")\n\n embedder = dspy.Embedder(model.encode)\n embeddings = embedder([\"hello\", \"world\"], batch_size=1)\n\n assert embeddings.shape == (2, 1024)\n ```\n\n Example 3: Using a custom function.\n\n ```python\n import dspy\n import numpy as np\n\n def my_embedder(texts):\n return np.random.rand(len(texts), 10)\n\n embedder = dspy.Embedder(my_embedder)\n embeddings = embedder([\"hello\", \"world\"], batch_size=1)\n\n assert embeddings.shape == (2, 10)\n ```"}, {Dspy.Tool, "Tool class.\n\nThis class is used to simplify the creation of tools for tool calling (function calling) in LLMs. Only supports\nfunctions for now."}, {Dspy.Code, "Code type in DSPy.\n\nThis type is useful for code generation and code analysis.\n\nExample 1: dspy.Code as output type in code generation:\n\n```python\nimport dspy\n\ndspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\n\nclass CodeGeneration(dspy.Signature):\n '''Generate python code to answer the question.'''\n\n question: str = dspy.InputField(description=\"The question to answer\")\n code: dspy.Code[\"java\"] = dspy.OutputField(description=\"The code to execute\")\n\n\npredict = dspy.Predict(CodeGeneration)\n\nresult = predict(question=\"Given an array, find if any of the two numbers sum up to 10\")\nprint(result.code)\n```\n\nExample 2: dspy.Code as input type in code analysis:\n\n```python\nimport dspy\nimport inspect\n\ndspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\nclass CodeAnalysis(dspy.Signature):\n '''Analyze the time complexity of the function.'''\n\n code: dspy.Code[\"python\"] = dspy.InputField(description=\"The function to analyze\")\n result: str = dspy.OutputField(description=\"The time complexity of the function\")\n\n\npredict = dspy.Predict(CodeAnalysis)\n\n\ndef sleepsort(x):\n import time\n\n for i in x:\n time.sleep(i)\n print(i)\n\nresult = predict(code=inspect.getsource(sleepsort))\nprint(result.result)\n```"}, {Dspy.RLM, "Experimental: This class may change or be removed in a future release without warning.\n\nRecursive Language Model module.\n\n Uses a sandboxed REPL to let the LLM programmatically explore large contexts\n through code execution. The LLM writes Python code to examine data, call\n sub-LLMs for semantic analysis, and build up answers iteratively.\n\n The default interpreter is PythonInterpreter (Deno/Pyodide/WASM), but you\n can provide any CodeInterpreter implementation (e.g., MockInterpreter, or write a custom one using E2B or Modal).\n\n Note: RLM instances are not thread-safe when using a custom interpreter.\n Create separate RLM instances for concurrent use, or use the default\n PythonInterpreter which creates a fresh instance per forward() call.\n\n Example:\n ```python\n # Basic usage\n rlm = dspy.RLM(\"context, query -> output\", max_iterations=10)\n result = rlm(context=\"...very long text...\", query=\"What is the magic number?\")\n print(result.output)\n ```\n "}, {Dspy.Signatures.SignatureMeta, "Metaclass for defining Abstract Base Classes (ABCs).\n\nUse this metaclass to create an ABC. An ABC can be subclassed\ndirectly, and then acts as a mix-in class. You can also register\nunrelated concrete classes (even built-in classes) and unrelated\nABCs as 'virtual subclasses' -- these and their descendants will\nbe considered subclasses of the registering ABC by the built-in\nissubclass() function, but the registering ABC won't show up in\ntheir MRO (Method Resolution Order) nor will method\nimplementations defined by the registering ABC be callable (not\neven via super())."}, {Dspy.OldInputField, "A more ergonomic datatype that infers prefix and desc if omitted."}, {Dspy.Parallel, ""}, {Dspy.CodeInterpreterError, "Error raised during code execution in an interpreter.\n\nThis covers runtime errors, undefined variables, tool call failures, etc.\nSyntaxError is raised separately for invalid Python syntax."}, {Dspy.PredictClass, "Basic DSPy module that maps inputs to outputs using a language model.\n\nArgs:\n signature: The input/output signature describing the task.\n callbacks: Optional list of callbacks for instrumentation.\n **config: Default keyword arguments forwarded to the underlying\n language model. These values can be overridden for a single\n invocation by passing a ``config`` dictionary when calling the\n module. For example::\n\n predict = dspy.Predict(\"q -> a\", rollout_id=1, temperature=1.0)\n predict(q=\"What is 1 + 52?\", config={\"rollout_id\": 2, \"temperature\": 1.0})"}, {Dspy.File, "A file input type for DSPy.\nSee https://platform.openai.com/docs/api-reference/chat/create#chat_create-messages-user_message-content-array_of_content_parts-file_content_part-file for specification.\n\nThe file_data field should be a data URI with the format:\n data:;base64,\n\nExample:\n ```python\n import dspy\n\n class QA(dspy.Signature):\n file: dspy.File = dspy.InputField()\n summary = dspy.OutputField()\n program = dspy.Predict(QA)\n result = program(file=dspy.File.from_path(\"./research.pdf\"))\n print(result.summary)\n ```"}, {Dspy.SignatureMeta, "Metaclass for defining Abstract Base Classes (ABCs).\n\nUse this metaclass to create an ABC. An ABC can be subclassed\ndirectly, and then acts as a mix-in class. You can also register\nunrelated concrete classes (even built-in classes) and unrelated\nABCs as 'virtual subclasses' -- these and their descendants will\nbe considered subclasses of the registering ABC by the built-in\nissubclass() function, but the registering ABC won't show up in\ntheir MRO (Method Resolution Order) nor will method\nimplementations defined by the registering ABC be callable (not\neven via super())."}, {Dspy.Example, "A flexible data container for DSPy examples and training data.\n\nThe `Example` class is the standard data format used in DSPy evaluation and optimization.\n\nKey features:\n - Dictionary-like access patterns (item access, iteration, etc.)\n - Flexible initialization from dictionaries, other `Example` instances, or keyword arguments\n - Input/output field separation for training data\n - Serialization support for saving/loading `Example` instances\n - Immutable operations that return new `Example` instances\n\nExamples:\n\n Basic usage with keyword arguments:\n\n ```python\n import dspy\n\n # Create an example with input and output fields\n example = dspy.Example(\n question=\"What is the capital of France?\",\n answer=\"Paris\",\n )\n print(example.question) # \"What is the capital of France?\"\n print(example.answer) # \"Paris\"\n ```\n\n Initialize from a dictionary:\n\n ```python\n data = {\"question\": \"What is 2+2?\", \"answer\": \"4\"}\n example = dspy.Example(data)\n print(example[\"question\"]) # \"What is 2+2?\"\n ```\n\n Copy from another Example:\n\n ```python\n original = dspy.Example(question=\"Hello\", answer=\"World\")\n copy = dspy.Example(original)\n print(copy.question) # \"Hello\"\n ```\n\n Working with input/output separation:\n\n ```python\n # Mark which fields are inputs for training\n example = dspy.Example(\n question=\"What is the weather?\",\n answer=\"It's sunny\",\n ).with_inputs(\"question\")\n\n # Get only input fields\n inputs = example.inputs()\n print(inputs.question) # \"What is the weather?\"\n\n # Get only output fields (labels)\n labels = example.labels()\n print(labels.answer) # \"It's sunny\"\n ```\n\n Dictionary-like operations:\n\n ```python\n example = dspy.Example(name=\"Alice\", age=30)\n\n # Check if key exists\n if \"name\" in example:\n print(\"Name field exists\")\n\n # Get with default value\n city = example.get(\"city\", \"Unknown\")\n print(city) # \"Unknown\"\n ```"}, {Dspy.BootstrapFinetune, ""}, {Dspy.Adapters.Types.Reasoning, "Reasoning type in DSPy.\n\nThis type is useful when you want the DSPy output to include the reasoning of the LM. We build this type so that\nDSPy can support the reasoning model and non-reasoning model with the same code.\n\nThis is a str-like type, you can convert a string directly to a Reasoning object, and from DSPy adapters'\nperspective, `Reasoning` is treated as a string."}, {Dspy.Predict.Refine, ""}, {Dspy.Adapters.Tool, "Tool class.\n\nThis class is used to simplify the creation of tools for tool calling (function calling) in LLMs. Only supports\nfunctions for now."}, {Dspy.Predict, "Basic DSPy module that maps inputs to outputs using a language model.\n\nArgs:\n signature: The input/output signature describing the task.\n callbacks: Optional list of callbacks for instrumentation.\n **config: Default keyword arguments forwarded to the underlying\n language model. These values can be overridden for a single\n invocation by passing a ``config`` dictionary when calling the\n module. For example::\n\n predict = dspy.Predict(\"q -> a\", rollout_id=1, temperature=1.0)\n predict(q=\"What is 1 + 52?\", config={\"rollout_id\": 2, \"temperature\": 1.0})"}, {Dspy.Teleprompt.InferRules, ""}, {Dspy.Streaming.StreamResponse, "StreamResponse(predict_name: str, signature_field_name: str, chunk: str, is_last_chunk: bool)"}, {Dspy.Adapters.TwoStepAdapter, "A two-stage adapter that:\n 1. Uses a simpler, more natural prompt for the main LM\n 2. Uses a smaller LM with chat adapter to extract structured data from the response of main LM\nThis adapter uses a common __call__ logic defined in base Adapter class.\nThis class is particularly useful when interacting with reasoning models as the main LM since reasoning models\nare known to struggle with structured outputs.\n\nExample:\n```\nimport dspy\nlm = dspy.LM(model=\"openai/o3-mini\", max_tokens=16000, temperature = 1.0)\nadapter = dspy.TwoStepAdapter(dspy.LM(\"openai/gpt-4o-mini\"))\ndspy.configure(lm=lm, adapter=adapter)\nprogram = dspy.ChainOfThought(\"question->answer\")\nresult = program(\"What is the capital of France?\")\nprint(result)\n```"}, {Dspy.Teleprompt.SIMBA, "SIMBA (Stochastic Introspective Mini-Batch Ascent) optimizer for DSPy.\n\nSIMBA is a DSPy optimizer that uses the LLM to analyze its own performance and \ngenerate improvement rules. It samples mini-batches, identifies challenging examples \nwith high output variability, then either creates self-reflective rules or adds \nsuccessful examples as demonstrations.\n\nFor more details, see: https://dspy.ai/api/optimizers/SIMBA/"}, {Dspy.Adapters.Types.File, "A file input type for DSPy.\nSee https://platform.openai.com/docs/api-reference/chat/create#chat_create-messages-user_message-content-array_of_content_parts-file_content_part-file for specification.\n\nThe file_data field should be a data URI with the format:\n data:;base64,\n\nExample:\n ```python\n import dspy\n\n class QA(dspy.Signature):\n file: dspy.File = dspy.InputField()\n summary = dspy.OutputField()\n program = dspy.Predict(QA)\n result = program(file=dspy.File.from_path(\"./research.pdf\"))\n print(result.summary)\n ```"}, {Dspy.Signatures.OldField, "A more ergonomic datatype that infers prefix and desc if omitted."}, {Dspy.Primitives.Example, "A flexible data container for DSPy examples and training data.\n\nThe `Example` class is the standard data format used in DSPy evaluation and optimization.\n\nKey features:\n - Dictionary-like access patterns (item access, iteration, etc.)\n - Flexible initialization from dictionaries, other `Example` instances, or keyword arguments\n - Input/output field separation for training data\n - Serialization support for saving/loading `Example` instances\n - Immutable operations that return new `Example` instances\n\nExamples:\n\n Basic usage with keyword arguments:\n\n ```python\n import dspy\n\n # Create an example with input and output fields\n example = dspy.Example(\n question=\"What is the capital of France?\",\n answer=\"Paris\",\n )\n print(example.question) # \"What is the capital of France?\"\n print(example.answer) # \"Paris\"\n ```\n\n Initialize from a dictionary:\n\n ```python\n data = {\"question\": \"What is 2+2?\", \"answer\": \"4\"}\n example = dspy.Example(data)\n print(example[\"question\"]) # \"What is 2+2?\"\n ```\n\n Copy from another Example:\n\n ```python\n original = dspy.Example(question=\"Hello\", answer=\"World\")\n copy = dspy.Example(original)\n print(copy.question) # \"Hello\"\n ```\n\n Working with input/output separation:\n\n ```python\n # Mark which fields are inputs for training\n example = dspy.Example(\n question=\"What is the weather?\",\n answer=\"It's sunny\",\n ).with_inputs(\"question\")\n\n # Get only input fields\n inputs = example.inputs()\n print(inputs.question) # \"What is the weather?\"\n\n # Get only output fields (labels)\n labels = example.labels()\n print(labels.answer) # \"It's sunny\"\n ```\n\n Dictionary-like operations:\n\n ```python\n example = dspy.Example(name=\"Alice\", age=30)\n\n # Check if key exists\n if \"name\" in example:\n print(\"Name field exists\")\n\n # Get with default value\n city = example.get(\"city\", \"Unknown\")\n print(city) # \"Unknown\"\n ```"}, {Dspy.Image, "Base class to support creating custom types for DSPy signatures.\n\nThis is the parent class of DSPy custom types, e.g, dspy.Image. Subclasses must implement the `format` method to\nreturn a list of dictionaries (same as the Array of content parts in the OpenAI API user message's content field).\n\nExample:\n\n ```python\n class Image(Type):\n url: str\n\n def format(self) -> list[dict[str, Any]]:\n return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n ```"}, {Dspy.FinalOutput, "Returned by interpreter.execute() when SUBMIT() is called.\n\nThis signals that the code execution loop should terminate and return\nthe contained output to the caller."}, {Dspy.Primitives.ReplTypes.REPLEntry, "A single REPL interaction entry containing reasoning, code, and output."}, {Dspy.Teleprompt.BootstrapFewShotWithOptuna, ""}, {Dspy.Predict.ChainOfThought, ""}, {Dspy.Ensemble, ""}, {Dspy.Datasets.DataLoader, ""}, {Dspy.ChatAdapter, "Default Adapter for most language models.\n\nThe ChatAdapter formats DSPy signatures into a format compatible with most language models.\nIt uses delimiter patterns like `[[ ## field_name ## ]]` to clearly separate input and output fields in\nthe message content.\n\nKey features:\n - Structures inputs and outputs using field header markers for clear field delineation.\n - Provides automatic fallback to JSONAdapter if the chat format fails."}, {Dspy.Adapters.History, "Class representing the conversation history.\n\nThe conversation history is a list of messages, each message entity should have keys from the associated signature.\nFor example, if you have the following signature:\n\n```\nclass MySignature(dspy.Signature):\n question: str = dspy.InputField()\n history: dspy.History = dspy.InputField()\n answer: str = dspy.OutputField()\n```\n\nThen the history should be a list of dictionaries with keys \"question\" and \"answer\".\n\nExample:\n ```\n import dspy\n\n dspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\n class MySignature(dspy.Signature):\n question: str = dspy.InputField()\n history: dspy.History = dspy.InputField()\n answer: str = dspy.OutputField()\n\n history = dspy.History(\n messages=[\n {\"question\": \"What is the capital of France?\", \"answer\": \"Paris\"},\n {\"question\": \"What is the capital of Germany?\", \"answer\": \"Berlin\"},\n ]\n )\n\n predict = dspy.Predict(MySignature)\n outputs = predict(question=\"What is the capital of France?\", history=history)\n ```\n\nExample of capturing the conversation history:\n ```\n import dspy\n\n dspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\n class MySignature(dspy.Signature):\n question: str = dspy.InputField()\n history: dspy.History = dspy.InputField()\n answer: str = dspy.OutputField()\n\n predict = dspy.Predict(MySignature)\n outputs = predict(question=\"What is the capital of France?\")\n history = dspy.History(messages=[{\"question\": \"What is the capital of France?\", **outputs}])\n outputs_with_history = predict(question=\"Are you sure?\", history=history)\n ```"}, {Dspy.COPRO, ""}, {Dspy.Teleprompt.MIPROv2, ""}, {Dspy.Provider, ""}, {Dspy.Refine, ""}, {Dspy.Completions, ""}, {Dspy.MIPROv2, ""}, {Dspy.Signatures.OldOutputField, "A more ergonomic datatype that infers prefix and desc if omitted."}, {Dspy.Teleprompt.AvatarOptimizer, ""}, {Dspy.Primitives.PythonInterpreter.CodeInterpreterError, "Error raised during code execution in an interpreter.\n\nThis covers runtime errors, undefined variables, tool call failures, etc.\nSyntaxError is raised separately for invalid Python syntax."}, {Dspy.Primitives.CodeInterpreter, "Protocol for code execution environments (interpreters).\n\nImplementations must provide:\n- start(): Initialize the interpreter (optional, can be lazy)\n- execute(): Run code and return results\n- shutdown(): Clean up resources\n\nThe interpreter maintains state across execute() calls within a session,\nallowing variables defined in one call to be used in subsequent calls.\n\nLifecycle:\n 1. Create instance (config only, no resources allocated)\n 2. start() - Initialize interpreter (explicit) or let execute() do it (lazy)\n 3. execute() - Run code (can be called many times)\n 4. shutdown() - Release resources\n\nExample implementations:\n - LocalInterpreter: Deno/Pyodide WASM interpreter (local)\n - MockInterpreter: Scriptable responses for testing\n\nPooling:\n For interpreter pooling, call start() to pre-warm instances, then\n distribute execute() calls across the pool."}, {Dspy.Adapters.ChatAdapter, "Default Adapter for most language models.\n\nThe ChatAdapter formats DSPy signatures into a format compatible with most language models.\nIt uses delimiter patterns like `[[ ## field_name ## ]]` to clearly separate input and output fields in\nthe message content.\n\nKey features:\n - Structures inputs and outputs using field header markers for clear field delineation.\n - Provides automatic fallback to JSONAdapter if the chat format fails."}, {Dspy.Predict.KNN, ""}, {Dspy.Teleprompt.BetterTogether, ""}, {Dspy.Primitives.PythonInterpreterClass, "Local interpreter for secure Python execution using Deno and Pyodide.\n\nImplements the Interpreter protocol for secure code execution in a\nWASM-based sandbox. Code runs in an isolated Pyodide environment with\nno access to the host filesystem, network, or environment by default.\n\nPrerequisites:\n Deno must be installed: https://docs.deno.com/runtime/getting_started/installation/\n\nExample:\n ```python\n # Basic execution\n with PythonInterpreter() as interp:\n result = interp(\"print(1 + 2)\") # Returns \"3\"\n\n # With host-side tools\n def my_tool(question: str) -> str:\n return \"answer\"\n\n with PythonInterpreter(tools={\"my_tool\": my_tool}) as interp:\n result = interp(\"print(my_tool(question='test'))\")\n ```"}, {Dspy.KNNFewShot, ""}, {Dspy.OldField, "A more ergonomic datatype that infers prefix and desc if omitted."}, {Dspy.Predict.ProgramOfThought, "A DSPy module that runs Python programs to solve a problem.\nThis module requires deno to be installed. Please install deno following https://docs.deno.com/runtime/getting_started/installation/\n\nExample:\n```\nimport dspy\n\nlm = dspy.LM('openai/gpt-4o-mini')\ndspy.configure(lm=lm)\npot = dspy.ProgramOfThought(\"question -> answer\")\npot(question=\"what is 1+1?\")\n```"}, {Dspy.Datasets.HotPotQA, ""}, {Dspy.ReAct, ""}, {Dspy.Adapters.Types.Audio, "Base class to support creating custom types for DSPy signatures.\n\nThis is the parent class of DSPy custom types, e.g, dspy.Image. Subclasses must implement the `format` method to\nreturn a list of dictionaries (same as the Array of content parts in the OpenAI API user message's content field).\n\nExample:\n\n ```python\n class Image(Type):\n url: str\n\n def format(self) -> list[dict[str, Any]]:\n return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n ```"}, {Dspy.Evaluate, "DSPy Evaluate class.\n\nThis class is used to evaluate the performance of a DSPy program. Users need to provide a evaluation dataset and\na metric function in order to use this class. This class supports parallel evaluation on the provided dataset."}, {Dspy.Adapters.Image, "Base class to support creating custom types for DSPy signatures.\n\nThis is the parent class of DSPy custom types, e.g, dspy.Image. Subclasses must implement the `format` method to\nreturn a list of dictionaries (same as the Array of content parts in the OpenAI API user message's content field).\n\nExample:\n\n ```python\n class Image(Type):\n url: str\n\n def format(self) -> list[dict[str, Any]]:\n return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n ```"}, {Dspy.Primitives.CodeInterpreterError, "Error raised during code execution in an interpreter.\n\nThis covers runtime errors, undefined variables, tool call failures, etc.\nSyntaxError is raised separately for invalid Python syntax."}, {Dspy.Clients.LM, "A language model supporting chat or text completion requests for use with DSPy modules."}, {Dspy.Audio, "Base class to support creating custom types for DSPy signatures.\n\nThis is the parent class of DSPy custom types, e.g, dspy.Image. Subclasses must implement the `format` method to\nreturn a list of dictionaries (same as the Array of content parts in the OpenAI API user message's content field).\n\nExample:\n\n ```python\n class Image(Type):\n url: str\n\n def format(self) -> list[dict[str, Any]]:\n return [{\"type\": \"image_url\", \"image_url\": {\"url\": self.url}}]\n ```"}, {Dspy.JSONAdapter, "Default Adapter for most language models.\n\nThe ChatAdapter formats DSPy signatures into a format compatible with most language models.\nIt uses delimiter patterns like `[[ ## field_name ## ]]` to clearly separate input and output fields in\nthe message content.\n\nKey features:\n - Structures inputs and outputs using field header markers for clear field delineation.\n - Provides automatic fallback to JSONAdapter if the chat format fails."}, {Dspy.Teleprompt.GEPAClass, "Experimental: This class may change or be removed in a future release without warning (introduced in v3.0.0).\n\n\nGEPA is an evolutionary optimizer, which uses reflection to evolve text components\nof complex systems. GEPA is proposed in the paper [GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning](https://arxiv.org/abs/2507.19457).\nThe GEPA optimization engine is provided by the `gepa` package, available from [https://github.com/gepa-ai/gepa](https://github.com/gepa-ai/gepa).\n\nGEPA captures full traces of the DSPy module's execution, identifies the parts of the trace\ncorresponding to a specific predictor, and reflects on the behaviour of the predictor to\npropose a new instruction for the predictor. GEPA allows users to provide textual feedback\nto the optimizer, which is used to guide the evolution of the predictor. The textual feedback\ncan be provided at the granularity of individual predictors, or at the level of the entire system's\nexecution.\n\nTo provide feedback to the GEPA optimizer, implement a metric as follows:\n```\ndef metric(\n gold: Example,\n pred: Prediction,\n trace: Optional[DSPyTrace] = None,\n pred_name: Optional[str] = None,\n pred_trace: Optional[DSPyTrace] = None,\n) -> float | ScoreWithFeedback:\n \"\"\"\n This function is called with the following arguments:\n - gold: The gold example.\n - pred: The predicted output.\n - trace: Optional. The trace of the program's execution.\n - pred_name: Optional. The name of the target predictor currently being optimized by GEPA, for which\n the feedback is being requested.\n - pred_trace: Optional. The trace of the target predictor's execution GEPA is seeking feedback for.\n\n Note the `pred_name` and `pred_trace` arguments. During optimization, GEPA will call the metric to obtain\n feedback for individual predictors being optimized. GEPA provides the name of the predictor in `pred_name`\n and the sub-trace (of the trace) corresponding to the predictor in `pred_trace`.\n If available at the predictor level, the metric should return {'score': float, 'feedback': str} corresponding\n to the predictor.\n If not available at the predictor level, the metric can also return a text feedback at the program level\n (using just the gold, pred and trace).\n If no feedback is returned, GEPA will use a simple text feedback consisting of just the score:\n f\"This trajectory got a score of {score}.\"\n \"\"\"\n ...\n```\n\nGEPA can also be used as a batch inference-time search strategy, by passing `valset=trainset, track_stats=True, track_best_outputs=True`, and using the\n`detailed_results` attribute of the optimized program (returned by `compile`) to get the Pareto frontier of the batch. `optimized_program.detailed_results.best_outputs_valset` will contain the best outputs for each task in the batch.\n\nExample:\n```\ngepa = GEPA(metric=metric, track_stats=True)\nbatch_of_tasks = [dspy.Example(...) for task in tasks]\nnew_prog = gepa.compile(student, trainset=trainset, valset=batch_of_tasks)\npareto_frontier = new_prog.detailed_results.val_aggregate_scores\n# pareto_frontier is a list of scores, one for each task in the batch.\n```\n\nArgs:\n metric: The metric function to use for feedback and evaluation.\n auto: The auto budget to use for the run. Options: \"light\", \"medium\", \"heavy\".\n max_full_evals: The maximum number of full evaluations to perform.\n max_metric_calls: The maximum number of metric calls to perform.\n reflection_minibatch_size: The number of examples to use for reflection in a single GEPA step. Default is 3.\n candidate_selection_strategy: The strategy to use for candidate selection. Default is \"pareto\",\n which stochastically selects candidates from the Pareto frontier of all validation scores.\n Options: \"pareto\", \"current_best\".\n reflection_lm: The language model to use for reflection. Required parameter. GEPA benefits from\n a strong reflection model. Consider using `dspy.LM(model='gpt-5', temperature=1.0, max_tokens=32000)`\n for optimal performance.\n skip_perfect_score: Whether to skip examples with perfect scores during reflection. Default is True.\n instruction_proposer: Optional custom instruction proposer implementing GEPA's ProposalFn protocol.\n **Default: None (recommended for most users)** - Uses GEPA's proven instruction proposer from\n the [GEPA library](https://github.com/gepa-ai/gepa), which implements the\n [`ProposalFn`](https://github.com/gepa-ai/gepa/blob/main/src/gepa/core/adapter.py). This default\n proposer is highly capable and was validated across diverse experiments reported in the GEPA\n paper and tutorials.\n\n See documentation on custom instruction proposers\n [here](https://dspy.ai/api/optimizers/GEPA/GEPA_Advanced/#custom-instruction-proposers).\n\n **Advanced Feature**: Only needed for specialized scenarios:\n - **Multi-modal handling**: Processing dspy.Image inputs alongside textual information\n - **Nuanced control over constraints**: Fine-grained control over instruction length, format,\n and structural requirements beyond standard feedback mechanisms\n - **Domain-specific knowledge injection**: Specialized terminology or context that cannot be\n provided through feedback_func alone\n - **Provider-specific prompting**: Optimizations for specific LLM providers (OpenAI, Anthropic)\n with unique formatting preferences\n - **Coupled component updates**: Coordinated updates of multiple components together rather\n than independent optimization\n - **External knowledge integration**: Runtime access to databases, APIs, or knowledge bases\n\n The default proposer handles the vast majority of use cases effectively. Use\n MultiModalInstructionProposer() from dspy.teleprompt.gepa.instruction_proposal for visual\n content or implement custom ProposalFn for highly specialized requirements.\n\n Note: When both instruction_proposer and reflection_lm are set, the instruction_proposer is called\n in the reflection_lm context. However, reflection_lm is optional when using a custom instruction_proposer.\n Custom instruction proposers can invoke their own LLMs if needed.\n component_selector: Custom component selector implementing the [ReflectionComponentSelector](https://github.com/gepa-ai/gepa/blob/main/src/gepa/proposer/reflective_mutation/base.py) protocol,\n or a string specifying a built-in selector strategy. Controls which components (predictors) are selected\n for optimization at each iteration. Defaults to 'round_robin' strategy which cycles through components\n one at a time. Available string options: 'round_robin' (cycles through components sequentially),\n 'all' (selects all components for simultaneous optimization). Custom selectors can implement strategies\n using LLM-driven selection logic based on optimization state and trajectories.\n See [gepa component selectors](https://github.com/gepa-ai/gepa/blob/main/src/gepa/strategies/component_selector.py)\n for available built-in selectors and the ReflectionComponentSelector protocol for implementing custom selectors.\n add_format_failure_as_feedback: Whether to add format failures as feedback. Default is False.\n use_merge: Whether to use merge-based optimization. Default is True.\n max_merge_invocations: The maximum number of merge invocations to perform. Default is 5.\n num_threads: The number of threads to use for evaluation with `Evaluate`. Optional.\n failure_score: The score to assign to failed examples. Default is 0.0.\n perfect_score: The maximum score achievable by the metric. Default is 1.0. Used by GEPA\n to determine if all examples in a minibatch are perfect.\n log_dir: The directory to save the logs. GEPA saves elaborate logs, along with all candidate\n programs, in this directory. Running G"}, {Dspy.Adapters.File, "A file input type for DSPy.\nSee https://platform.openai.com/docs/api-reference/chat/create#chat_create-messages-user_message-content-array_of_content_parts-file_content_part-file for specification.\n\nThe file_data field should be a data URI with the format:\n data:;base64,\n\nExample:\n ```python\n import dspy\n\n class QA(dspy.Signature):\n file: dspy.File = dspy.InputField()\n summary = dspy.OutputField()\n program = dspy.Predict(QA)\n result = program(file=dspy.File.from_path(\"./research.pdf\"))\n print(result.summary)\n ```"}, {Dspy.CodeAct, "CodeAct is a module that utilizes the Code Interpreter and predefined tools to solve the problem."}, {Dspy.Teleprompt.Ensemble, ""}, {Dspy.History, "Class representing the conversation history.\n\nThe conversation history is a list of messages, each message entity should have keys from the associated signature.\nFor example, if you have the following signature:\n\n```\nclass MySignature(dspy.Signature):\n question: str = dspy.InputField()\n history: dspy.History = dspy.InputField()\n answer: str = dspy.OutputField()\n```\n\nThen the history should be a list of dictionaries with keys \"question\" and \"answer\".\n\nExample:\n ```\n import dspy\n\n dspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\n class MySignature(dspy.Signature):\n question: str = dspy.InputField()\n history: dspy.History = dspy.InputField()\n answer: str = dspy.OutputField()\n\n history = dspy.History(\n messages=[\n {\"question\": \"What is the capital of France?\", \"answer\": \"Paris\"},\n {\"question\": \"What is the capital of Germany?\", \"answer\": \"Berlin\"},\n ]\n )\n\n predict = dspy.Predict(MySignature)\n outputs = predict(question=\"What is the capital of France?\", history=history)\n ```\n\nExample of capturing the conversation history:\n ```\n import dspy\n\n dspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"))\n\n class MySignature(dspy.Signature):\n question: str = dspy.InputField()\n history: dspy.History = dspy.InputField()\n answer: str = dspy.OutputField()\n\n predict = dspy.Predict(MySignature)\n outputs = predict(question=\"What is the capital of France?\")\n history = dspy.History(messages=[{\"question\": \"What is the capital of France?\", **outputs}])\n outputs_with_history = predict(question=\"Are you sure?\", history=history)\n ```"}, {Dspy.Adapters.Types.Tool, "Tool class.\n\nThis class is used to simplify the creation of tools for tool calling (function calling) in LLMs. Only supports\nfunctions for now."}, {Dspy.LabeledFewShot, ""}, {Dspy.Evaluate.EvaluationResult, "A class that represents the result of an evaluation.\nIt is a subclass of `dspy.Prediction` that contains the following fields\n\n- score: An float value (e.g., 67.30) representing the overall performance\n- results: a list of (example, prediction, score) tuples for each example in devset"}, {Dspy.Experimental.Citations, "Experimental: This class may change or be removed in a future release without warning (introduced in v3.0.4).\n\nCitations extracted from an LM response with source references.\n\n This type represents citations returned by language models that support\n citation extraction, particularly Anthropic's Citations API through LiteLLM.\n Citations include the quoted text and source information.\n\n Example:\n ```python\n import os\n import dspy\n from dspy.signatures import Signature\n from dspy.experimental import Citations, Document\n os.environ[\"ANTHROPIC_API_KEY\"] = \"YOUR_ANTHROPIC_API_KEY\"\n\n class AnswerWithSources(Signature):\n '''Answer questions using provided documents with citations.'''\n documents: list[Document] = dspy.InputField()\n question: str = dspy.InputField()\n answer: str = dspy.OutputField()\n citations: Citations = dspy.OutputField()\n\n # Create documents to provide as sources\n docs = [\n Document(\n data=\"The Earth orbits the Sun in an elliptical path.\",\n title=\"Basic Astronomy Facts\"\n ),\n Document(\n data=\"Water boils at 100°C at standard atmospheric pressure.\",\n title=\"Physics Fundamentals\",\n metadata={\"author\": \"Dr. Smith\", \"year\": 2023}\n )\n ]\n\n # Use with a model that supports citations like Claude\n lm = dspy.LM(\"anthropic/claude-opus-4-1-20250805\")\n predictor = dspy.Predict(AnswerWithSources)\n result = predictor(documents=docs, question=\"What temperature does water boil?\", lm=lm)\n\n for citation in result.citations.citations:\n print(citation.format())\n ```\n "}, {Dspy.BaseLM, "Base class for handling LLM calls.\n\nMost users can directly use the `dspy.LM` class, which is a subclass of `BaseLM`. Users can also implement their\nown subclasses of `BaseLM` to support custom LLM providers and inject custom logic. To do so, simply override the\n`forward` method and make sure the return format is identical to the\n[OpenAI response format](https://platform.openai.com/docs/api-reference/responses/object).\n\nExample:\n\n```python\nfrom openai import OpenAI\n\nimport dspy\n\n\nclass MyLM(dspy.BaseLM):\n def forward(self, prompt, messages=None, **kwargs):\n client = OpenAI()\n return client.chat.completions.create(\n model=self.model,\n messages=messages or [{\"role\": \"user\", \"content\": prompt}],\n **self.kwargs,\n )\n\n\nlm = MyLM(model=\"gpt-4o-mini\")\ndspy.configure(lm=lm)\nprint(dspy.Predict(\"q->a\")(q=\"Why did the chicken cross the kitchen?\"))\n```"}, {Dspy.Teleprompt.BootstrapFinetune, ""}, {Dspy.Primitives.Prediction, "A prediction object that contains the output of a DSPy module.\n\nPrediction inherits from Example.\n\nTo allow feedback-augmented scores, Prediction supports comparison operations\n(<, >, <=, >=) for Predictions with a `score` field. The comparison operations\ncompare the 'score' values as floats. For equality comparison, Predictions are equal\nif their underlying data stores are equal (inherited from Example).\n\nArithmetic operations (+, /, etc.) are also supported for Predictions with a 'score'\nfield, operating on the score value."}, {Dspy.Teleprompt.KNNFewShot, ""}, {Dspy.BootstrapRS, ""}, {Dspy.Predict.ReAct, ""}, {Dspy.Primitives.Completions, ""}, {Dspy.Utils.DummyLM, "Dummy language model for unit testing purposes.\n\nThree modes of operation:\n\nMode 1: List of dictionaries\n\nIf a list of dictionaries is provided, the dummy model will return the next dictionary\nin the list for each request, formatted according to the `format_field_with_value` function.\n\nExample:\n\n```\nlm = DummyLM([{\"answer\": \"red\"}, {\"answer\": \"blue\"}])\ndspy.configure(lm=lm)\npredictor(\"What color is the sky?\")\n# Output:\n# [[## answer ##]]\n# red\npredictor(\"What color is the sky?\")\n# Output:\n# [[## answer ##]]\n# blue\n```\n\nMode 2: Dictionary of dictionaries\n\nIf a dictionary of dictionaries is provided, the dummy model will return the value\ncorresponding to the key which is contained with the final message of the prompt,\nformatted according to the `format_field_with_value` function from the chat adapter.\n\n```\nlm = DummyLM({\"What color is the sky?\": {\"answer\": \"blue\"}})\ndspy.configure(lm=lm)\npredictor(\"What color is the sky?\")\n# Output:\n# [[## answer ##]]\n# blue\n```\n\nMode 3: Follow examples\n\nIf `follow_examples` is set to True, and the prompt contains an example input exactly equal to the prompt,\nthe dummy model will return the output from that example.\n\n```\nlm = DummyLM([{\"answer\": \"red\"}], follow_examples=True)\ndspy.configure(lm=lm)\npredictor(\"What color is the sky?, demos=dspy.Example(input=\"What color is the sky?\", output=\"blue\"))\n# Output:\n# [[## answer ##]]\n# blue\n```"}, {Dspy.TrainingJob, "Represents the result of an asynchronous computation."}, {Dspy.Adapters.XMLAdapter, "Default Adapter for most language models.\n\nThe ChatAdapter formats DSPy signatures into a format compatible with most language models.\nIt uses delimiter patterns like `[[ ## field_name ## ]]` to clearly separate input and output fields in\nthe message content.\n\nKey features:\n - Structures inputs and outputs using field header markers for clear field delineation.\n - Provides automatic fallback to JSONAdapter if the chat format fails."}, {Dspy.Primitives.BaseModule, ""} ] end @doc false def __search__(query) do SnakeBridge.Docs.search(__MODULE__, query) end @doc false def doc(function) do SnakeBridge.Docs.get(__MODULE__, function) end end