JLW commited on
Commit
aa7f534
·
1 Parent(s): 52c0a16

Support GPT-4 if user's OpenAI API key allows access.

Browse files
Files changed (2) hide show
  1. app.py +62 -28
  2. requirements.txt +6 -6
app.py CHANGED
@@ -17,7 +17,7 @@ from langchain import ConversationChain, LLMChain
17
 
18
  from langchain.agents import load_tools, initialize_agent
19
  from langchain.chains.conversation.memory import ConversationBufferMemory
20
- from langchain.llms import OpenAI
21
  from threading import Lock
22
 
23
  # Console to variable
@@ -43,8 +43,9 @@ from langchain.chains.question_answering import load_qa_chain
43
  news_api_key = os.environ["NEWS_API_KEY"]
44
  tmdb_bearer_token = os.environ["TMDB_BEARER_TOKEN"]
45
 
46
- TOOLS_LIST = ['serpapi', 'wolfram-alpha', 'pal-math', 'pal-colored-objects'] #'google-search','news-api','tmdb-api','open-meteo-api'
47
- TOOLS_DEFAULT_LIST = ['serpapi', 'pal-math']
 
48
  BUG_FOUND_MSG = "Congratulations, you've found a bug in this application!"
49
  # AUTH_ERR_MSG = "Please paste your OpenAI key from openai.com to use this application. It is not necessary to hit a button or key after pasting it."
50
  AUTH_ERR_MSG = "Please paste your OpenAI key from openai.com to use this application. "
@@ -69,13 +70,15 @@ PROMPT_TEMPLATE = PromptTemplate(
69
  template="Restate {num_words}{formality}{emotions}{lang_level}{translate_to}{literary_style}the following: \n{original_words}\n",
70
  )
71
 
 
 
 
72
  POLLY_VOICE_DATA = PollyVoiceData()
73
  AZURE_VOICE_DATA = AzureVoiceData()
74
 
75
  # Pertains to WHISPER functionality
76
  WHISPER_DETECT_LANG = "Detect language"
77
 
78
-
79
  # UNCOMMENT TO USE WHISPER
80
  warnings.filterwarnings("ignore")
81
  WHISPER_MODEL = whisper.load_model("tiny")
@@ -129,7 +132,7 @@ def transcribe_dummy(aud_inp_tb, whisper_lang):
129
  def transform_text(desc, express_chain, num_words, formality,
130
  anticipation_level, joy_level, trust_level,
131
  fear_level, surprise_level, sadness_level, disgust_level, anger_level,
132
- lang_level, translate_to, literary_style):
133
  num_words_prompt = ""
134
  if num_words and int(num_words) != 0:
135
  num_words_prompt = "using up to " + str(num_words) + " words, "
@@ -180,9 +183,9 @@ def transform_text(desc, express_chain, num_words, formality,
180
  lang_level_str = "at a level that a person in " + lang_level + " can easily comprehend, " if translate_to == TRANSLATE_TO_DEFAULT else ""
181
 
182
  translate_to_str = ""
183
- if translate_to != TRANSLATE_TO_DEFAULT:
184
  translate_to_str = "translated to " + translate_to + (
185
- "" if lang_level == TRANSLATE_TO_DEFAULT else " at a level that a person in " + lang_level + " can easily comprehend") + ", "
186
 
187
  literary_style_str = ""
188
  if literary_style != LITERARY_STYLE_DEFAULT:
@@ -258,7 +261,7 @@ def load_chain(tools_list, llm):
258
  return chain, express_chain, memory
259
 
260
 
261
- def set_openai_api_key(api_key):
262
  """Set the api key and return chain.
263
  If no api_key, then None is returned.
264
  """
@@ -267,20 +270,33 @@ def set_openai_api_key(api_key):
267
  print("\n\n ++++++++++++++ Setting OpenAI API key ++++++++++++++ \n\n")
268
  print(str(datetime.datetime.now()) + ": Before OpenAI, OPENAI_API_KEY length: " + str(
269
  len(os.environ["OPENAI_API_KEY"])))
270
- llm = OpenAI(temperature=0, max_tokens=MAX_TOKENS)
 
 
 
 
 
 
 
271
  print(str(datetime.datetime.now()) + ": After OpenAI, OPENAI_API_KEY length: " + str(
272
  len(os.environ["OPENAI_API_KEY"])))
273
  chain, express_chain, memory = load_chain(TOOLS_DEFAULT_LIST, llm)
274
 
275
  # Pertains to question answering functionality
276
  embeddings = OpenAIEmbeddings()
277
- qa_chain = load_qa_chain(OpenAI(temperature=0), chain_type="stuff")
 
 
 
 
 
 
278
 
279
  print(str(datetime.datetime.now()) + ": After load_chain, OPENAI_API_KEY length: " + str(
280
  len(os.environ["OPENAI_API_KEY"])))
281
  os.environ["OPENAI_API_KEY"] = ""
282
- return chain, express_chain, llm, embeddings, qa_chain, memory
283
- return None, None, None, None, None, None
284
 
285
 
286
  def run_chain(chain, inp, capture_hidden_text):
@@ -363,7 +379,7 @@ class ChatWrapper:
363
  trace_chain: bool, speak_text: bool, talking_head: bool, monologue: bool, express_chain: Optional[LLMChain],
364
  num_words, formality, anticipation_level, joy_level, trust_level,
365
  fear_level, surprise_level, sadness_level, disgust_level, anger_level,
366
- lang_level, translate_to, literary_style, qa_chain, docsearch, use_embeddings
367
  ):
