meln1337 commited on
Commit
84ee008
·
1 Parent(s): 3645cf5

Add application file

Browse files
Files changed (4) hide show
  1. Dockerfile +16 -0
  2. rag_lchain.py +255 -0
  3. requirements.txt +0 -0
  4. sparse_encoder.json +0 -0
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12
2
+
3
+ WORKDIR /APP
4
+
5
+ COPY requirements.txt .
6
+ COPY sparse_encoder.json .
7
+ COPY README.md .
8
+ RUN pip install --no-cache-dir -r requirements.txt
9
+
10
+ COPY rag_lchain.py .
11
+
12
+ EXPOSE 7860
13
+
14
+ ENV GRADIO_SERVER_NAME="0.0.0.0"
15
+
16
+ CMD ["python", "rag_lchain.py"]
rag_lchain.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_groq import ChatGroq
2
+ from langchain_core.messages import HumanMessage, ToolMessage, SystemMessage, AIMessage
3
+ import torch
4
+ import gradio as gr
5
+ import sys
6
+ from pinecone.grpc import PineconeGRPC as Pinecone
7
+ from langchain_community.cross_encoders import HuggingFaceCrossEncoder
8
+ from langchain.retrievers.document_compressors import CrossEncoderReranker
9
+ from langchain.retrievers import ContextualCompressionRetriever
10
+ from pinecone_text.sparse import BM25Encoder
11
+ from langchain_huggingface import HuggingFaceEmbeddings
12
+ from langchain_community.retrievers import PineconeHybridSearchRetriever
13
+
14
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
15
+
16
+ print(f"Device: {device}")
17
+
18
+ bm25 = BM25Encoder().load("sparse_encoder.json")
19
+ embedding = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
20
+ print('Pulled embedding model')
21
+ bge_reranker = HuggingFaceCrossEncoder(model_name="BAAI/bge-reranker-base")
22
+ print('Pulled cross-encoder model')
23
+ compressor = CrossEncoderReranker(model=bge_reranker, top_n=3)
24
+
25
+ system_prompt = """\
26
+ You are an intelligent assistant designed to provide accurate and relevant answers based on the provided context.
27
+
28
+ Rules:
29
+ - Always analyze the provided context thoroughly before answering.
30
+ - Respond with factual and concise information.
31
+ - If context is ambiguous or insufficient or you can't find answer, say 'I don't know.'
32
+ - Do not speculate or fabricate information beyond the provided context.
33
+ - Follow user instructions on the response style(default style is detailed response if user didn't provide any specifications):
34
+ - If the user asks for a detailed response, provide comprehensive explanations.
35
+ - If the user requests brevity, give concise and to-the-point answers.
36
+ - When applicable, summarize and synthesize information from the context to answer effectively.
37
+ - Avoid using information outside the given context.
38
+ """
39
+
40
+ class QABot:
41
+ def __init__(self, retriever):
42
+ self.retriever = retriever
43
+
44
+ def set_retriever(self, retriever):
45
+ self.retriever = retriever
46
+
47
+ def answer_question(self, question):
48
+ if len(bm25.encode_queries(question)['values']) == 0:
49
+ return "BM25 embedded this query as an empty list, please use other query"
50
+
51
+ self.chat = [
52
+ SystemMessage(
53
+ system_prompt
54
+ )
55
+ ]
56
+ results = self.retriever.invoke(question)
57
+
58
+ for i, match in enumerate(results[:1]):
59
+ print(f'\n\nMatch: {i}\n:{match}')
60
+
61
+ context = '\n'.join([el.page_content for el in results[:1]])
62
+
63
+ self.chat.append(
64
+ SystemMessage(f"""
65
+ Context information is below.
66
+ ---------------------
67
+ {context}
68
+ ---------------------
69
+ Given the context information and not prior knowledge, answer the query.
70
+ """
71
+ )
72
+ )
73
+
74
+ self.chat.append(
75
+ HumanMessage(question)
76
+ )
77
+
78
+ answer = llm.invoke(self.chat)
79
+
80
+ answer.content += f"\n\nSource: [{results[0].metadata['source']}]"
81
+ answer.content += f"\nChunks before reranking: [{', '.join([f'{idx + 1}. {results[idx].metadata['id']}' for idx in range(len(results))])}]"""
82
+ answer.content += f"\nChunks after reranking: [{results[0].metadata['id']}]\n"
83
+
84
+ if 'url' in results[0].metadata:
85
+ answer.content += f"URL: {results[0].metadata['url']}"
86
+
87
+ print(f'\n\nAnswer: {answer}\n\n')
88
+
89
+ self.chat.append(
90
+ AIMessage(answer.content)
91
+ )
92
+
93
+ print(f"Length of chat after answering: {len(self.chat)}")
94
+
95
+ return answer.content
96
+
97
+ pinecone_client = None
98
+ groq_client = None
99
+ pc = None
100
+ hybrid_compression_retriever = None
101
+ dense_compression_retriever = None
102
+ sparse_compression_retriever = None
103
+ llm = None
104
+ bot = None
105
+
106
+ def initialize_clients(pinecone_key, groq_key):
107
+ global bot, pinecone_client, groq_client, pc, hybrid_compression_retriever, dense_compression_retriever, sparse_compression_retriever, llm
108
+
109
+ try:
110
+ # Initialize Pinecone client
111
+
112
+ pc = Pinecone(api_key=pinecone_key)
113
+ index_name = "rag-llm"
114
+ namespace = "embedded-texts"
115
+ index = pc.Index(index_name)
116
+
117
+ hybrid_vector_store = PineconeHybridSearchRetriever(
118
+ index=index,
119
+ embeddings=embedding,
120
+ sparse_encoder=bm25,
121
+ namespace=namespace,
122
+ top_k=3,
123
+ alpha=0.7
124
+ )
125
+
126
+ hybrid_compression_retriever = ContextualCompressionRetriever(
127
+ base_compressor=compressor, base_retriever=hybrid_vector_store
128
+ )
129
+
130
+ dense_vector_store = PineconeHybridSearchRetriever(
131
+ index=index,
132
+ embeddings=embedding,
133
+ sparse_encoder=bm25,
134
+ namespace=namespace,
135
+ top_k=3,
136
+ alpha=1
137
+ )
138
+
139
+ dense_compression_retriever = ContextualCompressionRetriever(
140
+ base_compressor=compressor, base_retriever=dense_vector_store
141
+ )
142
+
143
+ sparse_vector_store = PineconeHybridSearchRetriever(
144
+ index=index,
145
+ embeddings=embedding,
146
+ sparse_encoder=bm25,
147
+ namespace=namespace,
148
+ top_k=3,
149
+ alpha=0
150
+ )
151
+
152
+ sparse_compression_retriever = ContextualCompressionRetriever(
153
+ base_compressor=compressor, base_retriever=sparse_vector_store
154
+ )
155
+
156
+ llm = ChatGroq(temperature=1, model_name="llama3-8b-8192",
157
+ groq_api_key=groq_key)
158
+
159
+ print('Connected to Groq API Provider of LLaMA')
160
+
161
+ bot = QABot(retriever=hybrid_compression_retriever)
162
+
163
+ # Initialize Groq client (replace with actual initialization code)
164
+ # groq_client = groq.Client(api_key=groq_key) # Replace with actual Groq initialization
165
+
166
+ return "Clients initialized successfully!"
167
+ except Exception as e:
168
+ return f"Error initializing clients: {e}"
169
+
170
+ def response(mode, message):
171
+ try:
172
+ if message == "/exit":
173
+ gr.close_all()
174
+ print('Finishing the program')
175
+ sys.exit(0)
176
+
177
+ # Set retriever based on mode
178
+ if mode == "Hybrid":
179
+ bot.set_retriever(hybrid_compression_retriever)
180
+ elif mode == "Dense":
181
+ bot.set_retriever(dense_compression_retriever)
182
+ elif mode == "Sparse":
183
+ bot.set_retriever(sparse_compression_retriever)
184
+
185
+ answer = bot.answer_question(message)
186
+ return answer
187
+ except Exception as e:
188
+ return str(e)
189
+
190
+ if __name__ == '__main__':
191
+ def check_inputs(pinecone_key, groq_key, mode, input_text):
192
+ return bool(pinecone_key and groq_key and mode and input_text)
193
+
194
+
195
+ with gr.Blocks(title="Music-based RAG Application") as app:
196
+ gr.Markdown("# Music-based RAG application based on LLaMa, Langchain, Pinecone")
197
+ gr.Markdown(
198
+ "Welcome to my RAG application that specializes in music. More precisely, on some of the artists I talked about on the Genius website: https://genius.com/. I scrapped their website and extracted info about artist and their most popular songs (maximum 100).")
199
+ gr.Markdown("""
200
+ - List of 48 available artists:\n
201
+ - Nu-metal: Deftones, Linkin Park, Korn, Slipknot, System of A Down, Limp Bizkit\n
202
+ - Shoegaze: Superheaven, Slowdive, Sunny Day Real Estate, Title Fight\n
203
+ - Punk rock: Blink 182, Sum 41, DUCKBOY\n
204
+ - Rap: Bones, A$AP Rocky, Travis Scott, Lil Uzi Vert, Future, $uicideboy$, Yeat, Playboi Carti, Kanye West, Lil Peep, Kendrick Lamar, 21 Savage, Destroy Lonely, Ken Carson, Bladee, Yung Lean, J. Cole, Eminem, Young Thug, Gunna\n
205
+ - Electronic music: Crystal Castles, Snow Strippers\n
206
+ - Other: Nirvana, Bring Me The Horizon, Misfits, The Smiths, Evanescence, Twin Tribes, TOOL, Metallica, Joy Division, Lebanon Hanover, The Cure, Marilyn Manson, The Weeknd
207
+ """)
208
+ gr.Markdown(
209
+ "Feel free to ask question! My project is described in more detail in my GitHub repository: https://github.com/meln1337/music-rag")
210
+
211
+ gr.Markdown("""
212
+ - Examples of questions:\n
213
+ - Who is rapper Bones?\n
214
+ - What are the alternate names of Bones?
215
+ """)
216
+
217
+ with gr.Row():
218
+ pinecone_key = gr.Textbox(label="Pinecone API Key", placeholder="Enter your Pinecone API key here")
219
+ groq_key = gr.Textbox(label="Groq API Key", placeholder="Enter your Groq API key here")
220
+ init_button = gr.Button("Submit API Keys")
221
+ output_api_keys = gr.Textbox(label="Output API keys", lines=4, interactive=False)
222
+
223
+ mode = gr.Radio(
224
+ value="Hybrid",
225
+ choices=["Dense", "Sparse", "Hybrid"],
226
+ label="Select Retriever Mode",
227
+ )
228
+
229
+ input_text = gr.Textbox(label="Input Text", placeholder="Enter your text here", lines=2)
230
+ output = gr.Textbox(label="Output", lines=4, interactive=False)
231
+ submit_button = gr.Button("Submit Query", interactive=False)
232
+
233
+ # Link initialization button to client setup
234
+ init_button.click(
235
+ initialize_clients,
236
+ inputs=[pinecone_key, groq_key],
237
+ outputs=output_api_keys
238
+ )
239
+
240
+
241
+ # Enable the submit button only after initialization
242
+ def enable_submit_button():
243
+ return gr.update(interactive=True)
244
+
245
+
246
+ init_button.click(enable_submit_button, outputs=submit_button)
247
+
248
+ # Link query submission to response
249
+ submit_button.click(
250
+ response,
251
+ inputs=[mode, input_text],
252
+ outputs=output
253
+ )
254
+
255
+ app.launch()
requirements.txt ADDED
Binary file (7.88 kB). View file
 
sparse_encoder.json ADDED
The diff for this file is too large to render. See raw diff