Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pip install jupyterlab_commands_toolkit
The extension provides a toolkit for Jupyter AI with the following tools:

1. **open_document_tool**: Open documents in JupyterLab with various layout modes
2. **open_markdown_preview_tool**: Open markdown files in rendered preview mode
2. **open_markdown_preview_tool**: Open markdown files in rendered preview mode
3. **clear_notebook_outputs_tool**: Clear all outputs in the active notebook
4. **show_notebook_diff_tool**: Show git diff for the current notebook using nbdime

Expand Down
69 changes: 58 additions & 11 deletions jupyterlab_commands_toolkit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
# in editable mode with pip. It is highly recommended to install
# the package from a stable release or in editable mode: https://pip.pypa.io/en/stable/topics/local-project-installs/#editable-installs
import warnings
warnings.warn("Importing 'jupyterlab_commands_toolkit' outside a proper installation.")

warnings.warn(
"Importing 'jupyterlab_commands_toolkit' outside a proper installation."
)
__version__ = "dev"

import pathlib
Expand All @@ -20,19 +23,63 @@
# If jupyter-ai is not available, the AI toolkit won't be available
toolkit = None


def _jupyter_labextension_paths():
return [{
"src": "labextension",
"dest": "jupyterlab-commands-toolkit"
}]
return [{"src": "labextension", "dest": "jupyterlab-commands-toolkit"}]


def _jupyter_server_extension_points():
return [{
"module": "jupyterlab_commands_toolkit"
}]
return [{"module": "jupyterlab_commands_toolkit"}]


def _load_jupyter_server_extension(serverapp: ServerApp):
schema_path = pathlib.Path(__file__).parent / "events" / "jupyterlab-command.yml"
serverapp.event_logger.register_event_schema(schema_path)
serverapp.log.info("jupyterlab_commands_toolkit extension loaded.")
command_schema_path = (
pathlib.Path(__file__).parent / "events" / "jupyterlab-command.yml"
)
serverapp.event_logger.register_event_schema(command_schema_path)

result_schema_path = (
pathlib.Path(__file__).parent / "events" / "jupyterlab-command-result.yml"
)
serverapp.event_logger.register_event_schema(result_schema_path)

async def command_result_listener(logger, schema_id: str, data: dict) -> None:
"""
Handle command result events from the frontend.

This listener receives the results of JupyterLab commands that were
executed in the frontend and processes them accordingly.
"""
from .tools import handle_command_result

try:
request_id = data.get("requestId", "unknown")
success = data.get("success", False)
result = data.get("result")
error = data.get("error")

serverapp.log.info(
f"Received command result for request {request_id}: success={success}"
)

if success:
if result is not None:
serverapp.log.debug(f"Command result: {result}")
else:
serverapp.log.warning(f"Command failed: {error}")

handle_command_result(data)

except Exception as e:
serverapp.log.error(f"Error processing command result: {e}")

result_schema_id = (
"https://events.jupyter.org/jupyterlab_command_toolkit/lab_command_result/v1"
)
serverapp.event_logger.add_listener(
schema_id=result_schema_id, listener=command_result_listener
)

serverapp.log.info(
"jupyterlab_commands_toolkit extension loaded with bidirectional event communication."
)
22 changes: 22 additions & 0 deletions jupyterlab_commands_toolkit/events/jupyterlab-command-result.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"$id": https://events.jupyter.org/jupyterlab_command_toolkit/lab_command_result/v1
version: 1
title: A JupyterLab Command Execution Result
personal-data: true
description: |
Result of a JupyterLab Command execution
type: object
required:
- requestId
- success
properties:
requestId:
type: string
description: The unique identifier for the command request
success:
type: boolean
description: Whether the command executed successfully
result:
description: The result data from the command execution
error:
type: string
description: Error message if the command failed
103 changes: 54 additions & 49 deletions jupyterlab_commands_toolkit/toolkit.py
Original file line number Diff line number Diff line change
@@ -1,50 +1,55 @@
"""JupyterLab Commands toolkit for Jupyter AI"""
from jupyter_ai.tools.models import Tool, Toolkit

