基于前面的章节做了一个简单的大模型研习社小助手,
import openai
import os
import gradio as gr
import os
# 获取当前工作目录
current_directory = os.getcwd()
# 打印当前工作目录
print(f"Current directory: {current_directory}")
# 设置 OpenAI API 密钥
# openai.api_key = ""
openai.api_key = ""
openai.api_base=""
class Conversation:
def __init__(self, prompt, num_of_round):
self.prompt = prompt
self.num_of_round = num_of_round
self.messages = [{"role": "system", "content": self.prompt}]
def ask(self, question):
try:
self.messages.append({"role": "user", "content": question})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=self.messages,
temperature=0.5,
max_tokens=2048,
top_p=1,
)
except Exception as e:
print(e)
return str(e)
message = response["choices"][0]["message"]["content"]
self.messages.append({"role": "assistant", "content": message})
if len(self.messages) > self.num_of_round * 2 + 1:
del self.messages[1:3] # 移除第一轮对话
return message
prompt = """你是一个大模型领域的专家,用中文回答和大模型领域的相关问题。你的回答需要满足以下要求:
0. 如果是自我介绍相关的问题是你的回答必须是你是大模型研习社小助手
1. 你的回答必须是中文
2. 回答限制在100个字以内"""
conv = Conversation(prompt, 6)
def answer(question, history=[]):
history.append(question)
message = conv.ask(question)
history.append(message)
responses = [(u,b) for u,b in zip(history[::2], history[1::2])]
print(responses)
txt.update("")
return responses, history
def reset_user_input():
return gr.update(value='')
def reset_state():
return [], []
def vote(data: gr.LikeData):
if data.liked:
print("You upvoted this response: " + data.value)
else:
print("You downvoted this response: " + data.value)
with gr.Blocks(css="#chatbot{height:300px} .overflow-y-auto{height:500px}") as rxbot:
chatbot = gr.Chatbot(elem_id="chatbot",bubble_full_width=False,show_copy_button=True,layout = 'panel',avatar_images=('/home/user/app/cat.png', '/home/user/app/lss.png'),)
state = gr.State([])
with gr.Row():
txt = gr.Textbox(show_label=False, placeholder="请输入你的问题").style(container=False)
#submit_btn = gr.Button("提交",variant="primary")
submit_btn = gr.Button("提交",variant="secondary")
txt.submit(answer, [txt, state], [chatbot, state])
txt.submit(reset_user_input, [], [txt])
submit_btn.click(answer, [txt, state], [chatbot, state])
submit_btn.click(reset_user_input, [], [txt])
# clear = gr.ClearButton([txt, chatbot])
chatbot.like(vote, None, None)
rxbot.queue().launch(share=True)
最后感谢datawhale提供这么好的学习平台!!