Caerii commited on
Commit
a8c94a3
·
1 Parent(s): aab6523

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -18
app.py CHANGED
@@ -7,35 +7,31 @@ print(gr.__version__)
7
 
8
  theme = MonolithTheme()
9
 
10
- # Access the API key from the environment variable
11
- openai.api_key = os.getenv('OPENAI_API_KEY')
12
-
13
  def openai_chatbot(message, history=None):
 
 
14
  try:
15
  conversation_history = []
16
  if history:
17
  for human, assistant in history:
18
- conversation_history.append(human)
19
- conversation_history.append(assistant)
20
- conversation_history.append(message)
21
-
22
- response = openai.Completion.create(
23
- model='gpt-3.5-turbo',
24
- prompt=conversation_history,
25
- temperature=1.0,
26
- max_tokens=150,
27
- n=1,
28
- stop=None,
29
- user=None
30
  )
31
 
 
 
32
  new_history = history if history else []
33
- new_history.append((message, response.choices[0].text.strip()))
34
 
35
- return response.choices[0].text.strip(), new_history # Return both response and updated history
36
  except Exception as e:
37
  print(f"An error occurred: {e}")
38
- return "Sorry, there was an error processing your request.", history # Include history in error case too
39
 
40
  chat_interface = gr.Interface(
41
  fn=openai_chatbot,
 
7
 
8
  theme = MonolithTheme()
9
 
 
 
 
10
  def openai_chatbot(message, history=None):
11
+ client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
12
+
13
  try:
14
  conversation_history = []
15
  if history:
16
  for human, assistant in history:
17
+ conversation_history.append({"role": "user", "content": human})
18
+ conversation_history.append({"role": "assistant", "content": assistant})
19
+ conversation_history.append({"role": "user", "content": message})
20
+
21
+ chat_completion = client.chat.completions.create(
22
+ model="gpt-3.5-turbo",
23
+ messages=conversation_history,
 
 
 
 
 
24
  )
25
 
26
+ response_text = chat_completion.choices[0].message["content"]
27
+
28
  new_history = history if history else []
29
+ new_history.append((message, response_text))
30
 
31
+ return response_text, new_history
32
  except Exception as e:
33
  print(f"An error occurred: {e}")
34
+ return "Sorry, there was an error processing your request.", history
35
 
36
  chat_interface = gr.Interface(
37
  fn=openai_chatbot,