Concept Intermediate · 3 min read

What is DSPy signature

Quick answer
A DSPy signature is a Python class that defines structured input and output fields for declarative AI model calls using the dspy package. It formalizes the expected inputs and outputs of an AI prompt as typed fields, enabling type-safe, declarative programming with language models.
DSPy signature is a declarative class in the dspy library that defines structured input and output fields for AI model calls, enabling typed, schema-driven prompt programming.

How it works

A DSPy signature works by defining a Python class that inherits from dspy.Signature. This class declares input fields with dspy.InputField() and output fields with dspy.OutputField(), each typed with Python type hints. When you call the signature, dspy uses these definitions to generate prompts, send them to the AI model, and parse the structured response back into the output fields. This approach is analogous to defining a function signature in Python, but for AI prompt inputs and outputs, ensuring clear contracts and type safety.

Concrete example

python
import os
import dspy

# Initialize the LM with your OpenAI API key
lm = dspy.LM("openai/gpt-4o-mini", api_key=os.environ["OPENAI_API_KEY"])
dspy.configure(lm=lm)

# Define a DSPy signature for a simple Q&A task
class QA(dspy.Signature):
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

# Create a prediction callable from the signature
qa = dspy.Predict(QA)

# Use the signature to get an answer
result = qa(question="What is Retrieval-Augmented Generation?")
print(result.answer)
output
Retrieval-Augmented Generation (RAG) is an AI architecture that combines a retrieval system with a language model to generate answers grounded in a specific knowledge base.

When to use it

Use a DSPy signature when you want to build AI applications with clear, typed input and output schemas that improve maintainability and reduce errors. It is ideal for structured extraction, question answering, and any scenario where you want to declaratively define the shape of prompts and responses. Avoid it if you need highly dynamic or unstructured prompt interactions that do not fit well into fixed input/output schemas.

Key Takeaways

  • DSPy signature defines structured input/output fields for AI model calls using Python classes.
  • It enables type-safe, declarative prompt programming with the dspy package.
  • Use it to improve code clarity and reliability in AI applications requiring structured data exchange.
Verified 2026-04 · openai/gpt-4o-mini
Verify ↗