dharshanre20 commited on
Commit
c88ba7e
·
verified ·
1 Parent(s): 18d3315

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +63 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ from transformers import pipeline
4
+
5
+ pipe = pipeline(
6
+ "text-generation",
7
+ model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
8
+ torch_dtype=torch.bfloat16,
9
+ device_map="auto"
10
+ )
11
+
12
+ chat_history = []
13
+
14
+ def chat_with_bot(user_input):
15
+ global chat_history
16
+
17
+ # Build chat messages
18
+ messages = [{"role": "system", "content": "You are a friendly chatbot who always responds in the style of a pirate"}]
19
+ for msg in chat_history:
20
+ messages.append({"role": "user", "content": msg["user"]})
21
+ messages.append({"role": "assistant", "content": msg["bot"]})
22
+ messages.append({"role": "user", "content": user_input})
23
+
24
+ # Format using chat template
25
+ prompt = pipe.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
26
+
27
+ # Generate model response
28
+ outputs = pipe(prompt, max_new_tokens=256, do_sample=True, temperature=0.7, top_k=50, top_p=0.95)
29
+ response = outputs[0]["generated_text"].split(prompt)[-1].strip()
30
+
31
+ # Save to history
32
+ chat_history.append({"user": user_input, "bot": response})
33
+
34
+ # Build display string
35
+ chat_text = ""
36
+ for turn in chat_history:
37
+ chat_text += f"🧑 You: {turn['user']}\n🤖 Bot: {turn['bot']}\n\n"
38
+ return chat_text.strip()
39
+
40
+ def clear_chat():
41
+ global chat_history
42
+ chat_history = []
43
+ return ""
44
+
45
+ with gr.Blocks() as demo:
46
+ gr.Markdown("## 🤖 TinyLlama 1.1b ChatBot")
47
+
48
+ # Row 1: User Input
49
+ user_input = gr.Textbox(placeholder="Type your question here...", label="Your Message")
50
+
51
+ # Row 2: Submit and Clear Buttons
52
+ with gr.Row():
53
+ submit_btn = gr.Button("Submit")
54
+ clear_btn = gr.Button("Clear")
55
+
56
+ # Row 3: Chat Output
57
+ chat_output = gr.Textbox(label="ChatBot", lines=20)
58
+
59
+ # Connect buttons
60
+ submit_btn.click(chat_with_bot, inputs=user_input, outputs=chat_output)
61
+ clear_btn.click(clear_chat, outputs=chat_output)
62
+ #Interface
63
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ transformers
2
+ torch