from typing import Optional
from .tools import (
open_document,
open_markdown_file_in_preview_mode,
clear_all_outputs_in_notebook,
show_diff_of_current_notebook,
INSERT_MODE
)

# Create the toolkit
toolkit = Toolkit(
name="jupyterlab_commands_toolkit",
description="""A comprehensive toolkit for controlling JupyterLab interface and performing notebook operations through AI commands.
This toolkit provides programmatic access to JupyterLab's core functionality, enabling AI assistants to:
**Document Management:**
- Open files, notebooks, and documents with precise control over layout positioning
- Support for split-pane layouts (top, left, right, bottom) and tab management
- Open markdown files in rendered preview mode for better readability
**Notebook Operations:**
- Clear all cell outputs in the active notebook for cleanup and sharing
- Display git diffs for notebooks using nbdime visualization
- Maintain notebook structure while performing operations
**Layout Control:**
- Split current workspace into multiple panes
- Merge content with adjacent areas
- Create new tabs before or after current position
- Flexible positioning options for optimal workspace organization
**Key Features:**
- Event-driven architecture using JupyterLab's command system
- Seamless integration with Jupyter AI for natural language control
- Support for relative file paths from server root directory
- Comprehensive error handling and user feedback
- Compatible with JupyterLab 4.0+ and modern Jupyter environments
Use these tools to programmatically manage your JupyterLab workspace, organize documents, and perform common notebook operations through conversational AI interfaces."""
)

# Add tools to the toolkit
toolkit.add_tool(Tool(callable=open_document, read=True))
toolkit.add_tool(Tool(callable=open_markdown_file_in_preview_mode, read=True))
toolkit.add_tool(Tool(callable=clear_all_outputs_in_notebook, read=True))
toolkit.add_tool(Tool(callable=show_diff_of_current_notebook, read=True))

try:
from jupyter_ai.tools.models import Tool, Toolkit

from typing import Optional
from .tools import (
open_document,
open_markdown_file_in_preview_mode,
clear_all_outputs_in_notebook,
show_diff_of_current_notebook,
INSERT_MODE,
)

# Create the toolkit
toolkit = Toolkit(
name="jupyterlab_commands_toolkit",
description="""A comprehensive toolkit for controlling JupyterLab interface and performing notebook operations through AI commands.
This toolkit provides programmatic access to JupyterLab's core functionality, enabling AI assistants to:
**Document Management:**
- Open files, notebooks, and documents with precise control over layout positioning
- Support for split-pane layouts (top, left, right, bottom) and tab management
- Open markdown files in rendered preview mode for better readability
**Notebook Operations:**
- Clear all cell outputs in the active notebook for cleanup and sharing
- Display git diffs for notebooks using nbdime visualization
- Maintain notebook structure while performing operations
**Layout Control:**
- Split current workspace into multiple panes
- Merge content with adjacent areas
- Create new tabs before or after current position
- Flexible positioning options for optimal workspace organization
**Key Features:**
- Event-driven architecture using JupyterLab's command system
- Seamless integration with Jupyter AI for natural language control
- Support for relative file paths from server root directory
- Comprehensive error handling and user feedback
- Compatible with JupyterLab 4.0+ and modern Jupyter environments
Use these tools to programmatically manage your JupyterLab workspace, organize documents, and perform common notebook operations through conversational AI interfaces.""",
)

# Add tools to the toolkit
toolkit.add_tool(Tool(callable=open_document, read=True))
toolkit.add_tool(Tool(callable=open_markdown_file_in_preview_mode, read=True))
toolkit.add_tool(Tool(callable=clear_all_outputs_in_notebook, read=True))
toolkit.add_tool(Tool(callable=show_diff_of_current_notebook, read=True))
except ImportError:
# If jupyter-ai is not available, the AI toolkit won't be available
toolkit = None
Loading