charbaaz356 commited on
Commit
a08917f
·
1 Parent(s): ead3b7e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -45
app.py CHANGED
@@ -44,7 +44,7 @@ from langchain.chains.question_answering import load_qa_chain
44
  # os.environ["TMDB_BEARER_TOKEN"] = ""
45
 
46
  news_api_key = os.environ["NEWS_API_KEY"]
47
- openai_api_key = os.environ["OPENAI_API_KEY"]
48
 
49
  TOOLS_LIST = ['serpapi', 'wolfram-alpha', 'pal-math', 'pal-colored-objects', 'news-api'] #'google-search','news-api','tmdb-api','open-meteo-api'
50
  TOOLS_DEFAULT_LIST = ['serpapi', 'wolfram-alpha', 'pal-math', 'pal-colored-objects', 'news-api']
@@ -252,7 +252,7 @@ def load_chain(tools_list, llm):
252
  if llm:
253
  print("\ntools_list", tools_list)
254
  tool_names = tools_list
255
- tools = load_tools(tool_names, llm=llm, news_api_key=news_api_key)
256
 
257
  memory = ConversationBufferMemory(memory_key="chat_history")
258
 
@@ -260,31 +260,52 @@ def load_chain(tools_list, llm):
260
  express_chain = LLMChain(llm=llm, prompt=PROMPT_TEMPLATE, verbose=True)
261
  return chain, express_chain, memory
262
 
263
- # The rest of the code remains the same.
264
 
265
- def set_openai_api_key():
266
- """Set the api key and return chain.
267
- If no api_key, then None is returned.
268
- """
269
- api_key = os.environ.get("OPENAI_API_KEY")
270
- if api_key and api_key.startswith("sk-") and len(api_key) > 50:
271
- print("\n\n ++++++++++++++ Setting OpenAI API key ++++++++++++++ \n\n")
272
- print(str(datetime.datetime.now()) + ": Before OpenAI, OPENAI_API_KEY length: " + str(
273
- len(os.environ["OPENAI_API_KEY"])))
274
- llm = OpenAI(temperature=0, max_tokens=MAX_TOKENS)
275
- print(str(datetime.datetime.now()) + ": After OpenAI, OPENAI_API_KEY length: " + str(
276
- len(os.environ["OPENAI_API_KEY"])))
277
- chain, express_chain, memory = load_chain(TOOLS_DEFAULT_LIST, llm)
 
 
278
 
279
- # Pertains to question answering functionality
280
- embeddings = OpenAIEmbeddings()
281
- qa_chain = load_qa_chain(OpenAI(temperature=0), chain_type="stuff")
282
 
283
- print(str(datetime.datetime.now()) + ": After load_chain, OPENAI_API_KEY length: " + str(
284
- len(os.environ["OPENAI_API_KEY"])))
285
- return chain, express_chain, llm, embeddings, qa_chain, memory
286
- return None, None, None, None, None, None
287
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
 
289
 
290
  def run_chain(chain, inp, capture_hidden_text):
@@ -373,7 +394,7 @@ class ChatWrapper:
373
  self.lock.acquire()
374
  try:
375
  print("\n==== date/time: " + str(datetime.datetime.now()) + " ====")
376
- print("inp: " + str(inp))
377
  print("trace_chain: ", trace_chain)
378
  print("speak_text: ", speak_text)
379
  print("talking_head: ", talking_head)
@@ -386,7 +407,7 @@ class ChatWrapper:
386
  if chain:
387
  # Set OpenAI key
388
  import openai
389
- openai.api_key = openai_api_key
390
  if not monologue:
391
  if use_embeddings:
392
  if inp and inp.strip() != "":
@@ -616,6 +637,9 @@ with gr.Blocks(css=".gradio-container {background-color: lightgray}") as block:
616
  <p><center>New features: <b>API key save. 2048 Input Tokens. News-api enabled
617
  </b></center></p>""")
618
 
 
 
 
619
  with gr.Row():
620
  with gr.Column(scale=1, min_width=TALKING_HEAD_WIDTH, visible=True):
621
  speak_text_cb = gr.Checkbox(label="Enable speech", value=False)
@@ -844,7 +868,29 @@ with gr.Blocks(css=".gradio-container {background-color: lightgray}") as block:
844
  <input type="hidden" name="currency_code" value="USD" />
845
  <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" border="0" name="submit" title="PayPal - The safer, easier way to pay online!" alt="Donate with PayPal button" />
846
  <img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" />
847
- </form>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
848
  """)
849
 
850
  gr.HTML("""<center>
@@ -853,22 +899,36 @@ with gr.Blocks(css=".gradio-container {background-color: lightgray}") as block:
853
  Powered by <a href='https://github.com/hwchase17/langchain'>LangChain 🦜️🔗</a>
854
  </center>""")
855
 
