rknl commited on
Commit
28a736c
·
verified ·
1 Parent(s): 3701855

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -0
app.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os,re
2
+ import gradio as gr
3
+ import nest_asyncio
4
+ from langchain import PromptTemplate
5
+ from llama_index.core import StorageContext, load_index_from_storage
6
+ import networkx as nx
7
+ from pyvis.network import Network
8
+ from IPython.display import HTML, Markdown, display
9
+
10
+ nest_asyncio.apply()
11
+
12
+ kg_index_path = "./telcom_full_property_kg_processed_schema/"
13
+ kg_plot_path = kg_index_path+"full_kg.html"
14
+ os.environ["OPENAI_API_KEY"] = ""
15
+
16
+
17
+ index = load_index_from_storage(
18
+ StorageContext.from_defaults(persist_dir="./telcom_full_property_kg_processed_schema")
19
+ )
20
+ query_engine = index.as_query_engine(
21
+ include_text=True,
22
+ similarity_top_k=7,
23
+ )
24
+ retriever = index.as_retriever(
25
+ include_text=True, # include source text, default True
26
+ similarity_top_k=7,
27
+ )
28
+
29
+
30
+ teamplate_prompt_upsell = '''You are a virtual assistant for a telecom company, designed to assist users with their queries and potentially upsell services. Your task is to analyze the customer's data from context, their query, and offer the most appropriate assistance.
31
+
32
+ First, you will be given the customer's data context. This information will help you understand the customer's current plan and usage patterns:
33
+
34
+ When interacting with a customer, you will receive a query with their details like name or phone number.
35
+ <query>
36
+ {QUERY}
37
+ </query>
38
+
39
+ Analyze the query to determine the type of assistance required. Categorize it into one of the following:
40
+ 1. Technical Support
41
+ 2. Billing Inquiry
42
+ 3. Plan Information
43
+ 4. Service Upgrade
44
+ 5. General Inquiry
45
+
46
+ Based on the query type and customer data, provide an appropriate response. Your response should:
47
+ 1. Address the customer's immediate concern
48
+ 2. Be clear and concise
49
+ 3. Use a friendly and causal tone
50
+ 4. Make sure to provide facts and relations for each response
51
+ 5. Use Emojis to engage the customer in conversation
52
+
53
+ If the query presents an opportunity for upselling, consider recommending relevant services or upgrades based on the customer's current plan and usage patterns. However, ensure that your primary focus remains on resolving the customer's initial query.
54
+
55
+ Format your response as follows:
56
+
57
+ <response>
58
+ <query_type>[Categorized query type]</query_type>
59
+ <answer>[Your detailed response addressing the customer's query]</answer>
60
+ <reference>[Provide the reference documents used for generating the response]</reference>
61
+ <facts>[Provide the facts used for generating the response]</facts>
62
+ <upsell_opportunity>[If applicable, provide a brief upsell recommendation]</upsell_opportunity>
63
+ </response>
64
+
65
+ Remember to always prioritize customer satisfaction and only suggest upsells when they genuinely benefit the customer.
66
+ '''
67
+
68
+
69
+
70
+
71
+ def parse_response_with_regex(xml_response):
72
+ # Define regex patterns for each tag
73
+ query_type_pattern = re.compile(r'<query_type>(.*?)</query_type>', re.DOTALL)
74
+ answer_pattern = re.compile(r'<answer>(.*?)</answer>', re.DOTALL)
75
+ reference_pattern = re.compile(r'<reference>(.*?)</reference>', re.DOTALL)
76
+ facts_pattern = re.compile(r'<facts>(.*?)</facts>', re.DOTALL)
77
+ upsell_opportunity_pattern = re.compile(r'<upsell_opportunity>(.*?)</upsell_opportunity>', re.DOTALL)
78
+
79
+ # Extract data using regex
80
+ query_type = query_type_pattern.search(xml_response).group(1).strip()
81
+ answer = answer_pattern.search(xml_response).group(1).strip()
82
+ reference = reference_pattern.search(xml_response).group(1).strip()
83
+ facts = facts_pattern.search(xml_response).group(1).strip()
84
+ upsell_opportunity = upsell_opportunity_pattern.search(xml_response).group(1).strip()
85
+
86
+ # Format the extracted information
87
+ formatted_response = f"""
88
+ ### Query Type
89
+ {query_type}
90
+
91
+ ### Answer
92
+ {answer}
93
+
94
+ ### Reference
95
+ {reference}
96
+
97
+ ### Facts
98
+ {facts}
99
+
100
+ ### Upsell Opportunity
101
+ {upsell_opportunity}
102
+ """
103
+ return formatted_response
104
+
105
+ def extract_pattern_triplet(text):
106
+ # Define the regex pattern to match the desired format
107
+ pattern = re.compile(r'\b\w+\b\s*->\s*\b\w+\b\s*->\s*\b\w+\b')
108
+ # Find all matches in the text
109
+ matches = pattern.findall(text)
110
+ return "\n <br> ".join(matches)
111
+
112
+ def query_tqa(query):
113
+ data = {
114
+ 'QUERY': query
115
+ }
116
+ prompt = PromptTemplate(template=teamplate_prompt_upsell, input_variables=["QUERY"])
117
+ query_ready = prompt.format(**data)
118
+ response = query_engine.query(query_ready)
119
+ nodes = retriever.retrieve(query_ready)
120
+ parsed_resp = parse_response_with_regex(str(response))
121
+
122
+ reference = []
123
+ reference_text = []
124
+ for node in nodes:
125
+ reference.append(extract_pattern_triplet(node.text))
126
+ reference_text.append(node.text)
127
+
128
+ return parsed_resp, response, reference , reference_text
129
+
130
+ def plot_full_kg():
131
+ """Plot the full knowledge graph and return the HTML representation."""
132
+ return HTML(filename=kg_plot_path)
133
+
134
+ with gr.Blocks() as demo:
135
+ gr.Markdown("<h1>Telcom Graph-RAG v0.1</h1>")
136
+
137
+ with gr.Tab("Virtual Assistant"):
138
+ with gr.Row():
139
+ query_input = gr.Textbox(label="Input Your Query..")
140
+ with gr.Row():
141
+ model_output = gr.Textbox(label="Response")
142
+ model_metadata = gr.Textbox(label="Raw Response")
143
+ with gr.Row():
144
+ reference = gr.HTML(label="Extracted Reference")
145
+ reference_text = gr.Textbox(label="Extracted Reference raw")
146
+
147
+
148
+ ask_button = gr.Button("Ask TelcomVA!!")
149
+
150
+ with gr.Accordion("Explore KG!", open=False):
151
+ gr.Markdown("This KG is built using a subset of Github repositories. ")
152
+ kg_output = gr.HTML()
153
+ plot_button = gr.Button("Plot Full KG!!")
154
+
155
+ ask_button.click(query_tqa, inputs=[query_input], outputs=[model_output,model_metadata,reference,reference_text])
156
+ plot_button.click(plot_full_kg, outputs=kg_output)
157
+
158
+ demo.launch(auth=("telcom", "letswin!!"), share=True)