aliMohammad16 commited on
Commit
decda19
·
verified ·
1 Parent(s): a56c1ee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -52
app.py CHANGED
@@ -1,64 +1,85 @@
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, pipeline
4
+ from sentence_transformers import SentenceTransformer
5
+ import faiss
6
+ import numpy as np
7
 
8
+ # Configuration
9
+ class Config:
10
+ model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
11
+ embedding_model = "all-MiniLM-L6-v2"
12
+ vector_dim = 384
13
+ top_k = 3
14
+ chunk_size = 256
15
 
16
+ # Vector Database
17
+ class VectorDB:
18
+ def __init__(self):
19
+ self.index = faiss.IndexFlatL2(Config.vector_dim)
20
+ self.texts = []
21
+ self.embedding_model = SentenceTransformer(Config.embedding_model)
22
+
23
+ def add_text(self, text: str):
24
+ embedding = self.embedding_model.encode([text])[0]
25
+ embedding = np.array([embedding], dtype=np.float32)
26
+ faiss.normalize_L2(embedding)
27
+ self.index.add(embedding)
28
+ self.texts.append(text)
29
+
30
+ def search(self, query: str):
31
+ if self.index.ntotal == 0:
32
+ return []
33
+ query_embedding = self.embedding_model.encode([query])[0]
34
+ query_embedding = np.array([query_embedding], dtype=np.float32)
35
+ faiss.normalize_L2(query_embedding)
36
+ D, I = self.index.search(query_embedding, min(Config.top_k, self.index.ntotal))
37
+ return [self.texts[i] for i in I[0] if i < len(self.texts)]
38
 
39
+ # Load Model
40
+ class TinyChatModel:
41
+ def __init__(self):
42
+ self.tokenizer = AutoTokenizer.from_pretrained(Config.model_name)
43
+ self.pipe = pipeline("text-generation", model=Config.model_name, torch_dtype=torch.bfloat16, device_map="auto")
 
 
 
 
44
 
45
+ def generate_response(self, message: str, context: str = ""):
46
+ messages = [{"role": "user", "content": message}]
47
+ if context:
48
+ messages.insert(0, {"role": "system", "content": f"Context:\n{context}"})
49
+ prompt = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
50
+ outputs = self.pipe(prompt, max_new_tokens=256, do_sample=True, temperature=0.7, top_k=50, top_p=0.95)
51
+ return outputs[0]["generated_text"].split("<|assistant|>")[-1].strip()
52
 
53
+ # Initialize
54
+ vector_db = VectorDB()
55
+ chat_model = TinyChatModel()
56
 
57
+ def chat_interface(user_input):
58
+ context = "\n".join(vector_db.search(user_input))
59
+ response = chat_model.generate_response(user_input, context)
60
+ vector_db.add_text(f"User: {user_input}\nAssistant: {response}")
61
+ return response
62
 
63
+ def add_text_interface(text):
64
+ vector_db.add_text(text)
65
+ return "Text added to memory!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
+ # Gradio UI
68
+ demo = gr.Blocks()
69
+ with demo:
70
+ gr.Markdown("# 🦙 TinyChat - AI Chatbot")
71
+ with gr.Row():
72
+ chatbot = gr.Chatbot()
73
+ with gr.Row():
74
+ user_input = gr.Textbox(label="Your Message")
75
+ send_btn = gr.Button("Send")
76
+ with gr.Row():
77
+ add_text_input = gr.Textbox(label="Add Knowledge to AI")
78
+ add_text_btn = gr.Button("Add Text")
79
+
80
+ send_btn.click(chat_interface, inputs=user_input, outputs=chatbot)
81
+ add_text_btn.click(add_text_interface, inputs=add_text_input, outputs=gr.Textbox())
82
 
83
+ # Launch
84
  if __name__ == "__main__":
85
  demo.launch()