Skip to content

Commit

Permalink
Add filter by (#6090)
Browse files Browse the repository at this point in the history
  • Loading branch information
ahuang11 authored Jan 12, 2024
1 parent eac968a commit 1804d15
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 11 deletions.
24 changes: 24 additions & 0 deletions examples/reference/chat/ChatFeed.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,30 @@
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The messages can be filtered by using a custom `filter_by` function."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def filter_by_reactions(messages):\n",
" return [message for message in messages if \"favorite\" in message.reactions]\n",
"\n",
"\n",
"chat_feed.send(\n",
" pn.chat.ChatMessage(\"I'm a message with a reaction!\", reactions=[\"favorite\"])\n",
")\n",
"\n",
"chat_feed.serialize(filter_by=filter_by_reactions)"
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down
23 changes: 16 additions & 7 deletions panel/chat/feed.py
Original file line number Diff line number Diff line change
Expand Up @@ -694,6 +694,7 @@ def clear(self) -> List[Any]:

def _serialize_for_transformers(
self,
messages: List[ChatMessage],
role_names: Dict[str, str | List[str]] | None = None,
default_role: str | None = "assistant",
custom_serializer: Callable = None
Expand All @@ -716,8 +717,8 @@ def _serialize_for_transformers(
for name in names:
names_role[name.lower()] = role

messages = []
for message in self._chat_log.objects:
serialized_messages = []
for message in messages:

lowercase_name = message.user.lower()
if lowercase_name not in names_role and not default_role:
Expand All @@ -738,11 +739,12 @@ def _serialize_for_transformers(
else:
content = str(message)

messages.append({"role": role, "content": content})
return messages
serialized_messages.append({"role": role, "content": content})
return serialized_messages

def serialize(
self,
filter_by: Callable | None = None,
format: Literal["transformers"] = "transformers",
custom_serializer: Callable | None = None,
**serialize_kwargs
Expand All @@ -755,10 +757,13 @@ def serialize(
format : str
The format to export the chat log as; currently only
supports "transformers".
filter_by : callable
A function to filter the chat log by.
The function must accept and return a list of ChatMessage objects.
custom_serializer : callable
A custom function to format the ChatMessage's object. The function must
accept one positional argument. If not provided,
uses the serialize method on ChatMessage.
accept one positional argument, the ChatMessage object, and return a string.
If not provided, uses the serialize method on ChatMessage.
**serialize_kwargs
Additional keyword arguments to use for the specified format.
Expand All @@ -777,9 +782,13 @@ def serialize(
-------
The chat log serialized in the specified format.
"""
messages = self._chat_log.objects.copy()
if filter_by is not None:
messages = filter_by(messages)

if format == "transformers":
return self._serialize_for_transformers(
custom_serializer=custom_serializer, **serialize_kwargs
messages, custom_serializer=custom_serializer, **serialize_kwargs
)
raise NotImplementedError(f"Format {format!r} is not supported.")

Expand Down
11 changes: 7 additions & 4 deletions panel/chat/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from ..widgets.button import Button
from ..widgets.input import FileInput, TextInput
from .feed import CallbackState, ChatFeed
from .message import _FileInputMessage
from .message import ChatMessage, _FileInputMessage


@dataclass
Expand Down Expand Up @@ -543,6 +543,7 @@ def active(self, index: int) -> None:

def _serialize_for_transformers(
self,
messages: List[ChatMessage],
role_names: Dict[str, str | List[str]] | None = None,
default_role: str | None = "assistant",
custom_serializer: Callable = None
Expand All @@ -552,6 +553,8 @@ def _serialize_for_transformers(
Arguments
---------
messages : list(ChatMessage)
A list of ChatMessage objects to serialize.
role_names : dict(str, str | list(str)) | None
A dictionary mapping the role to the ChatMessage's user name.
Defaults to `{"user": [self.user], "assistant": [self.callback_user]}`
Expand All @@ -563,8 +566,8 @@ def _serialize_for_transformers(
If this is set to None, raises a ValueError if the user name is not found.
custom_serializer : callable
A custom function to format the ChatMessage's object. The function must
accept one positional argument and return a string. If not provided,
uses the serialize method on ChatMessage.
accept one positional argument, the ChatMessage object, and return a string.
If not provided, uses the serialize method on ChatMessage.
Returns
-------
Expand All @@ -575,7 +578,7 @@ def _serialize_for_transformers(
"user": [self.user],
"assistant": [self.callback_user],
}
return super()._serialize_for_transformers(role_names, default_role, custom_serializer)
return super()._serialize_for_transformers(messages, role_names, default_role, custom_serializer)

@param.depends("_callback_state", watch=True)
async def _update_input_disabled(self):
Expand Down
10 changes: 10 additions & 0 deletions panel/tests/chat/test_feed.py
Original file line number Diff line number Diff line change
Expand Up @@ -824,6 +824,16 @@ def custom_serializer(obj):
with pytest.raises(ValueError, match="must return a string"):
chat_feed.serialize(custom_serializer=custom_serializer)

def test_serialize_filter_by(self, chat_feed):
def filter_by_reactions(messages):
return [obj for obj in messages if "favorite" in obj.reactions]

chat_feed.send(ChatMessage("no"))
chat_feed.send(ChatMessage("yes", reactions=["favorite"]))
filtered = chat_feed.serialize(filter_by=filter_by_reactions)
assert len(filtered) == 1
assert filtered[0]["content"] == "yes"


@pytest.mark.xdist_group("chat")
class TestChatFeedSerializeBase:
Expand Down

0 comments on commit 1804d15

Please sign in to comment.