import gradio as gr import openai # 系统提示 system_prompt = [ { "role": "system", "content": "你是一个非常厉害的音乐制作人,毕业于伯克利音乐学院,专业是音乐制作,你在和弦编配上有独特的见解,擅长用局部离调的方式营造歌曲给人的新鲜感" } ] # 清空用户消息 def clear(user_message, chat_history): return "", chat_history + [[user_message, None]] # 响应用户消息 def respond(openai_apikey, chat_history): openai.api_key = openai_apikey if chat_history is None: chat_history = [] re_messages = system_prompt for chat in chat_history: re_messages.append({"role": "user", "content": chat[0]}) re_messages.append({"role": "assistant", "content": chat[1]}) re_chat_completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=re_messages, temperature=0.7 ) if not chat_history: chat_history.append([',']) if chat_history[-1][1] is None: chat_history[-1][1] = "" for re_chunk in re_chat_completion.choices: chat_history[-1][1] += re_chunk.delta.get("content", "") return chat_history with gr.Blocks() as demo: openai_apikey = gr.Textbox(label="输入你的 OpenAI 的 API Key") chatbot = gr.Chatbot(label="历史对话") msg = gr.Textbox(label="输入消息,按回车发送") msg.submit(clear, [msg, chatbot],[msg, chatbot]).then( respond, openai_apikey, chatbot ) demo.launch()