文本消息是聊天机器人的基本构成要素,但我们常常想发送给用户的不仅仅是文本,还有图片、视频等等。

这就是元素的作用。每个元素都是一段内容,可以附加到消息步骤上,并在用户界面中显示。

示例

要将元素附加到消息或步骤,我们需要

  1. 实例化元素
  2. 将元素附加到消息或步骤
import chainlit as cl


@cl.on_chat_start
async def start():
    image = cl.Image(path="./cat.jpeg", name="image1", display="inline")

    # Attach the image to the message
    await cl.Message(
        content="This message has an image!",
        elements=[image],
    ).send()

显示选项

有 3 种显示选项决定元素如何渲染

侧边

@cl.on_chat_start
async def start():
    # Notice the display option
    image = cl.Image(path="./cat.jpeg", name="cat image", display="side")

    await cl.Message(
        # Notice that the name of the image is referenced in the message content
        content="Here is the cat image!",
        elements=[image],
    ).send()

图片不会显示在消息中。相反,图片的名称将显示为一个可点击的链接。当用户点击该链接时,图片将显示在消息的侧边。

页面

@cl.on_chat_start
async def start():
    # Notice the display option
    image = cl.Image(path="./cat.jpeg", name="cat image", display="page")

    await cl.Message(
        # Notice that the name of the image is referenced in the message content
        content="Here is the cat image!",
        elements=[image],
    ).send()

图片不会显示在消息中。相反,图片的名称将显示为一个可点击的链接。点击该链接将重定向到一个专门的页面,并在该页面上显示图片。

内联

@cl.on_chat_start
async def start():
    # Notice the display option
    image = cl.Image(path="./cat.jpeg", name="cat image", display="inline")

    await cl.Message(
        # Notice that the name of the image is NOT referenced in the message content
        content="Hello!",
        elements=[image],
    ).send()

无论图像名称是否在消息内容中被引用,图像都将显示在消息下方。

从 Python 控制元素侧边栏

您可以直接在 Python 中打开/关闭侧边栏。附加到侧边栏的元素不会被持久化,因为此侧边栏状态并非用户界面交互的结果。

import chainlit as cl


@cl.on_chat_start
async def start():
    # Define the elements you want to display
    elements = [
        cl.Image(path="./cat.jpeg", name="image1"),
        cl.Pdf(path="./dummy.pdf", name="pdf1"),
        cl.Text(content="Here is a side text document", name="text1"),
        cl.Text(content="Here is a page text document", name="text2"),
    ]

    # Setting elements will open the sidebar
    await cl.ElementSidebar.set_elements(elements)
    await cl.ElementSidebar.set_title("Test title")

@cl.on_message
async def message(msg: cl.Message):
    # You can update the elements
    await cl.ElementSidebar.set_elements([cl.Text(content="Text changed!")])
    # You can update the title
    await cl.ElementSidebar.set_title("Title changed!")

    await cl.sleep(2)

    # Setting the elements to an empty array will close the sidebar
    await cl.ElementSidebar.set_elements([])