๐ Exercise Overview
| Exercise | Difficulty | Topics Covered | Est. Time |
|---|---|---|---|
| Exercise 1 | โญ Beginner | Installation verification | 10-15 min |
| Exercise 2 | โญ Beginner | Basic signatures | 15-20 min |
| Exercise 3 | โญโญ Intermediate | Language model configuration | 20-25 min |
| Exercise 4 | โญโญ Intermediate | Building a Q&A system | 30-40 min |
| Exercise 5 | โญโญโญ Advanced | Multi-step pipeline | 45-60 min |
Verify Your DSPy Installation
Objective: Confirm that DSPy is properly installed and configured.
Requirements
Create a script that:
- Imports DSPy successfully
- Prints the DSPy version
- Checks for an API key in environment variables
- Creates and configures a language model
- Runs a simple test prediction
Starter Code
"""
Exercise 1: Verify DSPy Installation
"""
import os
from dotenv import load_dotenv
import dspy
def main():
# TODO: Load environment variables
# TODO: Print DSPy version
# TODO: Check for API key
# TODO: Configure language model
# TODO: Run a test prediction
pass
if __name__ == "__main__":
main()
Expected Output
DSPy Installation Check ======================= โ DSPy version: 2.5.x โ API key found โ Language model configured โ Test prediction successful Test question: What is 2+2? Test answer: 4 All checks passed!
Create Custom Signatures
Objective: Practice creating DSPy signatures for different tasks.
Requirements
Create signatures for:
- Translation: Translate English text to Spanish
- Sentiment Analysis: Classify text as positive, negative, or neutral
- Summarization: Create a brief summary of text
- Entity Extraction: Extract named entities from text
Starter Code
"""
Exercise 2: Create Custom Signatures
"""
import dspy
# TODO: Create Translation signature
class Translate(dspy.Signature):
pass
# TODO: Create Sentiment Analysis signature
class AnalyzeSentiment(dspy.Signature):
pass
# TODO: Create Summarization signature
class Summarize(dspy.Signature):
pass
# TODO: Create Entity Extraction signature
class ExtractEntities(dspy.Signature):
pass
def test_signatures():
"""Test each signature"""
# TODO: Test each signature with dspy.Predict
pass
if __name__ == "__main__":
test_signatures()
Success Criteria
- โ All four signatures are properly defined
- โ Each signature has a clear docstring
- โ Field names are descriptive
- โ Output fields have helpful descriptions
- โ All signatures work with
dspy.Predict
Configure Multiple Language Models
Objective: Learn to configure and switch between different language models.
Requirements
Create a program that:
- Configures three different LMs (fast, powerful, local)
- Defines a simple Q&A signature
- Tests the same question with all three models
- Compares the responses
- Measures and reports response time for each
Expected Output
Testing Multiple Language Models ================================= Question: Explain quantum computing in simple terms Model: gpt-4o-mini Time: 1.2s Response: Quantum computing uses quantum mechanics to process information... Model: gpt-4o Time: 2.1s Response: Quantum computing is a revolutionary approach that leverages... Summary: -------- Fastest: gpt-4o-mini (1.2s) Most detailed: gpt-4o
Build a Simple Q&A System
Objective: Build a complete question-answering system with context.
Requirements
Create a Q&A system that:
- Takes a context (paragraph of text) and a question
- Uses DSPy to answer the question based only on the context
- Provides a confidence level (high/medium/low)
- Cites which part of the context was used
- Handles cases where the answer isn't in the context
Test Data
test_cases = [
{
"context": "Paris is the capital of France. It has a population of about 2.1 million people.",
"question": "What is the capital of France?"
},
{
"context": "Python was created by Guido van Rossum and released in 1991.",
"question": "Who created Python?"
},
{
"context": "The Great Wall of China is over 13,000 miles long.",
"question": "What is the main programming language used in AI?" # Not in context!
}
]
Multi-Step Classification Pipeline
Objective: Build a multi-step pipeline that processes text through multiple stages.
Requirements
Create a pipeline that:
- Step 1: Extracts the main topic from input text
- Step 2: Classifies the sentiment (positive/negative/neutral)
- Step 3: Determines the intended audience (general/technical/academic)
- Step 4: Generates a summary tailored to the audience
- Returns all results in a structured format
Starter Code
"""
Exercise 5: Multi-Step Classification Pipeline
"""
import dspy
from dotenv import load_dotenv
load_dotenv()
# TODO: Define signatures for each step
class TextAnalysisPipeline(dspy.Module):
"""Multi-step text analysis pipeline."""
def __init__(self):
# TODO: Initialize modules for each step
pass
def forward(self, text):
"""Process text through the pipeline."""
# TODO: Implement pipeline logic
# TODO: Return structured results
pass
def test_pipeline():
"""Test the pipeline with different texts."""
test_texts = [
"Machine learning models require large datasets and computational power. "
"Recent advances in transformer architectures have revolutionized NLP tasks.",
"I absolutely love this new restaurant! The food was amazing and the "
"service was excellent. Can't wait to go back!",
]
# TODO: Process each text
# TODO: Display results
pass
if __name__ == "__main__":
test_pipeline()
Expected Output
Processing: "Machine learning models require large datasets..." Results: ======== Topic: Machine Learning and NLP Sentiment: Neutral Audience: Technical Summary (for Technical audience): ML models need significant data and compute. Transformer architectures have significantly advanced NLP capabilities. --- Processing: "I absolutely love this new restaurant..." Results: ======== Topic: Restaurant Review Sentiment: Positive Audience: General Summary (for General audience): A very positive review praising both food quality and service.
๐ Progress Tracker
Track your completion:
Important: Try to solve exercises yourself before looking at solutions!