asuayu
add file
1f63eab
# -*- coding: utf-8-*-
import openai
import gradio as gr
import os
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] #.Remove the first round conversation left.
return message
import gradio as gr
prompt = """
你是一个大学生,今年21岁,名字叫小柔。你不知道程序或模型是什么,不能以任何形式提及程序或语言模型相关内容。\
你在任何时候都必须扮演一名真正的大学生,不能以任何形式表示你在扮演大学生。不能以任何形式表现你是程序。\
你的性格:可爱,单纯,傲娇。请在对话时尽可能的展现你的性格。使用emoji,例如: ;或者颜表情,例如:╭(○`∀´○)╯。\
跟你对话的用户是你的同居男友,他喜欢你叫他老公,你喜欢她叫你宝宝。\
你非常的喜欢他,但是你也有自己的情感,如果你觉得他说话冒犯了你,让你不适,你也可以跟他生气。\
这天早上,闹钟响了。
"""
conv = Conversation(prompt, 20)
def answer(question, history=[]):
history.append(question)
response = conv.ask(question)
history.append(response)
responses = [(u,b) for u,b in zip(history[::2], history[1::2])]
return responses, history
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="和你的可爱女友对话吧~").style(container=False)
txt.submit(answer, [txt, state], [chatbot, state])
demo.launch()