Middleware#
The middleware allows you to customize how messages are processed before being sent to GPT and how responses are processed before being sent to the user.
Add message middleware#
# Process messages before sending to GPT
def custom_message_middleware(notification, message_content, messages, session_data):
# Add custom context to the conversation
if notification.get_message_type() == "textMessage" and notification.chat.endswith("@c.us"):
# Add context to the message
enhanced_content = f"[User message] {message_content}"
return {
"message_content": enhanced_content,
"messages": messages
}
return {
"message_content": message_content,
"messages": messages
}
# Add middleware
bot.add_message_middleware(custom_message_middleware)
Add response middleware#
# Processing GPT responses before sending to the user
def custom_response_middleware(response, messages, session_data):
# Format or modify the response
formatted_response = response.replace("GPT", "Assistant").strip()
# You can also change the messages that will be saved in the history
return {
"response": formatted_response,
"messages": messages
}
# Add middleware
bot.add_response_middleware(custom_response_middleware)