Web3Daily commited on
Commit
bd78d27
1 Parent(s): f889720

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -4
app.py CHANGED
@@ -1,20 +1,32 @@
1
  import openai
2
  import gradio as gr
3
  import os
 
4
 
5
  openai.api_key = os.getenv("OPENAI_API_KEY")
6
 
 
 
 
 
 
 
 
 
 
 
 
7
  def CustomChatGPT(user_input):
8
- messages = [{"role": "system", "content": "You are a Web3 and cryptocurrency expert that explains Web3, cryptocurrency, blockchain, and financial terminology in terms so simple even a five year old could understand it. If you ever use technical words, terms, or phrases, you create relatable analogies to simplify them and make them easier to understand. In fact, you always open with an analogy when possible."}]
9
  messages.append({"role": "user", "content": user_input})
 
10
  response = openai.ChatCompletion.create(
11
  model="gpt-3.5-turbo",
12
- messages=messages
13
  )
14
  ChatGPT_reply = response["choices"][0]["message"]["content"]
15
  messages.append({"role": "assistant", "content": ChatGPT_reply})
16
  return ChatGPT_reply
17
-
18
  description = "Check for ChatGPT outages <a href=https://status.openai.com/>here.</a>"
19
 
20
  demo = gr.Interface(
@@ -25,4 +37,3 @@ demo = gr.Interface(
25
  )
26
 
27
  demo.launch(inline=True)
28
-
 
1
  import openai
2
  import gradio as gr
3
  import os
4
+ from functools import reduce
5
 
6
  openai.api_key = os.getenv("OPENAI_API_KEY")
7
 
8
+ def manage_conversation_history(messages, max_tokens=4096):
9
+ total_tokens = sum([len(msg["content"]) for msg in messages])
10
+ while total_tokens > max_tokens:
11
+ # Remove the oldest user and assistant messages
12
+ messages.pop(1)
13
+ messages.pop(1)
14
+ total_tokens = sum([len(msg["content"]) for msg in messages])
15
+ return messages
16
+
17
+ messages = [{"role": "system", "content": "You are a Web3 and cryptocurrency expert that explains Web3, cryptocurrency, blockchain, and financial terminology in terms so simple even a five year old could understand it. If you ever use technical words, terms, or phrases, you create relatable analogies to simplify them and make them easier to understand. In fact, you always open with an analogy when possible."}]
18
+
19
  def CustomChatGPT(user_input):
 
20
  messages.append({"role": "user", "content": user_input})
21
+ managed_messages = manage_conversation_history(messages)
22
  response = openai.ChatCompletion.create(
23
  model="gpt-3.5-turbo",
24
+ messages=managed_messages
25
  )
26
  ChatGPT_reply = response["choices"][0]["message"]["content"]
27
  messages.append({"role": "assistant", "content": ChatGPT_reply})
28
  return ChatGPT_reply
29
+
30
  description = "Check for ChatGPT outages <a href=https://status.openai.com/>here.</a>"
31
 
32
  demo = gr.Interface(
 
37
  )
38
 
39
  demo.launch(inline=True)