# Generated by SnakeBridge v0.12.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`. ## Runtime Options All functions accept a `__runtime__` option for controlling execution behavior: Elixir.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 Elixir.Dspy.predict(data, __runtime__: [timeout_profile: :ml_inference]) # Or explicit timeout Elixir.Dspy.predict(data, __runtime__: [timeout: 600_000]) # Route to a pool and enforce strict affinity Elixir.Dspy.predict(data, __runtime__: [pool_name: :strict_pool, affinity: :strict_queue]) See `SnakeBridge.Defaults` for global timeout configuration. """ def __snakebridge_python_name__, do: "dspy" 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. Parameters: - `program` (term()) 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 """ """ @spec bootstrap_trace_data(Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t())) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), keyword() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, keyword() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term(), keyword() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term(), term() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term(), term(), keyword() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term(), term(), term() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term(), term(), term(), keyword() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term(), term(), term(), float() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term(), term(), term(), float(), keyword() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term(), term(), term(), float(), float() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term(), term(), term(), float(), float(), keyword() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term(), term(), term(), float(), float(), boolean() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term(), term(), term(), float(), float(), boolean(), keyword() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term(), term(), term(), float(), float(), boolean(), term() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {:error, Snakepit.Error.t()} @spec bootstrap_trace_data( Dspy.Primitives.Module.Module.t(), list(Dspy.Primitives.Example.t()), term() | nil, term(), term(), term(), float(), float(), boolean(), term(), keyword() ) :: {:ok, list(Dspy.Teleprompt.BootstrapTrace.TraceData.t())} | {: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: - `Dspy.Clients.Cache.Cache.t()` """ @spec cache() :: {:ok, Dspy.Clients.Cache.Cache.t()} | {:error, Snakepit.Error.t()} def cache() do SnakeBridge.Runtime.get_module_attr(__MODULE__, :cache) end @doc """ """ @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. Parameters: - `enable_disk_cache` (term() default: True) - `enable_memory_cache` (term() default: True) - `disk_cache_dir` (term() default: '/home/home/.dspy_cache') - `disk_size_limit_bytes` (term() default: 30000000000) - `memory_max_entries` (integer() default: 1000000) 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 """ """ @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 """ """ @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: - `Dspy.Clients.Cache.Cache.t()` """ @spec dspy_cache() :: {:ok, Dspy.Clients.Cache.Cache.t()} | {:error, Snakepit.Error.t()} def dspy_cache() do SnakeBridge.Runtime.get_module_attr(__MODULE__, "DSPY_CACHE") end @doc """ """ @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 """ """ @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 """ """ @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()`) Parameters: - `path` (String.t()) - `allow_pickle` (boolean() default: False) 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. Parameters: - `path` (String.t()) 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. Parameters: - `signature` (term()) - `instructions` (term() default: None) - `signature_name` (String.t() default: 'StringSignature') - `custom_types` (term() default: None) 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 """ """ @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: - `Dspy.Dsp.Utils.Settings.Settings.t()` """ @spec settings() :: {:ok, Dspy.Dsp.Utils.Settings.Settings.t()} | {: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. Parameters: - `program` (term()) - `status_message_provider` (term() default: None) - `stream_listeners` (term() default: None) - `include_final_prediction_in_output_stream` (boolean() default: True) - `is_async_program` (boolean() default: False) - `async_streaming` (boolean() default: True) 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. Parameters: - `program` (term()) - `in_place` (boolean() default: True) 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 [ {:colbertv2_post_request, 0, __MODULE__, ""}, {:enable_logging, 0, __MODULE__, "Enables the `DSPyLoggingStream` used by event logging APIs throughout DSPy"}, {:generate_instruction_class, 0, __MODULE__, ""}, {:colbertv2_post_request_v2_wrapped, 0, __MODULE__, ""}, {:has_answer, 2, __MODULE__, "Source: DPR Implementation from Facebook Research"}, {:track_usage, 0, __MODULE__, "Context manager for tracking LM usage."}, {:s_tokenizer, 0, __MODULE__, "Source: DPR Implementation from Facebook Research"}, {:find_data_errors_completion, 1, __MODULE__, ""}, {:normalize_text, 1, __MODULE__, "Normalize text for string and token comparisons."}, {:answer_exact_match, 2, __MODULE__, "Evaluate exact match or F1-thresholded match for an example/prediction pair."}, {:wrap_program, 2, __MODULE__, ""}, {:ensure_signature, 1, __MODULE__, ""}, {:create_directory, 1, __MODULE__, ""}, {:alitellm_text_completion, 2, __MODULE__, ""}, {:process_grouped_by_first_item, 1, __MODULE__, "Requires items in list to already be grouped by first item."}, {:prepare_models_for_resampling, 2, __MODULE__, ""}, {:assert_structural_equivalency, 2, __MODULE__, ""}, {:bootstrap_trace_data, 2, __MODULE__, ""}, {:load_batch_backgrounds, 2, __MODULE__, ""}, {:streamify, 1, __MODULE__, "Wrap a DSPy program so that it streams its outputs incrementally, rather than returning them"}, {:prepare_student, 1, __MODULE__, ""}, {:find_data_error_chat_message, 1, __MODULE__, ""}, {: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"}, {:default_normalize, 1, __MODULE__, ""}, {:get_annotation_name, 1, __MODULE__, ""}, {:locate_answers, 2, __MODULE__, "Returns each occurrence of an answer as (offset, endpos) in terms of *characters*."}, {:f1, 2, __MODULE__, "Compute the maximum token-level F1 score against reference answers."}, {:get_free_port, 0, __MODULE__, "Return a free TCP port on localhost."}, {:merge_dicts, 2, __MODULE__, ""}, {:get_signature, 1, __MODULE__, ""}, {:encode_file_to_dict, 1, __MODULE__, "Encode various file inputs to a dict with file_data, file_id, and/or filename."}, {:groupby_first_item, 1, __MODULE__, ""}, {:append_a_rule, 2, __MODULE__, ""}, {:dpr_normalize, 1, __MODULE__, ""}, {:settings, 0, __MODULE__, "A singleton class for DSPy configuration settings."}, {:int_or_float, 1, __MODULE__, ""}, {:get_program_instruction_set_string, 1, __MODULE__, ""}, {:create_n_fewshot_demo_sets, 7, __MODULE__, "This function is copied from random_search.py, and creates fewshot examples in the same way that random search does."}, {:dpr_tokenize, 1, __MODULE__, "Source: DPR Implementation from Facebook Research"}, {:configure_cache, 0, __MODULE__, "Configure the cache for DSPy."}, {:pretty_print_history, 1, __MODULE__, "Prints the last n prompts and their completions."}, {:run_async, 1, __MODULE__, "Run an async coroutine from a synchronous context."}, {:streaming_response, 1, __MODULE__, "Convert a DSPy program output stream to an OpenAI-compatible output stream that can be"}, {:batch, 2, __MODULE__, ""}, {:print_message, 0, __MODULE__, ""}, {:bootstrap_trace_data, 2, __MODULE__, ""}, {:create_output_dir, 2, __MODULE__, ""}, {:extract_answer, 1, __MODULE__, ""}, {:timestamp, 0, __MODULE__, ""}, {:colbertv2_post_request_v2, 3, __MODULE__, ""}, {:timestamp, 0, __MODULE__, ""}, {:enable_logging, 0, __MODULE__, "Enables the `DSPyLoggingStream` used by event logging APIs throughout DSPy"}, {:convert_langchain_tool, 1, __MODULE__, "Build a DSPy tool from a LangChain tool."}, {:save_candidate_program, 3, __MODULE__, "Save the candidate program to the log directory."}, {:f1_score, 2, __MODULE__, "Compute token-level F1 between prediction and reference (after normalization)."}, {:assert_no_shared_predictor, 2, __MODULE__, ""}, {:save_data, 1, __MODULE__, ""}, {:deduplicate, 1, __MODULE__, "From Raymond Hettinger"}, {:colbertv2_get_request_v2, 3, __MODULE__, ""}, {:single_query_passage, 1, __MODULE__, ""}, {:parse_list_of_instructions, 1, __MODULE__, ""}, {:strip_accents, 1, __MODULE__, "Strips accents from a piece of text."}, {:create_subdir_in_cachedir, 1, __MODULE__, "Create a subdirectory in the DSPy cache directory."}, {:request_cache, 0, __MODULE__, "Decorator for applying caching to a function based on the request argument."}, {:zipstar, 1, __MODULE__, "A much faster A, B, C = zip(*[(a, b, c), (a, b, c), ...])"}, {:truncate_cell, 1, __MODULE__, "Truncate content of a cell to 25 words."}, {:lookup, 2, __MODULE__, "Like get but instead of returning the final value it returns the"}, {:env_worker, 2, __MODULE__, "Worker process: creates a single AlfredTWEnv instance,"}, {:em, 2, __MODULE__, "Compute the Exact Match (EM) metric between a prediction and reference answers."}, {:grouper, 2, __MODULE__, "Collect data into fixed-length chunks or blocks"}, {:set_attribute_by_name, 3, __MODULE__, ""}, {:strip_accents, 1, __MODULE__, "Strips accents from a piece of text."}, {:litellm_completion, 2, __MODULE__, ""}, {:answer_passage_match, 2, __MODULE__, "Return True if any passage in `pred.context` contains the answer(s)."}, {:configure, 0, __MODULE__, ""}, {:set_signature, 2, __MODULE__, ""}, {:with_callbacks, 1, __MODULE__, "Decorator to add callback functionality to instance methods."}, {:print_full_program, 1, __MODULE__, "Print out the program's instructions & prefixes for each module."}, {:get_dependency_versions, 0, __MODULE__, ""}, {:get_unique_lms, 1, __MODULE__, ""}, {:setup_logging, 1, __MODULE__, "Setup logger, which will log our print statements to a txt file at our log_dir for later viewing"}, {:disable_lm_cache, 2, __MODULE__, "Disable the LM cache for all predictors in the program."}, {:get_number_with_suffix, 1, __MODULE__, ""}, {:get_limiter, 0, __MODULE__, ""}, {:download, 1, __MODULE__, ""}, {:eval_candidate_program_with_pruning, 6, __MODULE__, "Evaluation of candidate_program with pruning implemented"}, {:majority, 1, __MODULE__, "Returns the most common completion for the target field (or the last field) in the signature."}, {:get_dspy_source_code, 1, __MODULE__, ""}, {:recursive_mask, 1, __MODULE__, ""}, {:infer_prefix, 1, __MODULE__, "Infer a prefix from an attribute name by converting it to a human-readable format."}, {:zip_first, 2, __MODULE__, ""}, {:infer_data_format, 1, __MODULE__, ""}, {:write_lines, 2, __MODULE__, ""}, {:move_kwargs, 0, __MODULE__, ""}, {:launch_lms, 1, __MODULE__, ""}, {: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."}, {:em_score, 2, __MODULE__, "Compute boolean exact match after normalization."}, {:is_url, 1, __MODULE__, "Check if a string is a valid URL."}, {:find_enum_member, 2, __MODULE__, "Finds the enum member corresponding to the specified identifier, which may be the"}, {:get_token_usage, 1, __MODULE__, "Extract total input tokens and output tokens from a model's interaction history."}, {:prediction_is_dictlike, 1, __MODULE__, ""}, {:set, 3, __MODULE__, "A setattr that supports nested lookups on objects, dicts, lists, and"}, {:infer_prefix, 1, __MODULE__, "Infer a prefix from an attribute name by converting it to a human-readable format."}, {:deduplicate, 1, __MODULE__, "From Raymond Hettinger"}, {:dummy_rm, 0, __MODULE__, ""}, {:delete, 2, __MODULE__, "A delattr that supports deletion of a nested lookups on objects,"}, {:with_callbacks, 1, __MODULE__, "Decorator to add callback functionality to instance methods."}, {:get_task_model_history_for_full_example, 4, __MODULE__, "Get a full trace of the task model's history for a given candidate program."}, {:flatten, 1, __MODULE__, ""}, {:wait_for_server, 1, __MODULE__, "Wait for the server to be ready by polling the /v1/models endpoint."}, {:get_finetune_directory, 0, __MODULE__, ""}, {:answer_exact_match, 2, __MODULE__, "Evaluate exact match or F1-thresholded match for an example/prediction pair."}, {:configure_dspy_loggers, 1, __MODULE__, ""}, {:experimental, 0, __MODULE__, "Decorator / decorator creator for marking APIs experimental in the docstring."}, {:format_field_value, 2, __MODULE__, "Formats the value of the specified field according to the field's DSPy type (input or output),"}, {: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."}, {:create_instruction_set_history_string, 3, __MODULE__, ""}, {:get_number_with_suffix, 1, __MODULE__, ""}, {:calculate_last_n_proposed_quality, 6, __MODULE__, "Calculate the average and best quality of the last n programs proposed. This is useful for seeing if our proposals"}, {:make_signature, 1, __MODULE__, "Create a new Signature subclass with the specified fields and instructions."}, {:create_predictor_level_history_string, 4, __MODULE__, ""}, {:grouper, 2, __MODULE__, "Collect data into fixed-length chunks or blocks"}, {:disable_litellm_logging, 0, __MODULE__, ""}, {:inspect_history, 0, __MODULE__, "The global history shared across all LMs."}, {:p, 0, __MODULE__, "Parameter specification variable."}, {:output_field, 0, __MODULE__, ""}, {:bootstrap_trace_data, 2, __MODULE__, ""}, {:dpr_normalize, 1, __MODULE__, "Source: DPR Implementation from Facebook Research"}, {:int_or_float, 1, __MODULE__, ""}, {:r, 0, __MODULE__, "Type variable."}, {:build_call_data_from_trace, 3, __MODULE__, ""}, {:settings, 0, __MODULE__, "A singleton class for DSPy configuration settings."}, {:recursive_mask, 1, __MODULE__, ""}, {:encode_sft_example, 3, __MODULE__, "This function encodes a single example into a format that can be used for sft training."}, {:split_message_content_for_custom_types, 1, __MODULE__, "Split user message content into a list of content blocks."}, {:is_in_ipython_notebook_environment, 0, __MODULE__, "Check if the current environment is an IPython notebook environment."}, {:encode_audio, 1, __MODULE__, "Encode audio to a dict with 'data' and 'audio_format'."}, {:cache, 0, __MODULE__, "DSPy Cache"}, {:find_predictor_for_stream_listeners, 2, __MODULE__, "Find the predictor for each stream listener."}, {:create_dataset_summary, 3, __MODULE__, ""}, {:zipstar, 1, __MODULE__, "A much faster A, B, C = zip(*[(a, b, c), (a, b, c), ...])"}, {:f1_score, 2, __MODULE__, ""}, {:output_field, 0, __MODULE__, ""}, {:groupby_first_item, 1, __MODULE__, ""}, {:alitellm_responses_completion, 2, __MODULE__, ""}, {:hotpot_f1_score, 2, __MODULE__, "Compute HotPotQA-style token F1 with special labels."}, {:create_directory, 1, __MODULE__, ""}, {:has_answer, 2, __MODULE__, ""}, {:create_minibatch, 1, __MODULE__, "Create a minibatch from the trainset."}, {:display_dataframe, 1, __MODULE__, "Display the specified Pandas DataFrame in the console."}, {:hot_pot_f1, 2, __MODULE__, "Compute the maximum HotPotQA-style F1 score against reference answers."}, {:default_config, 0, __MODULE__, ""}, {:track_usage, 0, __MODULE__, "Context manager for tracking LM usage."}, {:load, 1, __MODULE__, "Load saved DSPy model."}, {:file_tqdm, 1, __MODULE__, ""}, {:load, 1, __MODULE__, "Load saved DSPy model."}, {:syncify, 1, __MODULE__, "Convert an async DSPy module to a sync program."}, {:display, 1, __MODULE__, "Display the specified Python object in the console."}, {:configure_cache, 0, __MODULE__, "Configure the cache for DSPy."}, {:dspy_logging_stream, 0, __MODULE__, "A Python stream for use with event logging APIs throughout DSPy (`eprint()`,"}, {:colbertv2_get_request, 0, __MODULE__, ""}, {:get_field_description_string, 1, __MODULE__, ""}, {:zip_first, 2, __MODULE__, ""}, {:lengths2offsets, 1, __MODULE__, ""}, {:strip_prefix, 1, __MODULE__, ""}, {:inspect_modules, 1, __MODULE__, ""}, {:asyncify, 1, __MODULE__, "Wraps a DSPy program so that it can be called asynchronously. This is useful for running a"}, {:translate_field_type, 2, __MODULE__, ""}, {:configure_dspy_loggers, 1, __MODULE__, ""}, {:kill_lms, 1, __MODULE__, ""}, {:all_predictors_have_lms, 1, __MODULE__, "Return True if all predictors in the program have an LM set."}, {:validate_data_format, 2, __MODULE__, ""}, {:settings, 0, __MODULE__, "A singleton class for DSPy configuration settings."}, {:normalize_text, 1, __MODULE__, "Normalize text for string and token comparisons."}, {:load_settings, 1, __MODULE__, "Load the settings from a file using cloudpickle."}, {:alitellm_completion, 2, __MODULE__, ""}, {:dpr_tokenize, 1, __MODULE__, ""}, {:sync_send_to_stream, 2, __MODULE__, "Send message to stream in a sync context, regardless of event loop state."}, {:make_signature, 1, __MODULE__, "Create a new Signature subclass with the specified fields and instructions."}, {:get, 2, __MODULE__, "A getattr that supports nested lookups on objects, dicts, lists, and"}, {:inspect_modules, 1, __MODULE__, ""}, {:configure_dataframe_for_ipython_notebook_display, 1, __MODULE__, "Set various pandas display options for DataFrame in an IPython notebook environment."}, {:dummy_rm, 0, __MODULE__, ""}, {:parse_value, 2, __MODULE__, ""}, {:load_batch_backgrounds, 2, __MODULE__, ""}, {:streamify, 1, __MODULE__, "Wrap a DSPy program so that it streams its outputs incrementally, rather than returning them"}, {:litellm_text_completion, 2, __MODULE__, ""}, {:print_message, 0, __MODULE__, ""}, {:train_sft_locally, 3, __MODULE__, ""}, {:append_a_demo, 1, __MODULE__, ""}, {:order_input_keys_in_string, 1, __MODULE__, ""}, {:old_getfile, 1, __MODULE__, "Work out which source or compiled file an object was defined in."}, {:save_file_to_log_dir, 2, __MODULE__, ""}, {:new_getfile, 1, __MODULE__, ""}, {:input_field, 0, __MODULE__, ""}, {:infer_prefix, 1, __MODULE__, "Infer a prefix from an attribute name by converting it to a human-readable format."}, {:log_token_usage, 3, __MODULE__, "Extract total input and output tokens used by each model and log to trial_logs[trial_num][\"token_usage\"]."}, {:serialize_for_json, 1, __MODULE__, "Formats the specified value so that it can be serialized as a JSON string."}, {:batch, 2, __MODULE__, ""}, {:inspect_history, 0, __MODULE__, "The global history shared across all LMs."}, {:file_tqdm, 1, __MODULE__, ""}, {:find_data_error_chat, 1, __MODULE__, ""}, {:colbertv2_get_request_v2_wrapped, 0, __MODULE__, ""}, {:locate_answers, 2, __MODULE__, "Returns each occurrence of an answer as (offset, endpos) in terms of *characters*."}, {:disable_logging, 0, __MODULE__, "Disables the `DSPyLoggingStream` used by event logging APIs throughout DSPy"}, {:enable_litellm_logging, 0, __MODULE__, ""}, {:html, 1, __MODULE__, "Obtain the HTML representation of the specified string."}, {:copy_program_with_lms, 1, __MODULE__, ""}, {:eval_candidate_program, 4, __MODULE__, "Evaluate a candidate program on the trainset, using the specified batch size."}, {:get_program_with_highest_avg_score, 2, __MODULE__, "Used as a helper function for bayesian + minibatching optimizers. Returns the program with the highest average score from the batches evaluated so far."}, {:s_tokenizer, 0, __MODULE__, ""}, {:new_to_old_field, 1, __MODULE__, ""}, {:apply_sync_streaming, 1, __MODULE__, "Convert the async streaming generator to a sync generator."}, {:streaming_response, 1, __MODULE__, "Convert a DSPy program output stream to an OpenAI-compatible output stream that can be"}, {:get_dspy_field_type, 1, __MODULE__, ""}, {:context, 0, __MODULE__, "Context manager for temporary configuration changes at the thread level."}, {:is_image, 1, __MODULE__, "Check if the object is an image or a valid media file reference."}, {:answer_passage_match, 2, __MODULE__, "Return True if any passage in `pred.context` contains the answer(s)."}, {:lengths2offsets, 1, __MODULE__, ""}, {:apply_sync_streaming, 1, __MODULE__, "Convert the async streaming generator to a sync generator."}, {:convert_mcp_tool, 2, __MODULE__, "Build a DSPy tool from an MCP tool."}, {:create_example_string, 2, __MODULE__, ""}, {:get_async_max_workers, 0, __MODULE__, ""}, {:process_grouped_by_first_item, 1, __MODULE__, "Requires items in list to already be grouped by first item."}, {:ensure_signature, 1, __MODULE__, "Signature class for DSPy."}, {:recover_lm_cache, 2, __MODULE__, "Recover the LM caches for all predictors in the program to their original state."}, {:precision_score, 2, __MODULE__, "Compute token-level precision of prediction against reference (after normalization)."}, {:encode_image, 1, __MODULE__, "Encode an image or file to a base64 data URI."}, {:gsm8k_metric, 2, __MODULE__, ""}, {:get_prompt_model, 1, __MODULE__, ""}, {:serialize_object, 1, __MODULE__, "Recursively serialize a given object into a JSON-compatible format."}, {:make_signature, 1, __MODULE__, "Create a new Signature subclass with the specified fields and instructions."}, {:flatten, 1, __MODULE__, ""}, {:convert_input_schema_to_tool_args, 1, __MODULE__, "Convert an input json schema to tool arguments compatible with DSPy Tool."}, {:parse_integer_answer, 1, __MODULE__, ""}, {:stylize_metric_name, 2, __MODULE__, "Stylize the cell contents of a pandas DataFrame corresponding to the specified metric name."}, {:experimental, 0, __MODULE__, "Decorator / decorator creator for marking APIs experimental in the docstring."}, {:main_thread_config, 0, __MODULE__, ""}, {:syncify, 1, __MODULE__, "Convert an async DSPy module to a sync program."}, {:litellm_responses_completion, 2, __MODULE__, ""}, {:input_field, 0, __MODULE__, ""}, {:enable_litellm_logging, 0, __MODULE__, ""}, {:pretty_print_history, 1, __MODULE__, "Prints the last n prompts and their completions."}, {:output_field, 0, __MODULE__, ""}, {:input_field, 0, __MODULE__, ""}, {:prepare_teacher, 1, __MODULE__, ""}, {:inspect_history, 0, __MODULE__, "The global history shared across all LMs."} ] end @doc false def __classes__ do [ {Dspy.Propose.ProposeBase.Proposer, "Helper class that provides a standard way to create an ABC using\ninheritance."}, {Dspy.Evaluate.AutoEvaluation.AnswerGroundedness, "Estimate the groundedness of a system's responses, against real retrieved documents written by people.\nYou will first enumerate whatever non-trivial or check-worthy claims are made in the system response, and then\ndiscuss the extent to which some or all of them can be deduced from the retrieved context and basic commonsense."}, {Dspy.Dsp.Utils.Dpr.Tokens, "A class to represent a list of tokenized text."}, {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.Predict.RLMClass, "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.Clients.BaseLMClass, "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.Dsp.Utils.DotdictLax, "dict() -> new empty dictionary\ndict(mapping) -> new dictionary initialized from a mapping object's\n (key, value) pairs\ndict(iterable) -> new dictionary initialized as if via:\n d = {}\n for k, v in iterable:\n d[k] = v\ndict(**kwargs) -> new dictionary initialized with the name=value pairs\n in the keyword argument list. For example: dict(one=1, two=2)"}, {Dspy.Teleprompt.Bettertogether.BetterTogether, ""}, {Dspy.Evaluate.CompleteAndGrounded, ""}, {Dspy.OldOutputField, "A more ergonomic datatype that infers prefix and desc if omitted."}, {Dspy.Clients.Openai.OpenAIProvider, ""}, {Dspy.Teleprompt.TelepromptOptuna.BootstrapFewShotWithOptuna, ""}, {Dspy.Teleprompt.Gepa.GepaUtils.PredictorFeedbackFn, "Base class for protocol classes.\n\nProtocol classes are defined as::\n\n class Proto(Protocol):\n def meth(self) -> int:\n ...\n\nSuch classes are primarily used with static type checkers that recognize\nstructural subtyping (static duck-typing).\n\nFor example::\n\n class C:\n def meth(self) -> int:\n return 0\n\n def func(x: Proto) -> int:\n return x.meth()\n\n func(C()) # Passes static type check\n\nSee PEP 544 for details. Protocol classes decorated with\n@typing.runtime_checkable act as simple-minded runtime protocols that check\nonly the presence of given attributes, ignoring their type signatures.\nProtocol classes can be generic, they are defined as::\n\n class GenProto[T](Protocol):\n def meth(self) -> T:\n ..."}, {Dspy.BootstrapFewShotWithRandomSearch, ""}, {Dspy.Adapters.Types.Audio.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.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.Primitives.ReplTypes.REPLHistory, "Container for REPL interaction history.\n\nImmutable: append() returns a new instance with the entry added."}, {Dspy.Predict.CodeActClass, "CodeAct is a module that utilizes the Code Interpreter and predefined tools to solve the problem."}, {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.Datasets.Alfworld.AlfWorld, ""}, {Dspy.Predict.Parameter, ""}, {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.Teleprompt.BootstrapTrace.TraceData, "dict() -> new empty dictionary\ndict(mapping) -> new dictionary initialized from a mapping object's\n (key, value) pairs\ndict(iterable) -> new dictionary initialized as if via:\n d = {}\n for k, v in iterable:\n d[k] = v\ndict(**kwargs) -> new dictionary initialized with the name=value pairs\n in the keyword argument list. For example: dict(one=1, two=2)"}, {Dspy.Teleprompt.BootstrapFinetuneClass, ""}, {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.Propose.GroundedProposer.GroundedProposer, "Helper class that provides a standard way to create an ABC using\ninheritance."}, {Dspy.Dsp.Utils.SettingsClass, "A singleton class for DSPy configuration settings.\nThread-safe global configuration.\n- 'configure' can be called by only one 'owner' thread (the first thread that calls it).\n- Other threads see the configured global values from 'main_thread_config'.\n- 'context' sets thread-local overrides. These overrides propagate to threads spawned\n inside that context block, when (and only when!) using a ParallelExecutor that copies overrides.\n\n 1. Only one unique thread (which can be any thread!) can call dspy.configure.\n 2. It affects a global state, visible to all. As a result, user threads work, but they shouldn't be\n mixed with concurrent changes to dspy.configure from the \"main\" thread.\n (TODO: In the future, add warnings: if there are near-in-time user-thread reads followed by .configure calls.)\n 3. Any thread can use dspy.context. It propagates to child threads created with DSPy primitives: Parallel, asyncify, etc."}, {Dspy.Teleprompt.BootstrapFewShot, ""}, {Dspy.Clients.UtilsFinetune.Message, "dict() -> new empty dictionary\ndict(mapping) -> new dictionary initialized from a mapping object's\n (key, value) pairs\ndict(iterable) -> new dictionary initialized as if via:\n d = {}\n for k, v in iterable:\n d[k] = v\ndict(**kwargs) -> new dictionary initialized with the name=value pairs\n in the keyword argument list. For example: dict(one=1, two=2)"}, {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.Dsp.Colbertv2.ColBERTv2, "Wrapper for the ColBERTv2 Retrieval."}, {Dspy.Teleprompt.Gepa.InstructionProposal.ToolProposer, "Proposer for optimizing tool-using module configurations.\n\nSupports two types of modules:\n- Tool modules (1 predictor): Optimizes predictor instruction and tool descriptions\n- ReAct modules (2 predictors): Jointly optimizes react instruction, extract instruction, and tool descriptions\n\nUses dynamic signature generation to create output fields for each tool and parameter,\nenabling the reflection LM to optimize all components cohesively based on execution feedback.\n\nThis joint optimization approach allows the LM to see how instructions and tool descriptions\nwork together, leading to more coherent improvements than optimizing each component separately."}, {Dspy.Predict.BestOfNClass, ""}, {Dspy.Primitives.ExampleClass, "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.Teleprompt.Gepa.InstructionProposal.GenerateImprovedToolModuleDescriptionsFromFeedback, "I provided an assistant with predictor instructions and tool descriptions,\nbut its performance needs improvement based on the examples_with_feedback below.\n\nYour task is to propose better predictor instructions, tool descriptions, and tool argument descriptions that address the issues shown in these examples.\nFocus on reinforcing patterns that clearly improve the assistant's performance on similar tasks, rather than rewriting everything from scratch unless necessary.\nThese components are progressively optimized - refine only what needs to change.\n\nAnalyze the examples_with_feedback to identify success and failure patterns, and write improved instructions and descriptions at their appropriate level of abstraction and/or specificity,\nso that each layer plays a clear, complementary role without unnecessary repetition or verbosity unless redundancy clearly helps the assistant's performance."}, {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.Predict.Avatar.Avatar.Avatar, ""}, {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.Evaluate.AutoEvaluation.DecompositionalSemanticRecallPrecision, "Compare a system's response to the ground truth to compute recall and precision of key ideas.\nYou will first enumerate key ideas in each response, discuss their overlap, and then report recall and precision."}, {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.Primitives.ModuleClass, ""}, {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.Streaming.Messages.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.Predict.Avatar.Models.Tool, "!!! abstract \"Usage Documentation\"\n [Models](../concepts/models.md)\n\nA base class for creating Pydantic models.\n\nAttributes:\n __class_vars__: The names of the class variables defined on the model.\n __private_attributes__: Metadata about the private attributes of the model.\n __signature__: The synthesized `__init__` [`Signature`][inspect.Signature] of the model.\n\n __pydantic_complete__: Whether model building is completed, or if there are still undefined fields.\n __pydantic_core_schema__: The core schema of the model.\n __pydantic_custom_init__: Whether the model has a custom `__init__` function.\n __pydantic_decorators__: Metadata containing the decorators defined on the model.\n This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.\n __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to\n __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.\n __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.\n __pydantic_post_init__: The name of the post-init method for the model, if defined.\n __pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel].\n __pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model.\n __pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model.\n\n __pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.\n __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.\n\n __pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra]\n is set to `'allow'`.\n __pydantic_fields_set__: The names of fields explicitly set during instantiation.\n __pydantic_private__: Values of private attributes set on the model instance."}, {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.Dsp.Utils.Tokenizer, "Base tokenizer class.\nTokenizers implement tokenize, which should return a Tokens class."}, {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.Dsp.Utils.SimpleTokenizer, "Base tokenizer class.\nTokenizers implement tokenize, which should return a Tokens class."}, {Dspy.Datasets.Dataset, ""}, {Dspy.Primitives.BaseModuleClass, ""}, {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.Predict.ParallelClass, ""}, {Dspy.Adapters.Types.CodeClass, "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.Types.ImageClass, "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.Predict.Avatar.Signatures.Actor, "You will be given `Tools` which will be a list of tools to use to accomplish the `Goal`. Given the user query, your task is to decide which tool to use and what input values to provide.\n\nYou will output action needed to accomplish the `Goal`. `Action` should have a tool to use and the input query to pass to the tool.\n\nNote: You can opt to use no tools and provide the final answer directly. You can also one tool multiple times with different input queries if applicable."}, {Dspy.LM, "A language model supporting chat or text completion requests for use with DSPy modules."}, {Dspy.Propose.GroundedProposer.DescribeProgram, "Below is some pseudo-code for a pipeline that solves tasks with calls to language models. Please describe what type of task this program appears to be designed to solve, and how it appears to work."}, {Dspy.Evaluate.SemanticF1, ""}, {Dspy.Signatures.Field.OldOutputField, "A more ergonomic datatype that infers prefix and desc if omitted."}, {Dspy.Streaming.StatusMessage, "Dataclass that wraps a status message for status streaming."}, {Dspy.Utils.Unbatchify, ""}, {Dspy.Primitives.PredictionClass, "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.Dsp.Utils.Dpr.Tokenizer, "Base tokenizer class.\nTokenizers implement tokenize, which should return a Tokens class."}, {Dspy.InferRules, ""}, {Dspy.Dsp.Utils.Utils.Dotdict, "dict() -> new empty dictionary\ndict(mapping) -> new dictionary initialized from a mapping object's\n (key, value) pairs\ndict(iterable) -> new dictionary initialized as if via:\n d = {}\n for k, v in iterable:\n d[k] = v\ndict(**kwargs) -> new dictionary initialized with the name=value pairs\n in the keyword argument list. For example: dict(one=1, two=2)"}, {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.Teleprompt.BootstrapFinetune.FinetuneTeleprompter, ""}, {Dspy.Clients.Provider, ""}, {Dspy.Clients.Embedding.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.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.Teleprompt.SignatureOpt.SignatureOptimizer, ""}, {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.Predict.Avatar.Actor, "You will be given `Tools` which will be a list of tools to use to accomplish the `Goal`. Given the user query, your task is to decide which tool to use and what input values to provide.\n\nYou will output action needed to accomplish the `Goal`. `Action` should have a tool to use and the input query to pass to the tool.\n\nNote: You can opt to use no tools and provide the final answer directly. You can also one tool multiple times with different input queries if applicable."}, {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.Teleprompt.InferRulesClass, ""}, {Dspy.Program, ""}, {Dspy.Clients.ProviderClass, ""}, {Dspy.Clients.UtilsFinetune.TrainDataFormat, "str(object='') -> str\nstr(bytes_or_buffer[, encoding[, errors]]) -> str\n\nCreate a new string object from the given object. If encoding or\nerrors is specified, then the object must expose a data buffer\nthat will be decoded using the given encoding and error handler.\nOtherwise, returns the result of object.__str__() (if defined)\nor repr(object).\nencoding defaults to sys.getdefaultencoding().\nerrors defaults to 'strict'."}, {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.Teleprompt.Bootstrap.BootstrapFewShot, ""}, {Dspy.Adapters.Base.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.Predict.BestOfN, ""}, {Dspy.Signatures.Signature.Signature, "Signature class for DSPy.\n\nYou typically subclass the Signature class, like this:\n class MySignature(dspy.Signature):\n input: str = InputField(desc=\"...\")\n output: int = OutputField(desc=\"...\")\n\nYou can call Signature(\"input1, input2 -> output1, output2\") to create a new signature type.\nYou can also include instructions, Signature(\"input -> output\", \"This is a test\").\nBut it's generally better to use the make_signature function.\n\nIf you are not sure if your input is a string representation, (like \"input1, input2 -> output1, output2\"),\nor a signature, you can use the ensure_signature function.\n\nFor compatibility with the legacy dsp format, you can use the signature_to_template function."}, {Dspy.Utils.DummyVectorizer, "Simple vectorizer based on n-grams."}, {Dspy.Predict.Refine.OfferFeedback, "In the discussion, assign blame to each module that contributed to the final reward being below the threshold, if\nany. Then, prescribe concrete advice of how the module should act on its future input when we retry the process, if\nit were to receive the same or similar inputs. If a module is not to blame, the advice should be N/A.\nThe module will not see its own history, so it needs to rely on entirely concrete and actionable advice from you\nto avoid the same mistake on the same or similar inputs."}, {Dspy.Clients.Databricks.TrainingJobDatabricks, "Represents the result of an asynchronous computation."}, {Dspy.Teleprompt.AvatarOptimizerClass, ""}, {Dspy.Datasets.ColorsClass, ""}, {Dspy.Primitives.CodeInterpreter.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.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.Teleprompt.AvatarOptimizer.EvalResult, "!!! abstract \"Usage Documentation\"\n [Models](../concepts/models.md)\n\nA base class for creating Pydantic models.\n\nAttributes:\n __class_vars__: The names of the class variables defined on the model.\n __private_attributes__: Metadata about the private attributes of the model.\n __signature__: The synthesized `__init__` [`Signature`][inspect.Signature] of the model.\n\n __pydantic_complete__: Whether model building is completed, or if there are still undefined fields.\n __pydantic_core_schema__: The core schema of the model.\n __pydantic_custom_init__: Whether the model has a custom `__init__` function.\n __pydantic_decorators__: Metadata containing the decorators defined on the model.\n This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.\n __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to\n __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.\n __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.\n __pydantic_post_init__: The name of the post-init method for the model, if defined.\n __pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel].\n __pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model.\n __pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model.\n\n __pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.\n __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.\n\n __pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra]\n is set to `'allow'`.\n __pydantic_fields_set__: The names of fields explicitly set during instantiation.\n __pydantic_private__: Values of private attributes set on the model instance."}, {Dspy.Primitives.CodeInterpreterClass, "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.Predict.React.ReAct, ""}, {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.Retrievers.Retrieve.Retrieve, ""}, {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.Utils.UsageTrackerClass3, "Tracks LM usage data within a context."}, {Dspy.Clients.Cache.Cache, "DSPy Cache\n\n`Cache` provides 2 levels of caching (in the given order):\n 1. In-memory cache - implemented with cachetools.LRUCache\n 2. On-disk cache - implemented with diskcache.FanoutCache"}, {Dspy.Utils.Parallelizer.ParallelExecutor, ""}, {Dspy.Adapters.ChatAdapterClass, "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.Avatar.Action, "!!! abstract \"Usage Documentation\"\n [Models](../concepts/models.md)\n\nA base class for creating Pydantic models.\n\nAttributes:\n __class_vars__: The names of the class variables defined on the model.\n __private_attributes__: Metadata about the private attributes of the model.\n __signature__: The synthesized `__init__` [`Signature`][inspect.Signature] of the model.\n\n __pydantic_complete__: Whether model building is completed, or if there are still undefined fields.\n __pydantic_core_schema__: The core schema of the model.\n __pydantic_custom_init__: Whether the model has a custom `__init__` function.\n __pydantic_decorators__: Metadata containing the decorators defined on the model.\n This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.\n __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to\n __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.\n __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.\n __pydantic_post_init__: The name of the post-init method for the model, if defined.\n __pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel].\n __pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model.\n __pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model.\n\n __pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.\n __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.\n\n __pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra]\n is set to `'allow'`.\n __pydantic_fields_set__: The names of fields explicitly set during instantiation.\n __pydantic_private__: Values of private attributes set on the model instance."}, {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.Clients.UtilsFinetune.MessageAssistant, "dict() -> new empty dictionary\ndict(mapping) -> new dictionary initialized from a mapping object's\n (key, value) pairs\ndict(iterable) -> new dictionary initialized as if via:\n d = {}\n for k, v in iterable:\n d[k] = v\ndict(**kwargs) -> new dictionary initialized with the name=value pairs\n in the keyword argument list. For example: dict(one=1, two=2)"}, {Dspy.Teleprompt.BootstrapFinetune.BootstrapFinetune, ""}, {Dspy.Datasets.MATH, ""}, {Dspy.Dsp.Utils.Dpr.SimpleTokenizer, "Base tokenizer class.\nTokenizers implement tokenize, which should return a Tokens class."}, {Dspy.Predict.ChainOfThoughtClass, ""}, {Dspy.Adapters.XMLAdapterClass, "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.Types.AudioClass, "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.Predict.Avatar.ActionOutput, "!!! abstract \"Usage Documentation\"\n [Models](../concepts/models.md)\n\nA base class for creating Pydantic models.\n\nAttributes:\n __class_vars__: The names of the class variables defined on the model.\n __private_attributes__: Metadata about the private attributes of the model.\n __signature__: The synthesized `__init__` [`Signature`][inspect.Signature] of the model.\n\n __pydantic_complete__: Whether model building is completed, or if there are still undefined fields.\n __pydantic_core_schema__: The core schema of the model.\n __pydantic_custom_init__: Whether the model has a custom `__init__` function.\n __pydantic_decorators__: Metadata containing the decorators defined on the model.\n This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.\n __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to\n __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.\n __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.\n __pydantic_post_init__: The name of the post-init method for the model, if defined.\n __pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel].\n __pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model.\n __pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model.\n\n __pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.\n __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.\n\n __pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra]\n is set to `'allow'`.\n __pydantic_fields_set__: The names of fields explicitly set during instantiation.\n __pydantic_private__: Values of private attributes set on the model instance."}, {Dspy.Clients.Provider.ReinforceJob, ""}, {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.Propose.GroundedProposer.DescribeModule, "Below is some pseudo-code for a pipeline that solves tasks with calls to language models. Please describe the purpose of one of the specified module in this pipeline."}, {Dspy.Propose.DatasetSummaryGenerator.DatasetDescriptor, "Given several examples from a dataset please write observations about trends that hold for most or all of the samples. Some areas you may consider in your observations: topics, content, syntax, conciseness, etc. It will be useful to make an educated guess as to the nature of the task this dataset will enable. Don't be afraid to be creative"}, {Dspy.Signature, ""}, {Dspy.BetterTogether, ""}, {Dspy.Teleprompt.EnsembleClass, ""}, {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.Streaming.StreamingListener.StreamListener, "Class that listens to the stream to capture the streeaming of a specific output field of a predictor."}, {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.Avatar.Models.ActionOutput, "!!! abstract \"Usage Documentation\"\n [Models](../concepts/models.md)\n\nA base class for creating Pydantic models.\n\nAttributes:\n __class_vars__: The names of the class variables defined on the model.\n __private_attributes__: Metadata about the private attributes of the model.\n __signature__: The synthesized `__init__` [`Signature`][inspect.Signature] of the model.\n\n __pydantic_complete__: Whether model building is completed, or if there are still undefined fields.\n __pydantic_core_schema__: The core schema of the model.\n __pydantic_custom_init__: Whether the model has a custom `__init__` function.\n __pydantic_decorators__: Metadata containing the decorators defined on the model.\n This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.\n __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to\n __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.\n __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.\n __pydantic_post_init__: The name of the post-init method for the model, if defined.\n __pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel].\n __pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model.\n __pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model.\n\n __pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.\n __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.\n\n __pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra]\n is set to `'allow'`.\n __pydantic_fields_set__: The names of fields explicitly set during instantiation.\n __pydantic_private__: Values of private attributes set on the model instance."}, {Dspy.Predict.MultiChainComparison, ""}, {Dspy.Signatures.SignatureClass, ""}, {Dspy.Teleprompt.Teleprompt.Teleprompter, ""}, {Dspy.Dsp.Utils.Utils.NullContextManager, ""}, {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.Predict.Predict.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.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.Types.Citation.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.Streaming.Messages.StreamResponse, "StreamResponse(predict_name: str, signature_field_name: str, chunk: str, is_last_chunk: bool)"}, {Dspy.Signatures.Field.OldInputField, "A more ergonomic datatype that infers prefix and desc if omitted."}, {Dspy.Adapters.Types.Tool.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.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.Adapters.Types.Tool.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.Primitives.CodeInterpreter.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.Teleprompt.InferRules.RulesInductionProgram, ""}, {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.Datasets.Hotpotqa.HotPotQA, ""}, {Dspy.BootstrapFewShotWithOptuna, ""}, {Dspy.Teleprompt.Gepa.InstructionProposal.SingleComponentMultiModalProposer, "dspy.Module for proposing improved instructions based on feedback."}, {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.Clients.Provider.TrainingJob, "Represents the result of an asynchronous computation."}, {Dspy.Retrieve, ""}, {Dspy.Predict.Avatar.Models.Action, "!!! abstract \"Usage Documentation\"\n [Models](../concepts/models.md)\n\nA base class for creating Pydantic models.\n\nAttributes:\n __class_vars__: The names of the class variables defined on the model.\n __private_attributes__: Metadata about the private attributes of the model.\n __signature__: The synthesized `__init__` [`Signature`][inspect.Signature] of the model.\n\n __pydantic_complete__: Whether model building is completed, or if there are still undefined fields.\n __pydantic_core_schema__: The core schema of the model.\n __pydantic_custom_init__: Whether the model has a custom `__init__` function.\n __pydantic_decorators__: Metadata containing the decorators defined on the model.\n This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.\n __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to\n __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.\n __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.\n __pydantic_post_init__: The name of the post-init method for the model, if defined.\n __pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel].\n __pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model.\n __pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model.\n\n __pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.\n __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.\n\n __pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra]\n is set to `'allow'`.\n __pydantic_fields_set__: The names of fields explicitly set during instantiation.\n __pydantic_private__: Values of private attributes set on the model instance."}, {Dspy.Primitives.Prediction.Completions, ""}, {Dspy.Retrievers.EmbeddingsClass, ""}, {Dspy.Dsp.Colbertv2.ColBERTv2RerankerLocal, ""}, {Dspy.Clients.UtilsFinetune.GRPOStatus, "dict() -> new empty dictionary\ndict(mapping) -> new dictionary initialized from a mapping object's\n (key, value) pairs\ndict(iterable) -> new dictionary initialized as if via:\n d = {}\n for k, v in iterable:\n d[k] = v\ndict(**kwargs) -> new dictionary initialized with the name=value pairs\n in the keyword argument list. For example: dict(one=1, two=2)"}, {Dspy.Datasets.DatasetClass, ""}, {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.Primitives.Module.ProgramMeta, "Metaclass ensuring every ``dspy.Module`` instance is properly initialised."}, {Dspy.Utils.StatusMessage, "Dataclass that wraps a status message for status streaming."}, {Dspy.Clients.UtilsFinetune.GRPOGroup, "dict() -> new empty dictionary\ndict(mapping) -> new dictionary initialized from a mapping object's\n (key, value) pairs\ndict(iterable) -> new dictionary initialized as if via:\n d = {}\n for k, v in iterable:\n d[k] = v\ndict(**kwargs) -> new dictionary initialized with the name=value pairs\n in the keyword argument list. For example: dict(one=1, two=2)"}, {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.Datasets.Gsm8k.GSM8K, ""}, {Dspy.Evaluate.AutoEvaluation.SemanticF1, ""}, {Dspy.Utils.Exceptions.AdapterParseError, "Exception raised when adapter cannot parse the LM response."}, {Dspy.Dsp.Utils.Tokens, "A class to represent a list of tokenized text."}, {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.Teleprompt.Gepa.InstructionProposal.GenerateEnhancedMultimodalInstructionFromFeedback, "I provided an assistant with instructions to perform a task involving visual content, but the assistant's performance needs improvement based on the examples and feedback below.\n\nYour task is to write a better instruction for the assistant that addresses the specific issues identified in the feedback, with particular attention to how visual and textual information should be analyzed and integrated.\n\n## Analysis Steps:\n1. **Read the inputs carefully** and identify both the visual and textual input formats, understanding how they work together\n2. **Read all the assistant responses and corresponding feedback** to understand what went wrong with visual analysis, text processing, or their integration\n3. **Identify visual analysis patterns** - what visual features, relationships, or details are important for this task\n4. **Identify domain-specific knowledge** about both visual and textual aspects, as this information may not be available to the assistant in the future\n5. **Look for successful visual-textual integration strategies** and include these patterns in the instruction\n6. **Address specific visual analysis issues** mentioned in the feedback\n\n## Instruction Requirements:\n- **Clear task definition** explaining how to process both visual and textual inputs\n- **Visual analysis guidance** specific to this task (what to look for, how to describe, what features matter)\n- **Integration strategies** for combining visual observations with textual information\n- **Domain-specific knowledge** about visual concepts, terminology, or relationships\n- **Error prevention guidance** for common visual analysis mistakes shown in the feedback\n- **Precise, actionable language** for both visual and textual processing\n\nFocus on creating an instruction that helps the assistant properly analyze visual content, integrate it with textual information, and avoid the specific visual analysis mistakes shown in the examples."}, {Dspy.KNN, ""}, {Dspy.Predict.PredictClass3, "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.Gepa.InstructionProposal.MultiModalInstructionProposer, "GEPA-compatible multimodal instruction proposer.\n\nThis class handles multimodal inputs (like dspy.Image) during GEPA optimization by using\na single-component proposer for each component that needs to be updated."}, {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.Signatures.Field.OldField, "A more ergonomic datatype that infers prefix and desc if omitted."}, {Dspy.Streaming.Messages.StatusStreamingCallback, "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.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.Dsp.Utils.NullContextManager, ""}, {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.Clients.Openai.TrainingJobOpenAI, "Represents the result of an asynchronous computation."}, {Dspy.Utils.Dummies.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.Utils.Hasher, "Hasher that accepts python objects as inputs."}, {Dspy.Predict.RefineClass, ""}, {Dspy.Teleprompt.BootstrapTrace.FailedPrediction, "FailedPrediction(completion_text: str, format_reward: float | None = None)"}, {Dspy.Parallel, ""}, {Dspy.Teleprompt.AvatarOptimizer.FeedbackBasedInstruction, "There is a task that needs to be completed for which one can use multiple tools to achieve the desired outcome. A group's performance was evaluated on a dataset of inputs, the inputs that did well are positive inputs, and the inputs that did not do well are negative inputs.\n\nYou received feedback on how they can better use the tools to improve your performance on the negative inputs. You have been provided with the previous instruction, that they followed to use tools to complete the task, and the feedback on your performance.\n\nYour task is to incorporate the feedback and generate a detailed instruction for the group to follow to improve their performance on the task.\n\nMake sure that the new instruction talks about how to use the tools effectively and should be no more than 3 paragraphs long. The previous instruction contains general guidelines that you must retain in the new instruction."}, {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.Adapters.Types.FileClass, "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.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.Teleprompt.Gepa.Gepa.GEPAFeedbackMetric, "Experimental: This class may change or be removed in a future release without warning (introduced in v3.0.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.Teleprompt.CoproOptimizer.BasicGenerateInstruction, "You are an instruction optimizer for large language models. I will give you a ``signature`` of fields (inputs and outputs) in English. Your task is to propose an instruction that will lead a good language model to perform the task well. Don't be afraid to be creative."}, {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.Dsp.Utils.Utils.DotdictLax, "dict() -> new empty dictionary\ndict(mapping) -> new dictionary initialized from a mapping object's\n (key, value) pairs\ndict(iterable) -> new dictionary initialized as if via:\n d = {}\n for k, v in iterable:\n d[k] = v\ndict(**kwargs) -> new dictionary initialized with the name=value pairs\n in the keyword argument list. For example: dict(one=1, two=2)"}, {Dspy.Evaluate.Evaluate.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.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.Datasets.Alfworld.Alfworld.AlfWorld, ""}, {Dspy.Propose.GroundedProposerClass3, "Helper class that provides a standard way to create an ABC using\ninheritance."}, {Dspy.Adapters.JSONAdapterClass, "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.BootstrapFinetune, ""}, {Dspy.Datasets.MATHClass, ""}, {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.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.Teleprompt.Gepa.GepaUtils.ScoreWithFeedback, "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.InferRules, ""}, {Dspy.Teleprompt.Vanilla.LabeledFewShot, ""}, {Dspy.Teleprompt.Gepa.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.StreamResponse, "StreamResponse(predict_name: str, signature_field_name: str, chunk: str, is_last_chunk: bool)"}, {Dspy.Dsp.Utils.Settings.Settings, "A singleton class for DSPy configuration settings.\nThread-safe global configuration.\n- 'configure' can be called by only one 'owner' thread (the first thread that calls it).\n- Other threads see the configured global values from 'main_thread_config'.\n- 'context' sets thread-local overrides. These overrides propagate to threads spawned\n inside that context block, when (and only when!) using a ParallelExecutor that copies overrides.\n\n 1. Only one unique thread (which can be any thread!) can call dspy.configure.\n 2. It affects a global state, visible to all. As a result, user threads work, but they shouldn't be\n mixed with concurrent changes to dspy.configure from the \"main\" thread.\n (TODO: In the future, add warnings: if there are near-in-time user-thread reads followed by .configure calls.)\n 3. Any thread can use dspy.context. It propagates to child threads created with DSPy primitives: Parallel, asyncify, etc."}, {Dspy.Teleprompt.AvatarOptimizer.Comparator, "After executing the given actions on user inputs using the given instruction, some inputs have yielded good, results, while others have not. I'll provide you the inputs along with their, corresponding evaluation metrics:\n\nTask:\n(1) Firstly, identify and contrast the patterns of inputs that have achieved good results with those that have not.\n(2) Then, review the computational logic for any inconsistencies in the previous actions.\n(3) Lastly, specify the modification in tools used that can lead to improved performance on the negative inputs."}, {Dspy.Propose.GroundedProposer.GenerateModuleInstruction, ""}, {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.Adapters.TwoStepAdapterClass, "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.Teleprompt.RandomSearch.BootstrapFewShotWithRandomSearch, ""}, {Dspy.Predict.Refine.Refine, ""}, {Dspy.Signatures.OldField, "A more ergonomic datatype that infers prefix and desc if omitted."}, {Dspy.Teleprompt.GRPO, ""}, {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.Propose.DatasetSummaryGenerator.ObservationSummarizer, "Given a series of observations I have made about my dataset, please summarize them into a brief 2-3 sentence summary which highlights only the most important details."}, {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.Teleprompt.MiproOptimizerV2.MIPROv2, ""}, {Dspy.Primitives.ReplTypes.REPLEntry, "A single REPL interaction entry containing reasoning, code, and output."}, {Dspy.Evaluate.AutoEvaluation.AnswerCompleteness, "Estimate the completeness of a system's responses, against the ground truth.\nYou will first enumerate key ideas in each response, discuss their overlap, and then report completeness."}, {Dspy.Teleprompt.BootstrapFewShotWithOptuna, ""}, {Dspy.Predict.ChainOfThought, ""}, {Dspy.Teleprompt.CoproOptimizer.GenerateInstructionGivenAttempts, "You are an instruction optimizer for large language models. I will give some task instructions I've tried, along with their corresponding validation scores. The instructions are arranged in increasing order based on their scores, where higher scores indicate better quality.\n\nYour task is to propose a new instruction that will lead a good language model to perform the task even better. Don't be afraid to be creative."}, {Dspy.Adapters.Types.File.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.Utils.Dummies.DummyVectorizer, "Simple vectorizer based on n-grams."}, {Dspy.Predict.Avatar.AvatarClass, ""}, {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.Utils.LoggingUtils.DSPyLoggingStream, "A Python stream for use with event logging APIs throughout DSPy (`eprint()`,\n`logger.info()`, etc.). This stream wraps `sys.stderr`, forwarding `write()` and\n`flush()` calls to the stream referred to by `sys.stderr` at the time of the call.\nIt also provides capabilities for disabling the stream to silence event logs."}, {Dspy.Refine, ""}, {Dspy.Completions, ""}, {Dspy.MIPROv2, ""}, {Dspy.Datasets.Dataloader.DataLoader, ""}, {Dspy.Primitives.Module.Module, ""}, {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.Adapters.Types.BaseType.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.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.Adapters.BAMLAdapter, "A DSPy adapter that improves the rendering of complex/nested Pydantic models to help LMs.\n\nThis adapter generates a compact, human-readable schema representation for nested Pydantic output\nfields, inspired by the BAML project's JSON formatter (https://github.com/BoundaryML/baml).\nThe resulting rendered schema is more token-efficient and easier for smaller LMs to follow than a\nraw JSON schema. It also includes Pydantic field descriptions as comments in the schema, which\nprovide valuable additional context for the LM to understand the expected output.\n\nExample Usage:\n```python\nimport dspy\nfrom pydantic import BaseModel, Field\nfrom typing import Literal\nfrom baml_adapter import BAMLAdapter # Import from your module\n\n# 1. Define your Pydantic models\nclass PatientAddress(BaseModel):\n street: str\n city: str\n country: Literal[\"US\", \"CA\"]\n\nclass PatientDetails(BaseModel):\n name: str = Field(description=\"Full name of the patient.\")\n age: int\n address: PatientAddress | None\n\n# 2. Define a signature using the Pydantic model as an output field\nclass ExtractPatientInfo(dspy.Signature):\n '''Extract patient information from the clinical note.'''\n clinical_note: str = dspy.InputField()\n patient_info: PatientDetails = dspy.OutputField()\n\n# 3. Configure dspy to use the new adapter\nllm = dspy.OpenAI(model=\"gpt-4.1-mini\")\ndspy.configure(lm=llm, adapter=BAMLAdapter())\n\n# 4. Run your program\nextractor = dspy.Predict(ExtractPatientInfo)\nnote = \"John Doe, 45 years old, lives at 123 Main St, Anytown. Resident of the US.\"\nresult = extractor(clinical_note=note)\nprint(result.patient_info)\n\n# Expected output:\n# PatientDetails(name='John Doe', age=45, address=PatientAddress(street='123 Main St', city='Anytown', country='US'))\n```"}, {Dspy.Teleprompt.SIMBAClass, "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.ChainOfThoughtWithHint, ""}, {Dspy.Predict.KNN, ""}, {Dspy.Teleprompt.SimbaUtils.OfferFeedback, "You will be given two trajectories of an LLM-driven program's execution. Your goal is to help the program's modules\nbuild up experience on how to maximize the reward value assigned to the program's outputs if it were to receive\nsimilar inputs in the future.\n\nThe module won't see its own history. It will rely on your advice balancing being concrete and being generalizable.\n\nIn your advice:\n- Avoid boilerplate. Offer advice that would change the module's behavior for the better in the future.\n- Ensure that advice offered to a module M is specific to that M's specific sub-task, not the overall program.\n- Rely on contrasting the behavior of the worse trajectory against the better trajectory in making recommendations.\n- Ensure each unique module name appears exactly once as a key in the advice dictionary."}, {Dspy.Teleprompt.BetterTogether, ""}, {Dspy.Dsp.Utils.Dotdict, "dict() -> new empty dictionary\ndict(mapping) -> new dictionary initialized from a mapping object's\n (key, value) pairs\ndict(iterable) -> new dictionary initialized as if via:\n d = {}\n for k, v in iterable:\n d[k] = v\ndict(**kwargs) -> new dictionary initialized with the name=value pairs\n in the keyword argument list. For example: dict(one=1, two=2)"}, {Dspy.Evaluate.EvaluateClass3, "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.Predict.KNNClass, ""}, {Dspy.Clients.Databricks.DatabricksProvider, ""}, {Dspy.Adapters.ChatAdapter.FieldInfoWithName, "FieldInfoWithName(name, info)"}, {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.Clients.LmLocal.LocalProvider, ""}, {Dspy.Streaming.Messages.StatusMessage, "Dataclass that wraps a status message for status streaming."}, {Dspy.Clients.LMClass, "A language model supporting chat or text completion requests for use with DSPy modules."}, {Dspy.Teleprompt.CoproOptimizer.COPRO, ""}, {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.ReasoningClass, "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.Teleprompt.Gepa.Gepa.DspyGEPAResult, "Experimental: This class may change or be removed in a future release without warning (introduced in v3.0.0).\n\n\nAdditional data related to the GEPA run.\n\nFields:\n- candidates: list of proposed candidates (component_name -> component_text)\n- parents: lineage info; for each candidate i, parents[i] is a list of parent indices or None\n- val_aggregate_scores: per-candidate aggregate score on the validation set (higher is better)\n- val_subscores: per-candidate per-instance scores on the validation set (len == num_val_instances)\n- per_val_instance_best_candidates: for each val instance t, a set of candidate indices achieving the best score on t\n- discovery_eval_counts: Budget (number of metric calls / rollouts) consumed up to the discovery of each candidate\n\n- total_metric_calls: total number of metric calls made across the run\n- num_full_val_evals: number of full validation evaluations performed\n- log_dir: where artifacts were written (if any)\n- seed: RNG seed for reproducibility (if known)\n\n- best_idx: candidate index with the highest val_aggregate_scores\n- best_candidate: the program text mapping for best_idx"}, {Dspy.Adapters.Types.ToolClass, "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.Evaluate.AutoEvaluation.CompleteAndGrounded, ""}, {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.Adapters.Types.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.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.Predict.Avatar.Tool, "!!! abstract \"Usage Documentation\"\n [Models](../concepts/models.md)\n\nA base class for creating Pydantic models.\n\nAttributes:\n __class_vars__: The names of the class variables defined on the model.\n __private_attributes__: Metadata about the private attributes of the model.\n __signature__: The synthesized `__init__` [`Signature`][inspect.Signature] of the model.\n\n __pydantic_complete__: Whether model building is completed, or if there are still undefined fields.\n __pydantic_core_schema__: The core schema of the model.\n __pydantic_custom_init__: Whether the model has a custom `__init__` function.\n __pydantic_decorators__: Metadata containing the decorators defined on the model.\n This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1.\n __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to\n __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these.\n __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models.\n __pydantic_post_init__: The name of the post-init method for the model, if defined.\n __pydantic_root_model__: Whether the model is a [`RootModel`][pydantic.root_model.RootModel].\n __pydantic_serializer__: The `pydantic-core` `SchemaSerializer` used to dump instances of the model.\n __pydantic_validator__: The `pydantic-core` `SchemaValidator` used to validate instances of the model.\n\n __pydantic_fields__: A dictionary of field names and their corresponding [`FieldInfo`][pydantic.fields.FieldInfo] objects.\n __pydantic_computed_fields__: A dictionary of computed field names and their corresponding [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] objects.\n\n __pydantic_extra__: A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra]\n is set to `'allow'`.\n __pydantic_fields_set__: The names of fields explicitly set during instantiation.\n __pydantic_private__: Values of private attributes set on the model instance."}, {Dspy.Predict.MultiChainComparisonClass, ""}, {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.Utils.Callback.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.Evaluate.AutoEvaluation.SemanticRecallPrecision, "Compare a system's response to the ground truth to compute its recall and precision.\nIf asked to reason, enumerate key ideas in each response, and whether they are present in the other response."}, {Dspy.Teleprompt.Gepa.GepaUtils.LoggerAdapter, ""}, {Dspy.Datasets.Alfworld.Alfworld.EnvPool, "Pool of processes, each with a unique env_worker.\nAcquire a worker using a context manager for safe usage:\n with pool.session() as sess:\n sess.init(5) # init with idx=5\n obs, rew, done, info = sess.step(\"go north\")\n ..."}, {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.Clients.UtilsFinetune.TrainingStatus, "str(object='') -> str\nstr(bytes_or_buffer[, encoding[, errors]]) -> str\n\nCreate a new string object from the given object. If encoding or\nerrors is specified, then the object must expose a data buffer\nthat will be decoded using the given encoding and error handler.\nOtherwise, returns the result of object.__str__() (if defined)\nor repr(object).\nencoding defaults to sys.getdefaultencoding().\nerrors defaults to 'strict'."}, {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.Teleprompt.Gepa.GepaUtils.DspyAdapter, "GEPAAdapter is the single integration point between your system\nand the GEPA optimization engine. Implementers provide three responsibilities:\n\nThe following are user-defined types that are not interpreted by GEPA but are used by the user's code\n to define the adapter:\nDataInst: User-defined type of input data to the program under optimization.\nTrajectory: User-defined type of trajectory data, which typically captures the\n different steps of the program candidate execution.\nRolloutOutput: User-defined type of output data from the program candidate.\n\nThe following are the responsibilities of the adapter:\n1) Program construction and evaluation (evaluate):\n Given a batch of DataInst and a \"candidate\" program (mapping from named components\n -> component text), execute the program to produce per-example scores and\n optionally rich trajectories (capturing intermediate states) needed for reflection.\n\n2) Reflective dataset construction (make_reflective_dataset):\n Given the candidate, EvaluationBatch (trajectories, outputs, scores), and the list of components to update,\n produce a small JSON-serializable dataset for each component that you want to update. This\n dataset is fed to the teacher LM to propose improved component text.\n\n3) Optional instruction proposal (propose_new_texts):\n GEPA provides a default implementation (instruction_proposal.py) that serializes the reflective dataset\n to propose new component texts. However, users can implement their own proposal logic by implementing this method.\n This method receives the current candidate, the reflective dataset, and the list of components to update,\n and returns a mapping from component name to new component text.\n\nKey concepts and contracts:\n- candidate: Dict[str, str] mapping a named component of the system to its corresponding text.\n- scores: higher is better. GEPA uses:\n - minibatch: sum(scores) to compare old vs. new candidate (acceptance test),\n - full valset: mean(scores) for tracking and Pareto-front selection.\n Ensure your metric is calibrated accordingly or normalized to a consistent scale.\n- trajectories: opaque to GEPA (the engine never inspects them). They must be\n consumable by your own make_reflective_dataset implementation to extract the\n minimal context needed to produce meaningful feedback for every component of\n the system under optimization.\n- error handling: Never raise for individual example failures. Instead:\n - Return a valid `EvaluationBatch` with per-example failure scores (e.g., 0.0)\n when formatting/parsing fails. Even better if the trajectories are also populated\n with the failed example, including the error message, identifying the reason for the failure.\n - Reserve exceptions for unrecoverable, systemic failures (e.g., missing model,\n misconfigured program, schema mismatch).\n - If an exception is raised, the engine will log the error and proceed to the next iteration."}, {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.Clients.UtilsFinetune.GRPOChatData, "dict() -> new empty dictionary\ndict(mapping) -> new dictionary initialized from a mapping object's\n (key, value) pairs\ndict(iterable) -> new dictionary initialized as if via:\n d = {}\n for k, v in iterable:\n d[k] = v\ndict(**kwargs) -> new dictionary initialized with the name=value pairs\n in the keyword argument list. For example: dict(one=1, two=2)"}, {Dspy.Predict.ProgramOfThoughtClass, "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.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.Signatures.Signature.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.Adapters.Types.Image.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.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.Teleprompt.KnnFewshot.KNNFewShot, ""}, {Dspy.Teleprompt.Gepa.GepaUtils.ReflectiveExample, "Structure of individual examples in the reflective dataset.\n\nEach example contains the predictor inputs, generated outputs, and feedback from evaluation."}, {Dspy.Adapters.Types.HistoryClass, "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.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.Retrievers.RetrieveClass3, ""}, {Dspy.Dsp.Colbertv2.ColBERTv2RetrieverLocal, ""}, {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, ""}, {Dspy.Propose.DatasetSummaryGenerator.DatasetDescriptorWithPriorObservations, "Given several examples from a dataset please write observations about trends that hold for most or all of the samples. I will also provide you with a few observations I have already made. Please add your own observations or if you feel the observations are comprehensive say 'COMPLETE' Some areas you may consider in your observations: topics, content, syntax, conciceness, etc. It will be useful to make an educated guess as to the nature of the task this dataset will enable. Don't be afraid to be creative"} ] 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