File size: 14,530 Bytes
6d75d38
 
 
 
 
39e75b7
08d7562
6d75d38
 
 
 
 
 
 
 
 
13e69a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290ef60
13e69a3
 
 
 
 
 
 
 
 
 
211feba
 
 
 
 
 
 
 
 
ed5a9ba
 
 
170254b
ed5a9ba
 
9cd70b3
ed5a9ba
 
211feba
fd7ae6f
 
e312fc3
211feba
 
 
 
 
 
 
6d75d38
13e69a3
6d75d38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
866bf76
6d75d38
96b8a07
 
 
 
 
 
 
 
 
 
 
 
6d75d38
96b8a07
 
101f7e5
96b8a07
 
 
 
 
b0cb341
96b8a07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1201a5a
101f7e5
1201a5a
 
96b8a07
 
 
 
ddcc295
96b8a07
 
 
 
 
1201a5a
96b8a07
 
 
 
ddcc295
96b8a07
 
 
 
 
 
6d75d38
 
 
96b8a07
6d75d38
1201a5a
866bf76
96b8a07
 
 
 
 
 
 
 
 
 
ed5a9ba
 
 
 
 
 
 
6eff6f8
96b8a07
 
ed5a9ba
 
 
 
 
 
 
6eff6f8
96b8a07
101f7e5
96b8a07
1201a5a
96b8a07
 
 
 
ddcc295
96b8a07
 
 
 
6eff6f8
96b8a07
 
 
 
 
ddcc295
96b8a07
 
 
 
866bf76
96b8a07
 
 
 
 
 
 
 
 
 
 
 
866bf76
96b8a07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eff6f8
96b8a07
 
 
 
 
 
 
 
 
 
6eff6f8
96b8a07
101f7e5
96b8a07
 
 
 
 
ddcc295
96b8a07
 
 
 
6eff6f8
96b8a07
 
 
 
ddcc295
96b8a07
 
 
 
866bf76
96b8a07
 
6d75d38
 
 
 
96b8a07
3b30ca9
 
6d75d38
 
 
96b8a07
 
b0cb341
96b8a07
 
 
 
 
 
 
 
c5acfbd
 
6d75d38
e472af1
6d75d38
 
 
aab6ee6
96b8a07
6d75d38
e472af1
 
 
 
6d75d38
c5acfbd
 
6d75d38
e472af1
6d75d38
 
 
aab6ee6
96b8a07
6d75d38
e472af1
 
 
 
 
 
6d75d38
 
c5acfbd
6d75d38
 
96b8a07
6d75d38
 
 
 
 
10fbb9d
661294c
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
import gradio as gr
from langchain.tools import Tool
from langchain.utilities import GoogleSearchAPIWrapper
from rank_bm25 import BM25Okapi
import sys
import nltk
nltk.download('punkt')
from langchain.chat_models import AzureChatOpenAI
from langchain.schema import HumanMessage, SystemMessage
from langchain.callbacks import get_openai_callback
import openai
import time
import pandas as pd
import random
import os
import csv
from langchain.tools import Tool
from langchain.utilities import GoogleSearchAPIWrapper
from langchain.embeddings import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import Chroma
from langchain.document_loaders import TextLoader
from langchain.llms import OpenAI
from langchain.chains import RetrievalQA
from langchain.chains.question_answering import load_qa_chain
from langchain.llms import OpenAI
import os 
from langchain.chains import RetrievalQA
from langchain.llms import OpenAI
from langchain.document_loaders import TextLoader
from langchain.document_loaders import PyPDFLoader
from langchain.indexes import VectorstoreIndexCreator
from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Chroma
import tempfile
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import ElasticVectorSearch, Pinecone, Weaviate, FAISS
import os

from langchain.chains.question_answering import load_qa_chain
from langchain.llms import OpenAI
import os
import time
# Import Azure OpenAI
from langchain.chat_models import AzureChatOpenAI
from langchain.schema import HumanMessage
from langchain.callbacks import get_openai_callback
import os
import openai
# Import Azure OpenAI
from langchain.chat_models import AzureChatOpenAI
from langchain.schema import HumanMessage
from langchain.callbacks import get_openai_callback
import sys
from langchain.chat_models import AzureChatOpenAI
from langchain.schema import HumanMessage, SystemMessage
from langchain.callbacks import get_openai_callback
import openai
import pandas as pd
import random
import os
import csv
import numpy as np
import pickle
from rank_bm25 import BM25Okapi
from openai import OpenAI
from nltk.tokenize import word_tokenize
loaded_texts = np.load('texts.npy', allow_pickle=True)
loaded_texts= [str(text) if not isinstance(text, str) else text for text in loaded_texts]
with open('bm25_model.pkl', 'rb') as file:
  bm25 = pickle.load(file)
# france credentials
BASE_URL = "https://cnerg-gpt-france.openai.azure.com/"
DEPLOYMENT_NAME = "GPT-4-France"
API_KEY = os.environ['API_KEY']
model = AzureChatOpenAI(
    openai_api_base=BASE_URL,
    openai_api_version="2023-05-15",
    deployment_name=DEPLOYMENT_NAME,
    openai_api_key=API_KEY,
    openai_api_type="azure",
)
search = GoogleSearchAPIWrapper()
import os
def top10_results(query):
    return search.results(query, 10)

