Tutorial: Build a Sentiment Analyzer
In this tutorial, you'll build a complete sentiment analysis system using DSPy Code. Perfect for beginners!
What you'll learn:
- Creating DSPy Signatures
- Building Modules
- Validating code
- Running and testing
- Optimizing with GEPA
Time: 15 minutes
Prerequisites
- DSPy Code installed (Installation Guide)
- Basic understanding of Python
- (Optional) Ollama or OpenAI API key for better results
Step 1: Start DSPy Code
Open your terminal and start the CLI:
You'll see the welcome screen with the DSPy version.
Step 2: Initialize Your Project
Let's set up a new project:
This will:
- Create project configuration
- Index your DSPy installation
- Set up directories
Watch the Jokes!
During indexing, you'll see entertaining messages. This is normal and makes the wait fun!
Step 3: Connect a Model (Optional)
For better code generation, connect to a model:
If you have Ollama:
If you have OpenAI:
Without a Model?
No problem! DSPy Code can still generate code using templates. The code will be more generic but still functional.
Step 4: Generate the Sentiment Analyzer
Now, just describe what you want in plain English:
DSPy Code will generate complete code for you!
What You'll Get
A complete DSPy program with: - Signature definition - Module implementation - Example usage - Configuration
Step 5: Review the Generated Code
The CLI will show you the code with syntax highlighting. Let's understand what was generated:
The Signature
class SentimentSignature(dspy.Signature):
"""Analyze the sentiment of text."""
text: str = dspy.InputField(desc="Text to analyze")
sentiment: str = dspy.OutputField(desc="positive or negative")
What this does:
- Defines the input (text) and output (sentiment)
- Provides descriptions for the LLM
- Sets up the task specification
The Module
class SentimentAnalyzer(dspy.Module):
def __init__(self):
super().__init__()
self.predictor = dspy.ChainOfThought(SentimentSignature)
def forward(self, text):
return self.predictor(text=text)
What this does:
- Creates a DSPy Module
- Uses ChainOfThought for reasoning
- Implements the forward method
Example Usage
# Configure DSPy (example small OpenAI model)
dspy.settings.configure(lm=dspy.OpenAI(model="gpt-5-nano"))
# Create analyzer
analyzer = SentimentAnalyzer()
# Analyze text
result = analyzer(text="I love this product!")
print(result.sentiment) # Output: positive
Step 6: Save Your Code
Save the generated code:
The file will be saved to generated/sentiment_analyzer.py.
Step 7: Validate the Code
Check if the code follows best practices:
The validator will check:
- â Signature has proper InputField and OutputField
- â Module inherits from dspy.Module
- â Forward method is implemented correctly
- â No common mistakes
Fix Any Issues
If the validator finds issues, it will tell you exactly what to fix and how.
Step 8: Test the Analyzer
Run your sentiment analyzer:
DSPy Code will execute your code in a safe sandbox and show the results.
Example Output
Step 9: Generate Training Data
To optimize your analyzer, you need training data. Let's generate some:
DSPy Code will create training examples for you!
What You'll Get
Save the training data:
Step 10: Optimize with GEPA
Now let's optimize your analyzer using GEPA:
Optimization Cost (Cloud & Local)
- Cloud providers (OpenAI, Anthropic, Gemini): GEPA may perform many optimization calls. Only run
/optimizeif you're aware of the potential API cost and have a billing plan/quotas that can support it. - Local hardware: For smoother optimization with local models, we recommend at least 32 GB RAM.
This generates a complete GEPA optimization script!
What the script includes:
- Metric with feedback for GEPA
- Training data loader
- GEPA configuration
- Optimization execution code
Save the optimization script:
Step 11: Run the Optimization
Exit DSPy Code and run the optimization:
GEPA will:
- Load your training data
- Evaluate your current program
- Use reflection to improve prompts
- Evolve better instructions
- Save the optimized version
Real Optimization
This is REAL GEPA optimization, not a simulation! It uses reflection to evolve your prompts.
Step 12: Test the Optimized Version
The optimized program will be saved. Test it:
Compare the results with your original version!
What You Built
Congratulations! You just built:
- â A complete sentiment analysis system
- â Training data for optimization
- â GEPA optimization pipeline
- â Validated, production-ready code
Customization Ideas
Now that you have a working analyzer, try these enhancements:
Add More Sentiment Categories
Add Confidence Scores
Handle Multiple Languages
Add Aspect-Based Sentiment
Common Issues
Model Not Connected
If you see "No model connected":
Or work without a model using templates.
Code Not Saving
Check if code was generated:
If no code is shown, try generating again.
Validation Errors
Read the error messages carefully. They tell you exactly what to fix:
Follow the suggestions to fix issues.
Optimization Fails
Make sure you have:
- Training data saved
- DSPy configured with a model
- GEPA available in your DSPy version
Next Steps
Now that you've built a sentiment analyzer, try:
-
đ Build a RAG System
Create a question-answering system with retrieval
-
â Question Answering
Build a QA system that answers questions from context
-
⥠Advanced Optimization
Learn advanced GEPA techniques
-
đĻ Deploy Your Analyzer
Package and deploy your sentiment analyzer
Summary
In this tutorial, you learned:
- â How to use DSPy Code interactively
- â Generating DSPy code from natural language
- â Validating and testing your code
- â Creating training data
- â Optimizing with GEPA
- â Building a complete, production-ready system
Time to build something amazing! đ
Questions? Check the FAQ, Troubleshooting Guide, or open an issue.