AI-ANK commited on
Commit
6041051
·
verified ·
1 Parent(s): e5c34a4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +324 -0
app.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, tempfile, qdrant_client
2
+ import streamlit as st
3
+ from llama_index.llms import OpenAI, Gemini, Cohere
4
+ from llama_index.embeddings import HuggingFaceEmbedding
5
+ from llama_index import SimpleDirectoryReader, ServiceContext, VectorStoreIndex, StorageContext
6
+ from llama_index.node_parser import SentenceSplitter, CodeSplitter, SemanticSplitterNodeParser, TokenTextSplitter
7
+ from llama_index.node_parser.file import HTMLNodeParser, JSONNodeParser, MarkdownNodeParser
8
+ from llama_index.vector_stores import QdrantVectorStore, PineconeVectorStore
9
+ from pinecone import Pinecone
10
+
11
+
12
+ def reset_pipeline_generated():
13
+ if 'pipeline_generated' in st.session_state:
14
+ st.session_state['pipeline_generated'] = False
15
+
16
+ def upload_file():
17
+ file = st.file_uploader("Upload a file", on_change=reset_pipeline_generated)
18
+ if file is not None:
19
+ file_path = save_uploaded_file(file)
20
+
21
+ if file_path:
22
+ loaded_file = SimpleDirectoryReader(input_files=[file_path]).load_data()
23
+ print(f"Total documents: {len(loaded_file)}")
24
+
25
+ st.success(f"File uploaded successfully. Total documents loaded: {len(loaded_file)}")
26
+ #print(loaded_file)
27
+ return loaded_file
28
+ return None
29
+
30
+ @st.cache_data
31
+ def save_uploaded_file(uploaded_file):
32
+ try:
33
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[1]) as tmp_file:
34
+ tmp_file.write(uploaded_file.getvalue())
35
+ return tmp_file.name
36
+ except Exception as e:
37
+ st.error(f"Error saving file: {e}")
38
+ return None
39
+
40
+
41
+ def select_llm():
42
+ st.header("Choose LLM")
43
+ llm_choice = st.selectbox("Select LLM", ["Gemini", "Cohere", "GPT-3.5", "GPT-4"], on_change=reset_pipeline_generated)
44
+
45
+ if llm_choice == "GPT-3.5":
46
+ llm = OpenAI(temperature=0.1, model="gpt-3.5-turbo-1106")
47
+ st.write(f"{llm_choice} selected")
48
+ elif llm_choice == "GPT-4":
49
+ llm = OpenAI(temperature=0.1, model="gpt-4-1106-preview")
50
+ st.write(f"{llm_choice} selected")
51
+ elif llm_choice == "Gemini":
52
+ llm = Gemini(model="models/gemini-pro")
53
+ st.write(f"{llm_choice} selected")
54
+ elif llm_choice == "Cohere":
55
+ llm = Cohere(model="command", api_key=os.environ['COHERE_API_TOKEN'])
56
+ st.write(f"{llm_choice} selected")
57
+ return llm, llm_choice
58
+
59
+ def select_embedding_model():
60
+ st.header("Choose Embedding Model")
61
+ model_names = [
62
+ "BAAI/bge-small-en-v1.5",
63
+ "WhereIsAI/UAE-Large-V1",
64
+ "BAAI/bge-large-en-v1.5",
65
+ "khoa-klaytn/bge-small-en-v1.5-angle",
66
+ "BAAI/bge-base-en-v1.5",
67
+ "llmrails/ember-v1",
68
+ "jamesgpt1/sf_model_e5",
69
+ "thenlper/gte-large",
70
+ "infgrad/stella-base-en-v2",
71
+ "thenlper/gte-base"
72
+ ]
73
+ selected_model = st.selectbox("Select Embedding Model", model_names, on_change=reset_pipeline_generated)
74
+ with st.spinner("Please wait") as status:
75
+ embed_model = HuggingFaceEmbedding(model_name=selected_model)
76
+ st.session_state['embed_model'] = embed_model
77
+ st.markdown(F"Embedding Model: {embed_model.model_name}")
78
+ st.markdown(F"Embed Batch Size: {embed_model.embed_batch_size}")
79
+ st.markdown(F"Embed Batch Size: {embed_model.max_length}")
80
+
81
+
82
+ return embed_model, selected_model
83
+
84
+ def select_node_parser():
85
+ st.header("Choose Node Parser")
86
+ parser_types = ["SentenceSplitter", "CodeSplitter", "SemanticSplitterNodeParser",
87
+ "TokenTextSplitter", "HTMLNodeParser", "JSONNodeParser", "MarkdownNodeParser"]
88
+ parser_type = st.selectbox("Select Node Parser", parser_types, on_change=reset_pipeline_generated)
89
+
90
+ parser_params = {}
91
+ if parser_type == "HTMLNodeParser":
92
+ tags = st.text_input("Enter tags separated by commas", "p, h1")
93
+ tag_list = tags.split(',')
94
+ parser = HTMLNodeParser(tags=tag_list)
95
+ parser_params = {'tags': tag_list}
96
+
97
+ elif parser_type == "JSONNodeParser":
98
+ parser = JSONNodeParser()
99
+
100
+ elif parser_type == "MarkdownNodeParser":
101
+ parser = MarkdownNodeParser()
102
+
103
+ elif parser_type == "CodeSplitter":
104
+ language = st.text_input("Language", "python")
105
+ chunk_lines = st.number_input("Chunk Lines", min_value=1, value=40)
106
+ chunk_lines_overlap = st.number_input("Chunk Lines Overlap", min_value=0, value=15)
107
+ max_chars = st.number_input("Max Chars", min_value=1, value=1500)
108
+ parser = CodeSplitter(language=language, chunk_lines=chunk_lines, chunk_lines_overlap=chunk_lines_overlap, max_chars=max_chars)
109
+ parser_params = {'language': language, 'chunk_lines': chunk_lines, 'chunk_lines_overlap': chunk_lines_overlap, 'max_chars': max_chars}
110
+
111
+ elif parser_type == "SentenceSplitter":
112
+ chunk_size = st.number_input("Chunk Size", min_value=1, value=1024)
113
+ chunk_overlap = st.number_input("Chunk Overlap", min_value=0, value=20)
114
+ parser = SentenceSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
115
+ parser_params = {'chunk_size': chunk_size, 'chunk_overlap': chunk_overlap}
116
+
117
+ elif parser_type == "SemanticSplitterNodeParser":
118
+ if 'embed_model' not in st.session_state:
119
+ st.warning("Please select an embedding model first.")
120
+ return None, None
121
+
122
+ embed_model = st.session_state['embed_model']
123
+ buffer_size = st.number_input("Buffer Size", min_value=1, value=1)
124
+ breakpoint_percentile_threshold = st.number_input("Breakpoint Percentile Threshold", min_value=0, max_value=100, value=95)
125
+ parser = SemanticSplitterNodeParser(buffer_size=buffer_size, breakpoint_percentile_threshold=breakpoint_percentile_threshold, embed_model=embed_model)
126
+ parser_params = {'buffer_size': buffer_size, 'breakpoint_percentile_threshold': breakpoint_percentile_threshold}
127
+
128
+ elif parser_type == "TokenTextSplitter":
129
+ chunk_size = st.number_input("Chunk Size", min_value=1, value=1024)
130
+ chunk_overlap = st.number_input("Chunk Overlap", min_value=0, value=20)
131
+ parser = TokenTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
132
+ parser_params = {'chunk_size': chunk_size, 'chunk_overlap': chunk_overlap}
133
+
134
+ # Save the parser type and parameters to the session state
135
+ st.session_state['node_parser_type'] = parser_type
136
+ st.session_state['node_parser_params'] = parser_params
137
+
138
+ return parser, parser_type
139
+
140
+
141
+ def select_response_synthesis_method():
142
+ st.header("Choose Response Synthesis Method")
143
+ response_modes = [
144
+ "refine",
145
+ "tree_summarize",
146
+ "compact",
147
+ "simple_summarize",
148
+ "accumulate",
149
+ "compact_accumulate"
150
+ ]
151
+ selected_mode = st.selectbox("Select Response Mode", response_modes, on_change=reset_pipeline_generated)
152
+ response_mode = selected_mode
153
+ return response_mode, selected_mode
154
+
155
+ def select_vector_store():
156
+ st.header("Choose Vector Store")
157
+ vector_stores = ["Simple", "Pinecone", "Qdrant"]
158
+ selected_store = st.selectbox("Select Vector Store", vector_stores, on_change=reset_pipeline_generated)
159
+
160
+ vector_store = None
161
+
162
+ if selected_store == "Pinecone":
163
+ pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
164
+ index = pc.Index("test")
165
+ vector_store = PineconeVectorStore(pinecone_index=index)
166
+
167
+
168
+ elif selected_store == "Qdrant":
169
+ client = qdrant_client.QdrantClient(location=":memory:")
170
+ vector_store = QdrantVectorStore(client=client, collection_name="sampledata")
171
+ st.write(selected_store)
172
+ return vector_store, selected_store
173
+
174
+ def generate_rag_pipeline(file, llm, embed_model, node_parser, response_mode, vector_store):
175
+ if vector_store is not None:
176
+ # Set storage context if vector_store is not None
177
+ storage_context = StorageContext.from_defaults(vector_store=vector_store)
178
+ else:
179
+ storage_context = None
180
+
181
+ # Create the service context
182
+ service_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model, node_parser=node_parser)
183
+
184
+ # Create the vector index
185
+ vector_index = VectorStoreIndex.from_documents(documents=file, storage_context=storage_context, service_context=service_context, show_progress=True)
186
+ if storage_context:
187
+ vector_index.storage_context.persist(persist_dir="persist_dir")
188
+
189
+ # Create the query engine
190
+ query_engine = vector_index.as_query_engine(
191
+ response_mode=response_mode,
192
+ verbose=True,
193
+ )
194
+
195
+ return query_engine
196
+
197
+ def send_query():
198
+ query = st.session_state['query']
199
+ response = f"Response for the query: {query}"
200
+ st.markdown(response)
201
+
202
+ def generate_code_snippet(llm_choice, embed_model_choice, node_parser_choice, response_mode, vector_store_choice):
203
+ node_parser_params = st.session_state.get('node_parser_params', {})
204
+ print(node_parser_params)
205
+ code_snippet = "from llama_index.llms import OpenAI, Gemini, Cohere\n"
206
+ code_snippet += "from llama_index.embeddings import HuggingFaceEmbedding\n"
207
+ code_snippet += "from llama_index import ServiceContext, VectorStoreIndex, StorageContext\n"
208
+ code_snippet += "from llama_index.node_parser import SentenceSplitter, CodeSplitter, SemanticSplitterNodeParser, TokenTextSplitter\n"
209
+ code_snippet += "from llama_index.node_parser.file import HTMLNodeParser, JSONNodeParser, MarkdownNodeParser\n"
210
+ code_snippet += "from llama_index.vector_stores import MilvusVectorStore, QdrantVectorStore\n"
211
+ code_snippet += "import qdrant_client\n\n"
212
+
213
+ # LLM initialization
214
+ if llm_choice == "GPT-3.5":
215
+ code_snippet += "llm = OpenAI(temperature=0.1, model='gpt-3.5-turbo-1106')\n"
216
+ elif llm_choice == "GPT-4":
217
+ code_snippet += "llm = OpenAI(temperature=0.1, model='gpt-4-1106-preview')\n"
218
+ elif llm_choice == "Gemini":
219
+ code_snippet += "llm = Gemini(model='models/gemini-pro')\n"
220
+ elif llm_choice == "Cohere":
221
+ code_snippet += "llm = Cohere(model='command', api_key='<YOUR_API_KEY>') # Replace <YOUR_API_KEY> with your actual API key\n"
222
+
223
+ # Embedding model initialization
224
+ code_snippet += f"embed_model = HuggingFaceEmbedding(model_name='{embed_model_choice}')\n\n"
225
+
226
+ # Node parser initialization
227
+ node_parsers = {
228
+ "SentenceSplitter": f"SentenceSplitter(chunk_size={node_parser_params.get('chunk_size', 1024)}, chunk_overlap={node_parser_params.get('chunk_overlap', 20)})",
229
+ "CodeSplitter": f"CodeSplitter(language={node_parser_params.get('language', 'python')}, chunk_lines={node_parser_params.get('chunk_lines', 40)}, chunk_lines_overlap={node_parser_params.get('chunk_lines_overlap', 15)}, max_chars={node_parser_params.get('max_chars', 1500)})",
230
+ "SemanticSplitterNodeParser": f"SemanticSplitterNodeParser(buffer_size={node_parser_params.get('buffer_size', 1)}, breakpoint_percentile_threshold={node_parser_params.get('breakpoint_percentile_threshold', 95)}, embed_model=embed_model)",
231
+ "TokenTextSplitter": f"TokenTextSplitter(chunk_size={node_parser_params.get('chunk_size', 1024)}, chunk_overlap={node_parser_params.get('chunk_overlap', 20)})",
232
+ "HTMLNodeParser": f"HTMLNodeParser(tags={node_parser_params.get('tags', ['p', 'h1'])})",
233
+ "JSONNodeParser": "JSONNodeParser()",
234
+ "MarkdownNodeParser": "MarkdownNodeParser()"
235
+ }
236
+ code_snippet += f"node_parser = {node_parsers[node_parser_choice]}\n\n"
237
+
238
+ # Response mode
239
+ code_snippet += f"response_mode = '{response_mode}'\n\n"
240
+
241
+ # Vector store initialization
242
+ if vector_store_choice == "Faiss":
243
+ code_snippet += "d = 1536\n"
244
+ code_snippet += "faiss_index = faiss.IndexFlatL2(d)\n"
245
+ code_snippet += "vector_store = FaissVectorStore(faiss_index=faiss_index)\n"
246
+ elif vector_store_choice == "Milvus":
247
+ code_snippet += "vector_store = MilvusVectorStore(dim=1536, overwrite=True)\n"
248
+ elif vector_store_choice == "Qdrant":
249
+ code_snippet += "client = qdrant_client.QdrantClient(location=':memory:')\n"
250
+ code_snippet += "vector_store = QdrantVectorStore(client=client, collection_name='sampledata')\n"
251
+ elif vector_store_choice == "Simple":
252
+ code_snippet += "vector_store = None # Simple in-memory vector store selected\n"
253
+
254
+ code_snippet += "\n# Finalizing the RAG pipeline setup\n"
255
+ code_snippet += "if vector_store is not None:\n"
256
+ code_snippet += " storage_context = StorageContext.from_defaults(vector_store=vector_store)\n"
257
+ code_snippet += "else:\n"
258
+ code_snippet += " storage_context = None\n\n"
259
+
260
+ code_snippet += "service_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model, node_parser=node_parser)\n\n"
261
+
262
+ code_snippet += "_file = 'path_to_your_file' # Replace with the path to your file\n"
263
+ code_snippet += "vector_index = VectorStoreIndex.from_documents(documents=_file, storage_context=storage_context, service_context=service_context, show_progress=True)\n"
264
+ code_snippet += "if storage_context:\n"
265
+ code_snippet += " vector_index.storage_context.persist(persist_dir='persist_dir')\n\n"
266
+
267
+ code_snippet += "query_engine = vector_index.as_query_engine(response_mode=response_mode, verbose=True)\n"
268
+
269
+ return code_snippet
270
+
271
+ def main():
272
+ st.title("RAGArch: RAG Pipeline Tester and Code Generator")
273
+ st.markdown("""
274
+ - **Configure and Test RAG Pipelines with Custom Parameters**
275
+ - **Automatically Generate Plug-and-Play Implementation Code Based on Your Configuration**
276
+ """)
277
+
278
+ # Upload file
279
+ file = upload_file()
280
+
281
+ # Select RAG components
282
+ llm, llm_choice = select_llm()
283
+ embed_model, embed_model_choice = select_embedding_model()
284
+
285
+
286
+ node_parser, node_parser_choice = select_node_parser()
287
+ # Process nodes only if a file has been uploaded
288
+ if file is not None:
289
+ if node_parser:
290
+ nodes = node_parser.get_nodes_from_documents(file)
291
+ st.write("First node: ")
292
+ st.code(f"{nodes[0].text}")
293
+
294
+ response_mode, response_mode_choice = select_response_synthesis_method()
295
+ vector_store, vector_store_choice = select_vector_store()
296
+
297
+ # Generate RAG Pipeline Button
298
+ if file is not None:
299
+ if st.button("Generate RAG Pipeline"):
300
+ with st.spinner():
301
+ query_engine = generate_rag_pipeline(file, llm, embed_model, node_parser, response_mode, vector_store)
302
+ st.session_state['query_engine'] = query_engine
303
+ st.session_state['pipeline_generated'] = True
304
+ st.success("RAG Pipeline Generated Successfully!")
305
+ elif file is None:
306
+ st.error('Please upload a file')
307
+
308
+
309
+ # After generating the RAG pipeline
310
+ if st.session_state.get('pipeline_generated', False):
311
+ query = st.text_input("Enter your query", key='query')
312
+ if st.button("Send"):
313
+ if 'query_engine' in st.session_state:
314
+ response = st.session_state['query_engine'].query(query)
315
+ st.markdown(response, unsafe_allow_html=True)
316
+ else:
317
+ st.error("Query engine not initialized. Please generate the RAG pipeline first.")
318
+
319
+ if file and st.button("Generate Code Snippet"):
320
+ code_snippet = generate_code_snippet(llm_choice, embed_model_choice, node_parser_choice, response_mode_choice, vector_store_choice)
321
+ st.code(code_snippet, language='python')
322
+
323
+ if __name__ == "__main__":
324
+ main()