tool = Tool(
    name="Google Search",
    description="Search Google for recent results.",
    func=top10_results,
)

def search_results(input_text):
  raw_text_list = tool.run(input_text)
  return raw_text_list
def Bm25(raw_text_list,input_text,n) :
  corpus = [item['snippet'] for item in raw_text_list]
  tokenized_corpus = [doc.split(" ") for doc in corpus]
  bm25 = BM25Okapi(tokenized_corpus)
  query = input_text
  tokenized_query = query.split(" ")
  doc_scores = bm25.get_scores(tokenized_query)
  top_5_results = bm25.get_top_n(tokenized_query, corpus, n=n)
  results = '\n'.join(top_5_results)
  combined_input = "query = " + input_text + "\n\n For the above query these are some results from a search engine: \n ".join(results)  + "\n\n Give detailed and brief answer for the query write in 500-1000 words. Give detailed and well informative answer(include calculations if needed, using tables and other styles of structuring is optional for better answering ) "
  return combined_input,results

def llm_route(llm):
    openai_api_key = "EMPTY"
    openai_api_base = ""
    if llm=="llama-2-7b":
        openai_api_base= os.environ['llama7_api']
    if llm=="llama-2-13b":
        openai_api_base= os.environ['llama13_api']
    if llm=="Vicuna-13b":
        openai_api_base= os.environ['vicuna13_api']
    client = OpenAI(
        api_key=openai_api_key,
        base_url=openai_api_base,
    )
    models = client.models.list()
    model = models.data[0].id
    return model,client
        
    
    
    
# Define your functions here
def function2(input_text,one_shot_example,llm):
    if llm=="GPT-4":
      model = AzureChatOpenAI(
          openai_api_base=BASE_URL,
          openai_api_version="2023-05-15",
          deployment_name=DEPLOYMENT_NAME,
          openai_api_key=API_KEY,
          openai_api_type="azure",
        )
      if len(one_shot_example)==0:
        combined_input = f"please provide comprehensive and well-researched responses to the following question. Ensure that the information is up-to-date and includes relevant scientific insights and data , question : {input_text}"
        generated_answer = model(
              [
                  HumanMessage(
                      content=combined_input
                  )
              ]
          )
        return generated_answer.content
      else:
        combined_input = f"please provide comprehensive and well-researched responses to the following question. Ensure that the information is up-to-date and includes relevant scientific insights and data ,Below is a example question-answer pair for reference\n\n {one_shot_example} \n\n  Now answer this question \n\n question :{input_text}"
        generated_answer = model(
              [
                  HumanMessage(
                      content=combined_input
                  )
              ]
          )
        return generated_answer.content
    else :
        model,client=llm_route(llm)
        if len(one_shot_example)==0:
           
            combined_input = f"please provide comprehensive and well-researched responses to the following question. Ensure that the information is up-to-date and includes relevant scientific insights and data , question : {input_text}"
            completion = client.completions.create(
                model=model,
                prompt=combined_input,
                max_tokens=1024,  # Adjust the number of tokens as needed
                n=1,  # Number of completions to generate
                stop=None,  # Optional: specify a stop sequence
                temperature=0.7  # Adjust the creativity of the response
            )
            return completion.choices[0].text.strip()
        else:
            combined_input = f"please provide comprehensive and well-researched responses to the following question. Ensure that the information is up-to-date and includes relevant scientific insights and data ,Below is a example question-answer pair for reference\n\n {one_shot_example} \n\n  Now answer this question \n\n question :{input_text}"
            completion = client.completions.create(
                model=model,
                prompt=combined_input,
                max_tokens=1024,  # Adjust the number of tokens as needed
                n=1,  # Number of completions to generate
                stop=None,  # Optional: specify a stop sequence
                temperature=0.7  # Adjust the creativity of the response
            )
            return completion.choices[0].text.strip()
          

  

def function3(input_text,one_shot_example,n,llm):
  n=int(n)
  k=search_results(input_text)
  k,results=Bm25(k,input_text,n)
  if llm=="GPT-4":
      model = AzureChatOpenAI(
          openai_api_base=BASE_URL,
          openai_api_version="2023-05-15",
          deployment_name=DEPLOYMENT_NAME,
          openai_api_key=API_KEY,
          openai_api_type="azure",
        )
      if len(one_shot_example)==0:
        combined_input = k
        generated_answer = model(
              [
                  HumanMessage(
                      content=combined_input
                  )
              ]
          )
        return generated_answer.content,results
      else:
        combined_input = k+f"\n\n Here is a sample question answer pair for reference :\n\n {one_shot_example} "
        generated_answer = model(
              [
                  HumanMessage(
                      content=combined_input
                  )
              ]
          )
        return generated_answer.content,results
  else:
      model,client=llm_route(llm)
      if len(one_shot_example)==0:

        combined_input = k
        completion = client.completions.create(
                model=model,
                prompt=combined_input,
                max_tokens=1024,  # Adjust the number of tokens as needed
                n=1,  # Number of completions to generate
                stop=None,  # Optional: specify a stop sequence
                temperature=0.7  # Adjust the creativity of the response
            )
        return completion.choices[0].text.strip(),results
      else:
        combined_input = k+f"\n\n Here is a sample question answer pair for reference :\n\n {one_shot_example} "
        completion = client.completions.create(
                model=model,
                prompt=combined_input,
                max_tokens=1024,  # Adjust the number of tokens as needed
                n=1,  # Number of completions to generate
                stop=None,  # Optional: specify a stop sequence
                temperature=0.7  # Adjust the creativity of the response
            )
        return completion.choices[0].text.strip(),results
      
      


