File size: 12,332 Bytes
191a7c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# from flask import Flask, request, jsonify, render_template
# from flask_cors import CORS

import gradio as gr
import random
import time
import openai
from langchain.chains.summarize import load_summarize_chain
import os
import json
from pprint import pprint
import pinecone
import time
from langchain.chat_models import AzureChatOpenAI
from langchain.vectorstores import Pinecone
from langchain.chains import RetrievalQA, LLMChain
from langchain.memory import ConversationBufferWindowMemory
from typing import Optional
import pandas as pd
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts import PromptTemplate
from Utility_New import MasterLLM, intent_recognition, entity_recognition_main, describe, compare, RAG, sentiment

openai.api_type = "azure"
openai.api_base = "https://di-sandbox-gpt4.openai.azure.com/"
openai.api_version = "2023-07-01-preview"
openai.api_key = "69ec3919a7314784be9c4f7414286fba"


os.environ['OPENAI_API_KEY']=openai.api_key
os.environ['OPENAI_API_BASE'] = openai.api_base
os.environ['OPENAI_API_VERSION'] = openai.api_version
os.environ['OPENAI_API_TYPE'] = openai.api_type

#Pinecone - Statements
PINECONE_API_KEY = '98bbd113-f65a-403b-b44f-507e60506d46'

pinecone.init(
    api_key=os.environ.get('PINECONE_API_KEY') or '98bbd113-f65a-403b-b44f-507e60506d46',
    environment=os.environ.get('PINECONE_ENVIRONMENT') or 'gcp-starter'
)

#Pinecone - JSON (orig)
# PINECONE_API_KEY = '49e9d57f-ca7b-45d8-9fe5-b02db54b2dc7'

# pinecone.init(
#     api_key=os.environ.get('PINECONE_API_KEY') or '49e9d57f-ca7b-45d8-9fe5-b02db54b2dc7',
#     environment=os.environ.get('PINECONE_ENVIRONMENT') or 'gcp-starter'
# )


index_name = 'rag-sbc'

embedding_model = OpenAIEmbeddings(openai_api_key = os.environ.get('OPENAI_API_KEY'), 
                              deployment="text-embedding-ada-002",
                              model="text-embedding-ada-002",
                              openai_api_base=os.environ.get('OPENAI_API_BASE'),
                              openai_api_type=os.environ.get('OPENAI_API_TYPE'))
    

index = pinecone.Index(index_name)

vectorstore = Pinecone(index, embedding_model.embed_query, 'text')


llm = AzureChatOpenAI(deployment_name = "GPT4_32k", model_name = "gpt-4-32k", temperature=0)

llm_35 = AzureChatOpenAI(deployment_name = "GPT_35_16k", model_name = "gpt-35-turbo-16k", temperature=0)

conversational_memory = ConversationBufferWindowMemory(
    memory_key='chat_history',
    k=10,
    return_messages=True)

session_memory = {}
entities = {}

# Latest data - SBC_Final_License_Level_Data.csv

# OLD JSON
# data = pd.read_csv('Combined_data_SBC.csv')

# Latest Summarized Data - New JSON
data = pd.read_csv('SBC_Final_License_Level_Data.csv')

data.drop(columns=['ID'],inplace=True)
# result = {}
# for main_key, group_df in data.groupby('License Name'):
#     group_dict = group_df.to_dict(orient='records')
#     result[main_key] = group_dict

# json_result = json.dumps(result, indent=2)
# json_result = json_result.replace("\\n","")
# json_result = json_result.replace("\\u2002","")
# json_result = json_result.replace("\n","")
# json_result = json_result.replace("/","")

data = data.applymap(lambda x: x.strip() if isinstance(x, str) else x)
LicenseName = data['License Name'].to_list()
#License_Service = data.groupby('License Name')['Service Name'].apply(list).reset_index(name='Service Name')