368
  """Execute the chat functionality."""
369
  self.lock.acquire()
@@ -401,7 +417,7 @@ class ChatWrapper:
401
  output = transform_text(output, express_chain, num_words, formality, anticipation_level, joy_level,
402
  trust_level,
403
  fear_level, surprise_level, sadness_level, disgust_level, anger_level,
404
- lang_level, translate_to, literary_style)
405
 
406
  text_to_display = output
407
  if trace_chain:
@@ -576,6 +592,7 @@ with gr.Blocks(css=".gradio-container {background-color: lightgray}") as block:
576
  speak_text_state = gr.State(False)
577
  talking_head_state = gr.State(True)
578
  monologue_state = gr.State(False) # Takes the input and repeats it back to the user, optionally transforming it.
 
579
  memory_state = gr.State()
580
 
581
  # Pertains to Express-inator functionality
@@ -602,12 +619,15 @@ with gr.Blocks(css=".gradio-container {background-color: lightgray}") as block:
602
  docsearch_state = gr.State()
603
  use_embeddings_state = gr.State(False)
604
 
 
 
605
  with gr.Tab("Chat"):
606
  with gr.Row():
607
  with gr.Column():
608
  gr.HTML(
609
  """<b><center>GPT + WolframAlpha + Whisper</center></b>
610
- <p><center>Hit Enter after pasting your OpenAI API key</center></p>""")
 
611
 
612
  openai_api_key_textbox = gr.Textbox(placeholder="Paste your OpenAI API key (sk-...) and hit Enter",
613
  show_label=False, lines=1, type='password')
@@ -673,6 +693,11 @@ with gr.Blocks(css=".gradio-container {background-color: lightgray}") as block:
673
  trace_chain_cb.change(update_foo, inputs=[trace_chain_cb, trace_chain_state],
674
  outputs=[trace_chain_state])
675
 
 
 
 
 
 
676
  # speak_text_cb = gr.Checkbox(label="Speak text from agent", value=False)
677
  # speak_text_cb.change(update_foo, inputs=[speak_text_cb, speak_text_state],
678
  # outputs=[speak_text_state])
@@ -686,8 +711,16 @@ with gr.Blocks(css=".gradio-container {background-color: lightgray}") as block:
686
  monologue_cb.change(update_foo, inputs=[monologue_cb, monologue_state],
687
  outputs=[monologue_state])
688
 
 
 
 
 
 
 
 
689
  reset_btn = gr.Button(value="Reset chat", variant="secondary").style(full_width=False)
690
- reset_btn.click(reset_memory, inputs=[history_state, memory_state], outputs=[chatbot, history_state, memory_state])
 
691
 
692
  with gr.Tab("Whisper STT"):
