On-demand send and handle user message
version: chainlit==2.5.5
Description:
I need to programmatically send a user message (e.g., to simulate). Using: await cl.Message(content="example", type="user_message", author="user").send() does send the message, but it does not trigger the @cl.on_message handler, which is essential for my use case. (and i don't want to call the function that wrap with ``@cl.on_message`)
To work around this, I tried manually emitting the client_message event using cl.context.emitter.emit, referencing how the frontend does it in [useChatInteract.ts](https://github.com/Chainlit/chainlit/blob/09d7d5e745961176c6f393afedd6ec607129638b/libs/react-client/src/useChatInteract.ts#L66):
session?.socket.emit('client_message', { message, fileReferences });
My corresponding Python implementation:
context_payload = {
"message": {
"id": str(uuid.uuid4()),
"createdAt": str(datetime.datetime.now().isoformat(timespec="milliseconds") + "Z"),
"content": str(next_user_response),
},
"fileReferences": [],
}
await cl.context.emitter.emit("client_message", context_payload)
However, this does not trigger the @cl.on_message handler either.
Request:
Is there a supported way to manually emit a user message that correctly triggers the @cl.on_message's function, similar to how the frontend socket event works?
Thanks in advance for your support.
Hi @thangbuiq! I'm Dosu and I’m helping the chainlit team.
There isn't a supported way in Chainlit v2.5.5 to programmatically emit a user message from backend code that triggers the @cl.on_message handler, similar to how the frontend socket event works. The @cl.on_message handler is designed to be triggered by actual frontend socket events, not by backend event emission or by sending a message with cl.Message(...).send()—which only posts a message to the UI and doesn't invoke the handler logic.
Emitting a 'client_message' event via cl.context.emitter.emit from the backend also doesn't work, as this mechanism doesn't route through the same internal flow as frontend socket events. This separation is intentional and there is no backend API or method that bridges this gap in v2.5.5. All examples and documentation show @cl.on_message being triggered by user input from the frontend, not by backend code or programmatic emission [source].
The only known workaround is to directly call the function wrapped by @cl.on_message, but this bypasses the decorator's internal logic and may not be future-proof or safe for all use cases.
If this capability is critical for your workflow, you may want to monitor future Chainlit releases for changes or enhancements in this area.
To reply, just mention @dosu.
Docs are dead. Just use Dosu.
What is your use case? Why can't you call the on_message decoratored function?
What is your use case? Why can't you call the on_message decoratored function?
tl;dr I'm building a suggestion system where the user can click response buttons instead of typing. These are set via actions in the message. However, Chainlit doesn't officially support "suggested next message" buttons out of the box.
In my use case, I generate suggested responses (sent as actions) based on the chat history. When the user clicks one, it triggers a new message and should invoke the on_message handler. The problem is: calling the on_message-decorated function doesn't update the UI step with streaming animation.
Current workaround: I'm using chainlit.socket.process_message, which works, but it makes the codebase messier:
import chainlit.socket as cl_socket
from chainlit.chat_context import chat_context
from chainlit.context import context
@cl.action_callback("next_response")
async def handle_next_response_action(action: cl.Action):
"""
Handle the suggestion response action when the user selects a response (in actions)
"""
user_response = action.payload.get("user_response", "")
user_message = cl.Message(
content=user_response,
author="user",
type="user_message",
)
await remove_next_response_actions()
user_message.created_at = utc_now()
step_dict = await user_message._create()
chat_context.add(user_message)
await context.emitter.send_step(step_dict)
message_payload = MessagePayload(message=step_dict, fileReferences=None)
await cl_socket.process_message(session=cl.context.session, payload=message_payload)
Reference screenshot
This issue is stale because it has been open for 14 days with no activity.
This issue was closed because it has been inactive for 7 days since being marked as stale.