adeelshuaib commited on
Commit
19cb684
·
verified ·
1 Parent(s): 54fb593

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -63
app.py CHANGED
@@ -1,72 +1,63 @@
1
  import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
3
 
4
- # Load the tokenizer and model directly
5
- tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-3B")
6
- model = AutoModelForSeq2SeqLM.from_pretrained("facebook/blenderbot-3B")
7
 
8
- def respond(
9
- message,
10
- history: list[tuple[str, str]],
11
- system_message,
12
- max_tokens,
13
- temperature,
14
- top_p,
15
- ):
16
- # Compile the messages for context
17
- messages = [{"role": "system", "content": system_message}]
18
-
19
- for val in history:
20
- if val[0]: # user message
21
- messages.append({"role": "user", "content": val[0]})
22
- if val[1]: # assistant response
23
- messages.append({"role": "assistant", "content": val[1]})
24
-
25
- messages.append({"role": "user", "content": message})
26
 
27
- # Concatenate messages as input text
28
- input_text = "\n".join([msg["content"] for msg in messages if msg["role"] == "user"])
29
-
30
- # Tokenize input text and generate response
31
- inputs = tokenizer(input_text, return_tensors="pt")
32
- outputs = model.generate(
33
- **inputs,
34
- max_length=max_tokens,
35
- temperature=temperature,
36
- top_p=top_p,
37
- do_sample=True
38
- )
39
 
40
- # Decode the generated response
41
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
42
-
43
- # Return response iteratively as tokens arrive (optional: can remove yield if streaming is not needed)
44
- yield response
45
 
46
- # Customize the system message for mental health support
47
- default_system_message = """
48
- You are a compassionate mental health specialist trained to listen empathetically and offer support.
49
- When engaging with users, make sure to respond with kindness and provide general emotional support.
50
- Avoid giving specific medical or clinical advice, but offer guidance, validate feelings, and suggest appropriate resources when needed.
51
- Encourage open conversations and create a safe, non-judgmental space for the user to share.
52
- """
53
 
54
- # Set up the Gradio interface
55
- demo = gr.ChatInterface(
56
- respond,
57
- additional_inputs=[
58
- gr.Textbox(value=default_system_message, label="System Message (Mental Health Specialist)"),
59
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
60
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
61
- gr.Slider(
62
- minimum=0.1,
63
- maximum=1.0,
64
- value=0.95,
65
- step=0.05,
66
- label="Top-p (nucleus sampling)",
67
- ),
68
- ],
69
- )
 
 
 
 
 
 
70
 
71
- if __name__ == "__main__":
72
  demo.launch()
 
 
 
 
1
  import gradio as gr
2
+ from groq import Groq
3
 
4
+ # Initialize Groq client
5
+ client = Groq(api_key='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')
 
6
 
7
+ # Function to generate responses with error handling
8
+ def generate_response(user_input, chat_history):
9
+ try:
10
+ # Prepare messages with chat history
11
+ messages = [{"role": "system", "content": "You are a helpful mental health assistant."}]
12
+ for user_message, bot_response in chat_history:
13
+ messages.append({"role": "user", "content": user_message})
14
+ messages.append({"role": "assistant", "content": bot_response})
15
+ messages.append({"role": "user", "content": user_input})
 
 
 
 
 
 
 
 
 
16
 
17
+ # Call Groq API to get a response from LLaMA
18
+ chat_completion = client.chat.completions.create(
19
+ messages=messages,
20
+ model="llama3-8b-8192"
21
+ )
22
+
23
+ # Extract response
24
+ response = chat_completion.choices[0].message.content
25
+ return response, chat_history
 
 
 
26
 
27
+ except Exception as e:
28
+ print(f"Error occurred: {e}") # Print error to console for debugging
29
+ return "An error occurred while generating the response. Please try again.", chat_history
 
 
30
 
31
+ # Define Gradio interface
32
+ def gradio_interface():
33
+ with gr.Blocks() as demo:
34
+ # Variable to store chat history
35
+ chat_history = []
 
 
36
 
37
+ def generate_and_clear(user_input):
38
+ response, updated_history = generate_response(user_input, chat_history)
39
+ chat_history.append((user_input, response))
40
+ return response
41
+
42
+ def clear_chat():
43
+ chat_history.clear()
44
+ return "Chat history cleared. Start a new conversation!"
45
+
46
+ # Title and instructions
47
+ gr.Markdown("## Mental Health Chatbot - Powered by LLaMA on Groq")
48
+
49
+ # Chat interface setup
50
+ chatbot = gr.ChatInterface(
51
+ fn=generate_and_clear,
52
+ additional_inputs=[gr.Textbox(placeholder="Enter your message here...", label="Your Message")],
53
+ title="Mental Health Chatbot"
54
+ )
55
+
56
+ # Add button to clear chat history
57
+ clear_button = gr.Button("Clear Chat History")
58
+ clear_button.click(fn=clear_chat, inputs=[], outputs=chatbot) # Clear chat on button click
59
 
 
60
  demo.launch()
61
+
62
+ # Run the interface
63
+ gradio_interface()