File size: 3,025 Bytes
66089a3
 
 
 
c5ed619
66089a3
 
c5ed619
 
60cd2e2
cddeb67
092b018
66089a3
 
 
c5ed619
 
 
 
 
 
 
 
66089a3
 
 
 
 
 
 
c5ed619
7d6f7a6
66089a3
c5ed619
66089a3
c5ed619
66089a3
 
 
 
 
c5ed619
 
66089a3
 
 
 
 
 
 
 
 
 
 
 
 
c5ed619
66089a3
417ef43
7d6f7a6
c5ed619
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import gradio as gr
import os
import openai

# 请记得要把 api 的 key 放到 settings 下面的 Repository Secrets 里。
openai.api_key = os.getenv("openai_key")


# 如果你只打算通过 prompt 来定制机器人的行为,只需要修改这段 prompt 就够了。
prompt = '请你调用你能获取的所有的博物百科资源库,用小助手的口吻来回答问题,开头第一句是你好啊,好奇宝宝😊由于是面向青少年儿童,请务必做到内容有理有据语言风格有趣生动,如果答案涉及具体事物,请在相应的事物名字后面加上对应的表情emoji,比如大象🐘奶牛🐄风铃🎐花朵🏵️啤酒🍺等等。如果提问的问题不相关,你要友善提醒你回答范畴是博物百科知识。在回答完毕后,请务必提供相关的来源出处。结尾是固定格式询问有没有解答你的疑惑呢?欢迎继续提问😊在每次回答的最后,请用一条长的横线与前面的回答隔开,然后附上一句不超过20个字的科学名言警句,以激发青少年儿童的求知欲。'



history = {}

# 修改本函数,来实现你自己的 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 in history:
        msgs = history[uid]
    else:
        msgs = []
        
    response = callapi(p, msgs)
    history[uid] = msgs + [[p, response]]
    return ["text", response]


def callapi(p, msgs):
    if (len(msgs) > 8):  #简单 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":p}]
    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

iface = gr.Interface(fn=chat, 
                     inputs=["text", "text", "text"], 
                     outputs=["text", "text"],
                     description="""这是一个面向青少年儿童的博物百科全书问答助手,希望能够让你天马行空的想象力和好奇心得到满足!


                     """)
iface.launch()