Getting Started with DSPy

Current Version: 2.6.16

Offical Doc:

https://dspy.ai/

Install

1
pip install dspy

Config

OPENAI

1
2
3
import dspy
lm = dspy.LM('openai/gpt-4o-mini', api_key='YOUR_OPENAI_API_KEY')
dspy.configure(lm=lm)

or

Other providers

1
2
3
import dspy
lm = dspy.LM('openai/your-model-name', api_key='PROVIDER_API_KEY', api_base='YOUR_PROVIDER_URL')
dspy.configure(lm=lm)
1
2
3
4
5
6
7
8
9
10
11
from typing import Literal

class Classify(dspy.Signature):
"""Classify sentiment of a given sentence."""

sentence: str = dspy.InputField()
sentiment: Literal['positive', 'negative', 'neutral'] = dspy.OutputField()
confidence: float = dspy.OutputField()

classify = dspy.Predict(Classify)
classify(sentence="This book was super fun to read, though not the last chapter.")

Getting Started with DSPy
https://www.hardyhu.cn/2025/04/08/Getting-Started-with-DSPy/
Author
John Doe
Posted on
April 8, 2025
Licensed under