DSPy signatures explained
Quick answer
In dspy, a Signature is a Pydantic-based class that defines structured input and output fields for AI model calls. Use dspy.InputField() to declare inputs and dspy.OutputField() for outputs, enabling type-safe, declarative AI interactions.
PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install dspy openai>=1.0
Setup
Install dspy and openai packages, and set your OpenAI API key as an environment variable.
- Run
pip install dspy openai - Set environment variable
OPENAI_API_KEYwith your API key
pip install dspy openai Step by step
Define a dspy.Signature subclass with input and output fields, then create a dspy.Predict instance to call the AI model with structured data.
import os
import dspy
from openai import OpenAI
# Initialize OpenAI LLM
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
llm = dspy.LM("openai/gpt-4o-mini", client=client)
dspy.configure(lm=llm)
# Define a signature with input and output fields
class QA(dspy.Signature):
question: str = dspy.InputField()
answer: str = dspy.OutputField()
# Create a Predict instance
qa = dspy.Predict(QA)
# Call the model with structured input
result = qa(question="What is DSPy?")
print("Answer:", result.answer) output
Answer: DSPy is a declarative Python library that simplifies AI model calls by defining structured input and output schemas using Pydantic signatures.
Common variations
You can use dspy.ChainOfThought for step-by-step reasoning, switch models by changing the LM initialization, or run async calls with asyncio.
import asyncio
async def async_qa():
result = await qa.acall(question="Explain chain-of-thought in DSPy.")
print("Async answer:", result.answer)
asyncio.run(async_qa()) output
Async answer: Chain-of-thought in DSPy allows you to define multi-step reasoning by chaining signatures for clearer AI explanations.
Troubleshooting
- If you see
ValidationError, check that your input types match the signature fields. - If the API key is missing or invalid, set
OPENAI_API_KEYcorrectly in your environment. - For unexpected output, verify your model name and update
dspy.LMaccordingly.
Key Takeaways
- Use dspy.Signature to declare structured AI inputs and outputs with type safety.
- Instantiate dspy.Predict with your signature to call AI models cleanly.
- Configure your LLM with dspy.LM and set the API key via environment variables.
- Leverage dspy.ChainOfThought for multi-step reasoning workflows.
- Always validate input types to avoid runtime errors and ensure predictable AI responses.