Spaces:
Sleeping
Sleeping
File size: 8,177 Bytes
c65ba42 c119679 c65ba42 c119679 d4b9099 c119679 3c6573c d4b9099 c119679 bd811e9 0217d37 7eccbd5 bd811e9 0217d37 bd811e9 0217d37 c119679 0217d37 c119679 d4b9099 0217d37 c119679 bd811e9 c119679 d4b9099 c119679 d4b9099 c119679 d4b9099 c119679 d4b9099 c119679 d4b9099 c119679 0217d37 c119679 7eccbd5 3c6573c c65ba42 c119679 d4b9099 c119679 d4b9099 c119679 d4b9099 c119679 d4b9099 c119679 d4b9099 c119679 d4b9099 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 |
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
from llama_index.llms.openai import OpenAI
from llama_index.embeddings.openai import OpenAIEmbedding
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(text=doc_content)])
summary_index = VectorStoreIndex.from_documents([Document(text=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.documents_dict = self.load_documents(data_folder)
self.embeddings = SentenceTransformer(embedding_model_name)
self.tokenizer, self.model = self.initialize_llm(lm_model_id)
self.llm = OpenAI(temperature=0, model="gpt-3.5-turbo")
self.embed_model = OpenAIEmbedding()
self.multi_doc_system = MultiDocumentAgentSystem(self.documents_dict, self.llm, self.embed_model)
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 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 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):
response = self.multi_doc_system.query(query)
return str(response), ""
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() |