Skip to content

Basics

Chat

Demonstrates how to use the ChatInterface and a callback function to respond.

The chatbot Assistant echoes back the message entered by the User.

Source code for basic_chat.py
"""
Demonstrates how to use the `ChatInterface` and a `callback` function to respond.

The chatbot Assistant echoes back the message entered by the User.
"""

import panel as pn

pn.extension()


def callback(contents: str, user: str, instance: pn.chat.ChatInterface):
    message = f"Echoing {user}: {contents}"
    return message


chat_interface = pn.chat.ChatInterface(callback=callback)
chat_interface.send(
    "Enter a message in the TextInput below and receive an echo!",
    user="System",
    respond=False,
)
chat_interface.servable()

Live Apps: Pyodide

Custom Widgets

Demonstrates how to use the ChatInterface and custom widgets, like TextAreaInput and FileInput, to create a chatbot that counts the number of lines in a message or file.

Source code for basic_custom_widgets.py
"""
Demonstrates how to use the `ChatInterface` and custom widgets,
like `TextAreaInput` and `FileInput`, to create a chatbot that counts
the number of lines in a message or file.
"""

import panel as pn

pn.extension()


def callback(contents: str, user: str, instance: pn.chat.ChatInterface):
    lines = contents.strip().count("\n")
    message = f"This snippet has {lines + 1} lines."
    return message


text_input = pn.widgets.TextInput(placeholder="Send a message")
text_area_input = pn.widgets.TextAreaInput(
    auto_grow=True, placeholder="Click Send to count lines."
)
file_input = pn.widgets.FileInput()
chat_interface = pn.chat.ChatInterface(
    callback=callback, widgets=[text_input, text_area_input, file_input]
)
chat_interface.send(
    "Enter a message in the TextAreaInput below to count how many lines there is, "
    "or upload a file to count the number of lines in the file.",
    user="System",
    respond=False,
)
chat_interface.servable()

Streaming Chat Async

Demonstrates how to use the ChatInterface and a callback function to stream back responses.

The chatbot Assistant echoes back the message entered by the User in an async streaming fashion.

Source code for basic_streaming_chat_async.py
"""
Demonstrates how to use the `ChatInterface` and a `callback` function to
stream back responses.

The chatbot Assistant echoes back the message entered by the User in an
*async streaming* fashion.
"""


from asyncio import sleep

import panel as pn

pn.extension()


async def callback(contents: str, user: str, instance: pn.chat.ChatInterface):
    await sleep(1)
    message = ""
    for char in "Echoing User: " + contents:
        await sleep(0.05)
        message += char
        yield message


chat_interface = pn.chat.ChatInterface(callback=callback)
chat_interface.send(
    "Enter a message in the TextInput below and receive an echo!",
    user="System",
    respond=False,
)
chat_interface.servable()

Live Apps: Pyodide