This repository contains a Python script, dspy_LabeledFewShot.py, that demonstrates how to use the dspy.teleprompt.LabeledFewShot optimizer for sentiment analysis.
The script defines a simple DSPy program to classify the sentiment of a sentence as "Positive", "Negative", or "Neutral". It then uses LabeledFewShot to "compile" this program by creating few-shot prompts from a small training set. Finally, it runs the compiled program on a new sentence and inspects the prompt sent to the Language Model (LLM) to show how the few-shot examples were included.
- Python 3.13+
- uv
The script uses uv to manage and run a virtual environment with the required dependencies.
-
Set Environment Variables:
You need to provide your OpenAI API key. The script will read it from the
OPENAI_API_KEYenvironment variable.export OPENAI_API_KEY="your-openai-api-key"
If you are using a custom OpenAI-compatible API endpoint (like a local LLM server or a proxy), you can specify its URL via the
OPENAI_API_BASEenvironment variable.export OPENAI_API_BASE="http://your-api-base-url"
To run the script, make it executable and run it directly:
chmod +x dspy_LabeledFewShot.py
./dspy_LabeledFewShot.pyThe script will:
- Configure the
gpt-4.1-nanomodel via the OpenAI API. - Compile a sentiment classifier using 2 few-shot examples from the training data.
- Classify the sentiment of the sentence "This is a great day.".
- Print the predicted sentiment.
- Print the full prompt that was sent to the LLM, including the few-shot examples.
The output will look something like this (the exact few-shot examples may vary but will be drawn from the training set):
Sentence: This is a great day.
Predicted Sentiment: Positive
--- LLM Call History (last call) ---
Classify sentiment of a sentence.
---
Follow the following format.
Sentence: a sentence for sentiment analysis
Sentiment: The sentiment of the sentence (e.g., Positive, Negative, Neutral).
---
Sentence: I'm not sure how I feel about this.
Sentiment: Neutral
---
Sentence: The movie was fantastic!
Sentiment: Positive
---
Sentence: This is a great day.
Sentiment: