Customizes DSPy prompt formatting per provider: switches between chat, JSON, XML adapters, forces structured output, and debugs prompt rendering issues.
Ships in dspy-api-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Adapters sit between your DSPy modules and the language model. They control how signatures get turned into prompts and how LM responses get parsed back into typed Python objects. Most of the time the default adapter just works -- but when you need tighter control over structured output, or you are working with reasoning models that struggle with formatting, adapters give you that control.
Every time a DSPy module calls an LM, an adapter handles two jobs:
You never call adapters directly. You configure one globally or per-module, and DSPy uses it behind the scenes.
| Adapter | How it formats | How it parses | Best for |
|---|---|---|---|
ChatAdapter | Field markers like [[ ## field_name ## ]] | Splits on field headers | General use (default) |
JSONAdapter | Requests JSON output with field schema | json_repair + type casting | Reliable structured output |
XMLAdapter | XML tags like <field_name>value</field_name> | Regex on XML tags | Models that handle XML well |
TwoStepAdapter | Natural language prompt (no formatting constraints) | Sends raw response to a second LM for extraction | Reasoning models (o1, o3) |
ChatAdapter is what DSPy uses unless you say otherwise. It formats prompts with field delimiters and parses responses by looking for those same delimiters in the output.
import dspy
# ChatAdapter is used automatically -- no configuration needed
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
dspy.configure(lm=lm)
classify = dspy.ChainOfThought("text -> label")
result = classify(text="Great product!")
print(result.label)
dspy.ChatAdapter(
callbacks=None, # Optional list of BaseCallback objects
use_native_function_calling=False, # Use native function calling features
native_response_types=None, # Output field types handled natively by the LM
use_json_adapter_fallback=True, # Fall back to JSONAdapter on parse failure
)
[[ ## field_name ## ]] delimiters in the prompt.JSONAdapter (unless you set use_json_adapter_fallback=False).You rarely need to instantiate ChatAdapter yourself. Do it when you want to:
dspy.ChatAdapter(use_json_adapter_fallback=False)dspy.ChatAdapter(use_native_function_calling=True)adapter = dspy.ChatAdapter(use_json_adapter_fallback=False)
dspy.configure(lm=lm, adapter=adapter)
JSONAdapter extends ChatAdapter and instructs the LM to respond with a JSON object matching your output fields. It uses the provider's native structured output mode when available, falling back to response_format: {"type": "json_object"}.
import dspy
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
adapter = dspy.JSONAdapter()
dspy.configure(lm=lm, adapter=adapter)
# Now all modules request JSON output from the LM
classify = dspy.Predict("text -> label: str, confidence: float")
result = classify(text="Great product!")
print(result.label) # positive
print(result.confidence) # 0.95
dspy.JSONAdapter(
callbacks=None, # Optional list of BaseCallback objects
use_native_function_calling=True, # Enabled by default (unlike ChatAdapter)
)
"(must be formatted as a valid Python str)").json_repair for resilience against minor formatting errors.AdapterParseError if the response cannot be parsed as a JSON object.Use JSONAdapter when you need more reliable structured output, especially with:
[[ ## field ## ]] formatfrom pydantic import BaseModel
class Invoice(BaseModel):
vendor: str
total: float
line_items: list[dict]
class ExtractInvoice(dspy.Signature):
"""Extract invoice details from the document text."""
document: str = dspy.InputField()
invoice: Invoice = dspy.OutputField()
lm = dspy.LM("openai/gpt-4o") # or "anthropic/claude-sonnet-4-5-20250929", etc.
adapter = dspy.JSONAdapter()
dspy.configure(lm=lm, adapter=adapter)
extractor = dspy.Predict(ExtractInvoice)
result = extractor(document="Invoice #1234 from Acme Corp. Total: $1,250.00 ...")
print(result.invoice.vendor) # Acme Corp
print(result.invoice.total) # 1250.0
print(result.invoice.line_items) # [...]
XMLAdapter extends ChatAdapter and wraps input/output fields in XML tags like <field_name>value</field_name> instead of [[ ## field ## ]] delimiters. Some models respond more reliably to XML-structured prompts.
import dspy
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
adapter = dspy.XMLAdapter()
dspy.configure(lm=lm, adapter=adapter)
classify = dspy.Predict("text -> label: str, confidence: float")
result = classify(text="Great product!")
dspy.XMLAdapter(
callbacks=None, # Optional list of BaseCallback objects
)
<field_name>value</field_name>.JSONAdapter on parse failure (like ChatAdapter).callbacks.Consider XMLAdapter when:
TwoStepAdapter is designed for reasoning models (like OpenAI's o1 and o3 series) that produce better answers when they are not forced into a rigid output format. It splits the work into two steps:
import dspy
# Main LM: a reasoning model that struggles with structured output
main_lm = dspy.LM("openai/o3-mini", max_tokens=16000, temperature=1.0) # or another reasoning model
# Extraction model: a fast, cheap model for parsing
extraction_lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-haiku-3-5-20241022", etc.
adapter = dspy.TwoStepAdapter(extraction_model=extraction_lm)
dspy.configure(lm=main_lm, adapter=adapter)
# The reasoning model thinks freely; gpt-4o-mini extracts the answer
solver = dspy.ChainOfThought("question -> answer")
result = solver(question="What is the sum of the first 100 prime numbers?")
print(result.answer)
dspy.TwoStepAdapter(
extraction_model=dspy.LM("openai/gpt-4o-mini"), # Required: cheap LM for extraction
)
ChatAdapter internally to parse the main LM's freeform response into structured fields.Use TwoStepAdapter when:
| Situation | Adapter | Why |
|---|---|---|
| General use, most models | ChatAdapter (default) | Works out of the box, no config needed |
| Need reliable JSON/Pydantic output | JSONAdapter | Stricter parsing, native structured output support |
| Complex nested output types | JSONAdapter | Better at complex schemas than field-delimiter parsing |
| Model responds better to XML structure | XMLAdapter | XML tags instead of field delimiters |
| Using reasoning models (o1, o3) | TwoStepAdapter | Reasoning models perform worse with format constraints |
| Parse failures in production | JSONAdapter | More resilient parsing with json_repair |
| Fastest iteration, prototyping | ChatAdapter (default) | Zero config, good enough for most tasks |
Set the adapter for all modules at once:
import dspy
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
adapter = dspy.JSONAdapter()
dspy.configure(lm=lm, adapter=adapter)
Switch adapters for a block of code without changing the global config:
json_adapter = dspy.JSONAdapter()
# Use JSONAdapter just for this block
with dspy.context(adapter=json_adapter):
result = extractor(document=text)
# Back to the default ChatAdapter outside the block
Assign different adapters to different modules using set_adapter():
class Pipeline(dspy.Module):
def __init__(self):
self.classify = dspy.Predict("text -> label")
self.extract = dspy.Predict(ExtractDetails)
def forward(self, text):
# Classification is simple -- default ChatAdapter is fine
label = self.classify(text=text)
return self.extract(text=text)
pipeline = Pipeline()
# Use JSONAdapter only for the extraction step
pipeline.extract.set_adapter(dspy.JSONAdapter())
dspy.adapters.baml_adapter) — exists in the DSPy source but is undocumented and likely experimental. It integrates with the BAML structured output framework. Do not use in production until it has official documentation.You can build your own adapter by subclassing the base Adapter class. This is advanced -- only needed if the built-in adapters do not fit your use case.
import dspy
from dspy.adapters import Adapter
class MyAdapter(Adapter):
def format(self, signature, demos, inputs, messages=None):
"""Convert signature + inputs into a list of messages for the LM."""
system_msg = {"role": "system", "content": f"Task: {signature.instructions}"}
user_msg = {"role": "user", "content": str(inputs)}
return [system_msg, user_msg]
def parse(self, signature, completion):
"""Extract output fields from the LM's raw response text."""
# Your custom parsing logic here
fields = {}
for field_name in signature.output_fields:
fields[field_name] = completion.strip()
return fields
adapter = MyAdapter()
dspy.configure(lm=lm, adapter=adapter)
Override format() to control how prompts are built and parse() to control how responses are read. The return from parse() should be a dict mapping output field names to their values.
By default, ChatAdapter already falls back to JSONAdapter on parse failure. This gives you the best of both worlds -- fast field-delimiter parsing most of the time, with JSON as a safety net.
# This is the default behavior -- you get it for free
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
dspy.configure(lm=lm)
# ChatAdapter is used, with automatic JSONAdapter fallback on failure
To disable this fallback:
adapter = dspy.ChatAdapter(use_json_adapter_fallback=False)
dspy.configure(lm=lm, adapter=adapter)
# Full setup for reasoning models
reasoning_lm = dspy.LM("openai/o3-mini", max_tokens=16000, temperature=1.0) # or another reasoning model
extraction_lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-haiku-3-5-20241022", etc.
adapter = dspy.TwoStepAdapter(extraction_model=extraction_lm)
dspy.configure(lm=reasoning_lm, adapter=adapter)
import dspy
lm = dspy.LM("openai/gpt-4o") # or "anthropic/claude-sonnet-4-5-20250929", etc.
dspy.configure(lm=lm) # default ChatAdapter
class MixedPipeline(dspy.Module):
def __init__(self):
self.summarize = dspy.ChainOfThought("document -> summary")
self.extract = dspy.Predict(ExtractInvoice)
def forward(self, document):
summary = self.summarize(document=document)
return self.extract(document=document)
pipeline = MixedPipeline()
# ChatAdapter for summarization (freeform text is fine)
# JSONAdapter for extraction (need reliable structured output)
pipeline.extract.set_adapter(dspy.JSONAdapter())
ChatAdapter automatically retries with JSONAdapter when parsing fails. If you are only switching to JSONAdapter to fix occasional parse errors, the default fallback may already handle it. Only switch globally when you need JSON for every call.set_adapter() for per-module overrides. When a pipeline has steps that need different adapters (e.g., freeform summarization + structured extraction), Claude sets the adapter globally instead of per-module. Use pipeline.extract.set_adapter(dspy.JSONAdapter()) to override only the modules that need it.Install any skill:
npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill <name>
/dspy-signatures -- Define the input/output fields that adapters format and parse/dspy-lm -- Configure the language model that adapters communicate with/dspy-modules -- Modules that use adapters under the hood (Predict, ChainOfThought, etc.)/ai-do if you do not have it — it routes any AI problem to the right skill and is the fastest way to work: npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill ai-doWhat SKILL.md sets; muted values are Claude Code's defaults
/dspy-api-skills:dspy-adaptersfrom dspy-api-skills
npx claudepluginhub lebsral/dspy-programming-not-prompting-lms-skills --plugin dspy-api-skills39 skills in this plugin
/dspy-assertionsLegacy reference for dspy.Assert and dspy.Suggest, both removed in DSPy 3.x - use dspy.Refine or dspy.BestOfN instead. Use when maintaining a legacy DSPy 2.x codebase that uses dspy.Assert or dspy.Suggest, or migrating from Assert/Suggest to DSPy 3.x. Also used for dspy.Assert, dspy.Suggest, runtime validation for LLM output, retry on bad output, backtracking on constraint violation, guard rails in DSPy, migrate from Assert, migrate from Suggest, ImportError cannot import Assert, ImportError cannot import Suggest./dspy-asyncUse when you need to run DSPy modules asynchronously — FastAPI endpoints, concurrent LM calls, non-blocking execution, or integrating DSPy into async web frameworks. Common scenarios - serving DSPy behind FastAPI or Starlette, running multiple LM calls concurrently with asyncio.gather, non-blocking batch processing, combining async with streaming, or building async agent loops. Related - ai-serving-apis, dspy-parallel, dspy-streaming, dspy-utils. Also used for aforward, acall, async DSPy, await dspy, FastAPI with DSPy async, concurrent DSPy calls, asyncio with DSPy, non-blocking DSPy, async batch processing, semaphore concurrency limit, asyncio.gather DSPy, async web framework DSPy, Starlette DSPy, aiohttp DSPy./dspy-best-of-nRuns any DSPy module N times and returns the highest-scoring output via a reward function using dspy.BestOfN. Use when output quality varies across runs and you want to sample multiple completions and pick the best — trading latency for reliability on high-stakes outputs. Common scenarios - generating multiple candidate answers and picking the highest-scoring one, improving reliability on high-stakes classification, reducing variance in creative generation, getting better summaries by sampling several and selecting the best, or trading latency for quality on critical decisions. Related - ai-improving-accuracy, ai-making-consistent, dspy-refine. Also used for sample multiple completions, pick the best of several LLM outputs, majority voting for LLM, self-consistency decoding, reduce LLM output variance, generate and select pattern, best candidate selection, how to make AI more reliable by trying multiple times, brute force better quality, retry and pick best, dspy.BestOfN, quality vs latency tradeoff, n=5 completions pick best./dspy-better-togetherJointly optimize prompts and model weights using dspy.BetterTogether for maximum accuracy. Use when you have already tried prompt-only optimization and want the next level — jointly tuning prompts and model weights for maximum quality. Common scenarios - you have maxed out prompt optimization and need the next level, combining instruction tuning with weight tuning for maximum quality, making a small model match a large model through joint optimization, or squeezing the last few percent of accuracy. Related - ai-fine-tuning, ai-improving-accuracy, ai-cutting-costs. Also used for dspy.BetterTogether, joint prompt and weight optimization, beyond prompt engineering, combine fine-tuning with prompt optimization, maximum possible quality from DSPy, hybrid optimization strategy, prompt optimization hit a ceiling, fine-tune and optimize prompts at the same time, advanced DSPy optimization, best possible accuracy, what to try after MIPROv2, next level AI quality./dspy-bootstrap-few-shotAutomatically generate and select few-shot demonstrations for a DSPy program from labeled data using dspy.BootstrapFewShot - the simplest and fastest optimizer. Use when you have 50+ labeled examples and want a quick accuracy boost as your first optimization step. Common scenarios - your first optimization attempt on a new DSPy program, adding few-shot examples automatically from labeled data, quick accuracy boost before trying heavier optimizers, bootstrapping demonstrations from a teacher model, or getting started with DSPy optimization. Related - ai-improving-accuracy, dspy-labeled-few-shot. Also used for dspy.BootstrapFewShot, simplest DSPy optimizer, first optimizer to try, automatic few-shot example selection, bootstrap demonstrations from labels, quick optimization baseline, add examples to prompt automatically, teacher bootstrapping, labeled data to few-shot demos, starting point for DSPy optimization, easy accuracy improvement, how to optimize DSPy program for the first time./dspy-bootstrap-finetuneGenerates training data from a teacher model and fine-tunes student model weights using dspy.BootstrapFinetune. Use when you need maximum quality from a smaller/cheaper model — distilling GPT-4 quality into a cheaper model, generating training data from a strong teacher to fine-tune a weak student, reducing inference costs by replacing an expensive model with a fine-tuned small one, or building a production model that is fast and cheap. Related - ai-fine-tuning, ai-cutting-costs, dspy-better-together. Also used for model distillation with DSPy, teacher-student training, fine-tune small model from GPT-4 outputs, reduce API costs with fine-tuning, generate training data then fine-tune, cheap model same quality, distill large model into small model, fine-tune Llama from GPT-4, production model training, move from API to self-hosted model.Other plugins' skills for the same job