How to beginner · 3 min read

How to install DSPy

Quick answer
Install dspy using pip install dspy in your Python environment. Ensure you have Python 3.8+ and an OpenAI API key set in your environment variables to use DSPy for AI integrations.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the dspy package via pip and set your OPENAI_API_KEY environment variable to authenticate API calls.

bash
pip install dspy

Step by step

Here is a complete example to initialize DSPy with OpenAI GPT-4o-mini model and make a simple prediction.

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 signature class
class QA(dspy.Signature):
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

# Create a prediction instance
qa = dspy.Predict(QA)

# Run a prediction
result = qa(question="What is DSPy?")
print(result.answer)
output
DSPy is a declarative Python library for AI programming that simplifies calling language models.

Common variations

You can use different models by changing the model string in dspy.LM, or integrate with Anthropic by initializing DSPy with an Anthropic client. DSPy supports chain-of-thought reasoning with dspy.ChainOfThought.

python
from anthropic import Anthropic
import dspy

# Anthropic client example
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
lm = dspy.from_anthropic(client, model="claude-3-5-sonnet-20241022")
dspy.configure(lm=lm)

class QA(dspy.Signature):
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

qa = dspy.Predict(QA)
result = qa(question="Explain RAG.")
print(result.answer)
output
RAG stands for Retrieval-Augmented Generation, a technique that combines retrieval of documents with language model generation.

Troubleshooting

  • If you see ModuleNotFoundError: No module named 'dspy', ensure you installed DSPy with pip install dspy.
  • If API calls fail, verify your OPENAI_API_KEY environment variable is set correctly.
  • For model errors, confirm you are using a supported model string like openai/gpt-4o-mini.

Key Takeaways

  • Install DSPy with pip install dspy and set your API key via environment variables.
  • Use dspy.LM to configure your language model client for declarative AI programming.
  • DSPy supports multiple providers including OpenAI and Anthropic with simple client initialization.
  • Define input/output schemas with dspy.Signature for structured AI calls.
  • Check environment and model names carefully to avoid common setup errors.
Verified 2026-04 · openai/gpt-4o-mini, claude-3-5-sonnet-20241022
Verify ↗