Skip to content

Commit

Permalink
pre-commit
Browse files Browse the repository at this point in the history
  • Loading branch information
dlqqq committed Dec 4, 2024
1 parent 956164b commit 5d89204
Show file tree
Hide file tree
Showing 6 changed files with 21 additions and 35 deletions.
20 changes: 6 additions & 14 deletions packages/jupyter-ai/jupyter_ai/chat_handlers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,19 +256,15 @@ async def process_message(self, message: HumanChatMessage):
"""
raise NotImplementedError("Should be implemented by subclasses.")

async def handle_exc(
self, e: Exception, message: HumanChatMessage
):
async def handle_exc(self, e: Exception, message: HumanChatMessage):
"""
Handles an exception raised by `self.process_message()`. A default
implementation is provided, however chat handlers (subclasses) should
implement this method to provide a more helpful error response.
"""
await self._default_handle_exc(e, message)

async def _default_handle_exc(
self, e: Exception, message: HumanChatMessage
):
async def _default_handle_exc(self, e: Exception, message: HumanChatMessage):
"""
The default definition of `handle_exc()`. This is the default used when
the `handle_exc()` excepts.
Expand All @@ -285,13 +281,13 @@ async def _default_handle_exc(
f"Sorry, an error occurred. Details below:\n\n```\n{formatted_e}\n```"
)
self.reply(response, message)

def write_message(self, body: str, id: Optional[str] = None) -> None:
"""[Jupyter Chat only] Writes a message to the YChat shared document
that this chat handler is assigned to."""
if not self.ychat:
return

bot = self.ychat.get_user(BOT["username"])
if not bot:
self.ychat.set_user(BOT)
Expand Down Expand Up @@ -422,9 +418,7 @@ def pending(
TODO: Simplify it by only modifying the awareness as soon as jupyterlab chat
is the only used chat.
"""
pending_msg = self.start_pending(
text, human_msg=human_msg, ellipsis=ellipsis
)
pending_msg = self.start_pending(text, human_msg=human_msg, ellipsis=ellipsis)
try:
yield pending_msg
finally:
Expand Down Expand Up @@ -501,9 +495,7 @@ def output_dir(self) -> str:
else:
return self.root_dir

def send_help_message(
self, human_msg: Optional[HumanChatMessage] = None
) -> None:
def send_help_message(self, human_msg: Optional[HumanChatMessage] = None) -> None:
"""Sends a help message to all connected clients."""
lm_provider = self.config_manager.lm_provider
unsupported_slash_commands = (
Expand Down
4 changes: 1 addition & 3 deletions packages/jupyter-ai/jupyter_ai/chat_handlers/fix.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,4 @@ async def process_message(self, message: HumanChatMessage):
"error_name": selection.error.name,
"error_value": selection.error.value,
}
await self.stream_reply(
inputs, message, pending_msg="Analyzing error"
)
await self.stream_reply(inputs, message, pending_msg="Analyzing error")
4 changes: 1 addition & 3 deletions packages/jupyter-ai/jupyter_ai/chat_handlers/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,9 +273,7 @@ async def process_message(self, message: HumanChatMessage):
response = f"""🎉 I have created your notebook and saved it to the location {final_path}. I am still learning how to create notebooks, so please review all code before running it."""
self.reply(response, message)

async def handle_exc(
self, e: Exception, message: HumanChatMessage
):
async def handle_exc(self, e: Exception, message: HumanChatMessage):
timestamp = time.strftime("%Y-%m-%d-%H.%M.%S")
default_log_dir = Path(self.output_dir) / "jupyter-ai-logs"
log_dir = self.log_dir or default_log_dir
Expand Down
8 changes: 2 additions & 6 deletions packages/jupyter-ai/jupyter_ai/chat_handlers/learn.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,7 @@ async def process_message(self, message: HumanChatMessage):

if args.delete:
self.delete()
self.reply(
f"👍 I have deleted everything I previously learned.", message
)
self.reply(f"👍 I have deleted everything I previously learned.", message)
return

if args.list:
Expand Down Expand Up @@ -205,9 +203,7 @@ async def process_message(self, message: HumanChatMessage):
# delete and relearn index if embedding model was changed
await self.delete_and_relearn()

with self.pending(
f"Loading and splitting files for {load_path}", message
):
with self.pending(f"Loading and splitting files for {load_path}", message):
try:
await self.learn_dir(
load_path, args.chunk_size, args.chunk_overlap, args.all_files
Expand Down
18 changes: 10 additions & 8 deletions packages/jupyter-ai/jupyter_ai/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from functools import partial
from typing import Dict, Optional

import traitlets
from dask.distributed import Client as DaskClient
from importlib_metadata import entry_points
from jupyter_ai.chat_handlers.learn import Retriever
Expand All @@ -18,7 +19,6 @@
from jupyterlab_chat.ychat import YChat
from pycrdt import ArrayEvent
from tornado.web import StaticFileHandler
import traitlets
from traitlets import Integer, List, Unicode

from .chat_handlers import (
Expand Down Expand Up @@ -237,7 +237,7 @@ def initialize(self):
"""
Nested dictionary that returns the dedicated chat handler instance that
should be used, given the room ID and command ID respectively.
Example: `self.chat_handlers_by_room[<room_id>]` yields the set of chat
handlers dedicated to the room identified by `<room_id>`.
"""
Expand All @@ -249,11 +249,11 @@ def initialize(self):
self.event_logger.add_listener(
schema_id=JUPYTER_COLLABORATION_EVENTS_URI, listener=self.connect_chat
)

async def connect_chat(
self, logger: EventLogger, schema_id: str, data: dict
) -> None:
# ignore events that are not chat room initialization events
# ignore events that are not chat room initialization events
if not (
data["room"].startswith("text:chat:")
and data["action"] == "initialize"
Expand All @@ -276,7 +276,7 @@ async def connect_chat(
)
if ychat.awareness is not None:
ychat.awareness.set_local_state_field("user", BOT)

# initialize chat handlers for new chat
self.chat_handlers_by_room[room_id] = self._init_chat_handlers(ychat)

Expand Down Expand Up @@ -504,11 +504,13 @@ async def _stop_extension(self):
await dask_client.close()
self.log.debug("Closed Dask client.")

def _init_chat_handlers(self, ychat: Optional[YChat] = None) -> Dict[str, BaseChatHandler]:
def _init_chat_handlers(
self, ychat: Optional[YChat] = None
) -> Dict[str, BaseChatHandler]:
"""
Initializes a set of chat handlers. May accept a YChat instance for
collaborative chats.
TODO: Make `ychat` required once Jupyter Chat migration is complete.
"""
eps = entry_points()
Expand All @@ -528,7 +530,7 @@ def _init_chat_handlers(self, ychat: Optional[YChat] = None) -> Dict[str, BaseCh
"chat_handlers": chat_handlers,
"context_providers": self.settings["jai_context_providers"],
"message_interrupted": self.settings["jai_message_interrupted"],
"ychat": ychat
"ychat": ychat,
}
default_chat_handler = DefaultChatHandler(**chat_handler_kwargs)
clear_chat_handler = ClearChatHandler(**chat_handler_kwargs)
Expand Down
2 changes: 1 addition & 1 deletion packages/jupyter-ai/jupyter_ai/tests/test_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def broadcast_message(message: Message) -> None:
chat_handlers={},
context_providers={},
message_interrupted={},
ychat=None
ychat=None,
)


Expand Down

0 comments on commit 5d89204

Please sign in to comment.