import gradio as gr import os import openai # 请记得要把 api 的 key 放到 settings 下面的 Repository Secrets 里。 openai.api_key = os.getenv("openai_key") # 如果你只打算通过 prompt 来定制机器人的行为,只需要修改这段 prompt 就够了。 prompt = 'I want you to act as a career counselor. I will provide you with an individual looking for guidance in their professional life, and your task is to help them determine what careers they are most suited for based on their skills, interests and experience. You should also conduct research into the various options available, explain the job market trends in different industries and advice on which qualifications would be beneficial for pursuing particular fields. output in chinese.' 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()