-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
59 lines (46 loc) · 1.94 KB
/
app.py
File metadata and controls
59 lines (46 loc) · 1.94 KB
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
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.core import StorageContext, load_index_from_storage
from flask import Flask, request, render_template
import os
# Set your OpenAI API key
os.environ["OPENAI_API_KEY"] = "sk-proj-****************************************"
app = Flask(__name__)
class RAG:
def __init__(self):
self.index = None
def load_documents(self, data_dir):
# Load documents from the specified directory using SimpleDirectoryReader
documents = SimpleDirectoryReader(data_dir).load_data()
print(f"Number of documents loaded: {len(documents)}")
return documents
def create_index(self, documents, persist_dir="Embeddings"):
# Create a VectorStoreIndex from the documents
index = VectorStoreIndex(documents, show_progress=True)
# Persist the index to the specified directory
index.storage_context.persist(persist_dir=persist_dir)
return index
def load_index(self, persist_dir="Embeddings"):
# Load the index from the specified directory
storage_context = StorageContext.from_defaults(persist_dir=persist_dir)
index = load_index_from_storage(storage_context)
return index
def query(self, question):
# Load all documents from the 'data' directory
documents = self.load_documents('data')
if not self.index:
self.index = self.create_index(documents)
else:
self.index = self.load_index()
query_engine = self.index.as_query_engine()
response = query_engine.query(question)
return response
@app.route('/', methods=['GET', 'POST'])
def index():
response = ""
if request.method == 'POST':
question = request.form['question']
obj = RAG()
response = obj.query(question)
return render_template('index.html', response=response)
if __name__ == '__main__':
app.run(debug=True)