import gradio as gr import requests import json import uuid def generate_random_id(): """Generate a random sender ID if none is provided""" return str(uuid.uuid4())[:8] def respond(message, history, rasa_api_url, nickname): """ Send a message to a Rasa chatbot API and get the response. Args: message (str): The user's message history (list): Chat history rasa_api_url (str): URL of the Rasa API endpoint nickname (str): User's nickname to be used as sender ID """ # Process the Rasa API URL if not rasa_api_url: return "Please enter a valid Rasa API URL first." # Ensure the URL ends with a slash if needed if not rasa_api_url.endswith("/"): rasa_api_url = rasa_api_url + "/" # Append webhooks/rest/webhook if not present if not rasa_api_url.endswith("webhooks/rest/webhook"): if "webhooks/rest/webhook" not in rasa_api_url: rasa_api_url = rasa_api_url + "webhooks/rest/webhook" # Determine sender ID - use nickname if provided, otherwise use the session ID sender_id = nickname if nickname else gr.State(generate_random_id()).value try: # Prepare the payload payload = { "sender": sender_id, "message": message } # Send request to Rasa server response = requests.post(rasa_api_url, json=payload) # Check if the request was successful if response.status_code == 200: # Parse the response response_data = response.json() # Handle different response formats if response_data: # Extract the text from the response if isinstance(response_data, list) and len(response_data) > 0: if "text" in response_data[0]: return response_data[0]["text"] else: return "Received a response from the bot, but it doesn't contain text." else: return "Received an empty response from the bot." else: return "No response from the bot." else: return f"Error: Received status code {response.status_code} from the Rasa server." except requests.exceptions.RequestException as e: return f"Connection error: {str(e)}" except json.JSONDecodeError: return "Error: Received invalid JSON response from the Rasa server." except Exception as e: return f"An unexpected error occurred: {str(e)}" # State to store the random ID for this session session_id = gr.State(generate_random_id) # Create the Gradio interface with gr.Blocks(title="Rasa Chatbot Interface") as demo: gr.Markdown("# Rasa Chatbot Interface") gr.Markdown("Enter the URL of your Rasa chatbot API, optionally provide a nickname, and start chatting.") with gr.Row(): with gr.Column(scale=3): rasa_api_url = gr.Textbox( value="", placeholder="e.g., http://your-rasa-server.com:5005/webhooks/rest/webhook", label="Rasa API URL" ) with gr.Column(scale=1): nickname = gr.Textbox( value="", placeholder="Enter a nickname (optional)", label="Your Nickname" ) chatbot = gr.Chatbot() msg = gr.Textbox(placeholder="Type your message here...", label="Message") clear = gr.Button("Clear") # Function to properly format messages for the chatbot def user_message_and_response(message, chat_history, rasa_url, nick): bot_response = respond(message, chat_history, rasa_url, nick) chat_history.append((message, bot_response)) return "", chat_history # Set up event handlers msg.submit( user_message_and_response, [msg, chatbot, rasa_api_url, nickname], [msg, chatbot] ) clear.click(lambda: None, None, chatbot) if __name__ == "__main__": demo.launch()