Mushaima commited on
Commit
92491c3
·
verified ·
1 Parent(s): cdceb2f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -50
app.py CHANGED
@@ -1,70 +1,89 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
  """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
 
18
 
19
- messages = [{"role": "system", "content": system_message}]
 
 
 
20
 
21
- messages.extend(history)
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- messages.append({"role": "user", "content": message})
 
 
 
24
 
25
- response = ""
 
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
41
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
  respond,
48
  type="messages",
49
  additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
  ],
 
 
 
61
  )
62
 
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
 
67
 
68
 
69
  if __name__ == "__main__":
 
70
  demo.launch()
 
1
  import gradio as gr
2
+ import requests
3
+ import json
4
+
5
+ # --- Configuration ---
6
+ # IMPORTANT: Replace this placeholder with the actual Webhook URL from your n8n workflow.
7
+ # You can find this URL in the "Webhook" trigger node in n8n.
8
+ N8N_WEBHOOK_URL = "https://swanbh.app.n8n.cloud/webhook-test/73e4ff29-41ec-4c45-a527-971fe8ec5d1f"
9
+
10
+
11
+ def respond(message: str, history: list[dict[str, str]], system_message: str):
 
 
 
 
12
  """
13
+ Sends the user's message, chat history, and system message to an n8n webhook
14
+ and returns the response from the workflow.
15
 
16
+ Args:
17
+ message: The new message from the user.
18
+ history: The history of the conversation, in Hugging Face format.
19
+ system_message: The system prompt/message.
20
 
21
+ Returns:
22
+ The response string from the n8n workflow.
23
+ """
24
+ if not N8N_WEBHOOK_URL or "YOUR_N8N_WEBHOOK_URL_HERE" in N8N_WEBHOOK_URL:
25
+ return "Error: The n8n Webhook URL is not configured. Please edit the `app.py` file."
26
+
27
+ # Construct the payload to send to your n8n workflow.
28
+ # The keys ('newMessage', 'history', 'systemMessage') can be customized,
29
+ # just make sure they match what your n8n workflow expects.
30
+ payload = {
31
+ "newMessage": message,
32
+ "history": history,
33
+ "systemMessage": system_message
34
+ }
35
 
36
+ try:
37
+ # Send the data to the n8n webhook using an HTTP POST request.
38
+ # We set a timeout to prevent the app from hanging indefinitely.
39
+ response = requests.post(N8N_WEBHOOK_URL, json=payload, timeout=60)
40
 
41
+ # Raise an exception if the webhook returns an error status code (e.g., 404, 500).
42
+ response.raise_for_status()
43
 
44
+ # n8n should be configured to return a JSON object.
45
+ # We expect a format like: {"reply": "This is the bot's answer."}
46
+ response_data = response.json()
47
+
48
+ # Extract the reply from the JSON response. If the 'reply' key is missing,
49
+ # return a helpful error message.
50
+ reply = response_data.get("reply", "Error: The backend did not provide a valid reply.")
51
+
52
+ return reply
 
 
53
 
54
+ except requests.exceptions.Timeout:
55
+ return "Error: The request to the backend timed out. Please try again."
56
+ except requests.exceptions.RequestException as e:
57
+ # This catches connection errors, invalid URLs, etc.
58
+ print(f"An error occurred while calling the n8n webhook: {e}")
59
+ return f"Error: Could not communicate with the backend. Please check the URL and n8n workflow."
60
+ except json.JSONDecodeError:
61
+ # This catches errors if the n8n response isn't valid JSON.
62
+ return "Error: Received an invalid format from the backend. Expected JSON."
63
 
64
 
65
+ # We've simplified the interface by removing the Hugging Face specific inputs
66
+ # like max_tokens, temperature, etc.
67
+ chatbot_interface = gr.ChatInterface(
 
68
  respond,
69
  type="messages",
70
  additional_inputs=[
71
+ # You can keep the system message if your n8n workflow uses it.
72
+ # Otherwise, you can remove this list completely for a cleaner UI.
73
+ gr.Textbox(value="You are a helpful assistant.", label="System Message"),
 
 
 
 
 
 
 
74
  ],
75
+ title="AI Chat Interface",
76
+ description="This chat interface is powered by a custom n8n.io workflow.",
77
+ examples=[["Hello!"], ["What is n8n?"], ["How do you connect to a webhook?"]],
78
  )
79
 
80
+
81
+ # Using gr.Blocks() to add a bit more structure, like the sidebar.
82
+ with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px !important; margin: auto !important;}") as demo:
83
+ gr.Markdown("# Chat with your n8n Workflow")
84
+ chatbot_interface.render()
85
 
86
 
87
  if __name__ == "__main__":
88
+ # Launch the Gradio app
89
  demo.launch()