def final_output(UserPrompt):
    final_json = {}
    
    intent = intent_recognition(UserPrompt)
    # if intent!='Compare':
    #     intent = "Others"

    print('Intent')
    print(intent)
    print()
    
    oldPrompt = UserPrompt
    
    if len(list(entities.keys())) == 0:
        PrevEntity = []
    else:
        PrevEntity = entities[list(entities.keys())[-1]]
    
    Prev_Entity = [i.strip() for i in PrevEntity]
    Prev_Entity = list(set(Prev_Entity))
    print('Prev_Entity')
    print(Prev_Entity)
    print()
    
    if len(session_memory) > 0:
        lastUserPrompt = list(session_memory.keys())[-1]
        # lastUserPrompt = [i.strip() for i in lastUserPrompt]
        lastOutput = session_memory[lastUserPrompt]
        # lastOutput = [i.strip() for i in lastOutput]
    
    else:
        lastUserPrompt = ""
        lastOutput = ""


    print("Last User Prompt")
    print(lastUserPrompt)
    print("Last Output")
    print(lastOutput)
    
    
    UserPrompt, Prev_Entity = sentiment(UserPrompt, Prev_Entity, lastUserPrompt, lastOutput)
           
    print('New Prev Entity')
    print(Prev_Entity)
      
    print('UserPrompt')
    print(UserPrompt)
    print()

    entity_main = entity_recognition_main(UserPrompt, LicenseName)
    entity_main = list(set(entity_main))
    print('Main Entity')
    print(entity_main)
    print()
    
    entities[oldPrompt] = entity_main
    
    for i in Prev_Entity:
        entity_main.append(i)
        
    entity  = entity_main
    entity = list(set(entity))
    print('Full Entity')
    print(entity)
    print()

    # try:
    #     json_data = json.loads(json_result)
    #     filtered_data = {key: json_data[key] for key in entity}
    #     filtered_json = json.dumps(filtered_data, indent=2)
    #     final_json = json.loads(filtered_json)
    # except:
    #     final_json = {}
    
    try:
        filtered_data = data[data['License Name'].isin(entity)]
        filtered_data.drop(columns=["Extra Details"],inplace=True)
        filtered_data_dict = filtered_data.to_dict(orient='records')
        
    except:
        filtered_data_dict = {}
    
    c = 0

    if intent in ['Transfer']:
        print(intent)
        print()
        output = "I have shared our last conversation on your WhatsApp" 
        return output, intent
               
    elif len(entity)>0: 
        for i in entity:
            if i in LicenseName:
                c+=1

        if c > 0 and c == len(entity):
            if intent in ['Describe'] and len(entity) > 0:
                print('Describe')
                prompt, prompt_template = describe(entity, filtered_data_dict, UserPrompt)
                if len(entity) <=3:
                    chain = LLMChain(llm=llm_35, prompt=prompt_template,memory = conversational_memory)
                else:
                    chain = LLMChain(llm=llm_35, prompt=prompt_template,memory = conversational_memory)
                output = chain({'context':prompt})['text']
                print(output)

            elif intent in ['Compare'] and len(entity) > 0:
                print('Compare')
                prompt,prompt_template = compare(entity, filtered_data_dict, UserPrompt)
                if len(entity) <=3:
                    chain = LLMChain(llm=llm_35, prompt=prompt_template,memory = conversational_memory)
                else:
                    chain = LLMChain(llm=llm_35, prompt=prompt_template,memory = conversational_memory)
                output = chain({'context':prompt})['text']
                print(output)
            else:
                print("RAG1")
                prompt = RAG(UserPrompt,entity)
                if len(entity) <=3:
                    qa = RetrievalQA.from_chain_type(llm=llm_35,
                    chain_type="stuff",
                    retriever=vectorstore.as_retriever(),
                    memory = conversational_memory)
                else:
                    qa = RetrievalQA.from_chain_type(llm=llm_35,
                    chain_type="stuff",
                    retriever=vectorstore.as_retriever(),
                    memory = conversational_memory)
                output = qa.run(prompt)
                print(output)


        else:
            print("RAG2")
            prompt = RAG(UserPrompt,entity)
            if len(entity) <=3:
                    qa = RetrievalQA.from_chain_type(llm=llm_35,
                    chain_type="stuff",
                    retriever=vectorstore.as_retriever(),
                    memory = conversational_memory)
            else:
                qa = RetrievalQA.from_chain_type(llm=llm,
                chain_type="stuff",
                retriever=vectorstore.as_retriever(),
                memory = conversational_memory)
            output = qa.run(prompt)
            print(output)
    else:
        print("RAG1")
        prompt = RAG(UserPrompt,entity)
        if len(entity) <=3:
                    qa = RetrievalQA.from_chain_type(llm=llm_35,
                    chain_type="stuff",
                    retriever=vectorstore.as_retriever(),
                    memory = conversational_memory)
        else:
            qa = RetrievalQA.from_chain_type(llm=llm,
            chain_type="stuff",
            retriever=vectorstore.as_retriever(),
            memory = conversational_memory)
        output = qa.run(prompt)
        print(output)
        
    session_memory[oldPrompt] = output
    
    print("1st Output")
    print(output)
    
    return output, intent