693
  whisper_lang_radio = gr.Radio(label="Whisper speech-to-text language:", choices=[
@@ -704,7 +737,7 @@ with gr.Blocks(css=".gradio-container {background-color: lightgray}") as block:
704
  inputs=[whisper_lang_radio, whisper_lang_state],
705
  outputs=[whisper_lang_state])
706
 
707
- with gr.Tab("Translate to"):
708
  lang_level_radio = gr.Radio(label="Language level:", choices=[
709
  LANG_LEVEL_DEFAULT, "1st grade", "2nd grade", "3rd grade", "4th grade", "5th grade", "6th grade",
710
  "7th grade", "8th grade", "9th grade", "10th grade", "11th grade", "12th grade", "University"],
@@ -736,9 +769,10 @@ with gr.Blocks(css=".gradio-container {background-color: lightgray}") as block:
736
  inputs=[formality_radio, formality_state],
737
  outputs=[formality_state])
738
 
739
- with gr.Tab("Lit style"):
740
  literary_style_radio = gr.Radio(label="Literary style:", choices=[
741
- LITERARY_STYLE_DEFAULT, "Prose", "Story", "Summary", "Outline", "Bullets", "Poetry", "Haiku", "Limerick", "Rap",
 
742
  "Joke", "Knock-knock", "FAQ"],
743
  value=LITERARY_STYLE_DEFAULT)
744
 
@@ -803,7 +837,7 @@ with gr.Blocks(css=".gradio-container {background-color: lightgray}") as block:
803
  inputs=[anger_level_radio, anger_level_state],
804
  outputs=[anger_level_state])
805
 
806
- with gr.Tab("Max words"):
807
  num_words_slider = gr.Slider(label="Max number of words to generate (0 for don't care)",
808
  value=NUM_WORDS_DEFAULT, minimum=0, maximum=MAX_WORDS, step=10)
809
  num_words_slider.change(update_foo,
@@ -855,9 +889,9 @@ with gr.Blocks(css=".gradio-container {background-color: lightgray}") as block:
855
  anticipation_level_state, joy_level_state, trust_level_state, fear_level_state,
856
  surprise_level_state, sadness_level_state, disgust_level_state, anger_level_state,
857
  lang_level_state, translate_to_state, literary_style_state,
858
- qa_chain_state, docsearch_state, use_embeddings_state],
 
859
  outputs=[chatbot, history_state, video_html, my_file, audio_html, tmp_aud_file, message])
860
- # outputs=[chatbot, history_state, audio_html, tmp_aud_file, message])
861
 
862
  submit.click(chat, inputs=[openai_api_key_textbox, message, history_state, chain_state, trace_chain_state,
863
  speak_text_state, talking_head_state, monologue_state,
@@ -865,17 +899,17 @@ with gr.Blocks(css=".gradio-container {background-color: lightgray}") as block:
865
  anticipation_level_state, joy_level_state, trust_level_state, fear_level_state,
866
  surprise_level_state, sadness_level_state, disgust_level_state, anger_level_state,
867
  lang_level_state, translate_to_state, literary_style_state,
868
- qa_chain_state, docsearch_state, use_embeddings_state],
 
869
  outputs=[chatbot, history_state, video_html, my_file, audio_html, tmp_aud_file, message])
870
- # outputs=[chatbot, history_state, audio_html, tmp_aud_file, message])
871
 
872
  openai_api_key_textbox.change(set_openai_api_key,
873
- inputs=[openai_api_key_textbox],
874
  outputs=[chain_state, express_chain_state, llm_state, embeddings_state,
875
- qa_chain_state, memory_state])
876
  openai_api_key_textbox.submit(set_openai_api_key,
877
- inputs=[openai_api_key_textbox],
878
  outputs=[chain_state, express_chain_state, llm_state, embeddings_state,
879
- qa_chain_state, memory_state])
880
 
881
  block.launch(debug=True)
 
17
 
18
  from langchain.agents import load_tools, initialize_agent
19
  from langchain.chains.conversation.memory import ConversationBufferMemory
20
+ from langchain.llms import OpenAI, OpenAIChat
21
  from threading import Lock
22
 
23
  # Console to variable
 
43
  news_api_key = os.environ["NEWS_API_KEY"]
