{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import asyncio\n", "import pandas as pd\n", "import panel as pn\n", "\n", "from panel.chat import ChatMessage\n", "\n", "pn.extension(\"vega\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `ChatMessage` is a pane for displaying chat messages with support for various content types.\n", "\n", "This pane provides a structured view of chat messages, including features like:\n", "- Displaying user avatars, which can be text, emoji, or images.\n", "- Showing the user's name.\n", "- Displaying the message timestamp in a customizable format.\n", "- Associating reactions with messages and mapping them to icons.\n", "- Rendering various content types including text, images, audio, video, and more.\n", "\n", "See [`ChatFeed`](ChatFeed.ipynb) for a structured and straightforward way to build a list of `ChatMessage` objects.\n", "\n", "See [`ChatInterface`](ChatInterface.ipynb) for a high-level, *easy to use*, *ChatGPT like* interface.\n", "\n", "\"Chat\n", "\n", "#### Parameters:\n", "\n", "For layout and styling related parameters see the [customization user guide](../../user_guide/Customization.ipynb).\n", "\n", "##### Core\n", "\n", "* **`object`** (object): The message contents. Can be a string, pane, widget, layout, etc.\n", "* **`renderers`** (List[Callable]): A callable or list of callables that accept the value and return a Panel object to render the value. If a list is provided, will attempt to use the first renderer that does not raise an exception. If None, will attempt to infer the renderer from the value.\n", "* **`user`** (str): Name of the user who sent the message.\n", "* **`avatar`** (str | BinaryIO): The avatar to use for the user. Can be a single character text, an emoji, or anything supported by `pn.pane.Image`. If not set, uses the first character of the name.\n", "* **`default_avatars`** (Dict[str, str | BinaryIO]): A default mapping of user names to their corresponding avatars to use when the user is set but the avatar is not. You can modify, but not replace the dictionary. Note, the keys are *only* alphanumeric sensitive, meaning spaces, special characters, and case sensitivity is disregarded, e.g. `\"Chat-GPT3.5\"`, `\"chatgpt 3.5\"` and `\"Chat GPT 3.5\"` all map to the same value.\n", "* **`footer_objects`** (List): A list of objects to display in the column of the footer of the message.\n", "* **`header_objects`** (List): A list of objects to display in the row of the header of the message.\n", "* **`avatar_lookup`** (Callable): A function that can lookup an `avatar` from a user name. The function signature should be `(user: str) -> Avatar`. If this is set, `default_avatars` is disregarded.\n", "* **`reactions`** (List): Reactions associated with the message.\n", "* **`reaction_icons`** (ChatReactionIcons | dict): A mapping of reactions to their reaction icons; if not provided defaults to `{\"favorite\": \"heart\"}`. Provides a visual representation of reactions.\n", "* **`timestamp`** (datetime): Timestamp of the message. Defaults to the instantiation time.\n", "* **`timestamp_format`** (str): The format in which the timestamp should be displayed.\n", "* **`timestamp_tz`** (str): The timezone to used for the creation timestamp; only applicable if timestamp is not set. If None, uses the default timezone of datetime.datetime.now(); see `zoneinfo.available_timezones()` for a list of valid timezones.\n", "\n", "##### Display\n", "\n", "* **`show_avatar`** (bool): Whether to display the avatar of the user.\n", "* **`show_user`** (bool): Whether to display the name of the user.\n", "* **`show_timestamp`** (bool): Whether to display the timestamp of the message.\n", "* **`show_reaction_icons`** (bool): Whether to display the reaction icons.\n", "* **`show_copy_icon`** (bool): Whether to show the copy icon.\n", "* **`show_activity_dot`** (bool): Whether to show the activity dot.\n", "* **`name`** (str): The title or name of the chat message widget, if any.\n", "\n", "___" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Basics" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ChatMessage(\"Hi and welcome!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `ChatMessage` can display any Python object that Panel can display! For example Panel components, dataframes and plot figures." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = pd.DataFrame({\"x\": [1, 2, 3], \"y\": [4, 5, 6]})\n", "\n", "vegalite = {\n", " \"$schema\": \"https://vega.github.io/schema/vega-lite/v5.json\",\n", " \"data\": {\"url\": \"https://raw.githubusercontent.com/vega/vega/master/docs/data/barley.json\"},\n", " \"mark\": \"bar\",\n", " \"encoding\": {\n", " \"x\": {\"aggregate\": \"sum\", \"field\": \"yield\", \"type\": \"quantitative\"},\n", " \"y\": {\"field\": \"variety\", \"type\": \"nominal\"},\n", " \"color\": {\"field\": \"site\", \"type\": \"nominal\"}\n", " },\n", " \"width\": \"container\",\n", "}\n", "vgl_pane = pn.pane.Vega(vegalite, height=240)\n", "\n", "pn.Column(\n", " ChatMessage(pn.widgets.Button(name=\"Click\")),\n", " ChatMessage(df),\n", " ChatMessage(vgl_pane),\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can specify a custom `user` name and `avatar`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ChatMessage(\"Want to hear some beat boxing?\", user=\"Beat Boxer\", avatar=\"🎶\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Instead of searching for emojis online, you can also set a personalized emoji avatar by using its name wrapped in `\\N{}`!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ChatMessage(\"Want to hear some beat boxing?\", user=\"Beat Boxer\", avatar=\"\\N{musical note}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can combine `ChatMessage` with other Panel components as you like." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pn.Column(\n", " ChatMessage(\n", " \"Yes. I want to hear some beat boxing\", user=\"Music Lover\", avatar=\"🎸\"\n", " ),\n", " ChatMessage(\n", " pn.Column(\n", " \"Here goes. Hope you like this one?\",\n", " pn.pane.Audio(\n", " \"https://assets.holoviz.org/panel/samples/beatboxing.mp3\"\n", " ),\n", " ),\n", " user=\"Beat Boxer\",\n", " avatar=\"🎶\",\n", " ),\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, if you're serializing output, it's better practice to put other objects into the `header_objects` or `footer_objects` of the `ChatMessage` so that you don't have to write a custom serializer to handle nested Panel components." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pn.Column(\n", " ChatMessage(\n", " \"Yes. I want to hear some beat boxing\", user=\"Music Lover\", avatar=\"🎸\"\n", " ),\n", " ChatMessage(\n", " pn.pane.Audio(\n", " \"https://assets.holoviz.org/panel/samples/beatboxing.mp3\",\n", " ),\n", " header_objects=[pn.pane.HTML(\"Here goes. Hope you like this one?\", margin=(5, 0))],\n", " footer_objects=[pn.widgets.ButtonIcon(icon=\"download\", description=\"Download this! (not implemented here)\")],\n", " user=\"Beat Boxer\",\n", " avatar=\"🎶\",\n", " ),\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`ChatMessage` can be initialized without any input." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "chat_message = pn.chat.ChatMessage()\n", "chat_message" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Updates" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That way, the `value`, `user`, and/or `avatar` can be dynamically updated either by setting the `value` like this..." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "chat_message.object = pn.pane.Markdown(\"## Cheers!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Or updating multiple values at once with the `.param.update` method!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "chat_message.param.update(user=\"Jolly Guy\", avatar=\"🎅\");" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The easiest and most optimal way to stream output to the `ChatMessage` is through async generators.\n", "\n", "If you're unfamiliar with this term, don't fret!\n", "\n", "It's simply prefixing your function with `async` and replacing `return` with `yield`.\n", "\n", "This example will show you how to **replace** the `ChatMessage` `value`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "async def replace_response():\n", " for value in range(0, 28):\n", " await asyncio.sleep(0.2)\n", " yield value\n", "\n", "ChatMessage(replace_response)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This example will show you how to **append** to the `ChatMessage` `value`. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sentence = \"\"\"\n", " The greatest glory in living lies not in never falling,\n", " but in rising every time we fall.\n", "\"\"\"\n", "\n", "async def append_response():\n", " value = \"\"\n", " for token in sentence.split():\n", " value += f\" {token}\"\n", " await asyncio.sleep(0.2)\n", " yield value\n", "\n", "ChatMessage(append_response, user=\"Wise guy\", avatar=\"🤓\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Styling" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you'd like a plain interface with only the `value` displayed, set `show_user`, `show_copy_icon`, `show_avatar`, and `show_timestamp` to `False` and provide an empty `dict` to `reaction_icons`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ChatMessage(\n", " \"Plain and simple\",\n", " show_avatar=False,\n", " show_user=False,\n", " show_timestamp=False,\n", " show_copy_icon=False,\n", " reaction_icons={},\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can set the usual styling and layout parameters like `sizing_mode`, `height`, `width`, `max_height`, `max_width`, and `styles`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ChatMessage(\n", " \"Want to hear some beat boxing?\",\n", " user=\"Beat Boxer\",\n", " avatar=\"🎶\",\n", " height=250,\n", " sizing_mode=\"stretch_width\",\n", " max_width=600,\n", " styles={\"background\": \"#CBC3E3\"},\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also use stylesheets to target parts of the `ChatMessage`\n", "\n", "Note, it's best practice to use a path to a `.css` stylesheet, but for demo purposes, we will be using a multi-line string here." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "path_to_stylesheet = \"\"\"\n", " .message {\n", " background-color: tan;\n", " font-size: 24px;\n", " font-family: \"Courier New\";\n", " }\n", " .avatar {\n", " background-color: red;\n", " border-radius: 5%;\n", " }\n", " .header {\n", " background-color: green;\n", " }\n", " .footer {\n", " background-color: blue;\n", " }\n", " .name {\n", " background-color: orange;\n", " }\n", " .timestamp {\n", " background-color: purple;\n", " }\n", " .activity-dot {\n", " background-color: black;\n", " }\n", " .reaction-icons {\n", " background-color: white;\n", " }\n", " .copy-icon {\n", " background-color: gold;\n", " }\n", " .right {\n", " background-color: grey;\n", " }\n", " .center {\n", " background-color: pink;\n", " }\n", " .left {\n", " background-color: yellow;\n", " }\n", "\"\"\"\n", "\n", "ChatMessage(\n", " \"Style me up!\",\n", " show_activity_dot=True,\n", " stylesheets=[path_to_stylesheet],\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Code Highlighting\n", "\n", ":::{note} Code Highlighting\n", "To enable code highlighting in code blocks, `pip install pygments`\n", ":::" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Reactions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some active `reactions` can be associated with the message too." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pn.chat.ChatMessage(\"Love this!\", reactions=[\"favorite\"])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you'd like to display other `reactions_icons`, pass a pair of `reaction` key to tabler `icon` name." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message = pn.chat.ChatMessage(\n", " \"Looks good!\",\n", " reactions=[\"like\"],\n", " reaction_icons={\"like\": \"thumb-up\", \"dislike\": \"thumb-down\"},\n", ")\n", "message" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You may bind a callback to the selected `reactions`.\n", "\n", "Here, when the user clicks or sets `reactions`, `print_reactions` activates. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def print_reactions(reactions):\n", " print(f\"{reactions} selected.\")\n", "\n", "pn.bind(print_reactions, message.param.reactions)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Misc" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you don't specify an `avatar` on construction, then an `avatar` will be looked up in the `default_avatars` dictionary." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ChatMessage.default_avatars" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can modify the `ChatMessage.default_avatars` in-place.\n", "\n", "Note, the keys are *only* alphanumeric sensitive, meaning spaces, special characters, and case sensitivity is disregarded, e.g. `\"Chat-GPT3.5\"`, `\"chatgpt 3.5\"` and `\"Chat GPT 3.5\"` all map to the same value." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ChatMessage.default_avatars[\"Wolfram\"] = \"🐺\"\n", "ChatMessage.default_avatars[\"#1 good-to-go guy\"] = \"👍\"\n", "\n", "pn.Column(\n", " ChatMessage(\"Mathematics!\", user=\"Wolfram\"),\n", " ChatMessage(\"Good to go!\", user=\"#1 Good-to-Go Guy\"),\n", " ChatMessage(\"What's up?\", user=\"Other Guy\"),\n", " max_width=300,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `timestamp` can be formatted using `timestamp_format`. Additionally, a timestamp_tz can be provided to use any timezones supported by `zoneinfo`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pn.chat.ChatMessage(timestamp_format=\"%b %d, %Y %I:%M %p\", timestamp_tz=\"US/Pacific\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `ChatMessage` can serialized into a string." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "widget = pn.widgets.FloatSlider(value=3, name=\"Number selected\")\n", "pn.chat.ChatMessage(widget).serialize()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For an example on `renderers`, see [ChatInterface](ChatInterface.ipynb)." ] } ], "metadata": { "language_info": { "name": "python", "pygments_lexer": "ipython3" } }, "nbformat": 4, "nbformat_minor": 4 }