def final_output_formatted(UserPrompt):

    answer,_ = final_output(UserPrompt)
    final_prompt_inst = """Your job is to compress the given answer. 
    You need to make sure the key points of the answer are retained. 
    Your answers will be short and direct without any explanation. 
    Remove redundancy in answer.
    Give answer in bullets.
    You need to analyze the answer and provide human like conversational responses.
    Provide hyperlink only when asked where or how to apply.

    User Prompt for your reference: {UserPrompt}
    Answer provided: {answer}

    Based on the above instructions, provide the final summarized answer."""

    prompt_template_final = PromptTemplate(template = final_prompt_inst,input_variables=['UserPrompt','answer'] )

    chain = LLMChain(llm=llm_35, prompt=prompt_template_final)

    final_text = chain({'UserPrompt':UserPrompt,'answer':answer})['text']

    return final_text


# app = Flask(__name__)
# CORS(app)

# @app.route("/")
# def get_bot():
#     return render_template('index.html')

# @app.route('/get_bot_response', methods=['POST'])
# def get_bot_response():
#     user_message = request.json['user_message']
#     print(f'Received user message: {user_message}')
#     bot_response = final_output_formatted(user_message)
#     print(f'Generated bot response: {bot_response}')
#     return jsonify({'bot_response': bot_response})


data_dict ={}

# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.

def add_text(history, text):
    history = history + [(text, None)]
    return history, gr.update(value="", interactive=True)


def bot(history):
    User_Prompt = history[-1][0]
    # entity = execute_entity(User_Prompt)
    # intent = execute_intent(User_Prompt)
    # print(User_Prompt)
    # print(entity)
    # print(intent)
    
    # try:
    #     executable_user_prompt = execute_final_prompt_formation(User_Prompt).strip()
    # except:
    #     executable_user_prompt = ""
        
    final_output_show = final_output_formatted(User_Prompt)
    
    response = final_output_show
    data_dict[history[-1][0]] = response
    history[-1][1] = ""
    for character in response:
        history[-1][1] += character
        time.sleep(0.05)
        yield history

with gr.Blocks() as demo:
    chatbot = gr.Chatbot([], elem_id="chatbot").style(height=750)

    with gr.Row():
        with gr.Column(scale=0.85):
            txt = gr.Textbox(
                show_label=False,
                placeholder="Enter text and press enter",
            ).style(container=False)
        with gr.Column(scale=0.10):
            submit_btn = gr.Button(
                'Submit',
                variant='primary'
            )
        with gr.Column(scale=0.10):
            clear_btn = gr.Button(
                'Clear',
                variant='stop'
            )
    txt_msg = txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(
        bot, chatbot, chatbot
    )
    submit_btn.click(add_text, [chatbot, txt], [chatbot, txt], queue=False).then(
        bot, chatbot, chatbot
    )
    clear_btn.click(lambda: None, None, chatbot, queue=False)
    txt_msg.then(lambda: gr.update(interactive=True), None, [txt], queue=False)

demo.queue()
if __name__ == "__main__":
    demo.launch(share=True)

# if __name__ == '__main__':
#     app.run(debug=True)