每当用户连接到您的 Chainlit 应用时,都会创建一个新的聊天会话。聊天会话会经历一系列事件生命周期,您可以通过定义钩子来响应这些事件。

聊天开始时

The on_chat_start 装饰器用于定义一个钩子,当新的聊天会话创建时调用。

@cl.on_chat_start
def on_chat_start():
    print("A new chat session has started!")

收到消息时

The on_message 装饰器用于定义一个钩子,当收到用户的新消息时调用。

@cl.on_message
def on_message(msg: cl.Message):
    print("The user sent: ", msg.content)

停止时

The on_stop 装饰器用于定义一个钩子,当用户在任务运行时点击停止按钮时调用。

@cl.on_stop
def on_stop():
    print("The user wants to stop the task!")

聊天结束时

The on_chat_end 装饰器用于定义一个钩子,当聊天会话结束时调用,原因可能是用户断开连接或开始了新的聊天会话。

@cl.on_chat_end
def on_chat_end():
    print("The user disconnected!")

聊天恢复时

The on_chat_resume 装饰器用于定义一个钩子,当用户恢复之前断开的聊天会话时调用。这仅在启用身份验证数据持久化时可能发生。

from chainlit.types import ThreadDict

@cl.on_chat_resume
async def on_chat_resume(thread: ThreadDict):
    print("The user resumed a previous chat session!")