Defines typed input/output contracts for LM calls using dspy.Signature, InputField, and OutputField. Helps choose between inline and class-based signatures, add type constraints, or use Pydantic models for structured outputs.
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.
Guide the user through defining DSPy Signatures — typed declarations of what goes into and comes out of an LM call.
Ask the user before diving in:
Then jump to the relevant section below.
A Signature declares the input/output contract for an LM call -- field names, types, and descriptions. DSPy compiles it into an optimized prompt automatically. You define the I/O spec; DSPy handles the prompting.
| Style | When to use | Example |
|---|---|---|
| Inline | Quick one-liner, 1-2 inputs, 1 output, string types | "question -> answer" |
| Class-based | Multiple fields, type constraints, descriptions, Pydantic outputs | class Classify(dspy.Signature) |
Rule of thumb: Start inline for prototyping. Switch to class-based when you need type constraints, field descriptions, or more than one output.
Inline signatures are strings with -> separating inputs from outputs: "question -> answer", "text -> label: bool". Supported type suffixes: str (default), int, float, bool, list[str].
Class-based signatures give you type constraints, field descriptions, and a docstring that acts as the task instruction. Use them when you need more than a one-liner.
Both InputField and OutputField accept these parameters:
class Example(dspy.Signature):
"""Demonstrate field options."""
# desc: describes the field to the LM (shows up in the prompt)
text: str = dspy.InputField(desc="The document to analyze")
# type constraint via inline annotation (preferred)
category: Literal["news", "blog", "research"] = dspy.OutputField(desc="The document category")
desc — a natural language description. Helps the LM understand what the field means. Use this when the field name alone is ambiguous.type_ — sets the type constraint on the field. Still supported, but prefer an inline Python annotation (category: Literal[...] = dspy.OutputField(...)).For complex or nested structured output, use a Pydantic BaseModel as the output type. DSPy handles serialization and validation automatically.
import dspy
from pydantic import BaseModel, Field
from typing import Optional
lm = dspy.LM("openai/gpt-4o-mini") # or "anthropic/claude-sonnet-4-5-20250929", etc.
dspy.configure(lm=lm)
class LineItem(BaseModel):
description: str
quantity: int
unit_price: float
class Invoice(BaseModel):
vendor: str
date: str = Field(description="Invoice date in YYYY-MM-DD format")
total: float
items: list[LineItem]
notes: Optional[str] = None
class ParseInvoice(dspy.Signature):
"""Extract structured invoice data from the raw text."""
text: str = dspy.InputField(desc="Raw invoice text")
invoice: Invoice = dspy.OutputField(desc="Parsed invoice data")
parser = dspy.ChainOfThought(ParseInvoice)
result = parser(text="Invoice from Acme Corp, Jan 15 2025. 2x Widget ($10 each), 1x Gadget ($25). Total: $45.")
print(result.invoice.vendor) # Acme Corp
print(result.invoice.items[0]) # LineItem(description='Widget', quantity=2, unit_price=10.0)
print(result.invoice.total) # 45.0
When to use Pydantic outputs:
Optional fields for data that may not be presentThe docstring is the most important part of a class-based signature. DSPy uses it as the primary instruction to the LM.
# Vague — the LM doesn't know what "classify" means in your context
class Bad(dspy.Signature):
"""Classify the text."""
text: str = dspy.InputField()
label: str = dspy.OutputField()
# Clear — tells the LM exactly what to do
class Good(dspy.Signature):
"""Classify the customer support message into a department for routing.
Consider the primary intent, not just keywords."""
message: str = dspy.InputField(desc="Customer support message")
department: Literal["billing", "technical", "account", "general"] = dspy.OutputField()
For runtime customization without defining new classes:
# Override instructions at call time (inline signatures)
predict = dspy.Predict("question -> answer", instructions="Answer in exactly one sentence.")
# Programmatically modify a class-based signature
MySignature = MySignature.with_instructions("New instructions for this run")
# Add/remove fields dynamically
MySignature = MySignature.append("confidence", dspy.OutputField(), type_=float)
MySignature = MySignature.delete("unused_field")
DSPy also supports special input types: dspy.Image for image inputs, dspy.History for conversation history, dspy.Audio for audio inputs, and dspy.Code for code content. These are primitives from dspy — use them as field type annotations just like str or int.
"question -> answer" captures your task, an inline signature is clearer and shorter. Do not over-engineer with a class when a string works.text -> summary works better than input -> output because DSPy uses field names directly in the generated prompt. Choose descriptive names.tuple() wrapping for dynamic values -- use Literal[tuple(["a", "b"])] not Literal[["a", "b"]] when constructing from a list at runtime.desc values are NOT optimized -- DSPy optimizers (GEPA, MIPROv2, COPRO) tune the Signature docstring and/or few-shot demos, but InputField(desc=...), OutputField(desc=...), and Pydantic Field(description=...) values are fixed. If your structured output task relies heavily on field descriptions for guidance, see /dspy-gepa for a workaround that flattens field descriptions into the instruction for optimization.Verify your signature works by calling the module with one realistic example and printing every output field. If a Pydantic output raises a validation error, the type constraint is too strict for what the LM produces — relax it or add a desc that tells the LM the exact format expected.
Install any skill:
npx skills add lebsral/DSPy-Programming-not-prompting-LMs-skills --skill <name>
/dspy-predict (Predict), /dspy-chain-of-thought (ChainOfThought), /dspy-modules (custom modules)/ai-parsing-data/ai-sorting/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
Three short reads, in order
/dspy-api-skills:dspy-signaturesfrom dspy-api-skills
npx claudepluginhub lebsral/dspy-programming-not-prompting-lms-skills --plugin dspy-api-skills39 skills in this plugin
/dspy-adaptersUse when you need to customize how DSPy formats prompts for a specific provider — switching from chat to completion format, forcing JSON output, or debugging prompt rendering issues. Common scenarios - debugging why your prompt looks wrong when sent to the model, switching from OpenAI to Anthropic and the formatting breaks, forcing the model to return valid JSON instead of markdown, working with completion-style models that do not support chat format, customizing system messages, or handling models that choke on structured output instructions. Related - ai-switching-models, ai-following-rules, ai-parsing-data. Also used for prompt template rendering, how DSPy builds the prompt, custom system message in DSPy, JSON mode not working, model ignores format instructions, switch from chat to completion API, dspy.ChatAdapter, dspy.JSONAdapter, prompt formatting issues, debug what DSPy sends to the model, dspy.XMLAdapter, XML output format./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.Other plugins' skills for the same job