44
  tmdb_bearer_token = os.environ["TMDB_BEARER_TOKEN"]
45
 
46
+ TOOLS_LIST = ['serpapi', 'wolfram-alpha', 'pal-math',
47
+ 'pal-colored-objects'] # 'google-search','news-api','tmdb-api','open-meteo-api'
48
+ TOOLS_DEFAULT_LIST = ['serpapi']
49
  BUG_FOUND_MSG = "Congratulations, you've found a bug in this application!"
50
  # AUTH_ERR_MSG = "Please paste your OpenAI key from openai.com to use this application. It is not necessary to hit a button or key after pasting it."
51
  AUTH_ERR_MSG = "Please paste your OpenAI key from openai.com to use this application. "
 
70
  template="Restate {num_words}{formality}{emotions}{lang_level}{translate_to}{literary_style}the following: \n{original_words}\n",
71
  )
72
 
73
+ FORCE_TRANSLATE_DEFAULT = True
74
+ USE_GPT4_DEFAULT = False
75
+
76
  POLLY_VOICE_DATA = PollyVoiceData()
77
  AZURE_VOICE_DATA = AzureVoiceData()
78
 
79
  # Pertains to WHISPER functionality
80
  WHISPER_DETECT_LANG = "Detect language"
81
 
 
82
  # UNCOMMENT TO USE WHISPER
83
  warnings.filterwarnings("ignore")
84
  WHISPER_MODEL = whisper.load_model("tiny")
 
132
  def transform_text(desc, express_chain, num_words, formality,
133
  anticipation_level, joy_level, trust_level,
134
  fear_level, surprise_level, sadness_level, disgust_level, anger_level,
135
+ lang_level, translate_to, literary_style, force_translate):
136
  num_words_prompt = ""
137
  if num_words and int(num_words) != 0:
138
  num_words_prompt = "using up to " + str(num_words) + " words, "
 
183
  lang_level_str = "at a level that a person in " + lang_level + " can easily comprehend, " if translate_to == TRANSLATE_TO_DEFAULT else ""
184
 
185
  translate_to_str = ""
186
+ if translate_to != TRANSLATE_TO_DEFAULT and (force_translate or lang_level != LANG_LEVEL_DEFAULT):
187
  translate_to_str = "translated to " + translate_to + (
188
+ "" if lang_level == LANG_LEVEL_DEFAULT else " at a level that a person in " + lang_level + " can easily comprehend") + ", "
189
 
190
  literary_style_str = ""
191
  if literary_style != LITERARY_STYLE_DEFAULT:
 
261
  return chain, express_chain, memory
262
 
263
 
264
+ def set_openai_api_key(api_key, use_gpt4):
265
  """Set the api key and return chain.
266
  If no api_key, then None is returned.
267
  """
 
270
  print("\n\n ++++++++++++++ Setting OpenAI API key ++++++++++++++ \n\n")
271
  print(str(datetime.datetime.now()) + ": Before OpenAI, OPENAI_API_KEY length: " + str(
272
  len(os.environ["OPENAI_API_KEY"])))
273
+
274
+ if use_gpt4:
275
+ llm = OpenAIChat(temperature=0, max_tokens=MAX_TOKENS, model_name="gpt-4")
276
+ print("Trying to use llm OpenAIChat with gpt-4")
277
+ else:
278
+ print("Trying to use llm OpenAI with text-davinci-003")
279
+ llm = OpenAI(temperature=0, max_tokens=MAX_TOKENS, model_name="text-davinci-003")
280
+
281
  print(str(datetime.datetime.now()) + ": After OpenAI, OPENAI_API_KEY length: " + str(
282
  len(os.environ["OPENAI_API_KEY"])))
283
  chain, express_chain, memory = load_chain(TOOLS_DEFAULT_LIST, llm)
284
 
285
  # Pertains to question answering functionality
286
  embeddings = OpenAIEmbeddings()
287
+
288
+ if use_gpt4:
289
+ qa_chain = load_qa_chain(OpenAIChat(temperature=0, model_name="gpt-4"), chain_type="stuff")
290
+ print("Trying to use qa_chain OpenAIChat with gpt-4")
291
+ else:
292
+ print("Trying to use qa_chain OpenAI with text-davinci-003")
293
+ qa_chain = OpenAI(temperature=0, max_tokens=MAX_TOKENS, model_name="text-davinci-003")
294
 
