Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add filter_by kwarg to serialize for ChatFeed #6090

Merged
merged 1 commit into from
Jan 12, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
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 @@ -659,6 +659,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 @@ -681,8 +682,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 @@ -703,11 +704,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 @@ -720,10 +722,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 @@ -742,9 +747,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 @@ -799,6 +799,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
Loading