Chapter 7 · Section 9

Exercises

Advanced practice exercises for mastering DSPy internals, performance, and deployment.

~45 min practice

Introduction

These exercises challenge you to apply advanced DSPy concepts to solve complex, real-world problems. You'll work with adapters, performance optimization, async programming, debugging, and deployment strategies.

Exercise 1: Build a Custom Database Adapter

Objective: Create a persistent database adapter for DSPy that caches predictions in PostgreSQL.

Python
class DatabaseAdapter(dspy.Adapter):
    """Implement a database adapter that caches results."""
    def __init__(self, connection_string):
        super().__init__()
        # TODO: Initialize connection
        pass

    def get(self, key):
        # TODO: Retrieve from DB
        pass
        
    def set(self, key, value):
        # TODO: Store in DB
        pass

Exercise 2: High-Performance Caching System

Objective: Implement a multi-level cache (L1 Memory, L2 Redis, L3 Disk) with smart eviction.

Python
class MultiLevelCache:
    """Implement L1/L2/L3 caching strategy."""
    def get(self, key):
        # TODO: check memory -> redis -> disk
        pass

Exercise 3: Async Streaming RAG

Objective: Build a system that can process concurrent document streams and queries asynchronously.

Hint: Use asyncio.Queue and aiohttp.

Exercise 5: Kubernetes Deployment

Objective: Create a full Kubernetes manifest (Deployment, Service, HPA) for a DSPy application.

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: dspy-app
# TODO: Complete the manifest