CoinW commited on
Commit
22d6eee
·
1 Parent(s): 3b2b460

fix: api key not clean after page refreshed

Browse files
Files changed (1) hide show
  1. app.py +10 -16
app.py CHANGED
@@ -1,21 +1,11 @@
1
  from openai import OpenAI
2
  import gradio as gr
3
 
4
- api_key = ""
5
- client = None
6
 
7
-
8
- def initialize_openai(api_key):
9
- print("Initializing OpenAI client for key: ", api_key[:10])
10
- global client
11
- client = OpenAI(api_key=api_key)
12
- print("OpenAI API Initialized")
13
-
14
-
15
- def generate_response(message, history):
16
- if not client:
17
  return "Please enter an API key to initialize the OpenAI API."
18
-
19
  formatted_history = []
20
  for msg in history:
21
  formatted_history.append({"role": msg["role"], "content": msg["content"]})
@@ -25,7 +15,7 @@ def generate_response(message, history):
25
  response = client.chat.completions.create(
26
  model="gpt-3.5-turbo", messages=formatted_history, temperature=1.0
27
  )
28
-
29
  return response.choices[0].message.content
30
 
31
 
@@ -33,9 +23,13 @@ with gr.Blocks() as demo:
33
  api_key_input = gr.Textbox(
34
  label="Enter API Key", type="password", placeholder="Enter your OpenAI API key"
35
  )
36
- api_key_input.change(initialize_openai, inputs=api_key_input, outputs=None)
37
  chatbot = gr.Chatbot(height=300, type="messages")
38
- gr.ChatInterface(fn=generate_response, type="messages", chatbot=chatbot)
 
 
 
 
 
39
 
40
 
41
  demo.launch()
 
1
  from openai import OpenAI
2
  import gradio as gr
3
 
 
 
4
 
5
+ def generate_response(message, history, api_key_input):
6
+ if not api_key_input:
 
 
 
 
 
 
 
 
7
  return "Please enter an API key to initialize the OpenAI API."
8
+ client = OpenAI(api_key=api_key_input)
9
  formatted_history = []
10
  for msg in history:
11
  formatted_history.append({"role": msg["role"], "content": msg["content"]})
 
15
  response = client.chat.completions.create(
16
  model="gpt-3.5-turbo", messages=formatted_history, temperature=1.0
17
  )
18
+ client.close()
19
  return response.choices[0].message.content
20
 
21
 
 
23
  api_key_input = gr.Textbox(
24
  label="Enter API Key", type="password", placeholder="Enter your OpenAI API key"
25
  )
 
26
  chatbot = gr.Chatbot(height=300, type="messages")
27
+ gr.ChatInterface(
28
+ fn=generate_response,
29
+ type="messages",
30
+ additional_inputs=api_key_input,
31
+ chatbot=chatbot,
32
+ )
33
 
34
 
35
  demo.launch()