|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Fix OpenAI API key handling in notebooks to use real keys when available. |
| 4 | +
|
| 5 | +This script updates notebooks to not set dummy keys in CI environments, |
| 6 | +allowing them to use the real OPENAI_API_KEY from the environment. |
| 7 | +""" |
| 8 | + |
| 9 | +import json |
| 10 | +import sys |
| 11 | +from pathlib import Path |
| 12 | + |
| 13 | + |
| 14 | +def fix_notebook(notebook_path: Path) -> bool: |
| 15 | + """Fix OpenAI key handling in a single notebook.""" |
| 16 | + print(f"Processing: {notebook_path}") |
| 17 | + |
| 18 | + with open(notebook_path, 'r') as f: |
| 19 | + nb = json.load(f) |
| 20 | + |
| 21 | + modified = False |
| 22 | + |
| 23 | + for cell in nb['cells']: |
| 24 | + if cell['cell_type'] == 'code': |
| 25 | + # Check if this cell has the _set_env function |
| 26 | + source_text = ''.join(cell['source']) |
| 27 | + if '_set_env' in source_text and 'sk-dummy-key-for-testing-purposes-only' in source_text: |
| 28 | + # Replace the dummy key logic |
| 29 | + new_source = [] |
| 30 | + for line in cell['source']: |
| 31 | + if 'sk-dummy-key-for-testing-purposes-only' in line: |
| 32 | + # Skip setting a dummy key - just pass |
| 33 | + new_source.append(' pass # Let it fail if key is actually needed\n') |
| 34 | + modified = True |
| 35 | + elif '# Non-interactive environment (like CI) - use a dummy key' in line: |
| 36 | + new_source.append(' # Non-interactive environment (like CI)\n') |
| 37 | + modified = True |
| 38 | + elif 'Non-interactive environment detected. Using dummy' in line: |
| 39 | + new_source.append(' print(f"⚠️ {key} not found in environment. Some features may not work.")\n') |
| 40 | + modified = True |
| 41 | + else: |
| 42 | + new_source.append(line) |
| 43 | + |
| 44 | + if modified: |
| 45 | + cell['source'] = new_source |
| 46 | + |
| 47 | + if modified: |
| 48 | + with open(notebook_path, 'w') as f: |
| 49 | + json.dump(nb, f, indent=2, ensure_ascii=False) |
| 50 | + f.write('\n') # Add trailing newline |
| 51 | + print(f" ✅ Updated {notebook_path.name}") |
| 52 | + return True |
| 53 | + else: |
| 54 | + print(f" ⏭️ No changes needed for {notebook_path.name}") |
| 55 | + return False |
| 56 | + |
| 57 | + |
| 58 | +def main(): |
| 59 | + notebooks_dir = Path(__file__).parent.parent / 'notebooks' |
| 60 | + |
| 61 | + # Find all notebooks in section-3 and section-4 |
| 62 | + patterns = [ |
| 63 | + 'section-3-memory/*.ipynb', |
| 64 | + 'section-4-optimizations/*.ipynb' |
| 65 | + ] |
| 66 | + |
| 67 | + total_updated = 0 |
| 68 | + |
| 69 | + for pattern in patterns: |
| 70 | + for notebook_path in notebooks_dir.glob(pattern): |
| 71 | + if fix_notebook(notebook_path): |
| 72 | + total_updated += 1 |
| 73 | + |
| 74 | + print(f"\n✅ Updated {total_updated} notebooks") |
| 75 | + return 0 |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == '__main__': |
| 79 | + sys.exit(main()) |
| 80 | + |
0 commit comments