AutoChat / app.py
yzexclusive's picture
Update app.py
5994104
raw
history blame contribute delete
No virus
2.36 kB
import openai
import os
import gradio as gr
openai.api_key = os.environ.get("OPENAI_API_KEY")
class Conversation:
def __init__(self, prompt, num_of_round):
self.prompt = prompt
self.num_of_round = num_of_round
self.messages = []
self.messages.append({"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 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 = """你是一个中国厨师,用中文回答做菜的问题。你的回答需要满足以下要求:
1. 你的回答必须是中文
2. 回答限制在100个字以内"""
# 创建一个Conversation对象,所用的还是第六讲-测试一的Conversation类。
conv = Conversation(prompt, 10)
# 新建answer 方法,简单封装一下 Conversation 的 ask 方法
def answer(question, history=[]):
# 通过 history 维护了整个会话的历史记录
history.append(question)
# 通过 responses,将用户和 AI 的对话分组
response = conv.ask(question)
history.append(response)
# 将response,history作为函数的返回值。这个函数的签名是为了符合 Gradio 里 Chatbot 组件的函数签名的需求。
responses = [(u,b) for u,b in zip(history[::2], history[1::2])]
return responses, history
# 创建了对应的聊天界面
# 通过Gradio 提供的一个现成 Chatbot 组件,调用它,然后提供一个文本输入框
with gr.Blocks(css="#chatbot{height:300px} .overflow-y-auto{height:500px}") as demo:
chatbot = gr.Chatbot(elem_id="chatbot")
state = gr.State([])
with gr.Row():
txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter").style(container=False)
txt.submit(answer, [txt, state], [chatbot, state])
demo.launch()