hichri-mo commited on
Commit
4fffb03
Β·
verified Β·
1 Parent(s): 6d7dba6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -59
app.py CHANGED
@@ -1,64 +1,104 @@
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
+ from datasets import load_dataset
3
+ import os
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, BitsAndBytesConfig
5
+ import torch
6
+ from threading import Thread
7
+ from sentence_transformers import SentenceTransformer
8
+ from datasets import load_dataset
9
+ import time
10
+
11
+ ST = SentenceTransformer("mixedbread-ai/mxbai-embed-large-v1")
12
+ art_dataset= load_dataset("hichri-mo/arxiver-1000",revision="embedded")
13
+
14
+ data = art_dataset["train"]
15
+ data = data.add_faiss_index("embeddings")
16
+
17
+
18
+ model_id= "Qwen/Qwen2.5-3B-Instruct"
19
+
20
+ # use quantization to lower GPU usage
21
+ bnb_config = BitsAndBytesConfig(
22
+ load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16
23
+ )
24
+
25
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
26
+ model = AutoModelForCausalLM.from_pretrained(
27
+ model_id,
28
+ torch_dtype=torch.bfloat16,
29
+ device_map="auto",
30
+ quantization_config=bnb_config
31
+ )
32
+ terminators = [
33
+ tokenizer.eos_token_id,
34
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
35
+ ]
36
+
37
+ SYS_PROMPT = """You are an assistant for answering questions.
38
+ You are given the extracted parts of a long document and a question. Provide a conversational answer.
39
+ If you don't know the answer, just say "I do not know." Don't make up an answer."""
40
+
41
+
42
+ def format_prompt(prompt,retrieved_documents,k):
43
+ """using the retrieved documents we will prompt the model to generate our responses"""
44
+ PROMPT = f"Question: {prompt}\nContext: \n"
45
+ for idx in range(k) :
46
+ PROMPT+= f"{retrieved_documents['markdown'][idx]}\n"
47
+ return PROMPT
48
+
49
+ def generate(formatted_prompt):
50
+ formatted_prompt = formatted_prompt[:2000] # to avoid GPU OOM
51
+ messages = [{"role":"system","content":SYS_PROMPT},{"role":"user","content":formatted_prompt}]
52
+ # tell the model to generate
53
+ input_ids = tokenizer.apply_chat_template(
54
+ messages,
55
+ add_generation_prompt=True,
56
+ return_tensors="pt"
57
+ ).to(model.device)
58
+ # Check if terminators contain None and replace with tokenizer.eos_token_id
59
+ eos_token_id = terminators[0] # Default to tokenizer.eos_token_id
60
+ if terminators[1] is not None:
61
+ eos_token_id = terminators[1] # Use "<|eot_id|>" if it exists
62
+
63
+ outputs = model.generate(
64
+ input_ids,
65
+ max_new_tokens=1024,
66
+ eos_token_id=eos_token_id, # Pass a single integer value
67
+ do_sample=True,
68
+ temperature=0.6,
69
+ top_p=0.9,
70
+ )
71
+ response = outputs[0][input_ids.shape[-1]:]
72
+ return tokenizer.decode(response, skip_special_tokens=True)
73
+
74
+ def rag_chatbot(prompt:str,k:int=2):
75
+ scores , retrieved_documents = search(prompt, k)
76
+ formatted_prompt = format_prompt(prompt,retrieved_documents,k)
77
+ return generate(formatted_prompt)
78
+
79
+
80
+
81
+
82
+ def rag_chatbot_interface(prompt, k):
83
+ return rag_chatbot(prompt, k)
84
+
85
+ iface = gr.Interface(
86
+ fn=rag_chatbot_interface,
87
+ inputs=[
88
+ gr.Textbox(label="Enter your question"),
89
+ gr.Slider(minimum=1, maximum=10, step=1, value=2, label="Number of documents to retrieve")
90
  ],
91
+ outputs=gr.Textbox(label="Response"),
92
+ title="Chatbot with RAG",
93
+ description="Ask questions and get answers based on retrieved documents."
94
  )
95
 
96
+ iface.launch()
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104