File size: 3,679 Bytes
fd13834
92491c3
 
 
 
 
 
 
 
 
 
fd13834
92491c3
 
fd13834
92491c3
 
 
 
fd13834
92491c3
 
 
 
 
 
 
 
 
 
 
 
 
 
fd13834
92491c3
 
 
 
fd13834
92491c3
 
fd13834
92491c3
 
 
 
 
 
 
 
 
fd13834
92491c3
 
 
 
 
 
 
 
 
fd13834
 
92491c3
 
 
fd13834
 
 
92491c3
 
 
fd13834
92491c3
 
 
fd13834
 
92491c3
 
 
 
 
fd13834
 
 
92491c3
fd13834
df22d6f
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
import gradio as gr
import requests
import json

# --- Configuration ---
# IMPORTANT: Replace this placeholder with the actual Webhook URL from your n8n workflow.
# You can find this URL in the "Webhook" trigger node in n8n.
N8N_WEBHOOK_URL = "https://swanbh.app.n8n.cloud/webhook-test/73e4ff29-41ec-4c45-a527-971fe8ec5d1f"


def respond(message: str, history: list[dict[str, str]], system_message: str):
    """
    Sends the user's message, chat history, and system message to an n8n webhook
    and returns the response from the workflow.

    Args:
        message: The new message from the user.
        history: The history of the conversation, in Hugging Face format.
        system_message: The system prompt/message.

    Returns:
        The response string from the n8n workflow.
    """
    if not N8N_WEBHOOK_URL or "YOUR_N8N_WEBHOOK_URL_HERE" in N8N_WEBHOOK_URL:
        return "Error: The n8n Webhook URL is not configured. Please edit the `app.py` file."

    # Construct the payload to send to your n8n workflow.
    # The keys ('newMessage', 'history', 'systemMessage') can be customized,
    # just make sure they match what your n8n workflow expects.
    payload = {
        "newMessage": message,
        "history": history,
        "systemMessage": system_message
    }

    try:
        # Send the data to the n8n webhook using an HTTP POST request.
        # We set a timeout to prevent the app from hanging indefinitely.
        response = requests.post(N8N_WEBHOOK_URL, json=payload, timeout=60)

        # Raise an exception if the webhook returns an error status code (e.g., 404, 500).
        response.raise_for_status()

        # n8n should be configured to return a JSON object.
        # We expect a format like: {"reply": "This is the bot's answer."}
        response_data = response.json()
        
        # Extract the reply from the JSON response. If the 'reply' key is missing,
        # return a helpful error message.
        reply = response_data.get("reply", "Error: The backend did not provide a valid reply.")
        
        return reply

    except requests.exceptions.Timeout:
        return "Error: The request to the backend timed out. Please try again."
    except requests.exceptions.RequestException as e:
        # This catches connection errors, invalid URLs, etc.
        print(f"An error occurred while calling the n8n webhook: {e}")
        return f"Error: Could not communicate with the backend. Please check the URL and n8n workflow."
    except json.JSONDecodeError:
        # This catches errors if the n8n response isn't valid JSON.
        return "Error: Received an invalid format from the backend. Expected JSON."


# We've simplified the interface by removing the Hugging Face specific inputs
# like max_tokens, temperature, etc.
chatbot_interface = gr.ChatInterface(
    respond,
    type="messages",
    additional_inputs=[
        # You can keep the system message if your n8n workflow uses it.
        # Otherwise, you can remove this list completely for a cleaner UI.
        gr.Textbox(value="You are a helpful assistant.", label="System Message"),
    ],
    title="AI Chat Interface",
    description="This chat interface is powered by a custom n8n.io workflow.",
    examples=[["Hello!"], ["What is n8n?"], ["How do you connect to a webhook?"]],
)


# Using gr.Blocks() to add a bit more structure, like the sidebar.
with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px !important; margin: auto !important;}") as demo:
    gr.Markdown("# Chat with your n8n Workflow")
    chatbot_interface.render()


if __name__ == "__main__":
    # Launch the Gradio app
    demo.launch()