syedmudassir16's picture
Update app.py
bd811e9 verified
raw
history blame
15.6 kB
import os
import multiprocessing
import concurrent.futures
from langchain.document_loaders import TextLoader, DirectoryLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import FAISS
from sentence_transformers import SentenceTransformer
import faiss
import torch
import numpy as np
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, BitsAndBytesConfig
from datetime import datetime
import json
import gradio as gr
import re
from threading import Thread
from llama_index.core import VectorStoreIndex, Document
from llama_index.core.tools import QueryEngineTool, ToolMetadata
from llama_index.agent.openai import OpenAIAgent
class Agent:
def __init__(self, name, role, doc_retrieval_gen, tokenizer):
self.name = name
self.role = role
self.doc_retrieval_gen = doc_retrieval_gen
self.tokenizer = tokenizer
def generate_response(self, query, context):
if self.role == "Information Retrieval":
return self.retriever_logic(query, context)
elif self.role == "Content Analysis":
return self.analyzer_logic(query, context)
elif self.role == "Response Generation":
return self.generator_logic(query, context)
elif self.role == "Task Coordination":
return self.coordinator_logic(query, context)
def retriever_logic(self, query, all_splits):
query_embedding = self.doc_retrieval_gen.embeddings.encode(query, convert_to_tensor=True).cpu().numpy()
distances, indices = self.doc_retrieval_gen.gpu_index.search(np.array([query_embedding]), k=3)
relevant_docs = [all_splits[i] for i in indices[0] if distances[0][i] <= 1]
return relevant_docs
def analyzer_logic(self, query, relevant_docs):
analysis_prompt = f"Analyze the following documents in relation to the query: '{query}'\n\nDocuments:\n"
for doc in relevant_docs:
analysis_prompt += f"- {doc.page_content}\n"
analysis_prompt += "\nProvide a concise analysis of the key points relevant to the query."
input_ids = self.tokenizer.encode(analysis_prompt, return_tensors="pt").to(self.doc_retrieval_gen.model.device)
analysis = self.doc_retrieval_gen.model.generate(input_ids, max_length=200, num_return_sequences=1)
return self.tokenizer.decode(analysis[0], skip_special_tokens=True)
def generator_logic(self, query, analyzed_content):
generation_prompt = f"Based on the following analysis, generate a comprehensive answer to the query: '{query}'\n\nAnalysis:\n{analyzed_content}\n\nGenerate a detailed response:"
input_ids = self.tokenizer.encode(generation_prompt, return_tensors="pt").to(self.doc_retrieval_gen.model.device)
response = self.doc_retrieval_gen.model.generate(input_ids, max_length=300, num_return_sequences=1)
return self.tokenizer.decode(response[0], skip_special_tokens=True)
def coordinator_logic(self, query, final_response):
coordination_prompt = f"As a coordinator, review and refine the following response to the query: '{query}'\n\nResponse:\n{final_response}\n\nProvide a final, polished answer:"
input_ids = self.tokenizer.encode(coordination_prompt, return_tensors="pt").to(self.doc_retrieval_gen.model.device)
coordinated_response = self.doc_retrieval_gen.model.generate(input_ids, max_length=350, num_return_sequences=1)
return self.tokenizer.decode(coordinated_response[0], skip_special_tokens=True)
class MultiDocumentAgentSystem:
def __init__(self, documents_dict, llm, embed_model):
self.llm = llm
self.embed_model = embed_model
self.document_agents = {}
self.create_document_agents(documents_dict)
self.top_agent = self.create_top_agent()
def create_document_agents(self, documents_dict):
for doc_name, doc_content in documents_dict.items():
vector_index = VectorStoreIndex.from_documents([Document(doc_content)])
summary_index = VectorStoreIndex.from_documents([Document(doc_content)])
vector_query_engine = vector_index.as_query_engine(similarity_top_k=2)
summary_query_engine = summary_index.as_query_engine()
query_engine_tools = [
QueryEngineTool(
query_engine=vector_query_engine,
metadata=ToolMetadata(
name=f"vector_tool_{doc_name}",
description=f"Useful for specific questions about {doc_name}",
),
),
QueryEngineTool(
query_engine=summary_query_engine,
metadata=ToolMetadata(
name=f"summary_tool_{doc_name}",
description=f"Useful for summarizing content about {doc_name}",
),
),
]
self.document_agents[doc_name] = OpenAIAgent.from_tools(
query_engine_tools,
llm=self.llm,
verbose=True,
system_prompt=f"You are an agent designed to answer queries about {doc_name}.",
)
def create_top_agent(self):
all_tools = []
for doc_name, agent in self.document_agents.items():
doc_tool = QueryEngineTool(
query_engine=agent,
metadata=ToolMetadata(
name=f"tool_{doc_name}",
description=f"Use this tool for questions about {doc_name}",
),
)
all_tools.append(doc_tool)
obj_index = VectorStoreIndex.from_objects(all_tools, embed_model=self.embed_model)
return OpenAIAgent.from_tools(
all_tools,
llm=self.llm,
verbose=True,
system_prompt="You are an agent designed to answer queries about multiple documents.",
tool_retriever=obj_index.as_retriever(similarity_top_k=3),
)
def query(self, user_input):
return self.top_agent.chat(user_input)
class DocumentRetrievalAndGeneration:
def __init__(self, embedding_model_name, lm_model_id, data_folder):
self.all_splits = self.load_documents(data_folder)
self.embeddings = SentenceTransformer(embedding_model_name)
self.gpu_index = self.create_faiss_index()
self.tokenizer, self.model = self.initialize_llm(lm_model_id)
self.agents = self.initialize_agents()
documents_dict = self.load_documents(data_folder)
self.multi_doc_system = MultiDocumentAgentSystem(documents_dict, self.model, self.embeddings)
def initialize_agents(self):
agents = [
Agent("Retriever", "Information Retrieval", self, self.tokenizer),
Agent("Analyzer", "Content Analysis", self, self.tokenizer),
Agent("Generator", "Response Generation", self, self.tokenizer),
Agent("Coordinator", "Task Coordination", self, self.tokenizer)
]
return agents
def load_documents(self, folder_path):
documents_dict = {}
for file_name in os.listdir(folder_path):
if file_name.endswith('.txt'):
file_path = os.path.join(folder_path, file_name)
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
documents_dict[file_name[:-4]] = content # Use filename without .txt as key
return documents_dict
def create_faiss_index(self):
all_texts = [split.page_content for split in self.all_splits]
embeddings = self.embeddings.encode(all_texts, convert_to_tensor=True).cpu().numpy()
index = faiss.IndexFlatL2(embeddings.shape[1])
index.add(embeddings)
gpu_resource = faiss.StandardGpuResources()
gpu_index = faiss.index_cpu_to_gpu(gpu_resource, 0, index)
return gpu_index
def initialize_llm(self, model_id):
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.bfloat16,
device_map="auto",
quantization_config=quantization_config
)
return tokenizer, model
def coordinate_agents(self, query):
coordinator = next(agent for agent in self.agents if agent.name == "Coordinator")
# Step 1: Information Retrieval
retriever = next(agent for agent in self.agents if agent.name == "Retriever")
relevant_docs = retriever.generate_response(query, self.all_splits)
# Step 2: Content Analysis
analyzer = next(agent for agent in self.agents if agent.name == "Analyzer")
analyzed_content = analyzer.generate_response(query, relevant_docs)
# Step 3: Response Generation
generator = next(agent for agent in self.agents if agent.name == "Generator")
final_response = generator.generate_response(query, analyzed_content)
# Step 4: Coordination and Refinement
coordinated_response = coordinator.generate_response(query, final_response)
return coordinated_response, "\n".join([doc.page_content for doc in relevant_docs])
def query_and_generate_response(self, query):
response = self.multi_doc_system.query(query)
return str(response), ""
def generate_response_with_timeout(self, input_ids, max_new_tokens=1000):
try:
streamer = TextIteratorStreamer(self.tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
generate_kwargs = dict(
input_ids=input_ids,
max_new_tokens=max_new_tokens,
do_sample=True,
top_p=1.0,
top_k=20,
temperature=0.8,
repetition_penalty=1.2,
eos_token_id=[128001, 128008, 128009],
streamer=streamer,
)
thread = Thread(target=self.model.generate, kwargs=generate_kwargs)
thread.start()
generated_text = ""
for new_text in streamer:
generated_text += new_text
return generated_text
except Exception as e:
print(f"Error in generate_response_with_timeout: {str(e)}")
return "Text generation process encountered an error"
def query_and_generate_response(self, query):
similarityThreshold = 1
query_embedding = self.embeddings.encode(query, convert_to_tensor=True).cpu().numpy()
distances, indices = self.gpu_index.search(np.array([query_embedding]), k=3)
print("Distance", distances, "indices", indices)
content = ""
filtered_results = []
for idx, distance in zip(indices[0], distances[0]):
if distance <= similarityThreshold:
filtered_results.append(idx)
for i in filtered_results:
print(self.all_splits[i].page_content)
content += "-" * 50 + "\n"
content += self.all_splits[idx].page_content + "\n"
print("CHUNK", idx)
print("Distance:", distance)
print("indices:", indices)
print(self.all_splits[idx].page_content)
print("############################")
conversation = [
{"role": "system", "content": "You are a knowledgeable assistant with access to a comprehensive database."},
{"role": "user", "content": f"""
I need you to answer my question and provide related information in a specific format.
I have provided five relatable json files {content}, choose the most suitable chunks for answering the query.
RETURN ONLY SOLUTION without additional comments, sign-offs, retrived chunks, refrence to any Ticket or extra phrases. Be direct and to the point.
IF THERE IS NO ANSWER RELATABLE IN RETRIEVED CHUNKS, RETURN "NO SOLUTION AVAILABLE".
DO NOT GIVE REFRENCE TO ANY CHUNKS OR TICKETS,BE ON POINT.
Here's my question:
Query: {query}
Solution==>
"""}
]
#Include a final answer without additional comments, sign-offs, or extra phrases. Be direct and to the point.
input_ids = self.tokenizer.apply_chat_template(conversation, return_tensors="pt").to(self.model.device)
start_time = datetime.now()
generated_response = self.generate_response_with_timeout(input_ids)
elapsed_time = datetime.now() - start_time
print("Generated response:", generated_response)
print("Time elapsed:", elapsed_time)
print("Device in use:", self.model.device)
solution_text = generated_response.strip()
if "Solution:" in solution_text:
solution_text = solution_text.split("Solution:", 1)[1].strip()
# Post-processing to remove "assistant" prefix
solution_text = re.sub(r'^assistant\s*', '', solution_text, flags=re.IGNORECASE)
solution_text = solution_text.strip()
return solution_text, content
def qa_infer_gradio(self, query):
response, related_queries = self.query_and_generate_response(query)
return response, related_queries
if __name__ == "__main__":
embedding_model_name = 'flax-sentence-embeddings/all_datasets_v3_MiniLM-L12'
lm_model_id = "meta-llama/Meta-Llama-3.1-8B-Instruct"
data_folder = 'sample_embedding_folder2'
doc_retrieval_gen = DocumentRetrievalAndGeneration(embedding_model_name, lm_model_id, data_folder)
def launch_interface():
css_code = """
.gradio-container {
background-color: #daccdb;
}
button {
background-color: #927fc7;
color: black;
border: 1px solid black;
padding: 10px;
margin-right: 10px;
font-size: 16px;
font-weight: bold;
}
"""
EXAMPLES = [
"On which devices can the VIP and CSI2 modules operate simultaneously?",
"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?",
"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?"
]
interface = gr.Interface(
fn=doc_retrieval_gen.qa_infer_gradio,
inputs=[gr.Textbox(label="QUERY", placeholder="Enter your query here")],
allow_flagging='never',
examples=EXAMPLES,
cache_examples=False,
outputs=[gr.Textbox(label="RESPONSE"), gr.Textbox(label="RELATED QUERIES")],
css=css_code,
title="TI E2E FORUM"
)
interface.launch(debug=True)
launch_interface()