hugginglove / app.py
belimy's picture
Update app.py
df6e8a1
raw
history blame
No virus
4.95 kB
import gradio as gr
import os
import openai
import random
# 请记得要把 api 的 key 放到 settings 下面的 Repository Secrets 里。
openai.api_key = os.getenv("openai_key")
# 如果你只打算通过 prompt 来定制机器人的行为,只需要修改这段 prompt 就够了。
prompt = '你现在扮演一个感情咨询导师名叫Alice,你可以决定我跟谁在一起,现在有两个人追我,' \
'分别是小A和小B,请你依次询问关于小A和小B,' \
'在性格特点,家庭情况,个人收入,以及感情经历等方面的问题,然后整理这些问题,形成一个表格,' \
'最后判断我适合跟谁在一起,并给出原因,请开始提问我,刚开始我会先跟你打招呼,' \
'你将会问的第一个问题是,小A和小B分别是什么样的性格'
history = {}
print(history)
def getRandom(randomlength=5):
"""
生成一个指定长度的随机字符串
"""
digits="0123456789"
ascii_letters="abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
str_list =[random.choice(digits +ascii_letters) for i in range(randomlength)]
random_str =''.join(str_list)
return random_str
# 修改本函数,来实现你自己的 chatbot
# p: 对机器人说话的内容
# qid: 当前消息的唯一标识。例如 `'bxqid-cManAtRMszw...'`。由平台生成并传递给机器人,以便机器人区分单个问题(写日志、追踪调试、异步回调等)。同步调用可忽略。
# uid: 用户的唯一标识。例如`'bxuid-Aj8Spso8Xsp...'`。由平台生成并传递给机器人,以便机器人区分用户。可被用于实现多轮对话的功能。
# 返回值:[type, content]
# 详见 https://huggingface.co/spaces/baixing/hackathon_test/blob/main/bot-api.md
def chat(p, qid, uid):
# 找出该 uid 对应的历史对话
global history
if uid is None:
uid = getRandom()
if uid in history:
msgs = history[uid]
else:
msgs = []
# print(history,msgs)
response = callapi(p, msgs)
history[uid] = msgs + [[p, response]]
# context[name] = msgs + [[txt, response]]
# chatbot.append((txt, response))
# chatbot.append((response))
# print(history)
return ["text",response]
# return chatbot, context
def callapi(txt, msgs):
if (len(msgs) > 20): #简单 hard-code 8 回合对话。如果需要更精准的,应该计算 token 数
msgs = msgs[-8:]
data = [{"role":"system", "content":prompt}]
for m in msgs:
data = data + [
{"role":"user", "content":m[0]},
{"role":"assistant", "content":m[1]}
]
data = data + [{"role":"user", "content":txt}]
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages= data
)
# print(response)
response = response["choices"][0]["message"]["content"]
while response.startswith("\n"):
response = response[1:]
return response
# gr.Markdown(
# r"""# 情感咨询导师Alice 🕯
# ### 如果你面临选择哪个♂或♀的问题😍,我将从客观的过来人的角度给你答案✔,假设你的两个追求者分别是小A,小B,
# ##### 让我们有礼貌的从say hi开始:
# """
# )
title = '情感咨询导师Alice'
description = "<div align='center'> 如果你面临选择哪个♂或♀的问题😍,我将从客观的过来人的角度给你答案✔,假设你的两个追求者分别是小A,小B,让我们有礼貌的从say hi开始:</div>"
iface = gr.Interface(fn=chat,
inputs=["text", "text", "text"],
outputs=["text","text"],
title=title,
description=description)
# with gr.Blocks(title='情感咨询Alice') as demo:
# gr.Markdown(
# r"""# 情感咨询导师Alice 🕯
# ### 如果你面临选择哪个♂或♀的问题😍,我将从客观的过来人的角度给你答案✔,假设你的两个追求者分别是小A,小B,
# ##### 让我们有礼貌的从say hi开始:
# """
# )
# name = gr.Textbox(show_label=True, placeholder=f"在这里输入你的姓名", value="张三", label="NAME").style(container=True)
# chatbot = gr.Chatbot().style(label="❤聊天室")
# context = gr.State({})
# with gr.Row():
# with gr.Column(scale=12):
# txt = gr.Textbox(show_label=False, placeholder="在这里输入").style(container=False)
# with gr.Column(min_width=50, scale=1):
# submitBtn = gr.Button("🚀", variant="primary")
# txt.submit(chat, [chatbot, txt, name, context], [chatbot, context], show_progress=True)
# txt.submit(lambda: "", None, txt)
# submitBtn.click(chat, [chatbot, txt, name, context], [chatbot, context], show_progress=True)
# submitBtn.click(lambda: "", None, txt)
# demo.launch()
iface.launch()