sajeewa commited on
Commit
31ab657
·
verified ·
1 Parent(s): 8bd31e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -51
app.py CHANGED
@@ -1,64 +1,86 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
3
 
4
- """
5
- 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
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
8
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
 
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
27
 
28
- response = ""
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.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
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
 
 
 
 
61
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer
4
 
5
+ # Load model & tokenizer
6
+ model_id = "sajeewa/empathy-chat-gemma"
7
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
8
+ model = AutoModelForCausalLM.from_pretrained(
9
+ model_id,
10
+ torch_dtype=torch.float16,
11
+ device_map="auto"
12
+ )
13
 
14
+ MAX_TOKENS = 2048
15
 
16
+ # System prompt
17
+ system_prompt = {
18
+ "role": "system",
19
+ "content": (
20
+ "You are an empathetic AI and your friend. Always give lovely caring messages. "
21
+ "Understand the user's feelings, then provide a caring response. "
22
+ "Talk like a sweet friend using words like 'baby', 'cutie', etc. "
23
+ "Use emojis when helpful. Try to continue the conversation in a gentle, emotional tone."
24
+ )
25
+ }
26
 
27
+ # Initialize chat history
28
+ chat_history = [system_prompt]
 
 
 
29
 
30
+ # Define a function to generate responses
31
+ def respond(user_input, history):
32
+ global chat_history
33
 
34
+ # Add user message
35
+ chat_history.append({"role": "user", "content": user_input})
36
 
37
+ # Token length control
38
+ chat_prompt = tokenizer.apply_chat_template(chat_history, tokenize=False)
39
+ while len(tokenizer(chat_prompt).input_ids) > MAX_TOKENS:
40
+ chat_history.pop(1) # Remove oldest non-system message
41
+ chat_prompt = tokenizer.apply_chat_template(chat_history, tokenize=False)
 
 
 
42
 
43
+ # Prepare model input
44
+ inputs = tokenizer(chat_prompt, return_tensors="pt").to(model.device)
45
 
46
+ # Generate response
47
+ output = model.generate(
48
+ **inputs,
49
+ max_new_tokens=128,
50
+ temperature=0.7,
51
+ top_p=0.95,
52
+ top_k=50,
53
+ do_sample=True,
54
+ )
55
+ response_text = tokenizer.decode(output[0], skip_special_tokens=True)
56
+ new_response = response_text[len(chat_prompt):].strip()
57
 
58
+ # Add assistant's response to history
59
+ chat_history.append({"role": "assistant", "content": new_response})
60
+
61
+ # Show full conversation
62
+ history.append((user_input, new_response))
63
+ return history, history
64
+
65
+ # Define reset function
66
+ def reset_chat():
67
+ global chat_history
68
+ chat_history = [system_prompt]
69
+ return [], []
70
+
71
+ # Gradio UI
72
+ with gr.Blocks() as demo:
73
+ gr.Markdown("## 💬 Empathy Chat with Gemma")
74
+ chatbot = gr.Chatbot()
75
+ with gr.Row():
76
+ msg = gr.Textbox(label="Your Message", placeholder="Tell me how you feel...")
77
+ with gr.Row():
78
+ send = gr.Button("Send")
79
+ clear = gr.Button("Reset Chat")
80
 
81
+ send.click(fn=respond, inputs=[msg, chatbot], outputs=[chatbot, chatbot])
82
+ clear.click(fn=reset_chat, outputs=[chatbot, chatbot])
83
+ msg.submit(fn=respond, inputs=[msg, chatbot], outputs=[chatbot, chatbot])
84
 
85
+ # Launch the app
86
+ demo.launch()