vedsadani commited on
Commit
6039889
1 Parent(s): f645e9a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +220 -54
app.py CHANGED
@@ -1,84 +1,250 @@
1
- from langchain.vectorstores import FAISS
 
 
 
 
2
  from langchain.chains import RetrievalQA
3
- from langchain.llms import HuggingFaceHub
4
  import gradio as gr
5
  import os
6
- from langchain.embeddings import HuggingFaceEmbeddings
7
- from langchain_experimental.agents.agent_toolkits.csv.base import create_csv_agent
8
- from langchain.document_loaders import PyPDFDirectoryLoader
9
  from langchain.document_loaders.csv_loader import CSVLoader
10
  from langchain.text_splitter import RecursiveCharacterTextSplitter
 
11
  import io
12
  import contextlib
 
 
 
13
 
14
-
15
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
16
- vector_store= FAISS.load_local("vector_db/", embeddings)
 
17
 
18
  repo_id="mistralai/Mixtral-8x7B-Instruct-v0.1"
19
- llm = HuggingFaceHub(repo_id=repo_id, model_kwargs={"temperature": 0.01, "max_new_tokens": 2048})
 
 
 
 
 
 
 
20
 
21
  retriever = vector_store.as_retriever(
22
  search_type="similarity",
23
- search_kwargs={"k":3, "include_metadata": True})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- agent=create_csv_agent(llm,['data/Gretel_Data.csv','data/RAN_Data _T.csv'],verbose=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  def echo(message, history):
28
  try:
29
- qa=RetrievalQA.from_chain_type(llm=llm, retriever=retriever,return_source_documents=True)
30
- message= "Your name is Clara. You are a senior telecom network engineer having access to troubleshooting tickets data and other technical and product documentation.Stick to the knowledge from these tickets. Ask clarification questions if needed. "+message
31
- result=qa({"query":message})
32
- bold_answer= "<b>" + result['result'] + "</b>"
33
- return bold_answer + "<br></br>" +'1. ' + str(result["source_documents"][0]) +"<br>" + '2. ' + str(result["source_documents"][1]) + "<br>" + "3. " + str(result["source_documents"][2])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  except Exception as e:
35
  error_message = f"An error occurred: {e}"+str(e.with_traceback) + str(e.args)
 
36
 
37
  def echo_agent(message, history):
38
- message="There are 2 df's. If you find a KeyError check for the same in the other df." + "<br>" + message
39
  try:
40
- with io.StringIO() as buffer:
41
- with contextlib.redirect_stdout(buffer):
42
- result= agent.run(message)
43
- verbose_output = buffer.getvalue()
44
- verbose_output = verbose_output.replace("\x1b[36;1m\x1b[1;3m", "")
45
- verbose_output = verbose_output.replace("> ", "")
46
- verbose_output = verbose_output.replace("", "")
47
- verbose_output = verbose_output.replace("", "")
48
- result= "<b>" + verbose_output + "<br>" + result + "</b>"
49
- return result
50
  except Exception as e:
51
  error_message = f"An error occurred: {e}"+str(e.with_traceback) + str(e.args)
52
  return error_message
53
 
54
- demo=gr.ChatInterface(
55
- fn=echo,
56
- chatbot=gr.Chatbot(height=300, label="Hi I am Clara!", show_label=True),
57
- textbox=gr.Textbox(placeholder="Ask me a question", container=True, autofocus=True, scale=7),
58
  title="Network Ticket Knowledge Management",
59
- description="<span style='font-size: 16x;'>Welcome to Verizon Network Operations Center!! I am here to help the Verizon Field Operations team with technical queries & escalation. I am trained on 1000s of RAN, Backhaul, Core network & End user equipment trouble tickets. Ask me!!!&nbsp;☺</span>",
60
- theme=gr.themes.Soft(),
61
- examples=["wifi connected but no internet showing", "internet stopped working after primary link down", "internet stopped working link not shifted to secondary after primary link down"],
62
- cache_examples=False,
63
- retry_btn=None,
64
- undo_btn="Delete Previous",
65
- clear_btn="Clear",
66
- stop_btn="Stop",
67
- )
68
-
69
-
70
- demo1=gr.ChatInterface(
71
- fn=echo_agent,
72
- chatbot=gr.Chatbot(height=300, label="Hi I am Sam!", show_label=True),
73
- textbox=gr.Textbox(placeholder="Ask me a question", container=True, autofocus=True, scale=7),
74
- title="LLM Powered Agent",
75
- description="<span style='font-size: 16x;'>Welcome to Verizon RAN Visualization & Analytics powered by GEN AI. I have access 100 of metrices generated by a RAN base station and can help in visualizing, correlating and generating insights, using power of Conversational AI &nbsp;☺</span>",
76
  theme=gr.themes.Soft(),
77
- retry_btn=None,
78
- undo_btn="Delete Previous",
79
- clear_btn="Clear",
80
- stop_btn="Stop",
81
- )
82
- demo2=gr.TabbedInterface([demo,demo1],["RAG","AGENT"], title='INCEDO', theme=gr.themes.Soft())
83
- demo2.launch(share=True,debug=True,auth=("admin", "Sam&Clara"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
 
 
1
+ from langchain_community.vectorstores import FAISS
2
+ from langchain_community.embeddings import HuggingFaceEmbeddings
3
+ from langchain_community.document_loaders import PyPDFDirectoryLoader
4
+ from langchain_community.llms import HuggingFaceEndpoint
5
+ from langchain.chains import ConversationalRetrievalChain
6
  from langchain.chains import RetrievalQA
 
7
  import gradio as gr
8
  import os
9
+ from pandasai import Agent
 
 
10
  from langchain.document_loaders.csv_loader import CSVLoader
11
  from langchain.text_splitter import RecursiveCharacterTextSplitter
12
+ from langchain.memory import ConversationSummaryBufferMemory
13
  import io
14
  import contextlib
15
+ import re
16
+ import pandas as pd
17
+ from transformers import AutoConfig
18
 
19
+ config = AutoConfig.from_pretrained("config.json")
20
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
21
+ config = AutoConfig.from_pretrained("config.json")
22
+ vector_store= FAISS.load_local("vector_db/", embeddings, allow_dangerous_deserialization=True)
23
 
24
  repo_id="mistralai/Mixtral-8x7B-Instruct-v0.1"
25
+
26
+ llm = HuggingFaceEndpoint(
27
+ repo_id = repo_id,
28
+ temperature = 0.01,
29
+ max_new_tokens = 4096,
30
+ verbose = True,
31
+ return_full_text = False
32
+ )
33
 
34
  retriever = vector_store.as_retriever(
35
  search_type="similarity",
36
+ search_kwargs={"k":5}
37
+ )
38
+
39
+ df=pd.read_csv('data/Gretel_Data.csv')
40
+ averages = df.mean(numeric_only=True).to_dict()
41
+
42
+ agent = Agent([df], config={"llm": llm, 'verbose':True})
43
+
44
+ global unique_columns
45
+ unique_columns = [
46
+ 'Avg_Connected_UEs',
47
+ 'PRB Util%',
48
+ 'CA Activation Rate',
49
+ 'DLRLCLayerDataVolume MB',
50
+ 'DRB UL Data Volume MB',
51
+ 'UPTP_Mbps',
52
+ 'UPTP Mbps Num',
53
+ 'UPTP Mbps Den',
54
+ 'UL MAC Vol Scell Pct',
55
+ 'DL MAC Vol Scell Pct',
56
+ 'DL MAC Vol Scell MB',
57
+ 'DL Volume',
58
+ 'DL Data Vol MAC in MB',
59
+ 'UL Throughput',
60
+ 'MB_per_connected_UE'
61
+ ]
62
+
63
+ global target_words
64
+ target_words = ["Bandwidth", "Interference", "Call Quality", "Network", "Handover"]
65
+
66
+ columns = []
67
 
68
+ column_avgs = {}
69
+
70
+ global network_features
71
+ network_features = {
72
+ 'Bandwidth': [
73
+ 'Avg_Connected_UEs',
74
+ 'PRB Util%',
75
+ 'CA Activation Rate',
76
+ 'DLRLCLayerDataVolume MB',
77
+ 'DRB UL Data Volume MB',
78
+ 'UPTP_Mbps',
79
+ 'UPTP Mbps Num',
80
+ 'UPTP Mbps Den',
81
+ 'UL MAC Vol Scell Pct',
82
+ 'DL MAC Vol Scell Pct',
83
+ 'DL MAC Vol Scell MB',
84
+ 'DL Volume',
85
+ 'DL Data Vol MAC in MB',
86
+ 'UL Throughput',
87
+ 'MB_per_connected_UE'
88
+ ],
89
+ 'Handover': [
90
+ 'Avg_Connected_UEs',
91
+ 'PRB Util%',
92
+ 'CA Activation Rate',
93
+ 'HO Failures',
94
+ 'HO_fail_InterFreq',
95
+ 'HO_fail_PCT_InterFreq',
96
+ 'HO Failure%',
97
+ 'HO Attempts',
98
+ 'HO_att_InterFreq'
99
+ ],
100
+ 'Network': [
101
+ 'Avg_Connected_UEs',
102
+ 'PRB Util%',
103
+ 'CA Activation Rate',
104
+ 'SIP DC%',
105
+ 'RRC Setup Attempts',
106
+ 'RRC Setup Failures',
107
+ 'RRC Setup Failure% 5G',
108
+ 'Combined RACH Failure%',
109
+ 'Combined RACH Preambles',
110
+ 'Combined RACH Failures',
111
+ 'Interference Pwr',
112
+ ],
113
+ 'Call Quality': [
114
+ 'Avg_Connected_UEs',
115
+ 'PRB Util%',
116
+ 'CA Activation Rate',
117
+ 'Avg_PUCCH_SINR',
118
+ 'Avg CQI',
119
+ 'SIP Calls with a Leg',
120
+ 'SIP_SC_Total_MOU',
121
+ 'SIP Dropped Calls',
122
+ 'VoLTE_MOU',
123
+ 'QCI 1 Bearer Drops',
124
+ 'QCI 1 Bearer Releases',
125
+ 'QCI 1 Bearer Drop%',
126
+ 'Peak UE',
127
+ 'DL Packet Loss Pct',
128
+ 'UL Resid BLER PCT',
129
+ 'Bearer Drops Voice',
130
+ 'Bearer Releases Voice',
131
+ 'Bearer Drop%',
132
+ 'Call_Drops_Credit'
133
+ ],
134
+ 'Interference': [
135
+ 'Avg_Connected_UEs',
136
+ 'PRB Util%',
137
+ 'CA Activation Rate',
138
+ 'Combined RACH Failure%',
139
+ 'Interference Pwr'
140
+ ]
141
+ }
142
 
143
  def echo(message, history):
144
  try:
145
+ qa=RetrievalQA.from_chain_type(llm=llm, retriever=retriever, return_source_documents=True)
146
+ message= " <s> [INST] You are a senior telecom network engineer having access to troubleshooting tickets data and other technical and product documentation. Stick to the knowledge provided. Search through the product documentation pdfs first before scanning the tickets to generate the answer. Return only the helpful answer. Question:" + message + '[/INST]'
147
+ result= qa({"query":message})
148
+ answer= result['result']
149
+ for word in target_words:
150
+ if re.search(r'\b' + re.escape(word) + r'\b', answer, flags=re.IGNORECASE):
151
+ columns.extend(network_features.get(word, []))
152
+ unique_columns = list(set(columns))
153
+
154
+ for column in unique_columns:
155
+ column_avgs.update({column:averages.get(column, [])})
156
+
157
+ result_df = df[unique_columns].iloc[:25]
158
+
159
+ def highlight_rows(val, threshold):
160
+ if val > threshold:
161
+ return 'color: red; font-weight: bold'
162
+ elif val < threshold:
163
+ return 'color: green'
164
+ else:
165
+ return ''
166
+
167
+ styled_df = result_df.style
168
+
169
+ for key in column_avgs:
170
+ styled_df = styled_df.applymap(lambda x, k=key: highlight_rows(x, column_avgs[k]), subset=[f'{key}'])
171
+
172
+ gr.Dataframe(styled_df)
173
+ return (
174
+ "Answer: \n"
175
+ + '\n' + answer.strip() + '\n'
176
+ + '\n' + "Sources: \n"
177
+ + '\n' + '1. ' + result['source_documents'][0].metadata['source'] + '\n' + result['source_documents'][0].page_content + "\n"
178
+ + '\n' + '2. ' + result['source_documents'][1].metadata['source'] + '\n' + result['source_documents'][1].page_content + "\n"
179
+ + '\n' + "3. " + result['source_documents'][2].metadata['source'] + '\n' + result['source_documents'][2].page_content + "\n"
180
+ + '\n' + "4. " + result['source_documents'][3].metadata['source'] + '\n' + result['source_documents'][3].page_content + "\n"
181
+ + '\n' + "5. " + result['source_documents'][4].metadata['source'] + '\n' + result['source_documents'][4].page_content + "\n",
182
+ styled_df
183
+ )
184
  except Exception as e:
185
  error_message = f"An error occurred: {e}"+str(e.with_traceback) + str(e.args)
186
+ return error_message, error_message
187
 
188
  def echo_agent(message, history):
 
189
  try:
190
+ response = agent.chat(message, output_type= 'text')
191
+ # explanation = agent.explain()
192
+
193
+ # result = "Answer: \n" + '\n' + response.str() + '\n' + '\n' + "Explanation: \n" + '\n' + explanation
194
+
195
+ return response
 
 
 
 
196
  except Exception as e:
197
  error_message = f"An error occurred: {e}"+str(e.with_traceback) + str(e.args)
198
  return error_message
199
 
200
+ demo_agent = gr.Blocks(
 
 
 
201
  title="Network Ticket Knowledge Management",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  theme=gr.themes.Soft(),
203
+ )
204
+
205
+ with demo_agent:
206
+
207
+ gr.Markdown(
208
+ '''
209
+ # <p style="text-align: center;">Network Ticket Knowledge Management</p>
210
+ Welcome to Verizon Network Operations Center. I am here to help the Field Operations team with technical queries & escalation.
211
+ '''
212
+ )
213
+
214
+ with gr.Tab('Clara'):
215
+ with gr.Row():
216
+ message = gr.Text(label="Input Query")
217
+
218
+ btn = gr.Button("Submit")
219
+
220
+ with gr.Row():
221
+ reply = gr.Text(label="RCA and MoP", autoscroll=False)
222
+
223
+ with gr.Accordion(label = "Metrics", open=False):
224
+ table = gr.Dataframe()
225
+
226
+ btn.click(echo, inputs=[message], outputs=[reply, table])
227
+
228
+ gr.Examples([
229
+ "Wi-Fi connected but no internet showing",
230
+ 'What are the possible cause of router overheating ?',
231
+ "What are the possible causes of RAN getting disconnected frequently?",
232
+ "For the past week, are there any specific cell towers in Texas experiencing unusually high call failure rates or data latency?",
233
+ "What are the network problems faced by people living in the state of California?",
234
+ "I have an FWA connection and all devices except my iPhone have internet access via this FWA device. Can you suggest steps for resolution?",
235
+ "We're receiving reports of congested cell towers in Cleveland. Can you identify the specific cell towers experiencing overload and suggest any temporary network adjustments to alleviate the congestion?"
236
+ ],
237
+ inputs=[message]
238
+ )
239
+
240
+ with gr.Tab('Sam'):
241
+ with gr.Row():
242
+ message_agent = gr.Text(label="Input Query")
243
+ with gr.Row():
244
+ reply_agent = gr.Text(label="Answer")
245
+
246
+ btn2 = gr.Button("Submit")
247
+ btn2.click(echo_agent, inputs=[message_agent], outputs=[reply_agent])
248
+
249
 
250
+ demo_agent.launch(share=True,debug=True,auth=("admin", "Sam&Clara"))