nsomabalint/rasa_ui
0
1import gradio as gr2import requests3import json4import uuid5 6def generate_random_id():7 """Generate a random sender ID if none is provided"""8 return str(uuid.uuid4())[:8]9 10def respond(message, history, rasa_api_url, nickname):11 """12 Send a message to a Rasa chatbot API and get the response.13 14 Args:15 message (str): The user's message16 history (list): Chat history17 rasa_api_url (str): URL of the Rasa API endpoint18 nickname (str): User's nickname to be used as sender ID19 """20 # Process the Rasa API URL21 if not rasa_api_url:22 return "Please enter a valid Rasa API URL first."23 24 # Ensure the URL ends with a slash if needed25 if not rasa_api_url.endswith("/"):26 rasa_api_url = rasa_api_url + "/"27 28 # Append webhooks/rest/webhook if not present29 if not rasa_api_url.endswith("webhooks/rest/webhook"):30 if "webhooks/rest/webhook" not in rasa_api_url:31 rasa_api_url = rasa_api_url + "webhooks/rest/webhook"32 33 # Determine sender ID - use nickname if provided, otherwise use the session ID34 sender_id = nickname if nickname else gr.State(generate_random_id()).value35 36 try:37 # Prepare the payload38 payload = {39 "sender": sender_id,40 "message": message41 }42 43 # Send request to Rasa server44 response = requests.post(rasa_api_url, json=payload)45 46 # Check if the request was successful47 if response.status_code == 200:48 # Parse the response49 response_data = response.json()50 51 # Handle different response formats52 if response_data:53 # Extract the text from the response54 if isinstance(response_data, list) and len(response_data) > 0:55 if "text" in response_data[0]:56 return response_data[0]["text"]57 else:58 return "Received a response from the bot, but it doesn't contain text."59 else:60 return "Received an empty response from the bot."61 else:62 return "No response from the bot."63 else:64 return f"Error: Received status code {response.status_code} from the Rasa server."65 except requests.exceptions.RequestException as e:66 return f"Connection error: {str(e)}"67 except json.JSONDecodeError:68 return "Error: Received invalid JSON response from the Rasa server."69 except Exception as e:70 return f"An unexpected error occurred: {str(e)}"71 72# State to store the random ID for this session73session_id = gr.State(generate_random_id)74 75# Create the Gradio interface76with gr.Blocks(title="Rasa Chatbot Interface") as demo:77 gr.Markdown("# Rasa Chatbot Interface")78 gr.Markdown("Enter the URL of your Rasa chatbot API, optionally provide a nickname, and start chatting.")79 80 with gr.Row():81 with gr.Column(scale=3):82 rasa_api_url = gr.Textbox(83 value="",84 placeholder="e.g., http://your-rasa-server.com:5005/webhooks/rest/webhook",85 label="Rasa API URL"86 )87 with gr.Column(scale=1):88 nickname = gr.Textbox(89 value="",90 placeholder="Enter a nickname (optional)",91 label="Your Nickname"92 )93 94 chatbot = gr.Chatbot()95 msg = gr.Textbox(placeholder="Type your message here...", label="Message")96 clear = gr.Button("Clear")97 98 # Function to properly format messages for the chatbot99 def user_message_and_response(message, chat_history, rasa_url, nick):100 bot_response = respond(message, chat_history, rasa_url, nick)101 chat_history.append((message, bot_response))102 return "", chat_history103 104 # Set up event handlers105 msg.submit(106 user_message_and_response, 107 [msg, chatbot, rasa_api_url, nickname], 108 [msg, chatbot]109 )110 111 clear.click(lambda: None, None, chatbot)112 113if __name__ == "__main__":114 demo.launch()