File size: 4,108 Bytes
a5ea60f
26a0ac9
 
8bd4cad
a5ea60f
8bd4cad
 
 
 
 
26a0ac9
 
 
 
 
 
 
8bd4cad
26a0ac9
 
 
 
 
 
 
 
 
 
 
 
 
 
8bd4cad
 
 
26a0ac9
 
 
8bd4cad
26a0ac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5ea60f
8bd4cad
 
 
26a0ac9
8bd4cad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e42a59a
 
 
 
 
 
8bd4cad
 
e42a59a
8bd4cad
e42a59a
8bd4cad
 
 
a5ea60f
 
26a0ac9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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()