File size: 5,506 Bytes
c44a4f2
ebccb32
 
85479a5
 
 
 
ebccb32
85479a5
ebccb32
85479a5
c44a4f2
85479a5
 
b9fad54
85479a5
 
 
c44a4f2
 
85479a5
c44a4f2
 
 
155939c
c44a4f2
85479a5
 
c44a4f2
 
85479a5
 
 
c44a4f2
 
 
 
 
 
 
 
 
85479a5
c44a4f2
 
 
 
 
 
 
 
 
 
 
5c8ae8a
c44a4f2
 
 
 
85479a5
 
 
 
 
 
 
 
 
be4080d
 
85479a5
 
 
 
 
 
 
 
 
 
 
 
 
 
155939c
85479a5
 
 
 
 
 
 
 
c44a4f2
 
85479a5
 
 
 
 
 
155939c
5c8ae8a
 
c44a4f2
c9c8374
 
 
c44a4f2
c9c8374
c44a4f2
c9c8374
 
 
 
c44a4f2
c9c8374
0daa561
01d48c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85479a5
 
 
 
 
155939c
85479a5
 
 
 
 
 
 
155939c
85479a5
 
 
 
 
155939c
01d48c5
85479a5
 
c44a4f2
 
 
155939c
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
import gradio as gr
from llama_index.core import (
    Settings,
    SimpleDirectoryReader,
    VectorStoreIndex,
    ServiceContext,
    LLMPredictor,
    StorageContext,
)
# from llama_index.storage.storage_context import StorageContext
from llama_index.vector_stores.milvus import MilvusVectorStore
from llama_index.llms.nvidia import NVIDIA
from llama_index.embeddings.nvidia import NVIDIAEmbedding
from llama_index.postprocessor import NvidiaNeMoRerank
from llama_index.readers.file import (
    Reader,
    # SimpleWebPageReader,
    HTMLTagReader,
    DocxReader,
    PDFReader,
    PresentationReader,
    ImageReader,
    CSVReader,
)
from llama_index.text_splitter import SentenceSplitter  # Import SentenceSplitter

# Initialize LLM, embedding model, and text splitter
Settings.llm = NVIDIA(model="meta/llama-3.1-8b-instruct")
Settings.embed_model = NVIDIAEmbedding(model="NV-Embed-QA", truncate="END")
Settings.text_splitter = SentenceSplitter(chunk_size=400)
Settings.service_context = ServiceContext.from_defaults(
    llm=Settings.llm, embed_model=Settings.embed_model, text_splitter=Settings.text_splitter
)

# Import Nemo modules

from nemoguardrails import LLMRails, RailsConfig

# Define a RailsConfig object
config = RailsConfig.from_path("./Config")
rails = LLMRails(config)


# Initialize global variables for the index and query engine
index = None
query_engine = None

# Function to get file names from file objects
def get_files_from_input(file_objs):
    if not file_objs:
        return []
    return [file_obj.name for file_obj in file_objs]

# Function to load documents and create the index
def load_documents(file_objs, url=None, service_context=None):
    global index, query_engine
    try:
        if not file_objs:
            return "Error: No files selected."

        # Create reader classes for different file types
        reader_classes = {
            ".pdf": PDFReader,
            ".docx": DocxReader,
            ".pptx": PresentationReader,
            ".csv": CSVReader,
            ".jpg": ImageReader,
            ".jpeg": ImageReader,
        }

        documents = []
        for file in file_objs:
            reader_class = reader_classes.get(file.name.lower()[-5:], Reader)
            reader = reader_class()
            documents.extend(reader.load_data(file))

        if url:
            reader = HTMLTagReader()
            documents.extend(reader.load_data(urls=[url]))

        if not documents:
            return f"No documents found in the selected files."

        # Create index from documents
        vector_store = MilvusVectorStore(
            host="127.0.0.1",
            port=19530,
            dim=1024,
            collection_name="vectorstore",
            gpu_id=0,  # Specify the GPU ID to use
            output_fields=["field1","field2"]
        )
        # vector_store = MilvusVectorStore(uri="./milvus_demo.db", dim=1024, overwrite=True) #For CPU only vector store
        storage_context = StorageContext.from_defaults(vector_store=vector_store)

        # Create index and query engine
        index = VectorStoreIndex.from_documents(
            documents, service_context=service_context
        )
        query_engine = index.as_query_engine(similarity_top_k=20, streaming=True)
        return "Documents loaded successfully!"

    except Exception as e:
        return f"Error loading documents: {str(e)}"

# Function to handle chat interactions
def chat(message,history):
    global query_engine
    if query_engine is None:
        return history + [("Please upload a file first.",None)]
    try:
        #modification for nemo guardrails ( next three rows)
        user_message = {"role":"user","content":message}
        response = rails.generate(messages=[user_message])
        return history + [(message,response['content'])]
    except Exception as e:
        return history + [(message,f"Error processing query: {str(e)}")]

# Function to stream responses
def stream_response(message,history):
    global query_engine
    if query_engine is None:
        yield history + [("Please upload a file first.",None)]
        return

    try:
        response = query_engine.query(message)
        partial_response = ""
        for text in response.response_gen:
            partial_response += text
            yield history + [(message,partial_response)]
    except Exception as e:
        yield history + [(message, f"Error processing query: {str(e)}")]

with gr.Blocks() as iface:
    gr.Markdown("# Multi-document RAG Chatbot 🦀 ")  # Title using Markdown
    gr.Markdown("Upload various documents or HTML URL for Q&A")
    with gr.Row():
        with gr.Column():
            file_input = gr.File(file_count="multiple", label="Upload documents")
        with gr.Column():
            url_input = gr.Textbox(label="Enter URL")
    with gr.Row():
        load_button = gr.Button("Load Documents & URL")
    status_output = gr.Textbox(label="Status")

    load_button.click(
        fn=load_documents, inputs=[file_input, url_input, outputs=status_output,
    )

    with gr.Row():
        chatbot = gr.Chatbot()
        msg = gr.Textbox(label="Enter your question")
        # Use the chat function with Gurardrails
        msg.submit(stream_response, inputs=[msg, chatbot], outputs=[chatbot])
        clear_button = gr.Button("Clear")
        clear_button.click(lambda: None, None, chatbot, queue=False)

# Launch the Gradio interface
if __name__ == "__main__":
    iface.queue().launch(share=True,debug=True)