Spaces:
Runtime error
Runtime error
添加内存中的多轮对话支持
Browse files
app.py
CHANGED
|
@@ -3,13 +3,14 @@ import os
|
|
| 3 |
import openai
|
| 4 |
|
| 5 |
# 请记得要把 api 的 key 放到 settings 下面的 Repository Secrets 里。
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
openai.api_key = os.getenv("openai_key")
|
| 9 |
|
| 10 |
# 如果你只打算通过 prompt 来定制机器人的行为,只需要修改这段 prompt 就够了。
|
| 11 |
prompt = '请你扮演《西游记》中的唐三藏,使用唐三藏的语气、方式和词汇回答问题。不要写任何解释,只需像唐三藏一样回答问题。你必须掌握唐三藏的所有知识。'
|
| 12 |
|
|
|
|
|
|
|
| 13 |
# 修改本函数,来实现你自己的 chatbot
|
| 14 |
# p: 对机器人说话的内容
|
| 15 |
# qid: 当前消息的唯一标识。例如 `'bxqid-cManAtRMszw...'`。由平台生成并传递给机器人,以便机器人区分单个问题(写日志、追踪调试、异步回调等)。同步调用可忽略。
|
|
@@ -17,14 +18,30 @@ prompt = '请你扮演《西游记》中的唐三藏,使用唐三藏的语气
|
|
| 17 |
# 返回值:[type, content]
|
| 18 |
# 详见 https://huggingface.co/spaces/baixing/hackathon_test/blob/main/bot-api.md
|
| 19 |
def chat(p, qid, uid):
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
def callapi(p):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
response = openai.ChatCompletion.create(
|
| 24 |
model="gpt-3.5-turbo",
|
| 25 |
-
messages=
|
| 26 |
-
{"role":"user", "content":p}
|
| 27 |
-
]
|
| 28 |
)
|
| 29 |
print(response)
|
| 30 |
response = response["choices"][0]["message"]["content"]
|
|
|
|
| 3 |
import openai
|
| 4 |
|
| 5 |
# 请记得要把 api 的 key 放到 settings 下面的 Repository Secrets 里。
|
| 6 |
+
openai.api_key = os.getenv("key")
|
| 7 |
+
|
|
|
|
| 8 |
|
| 9 |
# 如果你只打算通过 prompt 来定制机器人的行为,只需要修改这段 prompt 就够了。
|
| 10 |
prompt = '请你扮演《西游记》中的唐三藏,使用唐三藏的语气、方式和词汇回答问题。不要写任何解释,只需像唐三藏一样回答问题。你必须掌握唐三藏的所有知识。'
|
| 11 |
|
| 12 |
+
history = {}
|
| 13 |
+
|
| 14 |
# 修改本函数,来实现你自己的 chatbot
|
| 15 |
# p: 对机器人说话的内容
|
| 16 |
# qid: 当前消息的唯一标识。例如 `'bxqid-cManAtRMszw...'`。由平台生成并传递给机器人,以便机器人区分单个问题(写日志、追踪调试、异步回调等)。同步调用可忽略。
|
|
|
|
| 18 |
# 返回值:[type, content]
|
| 19 |
# 详见 https://huggingface.co/spaces/baixing/hackathon_test/blob/main/bot-api.md
|
| 20 |
def chat(p, qid, uid):
|
| 21 |
+
global history
|
| 22 |
+
if uid in history:
|
| 23 |
+
msgs = history[uid]
|
| 24 |
+
else:
|
| 25 |
+
msgs = []
|
| 26 |
+
response = callapi(p, msgs)
|
| 27 |
+
history[uid] = msgs + [[p, response]]
|
| 28 |
+
return ["text", response]
|
| 29 |
+
|
| 30 |
|
| 31 |
+
def callapi(p, msgs):
|
| 32 |
+
if (len(msgs) > 8): #hard-code 8 回合对话。如果需要更精准的,应该计算 token 数
|
| 33 |
+
msgs = msgs[-8:]
|
| 34 |
+
|
| 35 |
+
data = [{"role":"system", "content":prompt}]
|
| 36 |
+
for m in msgs:
|
| 37 |
+
data = data + [
|
| 38 |
+
{"role":"user", "content":m[0]},
|
| 39 |
+
{"role":"assistant", "content":m[1]}
|
| 40 |
+
]
|
| 41 |
+
data = data + [{"role":"user", "content":p}]
|
| 42 |
response = openai.ChatCompletion.create(
|
| 43 |
model="gpt-3.5-turbo",
|
| 44 |
+
messages= data
|
|
|
|
|
|
|
| 45 |
)
|
| 46 |
print(response)
|
| 47 |
response = response["choices"][0]["message"]["content"]
|