The user session is designed to persist data in memory through the life cycle of a chat session. Each user session is unique to a user and a given chat session.
Let’s say you want to keep track of each chat session message count.A naive implementation might look like this:
This example is for illustrative purposes only. It is not recommended to use
this code in production.
Naive Example
Copy
import chainlit as clcounter = 0@cl.on_messageasync def on_message(message: cl.Message): global counter counter += 1 await cl.Message(content=f"You sent {counter} message(s)!").send()
At first glance, this code seems to work. However, it has a major flaw. If two users are chatting with the bot at the same time, both users will increment the same counter.This is where the user session comes in. Let’s rewrite the above example using the user session: