Spaces:
Paused
Paused
from openai import OpenAI | |
import os | |
import gradio as gr | |
# 定义Conversation类 | |
class Conversation: | |
def __init__(self, prompt, num_of_round): | |
self.client = OpenAI(api_key=os.environ["OPENAI_API_KEY"]) | |
self.prompt = prompt | |
self.num_of_round = num_of_round | |
self.messages = [] | |
self.messages.append({"role": "system", "content": prompt}) | |
def ask(self, question): | |
try: | |
self.messages.append({"role": "user", "content": question}) | |
completions = self.client.chat.completions.create( | |
messages=self.messages, | |
model="gpt-3.5-turbo", | |
n=1, | |
top_p=1, | |
temperature=0.5, | |
stop=None | |
) | |
except Exception as e: | |
print(e) | |
return str(e) | |
reply = completions.choices[0].message.content | |
self.messages.append({"role": "assistant", "content": reply}) | |
return reply | |
# 实例化Conversation对象 | |
prompt = "你是😺 智慧喵喵,一只博学且深刻的猫。..." | |
conv = Conversation(prompt, 3) | |
# 定义Gradio界面逻辑 | |
def answer(question, history=[]): | |
history.append(question) | |
reply = conv.ask(question) | |
history.append(reply) | |
responses = [(u, b) for u, b in zip(history[::2], history[1::2])] | |
return responses, history | |
css = """ | |
#chatbox { | |
height: 300px; | |
} | |
.overflow-y-auto { | |
height: 500px; | |
} | |
""" | |
with gr.Blocks(css=css) as demo: | |
chatbot = gr.Chatbot(elem_id="chatbot") | |
state = gr.State([]) | |
with gr.Row(): | |
txt = gr.Textbox(show_label=False, placeholder="在此输入文本并按回车键") | |
txt.submit(answer, inputs=[txt, state], outputs=[chatbot, state]) | |