Spaces:
Paused
Paused
File size: 1,742 Bytes
db59c80 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
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])
|