856
- message.submit(chat, inputs=[message, history_state, chain_state, trace_chain_state,
857
- speak_text_state, talking_head_state, monologue_state,
858
- express_chain_state, num_words_state, formality_state,
859
- anticipation_level_state, joy_level_state, trust_level_state, fear_level_state,
860
- surprise_level_state, sadness_level_state, disgust_level_state, anger_level_state,
861
- lang_level_state, translate_to_state, literary_style_state,
862
- qa_chain_state, docsearch_state, use_embeddings_state],
863
- outputs=[chatbot, history_state, video_html, my_file, audio_html, tmp_aud_file, message])
864
-
865
- submit.click(chat, inputs=[message, history_state, chain_state, trace_chain_state,
866
- speak_text_state, talking_head_state, monologue_state,
867
- express_chain_state, num_words_state, formality_state,
868
- anticipation_level_state, joy_level_state, trust_level_state, fear_level_state,
869
- surprise_level_state, sadness_level_state, disgust_level_state, anger_level_state,
870
- lang_level_state, translate_to_state, literary_style_state,
871
- qa_chain_state, docsearch_state, use_embeddings_state],
872
- outputs=[chatbot, history_state, video_html, my_file, audio_html, tmp_aud_file, message])
873
-
874
- block.launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  # os.environ["TMDB_BEARER_TOKEN"] = ""
45
 
46
  news_api_key = os.environ["NEWS_API_KEY"]
47
+ tmdb_bearer_token = os.environ["TMDB_BEARER_TOKEN"]
48
 
49
  TOOLS_LIST = ['serpapi', 'wolfram-alpha', 'pal-math', 'pal-colored-objects', 'news-api'] #'google-search','news-api','tmdb-api','open-meteo-api'
50
  TOOLS_DEFAULT_LIST = ['serpapi', 'wolfram-alpha', 'pal-math', 'pal-colored-objects', 'news-api']
 
252
  if llm:
253
  print("\ntools_list", tools_list)
254
  tool_names = tools_list
255
+ tools = load_tools(tool_names, llm=llm, news_api_key=news_api_key, tmdb_bearer_token=tmdb_bearer_token)
256
 
257
  memory = ConversationBufferMemory(memory_key="chat_history")
258
 
 
260
  express_chain = LLMChain(llm=llm, prompt=PROMPT_TEMPLATE, verbose=True)
261
  return chain, express_chain, memory
262
 
 
263
 
264
+ async def set_chain_state_api_key(api_key):
265
+ # Set the API key for chain_state
266
+ chain_state.api_key = api_key
267
+
268
+ async def set_express_chain_state_api_key(api_key):
269
+ # Set the API key for express_chain_state
270
+ express_chain_state.api_key = api_key
271
+
272
+ async def set_llm_state_api_key(api_key):
273
+ # Set the API key for llm_state
274
+ llm_state.api_key = api_key
275
+
276
+ async def set_embeddings_state_api_key(api_key):
277
+ # Set the API key for embeddings_state
278
+ embeddings_state.api_key = api_key
279
 
280
+ async def set_qa_chain_state_api_key(api_key):
281
+ # Set the API key for qa_chain_state
282
+ qa_chain_state.api_key = api_key
283
 
284
+ async def set_memory_state_api_key(api_key):
285
+ # Set the API key for memory_state
286
+ memory_state.api_key = api_key
 
287
 
288
+ async def set_openai_api_key(api_key):
289
+ """
290
+ Sets the OpenAI API key for various components in the application asynchronously.
291
+
292
+ Args:
293
+ api_key (str): The OpenAI API key.
294
+
295
+ Side effects:
296
+ Updates the API key for chain_state, express_chain_state, llm_state,
297
+ embeddings_state, qa_chain_state, and memory_state.
298
+ """
299
+ try:
300
+ await set_chain_state_api_key(api_key)
301
+ await set_express_chain_state_api_key(api_key)
302
+ await set_llm_state_api_key(api_key)
303
+ await set_embeddings_state_api_key(api_key)
304
+ await set_qa_chain_state_api_key(api_key)
305
+ await set_memory_state_api_key(api_key)
306
+ except Exception as e:
307
+ # Handle the error, e.g., log the error message or show an alert to the user
308
+ print(f"Error setting OpenAI API key: {e}")
309
 
310
 
311
  def run_chain(chain, inp, capture_hidden_text):
 
394
  self.lock.acquire()
395
  try:
396
  print("\n==== date/time: " + str(datetime.datetime.now()) + " ====")
397
+ print("inp: " + inp)
398
  print("trace_chain: ", trace_chain)
399
  print("speak_text: ", speak_text)
400
  print("talking_head: ", talking_head)
 
407
  if chain:
408
  # Set OpenAI key
409
  import openai
410
+ openai.api_key = api_key
411
  if not monologue:
