pypi / dspy
dspy
What changed in dspy 3, from its official release notes, upgrade guides and advisories. Sources checked 2026-12-05.
71 breaking10 security9 deprecations103 new APIs and options2 performance40 behavior and defaults71 fixes and other
See which of these apply to your code, ranked, in your agent:
npx @unstale/cli initdspy 3306 changes
Breaking changes 71
Overdue Audio factory aliases are removed.
The deprecated CodeAct API is removed for DSPy 3.5.
ReAct is now ReActV2, with structured History and a typed submit tool.
Overdue Image factory aliases and the deprecated constructor download/verify shim are removed.
The deprecated ProgramOfThought API is removed for DSPy 3.5.
Restricted loading is now the default for disk caches, and plain NumPy arrays are stored without pickle.
XMLAdapter now formats and parses predictor calls by default, changing prompts and the output contract even when your Signature stays the same.
The bundled metadata snapshot now follows LiteLLM 1.105.0; offline setups may lose capability flags for still-routable models, changing structured-output, native-tool, and reasoning behavior.
The private shim file moved to dspy/primitives/_facade_shim.py, so the old module no longer imports.
Flex bridge shim constants and helpers moved here; imports from dspy.predict.flex.bridge now raise ImportError.
Signatures can no longer declare input fields named history or tools; the constructor raises ValueError because ReActV2 supplies both itself.
History replay now passes main_request= to format_user_message_content; custom adapter overrides must accept main_request: bool = False.
GEPA now requires reflection_lm to be a dspy.LM or another dspy.BaseLM that can return parseable JSON; plain functions fail and leave the program unoptimized.
Null Score level descriptions are rejected when defining signatures or setting criteria, and saved programs containing them no longer load or run successfully.
Custom engines own their connections; client settings belong on the engine, and DSPy rejects those settings on LM construction, copying, and calls with custom engines.
Importing this module now raises a migration error.
The experimental 3.3 LM request and response exports are removed; use
dspy.lm15.Requestanddspy.lm15.Responseinstead.Rejects empty development sets with a descriptive ValueError.
experimental=Trueno longer makes ordinary prompt calls return typed responses; use an explicit request.The
typed_lmforward contract is rejected; use explicit lm15 requests for typed responses.ReActV2 output fields cannot use this name because it collides with metadata.
The name is reserved for RLM runtime configuration; using it as an RLM signature input raises ValueError.
Replaces RLM's live-interpreter call-time override with a keyword-only interpreter_factory input, and reserves that input name.
Schemas derived from Pydantic models require all properties as OpenAI expects; caller-supplied raw schemas remain unchanged.
Requires Pydantic 2.11.0 or later.
RLM call-time overrides now require a keyword-only zero-argument interpreter factory; live interpreter instances and positional factory overrides raise TypeError.
Single failures now propagate as their original exceptions; groups containing multiple failures remain groups.
Propagates producer failures instead of silently ending; streamify unwraps a single nested task-group failure while multiple failures remain grouped.
URL downloads now default to a 30-second request timeout instead of potentially waiting forever; pass timeout=None to retain unbounded behavior.
Setting max_reflection_cost now raises clearly because DSPy's GEPA adapter does not support it, rather than silently providing an ineffective budget.
Sandbox startup ignores ambient Node and Deno project configuration, pins Pyodide, validates Deno versions, protects bundled runtime files, and revokes Deno-cache access after startup.
The direct BaseLM constructor now defaults max_tokens to None instead of 1000.
The direct BaseLM constructor now defaults temperature to None instead of 0.0.
Shallow-copies subclass-owned attributes while separately copying DSPy-owned mutable runtime containers; subclasses relying on deep copies should override copy or copy state explicitly.
When tracked, this value is now a dictionary keyed by validation instance id with lists of candidate and Prediction pairs.
No longer retries with an alternate output format after an LMError; provider and transport failures propagate directly.
TwoStepAdapter uses this exception for local extraction or parsing failures instead of ValueError.
Serialization and format output now use DSPy's native {name, args} call shape instead of the prior OpenAI-style shape.
Uses SHA-256 instead of xxhash64, so hash strings, hash-derived fine-tuning filenames, and deterministic bootstrap trace selection may change; LM response-cache keys are unaffected.
Now returns a compiled DSPy module.
Now contains a list of compiled DSPy modules rather than instruction dictionaries.
The download_images and verify options were removed from encode_image; use resource construction or an explicit factory instead.
Now returns a dictionary keyed by validation instance id.
Construction and validation no longer interpret locator-shaped strings as instructions to read local files or fetch remote URLs.
Explicitly reads and embeds a local image; constructing or validating Image values no longer performs implicit I/O.
Downloads the resource and returns an embedded data URI; use Image(url) for a non-downloading provider-fetched reference.
The download option was removed; choose reference construction or an explicit factory instead.
The LangChain extra now requires LangChain Core 0.3.0 or newer.
NumPy is no longer installed with base dspy; NumPy-backed features require the numpy extra.
OpenAI 1.66.2 is now the supported minimum.
Now has type dict[Any, set[int]].
No longer exposes a constructor-owned interpreter attribute or preserves sandbox state across calls; each invocation creates and shuts down a fresh interpreter unless one is caller-owned.
Passing this through GEPA's gepa_kwargs now raises ValueError; use instruction_proposer for custom proposal behavior.
Validates its execution namespace at construction and rejects unexpected invocation fields instead of ignoring them.
The RLM constructor parameter was renamed to max_iters.
Replaces the RLM constructor's max_iterations parameter to match other iterative DSPy modules.
Raises dspy.AdapterParseError rather than ValueError for local extraction or parsing failures; extraction-LM failures propagate as dspy.LMError.
Now has type list[dict[Any, float]], keyed by validation instance id.
An empty language-model response now raises AdapterParseError instead of silently returning None.
Introduces a DSPy-owned context-window error in place of the LiteLLM error, supporting decoupling from LiteLLM.
Both metrics now return dspy.Prediction.
Changes the messaging format to JSONRPC.
Removes the enable_tool_optimization feature.
Changes tools to take a list instead of a dict and properly serializes None/null values.
Replaces FinalAnswerResult as the RLM final output type.
Removes the RLM __call__ method.
BaseType was renamed to Type.
Unmaintained community retriever integrations were removed; migrate to custom code or use Tool/MCP integrations.
The dspy.Program alias was removed; replace its use.
Custom types work with adapters; the type API is named dspy.Type.
Python 3.9 is no longer supported; Python 3.10–3.13 are supported.
Security 10
LM calls made for sandboxed code accept generation parameters only; sandboxed code cannot set model, api_base, api_key, or headers.
Request handling rejects recursive execution through the interpreter's own host tools, uses unpredictable request IDs, prevents diagnostic desynchronization, and protects host-tool identity from guest mutation.
Interpreter file mounts with distinct host paths can no longer silently collide at the same sandbox basename.
Serializes sanitized LM state, excluding API keys and supporting legacy saved states.
Loads serialized LM state and requires explicit opt-in before importing trusted custom LM classes.
Opt-in restricted cache deserialization limits allowed pickle types to reduce arbitrary code execution risk from malicious or corrupted cache files.
Prevents argument injection in subprocess calls.
Removes overly permissive read permissions and adds strict allow rules.
Adds guards against loading pkl files and a load_memory_cache parameter to prevent loading them without explicit permission.
API keys are excluded from saved programs.
Deprecations 9
The old ReActV2 name is deprecated until 3.6; use dspy.ReAct.
TwoStepAdapter is deprecated in DSPy 3.5.
Custom
BaseLM.forward()andaforward()integrations still execute with DeprecationWarning and are scheduled for removal in 3.5; implement the engine interface.LegacyEngine, AsyncLegacyEngine, and custom complete_legacy() shortcuts still execute with DeprecationWarning and are scheduled for removal in 3.5.
Public OpenAI-style
messages=calls still execute in 3.4 but emit DeprecationWarning and are scheduled for removal in 3.5; use explicit requests.Constructing dspy.CodeAct now emits DeprecationWarning; it is scheduled for removal in DSPy 3.5, and the notes recommend dspy.RLM for new code.
Constructing dspy.ProgramOfThought now emits DeprecationWarning; it is scheduled for removal in DSPy 3.5, and the notes recommend dspy.RLM for new code.
Using prefix, format, and parser kwargs in InputField or OutputField now emits a deprecation warning.
Image from_* helpers are deprecated in favor of the flexible constructor.
New APIs and options 103
Adds a BoundingBox type with automatic Jev image support.
RLM can crop images with Pillow and send mixed text/image subqueries from its Python REPL.
Interpreters can be started ahead of need, enabling a ready pool for Flex and RLM execution.
RLM code can import dspy and build Predict, ChainOfThought, ReActV2, and nested RLM sub-agents; sub-agents run on the host and only JSON crosses the interpreter boundary.
Configure GEPA's instruction proposer with skills, additional_instructions, base_instructions, max_chars, truncate_history_outputs, and adapter.
Restoring saved custom engines requires enabling this option; the notes advise enabling it only for trusted state.
Adds async ReActV2 execution.
Adds an experimental typed choice among described alternatives, exposing the selected value, option probabilities, and confidence.
Adds the experimental Choice type for working with TypeSafe/Jev.
Allows replacing the default interpreter factory globally or through configuration; explicitly supplied non-default factories retain precedence.
Adds an optimizer that fits Boolean thresholds, Score cuts, and Choice weights against a program metric without rewriting instructions, criteria, or demonstrations.
Adds a TypeSafe Jev backend through the existing lm= interface; Predict translates signatures, inputs, demonstrations, and field criteria into Jev decision requests.
Adds
code_proposer=for custom Flex source proposals, complementinginstruction_proposer=.Exposes bundled native LM request, response, and streaming types without requiring a separate installation.
Lets developers declare an OpenAI- or Anthropic-compatible HTTP service's endpoint, authentication, and capabilities instead of writing a custom engine.
Adds a persistent CPython subprocess interpreter for trusted generated code, compatible with RLM and Flex and not requiring Deno.
Custom backends can implement
complete(Request) -> Responseand be supplied throughengine=, withasync_engine=available for async execution.Adds native
lm15and explicitlitellmengine selection;autoprefers native execution for supported routes and representable inputs.Adds a custom Flex code_proposer hook to GEPA.
Adds a persistent LocalInterpreter.
Adds an experimental Boolean decision type exposing
.value,.probability, and.confidence.Adds the experimental Noul type for working with TypeSafe/Jev.
Allows predictor decision rules such as Boolean thresholds to be set locally, so identical requests can reuse cached evidence.
Experimental ReActV2 now supports async calls, including async prediction, async tools, and final submission.
Adds the experimental ReAnchor calibration optimizer for Predict.
Adds an experimental rubric scoring type exposing a continuous value, ordinal level, rubric probabilities, and confidence.
Adds the experimental Score type for working with TypeSafe/Jev.
Adds an optional installation extra requiring typesafe-sdk>=0.6.0,<1.0.0; it is not included in the base installation.
An optional managed Deno runtime can be installed with this extra; DSPy prefers the managed binary when present while retaining system Deno and custom-command support.
GEPA supports multi-proposal sampling, selection, acceptance, tracking, and checkpoint-state contracts through gepa_kwargs; resumed proposal sampling restores RNG state.
Callbacks expose interpreter execution, sandbox-to-host tool calls, and interpreter process startup and shutdown, retaining ancestry across modules, interpreters, tools, and LM calls.
DSPy's MCP bridge supports SDK v1 and v2 field names, v1 ClientSession, and the v2 high-level Client without changing default tool-result semantics.
Metrics can report named objective scores and select objective-aware frontiers through gepa_kwargs; tracked results expose aggregate scores and per-objective candidate and maximum metadata.
Setting result_mode to structured opts into machine-readable MCP results, returning structuredContent exactly when supplied and otherwise falling back to existing content conversion.
Custom load_state overrides should accept this option for compatibility with module-valued parameter leaves.
Explicitly reads and embeds local audio.
Explicitly downloads and embeds remote audio.
Defines an explicit typed contract for new custom LM implementations: accept an LMRequest and return an LMResponse.
Submitted-code failures now raise this exception, a subclass of CodeInterpreterError.
Install this extra to use NumPy-backed features such as embeddings, KNN/KNNFewShot, SIMBA, and other optimizer or retrieval paths.
Enables trying the typed LM return path.
Adds an experimental module whose implementation GEPA can rewrite, including predictors, control flow, DSPy primitives, and the balance between Python and LM calls.
Provides structured user, assistant, and tool messages for ReActV2 history instead of a single trajectory string.
Provides a DSPy-normalized exception to catch instead of provider-specific LM errors.
Introduces a typed, provider-neutral request object for custom language-model implementations.
Introduces a typed, provider-neutral response object for custom language-model implementations.
Adds an experimental ReAct implementation built around native tool calling, structured history, and tool-result replay.
Can optionally be stored with ToolCalls to preserve tool results and replay native tool-call history.
Explicitly reads and embeds a local file.
Adds the typed_lm contract marker for custom language models.
ProgramOfThought, CodeAct, and RLM accept a zero-argument callable that creates a fresh CodeInterpreter for each invocation.
Adds an optional sixth GEPA metric parameter for scoring how a result was produced.
Derives a signature with additional instructions without mutating the original.
Exposes capability properties so custom language model backends can integrate with DSPy without adapters importing LiteLLM.
Accepts arbitrary optimizers as keyword arguments and chains them via strategy strings, evaluating each step on a valset and returning the best program.
Input values that mismatch declared signature types and extra fields now log warnings; this option disables those warnings.
Adds a retriever API for accessing similarity scores.
Adds a verify parameter to allow bypassing SSL verification for images.
Adds file output support and fixes the return type.
Adds XMLAdapter to dspy.ai.
Exposes the straggler_limit parameter in Parallel.
Exposes the timeout parameter in Parallel.
Adds methods to save and load DSpy settings.
Adds the RLM module for developers to use.
Supports generic type annotations for output.
Adds tool description optimization for multi-agent systems.
ChatAdapter gains an option to disable fallback.
Adds a File type for handling file data.
Introduces dspy.Reasoning to capture native reasoning from reasoning models.
A method extracts the system message based on the adapter and signature.
Adds support for the Anthropic Citation API.
GEPA supports custom component selection logic.
DummyLM takes an adapter at initialization.
Adds save and load support to Embeddings.
Exposes EvaluationResult as dspy.evaluate.EvaluationResult.
Pass custom keyword arguments to gepa.optimize using gepa_kwargs.
GEPA supports a custom instruction proposer, including handling for dspy.Image.
Adds MLflow support for GEPA.
Adds ToolCall.execute for smoother tool execution.
The prompt management layer can be exported via Adapters.
Caches are configurable and support high concurrency.
Audio is available as a multimodal I/O type.
A built-in BAML adapter is available.
A built-in adapter supports chat-formatted I/O, async paths, streaming, and fallback to native LLM structured outputs.
CodeAct is available as a module.
GEPA adds a Genetic-Pareto prompt optimizer using a Pareto tree and natural-language reflection to extract and validate lessons.
GRPO enables reinforcement learning on DSPy programs through the new Arbor library.
History is available as a higher-level I/O type.
Image is available as a multimodal I/O type.
A built-in JSON adapter supports async paths and fallback to native LLM structured outputs.
Refine is available as a module.
SIMBA is a prompt optimizer that learns from custom feedback.
syncify runs optimizers on async DSPy programs.
ToolCalls is available as a higher-level I/O type.
A built-in XML adapter supports token streaming.
Tooling integrations support LangChain tools out of the box.
Tooling integrations support MCP servers out of the box.
Native observability integration provides tracing, optimizer tracking, and improved deployment flows.
Batch module execution is available with thread-safe DSPy settings.
DSPy supports native async execution.
Output can be streamed from any layer.
Intermediate status can be streamed during execution.
Usage tracking is available.
Performance 2
Shares the corpus table across queries to reduce memory use; the FAISS path is unchanged.
Image.format is cached to improve throughput.
Behavior and default changes 40
Flex is no longer experimental.
GEPA is no longer experimental.
RLM can save and reload conversation History for later calls; live interpreter variables are not restored.
RLM is no longer experimental.
LiteLLM is now optional; DSPy calls supported providers through the lightweight lm15 engine while retaining compatibility execution.
The default API-family selection is now automatic rather than explicitly selecting chat or responses.
CoT and RLM prefer native reasoning, with a plan fallback; an explicit plan can be requested when useful.
The OpenAI Python library is now an optional dependency.
Tools can return images, files and other DSPy content parts on supported provider routes.
When instruction_proposer is omitted, GEPA now uses InstructionProposer(), which sends structured reflective examples through dspy.Predict with a JSONAdapter.
Replayed turns keep output-format reminders, making each turn's prompt a prefix of the next one for prompt caching.
Tool argument defaults are stored in JSON form for types such as Enum, Decimal, dates, Path, tuples, sets, pydantic models, and dataclasses, while omitted arguments retain their original Python defaults.
The RLM call budget now includes llm_query, llm_query_batched, and every sub-agent LM call; each requested completion uses one slot.
On Python 3.10–3.13, adapters now render PEP 604 union annotations like typing.Union; parsing is unchanged, but prompts differ.
Samples labeled demonstrations independently per predictor.
Cache implementations load only when their tiers are enabled, allowing both tiers to be disabled without constructing filesystem-backed storage.
Provider adaptations are now recorded in LM history.
Native
nanswers use separate sequential requests and may bill input tokens more than once; LiteLLM can be selected for its nativenbehavior.When an LM omits an output field, declared defaults, default factories, and None-allowing annotations now provide fallbacks; missing required outputs still raise AdapterParseError.
CodeInterpreterError is now a DSPyError while retaining RuntimeError compatibility.
Optimizer compile runs now receive callback start and end coverage.
When a strategy produces multiple candidates, DSPy can evaluate them concurrently while sharing the existing num_threads budget between candidate-level and example-level concurrency.
XMLAdapter formats and parses nested Pydantic models, typed dictionaries, lists, mappings, nullable fields, and unions as nested XML while retaining compatibility with the previous JSON-inside-XML representation.
Flex runs optimizer-authored source in a CodeInterpreter sandbox using PythonInterpreter by default.
RLM now invokes user tools through dspy.Tool, applying tool argument validation and coercion, default handling, and callbacks.
Legacy output from the Responses model path now uses the Chat Completions-compatible tool-call shape and always includes the text key.
The upper bound on the litellm dependency was removed, allowing use of later versions.
Optuna is no longer a required dependency; install it with
pip install dspy[optuna]to use MIPROv2 or BootstrapFewShotWithOptuna.Uses BaseModel docstrings as descriptions.
Increases the max_iters value.
Callback logging is enabled only for full evaluations on GEPA.
A stream listener can now work on any type.
Custom types can be streamed and use the native response.
Adds a DSPy User-Agent header.
DummyLM answer dictionary values can be any type, supporting a wider range of signatures.
The default max_tokens value is now None.
The default temperature is now None.
MIPROv2 is more reliable and now supports automatic hyperparameter selection.
ReAct has been improved.
Save/load is stable and includes the program.
Fixes and other changes 71
BootstrapFewShot now honors metric_threshold=0.0.
ChainOfThought now honors reasoning dictionaries.
Flex now supports class-based signatures.
majority() can vote on non-string field values.
MIPROv2.compile now respects seed=0.
Raises a ValueError naming student predictors without an LM instead of failing later with AttributeError; set the LM on each student predictor.
When a JSON value contains an item pydantic cannot serialize, that item renders as str(item) instead of converting the whole value to a Python repr.
Fixes a 3.4.0 import crash that could occur when DSPy lazily imported LiteLLM.
DSPy now supports Python 3.15; on that version, LiteLLM and GEPA are not installed, LiteLLM fallback routes are unavailable, and dspy.GEPA raises ImportError.
Streamed chunks no longer include whitespace around field markers, so joined chunks equal the parsed field value.
Hashing is order-insensitive to match equality, and copying preserves the input/label split.
Coerces non-string Literal members during parsing.
Is omitted when no tools are sent to the language model.
Use the async call when invoking an async tool inside a running event loop; a synchronous call raises ValueError even with async/sync conversion enabled.
Honors the remaining batch deadline instead of resetting the timeout on each queue read.
End callbacks receive terminating BaseException values such as cancellation and interruption instead of incorrectly reporting those operations as successful.
Passing eval_kwargs=None now matches the documented optional contract.
Valid zero-valued sizes and seeds are now honored.
When an LM omits an output field, declared defaults, default factories, and None-allowing annotations now provide fallbacks; missing required outputs still raise AdapterParseError.
A completed task returning None is now correctly treated as complete.
The property gives RLM an accurate description of the Pyodide environment, including state persistence and unavailable native process capabilities.
ReAct preserves ContextWindowExceededError after trajectory truncation is exhausted.
Tool defaults and NoneType annotations serialize correctly across the sandbox boundary.
Custom headers are now forwarded to LiteLLM streaming completions in async streaming LM calls.
Per-call
caching=Falseis now honored for both synchronous and asynchronous embedding calls.No longer includes JSON schema for DSPy custom types in prompts.
Tool calls use kwargs-only dispatch, the JS bridge returns structured errors, stdout parsing skips non-JSON lines, and subprocess restarts replay tool and mount registration.
Handles error responses from the ColBERTv2 server.
Fixes enable_read_paths when multiple files are used.
Fixes code fence parsing in RLMs.
Handles dict responses in RLM for reasoning models.
Fixes RLM getting stuck on imports.
Fixes large variable injection.
Fixes the request header in streaming mode.
Updates the DSpy settings save and load methods.
Avoids unwanted exception chaining when an async tool runs in a sync context.
Uses the language value in system instructions for dspy.Code fields.
Handles list[dict] output from a dspy.LM.
Fixes the Protocol definition by adding the missing self parameter.
Enforces a positive value for the in-memory cache entry limit.
Populates InputField default values.
Fixes ContextWindowExceededError after three retries.
Fixes structured outputs for the Responses API.
No longer appends StatusStreamingCallback directly to the shared settings.callbacks list.
Ensures streaming yields the last chunk.
Fixes parsing of underscore-style float numbers.
Skips merging when both usage entry values are None.
Fixes an AttributeError when using ParallelExecutor with dspy.context.
Updates old Anthropic model names.
Fixes a TypeError when tracking usage with Anthropic models that return Pydantic objects.
The x-wav audio format is normalized to wav.
Fixes issues with continuous format.
Fixes serialization of dspy.History objects.
Zero-shot detection now takes .compile parameters into account before determining whether the program was zero shot.
Fixes content input conversion for the OpenAI Responses API.
Python 3.14 is supported.
Excludes gpt-5-chat from reasoning model classification.
Implements user message formatting for XMLAdapter.
Fixes error handling in dspy parallel.
Headers are updated when specified.
Fixes parsing of doubly encoded base types in json.parse.
Fixes escaping when JSON mode is used without structured outputs.
Falls back to the memory cache when disk is unavailable.
Fixes selection between task_model and prompt_model.
Fixes chunk loss during long streaming with the native response field.
Fixes unexpected parsing of Optional[str] fields when strings contain brackets or braces.
Fixes response_format handling for the responses API.
Adds a fallback when the end marker is missing during streaming.
Fixes XML adapter markers.
History is available per module.
PythonInterpreter is more reliable.