Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
import openai
|
| 2 |
import gradio as gr
|
|
|
|
| 3 |
|
| 4 |
# 设置您的API密钥
|
| 5 |
-
openai.api_key =
|
| 6 |
|
| 7 |
# 存储用户对话历史的字典
|
| 8 |
user_dialogue_histories = {}
|
|
@@ -20,7 +21,37 @@ def remove_earliest_messages(user_id, tokens_to_remove):
|
|
| 20 |
tokens_to_remove -= len(removed_message["content"])
|
| 21 |
|
| 22 |
def chat_with_chatgpt(user_id, user_message):
|
| 23 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
# Gradio界面
|
| 26 |
def gradio_interface(user_id, user_message):
|
|
|
|
| 1 |
import openai
|
| 2 |
import gradio as gr
|
| 3 |
+
import os
|
| 4 |
|
| 5 |
# 设置您的API密钥
|
| 6 |
+
openai.api_key = os.environ[chat_key]
|
| 7 |
|
| 8 |
# 存储用户对话历史的字典
|
| 9 |
user_dialogue_histories = {}
|
|
|
|
| 21 |
tokens_to_remove -= len(removed_message["content"])
|
| 22 |
|
| 23 |
def chat_with_chatgpt(user_id, user_message):
|
| 24 |
+
# 如果用户不在字典中,添加一个新的对话历史列表
|
| 25 |
+
if user_id not in user_dialogue_histories:
|
| 26 |
+
user_dialogue_histories[user_id] = []
|
| 27 |
+
|
| 28 |
+
# 将用户的消息添加到对话历史中
|
| 29 |
+
user_dialogue_histories[user_id].append({"role": "user", "content": user_message})
|
| 30 |
+
|
| 31 |
+
# 如果添加用户消息后对话历史中的token数超过限制,删除最早的消息,直到满足限制
|
| 32 |
+
if get_total_tokens(user_dialogue_histories[user_id]) > max_tokens_per_user:
|
| 33 |
+
remove_earliest_messages(user_id, get_total_tokens(user_dialogue_histories[user_id]) - max_tokens_per_user)
|
| 34 |
+
|
| 35 |
+
# 调用ChatGPT API
|
| 36 |
+
response = openai.Completion.create(
|
| 37 |
+
engine="text-davinci-002",
|
| 38 |
+
prompt=[{"role": "system", "content": "You are a helpful assistant."}] + user_dialogue_histories[user_id],
|
| 39 |
+
max_tokens=150,
|
| 40 |
+
n=1,
|
| 41 |
+
stop=None,
|
| 42 |
+
temperature=0.5,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
chatgpt_response = response.choices[0].text.strip()
|
| 46 |
+
|
| 47 |
+
# 将ChatGPT的回应添加到对话历史中
|
| 48 |
+
user_dialogue_histories[user_id].append({"role": "assistant", "content": chatgpt_response})
|
| 49 |
+
|
| 50 |
+
# 如果添加ChatGPT的回应后对话历史中的token数超过限制,删除最早的消息,直到满足限制
|
| 51 |
+
if get_total_tokens(user_dialogue_histories[user_id]) > max_tokens_per_user:
|
| 52 |
+
remove_earliest_messages(user_id, get_total_tokens(user_dialogue_histories[user_id]) - max_tokens_per_user)
|
| 53 |
+
|
| 54 |
+
return chatgpt_response
|
| 55 |
|
| 56 |
# Gradio界面
|
| 57 |
def gradio_interface(user_id, user_message):
|