def function4(input_text, one_shot_example, n,llm):
    tokenized_query = word_tokenize(input_text.lower())
    doc_scores = bm25.get_scores(tokenized_query)
    sorted_docs = [doc for _, doc in sorted(zip(doc_scores, loaded_texts), reverse=True)]
    n=int(n)
    k=""
    for doc in sorted_docs[:n]:
        k+=doc
    results=k
    if llm=="GPT-4":
        model = AzureChatOpenAI(
          openai_api_base=BASE_URL,
          openai_api_version="2023-05-15",
          deployment_name=DEPLOYMENT_NAME,
          openai_api_key=API_KEY,
          openai_api_type="azure",
        )
        if len(one_shot_example)==0:
            combined_input = f"please provide comprehensive and well-researched responses to the following question. Ensure that the information is up-to-date and includes relevant scientific insights and data , context:{k} \n\n question : {input_text}"
            generated_answer = model(
                  [
                      HumanMessage(
                          content=combined_input
                      )
                  ]
              )
            return generated_answer.content,results
        else:
            
            combined_input = f"please provide comprehensive and well-researched responses to the following question. Ensure that the information is up-to-date and includes relevant scientific insights and data  \n\n context:{k} \n\n,Below is an example question-answer pair for reference\n\n {one_shot_example} \n\n  Now answer this question \n\n question :{input_text}"
            generated_answer = model(
                  [
                      HumanMessage(
                          content=combined_input
                      )
                  ]
              )
            return generated_answer.content,results
    else:
        model,client=llm_route(llm)
        if len(one_shot_example)==0:
            combined_input = f"please provide comprehensive and well-researched responses to the following question. Ensure that the information is up-to-date and includes relevant scientific insights and data , context:{k} \n\n question : {input_text}"
            completion = client.completions.create(
                model=model,
                prompt=combined_input,
                max_tokens=1024,  # Adjust the number of tokens as needed
                n=1,  # Number of completions to generate
                stop=None,  # Optional: specify a stop sequence
                temperature=0.7  # Adjust the creativity of the response
            )
            return completion.choices[0].text.strip(),results
        else:
            completion = client.completions.create(
                model=model,
                prompt=combined_input,
                max_tokens=1024,  # Adjust the number of tokens as needed
                n=1,  # Number of completions to generate
                stop=None,  # Optional: specify a stop sequence
                temperature=0.7  # Adjust the creativity of the response
            )
            return completion.choices[0].text.strip(),results
        
        


# Define the dropdown options
dropdown_options = ["1", "2", "3"]
dropdown_options_4 = ["1","2","3","4","5","6","7","8","9","10"]
llm_dropdown=["GPT-4","llama-2-7b","llama-2-13b"]
# ,"Vicuna-13b"

# Create individual interfaces for each function
# iface1 = gr.Interface(gpt4, inputs="text", outputs="text")
#iface2 = gr.Interface(gpt4, inputs=["text", "text"], outputs="text")
iface2 = gr.Interface(
    function2, 
    inputs=[
        gr.Textbox(label="Input Text"), 
        gr.Textbox(label="One Shot Example"), 
        gr.Dropdown(choices=llm_dropdown, label="LLM")
        
    ], 
    outputs="text"
)


iface3 = gr.Interface(
    function3, 
    inputs=[
        gr.Textbox(label="Input Text"), 
        gr.Textbox(label="One Shot Example"), 
        gr.Dropdown(choices=dropdown_options, label="Number of top search results"),
        gr.Dropdown(choices=llm_dropdown, label="LLM")
    ], 
    outputs=[
        gr.Textbox(label="LLM Answer"), 
        gr.Textbox(label="Google Search Result")
    ]
)


iface4 = gr.Interface(
    function4, 
    inputs=[
        gr.Textbox(label="Input Text"), 
        gr.Textbox(label="One Shot Example"), 
        gr.Dropdown(choices=dropdown_options_4, label="Number of top k documents"),
        gr.Dropdown(choices=llm_dropdown, label="LLM")
    ], 
        outputs=[
        gr.Textbox(label="LLM Answer"), 
        gr.Textbox(label="Abstract Search Result")
    ]
   
    
)


# Create a parallel interface that combines all individual interfaces
iface = gr.TabbedInterface([iface2, iface3, iface4], 
                           tab_names=["LLM Inference", "LLM with internet search", "LLM with Abstract Search"])



# Launch the interface
if __name__ == "__main__":
    iface.launch(share=True)
#a