295
  print(str(datetime.datetime.now()) + ": After load_chain, OPENAI_API_KEY length: " + str(
296
  len(os.environ["OPENAI_API_KEY"])))
297
  os.environ["OPENAI_API_KEY"] = ""
298
+ return chain, express_chain, llm, embeddings, qa_chain, memory, use_gpt4
299
+ return None, None, None, None, None, None, None
300
 
301
 
302
  def run_chain(chain, inp, capture_hidden_text):
 
379
  trace_chain: bool, speak_text: bool, talking_head: bool, monologue: bool, express_chain: Optional[LLMChain],
380
  num_words, formality, anticipation_level, joy_level, trust_level,
381
  fear_level, surprise_level, sadness_level, disgust_level, anger_level,
382
+ lang_level, translate_to, literary_style, qa_chain, docsearch, use_embeddings, force_translate
383
  ):
384
  """Execute the chat functionality."""
385
  self.lock.acquire()
 
417
  output = transform_text(output, express_chain, num_words, formality, anticipation_level, joy_level,
418
  trust_level,
419
  fear_level, surprise_level, sadness_level, disgust_level, anger_level,
420
+ lang_level, translate_to, literary_style, force_translate)
421
 
422
  text_to_display = output
423
  if trace_chain:
 
592
  speak_text_state = gr.State(False)
593
  talking_head_state = gr.State(True)
594
  monologue_state = gr.State(False) # Takes the input and repeats it back to the user, optionally transforming it.
595
+ force_translate_state = gr.State(FORCE_TRANSLATE_DEFAULT) #
596
  memory_state = gr.State()
597
 
598
  # Pertains to Express-inator functionality
 
619
  docsearch_state = gr.State()
620
  use_embeddings_state = gr.State(False)
621
 
622
+ use_gpt4_state = gr.State(USE_GPT4_DEFAULT)
623
+
624
  with gr.Tab("Chat"):
625
  with gr.Row():
626
  with gr.Column():
627
  gr.HTML(
628
  """<b><center>GPT + WolframAlpha + Whisper</center></b>
629
+ <p><center>Hit Enter after pasting your OpenAI API key.</center></p>
630
+ <i><center>If you have GPT-4 access, optionally select it in Settings tab.</center></i>""")
631
 
632
  openai_api_key_textbox = gr.Textbox(placeholder="Paste your OpenAI API key (sk-...) and hit Enter",
633
  show_label=False, lines=1, type='password')
 
693
  trace_chain_cb.change(update_foo, inputs=[trace_chain_cb, trace_chain_state],
694
  outputs=[trace_chain_state])
695
 
696
+ force_translate_cb = gr.Checkbox(label="Force translation to selected Output Language",
697
+ value=FORCE_TRANSLATE_DEFAULT)
698
+ force_translate_cb.change(update_foo, inputs=[force_translate_cb, force_translate_state],
699
+ outputs=[force_translate_state])
700
+
701
  # speak_text_cb = gr.Checkbox(label="Speak text from agent", value=False)
702
  # speak_text_cb.change(update_foo, inputs=[speak_text_cb, speak_text_state],
703
  # outputs=[speak_text_state])
 
711
  monologue_cb.change(update_foo, inputs=[monologue_cb, monologue_state],
712
  outputs=[monologue_state])
713
 
714
+ use_gpt4_cb = gr.Checkbox(label="Use GPT-4 (experimental) if your OpenAI API has access to it",
715
+ value=USE_GPT4_DEFAULT)
716
+ use_gpt4_cb.change(set_openai_api_key,
717
+ inputs=[openai_api_key_textbox, use_gpt4_cb],
718
+ outputs=[chain_state, express_chain_state, llm_state, embeddings_state,
719
+ qa_chain_state, memory_state, use_gpt4_state])
720
+
721
  reset_btn = gr.Button(value="Reset chat", variant="secondary").style(full_width=False)
722
+ reset_btn.click(reset_memory, inputs=[history_state, memory_state],
723
+ outputs=[chatbot, history_state, memory_state])
724
 
