pythonpython-3.xstreamlitchainlit

Chainlit: How to know when selection in settings changes


I am using latest version of Chainlit. The Python code below correctly prints which option chosen initially by default. It also displays all available options in given list when clicked on setting. But if I change option, it never runs on_option_change

How can I handle when user changes option in settings?

# To run:
#   chainlit run chainlit_trials.py --port 9503
#

import chainlit as cl
from chainlit.input_widget import Select

@cl.on_chat_start
async def initialize():
    print(f"Started. Carrying initializations.")

    settings = await cl.ChatSettings(
        [
            Select(
                id="Options",
                label="Available Options",
                values=["option1", "option2", "option3"],
                initial_index=0,
                on_change= on_option_change
            )
        ]
    ).send()

    option = settings["Options"]
    print(f"Option chosen: {option}")    

# This function will be called whenever the user changes the database selection
async def on_option_change(value):
    print(f"Selected option: {value}")

Solution

  • Well I found the answer. It is @cl.on_settings_update what we need to define. Here is complete working code:

    # To run:
    #   chainlit run chainlit_trials.py --port 9503
    #
    
    import chainlit as cl
    from chainlit.input_widget import Select
    
    @cl.on_chat_start
    async def some_name_doesnt_matter_what_it_is():
        print(f"Started. Carrying initialisations.")
    
        settings = await cl.ChatSettings(
            [
                Select(
                    id="Options",
                    label="Available Options",
                    values=["option1", "option2", "option3"],
                    initial_index=0,
                )
            ]
        ).send()
    
        option = settings["Options"]
        print(f"Option chosen: {option}")    
    
    
    # This receives updates in settings
    @cl.on_settings_update
    async def some_name_doesnt_matter_what_it_is(settings):
        print("Settings updated ", settings)
        print(f"Option selected: {settings["Options"]}")