412
  if use_embeddings:
413
  if inp and inp.strip() != "":
 
637
  <p><center>New features: <b>API key save. 2048 Input Tokens. News-api enabled
638
  </b></center></p>""")
639
 
640
+ openai_api_key_textbox = gr.Textbox(placeholder="Paste your OpenAI API key (sk-...)",
641
+ show_label=False, lines=1, type='password', elem_id="openai_api_key_textbox")
642
+
643
  with gr.Row():
644
  with gr.Column(scale=1, min_width=TALKING_HEAD_WIDTH, visible=True):
645
  speak_text_cb = gr.Checkbox(label="Enable speech", value=False)
 
868
  <input type="hidden" name="currency_code" value="USD" />
869
  <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" border="0" name="submit" title="PayPal - The safer, easier way to pay online!" alt="Donate with PayPal button" />
870
  <img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" />
871
+ </form># The OpenAI API key is stored in the browser's local storage and retrieved when the application is loaded.
872
+ # This is done using the change() and load() methods of the openai_api_key_textbox object.
873
+
874
+ # When the user inputs the OpenAI API key, it is saved to the local storage:
875
+ openai_api_key_textbox.change(None,
876
+ inputs=[openai_api_key_textbox],
877
+ outputs=None, _js="(api_key) => localStorage.setItem('open_api_key', api_key)")
878
+
879
+ # When the application is loaded, the OpenAI API key is retrieved from the local storage and set to the openai_api_key_textbox:
880
+ block.load(None, inputs=None, outputs=openai_api_key_textbox, _js="()=> localStorage.getItem('open_api_key')")
881
+
882
+ # The OpenAI API key is then used to set the API key for various components in the application:
883
+ openai_api_key_textbox.change(set_openai_api_key,
884
+ inputs=[openai_api_key_textbox],
885
+ outputs=[chain_state, express_chain_state, llm_state, embeddings_state,
886
+ qa_chain_state, memory_state])
887
+
888
+ # The algorithmic timeline for using the OpenAI API key is as follows:
889
+ # 1. The user inputs the OpenAI API key, which is saved to the local storage.
890
+ # 2. The application retrieves the OpenAI API key from the local storage when it is loaded.
891
+ # 3. The OpenAI API key is used to set the API key for various components in the application.
892
+ # 4. The application can now use the OpenAI API key to make requests to the OpenAI API.
893
+
894
  """)
895
 
896
  gr.HTML("""<center>
 
899
  Powered by <a href='https://github.com/hwchase17/langchain'>LangChain 🦜️🔗</a>
900
  </center>""")
901
 
902
+ message.submit(chat, inputs=[openai_api_key_textbox, message, history_state, chain_state, trace_chain_state,
903
+ speak_text_state, talking_head_state, monologue_state,
904
+ express_chain_state, num_words_state, formality_state,
905
+ anticipation_level_state, joy_level_state, trust_level_state, fear_level_state,
906
+ surprise_level_state, sadness_level_state, disgust_level_state, anger_level_state,
907
+ lang_level_state, translate_to_state, literary_style_state,
908
+ qa_chain_state, docsearch_state, use_embeddings_state],
909
+ outputs=[chatbot, history_state, video_html, my_file, audio_html, tmp_aud_file, message])
910
+ # outputs=[chatbot, history_state, audio_html, tmp_aud_file, message])
911
+
912
+ submit.click(chat, inputs=[openai_api_key_textbox, message, history_state, chain_state, trace_chain_state,
913
+ speak_text_state, talking_head_state, monologue_state,
914
+ express_chain_state, num_words_state, formality_state,
915
+ anticipation_level_state, joy_level_state, trust_level_state, fear_level_state,
916
+ surprise_level_state, sadness_level_state, disgust_level_state, anger_level_state,
917
+ lang_level_state, translate_to_state, literary_style_state,
918
+ qa_chain_state, docsearch_state, use_embeddings_state],
919
+ outputs=[chatbot, history_state, video_html, my_file, audio_html, tmp_aud_file, message])
920
+ # outputs=[chatbot, history_state, audio_html, tmp_aud_file, message])
921
+
922
+ openai_api_key_textbox.change(None,
923
+ inputs=[openai_api_key_textbox],
924
+ outputs=None, _js="(api_key) => localStorage.setItem('open_api_key', api_key)")
925
+
926
+ openai_api_key_textbox.change(lambda api_key: asyncio.run(set_openai_api_key(api_key)),
927
+ inputs=[openai_api_key_textbox],
928
+ outputs=[chain_state, express_chain_state, llm_state, embeddings_state,
929
+ qa_chain_state, memory_state])
930
+
931
+ block.load(None, inputs=None, outputs=openai_api_key_textbox, _js="()=> localStorage.getItem('open_api_key')")
932
+
933
+
934
+ block.launch(debug=True)