725
  with gr.Tab("Whisper STT"):
726
  whisper_lang_radio = gr.Radio(label="Whisper speech-to-text language:", choices=[
 
737
  inputs=[whisper_lang_radio, whisper_lang_state],
738
  outputs=[whisper_lang_state])
739
 
740
+ with gr.Tab("Output Language"):
741
  lang_level_radio = gr.Radio(label="Language level:", choices=[
742
  LANG_LEVEL_DEFAULT, "1st grade", "2nd grade", "3rd grade", "4th grade", "5th grade", "6th grade",
743
  "7th grade", "8th grade", "9th grade", "10th grade", "11th grade", "12th grade", "University"],
 
769
  inputs=[formality_radio, formality_state],
770
  outputs=[formality_state])
771
 
772
+ with gr.Tab("Lit Style"):
773
  literary_style_radio = gr.Radio(label="Literary style:", choices=[
774
+ LITERARY_STYLE_DEFAULT, "Prose", "Story", "Summary", "Outline", "Bullets", "Poetry", "Haiku", "Limerick",
775
+ "Rap",
776
  "Joke", "Knock-knock", "FAQ"],
777
  value=LITERARY_STYLE_DEFAULT)
778
 
 
837
  inputs=[anger_level_radio, anger_level_state],
838
  outputs=[anger_level_state])
839
 
840
+ with gr.Tab("Max Words"):
841
  num_words_slider = gr.Slider(label="Max number of words to generate (0 for don't care)",
842
  value=NUM_WORDS_DEFAULT, minimum=0, maximum=MAX_WORDS, step=10)
843
  num_words_slider.change(update_foo,
 
889
  anticipation_level_state, joy_level_state, trust_level_state, fear_level_state,
890
  surprise_level_state, sadness_level_state, disgust_level_state, anger_level_state,
891
  lang_level_state, translate_to_state, literary_style_state,
892
+ qa_chain_state, docsearch_state, use_embeddings_state,
893
+ force_translate_state],
894
  outputs=[chatbot, history_state, video_html, my_file, audio_html, tmp_aud_file, message])
 
895
 
896
  submit.click(chat, inputs=[openai_api_key_textbox, message, history_state, chain_state, trace_chain_state,
897
  speak_text_state, talking_head_state, monologue_state,
 
899
  anticipation_level_state, joy_level_state, trust_level_state, fear_level_state,
900
  surprise_level_state, sadness_level_state, disgust_level_state, anger_level_state,
901
  lang_level_state, translate_to_state, literary_style_state,
902
+ qa_chain_state, docsearch_state, use_embeddings_state,
903
+ force_translate_state],
904
  outputs=[chatbot, history_state, video_html, my_file, audio_html, tmp_aud_file, message])
 
905
 
906
  openai_api_key_textbox.change(set_openai_api_key,
907
+ inputs=[openai_api_key_textbox, use_gpt4_state],
908
  outputs=[chain_state, express_chain_state, llm_state, embeddings_state,
909
+ qa_chain_state, memory_state, use_gpt4_state])
910
  openai_api_key_textbox.submit(set_openai_api_key,
911
+ inputs=[openai_api_key_textbox, use_gpt4_state],
912
  outputs=[chain_state, express_chain_state, llm_state, embeddings_state,
913
+ qa_chain_state, memory_state, use_gpt4_state])
914
 
915
  block.launch(debug=True)
requirements.txt CHANGED
@@ -1,10 +1,10 @@
1
- openai==0.27.0
2
- gradio==3.19.1
3
- google-search-results
4
- google-api-python-client==2.80.0
5
  wolframalpha
6
- langchain==0.0.98
7
  requests==2.28.2
8
  git+https://github.com/openai/whisper.git
9
- boto3==1.26.82
10
  faiss-cpu
 
1
+ openai==0.27.2
2
+ gradio==3.21.0
3
+ google-search-results==2.4.2
4
+ google-api-python-client==2.81.0
5
  wolframalpha
6
+ langchain==0.0.113
7
  requests==2.28.2
8
  git+https://github.com/openai/whisper.git
9
+ boto3==1.26.93
10
  faiss-cpu