Skip to content

Commit 2e79291

Browse files
committed
Add create_notebook function to notebook toolkit
This function creates a new empty Jupyter notebook at the specified file path with proper nbformat structure, including directory creation if needed.
1 parent 0150308 commit 2e79291

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

jupyter_ai_tools/toolkits/notebook.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import asyncio
22
import difflib
33
import json
4+
import os
45
import re
56
from typing import Any, Dict, Literal, Optional, Tuple
67

@@ -911,6 +912,44 @@ def _determine_insert_index(cells_count: int, cell_index: Optional[int], add_abo
911912
return insert_index
912913

913914

915+
async def create_notebook(file_path: str) -> str:
916+
"""Creates a new empty Jupyter notebook at the specified file path.
917+
918+
This function creates a new empty notebook with proper nbformat structure.
919+
If the file already exists, it will return an error message.
920+
921+
Args:
922+
file_path:
923+
The path where the new notebook should be created.
924+
925+
Returns:
926+
A success message or error message.
927+
"""
928+
try:
929+
file_path = normalize_filepath(file_path)
930+
931+
# Check if file already exists
932+
if os.path.exists(file_path):
933+
return f"Error: File already exists at {file_path}"
934+
935+
# Ensure the directory exists
936+
directory = os.path.dirname(file_path)
937+
if directory and not os.path.exists(directory):
938+
os.makedirs(directory, exist_ok=True)
939+
940+
# Create a new empty notebook
941+
notebook = nbformat.v4.new_notebook()
942+
943+
# Write the notebook to the file
944+
with open(file_path, "w", encoding="utf-8") as f:
945+
nbformat.write(notebook, f)
946+
947+
return f"Successfully created new notebook at {file_path}"
948+
949+
except Exception as e:
950+
return f"Error: Failed to create notebook: {str(e)}"
951+
952+
914953

915954
toolkit = Toolkit(
916955
name="notebook_toolkit",
@@ -923,3 +962,4 @@ def _determine_insert_index(cells_count: int, cell_index: Optional[int], add_abo
923962
toolkit.add_tool(Tool(callable=delete_cell, delete=True))
924963
toolkit.add_tool(Tool(callable=edit_cell, read=True, write=True))
925964
toolkit.add_tool(Tool(callable=get_cell_id_from_index, read=True))
965+
toolkit.add_tool(Tool(callable=create_notebook, write=True))

0 commit comments

Comments
 (0)