adeelshuaib commited on
Commit
2a52487
·
verified ·
1 Parent(s): 6305dd7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -29
app.py CHANGED
@@ -1,20 +1,27 @@
1
  import gradio as gr
2
  from groq import Groq
3
  import os
 
4
 
5
  api_key = os.getenv('GROQ_API_KEY')
6
  # Initialize Groq client
7
  client = Groq(api_key=api_key)
8
 
9
  # Function to generate responses with error handling
10
- def generate_response(user_input, chat_history):
11
  try:
12
  # Prepare messages with chat history
13
- messages = [{"role": "system", "content": "You are a helpful mental health assistant."}]
14
- for user_message, bot_response in chat_history:
15
- messages.append({"role": "user", "content": user_message})
16
- messages.append({"role": "assistant", "content": bot_response})
17
- messages.append({"role": "user", "content": user_input})
 
 
 
 
 
 
18
 
19
  # Call Groq API to get a response from LLaMA
20
  chat_completion = client.chat.completions.create(
@@ -24,7 +31,7 @@ def generate_response(user_input, chat_history):
24
 
25
  # Extract response
26
  response = chat_completion.choices[0].message.content
27
- return response, chat_history
28
 
29
  except Exception as e:
30
  print(f"Error occurred: {e}") # Print error to console for debugging
@@ -33,35 +40,42 @@ def generate_response(user_input, chat_history):
33
  # Define Gradio interface
34
  def gradio_interface():
35
  with gr.Blocks() as demo:
36
- # Variable to store chat history
37
  chat_history = []
38
 
39
- # Modify `generate_and_clear` to accept additional unused arguments
40
- def generate_and_clear(user_input, *args, **kwargs):
41
- response, updated_history = generate_response(user_input, chat_history)
42
- chat_history.append((user_input, response))
43
- return response
44
 
45
- def clear_chat():
46
- chat_history.clear()
47
- return "Chat history cleared. Start a new conversation!"
 
 
48
 
49
- # Title and instructions
50
- gr.Markdown("## Mental Health Chatbot - Powered by LLaMA on Groq")
 
 
 
 
51
 
52
- # Chat interface setup
53
- chatbot = gr.ChatInterface(
54
- fn=generate_and_clear,
55
- #additional_inputs=[gr.Textbox(placeholder="Enter your message here...", label="Your Message")],
56
- #title="Mental Health Chatbot"
57
- )
58
 
59
- # Add button to clear chat history
60
- clear_button = gr.Button("Clear Chat History")
61
- clear_button.click(fn=clear_chat, inputs=[], outputs=chatbot) # Clear chat on button click
 
 
 
 
 
 
62
 
63
  demo.launch()
64
 
65
  # Run the interface
66
- gradio_interface()
67
-
 
1
  import gradio as gr
2
  from groq import Groq
3
  import os
4
+ import time
5
 
6
  api_key = os.getenv('GROQ_API_KEY')
7
  # Initialize Groq client
8
  client = Groq(api_key=api_key)
9
 
10
  # Function to generate responses with error handling
11
+ def generate_response(user_input, chat_history: list):
12
  try:
13
  # Prepare messages with chat history
14
+ messages = [{"role": "system", "content": "You are a mental health assistant. Your responses should be empathetic, non-judgmental, and provide helpful advice based on mental health principles. Always encourage seeking professional help when needed."}]
15
+
16
+ # Iterate through chat history and add user and assistant messages
17
+ for message in chat_history:
18
+ # Ensure that each message contains only 'role' and 'content' keys
19
+ if 'role' in message and 'content' in message:
20
+ messages.append({"role": message["role"], "content": message["content"]})
21
+ else:
22
+ print(f"Skipping invalid message: {message}")
23
+
24
+ messages.append({"role": "user", "content": user_input}) # Add the current user message
25
 
26
  # Call Groq API to get a response from LLaMA
27
  chat_completion = client.chat.completions.create(
 
31
 
32
  # Extract response
33
  response = chat_completion.choices[0].message.content
34
+ return response, chat_history # Ensure you return both response and chat_history
35
 
36
  except Exception as e:
37
  print(f"Error occurred: {e}") # Print error to console for debugging
 
40
  # Define Gradio interface
41
  def gradio_interface():
42
  with gr.Blocks() as demo:
43
+ # Initialize chat history
44
  chat_history = []
45
 
46
+ # Create input textbox and button for clearing chat
47
+ gr.Markdown("## Mental Health Chatbot")
48
+ chatbot = gr.Chatbot(type="messages")
49
+ msg = gr.Textbox(placeholder="Type your message here...")
50
+ clear = gr.Button("Clear")
51
 
52
+ # User message submission function
53
+ def user(user_message, history: list):
54
+ # Add user message to the history
55
+ history.append({"role": "user", "content": user_message})
56
+ return "", history # Reset message input and return updated history
57
 
58
+ # Bot response function with simulated typing effect
59
+ def bot(history: list):
60
+ # Ensure that history is not empty
61
+ if len(history) > 0:
62
+ user_input = history[-1]["content"] # Get the last user message
63
+ response, updated_history = generate_response(user_input, history) # Get bot's response
64
 
65
+ history = updated_history # Update the history with the new response
66
+ history.append({"role": "assistant", "content": ""}) # Add placeholder for assistant
 
 
 
 
67
 
68
+ # Simulate typing effect for the bot's response
69
+ for character in response:
70
+ history[-1]['content'] += character
71
+ time.sleep(0.02) # Typing delay
72
+ yield history # Yield updated history as the bot types
73
+
74
+ # Set up interaction flow:
75
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(bot, chatbot, chatbot)
76
+ clear.click(lambda: [], None, chatbot, queue=False) # Clear chat history when clicked
77
 
78
  demo.launch()
79
 
80
  # Run the interface
81
+ gradio_interface()