syedmudassir16 commited on
Commit
77190bb
1 Parent(s): 83074ac

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +204 -0
app.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import multiprocessing
3
+ import concurrent.futures
4
+ from langchain.document_loaders import TextLoader, DirectoryLoader
5
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
6
+ from langchain.vectorstores import FAISS
7
+ from sentence_transformers import SentenceTransformer
8
+ import faiss
9
+ import torch
10
+ import numpy as np
11
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, BitsAndBytesConfig
12
+ from datetime import datetime
13
+ import json
14
+ import gradio as gr
15
+ import re
16
+ from threading import Thread
17
+
18
+ class MultiAgentRAG:
19
+ def __init__(self, embedding_model_name, lm_model_id, data_folder):
20
+ self.all_splits = self.load_documents(data_folder)
21
+ self.embeddings = SentenceTransformer(embedding_model_name)
22
+ self.gpu_index = self.create_faiss_index()
23
+ self.tokenizer, self.model = self.initialize_llm(lm_model_id)
24
+
25
+ def load_documents(self, folder_path):
26
+ loader = DirectoryLoader(folder_path, loader_cls=TextLoader)
27
+ documents = loader.load()
28
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=5000, chunk_overlap=250)
29
+ all_splits = text_splitter.split_documents(documents)
30
+ print('Length of documents:', len(documents))
31
+ print("LEN of all_splits", len(all_splits))
32
+ for i in range(3):
33
+ print(all_splits[i].page_content)
34
+ return all_splits
35
+
36
+ def create_faiss_index(self):
37
+ all_texts = [split.page_content for split in self.all_splits]
38
+ embeddings = self.embeddings.encode(all_texts, convert_to_tensor=True).cpu().numpy()
39
+ index = faiss.IndexFlatL2(embeddings.shape[1])
40
+ index.add(embeddings)
41
+ gpu_resource = faiss.StandardGpuResources()
42
+ gpu_index = faiss.index_cpu_to_gpu(gpu_resource, 0, index)
43
+ return gpu_index
44
+
45
+ def initialize_llm(self, model_id):
46
+ quantization_config = BitsAndBytesConfig(
47
+ load_in_4bit=True,
48
+ bnb_4bit_use_double_quant=True,
49
+ bnb_4bit_quant_type="nf4",
50
+ bnb_4bit_compute_dtype=torch.bfloat16
51
+ )
52
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
53
+ model = AutoModelForCausalLM.from_pretrained(
54
+ model_id,
55
+ torch_dtype=torch.bfloat16,
56
+ device_map="auto",
57
+ quantization_config=quantization_config
58
+ )
59
+ return tokenizer, model
60
+
61
+ def generate_response_with_timeout(self, input_ids, max_new_tokens=1000):
62
+ try:
63
+ streamer = TextIteratorStreamer(self.tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
64
+ generate_kwargs = dict(
65
+ input_ids=input_ids,
66
+ max_new_tokens=max_new_tokens,
67
+ do_sample=True,
68
+ top_p=1.0,
69
+ top_k=20,
70
+ temperature=0.8,
71
+ repetition_penalty=1.2,
72
+ eos_token_id=[128001, 128008, 128009],
73
+ streamer=streamer,
74
+ )
75
+
76
+ thread = Thread(target=self.model.generate, kwargs=generate_kwargs)
77
+ thread.start()
78
+
79
+ generated_text = ""
80
+ for new_text in streamer:
81
+ generated_text += new_text
82
+
83
+ return generated_text
84
+ except Exception as e:
85
+ print(f"Error in generate_response_with_timeout: {str(e)}")
86
+ return "Text generation process encountered an error"
87
+
88
+ def retrieval_agent(self, query):
89
+ query_embedding = self.embeddings.encode(query, convert_to_tensor=True).cpu().numpy()
90
+ distances, indices = self.gpu_index.search(np.array([query_embedding]), k=3)
91
+ content = ""
92
+ for idx, distance in zip(indices[0], distances[0]):
93
+ content += "-" * 50 + "\n"
94
+ content += self.all_splits[idx].page_content + "\n"
95
+ return content
96
+
97
+ def grading_agent(self, query, retrieved_content):
98
+ grading_prompt = f"""
99
+ Evaluate the relevance of the following retrieved content to the given query:
100
+
101
+ Query: {query}
102
+
103
+ Retrieved Content:
104
+ {retrieved_content}
105
+
106
+ Rate the relevance on a scale of 1-10 and explain your rating:
107
+ """
108
+ input_ids = self.tokenizer.encode(grading_prompt, return_tensors="pt").to(self.model.device)
109
+ grading_response = self.generate_response_with_timeout(input_ids)
110
+
111
+ # Extract the numerical rating from the response
112
+ rating = int(re.search(r'\d+', grading_response).group())
113
+ return rating, grading_response
114
+
115
+ def query_rewrite_agent(self, original_query):
116
+ rewrite_prompt = f"""
117
+ The following query did not yield relevant results. Please rewrite it to potentially improve retrieval:
118
+
119
+ Original Query: {original_query}
120
+
121
+ Rewritten Query:
122
+ """
123
+ input_ids = self.tokenizer.encode(rewrite_prompt, return_tensors="pt").to(self.model.device)
124
+ rewritten_query = self.generate_response_with_timeout(input_ids)
125
+ return rewritten_query.strip()
126
+
127
+ def generation_agent(self, query, retrieved_content):
128
+ generation_prompt = f"""
129
+ Using the following information retrieved from the knowledge base:
130
+
131
+ {retrieved_content}
132
+
133
+ Provide a comprehensive answer to the question below:
134
+
135
+ Question: {query}
136
+ Answer:
137
+ """
138
+ input_ids = self.tokenizer.encode(generation_prompt, return_tensors="pt").to(self.model.device)
139
+ return self.generate_response_with_timeout(input_ids)
140
+
141
+ def run_multi_agent_rag(self, query):
142
+ max_iterations = 3
143
+ for i in range(max_iterations):
144
+ # Retrieval step
145
+ retrieved_content = self.retrieval_agent(query)
146
+
147
+ # Grading step
148
+ relevance_score, grading_explanation = self.grading_agent(query, retrieved_content)
149
+
150
+ if relevance_score >= 7: # Assuming 7 out of 10 is the threshold for relevance
151
+ # Generation step
152
+ answer = self.generation_agent(query, retrieved_content)
153
+ return answer, retrieved_content, grading_explanation
154
+ else:
155
+ # Query rewrite step
156
+ query = self.query_rewrite_agent(query)
157
+
158
+ return "Unable to find a relevant answer after multiple attempts.", "", "Low relevance across all attempts."
159
+
160
+ def qa_infer_gradio(self, query):
161
+ answer, retrieved_content, grading_explanation = self.run_multi_agent_rag(query)
162
+ return answer, f"Retrieved Content:\n{retrieved_content}\n\nGrading Explanation:\n{grading_explanation}"
163
+
164
+ def launch_interface(doc_retrieval_gen):
165
+ css_code = """
166
+ .gradio-container {
167
+ background-color: #daccdb;
168
+ }
169
+ button {
170
+ background-color: #927fc7;
171
+ color: black;
172
+ border: 1px solid black;
173
+ padding: 10px;
174
+ margin-right: 10px;
175
+ font-size: 16px;
176
+ font-weight: bold;
177
+ }
178
+ """
179
+ EXAMPLES = [
180
+ "On which devices can the VIP and CSI2 modules operate simultaneously?",
181
+ "I'm using Code Composer Studio 5.4.0.00091 and enabled FPv4SPD16 floating point support for CortexM4 in TDA2. However, after building the project, the .asm file shows --float_support=vfplib instead of FPv4SPD16. Why is this happening?",
182
+ "Could you clarify the maximum number of cameras that can be connected simultaneously to the video input ports on the TDA2x SoC, considering it supports up to 10 multiplexed input ports and includes 3 dedicated video input modules?"
183
+ ]
184
+
185
+ interface = gr.Interface(
186
+ fn=doc_retrieval_gen.qa_infer_gradio,
187
+ inputs=[gr.Textbox(label="QUERY", placeholder="Enter your query here")],
188
+ allow_flagging='never',
189
+ examples=EXAMPLES,
190
+ cache_examples=False,
191
+ outputs=[gr.Textbox(label="RESPONSE"), gr.Textbox(label="RELATED QUERIES")],
192
+ css=css_code,
193
+ title="TI E2E FORUM Multi-Agent RAG"
194
+ )
195
+
196
+ interface.launch(debug=True)
197
+
198
+ if __name__ == "__main__":
199
+ embedding_model_name = 'flax-sentence-embeddings/all_datasets_v3_MiniLM-L12'
200
+ lm_model_id = "meta-llama/Meta-Llama-3.1-8B-Instruct"
201
+ data_folder = 'sample_embedding_folder2'
202
+
203
+ multi_agent_rag = MultiAgentRAG(embedding_model_name, lm_model_id, data_folder)
204
+ launch_interface(multi_agent_rag)