-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest_notebooks.py
More file actions
167 lines (135 loc) · 5.65 KB
/
test_notebooks.py
File metadata and controls
167 lines (135 loc) · 5.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#!/usr/bin/env python3
"""
Quick test to verify notebooks will work for users
"""
import os
import sys
import json
from pathlib import Path
def test_notebook_structure():
"""Test that notebooks have valid structure"""
notebooks_dir = Path("notebooks")
notebooks = list(notebooks_dir.glob("*.ipynb"))
print(f"📓 Found {len(notebooks)} notebooks:")
for notebook_path in notebooks:
print(f"\n📋 Testing {notebook_path.name}...")
try:
with open(notebook_path) as f:
notebook = json.load(f)
cells = notebook.get('cells', [])
code_cells = [c for c in cells if c.get('cell_type') == 'code']
markdown_cells = [c for c in cells if c.get('cell_type') == 'markdown']
print(f" ✅ Valid JSON structure")
print(f" 📊 {len(cells)} total cells ({len(code_cells)} code, {len(markdown_cells)} markdown)")
# Check first code cell has setup
if code_cells:
first_code = ''.join(code_cells[0].get('source', []))
if 'sys.path.append' in first_code and 'load_dotenv' in first_code:
print(f" ✅ Proper setup in first code cell")
else:
print(f" ⚠️ First code cell missing setup")
# Check for API key handling
has_api_check = False
for cell in code_cells:
source = ''.join(cell.get('source', []))
if 'OPENAI_API_KEY' in source and 'not api_key' in source:
has_api_check = True
break
if has_api_check:
print(f" ✅ Proper API key error handling")
else:
print(f" ⚠️ Missing API key error handling")
except Exception as e:
print(f" ❌ Error: {e}")
return True
def test_imports():
"""Test that all imports used in notebooks work"""
print(f"\n🔍 Testing notebook imports...")
try:
# Core dependencies
import dspy
import matplotlib.pyplot as plt
from IPython.display import HTML, display
import numpy as np
from dotenv import load_dotenv
# Our modules
from src.prompts.manager_style import create_customer_support_manager, ManagerStylePromptConfig
from src.techniques.escape_hatches import EscapeHatchResponder
from src.techniques.thinking_traces import ThinkingTracer
from src.techniques.few_shot import FewShotLearner, create_bug_analysis_examples
print(f" ✅ All notebook imports successful")
return True
except ImportError as e:
print(f" ❌ Import error: {e}")
return False
def test_basic_functionality():
"""Test core functionality without API calls"""
print(f"\n⚙️ Testing basic functionality...")
try:
# Test uncertainty detection (no API needed)
from src.techniques.escape_hatches import UncertaintyDetector
detector = UncertaintyDetector()
level, confidence = detector.detect_uncertainty("I might be wrong about this")
print(f" ✅ Uncertainty detection: {level} (confidence: {confidence:.2f})")
# Test config creation
from src.prompts.manager_style import ManagerStylePromptConfig
config = ManagerStylePromptConfig(
role_title="Test",
department="Test",
company_context="Test",
reporting_structure="Test",
key_responsibilities=["Test"],
performance_metrics=["Test"],
tools_and_resources=["Test"],
communication_style="Test",
decision_authority="Test",
escalation_procedures="Test",
constraints=["Test"],
examples_of_excellence=[{"title": "Test", "situation": "Test", "action": "Test", "result": "Test", "takeaway": "Test"}]
)
print(f" ✅ Config creation works")
return True
except Exception as e:
print(f" ❌ Functionality error: {e}")
return False
def main():
print("🧪 Testing DSpy Advanced Prompting Notebooks")
print("=" * 50)
# Check if we're in the right directory
if not Path("notebooks").exists():
print("❌ notebooks/ directory not found. Run from project root.")
return False
if not Path("src").exists():
print("❌ src/ directory not found. Run from project root.")
return False
# Run tests
tests = [
("Notebook Structure", test_notebook_structure),
("Import Dependencies", test_imports),
("Basic Functionality", test_basic_functionality)
]
results = []
for test_name, test_func in tests:
print(f"\n🔬 Running {test_name} test...")
try:
result = test_func()
results.append(result)
status = "✅ PASSED" if result else "❌ FAILED"
print(f" {status}")
except Exception as e:
print(f" ❌ FAILED with error: {e}")
results.append(False)
# Summary
passed = sum(results)
total = len(results)
print(f"\n" + "=" * 50)
print(f"📊 TEST SUMMARY: {passed}/{total} tests passed")
if passed == total:
print(f"✅ All notebooks should work correctly!")
print(f"📓 Users can run: jupyter notebook notebooks/")
else:
print(f"⚠️ Some issues found. Check output above.")
return passed == total
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)