# Working with DSPy

## Table of Contents

- [Introduction](#introduction)
- [What is DSPy?](#what-is-dspy)
- [Why DSPy in CortexAI?](#why-dspy-in-cortexai)
- [Architecture Overview](#architecture-overview)
- [Implementation Details](#implementation-details)
- [How It Works](#how-it-works)
- [Pros and Cons](#pros-and-cons)
- [Usage Guide](#usage-guide)
- [Future Enhancements](#future-enhancements)

---

## Introduction

Recently I learned about DSPy and thought to give it a try in my very own [CortexAI application](https://webvictory.hashnode.dev/cortexai-building-tenant-aware-ai-insights-on-aws). CortexAI integrates **DSPy (Declarative Self-improving Python)** as an optional enhancement layer for AI-powered data insights generation. So lets learn what exactly DSPy integrating it into CortexAI, the benefits it provides, and how users can leverage it to get better insights from their data.

---

## What is DSPy?

**DSPy** is a framework for building LLM applications using a declarative, modular approach. Instead of manually crafting prompts and chaining API calls, DSPy allows developers to:

- **Define Signatures**: Specify input/output types and descriptions
- **Compose Modules**: Build reusable components like `ChainOfThought`, `ReAct`, etc.
- **Optimize Automatically**: Use optimizers to improve prompts, few-shot examples, and even fine-tune models
- **Abstract Models**: Switch between different LLMs without changing application logic

### Key Concepts

1. **Signatures**: Define what inputs and outputs your module expects

   ```python
   class DataInsightSignature(dspy.Signature):
       data_summary: str = dspy.InputField(...)
       user_question: str = dspy.InputField(...)
       insights: str = dspy.OutputField(...)
   ```
2. **Modules**: Reusable components that encapsulate LLM logic

   ```python
   class DataAnalysisModule(dspy.Module):
       def __init__(self):
           self.generate_insights = dspy.ChainOfThought(DataInsightSignature)
   ```
3. **Language Models**: Abstracted LLM interface (works with Bedrock, OpenAI, etc.)

   ```python
   lm = BedrockLM(model_id="anthropic.claude-3-sonnet-20240229-v1:0")
   dspy.configure(lm=lm)
   ```

---

## Why DSPy in CortexAI?

### The Problem

Before DSPy, CortexAI used direct API calls to Amazon Bedrock:

```typescript
// Direct Bedrock call (before DSPy)
const response = await bedrock.send(new InvokeModelCommand({
  modelId: 'anthropic.claude-3-sonnet-20240229-v1:0',
  body: JSON.stringify({
    system: "You are an expert data analyst...",
    messages: [{ role: "user", content: customPrompt }]
  })
}));
```

**Challenges:**

- Prompts were strings difficult to optimize
- No systematic way to improve prompt quality
- Switching models required code changes
- No structured way to handle few-shot examples
- Difficult to A/B test different prompt strategies

### The Solution

DSPy provides:

- **Modular Design**: Separate concerns (signatures, modules, optimizers)
- **Automatic Optimization**: Improve prompts using training examples
- **Model Abstraction**: Switch models without changing application code
- **Better Testing**: Structured evaluation and metrics
- **Maintainability**: Clear separation between logic and prompts

---

## Architecture Overview

### High-Level Architecture

```plaintext
FileAnalysis Component
                         │ HTTP Request
                         │ (useDspy=true/false)
                         ▼
┌─────────────────────────────────────────────────────────────┐
│              API Gateway                                    │
│  GET /insights?dataId=xxx&prompt=yyy&useDspy=true          │
└────────────────────────┬────────────────────────────────────┘
                         │
                         ▼
┌─────────────────────────────────────────────────────────────┐
│         TypeScript Insights Lambda                          │
│  ┌──────────────────────────────────────────────────────┐   │
│  │  if (useDspy) {                                      │   │
│  │    → Invoke DSPy Lambda                             │   │
│  │  } else {                                           │   │
│  │    → Direct Bedrock Call                            │   │
│  │  }                                                   │   │
│  └──────────────────────────────────────────────────────┘   │
└────────────┬───────────────────────────┬────────────────────┘
             │                           │
             │ (if useDspy=true)         │ (if useDspy=false)
             ▼                           ▼
┌──────────────────────────┐  ┌──────────────────────────┐
│   Python DSPy Lambda     │  │   Amazon Bedrock         │
│  ┌────────────────────┐  │  │   (Claude 3 Sonnet)     │
│  │ DSPy Module        │  │  └────────────────────────┘
│  │ - Signatures       │  │
│  │ - ChainOfThought   │  │
│  │ - Optimizations    │  │
│  └────────┬───────────┘  │
│           │               │
│           ▼               │
│  ┌────────────────────┐  │
│  │ BedrockLM Wrapper  │  │
│  └────────┬───────────┘  │
└───────────┼───────────────┘
            │
            ▼
┌──────────────────────────┐
│   Amazon Bedrock         │
│   (Claude 3 Sonnet)      │
└──────────────────────────┘
```

### Component Breakdown

1. **Frontend (React/Next.js)**
   - Checkbox to toggle DSPy on/off
   - Preference stored in localStorage
   - Sends `useDspy` parameter to API
2. **TypeScript Insights Lambda**
   - Receives `useDspy` from query parameters
   - Routes to DSPy Lambda or direct Bedrock
   - Handles rate limiting, validation, persistence
3. **Python DSPy Lambda**
   - Implements DSPy signatures and modules
   - Wraps Bedrock API calls
   - Can be optimized with training examples
4. **Amazon Bedrock**
   - Provides Claude 3 Sonnet model
   - Same model used regardless of path

---

## Implementation Details

### 1\. DSPy Signature Definition

```python
class DataInsightSignature(dspy.Signature):
    """Generate actionable insights from data analysis."""
    data_summary: str = dspy.InputField(
        desc="Summary of data structure, record count, quality score, and sample records"
    )
    user_question: str = dspy.InputField(
        desc="Specific question or prompt about the data"
    )
    insights: str = dspy.OutputField(
        desc="Detailed, actionable insights answering the user's question with specific data points and recommendations"
    )
```

**Why this matters:**

- Clear contract for inputs/outputs
- Self-documenting code
- Enables automatic prompt generation
- Type-safe interactions

### 2\. DSPy Module Implementation

```python
class DataAnalysisModule(dspy.Module):
    """DSPy module for generating data insights"""
    
    def __init__(self):
        super().__init__()
        self.generate_insights = dspy.ChainOfThought(DataInsightSignature)
    
    def forward(self, data_summary: str, user_question: str) -> str:
        """Generate insights from data summary and user question"""
        result = self.generate_insights(
            data_summary=data_summary,
            user_question=user_question
        )
        return result.insights
```

**ChainOfThought Benefits:**

- Encourages step-by-step reasoning
- Better structured outputs
- More reliable responses
- Easier to debug

### 3\. Bedrock Language Model Wrapper

```python
class BedrockLM(dspy.LM):
    """DSPy Language Model wrapper for Amazon Bedrock"""
    
    def __init__(self, model_id: str = BEDROCK_MODEL_ID):
        super().__init__(model_id)
        self.model_id = model_id
        self.bedrock = bedrock_client
    
    def basic_request(self, prompt: str, **kwargs) -> str:
        # Convert DSPy prompt to Bedrock API format
        # Handle system prompts, temperature, max_tokens
        # Return parsed response
```

**Abstraction Benefits:**

- DSPy doesn't need to know Bedrock specifics
- Easy to switch to other models (OpenAI, Anthropic API, etc.)
- Consistent interface across models

### 4\. Frontend Integration

```typescript
// Checkbox state with localStorage persistence
const [useDspy, setUseDspy] = useState(() => {
  const saved = localStorage.getItem('useDspy')
  return saved !== null ? saved === 'true' : true
})

// API call with useDspy parameter
const response = await get({
  apiName: 'CortexAI',
  path: 'insights',
  options: {
    queryParams: {
      dataId: file.dataId,
      prompt: prompt,
      useDspy: useDspy.toString() // User preference
    }
  }
})
```

---

## How It Works

### Step-by-Step Flow

1. **User Action**
   - User selects a file and enters a prompt
   - Toggles DSPy checkbox (on by default)
   - Clicks "Generate"
2. **Frontend Request**
   - Sends GET request to `/insights` with:
     - `dataId`: File identifier
     - `prompt`: User's question
     - `useDspy`: `"true"` or `"false"`
3. **TypeScript Lambda Processing**
   - Validates prompt length (max 100 chars)
   - Checks rate limits (6 requests/minute)
   - Fetches file metadata from DynamoDB
   - Retrieves data from S3
4. **Routing Decision**

   ```typescript
   if (shouldUseDspy && DSPY_LAMBDA_NAME) {
     // Invoke Python DSPy Lambda
     const dspyResponse = await lambdaClient.send(new InvokeCommand({
       FunctionName: DSPY_LAMBDA_NAME,
       Payload: JSON.stringify({
         dataSummary: buildDataSummary(...),
         prompt: prompt,
         dataId, tenantId
       })
     }))
   } else {
     // Direct Bedrock call
     const response = await bedrock.send(new InvokeModelCommand({...}))
   }
   ```
5. **DSPy Lambda Processing** (if enabled)
   - Initializes DSPy with BedrockLM
   - Builds structured data summary
   - Calls `DataAnalysisModule.forward()`
   - DSPy generates optimized prompt internally
   - Calls Bedrock API via wrapper
   - Returns structured insights
6. **Response Handling**
   - Insights saved to DynamoDB (with history)
   - Response returned to frontend
   - UI displays insights in scrollable area

### Data Flow Example

**Input:**

```json
{
  "dataId": "abc-123",
  "prompt": "What are the top products?",
  "useDspy": "true"
}
```

**DSPy Processing:**

```plaintext
1. Data Summary Built:
   - Record count: 1000
   - Quality score: 85
   - Fields: product, sales, date
   - Sample: [{"product": "A", "sales": 100}, ...]

2. DSPy Signature Called:
   - Input: data_summary + user_question
   - ChainOfThought reasoning
   - Output: structured insights

3. Bedrock API Call:
   - System prompt: (auto-generated by DSPy)
   - User prompt: (optimized by DSPy)
   - Response: Detailed insights
```

**Output:**

```json
{
  "insights": "Top products by sales: Product A (25%), Product B (20%)...",
  "model": "dspy-optimized",
  "modelId": "anthropic.claude-3-sonnet-20240229-v1:0"
}
```

---

## Pros and Cons

### ✅ Pros

#### 1\. **Modularity and Maintainability**

- **Before**: Prompts scattered throughout code, hard to update
- **After**: Centralized signatures and modules, easy to modify
- **Benefit**: Changes to prompts don't require code changes

#### 2\. **Automatic Optimization**

- DSPy can optimize prompts using training examples
- BootstrapFewShot optimizer improves few-shot examples
- Can fine-tune for specific use cases
- **Benefit**: Better insights quality over time

#### 3\. **Model Abstraction**

- Switch between models without changing application code
- Test different models (Claude, GPT-4, etc.) easily
- **Benefit**: Flexibility to choose best model per use case

#### 4\. **Structured Outputs**

- Type-safe signatures ensure consistent outputs
- Easier to parse and validate responses
- **Benefit**: More reliable integration with downstream systems

#### 5\. **Better Testing**

- Can evaluate modules with metrics
- A/B test different prompt strategies
- **Benefit**: Data-driven improvements

#### 6\. **User Control**

- Users can toggle DSPy on/off
- Preference persists across sessions
- **Benefit**: Users can compare and choose what works best

### ❌ Cons

#### 1\. **Additional Complexity**

- **Challenge**: Two Lambda functions instead of one
- **Impact**: More moving parts to deploy and monitor
- **Mitigation**: Well-documented architecture, automated deployment

#### 2\. **Latency Overhead**

- **Challenge**: Extra Lambda invocation adds ~50-100ms
- **Impact**: Slightly slower response times
- **Mitigation**: Acceptable trade-off for better quality, can optimize

#### 3\. **Python Dependency**

- **Challenge**: Need Python runtime in Lambda
- **Impact**: Larger deployment package, different language
- **Mitigation**: CDK handles bundling automatically

#### 4\. **Learning Curve**

- **Challenge**: Team needs to understand DSPy concepts
- **Impact**: Initial setup and optimization requires DSPy knowledge
- **Mitigation**: Good documentation, gradual adoption

#### 5\. **Optimization Requires Data**

- **Challenge**: Need training examples for optimization
- **Impact**: Initial setup requires collecting examples
- **Mitigation**: Works without optimization, can improve over time

#### 6\. **Cost Considerations**

- **Challenge**: Additional Lambda invocation cost
- **Impact**: ~$0.20 per 1M requests (512MB, 1s avg)
- **Mitigation**: Minimal compared to Bedrock API costs

### Trade-off Summary

| Aspect | Direct Bedrock | DSPy |
| --- | --- | --- |
| **Latency** | Lower (~500ms) | Higher (~600ms) |
| **Maintainability** | Lower | Higher |
| **Optimization** | Manual | Automatic |
| **Flexibility** | Lower | Higher |
| **Complexity** | Lower | Higher |
| **Cost** | Lower | Slightly Higher |

**Recommendation**: Use DSPy when:

- You want to improve insights quality over time
- You have training examples for optimization
- Maintainability is important
- You want to experiment with different models

Use Direct Bedrock when:

- Latency is critical
- You have simple, stable prompts
- You want minimal complexity

---

## Usage Guide

### For End Users

1. **Enable DSPy** (default):
   - Checkbox is checked by default
   - Generate insights normally
   - DSPy will optimize the prompt automatically
2. **Disable DSPy**:
   - Uncheck "Use DSPy Optimization" checkbox
   - Generate insights
   - Uses direct Bedrock call (faster, simpler)
3. **Compare Results**:
   - Generate insights with DSPy enabled
   - Generate same insights with DSPy disabled
   - Compare quality and choose preference

### For Developers

#### Running Optimization

```bash
cd infra/scripts
python optimize-dspy-prompts.py
```

This will:

1. Load training examples from `dspy-training-examples.json`
2. Optimize prompts using BootstrapFewShot
3. Save optimized prompts to `optimized-dspy-prompts.json`

#### Adding Training Examples

Create `infra/scripts/dspy-training-examples.json`:

```json
[
  {
    "data_summary": "Sales data with 1000 records\nQuality score: 85\nFields: product, sales",
    "user_question": "What are the top products?",
    "insights": "Top products: Product A (25%), Product B (20%)..."
  }
]
```

#### Monitoring

Check CloudWatch Logs:

- **DSPy Lambda**: `/aws/lambda/cortex-ai-{env}-dspy-insights`
- **Insights Lambda**: `/aws/lambda/cortex-ai-{env}-insights`

Look for:

- `Using DSPy Lambda for insights generation` (DSPy path)
- `Using direct Bedrock call` (Direct path)
- Error messages if DSPy fails

---

## Future Enhancements

### 1\. **Automatic Prompt Optimization**

- Run optimization script in CI/CD
- Deploy improved prompts automatically
- A/B test different prompt versions

### 2\. **Multi-Model Support**

- Support multiple models (Claude, GPT-4, etc.)
- Let users choose model per request
- Compare model performance

### 3\. **Custom Optimizers**

- Domain-specific optimizers for data analysis
- Fine-tune for specific industries
- Custom metrics for evaluation

### 4\. **Caching Layer**

- Cache optimized prompts
- Reduce Bedrock API calls
- Improve latency

### 5\. **Analytics Dashboard**

- Track DSPy vs Direct Bedrock usage
- Compare quality metrics
- User preference analytics

### 6\. **Fine-Tuning Support**

- Fine-tune models for specific use cases
- Use DSPy's BootstrapFinetune optimizer
- Deploy custom models

---

## Conclusion

DSPy integration in CortexAI provides a powerful, flexible approach to generating AI insights. While it adds some complexity, the benefits in terms of maintainability, optimization, and flexibility make it a valuable addition to the platform.

Users can choose whether to use DSPy based on their needs, and the system gracefully falls back to direct Bedrock calls when DSPy is disabled or unavailable.

The modular architecture allows for future enhancements like automatic optimization, multi-model support, and fine-tuning, making DSPy a solid foundation for evolving AI capabilities in CortexAI.

---

## References

- [DSPy Documentation](https://dspy-docs.vercel.app/)
- [DSPy GitHub Repository](https://github.com/stanfordnlp/dspy)
- [Amazon Bedrock Documentation](https://docs.aws.amazon.com/bedrock/)
- [CortexAI Architecture](./ARCHITECTURE.md)
