Chapter 1 ยท Section 6

Exercises

Practice what you've learned in this chapter with these hands-on exercises.

~1-2 hours

๐Ÿ“‹ 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
Exercise 1 โญ Beginner

Verify Your DSPy Installation

Objective: Confirm that DSPy is properly installed and configured.

Requirements

Create a script that:

  1. Imports DSPy successfully
  2. Prints the DSPy version
  3. Checks for an API key in environment variables
  4. Creates and configures a language model
  5. 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!
Exercise 2 โญ Beginner

Create Custom Signatures

Objective: Practice creating DSPy signatures for different tasks.

Requirements

Create signatures for:

  1. Translation: Translate English text to Spanish
  2. Sentiment Analysis: Classify text as positive, negative, or neutral
  3. Summarization: Create a brief summary of text
  4. 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
Exercise 3 โญโญ Intermediate

Configure Multiple Language Models

Objective: Learn to configure and switch between different language models.

Requirements

Create a program that:

  1. Configures three different LMs (fast, powerful, local)
  2. Defines a simple Q&A signature
  3. Tests the same question with all three models
  4. Compares the responses
  5. 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
Exercise 4 โญโญ Intermediate

Build a Simple Q&A System

Objective: Build a complete question-answering system with context.

Requirements

Create a Q&A system that:

  1. Takes a context (paragraph of text) and a question
  2. Uses DSPy to answer the question based only on the context
  3. Provides a confidence level (high/medium/low)
  4. Cites which part of the context was used
  5. 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!
    }
]
Exercise 5 โญโญโญ Advanced

Multi-Step Classification Pipeline

Objective: Build a multi-step pipeline that processes text through multiple stages.

Requirements

Create a pipeline that:

  1. Step 1: Extracts the main topic from input text
  2. Step 2: Classifies the sentiment (positive/negative/neutral)
  3. Step 3: Determines the intended audience (general/technical/academic)
  4. Step 4: Generates a summary tailored to the audience
  5. 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:

โ˜ Exercise 1: Installation verification
โ˜ Exercise 2: Custom signatures
โ˜ Exercise 3: Multiple models
โ˜ Exercise 4: Q&A system
โ˜ Exercise 5: Multi-step pipeline
๐Ÿ’ก

Important: Try to solve exercises yourself before looking at solutions!

๐ŸŽ‰

Great Work!

You've completed the exercises! Ready to check your solutions?