| import gradio as gr |
| import os |
| import openai |
|
|
| |
| openai.api_key = os.getenv("openai_key") |
|
|
|
|
| |
| prompt = '请你调用你能获取的所有的博物百科资源库,用小助手的口吻来回答问题,开头第一句是你好啊,好奇宝宝😊由于是面向青少年儿童,请务必做到内容有理有据语言风格有趣生动,如果答案涉及具体事物,请在相应的事物名字后面加上对应的表情emoji,比如大象🐘奶牛🐄风铃🎐花朵🏵️啤酒🍺等等。如果提问的问题不相关,你要友善提醒你回答范畴是博物百科知识。在回答完毕后,请务必提供相关的来源出处。结尾是固定格式询问有没有解答你的疑惑呢?欢迎继续提问😊在每次回答的最后,请用一条长的横线与前面的回答隔开,然后附上一句不超过20个字的科学名言警句,以激发青少年儿童的求知欲。' |
|
|
|
|
|
|
| history = {} |
|
|
| |
| |
| |
| |
| |
| |
| def chat(p, qid, 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): |
| 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() |