DSPy 3.5 explained: signatures, ReAct agents and optimizers with offline runnable code
DSPy 3.5.0 arrived on 10 November 2026 with XML prompts by default, an optional LiteLLM and a ReAct module built on structured history. This guide explains signatures, modules, the ReAct loop and optimizers step by step, with code that runs offline on DummyLM.
- Reading time
- 17 min
- Sections
- 8
- Code examples
- 8
- Tables
- 2
- Sources
- 7
- Published
- 25 Nov 2026
- What changed
- DSPy 3.5.0 changes defaults and graduates core modules
- Why it matters
- DSPy shifts the work from writing prompts to writing metrics and data.
- What to do
- Pin the version
DSPy is a Python framework from Stanford NLP that treats prompts as code you compile, not text you hand-tune. You declare what a step takes in and gives back (a signature), wrap it in a module, write a metric, and let an optimizer search for better instructions and examples. DSPy 3.5.0 was released on 10 November 2026. Its release notes say it "changes prompts, defaults and APIs": the XML adapter is now the default prompt format, LiteLLM and the OpenAI library became optional, and the GEPA optimizer, the RLM module and dspy.Flex left experimental status.
This article teaches DSPy for agent builders. It covers signatures and adapters, the ReAct agent module as it works in 3.5, how optimizers turn a metric into better prompts, and what the original papers measured. Every code block ran on dspy 3.5.0 with Python 3.13, using DSPy's own DummyLM test model, so you can follow along without an API key.
See the DSPy tool page for a short overview. For background on the reasoning-and-acting loop itself, read ReAct explained from the paper. For how DSPy compares with other frameworks, see one agent built in seven frameworks.
What happened
DSPy 3.5.0 changes defaults and graduates core modules (10 November 2026)
The release describes itself as bringing "a lighter LM layer, graduated core modules, and new History and image capabilities for RLM." The changes that matter most:
- "LiteLLM and OpenAI's Python library are now optional: DSPy calls supported providers through the lightweight lm15 engine." On 3.5.0,
dspy.LMtakes anengineargument of"auto","lm15"or"litellm". - "XMLAdapter now formats and parses predictor calls by default." Prompts now wrap each field in tags such as
<answer>instead of the older[[ ## answer ## ]]markers. - RLM, Flex and GEPA graduate from experimental, and ReAct gets structured History.
- Disk caches use restricted loading by default, and NumPy arrays are stored without pickle.
The notes tell users upgrading from 3.4.1 to "re-evaluate optimized programs", because the prompt text changed.
DSPy 3.4 sets the LM migration deadline (25 September 2026)
Version 3.4.0 introduced native LM engines built on bundled lm15 types and kept LiteLLM as a compatibility backend. Its notes said "3.4 is the LM transition release; 3.5 is the migration deadline." It also added async ReActV2 and a persistent LocalInterpreter, with a warning that "LocalInterpreter is not a security sandbox."
DSPy 3.3 adds Flex and ReActV2 (3 August 2026)
Version 3.3.0 added dspy.Flex, which lets GEPA change a module's structure, not only its prompts, and an experimental ReActV2 built on native tool calling. The notes reported "up to 50% decreases in cost" on some tasks in internal testing. It also stopped treating file paths and URLs in strings as instructions to load files; you now call factories such as Image.from_path().
Signatures, modules and adapters
A signature is a typed contract
A signature lists input and output fields, with types and short descriptions. The docstring becomes the task instruction. Think of it as a form: you print the blank fields, and the model fills them in.
import dspy
from dspy.utils import DummyLM
class Triage(dspy.Signature):
"""Classify a support ticket."""
ticket: str = dspy.InputField()
category: str = dspy.OutputField(desc="one of: billing, refund, technical")
urgent: bool = dspy.OutputField()
lm = DummyLM([{"category": "refund", "urgent": True}])
dspy.configure(lm=lm)
pred = dspy.Predict(Triage)(ticket="Charged twice for order A-1042, please refund today")
print(pred.category, pred.urgent, type(pred.urgent).__name__)
refund True bool
Note that urgent came back as a Python bool, much like structured outputs in model APIs. The adapter parsed the text "True" into the declared type. A short string signature such as "ticket -> category" works too, with every field typed as str.
The adapter writes the prompt
An adapter turns a signature and inputs into chat messages, then parses the reply. In 3.5 the default is XMLAdapter. Here is the system message DSPy built for the call above, captured from lm.history:
Your input fields are:
1. `ticket` (str):
Your output fields are:
1. `category` (str): one of: billing, refund, technical
2. `urgent` (bool):
Output format (replace placeholders):
<category>
{category}
</category>
<urgent>
{urgent}
</urgent>
In adhering to this structure, your objective is:
Classify a support ticket.
The user message wraps the input as <ticket>...</ticket> and repeats the output format. You never write this text; you change the signature, and the prompt follows. ChatAdapter, JSONAdapter and TwoStepAdapter are still available if a model handles another format better.
| Piece | What it is | Example on 3.5.0 |
|---|---|---|
| Signature | typed inputs, outputs, instruction | class Triage(dspy.Signature) |
| Module | a step that uses a signature | dspy.Predict, dspy.ChainOfThought, dspy.ReAct |
| Adapter | prompt format and parser | XMLAdapter (default), ChatAdapter, JSONAdapter |
| LM | model client | dspy.LM("provider/model", engine="auto") |
| Metric | Python function that scores a prediction | def exact(example, pred, trace=None) |
| Optimizer | searches prompts and demos with the metric | BootstrapFewShot, MIPROv2, GEPA, SIMBA |
Modules compose like PyTorch layers
dspy.Predict calls the model once. dspy.ChainOfThought reasons before answering: its docstring on 3.5.0 says it "uses native reasoning when supported, otherwise requests a short plan before answering", and exposes either as reasoning. Other built-ins include dspy.ReAct, dspy.BestOfN, dspy.Refine, dspy.Parallel and dspy.RLM. You combine them inside a dspy.Module subclass with a forward method, much as you stack layers in PyTorch. The optimizer then sees every Predict inside your program and can tune each one.
How the ReAct agent works in DSPy 3.5
dspy.ReAct(signature, tools, max_iters=20) turns any signature into a tool-using agent. In 3.5 the loop is built on dspy.History. Reading the 3.5.0 source, each turn works like this:
- Build an inner signature with your inputs plus
history,toolsandturn_budget, and two outputs:next_thoughtandtool_calls. - Call the model. The turn budget tells it where it stands, for example "Turn 1 of 5 (4 more after this one)."
- Run the requested tool calls and append one event (thought, calls and results) to the history.
- If the model called the built-in
submittool, return its arguments as the final outputs, withtermination_reason="submit". - If the model asked for no tools, a reply failed to parse, the context overflowed, or
max_itersran out, make one forced final call to submit.
The name submit is reserved, and history, tools and turn_budget cannot be used as your own input names. The source notes that keeping each request a prefix of the next helps provider prompt caching.
A refund agent, traced
import dspy
from dspy.utils import DummyLM
ORDERS = {"A-1042": {"total_eur": 120.0, "days_since_delivery": 9}}
def get_order(order_id: str) -> dict:
"""Look up an order by id."""
return ORDERS[order_id]
def refund_allowed(days_since_delivery: int) -> bool:
"""Refunds are allowed within 14 days of delivery."""
return days_since_delivery <= 14
agent = dspy.ReAct("ticket -> decision: str, amount_eur: float",
tools=[get_order, refund_allowed], max_iters=5)
lm = DummyLM([
{"next_thought": "I need the order first.",
"tool_calls": {"tool_calls": [{"name": "get_order", "args": {"order_id": "A-1042"}}]}},
{"next_thought": "Delivered 9 days ago; check the policy.",
"tool_calls": {"tool_calls": [{"name": "refund_allowed", "args": {"days_since_delivery": 9}}]}},
{"next_thought": "Allowed. Submit.",
"tool_calls": {"tool_calls": [{"name": "submit",
"args": {"decision": "approve", "amount_eur": 120.0}}]}},
])
dspy.configure(lm=lm)
pred = agent(ticket="Refund order A-1042 please")
print(pred.decision, pred.amount_eur, pred.termination_reason)
print("LM calls:", len(lm.history))
print("prompt chars per call:",
[sum(len(m["content"]) for m in h["messages"]) for h in lm.history])
approve 120.0 submit
LM calls: 3
prompt chars per call: [2940, 3743, 4546]
The first history event shows the full record of turn 1: the ticket, the budget "Turn 1 of 5 (4 more after this one).", the thought, the call get_order(order_id="A-1042") and its result {'total_eur': 120.0, 'days_since_delivery': 9}. The tool docstrings and type hints became the tool descriptions automatically. The ReAct tool-calling simulation animates the same think-call-observe cycle.
Look at the prompt sizes. Each turn adds 3,743 − 2,940 = 803 characters, the same as 4,546 − 3,743. So turn n sends about 2,940 + 803 × (n − 1) characters. A six-turn run would send 6,955 characters on its last call, and the three-turn run above sends 2,940 + 3,743 + 4,546 = 11,229 characters in total. Evaluating this agent on 200 tickets means 200 × 3 = 600 model calls and about 200 × 11,229 = 2,245,800 prompt characters, before any optimization. The agent loop token cost simulation shows the same growth.
How optimizers improve a program
An optimizer takes your program, a training set and a metric. It runs the program, scores the results and changes the prompts: the instructions, the few-shot demonstrations, or both. It is like a coach who watches recordings of your matches and rewrites your playbook from the plays that worked.
BootstrapFewShot: keep the traces that pass
BootstrapFewShot runs a teacher (by default the same program) on the training examples and keeps a trace as a demonstration only if the metric passes. Here the scripted model gets three of four tickets right:
import dspy
from dspy.utils import DummyLM
train = [dspy.Example(ticket=t, category=c).with_inputs("ticket") for t, c in [
("Charged twice this month", "billing"),
("App crashes on login", "technical"),
("Return my money for order 77", "refund"),
("Invoice shows wrong VAT", "billing"),
]]
def exact(example, pred, trace=None):
return example.category == pred.category
classify = dspy.Predict("ticket -> category")
lm = DummyLM([{"category": c} for c in ["billing", "technical", "refund", "technical"]])
dspy.configure(lm=lm)
opt = dspy.BootstrapFewShot(metric=exact, max_bootstrapped_demos=4, max_labeled_demos=0)
compiled = opt.compile(classify, trainset=train)
print("demos kept:", len(compiled.demos))
Bootstrapped 3 full traces after 3 examples for up to 1 rounds, amounting to 4 attempts.
demos kept: 3
The VAT ticket was labelled "technical", failed the metric and was dropped. Only correct traces become examples in the compiled prompt, which is few-shot learning with machine-picked examples. For agents this matters: a demonstration of a whole successful ReAct trajectory teaches the model which tools to call and in what order.
MIPROv2 and GEPA: search the instructions too
MIPROv2 proposes candidate instructions and demo sets and searches over them; on 3.5.0 its defaults include auto="light", max_bootstrapped_demos=4 and max_labeled_demos=4. GEPA goes further. Its documentation says it "uses LLMs to reflect on structured execution traces (inputs, outputs, failures, feedback)" and proposes a new instruction for the module it targets. It keeps a Pareto frontier, "the set of candidates which achieve the highest score on at least one evaluation instance", instead of only the single best prompt, so a prompt that wins on rare cases is not thrown away.
GEPA works best when the metric explains itself. Return dspy.Prediction(score=..., feedback="...") instead of a bare number, for example "wrong: called refund tool before checking the 14-day policy". GEPA reads this text when it rewrites the instruction. On 3.5.0 its budget is set with one of auto ("light", "medium", "heavy"), max_full_evals or max_metric_calls, and a separate reflection_lm can be a stronger model than the one being tuned.
| Optimizer | Changes | Needs | Good for |
|---|---|---|---|
BootstrapFewShot |
demonstrations | metric, about 10+ examples | a quick first gain |
MIPROv2 |
instructions and demos | metric, more examples, more calls | stable tasks with a dev set |
GEPA |
instructions (and structure via Flex) |
metric, ideally with text feedback | agents and multi-step programs |
BootstrapFinetune |
model weights | a fine-tunable model | moving a pipeline to a small model |
What the papers measured
The DSPy paper (Khattab and others, October 2023) reported that "a few lines of DSPy allow GPT-3.5 and llama2-13b-chat to self-bootstrap pipelines that outperform standard few-shot prompting (generally by over 25% and 65%, respectively)". It also reported gains of 5-46% for GPT-3.5 and 16-40% for llama2-13b-chat over pipelines with expert-created demonstrations.
The GEPA paper (Agrawal and others, July 2025, revised February 2026) reports that GEPA "outperforms GRPO by 6% on average and by up to 20%, while using up to 35x fewer rollouts", and beats MIPROv2 "by over 10% (e.g., +12% accuracy on AIME-2025)". GRPO is a reinforcement-learning method that updates model weights; the GRPO simulation shows how it works. These are the authors' results on their tasks; your gains depend on your metric and data.
Continue learning
How this article connects
7 pages link to or from it. Drag to turn, click a dot to open it.
Use cases and examples
Support triage with typed outputs. A help-desk team uses the Triage signature to set category and urgent on every ticket. Because outputs are typed, urgent arrives as a real bool and can drive a paging rule directly. They label 50 tickets and run BootstrapFewShot; only correctly answered traces become demos, as in the four-ticket run above.
A refund agent with a policy tool. An e-commerce team builds the ReAct agent above with max_iters=5. In tests it takes three model calls per refund. Evaluating 200 tickets therefore costs 600 calls and about 2.2 million prompt characters, which they budget before choosing an optimizer.
Moving a pipeline to a cheaper model. A team that prototyped with a large model compiles the same program for a smaller one. The DSPy paper's claim that compiled programs on small models such as llama2-13b-chat were "competitive with approaches that rely on expert-written prompt chains for proprietary GPT-3.5" is the reason to try; their own dev-set metric decides.
Agent instruction tuning with feedback. A research-assistant team writes a GEPA metric that returns a score and a sentence of feedback per trajectory, such as "cited a source that was not retrieved". GEPA's reflection step reads these sentences and rewrites the agent's instruction, keeping a Pareto set of candidates across question types.
Offline regression tests. A platform team scripts DummyLM replies for key flows and asserts on termination_reason, tool order and parsed types in CI. After the 3.5 upgrade changed the prompt format, these tests showed that parsing still worked, and the team re-ran their optimizer as the release notes advise.
What it means in practice
DSPy shifts the work from writing prompts to writing metrics and data. That is a good trade when you have a task you can score, such as correct category, correct tool order, or a faithful answer, and at least a few dozen examples. It is a poor fit when "good" cannot be measured, because the optimizer has nothing to climb.
The 3.5 release also shows the cost of this approach: when the framework changes its prompt format, every compiled program changes too. Treat a DSPy upgrade like a model upgrade. Pin the version, keep your dev set, and re-evaluate before you ship. For agent-specific evaluation methods, see agent evaluation with trajectories and judges.
What to do now
- Pin the version. Install
dspy==3.5.0and note that prompts differ from 3.4.x because of the XML default. - Re-run your optimizers after upgrading. The release notes ask users to "re-evaluate optimized programs"; compare old and new on the same dev set.
- Choose the engine explicitly. Pass
engine="lm15"orengine="litellm"todspy.LMif you need predictable provider behaviour. - Type your outputs. Use
bool,float,Literaland Pydantic types in signatures so parsing errors show up early. - Set
max_itersfor agents. The ReAct default is 20; most tool flows need far fewer, and each turn re-sends the history. - Write a metric with feedback. Return a score and a short reason so GEPA can learn from failures.
- Start with BootstrapFewShot. Get a cheap baseline gain, then try MIPROv2 or GEPA if the metric still has room.
- Test with DummyLM. Script replies and assert on outputs, tool calls and
termination_reasonin CI. - Sandbox code tools. Remember that
LocalInterpreter"is not a security sandbox"; run untrusted code in a real sandbox.
Risks and open questions
Optimizers can overfit small sets. With a handful of training examples, a compiled prompt may learn quirks of those examples. Hold out a separate dev set and check it.
Prompt format changes break saved programs. The move to XMLAdapter changed what the model sees. Scores can move, so re-evaluate.
Metric quality caps the result. An optimizer maximises the metric you give it. A metric that rewards the right label but ignores unsafe tool calls will produce an agent that is accurate and unsafe.
Reported gains are task-specific. The paper figures above come from the authors' benchmarks and models. They show what is possible, not what your task will get.
Optimization runs cost real money. Every candidate prompt is evaluated on examples, often with a stronger reflection model. Budget the calls before you start.
Watch next: how the lm15 engine and the graduated Flex module are used in practice, whether GEPA's structure search becomes common for agents, and what the 3.6 release removes after the current deprecation period.
Frequently asked questions
What is DSPy in one sentence?
DSPy is a framework for building language-model programs from typed signatures and modules, then improving their prompts automatically with optimizers that use your metric. You write code and evaluation data; DSPy writes and tunes the prompt text.
Do I need LiteLLM to use DSPy 3.5?
No. Since 3.5.0, LiteLLM and the OpenAI Python library are optional, and DSPy calls supported providers through the lm15 engine by default. You can still choose LiteLLM with engine="litellm" if you need a provider it supports.
How does DSPy's ReAct know when to stop?
It stops when the model calls the built-in submit tool with the final outputs. It also ends after a parse failure, a context overflow, an empty tool call or max_iters turns, and then makes one forced submit call. The prediction's termination_reason tells you which case happened.
Which optimizer should I try first?
Start with BootstrapFewShot, which only keeps demonstrations whose traces pass your metric and is cheap to run. Move to MIPROv2 to search instructions as well, or to GEPA for multi-step agents, especially if your metric can return text feedback.
Can I test DSPy programs without calling a model?
Yes. dspy.utils.DummyLM returns scripted outputs in the format of the active adapter, and it records each call in lm.history. All examples in this article ran this way, which makes it practical for unit tests.
Summary
DSPy 3.5.0, released on 10 November 2026, makes the XML adapter the default, makes LiteLLM optional through the lm15 engine, and graduates GEPA, Flex and RLM. Its core idea is unchanged: declare signatures, compose modules, write a metric and let an optimizer improve the prompts. The 3.5 ReAct module runs a history-based loop that ends when the model calls submit, and our run showed prompts growing by 803 characters per turn. Optimizers range from BootstrapFewShot, which keeps only passing traces, to GEPA, which reflects on traces and feedback; the papers report sizeable gains on their tasks. Pin the version, test with DummyLM and re-evaluate after every upgrade.
Sources
- Code GitHub: DSPy release 3.5.0
- Code GitHub: DSPy release 3.4.0
- Code GitHub: DSPy releases
- Web DSPy: GEPA overview
- Paper arXiv: DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines
- Paper arXiv: GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning
- Code PyPI: dspy
Cite this article
Kelahmet, Ö. C. (2026, November 25). DSPy 3.5 explained: signatures, ReAct agents and optimizers with offline runnable code. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/dspy-3-5-signatures-react-optimizers
BibTeX
@online{kelahmet2026dspy,
author = {Kelahmet, {\"O}zer Cem},
title = {{DSPy 3.5 explained: signatures, ReAct agents and optimizers with offline runnable code}},
year = {2026},
month = {nov},
url = {https://www.ozercemkelahmet.com/articles/dspy-3-5-signatures-react-optimizers}
}Version historyfirst version
- Published
Factual corrections are listed here with what changed. Wording and formatting edits are not listed.