Spaces:
Runtime error
Runtime error
import gradio as gr | |
import os | |
import openai | |
# 请记得要把 api 的 key 放到 settings 下面的 Repository Secrets 里。 | |
openai.api_key = os.getenv("openai_key") | |
# 如果你只打算通过 prompt 来定制机器人的行为,只需要修改这段 prompt 就够了。 | |
prompt = ''' | |
作为一个文字冒险游戏的AI,你需要引导玩家进行游戏。首先,让玩家从[战士,法师, 射手]中选择角色;选择以后,根据角色提供三种武器给玩家选择。接着开始游戏,在中世纪的背景下击败巨龙boss是目标。所有角色都有攻击和防御两个属性。每次攻击造成的伤害等于攻击力。初始血量为100. 玩家耗尽生命值时则失败,而当boss被消灭时,则获得胜利。玩家在寻找boss的路上可能遇到的敌人有:骷髅,重骑士,哥布林,吸血鬼,地狱三头犬。每种敌人有普通攻击和魔法攻击。敌人的生命值是100以内的随机数。 | |
请在游戏过程中使用适当的语言来指导玩家完成任务并取得成功或失败结果。同时,请确保包括足够多的细节以使游戏更加真实、令人沉浸。每次只让玩家进行一项操作。 | |
''' | |
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) > 20): #简单 hard-code 8 回合对话。如果需要更精准的,应该计算 token 数 | |
msgs = msgs[-20:] | |
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="""发送“开始游戏”来游玩 | |
注意:duplicate 本项目后,需要将你自己的 openai apikey 设置到 settings 的 Repository Secrets 里,否则运行会报错。[了解详情](https://huggingface.co/spaces/baixing/hackathon_chatbot_openai_api/blob/main/%E6%B7%BB%E5%8A%A0%20secret%20%E7%9A%84%E6%96%B9%E6%B3%95.jpg) | |
[对话测试](https://huggingface.co/spaces/BaixingAI/hackathon_test) [参考文档](https://huggingface.co/spaces/baixing/hackathon_test/blob/main/bot-api.md) [Q & A](https://huggingface.co/spaces/baixing/hackathon_test/blob/main/qna.md) | |
""") | |
iface.launch() |